This file is indexed.

/usr/lib/python3/dist-packages/pandas/io/pytables.py is in python3-pandas 0.13.1-2ubuntu2.

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
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
"""
High level interface to PyTables for reading and writing pandas data structures
to disk
"""

# pylint: disable-msg=E1101,W0613,W0603
from datetime import datetime, date
import time
import re
import copy
import itertools
import warnings
import os

import numpy as np
from pandas import (Series, TimeSeries, DataFrame, Panel, Panel4D, Index,
                    MultiIndex, Int64Index, Timestamp, _np_version_under1p7)
from pandas.sparse.api import SparseSeries, SparseDataFrame, SparsePanel
from pandas.sparse.array import BlockIndex, IntIndex
from pandas.tseries.api import PeriodIndex, DatetimeIndex
from pandas.core.base import StringMixin
from pandas.core.common import adjoin, pprint_thing
from pandas.core.algorithms import match, unique
from pandas.core.categorical import Categorical
from pandas.core.common import _asarray_tuplesafe
from pandas.core.internals import BlockManager, make_block
from pandas.core.reshape import block2d_to_blocknd, factor_indexer
from pandas.core.index import _ensure_index
from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type
import pandas.core.common as com
from pandas.tools.merge import concat
from pandas import compat
from pandas.compat import u_safe as u, PY3, range, lrange
from pandas.io.common import PerformanceWarning
from pandas.core.config import get_option
from pandas.computation.pytables import Expr, maybe_expression

import pandas.lib as lib
import pandas.algos as algos
import pandas.tslib as tslib

from contextlib import contextmanager

# versioning attribute
_version = '0.10.1'

# PY3 encoding if we don't specify
_default_encoding = 'UTF-8'


def _ensure_decoded(s):
    """ if we have bytes, decode them to unicde """
    if isinstance(s, np.bytes_):
        s = s.decode('UTF-8')
    return s


def _ensure_encoding(encoding):
    # set the encoding if we need
    if encoding is None:
        if PY3:
            encoding = _default_encoding
    return encoding


Term = Expr


def _ensure_term(where):
    """
    ensure that the where is a Term or a list of Term
    this makes sure that we are capturing the scope of variables
    that are passed
    create the terms here with a frame_level=2 (we are 2 levels down)
    """

    # only consider list/tuple here as an ndarray is automaticaly a coordinate
    # list
    if isinstance(where, (list, tuple)):
        where = [w if not maybe_expression(w) else Term(w, scope_level=2)
                 for w in where if w is not None]
    elif maybe_expression(where):
        where = Term(where, scope_level=2)
    return where


class PossibleDataLossError(Exception):
    pass


class ClosedFileError(Exception):
    pass


class IncompatibilityWarning(Warning):
    pass

incompatibility_doc = """
where criteria is being ignored as this version [%s] is too old (or
not-defined), read the file in and write it out to a new file to upgrade (with
the copy_to method)
"""


class AttributeConflictWarning(Warning):
    pass

attribute_conflict_doc = """
the [%s] attribute of the existing index is [%s] which conflicts with the new
[%s], resetting the attribute to None
"""


class DuplicateWarning(Warning):
    pass

duplicate_doc = """
duplicate entries in table, taking most recently appended
"""

performance_doc = """
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->%s,key->%s] [items->%s]
"""

# formats
_FORMAT_MAP = {
    u('f'): 'fixed',
    u('fixed'): 'fixed',
    u('t'): 'table',
    u('table'): 'table',
}

format_deprecate_doc = """
the table keyword has been deprecated
use the format='fixed(f)|table(t)' keyword instead
  fixed(f) : specifies the Fixed format
             and is the default for put operations
  table(t) : specifies the Table format
             and is the default for append operations
"""

# map object types
_TYPE_MAP = {

    Series: u('series'),
    SparseSeries: u('sparse_series'),
    TimeSeries: u('series'),
    DataFrame: u('frame'),
    SparseDataFrame: u('sparse_frame'),
    Panel: u('wide'),
    Panel4D: u('ndim'),
    SparsePanel: u('sparse_panel')
}

# storer class map
_STORER_MAP = {
    u('TimeSeries'): 'LegacySeriesFixed',
    u('Series'): 'LegacySeriesFixed',
    u('DataFrame'): 'LegacyFrameFixed',
    u('DataMatrix'): 'LegacyFrameFixed',
    u('series'): 'SeriesFixed',
    u('sparse_series'): 'SparseSeriesFixed',
    u('frame'): 'FrameFixed',
    u('sparse_frame'): 'SparseFrameFixed',
    u('wide'): 'PanelFixed',
    u('sparse_panel'): 'SparsePanelFixed',
}

# table class map
_TABLE_MAP = {
    u('generic_table'): 'GenericTable',
    u('appendable_series'): 'AppendableSeriesTable',
    u('appendable_multiseries'): 'AppendableMultiSeriesTable',
    u('appendable_frame'): 'AppendableFrameTable',
    u('appendable_multiframe'): 'AppendableMultiFrameTable',
    u('appendable_panel'): 'AppendablePanelTable',
    u('appendable_ndim'): 'AppendableNDimTable',
    u('worm'): 'WORMTable',
    u('legacy_frame'): 'LegacyFrameTable',
    u('legacy_panel'): 'LegacyPanelTable',
}

# axes map
_AXES_MAP = {
    DataFrame: [0],
    Panel: [1, 2],
    Panel4D: [1, 2, 3],
}

# register our configuration options
from pandas.core import config
dropna_doc = """
: boolean
    drop ALL nan rows when appending to a table
"""
format_doc = """
: format
    default format writing format, if None, then
    put will default to 'fixed' and append will default to 'table'
"""

with config.config_prefix('io.hdf'):
    config.register_option('dropna_table', True, dropna_doc,
                           validator=config.is_bool)
    config.register_option(
        'default_format', None, format_doc,
        validator=config.is_one_of_factory(['fixed', 'table', None])
    )

# oh the troubles to reduce import time
_table_mod = None
_table_supports_index = False
_table_file_open_policy_is_strict = False

def _tables():
    global _table_mod
    global _table_supports_index
    global _table_file_open_policy_is_strict
    if _table_mod is None:
        import tables
        from distutils.version import LooseVersion
        _table_mod = tables

        # version requirements
        ver = tables.__version__
        _table_supports_index = LooseVersion(ver) >= '2.3'

        # set the file open policy
        # return the file open policy; this changes as of pytables 3.1
        # depending on the HDF5 version
        try:
            _table_file_open_policy_is_strict = tables.file._FILE_OPEN_POLICY == 'strict'
        except:
            pass

    return _table_mod

@contextmanager
def get_store(path, **kwargs):
    """
    Creates an HDFStore instance. This function can be used in a with statement

    Parameters
    ----------
    same as HDFStore

    Examples
    --------
    >>> from pandas import DataFrame
    >>> from numpy.random import randn
    >>> bar = DataFrame(randn(10, 4))
    >>> with get_store('test.h5') as store:
    ...     store['foo'] = bar   # write to HDF5
    ...     bar = store['foo']   # retrieve
    """
    store = None
    try:
        store = HDFStore(path, **kwargs)
        yield store
    finally:
        if store is not None:
            store.close()


# interface to/from ###

def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
           append=None, **kwargs):
    """ store this object, close it if we opened it """
    if append:
        f = lambda store: store.append(key, value, **kwargs)
    else:
        f = lambda store: store.put(key, value, **kwargs)

    if isinstance(path_or_buf, compat.string_types):
        with get_store(path_or_buf, mode=mode, complevel=complevel,
                       complib=complib) as store:
            f(store)
    else:
        f(path_or_buf)


def read_hdf(path_or_buf, key, **kwargs):
    """ read from the store, close it if we opened it

        Retrieve pandas object stored in file, optionally based on where
        criteria

        Parameters
        ----------
        path_or_buf : path (string), or buffer to read from
        key : group identifier in the store
        where : list of Term (or convertable) objects, optional
        start : optional, integer (defaults to None), row number to start
            selection
        stop  : optional, integer (defaults to None), row number to stop
            selection
        columns : optional, a list of columns that if not None, will limit the
            return columns
        iterator : optional, boolean, return an iterator, default False
        chunksize : optional, nrows to include in iteration, return an iterator
        auto_close : optional, boolean, should automatically close the store
            when finished, default is False

        Returns
        -------
        The selected object

        """

    # grab the scope
    if 'where' in kwargs:
        kwargs['where'] = _ensure_term(kwargs['where'])

    f = lambda store, auto_close: store.select(
        key, auto_close=auto_close, **kwargs)

    if isinstance(path_or_buf, compat.string_types):

        # can't auto open/close if we are using an iterator
        # so delegate to the iterator
        store = HDFStore(path_or_buf, **kwargs)
        try:
            return f(store, True)
        except:

            # if there is an error, close the store
            try:
                store.close()
            except:
                pass

            raise

    # a passed store; user controls open/close
    f(path_or_buf, False)


class HDFStore(StringMixin):

    """
    dict-like IO interface for storing pandas objects in PyTables
    either Fixed or Table format.

    Parameters
    ----------
    path : string
        File path to HDF5 file
    mode : {'a', 'w', 'r', 'r+'}, default 'a'

        ``'r'``
            Read-only; no data can be modified.
        ``'w'``
            Write; a new file is created (an existing file with the same
            name would be deleted).
        ``'a'``
            Append; an existing file is opened for reading and writing,
            and if the file does not exist it is created.
        ``'r+'``
            It is similar to ``'a'``, but the file must already exist.
    complevel : int, 1-9, default 0
            If a complib is specified compression will be applied
            where possible
    complib : {'zlib', 'bzip2', 'lzo', 'blosc', None}, default None
            If complevel is > 0 apply compression to objects written
            in the store wherever possible
    fletcher32 : bool, default False
            If applying compression use the fletcher32 checksum

    Examples
    --------
    >>> from pandas import DataFrame
    >>> from numpy.random import randn
    >>> bar = DataFrame(randn(10, 4))
    >>> store = HDFStore('test.h5')
    >>> store['foo'] = bar   # write to HDF5
    >>> bar = store['foo']   # retrieve
    >>> store.close()
    """

    def __init__(self, path, mode=None, complevel=None, complib=None,
                 fletcher32=False, **kwargs):
        try:
            import tables
        except ImportError:  # pragma: no cover
            raise ImportError('HDFStore requires PyTables')

        self._path = path
        if mode is None:
            mode = 'a'
        self._mode = mode
        self._handle = None
        self._complevel = complevel
        self._complib = complib
        self._fletcher32 = fletcher32
        self._filters = None
        self.open(mode=mode, **kwargs)

    @property
    def root(self):
        """ return the root node """
        self._check_if_open()
        return self._handle.root

    @property
    def filename(self):
        return self._path

    def __getitem__(self, key):
        return self.get(key)

    def __setitem__(self, key, value):
        self.put(key, value)

    def __delitem__(self, key):
        return self.remove(key)

    def __getattr__(self, name):
        """ allow attribute access to get stores """
        self._check_if_open()
        try:
            return self.get(name)
        except:
            pass
        raise AttributeError("'%s' object has no attribute '%s'" %
                             (type(self).__name__, name))

    def __contains__(self, key):
        """ check for existance of this key
              can match the exact pathname or the pathnm w/o the leading '/'
              """
        node = self.get_node(key)
        if node is not None:
            name = node._v_pathname
            if name == key or name[1:] == key:
                return True
        return False

    def __len__(self):
        return len(self.groups())

    def __unicode__(self):
        output = '%s\nFile path: %s\n' % (type(self), pprint_thing(self._path))
        if self.is_open:
            lkeys = list(self.keys())
            if len(lkeys):
                keys = []
                values = []

                for k in lkeys:
                    try:
                        s = self.get_storer(k)
                        if s is not None:
                            keys.append(pprint_thing(s.pathname or k))
                            values.append(
                                pprint_thing(s or 'invalid_HDFStore node'))
                    except Exception as detail:
                        keys.append(k)
                        values.append("[invalid_HDFStore node: %s]"
                                      % pprint_thing(detail))

                output += adjoin(12, keys, values)
            else:
                output += 'Empty'
        else:
            output += "File is CLOSED"

        return output

    def keys(self):
        """
        Return a (potentially unordered) list of the keys corresponding to the
        objects stored in the HDFStore. These are ABSOLUTE path-names (e.g.
        have the leading '/'
        """
        return [n._v_pathname for n in self.groups()]

    def items(self):
        """
        iterate on key->group
        """
        for g in self.groups():
            yield g._v_pathname, g

    iteritems = items

    def open(self, mode='a', **kwargs):
        """
        Open the file in the specified mode

        Parameters
        ----------
        mode : {'a', 'w', 'r', 'r+'}, default 'a'
            See HDFStore docstring or tables.openFile for info about modes
        """
        tables = _tables()

        if self._mode != mode:

            # if we are changing a write mode to read, ok
            if self._mode in ['a', 'w'] and mode in ['r', 'r+']:
                pass
            elif mode in ['w']:

                # this would truncate, raise here
                if self.is_open:
                    raise PossibleDataLossError(
                        "Re-opening the file [{0}] with mode [{1}] "
                        "will delete the current file!"
                        .format(self._path, self._mode)
                    )

            self._mode = mode

        # close and reopen the handle
        if self.is_open:
            self.close()

        if self._complib is not None:
            if self._complevel is None:
                self._complevel = 9
            self._filters = _tables().Filters(self._complevel,
                                              self._complib,
                                              fletcher32=self._fletcher32)

        try:
            self._handle = tables.openFile(self._path, self._mode, **kwargs)
        except (IOError) as e:  # pragma: no cover
            if 'can not be written' in str(e):
                print('Opening %s in read-only mode' % self._path)
                self._handle = tables.openFile(self._path, 'r', **kwargs)
            else:
                raise

        except (ValueError) as e:

            # trap PyTables >= 3.1 FILE_OPEN_POLICY exception
            # to provide an updated message
            if 'FILE_OPEN_POLICY' in str(e):

                e = ValueError("PyTables [{version}] no longer supports opening multiple files\n"
                               "even in read-only mode on this HDF5 version [{hdf_version}]. You can accept this\n"
                               "and not open the same file multiple times at once,\n"
                               "upgrade the HDF5 version, or downgrade to PyTables 3.0.0 which allows\n"
                               "files to be opened multiple times at once\n".format(version=tables.__version__,
                                                                                    hdf_version=tables.getHDF5Version()))

            raise e

        except (Exception) as e:

            # trying to read from a non-existant file causes an error which
            # is not part of IOError, make it one
            if self._mode == 'r' and 'Unable to open/create file' in str(e):
                raise IOError(str(e))
            raise

    def close(self):
        """
        Close the PyTables file handle
        """
        if self._handle is not None:
            self._handle.close()
        self._handle = None

    @property
    def is_open(self):
        """
        return a boolean indicating whether the file is open
        """
        if self._handle is None:
            return False
        return bool(self._handle.isopen)

    def flush(self, fsync=False):
        """
        Force all buffered modifications to be written to disk.

        Parameters
        ----------
        fsync : bool (default False)
          call ``os.fsync()`` on the file handle to force writing to disk.

        Notes
        -----
        Without ``fsync=True``, flushing may not guarantee that the OS writes
        to disk. With fsync, the operation will block until the OS claims the
        file has been written; however, other caching layers may still
        interfere.
        """
        if self._handle is not None:
            self._handle.flush()
            if fsync:
                try:
                    os.fsync(self._handle.fileno())
                except:
                    pass

    def get(self, key):
        """
        Retrieve pandas object stored in file

        Parameters
        ----------
        key : object

        Returns
        -------
        obj : type of object stored in file
        """
        group = self.get_node(key)
        if group is None:
            raise KeyError('No object named %s in the file' % key)
        return self._read_group(group)

    def select(self, key, where=None, start=None, stop=None, columns=None,
               iterator=False, chunksize=None, auto_close=False, **kwargs):
        """
        Retrieve pandas object stored in file, optionally based on where
        criteria

        Parameters
        ----------
        key : object
        where : list of Term (or convertable) objects, optional
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection
        columns : a list of columns that if not None, will limit the return
            columns
        iterator : boolean, return an iterator, default False
        chunksize : nrows to include in iteration, return an iterator
        auto_close : boolean, should automatically close the store when
            finished, default is False

        Returns
        -------
        The selected object

        """
        group = self.get_node(key)
        if group is None:
            raise KeyError('No object named %s in the file' % key)

        # create the storer and axes
        where = _ensure_term(where)
        s = self._create_storer(group)
        s.infer_axes()

        # what we are actually going to do for a chunk
        def func(_start, _stop):
            return s.read(where=where, start=_start, stop=_stop,
                          columns=columns, **kwargs)

        if iterator or chunksize is not None:
            if not s.is_table:
                raise TypeError(
                    "can only use an iterator or chunksize on a table")
            return TableIterator(self, func, nrows=s.nrows, start=start,
                                 stop=stop, chunksize=chunksize,
                                 auto_close=auto_close)

        return TableIterator(self, func, nrows=s.nrows, start=start, stop=stop,
                             auto_close=auto_close).get_values()

    def select_as_coordinates(
            self, key, where=None, start=None, stop=None, **kwargs):
        """
        return the selection as an Index

        Parameters
        ----------
        key : object
        where : list of Term (or convertable) objects, optional
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection
        """
        where = _ensure_term(where)
        return self.get_storer(key).read_coordinates(where=where, start=start,
                                                     stop=stop, **kwargs)

    def unique(self, key, column, **kwargs):
        warnings.warn("unique(key,column) is deprecated\n"
                      "use select_column(key,column).unique() instead",
                      FutureWarning)
        return self.get_storer(key).read_column(column=column,
                                                **kwargs).unique()

    def select_column(self, key, column, **kwargs):
        """
        return a single column from the table. This is generally only useful to
        select an indexable

        Parameters
        ----------
        key : object
        column: the column of interest

        Exceptions
        ----------
        raises KeyError if the column is not found (or key is not a valid
            store)
        raises ValueError if the column can not be extracted individually (it
            is part of a data block)

        """
        return self.get_storer(key).read_column(column=column, **kwargs)

    def select_as_multiple(self, keys, where=None, selector=None, columns=None,
                           start=None, stop=None, iterator=False,
                           chunksize=None, auto_close=False, **kwargs):
        """ Retrieve pandas objects from multiple tables

        Parameters
        ----------
        keys : a list of the tables
        selector : the table to apply the where criteria (defaults to keys[0]
            if not supplied)
        columns : the columns I want back
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection
        iterator : boolean, return an iterator, default False
        chunksize : nrows to include in iteration, return an iterator

        Exceptions
        ----------
        raise if any of the keys don't refer to tables or if they are not ALL
        THE SAME DIMENSIONS
        """

        # default to single select
        where = _ensure_term(where)
        if isinstance(keys, (list, tuple)) and len(keys) == 1:
            keys = keys[0]
        if isinstance(keys, compat.string_types):
            return self.select(key=keys, where=where, columns=columns,
                               start=start, stop=stop, iterator=iterator,
                               chunksize=chunksize, **kwargs)

        if not isinstance(keys, (list, tuple)):
            raise TypeError("keys must be a list/tuple")

        if not len(keys):
            raise ValueError("keys must have a non-zero length")

        if selector is None:
            selector = keys[0]

        # collect the tables
        tbls = [self.get_storer(k) for k in keys]

        # validate rows
        nrows = None
        for t, k in zip(tbls, keys):
            if t is None:
                raise TypeError("Invalid table [%s]" % k)
            if not t.is_table:
                raise TypeError(
                    "object [%s] is not a table, and cannot be used in all "
                    "select as multiple" % t.pathname
                )

            if nrows is None:
                nrows = t.nrows
            elif t.nrows != nrows:
                raise ValueError(
                    "all tables must have exactly the same nrows!")

        # select coordinates from the selector table
        try:
            c = self.select_as_coordinates(
                selector, where, start=start, stop=stop)
            nrows = len(c)
        except Exception:
            raise ValueError("invalid selector [%s]" % selector)

        def func(_start, _stop):

            # collect the returns objs
            objs = [t.read(where=c[_start:_stop], columns=columns)
                    for t in tbls]

            # axis is the concentation axes
            axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0]

            # concat and return
            return concat(objs, axis=axis,
                          verify_integrity=False).consolidate()

        if iterator or chunksize is not None:
            return TableIterator(self, func, nrows=nrows, start=start,
                                 stop=stop, chunksize=chunksize,
                                 auto_close=auto_close)

        return TableIterator(self, func, nrows=nrows, start=start, stop=stop,
                             auto_close=auto_close).get_values()

    def put(self, key, value, format=None, append=False, **kwargs):
        """
        Store object in HDFStore

        Parameters
        ----------
        key      : object
        value    : {Series, DataFrame, Panel}
        format   : 'fixed(f)|table(t)', default is 'fixed'
            fixed(f) : Fixed format
                       Fast writing/reading. Not-appendable, nor searchable
            table(t) : Table format
                       Write as a PyTables Table structure which may perform
                       worse but allow more flexible operations like searching
                       / selecting subsets of the data
        append   : boolean, default False
            This will force Table format, append the input data to the
            existing.
        encoding : default None, provide an encoding for strings
        """
        if format is None:
            format = get_option("io.hdf.default_format") or 'fixed'
        kwargs = self._validate_format(format, kwargs)
        self._write_to_group(key, value, append=append, **kwargs)

    def remove(self, key, where=None, start=None, stop=None):
        """
        Remove pandas object partially by specifying the where condition

        Parameters
        ----------
        key : string
            Node to remove or delete rows from
        where : list of Term (or convertable) objects, optional
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection

        Returns
        -------
        number of rows removed (or None if not a Table)

        Exceptions
        ----------
        raises KeyError if key is not a valid store

        """
        where = _ensure_term(where)
        try:
            s = self.get_storer(key)
        except:

            if where is not None:
                raise ValueError(
                    "trying to remove a node with a non-None where clause!")

            # we are actually trying to remove a node (with children)
            s = self.get_node(key)
            if s is not None:
                s._f_remove(recursive=True)
                return None

        if s is None:
            raise KeyError('No object named %s in the file' % key)

        # remove the node
        if where is None:
            s.group._f_remove(recursive=True)

        # delete from the table
        else:
            if not s.is_table:
                raise ValueError(
                    'can only remove with where on objects written as tables')
            return s.delete(where=where, start=start, stop=stop)

    def append(self, key, value, format=None, append=True, columns=None,
               dropna=None, **kwargs):
        """
        Append to Table in file. Node must already exist and be Table
        format.

        Parameters
        ----------
        key : object
        value : {Series, DataFrame, Panel, Panel4D}
        format: 'table' is the default
            table(t) : table format
                       Write as a PyTables Table structure which may perform
                       worse but allow more flexible operations like searching
                       / selecting subsets of the data
        append       : boolean, default True, append the input data to the
            existing
        data_columns : list of columns to create as data columns, or True to
            use all columns
        min_itemsize : dict of columns that specify minimum string sizes
        nan_rep      : string to use as string nan represenation
        chunksize    : size to chunk the writing
        expectedrows : expected TOTAL row size of this table
        encoding     : default None, provide an encoding for strings
        dropna       : boolean, default True, do not write an ALL nan row to
            the store settable by the option 'io.hdf.dropna_table'
        Notes
        -----
        Does *not* check if data being appended overlaps with existing
        data in the table, so be careful
        """
        if columns is not None:
            raise TypeError("columns is not a supported keyword in append, "
                            "try data_columns")

        if dropna is None:
            dropna = get_option("io.hdf.dropna_table")
        if format is None:
            format = get_option("io.hdf.default_format") or 'table'
        kwargs = self._validate_format(format, kwargs)
        self._write_to_group(key, value, append=append, dropna=dropna,
                             **kwargs)

    def append_to_multiple(self, d, value, selector, data_columns=None,
                           axes=None, dropna=True, **kwargs):
        """
        Append to multiple tables

        Parameters
        ----------
        d : a dict of table_name to table_columns, None is acceptable as the
            values of one node (this will get all the remaining columns)
        value : a pandas object
        selector : a string that designates the indexable table; all of its
            columns will be designed as data_columns, unless data_columns is
            passed, in which case these are used
        data_columns : list of columns to create as data columns, or True to
            use all columns
        dropna : if evaluates to True, drop rows from all tables if any single
                 row in each table has all NaN

        Notes
        -----
        axes parameter is currently not accepted

        """
        if axes is not None:
            raise TypeError("axes is currently not accepted as a parameter to"
                            " append_to_multiple; you can create the "
                            "tables independently instead")

        if not isinstance(d, dict):
            raise ValueError(
                "append_to_multiple must have a dictionary specified as the "
                "way to split the value"
            )

        if selector not in d:
            raise ValueError(
                "append_to_multiple requires a selector that is in passed dict"
            )

        # figure out the splitting axis (the non_index_axis)
        axis = list(set(range(value.ndim)) - set(_AXES_MAP[type(value)]))[0]

        # figure out how to split the value
        remain_key = None
        remain_values = []
        for k, v in d.items():
            if v is None:
                if remain_key is not None:
                    raise ValueError(
                        "append_to_multiple can only have one value in d that "
                        "is None"
                    )
                remain_key = k
            else:
                remain_values.extend(v)
        if remain_key is not None:
            ordered = value.axes[axis]
            ordd = ordered - Index(remain_values)
            ordd = sorted(ordered.get_indexer(ordd))
            d[remain_key] = ordered.take(ordd)

        # data_columns
        if data_columns is None:
            data_columns = d[selector]

        # ensure rows are synchronized across the tables
        if dropna:
            idxs = (value[cols].dropna(how='all').index for cols in d.values())
            valid_index = next(idxs)
            for index in idxs:
                valid_index = valid_index.intersection(index)
            value = value.ix[valid_index]

        # append
        for k, v in d.items():
            dc = data_columns if k == selector else None

            # compute the val
            val = value.reindex_axis(v, axis=axis)

            self.append(k, val, data_columns=dc, **kwargs)

    def create_table_index(self, key, **kwargs):
        """ Create a pytables index on the table
        Paramaters
        ----------
        key : object (the node to index)

        Exceptions
        ----------
        raises if the node is not a table

        """

        # version requirements
        _tables()
        if not _table_supports_index:
            raise ValueError("PyTables >= 2.3 is required for table indexing")

        s = self.get_storer(key)
        if s is None:
            return

        if not s.is_table:
            raise TypeError(
                "cannot create table index on a Fixed format store")
        s.create_index(**kwargs)

    def groups(self):
        """return a list of all the top-level nodes (that are not themselves a
        pandas storage object)
        """
        _tables()
        self._check_if_open()
        return [
            g for g in self._handle.walkNodes()
            if (getattr(g._v_attrs, 'pandas_type', None) or
                getattr(g, 'table', None) or
                (isinstance(g, _table_mod.table.Table) and
                 g._v_name != u('table')))
        ]

    def get_node(self, key):
        """ return the node with the key or None if it does not exist """
        self._check_if_open()
        try:
            if not key.startswith('/'):
                key = '/' + key
            return self._handle.getNode(self.root, key)
        except:
            return None

    def get_storer(self, key):
        """ return the storer object for a key, raise if not in the file """
        group = self.get_node(key)
        if group is None:
            return None
        s = self._create_storer(group)
        s.infer_axes()
        return s

    def copy(self, file, mode='w', propindexes=True, keys=None, complib=None,
             complevel=None, fletcher32=False, overwrite=True):
        """ copy the existing store to a new file, upgrading in place

            Parameters
            ----------
            propindexes: restore indexes in copied file (defaults to True)
            keys       : list of keys to include in the copy (defaults to all)
            overwrite  : overwrite (remove and replace) existing nodes in the
                new store (default is True)
            mode, complib, complevel, fletcher32 same as in HDFStore.__init__

            Returns
            -------
            open file handle of the new store

        """
        new_store = HDFStore(
            file,
            mode=mode,
            complib=complib,
            complevel=complevel,
            fletcher32=fletcher32)
        if keys is None:
            keys = list(self.keys())
        if not isinstance(keys, (tuple, list)):
            keys = [keys]
        for k in keys:
            s = self.get_storer(k)
            if s is not None:

                if k in new_store:
                    if overwrite:
                        new_store.remove(k)

                data = self.select(k)
                if s.is_table:

                    index = False
                    if propindexes:
                        index = [a.name for a in s.axes if a.is_indexed]
                    new_store.append(
                        k, data, index=index,
                        data_columns=getattr(s, 'data_columns', None),
                        encoding=s.encoding
                    )
                else:
                    new_store.put(k, data, encoding=s.encoding)

        return new_store

    # private methods ######
    def _check_if_open(self):
        if not self.is_open:
            raise ClosedFileError("{0} file is not open!".format(self._path))

    def _validate_format(self, format, kwargs):
        """ validate / deprecate formats; return the new kwargs """
        kwargs = kwargs.copy()

        # table arg
        table = kwargs.pop('table', None)

        if table is not None:
            warnings.warn(format_deprecate_doc, FutureWarning)

            if table:
                format = 'table'
            else:
                format = 'fixed'

        # validate
        try:
            kwargs['format'] = _FORMAT_MAP[format.lower()]
        except:
            raise TypeError("invalid HDFStore format specified [{0}]"
                            .format(format))

        return kwargs

    def _create_storer(self, group, format=None, value=None, append=False,
                       **kwargs):
        """ return a suitable class to operate """

        def error(t):
            raise TypeError(
                "cannot properly create the storer for: [%s] [group->%s,"
                "value->%s,format->%s,append->%s,kwargs->%s]"
                % (t, group, type(value), format, append, kwargs)
            )

        pt = _ensure_decoded(getattr(group._v_attrs, 'pandas_type', None))
        tt = _ensure_decoded(getattr(group._v_attrs, 'table_type', None))

        # infer the pt from the passed value
        if pt is None:
            if value is None:

                _tables()
                if (getattr(group, 'table', None) or
                        isinstance(group, _table_mod.table.Table)):
                    pt = u('frame_table')
                    tt = u('generic_table')
                else:
                    raise TypeError(
                        "cannot create a storer if the object is not existing "
                        "nor a value are passed")
            else:

                try:
                    pt = _TYPE_MAP[type(value)]
                except:
                    error('_TYPE_MAP')

                # we are actually a table
                if format == 'table':
                    pt += u('_table')

        # a storer node
        if u('table') not in pt:
            try:
                return globals()[_STORER_MAP[pt]](self, group, **kwargs)
            except:
                error('_STORER_MAP')

        # existing node (and must be a table)
        if tt is None:

            # if we are a writer, determin the tt
            if value is not None:

                if pt == u('series_table'):
                    index = getattr(value, 'index', None)
                    if index is not None:
                        if index.nlevels == 1:
                            tt = u('appendable_series')
                        elif index.nlevels > 1:
                            tt = u('appendable_multiseries')
                elif pt == u('frame_table'):
                    index = getattr(value, 'index', None)
                    if index is not None:
                        if index.nlevels == 1:
                            tt = u('appendable_frame')
                        elif index.nlevels > 1:
                            tt = u('appendable_multiframe')
                elif pt == u('wide_table'):
                    tt = u('appendable_panel')
                elif pt == u('ndim_table'):
                    tt = u('appendable_ndim')

            else:

                # distiguish between a frame/table
                tt = u('legacy_panel')
                try:
                    fields = group.table._v_attrs.fields
                    if len(fields) == 1 and fields[0] == u('value'):
                        tt = u('legacy_frame')
                except:
                    pass

        try:
            return globals()[_TABLE_MAP[tt]](self, group, **kwargs)
        except:
            error('_TABLE_MAP')

    def _write_to_group(self, key, value, format, index=True, append=False,
                        complib=None, encoding=None, **kwargs):
        group = self.get_node(key)

        # remove the node if we are not appending
        if group is not None and not append:
            self._handle.removeNode(group, recursive=True)
            group = None

        # we don't want to store a table node at all if are object is 0-len
        # as there are not dtypes
        if getattr(value, 'empty', None) and (format == 'table' or append):
            return

        if group is None:
            paths = key.split('/')

            # recursively create the groups
            path = '/'
            for p in paths:
                if not len(p):
                    continue
                new_path = path
                if not path.endswith('/'):
                    new_path += '/'
                new_path += p
                group = self.get_node(new_path)
                if group is None:
                    group = self._handle.createGroup(path, p)
                path = new_path

        s = self._create_storer(group, format, value, append=append,
                                encoding=encoding, **kwargs)
        if append:
            # raise if we are trying to append to a Fixed format,
            #       or a table that exists (and we are putting)
            if (not s.is_table or
                    (s.is_table and format == 'fixed' and s.is_exists)):
                raise ValueError('Can only append to Tables')
            if not s.is_exists:
                s.set_object_info()
        else:
            s.set_object_info()

        if not s.is_table and complib:
            raise ValueError(
                'Compression not supported on Fixed format stores'
            )

        # write the object
        s.write(obj=value, append=append, complib=complib, **kwargs)

        if s.is_table and index:
            s.create_index(columns=index)

    def _read_group(self, group, **kwargs):
        s = self._create_storer(group)
        s.infer_axes()
        return s.read(**kwargs)


class TableIterator(object):

    """ define the iteration interface on a table

        Parameters
        ----------

        store : the reference store
        func  : the function to get results
        nrows : the rows to iterate on
        start : the passed start value (default is None)
        stop  : the passed stop value (default is None)
        chunksize : the passed chunking valeu (default is 50000)
        auto_close : boolean, automatically close the store at the end of
            iteration, default is False
        kwargs : the passed kwargs
        """

    def __init__(self, store, func, nrows, start=None, stop=None,
                 chunksize=None, auto_close=False):
        self.store = store
        self.func = func
        self.nrows = nrows or 0
        self.start = start or 0

        if stop is None:
            stop = self.nrows
        self.stop = min(self.nrows, stop)

        if chunksize is None:
            chunksize = 100000

        self.chunksize = chunksize
        self.auto_close = auto_close

    def __iter__(self):
        current = self.start
        while current < self.stop:
            stop = current + self.chunksize
            v = self.func(current, stop)
            current = stop

            if v is None:
                continue

            yield v

        self.close()

    def close(self):
        if self.auto_close:
            self.store.close()

    def get_values(self):
        results = self.func(self.start, self.stop)
        self.close()
        return results


class IndexCol(StringMixin):

    """ an index column description class

        Parameters
        ----------

        axis   : axis which I reference
        values : the ndarray like converted values
        kind   : a string description of this type
        typ    : the pytables type
        pos    : the position in the pytables

        """
    is_an_indexable = True
    is_data_indexable = True
    _info_fields = ['freq', 'tz', 'index_name']

    def __init__(self, values=None, kind=None, typ=None, cname=None,
                 itemsize=None, name=None, axis=None, kind_attr=None, pos=None,
                 freq=None, tz=None, index_name=None, **kwargs):
        self.values = values
        self.kind = kind
        self.typ = typ
        self.itemsize = itemsize
        self.name = name
        self.cname = cname
        self.kind_attr = kind_attr
        self.axis = axis
        self.pos = pos
        self.freq = freq
        self.tz = tz
        self.index_name = index_name
        self.table = None

        if name is not None:
            self.set_name(name, kind_attr)
        if pos is not None:
            self.set_pos(pos)

    def set_name(self, name, kind_attr=None):
        """ set the name of this indexer """
        self.name = name
        self.kind_attr = kind_attr or "%s_kind" % name
        if self.cname is None:
            self.cname = name

        return self

    def set_axis(self, axis):
        """ set the axis over which I index """
        self.axis = axis

        return self

    def set_pos(self, pos):
        """ set the position of this column in the Table """
        self.pos = pos
        if pos is not None and self.typ is not None:
            self.typ._v_pos = pos
        return self

    def set_table(self, table):
        self.table = table
        return self

    def __unicode__(self):
        temp = tuple(
            map(pprint_thing,
                    (self.name,
                     self.cname,
                     self.axis,
                     self.pos,
                     self.kind)))
        return "name->%s,cname->%s,axis->%s,pos->%s,kind->%s" % temp

    def __eq__(self, other):
        """ compare 2 col items """
        return all([getattr(self, a, None) == getattr(other, a, None)
                    for a in ['name', 'cname', 'axis', 'pos']])

    def __ne__(self, other):
        return not self.__eq__(other)

    @property
    def is_indexed(self):
        """ return whether I am an indexed column """
        try:
            return getattr(self.table.cols, self.cname).is_indexed
        except:
            False

    def copy(self):
        new_self = copy.copy(self)
        return new_self

    def infer(self, table):
        """infer this column from the table: create and return a new object"""
        new_self = self.copy()
        new_self.set_table(table)
        new_self.get_attr()
        return new_self

    def convert(self, values, nan_rep, encoding):
        """ set the values from this selection: take = take ownership """
        try:
            values = values[self.cname]
        except:
            pass

        values = _maybe_convert(values, self.kind, encoding)

        kwargs = dict()
        if self.freq is not None:
            kwargs['freq'] = _ensure_decoded(self.freq)
        if self.index_name is not None:
            kwargs['name'] = _ensure_decoded(self.index_name)
        try:
            self.values = Index(values, **kwargs)
        except:

            # if the output freq is different that what we recorded,
            # it should be None (see also 'doc example part 2')
            if 'freq' in kwargs:
                kwargs['freq'] = None
            self.values = Index(values, **kwargs)

        # set the timezone if indicated
        # we stored in utc, so reverse to local timezone
        if self.tz is not None:
            self.values = self.values.tz_localize(
                'UTC').tz_convert(_ensure_decoded(self.tz))

        return self

    def take_data(self):
        """ return the values & release the memory """
        self.values, values = None, self.values
        return values

    @property
    def attrs(self):
        return self.table._v_attrs

    @property
    def description(self):
        return self.table.description

    @property
    def col(self):
        """ return my current col description """
        return getattr(self.description, self.cname, None)

    @property
    def cvalues(self):
        """ return my cython values """
        return self.values

    def __iter__(self):
        return iter(self.values)

    def maybe_set_size(self, min_itemsize=None, **kwargs):
        """ maybe set a string col itemsize:
               min_itemsize can be an interger or a dict with this columns name
               with an integer size """
        if _ensure_decoded(self.kind) == u('string'):

            if isinstance(min_itemsize, dict):
                min_itemsize = min_itemsize.get(self.name)

            if min_itemsize is not None and self.typ.itemsize < min_itemsize:
                self.typ = _tables(
                ).StringCol(itemsize=min_itemsize, pos=self.pos)

    def validate_and_set(self, table, append, **kwargs):
        self.set_table(table)
        self.validate_col()
        self.validate_attr(append)
        self.set_attr()

    def validate_col(self, itemsize=None):
        """ validate this column: return the compared against itemsize """

        # validate this column for string truncation (or reset to the max size)
        if _ensure_decoded(self.kind) == u('string'):
            c = self.col
            if c is not None:
                if itemsize is None:
                    itemsize = self.itemsize
                if c.itemsize < itemsize:
                    raise ValueError(
                        "Trying to store a string with len [%s] in [%s] "
                        "column but\nthis column has a limit of [%s]!\n"
                        "Consider using min_itemsize to preset the sizes on "
                        "these columns" % (itemsize, self.cname, c.itemsize))
                return c.itemsize

        return None

    def validate_attr(self, append):
        # check for backwards incompatibility
        if append:
            existing_kind = getattr(self.attrs, self.kind_attr, None)
            if existing_kind is not None and existing_kind != self.kind:
                raise TypeError("incompatible kind in col [%s - %s]" %
                                (existing_kind, self.kind))

    def update_info(self, info):
        """ set/update the info for this indexable with the key/value
            if there is a conflict raise/warn as needed """

        for key in self._info_fields:

            value = getattr(self, key, None)
            idx = _get_info(info, self.name)

            existing_value = idx.get(key)
            if key in idx and value is not None and existing_value != value:

                # frequency/name just warn
                if key in ['freq', 'index_name']:
                    ws = attribute_conflict_doc % (key, existing_value, value)
                    warnings.warn(ws, AttributeConflictWarning)

                    # reset
                    idx[key] = None
                    setattr(self, key, None)

                else:
                    raise ValueError(
                        "invalid info for [%s] for [%s], existing_value [%s] "
                        "conflicts with new value [%s]"
                        % (self.name, key, existing_value, value))
            else:
                if value is not None or existing_value is not None:
                    idx[key] = value

        return self

    def set_info(self, info):
        """ set my state from the passed info """
        idx = info.get(self.name)
        if idx is not None:
            self.__dict__.update(idx)

    def get_attr(self):
        """ set the kind for this colummn """
        self.kind = getattr(self.attrs, self.kind_attr, None)

    def set_attr(self):
        """ set the kind for this colummn """
        setattr(self.attrs, self.kind_attr, self.kind)


class GenericIndexCol(IndexCol):

    """ an index which is not represented in the data of the table """

    @property
    def is_indexed(self):
        return False

    def convert(self, values, nan_rep, encoding):
        """ set the values from this selection: take = take ownership """

        self.values = Int64Index(np.arange(self.table.nrows))
        return self

    def get_attr(self):
        pass

    def set_attr(self):
        pass


class DataCol(IndexCol):

    """ a data holding column, by definition this is not indexable

        Parameters
        ----------

        data   : the actual data
        cname  : the column name in the table to hold the data (typically
            values)
        """
    is_an_indexable = False
    is_data_indexable = False
    _info_fields = ['tz']

    @classmethod
    def create_for_block(
            cls, i=None, name=None, cname=None, version=None, **kwargs):
        """ return a new datacol with the block i """

        if cname is None:
            cname = name or 'values_block_%d' % i
        if name is None:
            name = cname

        # prior to 0.10.1, we named values blocks like: values_block_0 an the
        # name values_0
        try:
            if version[0] == 0 and version[1] <= 10 and version[2] == 0:
                m = re.search("values_block_(\d+)", name)
                if m:
                    name = "values_%s" % m.groups()[0]
        except:
            pass

        return cls(name=name, cname=cname, **kwargs)

    def __init__(self, values=None, kind=None, typ=None,
                 cname=None, data=None, block=None, **kwargs):
        super(DataCol, self).__init__(
            values=values, kind=kind, typ=typ, cname=cname, **kwargs)
        self.dtype = None
        self.dtype_attr = u("%s_dtype" % self.name)
        self.set_data(data)

    def __unicode__(self):
        return "name->%s,cname->%s,dtype->%s,shape->%s" % (
            self.name, self.cname, self.dtype, self.shape
        )

    def __eq__(self, other):
        """ compare 2 col items """
        return all([getattr(self, a, None) == getattr(other, a, None)
                    for a in ['name', 'cname', 'dtype', 'pos']])

    def set_data(self, data, dtype=None):
        self.data = data
        if data is not None:
            if dtype is not None:
                self.dtype = dtype
                self.set_kind()
            elif self.dtype is None:
                self.dtype = data.dtype.name
                self.set_kind()

    def take_data(self):
        """ return the data & release the memory """
        self.data, data = None, self.data
        return data

    def set_kind(self):
        # set my kind if we can
        if self.dtype is not None:
            dtype = _ensure_decoded(self.dtype)
            if dtype.startswith(u('string')) or dtype.startswith(u('bytes')):
                self.kind = 'string'
            elif dtype.startswith(u('float')):
                self.kind = 'float'
            elif dtype.startswith(u('int')) or dtype.startswith(u('uint')):
                self.kind = 'integer'
            elif dtype.startswith(u('date')):
                self.kind = 'datetime'
            elif dtype.startswith(u('timedelta')):
                self.kind = 'timedelta'
            elif dtype.startswith(u('bool')):
                self.kind = 'bool'
            else:
                raise AssertionError(
                    "cannot interpret dtype of [%s] in [%s]" % (dtype, self))

            # set my typ if we need
            if self.typ is None:
                self.typ = getattr(self.description, self.cname, None)

    def set_atom(self, block, existing_col, min_itemsize,
                 nan_rep, info, encoding=None, **kwargs):
        """ create and setup my atom from the block b """

        self.values = list(block.items)
        dtype = block.dtype.name
        rvalues = block.values.ravel()
        inferred_type = lib.infer_dtype(rvalues)

        if inferred_type == 'datetime64':
            self.set_atom_datetime64(block)
        elif dtype == 'timedelta64[ns]':
            if _np_version_under1p7:
                raise TypeError(
                    "timdelta64 is not supported under under numpy < 1.7")
            self.set_atom_timedelta64(block)
        elif inferred_type == 'date':
            raise TypeError(
                "[date] is not implemented as a table column")
        elif inferred_type == 'datetime':
            if getattr(rvalues[0], 'tzinfo', None) is not None:

                # if this block has more than one timezone, raise
                if len(set([r.tzinfo for r in rvalues])) != 1:
                    raise TypeError(
                        "too many timezones in this block, create separate "
                        "data columns"
                    )

                # convert this column to datetime64[ns] utc, and save the tz
                index = DatetimeIndex(rvalues)
                tz = getattr(index, 'tz', None)
                if tz is None:
                    raise TypeError(
                        "invalid timezone specification")

                values = index.tz_convert('UTC').values.view('i8')

                # store a converted timezone
                zone = tslib.get_timezone(index.tz)
                if zone is None:
                    zone = tslib.tot_seconds(index.tz.utcoffset())
                self.tz = zone

                self.update_info(info)
                self.set_atom_datetime64(
                    block, values.reshape(block.values.shape))

            else:
                raise TypeError(
                    "[datetime] is not implemented as a table column")
        elif inferred_type == 'unicode':
            raise TypeError(
                "[unicode] is not implemented as a table column")

        # this is basically a catchall; if say a datetime64 has nans then will
        # end up here ###
        elif inferred_type == 'string' or dtype == 'object':
            self.set_atom_string(
                block,
                existing_col,
                min_itemsize,
                nan_rep,
                encoding)
        else:
            self.set_atom_data(block)

        return self

    def get_atom_string(self, block, itemsize):
        return _tables().StringCol(itemsize=itemsize, shape=block.shape[0])

    def set_atom_string(
            self, block, existing_col, min_itemsize, nan_rep, encoding):
        # fill nan items with myself, don't disturb the blocks by
        # trying to downcast
        block = block.fillna(nan_rep, downcast=False)[0]
        data = block.values

        # see if we have a valid string type
        inferred_type = lib.infer_dtype(data.ravel())
        if inferred_type != 'string':

            # we cannot serialize this data, so report an exception on a column
            # by column basis
            for item in block.items:

                col = block.get(item)
                inferred_type = lib.infer_dtype(col.ravel())
                if inferred_type != 'string':
                    raise TypeError(
                        "Cannot serialize the column [%s] because\n"
                        "its data contents are [%s] object dtype"
                        % (item, inferred_type)
                    )

        # itemsize is the maximum length of a string (along any dimension)
        itemsize = lib.max_len_string_array(com._ensure_object(data.ravel()))

        # specified min_itemsize?
        if isinstance(min_itemsize, dict):
            min_itemsize = int(min_itemsize.get(
                self.name) or min_itemsize.get('values') or 0)
        itemsize = max(min_itemsize or 0, itemsize)

        # check for column in the values conflicts
        if existing_col is not None:
            eci = existing_col.validate_col(itemsize)
            if eci > itemsize:
                itemsize = eci

        self.itemsize = itemsize
        self.kind = 'string'
        self.typ = self.get_atom_string(block, itemsize)
        self.set_data(self.convert_string_data(data, itemsize, encoding))

    def convert_string_data(self, data, itemsize, encoding):
        return _convert_string_array(data, encoding, itemsize)

    def get_atom_coltype(self):
        """ return the PyTables column class for this column """
        if self.kind.startswith('uint'):
            col_name = "UInt%sCol" % self.kind[4:]
        else:
            col_name = "%sCol" % self.kind.capitalize()

        return getattr(_tables(), col_name)

    def get_atom_data(self, block):
        return self.get_atom_coltype()(shape=block.shape[0])

    def set_atom_data(self, block):
        self.kind = block.dtype.name
        self.typ = self.get_atom_data(block)
        self.set_data(block.values.astype(self.typ.type))

    def get_atom_datetime64(self, block):
        return _tables().Int64Col(shape=block.shape[0])

    def set_atom_datetime64(self, block, values=None):
        self.kind = 'datetime64'
        self.typ = self.get_atom_datetime64(block)
        if values is None:
            values = block.values.view('i8')
        self.set_data(values, 'datetime64')

    def get_atom_timedelta64(self, block):
        return _tables().Int64Col(shape=block.shape[0])

    def set_atom_timedelta64(self, block, values=None):
        self.kind = 'timedelta64'
        self.typ = self.get_atom_timedelta64(block)
        if values is None:
            values = block.values.view('i8')
        self.set_data(values, 'timedelta64')

    @property
    def shape(self):
        return getattr(self.data, 'shape', None)

    @property
    def cvalues(self):
        """ return my cython values """
        return self.data

    def validate_attr(self, append):
        """validate that we have the same order as the existing & same dtype"""
        if append:
            existing_fields = getattr(self.attrs, self.kind_attr, None)
            if (existing_fields is not None and
                    existing_fields != list(self.values)):
                raise ValueError("appended items do not match existing items"
                                 " in table!")

            existing_dtype = getattr(self.attrs, self.dtype_attr, None)
            if (existing_dtype is not None and
                    existing_dtype != self.dtype):
                raise ValueError("appended items dtype do not match existing "
                                 "items dtype in table!")

    def convert(self, values, nan_rep, encoding):
        """set the data from this selection (and convert to the correct dtype
        if we can)
        """
        try:
            values = values[self.cname]
        except:
            pass
        self.set_data(values)

        # convert to the correct dtype
        if self.dtype is not None:
            dtype = _ensure_decoded(self.dtype)

            # reverse converts
            if dtype == u('datetime64'):
                # recreate the timezone
                if self.tz is not None:

                    # data should be 2-dim here
                    # we stored as utc, so just set the tz

                    index = DatetimeIndex(
                        self.data.ravel(), tz='UTC').tz_convert(self.tz)
                    self.data = np.array(
                        index.tolist(), dtype=object).reshape(self.data.shape)

                else:
                    self.data = np.asarray(self.data, dtype='M8[ns]')

            elif dtype == u('timedelta64'):
                self.data = np.asarray(self.data, dtype='m8[ns]')
            elif dtype == u('date'):
                try:
                    self.data = np.array(
                        [date.fromordinal(v) for v in self.data], dtype=object)
                except ValueError:
                    self.data = np.array(
                        [date.fromtimestamp(v) for v in self.data],
                        dtype=object)
            elif dtype == u('datetime'):
                self.data = np.array(
                    [datetime.fromtimestamp(v) for v in self.data],
                    dtype=object)
            else:

                try:
                    self.data = self.data.astype(dtype)
                except:
                    self.data = self.data.astype('O')

        # convert nans / decode
        if _ensure_decoded(self.kind) == u('string'):
            self.data = _unconvert_string_array(
                self.data, nan_rep=nan_rep, encoding=encoding)

        return self

    def get_attr(self):
        """ get the data for this colummn """
        self.values = getattr(self.attrs, self.kind_attr, None)
        self.dtype = getattr(self.attrs, self.dtype_attr, None)
        self.set_kind()

    def set_attr(self):
        """ set the data for this colummn """
        setattr(self.attrs, self.kind_attr, self.values)
        if self.dtype is not None:
            setattr(self.attrs, self.dtype_attr, self.dtype)


class DataIndexableCol(DataCol):

    """ represent a data column that can be indexed """
    is_data_indexable = True

    def get_atom_string(self, block, itemsize):
        return _tables().StringCol(itemsize=itemsize)

    def get_atom_data(self, block):
        return self.get_atom_coltype()()

    def get_atom_datetime64(self, block):
        return _tables().Int64Col()

    def get_atom_timedelta64(self, block):
        return _tables().Int64Col()


class GenericDataIndexableCol(DataIndexableCol):

    """ represent a generic pytables data column """

    def get_attr(self):
        pass


class Fixed(StringMixin):

    """ represent an object in my store
        facilitate read/write of various types of objects
        this is an abstract base class

        Parameters
        ----------

        parent : my parent HDFStore
        group  : the group node where the table resides
        """
    pandas_kind = None
    obj_type = None
    ndim = None
    is_table = False

    def __init__(self, parent, group, encoding=None, **kwargs):
        self.parent = parent
        self.group = group
        self.encoding = _ensure_encoding(encoding)
        self.set_version()

    @property
    def is_old_version(self):
        return (self.version[0] <= 0 and self.version[1] <= 10 and
                self.version[2] < 1)

    def set_version(self):
        """ compute and set our version """
        version = _ensure_decoded(
            getattr(self.group._v_attrs, 'pandas_version', None))
        try:
            self.version = tuple([int(x) for x in version.split('.')])
            if len(self.version) == 2:
                self.version = self.version + (0,)
        except:
            self.version = (0, 0, 0)

    @property
    def pandas_type(self):
        return _ensure_decoded(getattr(self.group._v_attrs,
                                       'pandas_type', None))

    @property
    def format_type(self):
        return 'fixed'

    def __unicode__(self):
        """ return a pretty representation of myself """
        self.infer_axes()
        s = self.shape
        if s is not None:
            if isinstance(s, (list, tuple)):
                s = "[%s]" % ','.join([pprint_thing(x) for x in s])
            return "%-12.12s (shape->%s)" % (self.pandas_type, s)
        return self.pandas_type

    def set_object_info(self):
        """ set my pandas type & version """
        self.attrs.pandas_type = str(self.pandas_kind)
        self.attrs.pandas_version = str(_version)
        self.set_version()

    def copy(self):
        new_self = copy.copy(self)
        return new_self

    @property
    def storage_obj_type(self):
        return self.obj_type

    @property
    def shape(self):
        return self.nrows

    @property
    def pathname(self):
        return self.group._v_pathname

    @property
    def _handle(self):
        return self.parent._handle

    @property
    def _filters(self):
        return self.parent._filters

    @property
    def _complevel(self):
        return self.parent._complevel

    @property
    def _fletcher32(self):
        return self.parent._fletcher32

    @property
    def _complib(self):
        return self.parent._complib

    @property
    def attrs(self):
        return self.group._v_attrs

    def set_attrs(self):
        """ set our object attributes """
        pass

    def get_attrs(self):
        """ get our object attributes """
        pass

    @property
    def storable(self):
        """ return my storable """
        return self.group

    @property
    def is_exists(self):
        return False

    @property
    def nrows(self):
        return getattr(self.storable, 'nrows', None)

    def validate(self, other):
        """ validate against an existing storable """
        if other is None:
            return
        return True

    def validate_version(self, where=None):
        """ are we trying to operate on an old version? """
        return True

    def infer_axes(self):
        """ infer the axes of my storer
              return a boolean indicating if we have a valid storer or not """

        s = self.storable
        if s is None:
            return False
        self.get_attrs()
        return True

    def read(self, **kwargs):
        raise NotImplementedError(
            "cannot read on an abstract storer: subclasses should implement")

    def write(self, **kwargs):
        raise NotImplementedError(
            "cannot write on an abstract storer: sublcasses should implement")

    def delete(self, where=None, **kwargs):
        """support fully deleting the node in its entirety (only) - where
        specification must be None
        """
        if where is None:
            self._handle.removeNode(self.group, recursive=True)
            return None

        raise TypeError("cannot delete on an abstract storer")


class GenericFixed(Fixed):

    """ a generified fixed version """
    _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'}
    _reverse_index_map = dict([(v, k)
                              for k, v in compat.iteritems(_index_type_map)])
    attributes = []

    # indexer helpders
    def _class_to_alias(self, cls):
        return self._index_type_map.get(cls, '')

    def _alias_to_class(self, alias):
        if isinstance(alias, type):  # pragma: no cover
            # compat: for a short period of time master stored types
            return alias
        return self._reverse_index_map.get(alias, Index)

    def _get_index_factory(self, klass):
        if klass == DatetimeIndex:
            def f(values, freq=None, tz=None):
                return DatetimeIndex._simple_new(values, None, freq=freq,
                                                 tz=tz)
            return f
        return klass

    def validate_read(self, kwargs):
        if kwargs.get('columns') is not None:
            raise TypeError("cannot pass a column specification when reading "
                            "a Fixed format store. this store must be "
                            "selected in its entirety")
        if kwargs.get('where') is not None:
            raise TypeError("cannot pass a where specification when reading "
                            "from a Fixed format store. this store must be "
                            "selected in its entirety")

    @property
    def is_exists(self):
        return True

    def set_attrs(self):
        """ set our object attributes """
        self.attrs.encoding = self.encoding

    def get_attrs(self):
        """ retrieve our attributes """
        self.encoding = _ensure_encoding(getattr(self.attrs, 'encoding', None))
        for n in self.attributes:
            setattr(self, n, _ensure_decoded(getattr(self.attrs, n, None)))

    def write(self, obj, **kwargs):
        self.set_attrs()

    def read_array(self, key):
        """ read an array for the specified node (off of group """
        import tables
        node = getattr(self.group, key)
        data = node[:]
        attrs = node._v_attrs

        transposed = getattr(attrs, 'transposed', False)

        if isinstance(node, tables.VLArray):
            ret = data[0]
        else:
            dtype = getattr(attrs, 'value_type', None)
            shape = getattr(attrs, 'shape', None)

            if shape is not None:
                # length 0 axis
                ret = np.empty(shape, dtype=dtype)
            else:
                ret = data

            if dtype == u('datetime64'):
                ret = np.array(ret, dtype='M8[ns]')
            elif dtype == u('timedelta64'):
                if _np_version_under1p7:
                    raise TypeError(
                        "timedelta64 is not supported under under numpy < 1.7")
                ret = np.array(ret, dtype='m8[ns]')

        if transposed:
            return ret.T
        else:
            return ret

    def read_index(self, key):
        variety = _ensure_decoded(getattr(self.attrs, '%s_variety' % key))

        if variety == u('multi'):
            return self.read_multi_index(key)
        elif variety == u('block'):
            return self.read_block_index(key)
        elif variety == u('sparseint'):
            return self.read_sparse_intindex(key)
        elif variety == u('regular'):
            _, index = self.read_index_node(getattr(self.group, key))
            return index
        else:  # pragma: no cover
            raise TypeError('unrecognized index variety: %s' % variety)

    def write_index(self, key, index):
        if isinstance(index, MultiIndex):
            setattr(self.attrs, '%s_variety' % key, 'multi')
            self.write_multi_index(key, index)
        elif isinstance(index, BlockIndex):
            setattr(self.attrs, '%s_variety' % key, 'block')
            self.write_block_index(key, index)
        elif isinstance(index, IntIndex):
            setattr(self.attrs, '%s_variety' % key, 'sparseint')
            self.write_sparse_intindex(key, index)
        else:
            setattr(self.attrs, '%s_variety' % key, 'regular')
            converted = _convert_index(index, self.encoding,
                                       self.format_type).set_name('index')
            self.write_array(key, converted.values)
            node = getattr(self.group, key)
            node._v_attrs.kind = converted.kind
            node._v_attrs.name = index.name

            if isinstance(index, (DatetimeIndex, PeriodIndex)):
                node._v_attrs.index_class = self._class_to_alias(type(index))

            if hasattr(index, 'freq'):
                node._v_attrs.freq = index.freq

            if hasattr(index, 'tz') and index.tz is not None:
                zone = tslib.get_timezone(index.tz)
                if zone is None:
                    zone = tslib.tot_seconds(index.tz.utcoffset())
                node._v_attrs.tz = zone

    def write_block_index(self, key, index):
        self.write_array('%s_blocs' % key, index.blocs)
        self.write_array('%s_blengths' % key, index.blengths)
        setattr(self.attrs, '%s_length' % key, index.length)

    def read_block_index(self, key):
        length = getattr(self.attrs, '%s_length' % key)
        blocs = self.read_array('%s_blocs' % key)
        blengths = self.read_array('%s_blengths' % key)
        return BlockIndex(length, blocs, blengths)

    def write_sparse_intindex(self, key, index):
        self.write_array('%s_indices' % key, index.indices)
        setattr(self.attrs, '%s_length' % key, index.length)

    def read_sparse_intindex(self, key):
        length = getattr(self.attrs, '%s_length' % key)
        indices = self.read_array('%s_indices' % key)
        return IntIndex(length, indices)

    def write_multi_index(self, key, index):
        setattr(self.attrs, '%s_nlevels' % key, index.nlevels)

        for i, (lev, lab, name) in enumerate(zip(index.levels,
                                                 index.labels,
                                                 index.names)):
            # write the level
            level_key = '%s_level%d' % (key, i)
            conv_level = _convert_index(lev, self.encoding,
                                        self.format_type).set_name(level_key)
            self.write_array(level_key, conv_level.values)
            node = getattr(self.group, level_key)
            node._v_attrs.kind = conv_level.kind
            node._v_attrs.name = name

            # write the name
            setattr(node._v_attrs, '%s_name%d' % (key, i), name)

            # write the labels
            label_key = '%s_label%d' % (key, i)
            self.write_array(label_key, lab)

    def read_multi_index(self, key):
        nlevels = getattr(self.attrs, '%s_nlevels' % key)

        levels = []
        labels = []
        names = []
        for i in range(nlevels):
            level_key = '%s_level%d' % (key, i)
            name, lev = self.read_index_node(getattr(self.group, level_key))
            levels.append(lev)
            names.append(name)

            label_key = '%s_label%d' % (key, i)
            lab = self.read_array(label_key)
            labels.append(lab)

        return MultiIndex(levels=levels, labels=labels, names=names,
                          verify_integrity=True)

    def read_index_node(self, node):
        data = node[:]
        # If the index was an empty array write_array_empty() will
        # have written a sentinel. Here we relace it with the original.
        if ('shape' in node._v_attrs and
                self._is_empty_array(getattr(node._v_attrs, 'shape'))):
            data = np.empty(getattr(node._v_attrs, 'shape'),
                            dtype=getattr(node._v_attrs, 'value_type'))
        kind = _ensure_decoded(node._v_attrs.kind)
        name = None

        if 'name' in node._v_attrs:
            name = node._v_attrs.name

        index_class = self._alias_to_class(getattr(node._v_attrs,
                                                   'index_class', ''))
        factory = self._get_index_factory(index_class)

        kwargs = {}
        if u('freq') in node._v_attrs:
            kwargs['freq'] = node._v_attrs['freq']

        if u('tz') in node._v_attrs:
            kwargs['tz'] = node._v_attrs['tz']

        if kind in (u('date'), u('datetime')):
            index = factory(
                _unconvert_index(data, kind, encoding=self.encoding),
                dtype=object, **kwargs)
        else:
            index = factory(
                _unconvert_index(data, kind, encoding=self.encoding), **kwargs)

        index.name = name

        return name, index

    def write_array_empty(self, key, value):
        """ write a 0-len array """

        # ugly hack for length 0 axes
        arr = np.empty((1,) * value.ndim)
        self._handle.createArray(self.group, key, arr)
        getattr(self.group, key)._v_attrs.value_type = str(value.dtype)
        getattr(self.group, key)._v_attrs.shape = value.shape

    def _is_empty_array(self, shape):
        """Returns true if any axis is zero length."""
        return any(x == 0 for x in shape)

    def write_array(self, key, value, items=None):
        if key in self.group:
            self._handle.removeNode(self.group, key)

        # Transform needed to interface with pytables row/col notation
        empty_array = self._is_empty_array(value.shape)
        transposed = False

        if not empty_array:
            value = value.T
            transposed = True

        if self._filters is not None:
            atom = None
            try:
                # get the atom for this datatype
                atom = _tables().Atom.from_dtype(value.dtype)
            except ValueError:
                pass

            if atom is not None:
                # create an empty chunked array and fill it from value
                if not empty_array:
                    ca = self._handle.createCArray(self.group, key, atom,
                                                   value.shape,
                                                   filters=self._filters)
                    ca[:] = value
                    getattr(self.group, key)._v_attrs.transposed = transposed

                else:
                    self.write_array_empty(key, value)

                return

        if value.dtype.type == np.object_:

            # infer the type, warn if we have a non-string type here (for
            # performance)
            inferred_type = lib.infer_dtype(value.ravel())
            if empty_array:
                pass
            elif inferred_type == 'string':
                pass
            else:
                try:
                    items = list(items)
                except:
                    pass
                ws = performance_doc % (inferred_type, key, items)
                warnings.warn(ws, PerformanceWarning)

            vlarr = self._handle.createVLArray(self.group, key,
                                               _tables().ObjectAtom())
            vlarr.append(value)
        else:
            if empty_array:
                self.write_array_empty(key, value)
            else:
                if value.dtype.type == np.datetime64:
                    self._handle.createArray(self.group, key, value.view('i8'))
                    getattr(
                        self.group, key)._v_attrs.value_type = 'datetime64'
                elif value.dtype.type == np.timedelta64:
                    self._handle.createArray(self.group, key, value.view('i8'))
                    getattr(
                        self.group, key)._v_attrs.value_type = 'timedelta64'
                else:
                    self._handle.createArray(self.group, key, value)

        getattr(self.group, key)._v_attrs.transposed = transposed


class LegacyFixed(GenericFixed):

    def read_index_legacy(self, key):
        node = getattr(self.group, key)
        data = node[:]
        kind = node._v_attrs.kind
        return _unconvert_index_legacy(data, kind, encoding=self.encoding)


class LegacySeriesFixed(LegacyFixed):

    def read(self, **kwargs):
        self.validate_read(kwargs)
        index = self.read_index_legacy('index')
        values = self.read_array('values')
        return Series(values, index=index)


class LegacyFrameFixed(LegacyFixed):

    def read(self, **kwargs):
        self.validate_read(kwargs)
        index = self.read_index_legacy('index')
        columns = self.read_index_legacy('columns')
        values = self.read_array('values')
        return DataFrame(values, index=index, columns=columns)


class SeriesFixed(GenericFixed):
    pandas_kind = u('series')
    attributes = ['name']

    @property
    def shape(self):
        try:
            return len(getattr(self.group, 'values')),
        except:
            return None

    def read(self, **kwargs):
        self.validate_read(kwargs)
        index = self.read_index('index')
        values = self.read_array('values')
        return Series(values, index=index, name=self.name)

    def write(self, obj, **kwargs):
        super(SeriesFixed, self).write(obj, **kwargs)
        self.write_index('index', obj.index)
        self.write_array('values', obj.values)
        self.attrs.name = obj.name


class SparseSeriesFixed(GenericFixed):
    pandas_kind = u('sparse_series')
    attributes = ['name', 'fill_value', 'kind']

    def read(self, **kwargs):
        self.validate_read(kwargs)
        index = self.read_index('index')
        sp_values = self.read_array('sp_values')
        sp_index = self.read_index('sp_index')
        return SparseSeries(sp_values, index=index, sparse_index=sp_index,
                            kind=self.kind or u('block'),
                            fill_value=self.fill_value,
                            name=self.name)

    def write(self, obj, **kwargs):
        super(SparseSeriesFixed, self).write(obj, **kwargs)
        self.write_index('index', obj.index)
        self.write_index('sp_index', obj.sp_index)
        self.write_array('sp_values', obj.sp_values)
        self.attrs.name = obj.name
        self.attrs.fill_value = obj.fill_value
        self.attrs.kind = obj.kind


class SparseFrameFixed(GenericFixed):
    pandas_kind = u('sparse_frame')
    attributes = ['default_kind', 'default_fill_value']

    def read(self, **kwargs):
        self.validate_read(kwargs)
        columns = self.read_index('columns')
        sdict = {}
        for c in columns:
            key = 'sparse_series_%s' % c
            s = SparseSeriesFixed(self.parent, getattr(self.group, key))
            s.infer_axes()
            sdict[c] = s.read()
        return SparseDataFrame(sdict, columns=columns,
                               default_kind=self.default_kind,
                               default_fill_value=self.default_fill_value)

    def write(self, obj, **kwargs):
        """ write it as a collection of individual sparse series """
        super(SparseFrameFixed, self).write(obj, **kwargs)
        for name, ss in compat.iteritems(obj):
            key = 'sparse_series_%s' % name
            if key not in self.group._v_children:
                node = self._handle.createGroup(self.group, key)
            else:
                node = getattr(self.group, key)
            s = SparseSeriesFixed(self.parent, node)
            s.write(ss)
        self.attrs.default_fill_value = obj.default_fill_value
        self.attrs.default_kind = obj.default_kind
        self.write_index('columns', obj.columns)


class SparsePanelFixed(GenericFixed):
    pandas_kind = u('sparse_panel')
    attributes = ['default_kind', 'default_fill_value']

    def read(self, **kwargs):
        self.validate_read(kwargs)
        items = self.read_index('items')

        sdict = {}
        for name in items:
            key = 'sparse_frame_%s' % name
            s = SparseFrameFixed(self.parent, getattr(self.group, key))
            s.infer_axes()
            sdict[name] = s.read()
        return SparsePanel(sdict, items=items, default_kind=self.default_kind,
                           default_fill_value=self.default_fill_value)

    def write(self, obj, **kwargs):
        super(SparsePanelFixed, self).write(obj, **kwargs)
        self.attrs.default_fill_value = obj.default_fill_value
        self.attrs.default_kind = obj.default_kind
        self.write_index('items', obj.items)

        for name, sdf in compat.iteritems(obj):
            key = 'sparse_frame_%s' % name
            if key not in self.group._v_children:
                node = self._handle.createGroup(self.group, key)
            else:
                node = getattr(self.group, key)
            s = SparseFrameFixed(self.parent, node)
            s.write(sdf)


class BlockManagerFixed(GenericFixed):
    attributes = ['ndim', 'nblocks']
    is_shape_reversed = False

    @property
    def shape(self):
        try:
            ndim = self.ndim

            # items
            items = 0
            for i in range(self.nblocks):
                node = getattr(self.group, 'block%d_items' % i)
                shape = getattr(node, 'shape', None)
                if shape is not None:
                    items += shape[0]

            # data shape
            node = getattr(self.group, 'block0_values')
            shape = getattr(node, 'shape', None)
            if shape is not None:
                shape = list(shape[0:(ndim - 1)])
            else:
                shape = []

            shape.append(items)

            # hacky - this works for frames, but is reversed for panels
            if self.is_shape_reversed:
                shape = shape[::-1]

            return shape
        except:
            return None

    def read(self, **kwargs):
        self.validate_read(kwargs)

        axes = []
        for i in range(self.ndim):
            ax = self.read_index('axis%d' % i)
            axes.append(ax)

        items = axes[0]
        blocks = []
        for i in range(self.nblocks):
            blk_items = self.read_index('block%d_items' % i)
            values = self.read_array('block%d_values' % i)
            blk = make_block(values, blk_items, items)
            blocks.append(blk)

        return self.obj_type(BlockManager(blocks, axes))

    def write(self, obj, **kwargs):
        super(BlockManagerFixed, self).write(obj, **kwargs)
        data = obj._data
        if not data.is_consolidated():
            data = data.consolidate()

        self.attrs.ndim = data.ndim
        for i, ax in enumerate(data.axes):
            self.write_index('axis%d' % i, ax)

        # Supporting mixed-type DataFrame objects...nontrivial
        self.attrs.nblocks = nblocks = len(data.blocks)
        for i in range(nblocks):
            blk = data.blocks[i]
            # I have no idea why, but writing values before items fixed #2299
            self.write_array('block%d_values' % i, blk.values, items=blk.items)
            self.write_index('block%d_items' % i, blk.items)


class FrameFixed(BlockManagerFixed):
    pandas_kind = u('frame')
    obj_type = DataFrame


class PanelFixed(BlockManagerFixed):
    pandas_kind = u('wide')
    obj_type = Panel
    is_shape_reversed = True

    def write(self, obj, **kwargs):
        obj._consolidate_inplace()
        return super(PanelFixed, self).write(obj, **kwargs)


class Table(Fixed):

    """ represent a table:
          facilitate read/write of various types of tables

        Attrs in Table Node
        -------------------
        These are attributes that are store in the main table node, they are
        necessary to recreate these tables when read back in.

        index_axes    : a list of tuples of the (original indexing axis and
            index column)
        non_index_axes: a list of tuples of the (original index axis and
            columns on a non-indexing axis)
        values_axes   : a list of the columns which comprise the data of this
            table
        data_columns  : a list of the columns that we are allowing indexing
            (these become single columns in values_axes), or True to force all
            columns
        nan_rep       : the string to use for nan representations for string
            objects
        levels        : the names of levels

        """
    pandas_kind = u('wide_table')
    table_type = None
    levels = 1
    is_table = True
    is_shape_reversed = False

    def __init__(self, *args, **kwargs):
        super(Table, self).__init__(*args, **kwargs)
        self.index_axes = []
        self.non_index_axes = []
        self.values_axes = []
        self.data_columns = []
        self.info = dict()
        self.nan_rep = None
        self.selection = None

    @property
    def table_type_short(self):
        return self.table_type.split('_')[0]

    @property
    def format_type(self):
        return 'table'

    def __unicode__(self):
        """ return a pretty representatgion of myself """
        self.infer_axes()
        dc = ",dc->[%s]" % ','.join(
            self.data_columns) if len(self.data_columns) else ''

        ver = ''
        if self.is_old_version:
            ver = "[%s]" % '.'.join([str(x) for x in self.version])

        return "%-12.12s%s (typ->%s,nrows->%s,ncols->%s,indexers->[%s]%s)" % (
            self.pandas_type, ver, self.table_type_short, self.nrows,
            self.ncols, ','.join([a.name for a in self.index_axes]), dc
        )

    def __getitem__(self, c):
        """ return the axis for c """
        for a in self.axes:
            if c == a.name:
                return a
        return None

    def validate(self, other):
        """ validate against an existing table """
        if other is None:
            return

        if other.table_type != self.table_type:
            raise TypeError("incompatible table_type with existing [%s - %s]" %
                            (other.table_type, self.table_type))

        for c in ['index_axes', 'non_index_axes', 'values_axes']:
            sv = getattr(self, c, None)
            ov = getattr(other, c, None)
            if sv != ov:

                # show the error for the specific axes
                for i, sax in enumerate(sv):
                    oax = ov[i]
                    if sax != oax:
                        raise ValueError(
                            "invalid combinate of [%s] on appending data [%s] "
                            "vs current table [%s]" % (c, sax, oax))

                # should never get here
                raise Exception(
                    "invalid combinate of [%s] on appending data [%s] vs "
                    "current table [%s]" % (c, sv, ov))

    @property
    def is_multi_index(self):
        """the levels attribute is 1 or a list in the case of a multi-index"""
        return isinstance(self.levels, list)

    def validate_multiindex(self, obj):
        """validate that we can store the multi-index; reset and return the
        new object
        """
        levels = [l if l is not None else "level_{0}".format(i)
                  for i, l in enumerate(obj.index.names)]
        try:
            return obj.reset_index(), levels
        except ValueError:
            raise ValueError("duplicate names/columns in the multi-index when "
                             "storing as a table")

    @property
    def nrows_expected(self):
        """ based on our axes, compute the expected nrows """
        return np.prod([i.cvalues.shape[0] for i in self.index_axes])

    @property
    def is_exists(self):
        """ has this table been created """
        return u('table') in self.group

    @property
    def storable(self):
        return getattr(self.group, 'table', None)

    @property
    def table(self):
        """ return the table group (this is my storable) """
        return self.storable

    @property
    def dtype(self):
        return self.table.dtype

    @property
    def description(self):
        return self.table.description

    @property
    def axes(self):
        return itertools.chain(self.index_axes, self.values_axes)

    @property
    def ncols(self):
        """ the number of total columns in the values axes """
        return sum([len(a.values) for a in self.values_axes])

    @property
    def is_transposed(self):
        return False

    @property
    def data_orientation(self):
        """return a tuple of my permutated axes, non_indexable at the front"""
        return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes],
                                     [int(a.axis) for a in self.index_axes]))

    def queryables(self):
        """ return a dict of the kinds allowable columns for this object """

        # compute the values_axes queryables
        return dict(
            [(a.cname, a.kind) for a in self.index_axes] +
            [(self.storage_obj_type._AXIS_NAMES[axis], None)
             for axis, values in self.non_index_axes] +
            [(v.cname, v.kind) for v in self.values_axes
             if v.name in set(self.data_columns)]
        )

    def index_cols(self):
        """ return a list of my index cols """
        return [(i.axis, i.cname) for i in self.index_axes]

    def values_cols(self):
        """ return a list of my values cols """
        return [i.cname for i in self.values_axes]

    def set_info(self):
        """ update our table index info """
        self.attrs.info = self.info

    def set_attrs(self):
        """ set our table type & indexables """
        self.attrs.table_type = str(self.table_type)
        self.attrs.index_cols = self.index_cols()
        self.attrs.values_cols = self.values_cols()
        self.attrs.non_index_axes = self.non_index_axes
        self.attrs.data_columns = self.data_columns
        self.attrs.nan_rep = self.nan_rep
        self.attrs.encoding = self.encoding
        self.attrs.levels = self.levels
        self.set_info()

    def get_attrs(self):
        """ retrieve our attributes """
        self.non_index_axes = getattr(
            self.attrs, 'non_index_axes', None) or []
        self.data_columns = getattr(
            self.attrs, 'data_columns', None) or []
        self.info = getattr(
            self.attrs, 'info', None) or dict()
        self.nan_rep = getattr(self.attrs, 'nan_rep', None)
        self.encoding = _ensure_encoding(
            getattr(self.attrs, 'encoding', None))
        self.levels = getattr(
            self.attrs, 'levels', None) or []
        t = self.table
        self.index_axes = [
            a.infer(t) for a in self.indexables if a.is_an_indexable
        ]
        self.values_axes = [
            a.infer(t) for a in self.indexables if not a.is_an_indexable
        ]

    def validate_version(self, where=None):
        """ are we trying to operate on an old version? """
        if where is not None:
            if (self.version[0] <= 0 and self.version[1] <= 10 and
                    self.version[2] < 1):
                ws = incompatibility_doc % '.'.join(
                    [str(x) for x in self.version])
                warnings.warn(ws, IncompatibilityWarning)

    def validate_min_itemsize(self, min_itemsize):
        """validate the min_itemisze doesn't contain items that are not in the
        axes this needs data_columns to be defined
        """
        if min_itemsize is None:
            return
        if not isinstance(min_itemsize, dict):
            return

        q = self.queryables()
        for k, v in min_itemsize.items():

            # ok, apply generally
            if k == 'values':
                continue
            if k not in q:
                raise ValueError(
                    "min_itemsize has the key [%s] which is not an axis or "
                    "data_column" % k)

    @property
    def indexables(self):
        """ create/cache the indexables if they don't exist """
        if self._indexables is None:

            self._indexables = []

            # index columns
            self._indexables.extend([
                IndexCol(name=name, axis=axis, pos=i)
                for i, (axis, name) in enumerate(self.attrs.index_cols)
            ])

            # values columns
            dc = set(self.data_columns)
            base_pos = len(self._indexables)

            def f(i, c):
                klass = DataCol
                if c in dc:
                    klass = DataIndexableCol
                return klass.create_for_block(i=i, name=c, pos=base_pos + i,
                                              version=self.version)

            self._indexables.extend(
                [f(i, c) for i, c in enumerate(self.attrs.values_cols)])

        return self._indexables

    def create_index(self, columns=None, optlevel=None, kind=None):
        """
        Create a pytables index on the specified columns
          note: cannot index Time64Col() currently; PyTables must be >= 2.3


        Paramaters
        ----------
        columns : False (don't create an index), True (create all columns
            index), None or list_like (the indexers to index)
        optlevel: optimization level (defaults to 6)
        kind    : kind of index (defaults to 'medium')

        Exceptions
        ----------
        raises if the node is not a table

        """

        if not self.infer_axes():
            return
        if columns is False:
            return

        # index all indexables and data_columns
        if columns is None or columns is True:
            columns = [a.cname for a in self.axes if a.is_data_indexable]
        if not isinstance(columns, (tuple, list)):
            columns = [columns]

        kw = dict()
        if optlevel is not None:
            kw['optlevel'] = optlevel
        if kind is not None:
            kw['kind'] = kind

        table = self.table
        for c in columns:
            v = getattr(table.cols, c, None)
            if v is not None:

                # remove the index if the kind/optlevel have changed
                if v.is_indexed:
                    index = v.index
                    cur_optlevel = index.optlevel
                    cur_kind = index.kind

                    if kind is not None and cur_kind != kind:
                        v.removeIndex()
                    else:
                        kw['kind'] = cur_kind

                    if optlevel is not None and cur_optlevel != optlevel:
                        v.removeIndex()
                    else:
                        kw['optlevel'] = cur_optlevel

                # create the index
                if not v.is_indexed:
                    v.createIndex(**kw)

    def read_axes(self, where, **kwargs):
        """create and return the axes sniffed from the table: return boolean
        for success
        """

        # validate the version
        self.validate_version(where)

        # infer the data kind
        if not self.infer_axes():
            return False

        # create the selection
        self.selection = Selection(self, where=where, **kwargs)
        values = self.selection.select()

        # convert the data
        for a in self.axes:
            a.set_info(self.info)
            a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding)

        return True

    def get_object(self, obj):
        """ return the data for this obj """
        return obj

    def validate_data_columns(self, data_columns, min_itemsize):
        """take the input data_columns and min_itemize and create a data
        columns spec
        """

        if not len(self.non_index_axes):
            return []

        axis, axis_labels = self.non_index_axes[0]
        info = self.info.get(axis, dict())
        if info.get('type') == 'MultiIndex' and data_columns:
            raise ValueError("cannot use a multi-index on axis [{0}] with "
                             "data_columns {1}".format(axis, data_columns))

        # evaluate the passed data_columns, True == use all columns
        # take only valide axis labels
        if data_columns is True:
            data_columns = axis_labels
        elif data_columns is None:
            data_columns = []

        # if min_itemsize is a dict, add the keys (exclude 'values')
        if isinstance(min_itemsize, dict):

            existing_data_columns = set(data_columns)
            data_columns.extend([
                k for k in min_itemsize.keys()
                if k != 'values' and k not in existing_data_columns
            ])

        # return valid columns in the order of our axis
        return [c for c in data_columns if c in axis_labels]

    def create_axes(self, axes, obj, validate=True, nan_rep=None,
                    data_columns=None, min_itemsize=None, **kwargs):
        """ create and return the axes
        leagcy tables create an indexable column, indexable index,
        non-indexable fields

            Parameters:
            -----------
            axes: a list of the axes in order to create (names or numbers of
                the axes)
            obj : the object to create axes on
            validate: validate the obj against an existing object already
                written
            min_itemsize: a dict of the min size for a column in bytes
            nan_rep : a values to use for string column nan_rep
            encoding : the encoding for string values
            data_columns : a list of columns that we want to create separate to
                allow indexing (or True will force all columns)

        """

        # set the default axes if needed
        if axes is None:
            try:
                axes = _AXES_MAP[type(obj)]
            except:
                raise TypeError("cannot properly create the storer for: "
                                "[group->%s,value->%s]"
                                % (self.group._v_name, type(obj)))

        # map axes to numbers
        axes = [obj._get_axis_number(a) for a in axes]

        # do we have an existing table (if so, use its axes & data_columns)
        if self.infer_axes():
            existing_table = self.copy()
            existing_table.infer_axes()
            axes = [a.axis for a in existing_table.index_axes]
            data_columns = existing_table.data_columns
            nan_rep = existing_table.nan_rep
            self.encoding = existing_table.encoding
            self.info = copy.copy(existing_table.info)
        else:
            existing_table = None

        # currently support on ndim-1 axes
        if len(axes) != self.ndim - 1:
            raise ValueError(
                "currently only support ndim-1 indexers in an AppendableTable")

        # create according to the new data
        self.non_index_axes = []
        self.data_columns = []

        # nan_representation
        if nan_rep is None:
            nan_rep = 'nan'

        self.nan_rep = nan_rep

        # create axes to index and non_index
        index_axes_map = dict()
        for i, a in enumerate(obj.axes):

            if i in axes:
                name = obj._AXIS_NAMES[i]
                index_axes_map[i] = _convert_index(
                    a, self.encoding, self.format_type
                ).set_name(name).set_axis(i)
            else:

                # we might be able to change the axes on the appending data if
                # necessary
                append_axis = list(a)
                if existing_table is not None:
                    indexer = len(self.non_index_axes)
                    exist_axis = existing_table.non_index_axes[indexer][1]
                    if append_axis != exist_axis:

                        # ahah! -> reindex
                        if sorted(append_axis) == sorted(exist_axis):
                            append_axis = exist_axis

                # the non_index_axes info
                info = _get_info(self.info, i)
                info['names'] = list(a.names)
                info['type'] = a.__class__.__name__

                self.non_index_axes.append((i, append_axis))

        # set axis positions (based on the axes)
        self.index_axes = [
            index_axes_map[a].set_pos(j).update_info(self.info)
            for j, a in enumerate(axes)
        ]
        j = len(self.index_axes)

        # check for column conflicts
        if validate:
            for a in self.axes:
                a.maybe_set_size(min_itemsize=min_itemsize)

        # reindex by our non_index_axes & compute data_columns
        for a in self.non_index_axes:
            obj = _reindex_axis(obj, a[0], a[1])

        # figure out data_columns and get out blocks
        block_obj = self.get_object(obj).consolidate()
        blocks = block_obj._data.blocks
        if len(self.non_index_axes):
            axis, axis_labels = self.non_index_axes[0]
            data_columns = self.validate_data_columns(
                data_columns, min_itemsize)
            if len(data_columns):
                blocks = block_obj.reindex_axis(
                    Index(axis_labels) - Index(data_columns),
                    axis=axis
                )._data.blocks
                for c in data_columns:
                    blocks.extend(
                        block_obj.reindex_axis([c], axis=axis)._data.blocks)

        # reorder the blocks in the same order as the existing_table if we can
        if existing_table is not None:
            by_items = dict([(tuple(b.items.tolist()), b) for b in blocks])
            new_blocks = []
            for ea in existing_table.values_axes:
                items = tuple(ea.values)
                try:
                    b = by_items.pop(items)
                    new_blocks.append(b)
                except:
                    raise ValueError(
                        "cannot match existing table structure for [%s] on "
                        "appending data" % ','.join(com.pprint_thing(item) for
                                                    item in items))
            blocks = new_blocks

        # add my values
        self.values_axes = []
        for i, b in enumerate(blocks):

            # shape of the data column are the indexable axes
            klass = DataCol
            name = None

            # we have a data_column
            if (data_columns and len(b.items) == 1 and
                    b.items[0] in data_columns):
                klass = DataIndexableCol
                name = b.items[0]
                self.data_columns.append(name)

            # make sure that we match up the existing columns
            # if we have an existing table
            if existing_table is not None and validate:
                try:
                    existing_col = existing_table.values_axes[i]
                except:
                    raise ValueError("Incompatible appended table [%s] with "
                                     "existing table [%s]"
                                     % (blocks, existing_table.values_axes))
            else:
                existing_col = None

            try:
                col = klass.create_for_block(
                    i=i, name=name, version=self.version)
                col.set_atom(block=b,
                             existing_col=existing_col,
                             min_itemsize=min_itemsize,
                             nan_rep=nan_rep,
                             encoding=self.encoding,
                             info=self.info,
                             **kwargs)
                col.set_pos(j)

                self.values_axes.append(col)
            except (NotImplementedError, ValueError, TypeError) as e:
                raise e
            except Exception as detail:
                raise Exception(
                    "cannot find the correct atom type -> "
                    "[dtype->%s,items->%s] %s"
                    % (b.dtype.name, b.items, str(detail))
                )
            j += 1

        # validate our min_itemsize
        self.validate_min_itemsize(min_itemsize)

        # validate the axes if we have an existing table
        if validate:
            self.validate(existing_table)

    def process_axes(self, obj, columns=None):
        """ process axes filters """

        # make sure to include levels if we have them
        if columns is not None and self.is_multi_index:
            for n in self.levels:
                if n not in columns:
                    columns.insert(0, n)

        # reorder by any non_index_axes & limit to the select columns
        for axis, labels in self.non_index_axes:
            obj = _reindex_axis(obj, axis, labels, columns)

        # apply the selection filters (but keep in the same order)
        if self.selection.filter is not None:
            for field, op, filt in self.selection.filter.format():

                def process_filter(field, filt):

                    for axis_name in obj._AXIS_NAMES.values():
                        axis_number = obj._get_axis_number(axis_name)
                        axis_values = obj._get_axis(axis_name)

                        # see if the field is the name of an axis
                        if field == axis_name:

                            # if we have a multi-index, then need to include
                            # the levels
                            if self.is_multi_index:
                                filt = filt + Index(self.levels)

                            takers = op(axis_values, filt)
                            return obj.ix._getitem_axis(takers,
                                                        axis=axis_number)

                        # this might be the name of a file IN an axis
                        elif field in axis_values:

                            # we need to filter on this dimension
                            values = _ensure_index(getattr(obj, field).values)
                            filt = _ensure_index(filt)

                            # hack until we support reversed dim flags
                            if isinstance(obj, DataFrame):
                                axis_number = 1 - axis_number
                            takers = op(values, filt)
                            return obj.ix._getitem_axis(takers,
                                                        axis=axis_number)

                    raise ValueError(
                        "cannot find the field [%s] for filtering!" % field)

                obj = process_filter(field, filt)

        return obj

    def create_description(self, complib=None, complevel=None,
                           fletcher32=False, expectedrows=None):
        """ create the description of the table from the axes & values """

        # expected rows estimate
        if expectedrows is None:
            expectedrows = max(self.nrows_expected, 10000)
        d = dict(name='table', expectedrows=expectedrows)

        # description from the axes & values
        d['description'] = dict([(a.cname, a.typ) for a in self.axes])

        if complib:
            if complevel is None:
                complevel = self._complevel or 9
            filters = _tables().Filters(
                complevel=complevel, complib=complib,
                fletcher32=fletcher32 or self._fletcher32)
            d['filters'] = filters
        elif self._filters is not None:
            d['filters'] = self._filters

        return d

    def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
        """select coordinates (row numbers) from a table; return the
        coordinates object
        """

        # validate the version
        self.validate_version(where)

        # infer the data kind
        if not self.infer_axes():
            return False

        # create the selection
        self.selection = Selection(
            self, where=where, start=start, stop=stop, **kwargs)
        return Index(self.selection.select_coords())

    def read_column(self, column, where=None, **kwargs):
        """return a single column from the table, generally only indexables
        are interesting
        """

        # validate the version
        self.validate_version()

        # infer the data kind
        if not self.infer_axes():
            return False

        if where is not None:
            raise TypeError("read_column does not currently accept a where "
                            "clause")

        # find the axes
        for a in self.axes:
            if column == a.name:

                if not a.is_data_indexable:
                    raise ValueError(
                        "column [%s] can not be extracted individually; it is "
                        "not data indexable" % column)

                # column must be an indexable or a data column
                c = getattr(self.table.cols, column)
                a.set_info(self.info)
                return Series(a.convert(c[:], nan_rep=self.nan_rep,
                                        encoding=self.encoding).take_data())

        raise KeyError("column [%s] not found in the table" % column)


class WORMTable(Table):

    """ a write-once read-many table: this format DOES NOT ALLOW appending to a
         table. writing is a one-time operation the data are stored in a format
         that allows for searching the data on disk
         """
    table_type = u('worm')

    def read(self, **kwargs):
        """ read the indicies and the indexing array, calculate offset rows and
        return """
        raise NotImplementedError("WORMTable needs to implement read")

    def write(self, **kwargs):
        """ write in a format that we can search later on (but cannot append
               to): write out the indicies and the values using _write_array
               (e.g. a CArray) create an indexing table so that we can search
        """
        raise NotImplementedError("WORKTable needs to implement write")


class LegacyTable(Table):

    """ an appendable table: allow append/query/delete operations to a
          (possibily) already existing appendable table this table ALLOWS
          append (but doesn't require them), and stores the data in a format
          that can be easily searched

    """
    _indexables = [
        IndexCol(name='index', axis=1, pos=0),
        IndexCol(name='column', axis=2, pos=1, index_kind='columns_kind'),
        DataCol(name='fields', cname='values', kind_attr='fields', pos=2)
    ]
    table_type = u('legacy')
    ndim = 3

    def write(self, **kwargs):
        raise TypeError("write operations are not allowed on legacy tables!")

    def read(self, where=None, columns=None, **kwargs):
        """we have n indexable columns, with an arbitrary number of data
        axes
        """

        if not self.read_axes(where=where, **kwargs):
            return None

        factors = [Categorical.from_array(a.values) for a in self.index_axes]
        levels = [f.levels for f in factors]
        N = [len(f.levels) for f in factors]
        labels = [f.labels for f in factors]

        # compute the key
        key = factor_indexer(N[1:], labels)

        objs = []
        if len(unique(key)) == len(key):

            sorter, _ = algos.groupsort_indexer(
                com._ensure_int64(key), np.prod(N))
            sorter = com._ensure_platform_int(sorter)

            # create the objs
            for c in self.values_axes:

                # the data need to be sorted
                sorted_values = c.take_data().take(sorter, axis=0)
                if sorted_values.ndim == 1:
                    sorted_values = sorted_values.reshape(sorted_values.shape[0],1)

                take_labels = [l.take(sorter) for l in labels]
                items = Index(c.values)
                block = block2d_to_blocknd(
                    sorted_values, items, tuple(N), take_labels)

                # create the object
                mgr = BlockManager([block], [items] + levels)
                obj = self.obj_type(mgr)

                # permute if needed
                if self.is_transposed:
                    obj = obj.transpose(
                        *tuple(Series(self.data_orientation).argsort()))

                objs.append(obj)

        else:
            warnings.warn(duplicate_doc, DuplicateWarning)

            # reconstruct
            long_index = MultiIndex.from_arrays(
                [i.values for i in self.index_axes])

            for c in self.values_axes:
                lp = DataFrame(c.data, index=long_index, columns=c.values)

                # need a better algorithm
                tuple_index = long_index._tuple_index

                unique_tuples = lib.fast_unique(tuple_index)
                unique_tuples = _asarray_tuplesafe(unique_tuples)

                indexer = match(unique_tuples, tuple_index)
                indexer = com._ensure_platform_int(indexer)

                new_index = long_index.take(indexer)
                new_values = lp.values.take(indexer, axis=0)

                lp = DataFrame(new_values, index=new_index, columns=lp.columns)
                objs.append(lp.to_panel())

        # create the composite object
        if len(objs) == 1:
            wp = objs[0]
        else:
            wp = concat(objs, axis=0, verify_integrity=False).consolidate()

        # apply the selection filters & axis orderings
        wp = self.process_axes(wp, columns=columns)

        return wp


class LegacyFrameTable(LegacyTable):

    """ support the legacy frame table """
    pandas_kind = u('frame_table')
    table_type = u('legacy_frame')
    obj_type = Panel

    def read(self, *args, **kwargs):
        return super(LegacyFrameTable, self).read(*args, **kwargs)['value']


class LegacyPanelTable(LegacyTable):

    """ support the legacy panel table """
    table_type = u('legacy_panel')
    obj_type = Panel


class AppendableTable(LegacyTable):

    """ suppor the new appendable table formats """
    _indexables = None
    table_type = u('appendable')

    def write(self, obj, axes=None, append=False, complib=None,
              complevel=None, fletcher32=None, min_itemsize=None,
              chunksize=None, expectedrows=None, dropna=True, **kwargs):

        if not append and self.is_exists:
            self._handle.removeNode(self.group, 'table')

        # create the axes
        self.create_axes(axes=axes, obj=obj, validate=append,
                         min_itemsize=min_itemsize,
                         **kwargs)

        if not self.is_exists:

            # create the table
            options = self.create_description(complib=complib,
                                              complevel=complevel,
                                              fletcher32=fletcher32,
                                              expectedrows=expectedrows)

            # set the table attributes
            self.set_attrs()

            # create the table
            table = self._handle.createTable(self.group, **options)

        else:
            table = self.table

        # update my info
        self.set_info()

        # validate the axes and set the kinds
        for a in self.axes:
            a.validate_and_set(table, append)

        # add the rows
        self.write_data(chunksize, dropna=dropna)

    def write_data(self, chunksize, dropna=True):
        """ we form the data into a 2-d including indexes,values,mask
            write chunk-by-chunk """

        names = self.dtype.names
        nrows = self.nrows_expected

        # if dropna==True, then drop ALL nan rows
        if dropna:

            masks = []
            for a in self.values_axes:

                # figure the mask: only do if we can successfully process this
                # column, otherwise ignore the mask
                mask = com.isnull(a.data).all(axis=0)
                masks.append(mask.astype('u1'))

            # consolidate masks
            mask = masks[0]
            for m in masks[1:]:
                mask = mask & m
            mask = mask.ravel()

        else:

            mask = np.empty(nrows, dtype='u1')
            mask.fill(False)

        # broadcast the indexes if needed
        indexes = [a.cvalues for a in self.index_axes]
        nindexes = len(indexes)
        bindexes = []
        for i, idx in enumerate(indexes):

            # broadcast to all other indexes except myself
            if i > 0 and i < nindexes:
                repeater = np.prod(
                    [indexes[bi].shape[0] for bi in range(0, i)])
                idx = np.tile(idx, repeater)

            if i < nindexes - 1:
                repeater = np.prod([indexes[bi].shape[0]
                                   for bi in range(i + 1, nindexes)])
                idx = np.repeat(idx, repeater)

            bindexes.append(idx)

        # transpose the values so first dimension is last
        # reshape the values if needed
        values = [a.take_data() for a in self.values_axes]
        values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1))
                  for v in values]
        bvalues = []
        for i, v in enumerate(values):
            new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
            bvalues.append(values[i].ravel().reshape(new_shape))

        # write the chunks
        if chunksize is None:
            chunksize = 100000

        chunks = int(nrows / chunksize) + 1
        for i in range(chunks):
            start_i = i * chunksize
            end_i = min((i + 1) * chunksize, nrows)
            if start_i >= end_i:
                break

            self.write_data_chunk(
                indexes=[a[start_i:end_i] for a in bindexes],
                mask=mask[start_i:end_i],
                values=[v[start_i:end_i] for v in bvalues])

    def write_data_chunk(self, indexes, mask, values):

        # 0 len
        for v in values:
            if not np.prod(v.shape):
                return

        try:
            nrows = indexes[0].shape[0]
            rows = np.empty(nrows, dtype=self.dtype)
            names = self.dtype.names
            nindexes = len(indexes)

            # indexes
            for i, idx in enumerate(indexes):
                rows[names[i]] = idx

            # values
            for i, v in enumerate(values):
                rows[names[i + nindexes]] = v

            # mask
            rows = rows[~mask.ravel().astype(bool)]

        except Exception as detail:
            raise Exception("cannot create row-data -> %s" % detail)

        try:
            if len(rows):
                self.table.append(rows)
                self.table.flush()
        except Exception as detail:
            raise TypeError("tables cannot write this data -> %s" % detail)

    def delete(self, where=None, **kwargs):

        # delete all rows (and return the nrows)
        if where is None or not len(where):
            nrows = self.nrows
            self._handle.removeNode(self.group, recursive=True)
            return nrows

        # infer the data kind
        if not self.infer_axes():
            return None

        # create the selection
        table = self.table
        self.selection = Selection(self, where, **kwargs)
        values = self.selection.select_coords()

        # delete the rows in reverse order
        l = Series(values).order()
        ln = len(l)

        if ln:

            # construct groups of consecutive rows
            diff = l.diff()
            groups = list(diff[diff > 1].index)

            # 1 group
            if not len(groups):
                groups = [0]

            # final element
            if groups[-1] != ln:
                groups.append(ln)

            # initial element
            if groups[0] != 0:
                groups.insert(0, 0)

            # we must remove in reverse order!
            pg = groups.pop()
            for g in reversed(groups):
                rows = l.take(lrange(g, pg))
                table.removeRows(start=rows[rows.index[0]
                                            ], stop=rows[rows.index[-1]] + 1)
                pg = g

            self.table.flush()

        # return the number of rows removed
        return ln


class AppendableFrameTable(AppendableTable):

    """ suppor the new appendable table formats """
    pandas_kind = u('frame_table')
    table_type = u('appendable_frame')
    ndim = 2
    obj_type = DataFrame

    @property
    def is_transposed(self):
        return self.index_axes[0].axis == 1

    def get_object(self, obj):
        """ these are written transposed """
        if self.is_transposed:
            obj = obj.T
        return obj

    def read(self, where=None, columns=None, **kwargs):

        if not self.read_axes(where=where, **kwargs):
            return None

        info = (self.info.get(self.non_index_axes[0][0], dict())
                if len(self.non_index_axes) else dict())
        index = self.index_axes[0].values
        frames = []
        for a in self.values_axes:

            # we could have a multi-index constructor here
            # _ensure_index doesn't recognized our list-of-tuples here
            if info.get('type') == 'MultiIndex':
                cols = MultiIndex.from_tuples(a.values)
            else:
                cols = Index(a.values)
            names = info.get('names')
            if names is not None:
                cols.set_names(names, inplace=True)

            if self.is_transposed:
                values = a.cvalues
                index_ = cols
                cols_ = Index(index, name=getattr(index, 'name', None))
            else:
                values = a.cvalues.T
                index_ = Index(index, name=getattr(index, 'name', None))
                cols_ = cols

            # if we have a DataIndexableCol, its shape will only be 1 dim
            if values.ndim == 1:
                values = values.reshape(1, values.shape[0])

            block = make_block(values, cols_, cols_)
            mgr = BlockManager([block], [cols_, index_])
            frames.append(DataFrame(mgr))

        if len(frames) == 1:
            df = frames[0]
        else:
            df = concat(frames, axis=1, verify_integrity=False).consolidate()

        # apply the selection filters & axis orderings
        df = self.process_axes(df, columns=columns)

        return df


class AppendableSeriesTable(AppendableFrameTable):
    """ support the new appendable table formats """
    pandas_kind = u('series_table')
    table_type = u('appendable_series')
    ndim = 2
    obj_type = Series
    storage_obj_type = DataFrame

    @property
    def is_transposed(self):
        return False

    def get_object(self, obj):
        return obj

    def write(self, obj, data_columns=None, **kwargs):
        """ we are going to write this as a frame table """
        if not isinstance(obj, DataFrame):
            name = obj.name or 'values'
            obj = DataFrame({name: obj}, index=obj.index)
            obj.columns = [name]
        return super(AppendableSeriesTable, self).write(
            obj=obj, data_columns=obj.columns, **kwargs)

    def read(self, columns=None, **kwargs):

        is_multi_index = self.is_multi_index
        if columns is not None and is_multi_index:
            for n in self.levels:
                if n not in columns:
                    columns.insert(0, n)
        s = super(AppendableSeriesTable, self).read(columns=columns, **kwargs)
        if is_multi_index:
            s.set_index(self.levels, inplace=True)

        s = s.iloc[:, 0]

        # remove the default name
        if s.name == 'values':
            s.name = None
        return s


class AppendableMultiSeriesTable(AppendableSeriesTable):
    """ support the new appendable table formats """
    pandas_kind = u('series_table')
    table_type = u('appendable_multiseries')

    def write(self, obj, **kwargs):
        """ we are going to write this as a frame table """
        name = obj.name or 'values'
        obj, self.levels = self.validate_multiindex(obj)
        cols = list(self.levels)
        cols.append(name)
        obj.columns = cols
        return super(AppendableMultiSeriesTable, self).write(obj=obj, **kwargs)


class GenericTable(AppendableFrameTable):
    """ a table that read/writes the generic pytables table format """
    pandas_kind = u('frame_table')
    table_type = u('generic_table')
    ndim = 2
    obj_type = DataFrame

    @property
    def pandas_type(self):
        return self.pandas_kind

    @property
    def storable(self):
        return getattr(self.group, 'table', None) or self.group

    def get_attrs(self):
        """ retrieve our attributes """
        self.non_index_axes = []
        self.nan_rep = None
        self.levels = []
        t = self.table
        self.index_axes = [a.infer(t)
                           for a in self.indexables if a.is_an_indexable]
        self.values_axes = [a.infer(t)
                            for a in self.indexables if not a.is_an_indexable]
        self.data_columns = [a.name for a in self.values_axes]

    @property
    def indexables(self):
        """ create the indexables from the table description """
        if self._indexables is None:

            d = self.description

            # the index columns is just a simple index
            self._indexables = [GenericIndexCol(name='index', axis=0)]

            for i, n in enumerate(d._v_names):

                dc = GenericDataIndexableCol(
                    name=n, pos=i, values=[n], version=self.version)
                self._indexables.append(dc)

        return self._indexables

    def write(self, **kwargs):
        raise NotImplementedError("cannot write on an generic table")


class AppendableMultiFrameTable(AppendableFrameTable):

    """ a frame with a multi-index """
    table_type = u('appendable_multiframe')
    obj_type = DataFrame
    ndim = 2
    _re_levels = re.compile("^level_\d+$")

    @property
    def table_type_short(self):
        return u('appendable_multi')

    def write(self, obj, data_columns=None, **kwargs):
        if data_columns is None:
            data_columns = []
        elif data_columns is True:
            data_columns = obj.columns[:]
        obj, self.levels = self.validate_multiindex(obj)
        for n in self.levels:
            if n not in data_columns:
                data_columns.insert(0, n)
        return super(AppendableMultiFrameTable, self).write(
            obj=obj, data_columns=data_columns, **kwargs)

    def read(self, **kwargs):

        df = super(AppendableMultiFrameTable, self).read(**kwargs)
        df = df.set_index(self.levels)

        # remove names for 'level_%d'
        df.index = df.index.set_names([
            None if self._re_levels.search(l) else l for l in df.index.names
        ])

        return df

class AppendablePanelTable(AppendableTable):

    """ suppor the new appendable table formats """
    table_type = u('appendable_panel')
    ndim = 3
    obj_type = Panel

    def get_object(self, obj):
        """ these are written transposed """
        if self.is_transposed:
            obj = obj.transpose(*self.data_orientation)
        return obj

    @property
    def is_transposed(self):
        return self.data_orientation != tuple(range(self.ndim))


class AppendableNDimTable(AppendablePanelTable):

    """ suppor the new appendable table formats """
    table_type = u('appendable_ndim')
    ndim = 4
    obj_type = Panel4D


def _reindex_axis(obj, axis, labels, other=None):
    ax = obj._get_axis(axis)
    labels = _ensure_index(labels)

    # try not to reindex even if other is provided
    # if it equals our current index
    if other is not None:
        other = _ensure_index(other)
    if (other is None or labels.equals(other)) and labels.equals(ax):
        return obj

    labels = _ensure_index(labels.unique())
    if other is not None:
        labels = labels & _ensure_index(other.unique())
    if not labels.equals(ax):
        slicer = [slice(None, None)] * obj.ndim
        slicer[axis] = labels
        obj = obj.loc[tuple(slicer)]
    return obj


def _get_info(info, name):
    """ get/create the info for this name """
    try:
        idx = info[name]
    except:
        idx = info[name] = dict()
    return idx


def _convert_index(index, encoding=None, format_type=None):
    index_name = getattr(index, 'name', None)

    if isinstance(index, DatetimeIndex):
        converted = index.asi8
        return IndexCol(converted, 'datetime64', _tables().Int64Col(),
                        freq=getattr(index, 'freq', None),
                        tz=getattr(index, 'tz', None),
                        index_name=index_name)
    elif isinstance(index, (Int64Index, PeriodIndex)):
        atom = _tables().Int64Col()
        return IndexCol(
            index.values, 'integer', atom, freq=getattr(index, 'freq', None),
            index_name=index_name)

    if isinstance(index, MultiIndex):
        raise TypeError('MultiIndex not supported here!')

    inferred_type = lib.infer_dtype(index)

    values = np.asarray(index)

    if inferred_type == 'datetime64':
        converted = values.view('i8')
        return IndexCol(converted, 'datetime64', _tables().Int64Col(),
                        freq=getattr(index, 'freq', None),
                        tz=getattr(index, 'tz', None),
                        index_name=index_name)
    elif inferred_type == 'datetime':
        converted = np.array([(time.mktime(v.timetuple()) +
                               v.microsecond / 1E6) for v in values],
                             dtype=np.float64)
        return IndexCol(converted, 'datetime', _tables().Time64Col(),
                        index_name=index_name)
    elif inferred_type == 'date':
        converted = np.array([v.toordinal() for v in values],
                             dtype=np.int32)
        return IndexCol(converted, 'date', _tables().Time32Col(),
                        index_name=index_name)
    elif inferred_type == 'string':
        # atom = _tables().ObjectAtom()
        # return np.asarray(values, dtype='O'), 'object', atom

        converted = _convert_string_array(values, encoding)
        itemsize = converted.dtype.itemsize
        return IndexCol(
            converted, 'string', _tables().StringCol(itemsize),
            itemsize=itemsize, index_name=index_name
        )
    elif inferred_type == 'unicode':
        if format_type == 'fixed':
            atom = _tables().ObjectAtom()
            return IndexCol(np.asarray(values, dtype='O'), 'object', atom,
                            index_name=index_name)
        raise TypeError(
            "[unicode] is not supported as a in index type for [{0}] formats"
            .format(format_type)
        )

    elif inferred_type == 'integer':
        # take a guess for now, hope the values fit
        atom = _tables().Int64Col()
        return IndexCol(np.asarray(values, dtype=np.int64), 'integer', atom,
                        index_name=index_name)
    elif inferred_type == 'floating':
        atom = _tables().Float64Col()
        return IndexCol(np.asarray(values, dtype=np.float64), 'float', atom,
                        index_name=index_name)
    else:  # pragma: no cover
        atom = _tables().ObjectAtom()
        return IndexCol(np.asarray(values, dtype='O'), 'object', atom,
                        index_name=index_name)


def _unconvert_index(data, kind, encoding=None):
    kind = _ensure_decoded(kind)
    if kind == u('datetime64'):
        index = DatetimeIndex(data)
    elif kind == u('datetime'):
        index = np.array([datetime.fromtimestamp(v) for v in data],
                         dtype=object)
    elif kind == u('date'):
        try:
            index = np.array(
                [date.fromordinal(v) for v in data], dtype=object)
        except (ValueError):
            index = np.array(
                [date.fromtimestamp(v) for v in data], dtype=object)
    elif kind in (u('integer'), u('float')):
        index = np.array(data)
    elif kind in (u('string')):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding)
    elif kind == u('object'):
        index = np.array(data[0])
    else:  # pragma: no cover
        raise ValueError('unrecognized index type %s' % kind)
    return index


def _unconvert_index_legacy(data, kind, legacy=False, encoding=None):
    kind = _ensure_decoded(kind)
    if kind == u('datetime'):
        index = lib.time64_to_datetime(data)
    elif kind in (u('integer')):
        index = np.array(data, dtype=object)
    elif kind in (u('string')):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding)
    else:  # pragma: no cover
        raise ValueError('unrecognized index type %s' % kind)
    return index


def _convert_string_array(data, encoding, itemsize=None):

    # encode if needed
    if encoding is not None and len(data):
        f = np.vectorize(lambda x: x.encode(encoding), otypes=[np.object])
        data = f(data)

    # create the sized dtype
    if itemsize is None:
        itemsize = lib.max_len_string_array(com._ensure_object(data.ravel()))

    data = np.array(data, dtype="S%d" % itemsize)
    return data


def _unconvert_string_array(data, nan_rep=None, encoding=None):
    """ deserialize a string array, possibly decoding """
    shape = data.shape
    data = np.array(data.ravel(), dtype=object)

    # guard against a None encoding in PY3 (because of a legacy
    # where the passed encoding is actually None)
    encoding = _ensure_encoding(encoding)
    if encoding is not None and len(data):
        try:
            data = data.astype(str).astype(object)
        except:
            f = np.vectorize(lambda x: x.decode(encoding), otypes=[np.object])
            data = f(data)

    if nan_rep is None:
        nan_rep = 'nan'

    data = lib.string_array_replace_from_nan_rep(data, nan_rep)
    return data.reshape(shape)


def _maybe_convert(values, val_kind, encoding):
    if _need_convert(val_kind):
        conv = _get_converter(val_kind, encoding)
        # conv = np.frompyfunc(conv, 1, 1)
        values = conv(values)
    return values


def _get_converter(kind, encoding):
    kind = _ensure_decoded(kind)
    if kind == 'datetime64':
        return lambda x: np.array(x, dtype='M8[ns]')
    elif kind == 'datetime':
        return lib.convert_timestamps
    elif kind == 'string':
        return lambda x: _unconvert_string_array(x, encoding=encoding)
    else:  # pragma: no cover
        raise ValueError('invalid kind %s' % kind)


def _need_convert(kind):
    kind = _ensure_decoded(kind)
    if kind in (u('datetime'), u('datetime64'), u('string')):
        return True
    return False


class Selection(object):

    """
    Carries out a selection operation on a tables.Table object.

    Parameters
    ----------
    table : a Table object
    where : list of Terms (or convertable to)
    start, stop: indicies to start and/or stop selection

    """

    def __init__(self, table, where=None, start=None, stop=None, **kwargs):
        self.table = table
        self.where = where
        self.start = start
        self.stop = stop
        self.condition = None
        self.filter = None
        self.terms = None
        self.coordinates = None

        if com.is_list_like(where):

            # see if we have a passed coordinate like
            try:
                inferred = lib.infer_dtype(where)
                if inferred == 'integer' or inferred == 'boolean':
                    where = np.array(where)
                    if where.dtype == np.bool_:
                        start, stop = self.start, self.stop
                        if start is None:
                            start = 0
                        if stop is None:
                            stop = self.table.nrows
                        self.coordinates = np.arange(start, stop)[where]
                    elif issubclass(where.dtype.type, np.integer):
                        if ((self.start is not None and
                                (where < self.start).any()) or
                            (self.stop is not None and
                                (where >= self.stop).any())):
                            raise ValueError(
                                "where must have index locations >= start and "
                                "< stop"
                            )
                        self.coordinates = where

            except:
                pass

        if self.coordinates is None:

            self.terms = self.generate(where)

            # create the numexpr & the filter
            if self.terms is not None:
                self.condition, self.filter = self.terms.evaluate()

    def generate(self, where):
        """ where can be a : dict,list,tuple,string """
        if where is None:
            return None

        q = self.table.queryables()
        try:
            return Expr(where, queryables=q, encoding=self.table.encoding)
        except NameError as detail:
            # raise a nice message, suggesting that the user should use
            # data_columns
            raise ValueError(
                "The passed where expression: {0}\n"
                "            contains an invalid variable reference\n"
                "            all of the variable refrences must be a "
                "reference to\n"
                "            an axis (e.g. 'index' or 'columns'), or a "
                "data_column\n"
                "            The currently defined references are: {1}\n"
                .format(where, ','.join(q.keys()))
            )

    def select(self):
        """
        generate the selection
        """
        if self.condition is not None:
            return self.table.table.readWhere(self.condition.format(),
                                              start=self.start, stop=self.stop)
        elif self.coordinates is not None:
            return self.table.table.readCoordinates(self.coordinates)
        return self.table.table.read(start=self.start, stop=self.stop)

    def select_coords(self):
        """
        generate the selection
        """
        if self.condition is None:
            return np.arange(self.table.nrows)

        return self.table.table.getWhereList(self.condition.format(),
                                             start=self.start, stop=self.stop,
                                             sort=True)


# utilities ###

def timeit(key, df, fn=None, remove=True, **kwargs):
    if fn is None:
        fn = 'timeit.h5'
    store = HDFStore(fn, mode='w')
    store.append(key, df, **kwargs)
    store.close()

    if remove:
        os.remove(fn)