File: table.py

package info (click to toggle)
python-biom-format 2.1.7%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 51,820 kB
  • sloc: python: 12,757; makefile: 155; sh: 79
file content (5098 lines) | stat: -rw-r--r-- 180,787 bytes parent folder | download
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
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
BIOM Table (:mod:`biom.table`)
==============================

The biom-format project provides rich ``Table`` objects to support use of the
BIOM file format. The objects encapsulate matrix data (such as OTU counts) and
abstract the interaction away from the programmer.

.. currentmodule:: biom.table

Classes
-------

.. autosummary::
   :toctree: generated/

   Table

Examples
--------
First, lets create a toy table to play around with. For this example, we're
going to construct a 10x4 `Table`, or one that has 10 observations and 4
samples. Each observation and sample will be given an arbitrary but unique
name. We'll also add on some metadata.

>>> import numpy as np
>>> from biom.table import Table
>>> data = np.arange(40).reshape(10, 4)
>>> sample_ids = ['S%d' % i for i in range(4)]
>>> observ_ids = ['O%d' % i for i in range(10)]
>>> sample_metadata = [{'environment': 'A'}, {'environment': 'B'},
...                    {'environment': 'A'}, {'environment': 'B'}]
>>> observ_metadata = [{'taxonomy': ['Bacteria', 'Firmicutes']},
...                    {'taxonomy': ['Bacteria', 'Firmicutes']},
...                    {'taxonomy': ['Bacteria', 'Proteobacteria']},
...                    {'taxonomy': ['Bacteria', 'Proteobacteria']},
...                    {'taxonomy': ['Bacteria', 'Proteobacteria']},
...                    {'taxonomy': ['Bacteria', 'Bacteroidetes']},
...                    {'taxonomy': ['Bacteria', 'Bacteroidetes']},
...                    {'taxonomy': ['Bacteria', 'Firmicutes']},
...                    {'taxonomy': ['Bacteria', 'Firmicutes']},
...                    {'taxonomy': ['Bacteria', 'Firmicutes']}]
>>> table = Table(data, observ_ids, sample_ids, observ_metadata,
...               sample_metadata, table_id='Example Table')

Now that we have a table, let's explore it at a high level first.

>>> table
10 x 4 <class 'biom.table.Table'> with 39 nonzero entries (97% dense)
>>> print(table) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0  S1  S2  S3
O0  0.0 1.0 2.0 3.0
O1  4.0 5.0 6.0 7.0
O2  8.0 9.0 10.0    11.0
O3  12.0    13.0    14.0    15.0
O4  16.0    17.0    18.0    19.0
O5  20.0    21.0    22.0    23.0
O6  24.0    25.0    26.0    27.0
O7  28.0    29.0    30.0    31.0
O8  32.0    33.0    34.0    35.0
O9  36.0    37.0    38.0    39.0
>>> print(table.ids()) # doctest: +NORMALIZE_WHITESPACE
['S0' 'S1' 'S2' 'S3']
>>> print(table.ids(axis='observation')) # doctest: +NORMALIZE_WHITESPACE
['O0' 'O1' 'O2' 'O3' 'O4' 'O5' 'O6' 'O7' 'O8' 'O9']
>>> print(table.nnz)  # number of nonzero entries
39

While it's fun to just poke at the table, let's dig deeper. First, we're going
to convert `table` into relative abundances (within each sample), and then
filter `table` to just the samples associated with environment 'A'. The
filtering gets fancy: we can pass in an arbitrary function to determine what
samples we want to keep. This function must accept a sparse vector of values,
the corresponding ID and the corresponding metadata, and should return ``True``
or ``False``, where ``True`` indicates that the vector should be retained.

>>> normed = table.norm(axis='sample', inplace=False)
>>> filter_f = lambda values, id_, md: md['environment'] == 'A'
>>> env_a = normed.filter(filter_f, axis='sample', inplace=False)
>>> print(env_a) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0  S2
O0  0.0 0.01
O1  0.0222222222222 0.03
O2  0.0444444444444 0.05
O3  0.0666666666667 0.07
O4  0.0888888888889 0.09
O5  0.111111111111  0.11
O6  0.133333333333  0.13
O7  0.155555555556  0.15
O8  0.177777777778  0.17
O9  0.2 0.19

But, what if we wanted individual tables per environment? While we could just
perform some fancy iteration, we can instead just rely on `Table.partition` for
these operations. `partition`, like `filter`, accepts a function. However, the
`partition` method only passes the corresponding ID and metadata to the
function. The function should return what partition the data are a part of.
Within this example, we're also going to sum up our tables over the partitioned
samples. Please note that we're using the original table (ie, not normalized)
here.

>>> part_f = lambda id_, md: md['environment']
>>> env_tables = table.partition(part_f, axis='sample')
>>> for partition, env_table in env_tables:
...     print(partition, env_table.sum('sample'))
A [ 180.  200.]
B [ 190.  210.]

For this last example, and to highlight a bit more functionality, we're going
to first transform the table such that all multiples of three will be retained,
while all non-multiples of three will get set to zero. Following this, we'll
then collpase the table by taxonomy, and then convert the table into
presence/absence data.

First, let's setup the transform. We're going to define a function that takes
the modulus of every value in the vector, and see if it is equal to zero. If it
is equal to zero, we'll keep the value, otherwise we'll set the value to zero.

>>> transform_f = lambda v,i,m: np.where(v % 3 == 0, v, 0)
>>> mult_of_three = tform = table.transform(transform_f, inplace=False)
>>> print(mult_of_three) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0  S1  S2  S3
O0  0.0 0.0 0.0 3.0
O1  0.0 0.0 6.0 0.0
O2  0.0 9.0 0.0 0.0
O3  12.0    0.0 0.0 15.0
O4  0.0 0.0 18.0    0.0
O5  0.0 21.0    0.0 0.0
O6  24.0    0.0 0.0 27.0
O7  0.0 0.0 30.0    0.0
O8  0.0 33.0    0.0 0.0
O9  36.0    0.0 0.0 39.0

Next, we're going to collapse the table over the phylum level taxon. To do
this, we're going to define a helper variable for the index position of the
phylum (see the construction of the table above). Next, we're going to pass
this to `Table.collapse`, and since we want to collapse over the observations,
we'll need to specify 'observation' as the axis.

>>> phylum_idx = 1
>>> collapse_f = lambda id_, md: '; '.join(md['taxonomy'][:phylum_idx + 1])
>>> collapsed = mult_of_three.collapse(collapse_f, axis='observation')
>>> print(collapsed) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0  S1  S2  S3
Bacteria; Firmicutes  7.2 6.6 7.2 8.4
Bacteria; Proteobacteria  4.0 3.0 6.0 5.0
Bacteria; Bacteroidetes   12.0    10.5    0.0 13.5

Finally, let's convert the table to presence/absence data.

>>> pa = collapsed.pa()
>>> print(pa) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0  S1  S2  S3
Bacteria; Firmicutes  1.0 1.0 1.0 1.0
Bacteria; Proteobacteria  1.0 1.0 1.0 1.0
Bacteria; Bacteroidetes   1.0 1.0 0.0 1.0

"""

# -----------------------------------------------------------------------------
# Copyright (c) 2011-2017, The BIOM Format Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------------------------------------------------

from __future__ import division
import numpy as np
import scipy.stats
from copy import deepcopy
from datetime import datetime
from json import dumps
from functools import reduce
from operator import itemgetter
from future.builtins import zip
from future.utils import viewitems
from collections import defaultdict, Hashable, Iterable
from numpy import ndarray, asarray, zeros, newaxis
from scipy.sparse import (coo_matrix, csc_matrix, csr_matrix, isspmatrix,
                          vstack, hstack)
import pandas as pd

import six
from future.utils import string_types as _future_string_types
from biom.exception import (TableException, UnknownAxisError, UnknownIDError,
                            DisjointIDError)
from biom.util import (get_biom_format_version_string,
                       get_biom_format_url_string, flatten, natsort,
                       prefer_self, index_list, H5PY_VLEN_STR, HAVE_H5PY,
                       __format_version__)
from biom.err import errcheck
from ._filter import _filter
from ._transform import _transform
from ._subsample import _subsample


if not six.PY3:
    string_types = list(_future_string_types)
    string_types.append(str)
    string_types.append(unicode)  # noqa
    string_types = tuple(string_types)
else:
    string_types = _future_string_types


__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2011-2017, The BIOM Format Development Team"
__credits__ = ["Daniel McDonald", "Jai Ram Rideout", "Greg Caporaso",
               "Jose Clemente", "Justin Kuczynski", "Adam Robbins-Pianka",
               "Joshua Shorenstein", "Jose Antonio Navas Molina",
               "Jorge Cañardo Alastuey", "Steven Brown"]
__license__ = "BSD"
__url__ = "http://biom-format.org"
__maintainer__ = "Daniel McDonald"
__email__ = "daniel.mcdonald@colorado.edu"


MATRIX_ELEMENT_TYPE = {'int': int, 'float': float, 'unicode': str,
                       u'int': int, u'float': float, u'unicode': str}


def _identify_bad_value(dtype, fields):
    """Identify the first value which cannot be cast

    Paramters
    ---------
    dtype : type
        A type to cast to
    fields : Iterable of str
        A series of str to cast into dtype

    Returns
    -------
    str or None
        A value that cannot be cast
    int or None
        The index of the value that cannot be cast
    """
    badval = None
    badidx = None
    for idx, v in enumerate(fields):
        try:
            dtype(v)
        except:  # noqa
            badval = v
            badidx = idx
            break
    return (badval, badidx)


def general_parser(x):
    return x


def vlen_list_of_str_parser(value):
    """Parses the taxonomy value"""
    new_value = []
    for v in value:
        if v:
            if isinstance(v, bytes):
                v = v.decode('utf8')
            new_value.append(v)

    return new_value if new_value else None


def general_formatter(grp, header, md, compression):
    """Creates a dataset for a general atomic type category"""
    shape = (len(md),)
    name = 'metadata/%s' % header
    dtypes = [type(m[header]) for m in md]

    if set(dtypes).issubset(set(string_types)):
        grp.create_dataset(name, shape=shape,
                           dtype=H5PY_VLEN_STR,
                           data=[m[header].encode('utf8') for m in md],
                           compression=compression)
    elif set(dtypes).issubset({list, tuple}):
        vlen_list_of_str_formatter(grp, header, md, compression)
    else:
        formatted = []
        dtypes_used = []
        for dt, m in zip(dtypes, md):
            val = m[header]
            if val is None:
                val = '\0'
                dt = str

            if dt in string_types:
                val = val.encode('utf8')

            formatted.append(val)
            dtypes_used.append(dt)

        if set(dtypes_used).issubset(set(string_types)):
            dtype_to_use = H5PY_VLEN_STR
        else:
            dtype_to_use = None

        # try our best...
        grp.create_dataset(
            name, shape=(len(md),),
            dtype=dtype_to_use,
            data=formatted,
            compression=compression)


def vlen_list_of_str_formatter(grp, header, md, compression):
    """Creates a (N, ?) vlen str dataset"""
    # It is possible that the value for some sample/observation
    # is None. In that case, we still need to see them as
    # iterables, but their length will be 0
    iterable_checks = []
    lengths = []
    for m in md:
        if m[header] is None:
            iterable_checks.append(True)
        elif isinstance(m.get(header), str):
            iterable_checks.append(False)
        else:
            iterable_checks.append(
                isinstance(m.get(header, []), Iterable))
            lengths.append(len(m[header]))

    if not np.all(iterable_checks):
        if header == 'taxonomy':
            # attempt to handle the general case issue where the taxonomy
            # was not split on semicolons and represented as a flat string
            # instead of a list
            def split_and_strip(i):
                parts = i.split(';')
                return [p.strip() for p in parts]
            try:
                new_md = []
                lengths = []
                for m in md:
                    parts = split_and_strip(m[header])
                    new_md.append({header: parts})
                    lengths.append(len(parts))
                md = new_md
            except:  # noqa
                raise TypeError("Category '%s' is not formatted properly. The "
                                "most common issue is when 'taxonomy' is "
                                "represented as a flat string instead of a "
                                "list. An attempt was made to split this "
                                "field on a ';' to coerce it into a list but "
                                "it failed. An example entry (which is not "
                                "assured to be the problematic entry) is "
                                "below:\n%s" % (header, md[0][header]))
        else:
            raise TypeError(
                "Category %s not formatted correctly. Did you pass"
                " --process-obs-metadata taxonomy when converting "
                " from tsv? Please see Table.to_hdf5 docstring for"
                " more information" % header)

    max_list_len = max(lengths)
    shape = (len(md), max_list_len)
    data = np.empty(shape, dtype=object)
    for i, m in enumerate(md):
        if m[header] is None:
            continue
        value = np.asarray(m[header])
        data[i, :len(value)] = [v.encode('utf8') for v in value]
    # Change the None entries on data to empty strings ""
    data = np.where(data == np.array(None), "", data)
    grp.create_dataset(
        'metadata/%s' % header, shape=shape,
        dtype=H5PY_VLEN_STR, data=data,
        compression=compression)


class Table(object):

    """The (canonically pronounced 'teh') Table.

    Give in to the power of the Table!

    Creates an in-memory representation of a BIOM file. BIOM version 1.0 is
    based on JSON to provide the overall structure for the format while
    versions 2.0 and 2.1 are based on HDF5. For more information see [1]_
    and [2]_

    Paramaters
    ----------
    data : array_like
        An (N,M) sample by observation matrix represented as one of these
        types:
            An 1-dimensional array of values
            An n-dimensional array of values
            An empty list
            A list of numpy arrays
            A list of dict
            A list of sparse matrices
            A dictionary of values
            A list of lists
            A sparse matrix of values
    observation_ids : array_like of str
        A (N,) dataset of the observation IDs, where N is the total number
        of IDs
    sample_ids : array_like of str
        A (M,) dataset of the sample IDs, where M is the total number of IDs
    observation_metadata : list of dicts, optional
        per observation dictionary of annotations where every key represents a
        metadata field that contains specific metadata information,
        ie taxonomy, KEGG pathway, etc
    sample_metadata : array_like of dicts, optional
        per sample dictionary of annotations where every key represents a
        metadata field that contains sample specific metadata information, ie
    table_id : str, optional
        A field that can be used to identify the table
    type : {None, "OTU table", "Pathway table", "Function table",
            "Ortholog table", "Gene table", "Metabolite table", "Taxon table"}
        The type of table represented
    create_date : str, optional
        Date that this table was built
    generated_by : str, optional
        Individual who built the table
    observation_group_metadata : list, optional
        group that contains observation specific group metadata information
        (e.g., phylogenetic tree)
    sample_group_metadata : list, optional
        group that contains sample specific group metadata information
        (e.g., relationships between samples)

    Attributes
    ----------
    shape
    dtype
    nnz
    matrix_data
    type
    table_id
    create_date
    generated_by
    format_version

    Raises
    ------
    TableException
        When an invalid table type is provided.

    References
    ----------
    .. [1] http://biom-format.org/documentation/biom_format.html
    .. [2] D. McDonald, et al. "The Biological Observation Matrix (BIOM) format
       or: how I learned to stop worrying and love the ome-ome"
       GigaScience 2012 1:7
    """

    def __init__(self, data, observation_ids, sample_ids,
                 observation_metadata=None, sample_metadata=None,
                 table_id=None, type=None, create_date=None, generated_by=None,
                 observation_group_metadata=None, sample_group_metadata=None,
                 **kwargs):

        self.type = type
        self.table_id = table_id
        self.create_date = create_date
        self.generated_by = generated_by
        self.format_version = __format_version__

        if not isspmatrix(data):
            shape = (len(observation_ids), len(sample_ids))
            input_is_dense = kwargs.get('input_is_dense', False)
            self._data = Table._to_sparse(data, input_is_dense=input_is_dense,
                                          shape=shape)
        else:
            self._data = data.tocsr()

        self._data = self._data.astype(float)

        # using object to allow for variable length strings
        self._sample_ids = np.asarray(sample_ids, dtype=object)
        self._observation_ids = np.asarray(observation_ids, dtype=object)

        if sample_metadata is not None:
            # not m will evaluate True if the object tested is None or
            # an empty dict, etc.
            if {not m for m in sample_metadata} == {True, }:
                self._sample_metadata = None
            else:
                self._sample_metadata = tuple(sample_metadata)
        else:
            self._sample_metadata = None

        if observation_metadata is not None:
            # not m will evaluate True if the object tested is None or
            # an empty dict, etc.
            if {not m for m in observation_metadata} == {True, }:
                self._observation_metadata = None
            else:
                self._observation_metadata = tuple(observation_metadata)
        else:
            self._observation_metadata = None

        self._sample_group_metadata = sample_group_metadata
        self._observation_group_metadata = observation_group_metadata

        errcheck(self)

        # These will be set by _index_ids()
        self._sample_index = None
        self._obs_index = None

        self._cast_metadata()
        self._index_ids()

    def _index_ids(self):
        """Sets lookups {id:index in _data}.

        Should only be called in constructor as this modifies state.
        """
        self._sample_index = index_list(self._sample_ids)
        self._obs_index = index_list(self._observation_ids)

    def _index(self, axis='sample'):
        """Return the index lookups of the given axis

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            Axis to get the index dict. Defaults to 'sample'

        Returns
        -------
        dict
            lookups {id:index}

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.
        """
        if axis == 'sample':
            return self._sample_index
        elif axis == 'observation':
            return self._obs_index
        else:
            raise UnknownAxisError(axis)

    def _conv_to_self_type(self, vals, transpose=False, dtype=None):
        """For converting vectors to a compatible self type"""
        if dtype is None:
            dtype = self.dtype

        if isspmatrix(vals):
            return vals
        else:
            return Table._to_sparse(vals, transpose, dtype)

    @staticmethod
    def _to_dense(vec):
        """Converts a row/col vector to a dense numpy array.

        Always returns a 1-D row vector for consistency with numpy iteration
        over arrays.
        """
        dense_vec = vec.toarray()

        if vec.shape == (1, 1):
            # Handle the special case where we only have a single element, but
            # we don't want to return a numpy scalar / 0-d array. We still want
            # to return a vector of length 1.
            return dense_vec.reshape(1)
        else:
            return np.squeeze(dense_vec)

    @staticmethod
    def _to_sparse(values, transpose=False, dtype=float, input_is_dense=False,
                   shape=None):
        """Try to return a populated scipy.sparse matrix.

        NOTE: assumes the max value observed in row and col defines the size of
        the matrix.
        """
        # if it is a vector
        if isinstance(values, ndarray) and len(values.shape) == 1:
            if transpose:
                mat = nparray_to_sparse(values[:, newaxis], dtype)
            else:
                mat = nparray_to_sparse(values, dtype)
            return mat
        if isinstance(values, ndarray):
            if transpose:
                mat = nparray_to_sparse(values.T, dtype)
            else:
                mat = nparray_to_sparse(values, dtype)
            return mat
        # the empty list
        elif isinstance(values, list) and len(values) == 0:
            return coo_matrix((0, 0))
        # list of np vectors
        elif isinstance(values, list) and isinstance(values[0], ndarray):
            mat = list_nparray_to_sparse(values, dtype)
            if transpose:
                mat = mat.T
            return mat
        # list of dicts, each representing a row in row order
        elif isinstance(values, list) and isinstance(values[0], dict):
            mat = list_dict_to_sparse(values, dtype)
            if transpose:
                mat = mat.T
            return mat
        # list of scipy.sparse matrices, each representing a row in row order
        elif isinstance(values, list) and isspmatrix(values[0]):
            mat = list_sparse_to_sparse(values, dtype)
            if transpose:
                mat = mat.T
            return mat
        elif isinstance(values, dict):
            mat = dict_to_sparse(values, dtype, shape)
            if transpose:
                mat = mat.T
            return mat
        elif isinstance(values, list) and isinstance(values[0], list):
            if input_is_dense:
                d = coo_matrix(values)
                mat = coo_arrays_to_sparse((d.data, (d.row, d.col)),
                                           dtype=dtype, shape=shape)
            else:
                mat = list_list_to_sparse(values, dtype, shape=shape)
            return mat
        elif isspmatrix(values):
            mat = values
            if transpose:
                mat = mat.transpose()
            return mat
        else:
            raise TableException("Unknown input type")

    def _cast_metadata(self):
        """Casts all metadata to defaultdict to support default values.

        Should be called after any modifications to sample/observation
        metadata.
        """
        def cast_metadata(md):
            """Do the actual casting"""
            default_md = []
            # if we have a list of [None], set to None
            if md is not None:
                if md.count(None) == len(md):
                    return None
            if md is not None:
                for item in md:
                    d = defaultdict(lambda: None)

                    if isinstance(item, dict):
                        d.update(item)
                    elif item is None:
                        pass
                    else:
                        raise TableException("Unable to cast metadata: %s" %
                                             repr(item))
                    default_md.append(d)
                return tuple(default_md)
            return md

        self._sample_metadata = cast_metadata(self._sample_metadata)
        self._observation_metadata = cast_metadata(self._observation_metadata)

        self._sample_group_metadata = (
            self._sample_group_metadata
            if self._sample_group_metadata else None)
        self._observation_group_metadata = (
            self._observation_group_metadata
            if self._observation_group_metadata else None)

    @property
    def shape(self):
        """The shape of the underlying contingency matrix"""
        return self._data.shape

    @property
    def dtype(self):
        """The type of the objects in the underlying contingency matrix"""
        return self._data.dtype

    @property
    def nnz(self):
        """Number of non-zero elements of the underlying contingency matrix"""
        self._data.eliminate_zeros()
        return self._data.nnz

    @property
    def matrix_data(self):
        """The sparse matrix object"""
        return self._data

    def length(self, axis='sample'):
        """Return the length of an axis

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            The axis to operate on

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> from biom import example_table
        >>> print(example_table.length(axis='sample'))
        3
        >>> print(example_table.length(axis='observation'))
        2
        """
        if axis not in ('sample', 'observation'):
            raise UnknownAxisError(axis)

        return self.shape[1] if axis == 'sample' else self.shape[0]

    def add_group_metadata(self, group_md, axis='sample'):
        """Take a dict of group metadata and add it to an axis

        Parameters
        ----------
        group_md : dict of tuples
            `group_md` should be of the form ``{category: (data type, value)``
        axis : {'sample', 'observation'}, optional
            The axis to operate on

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.
        """
        if axis == 'sample':
            if self._sample_group_metadata is not None:
                self._sample_group_metadata.update(group_md)
            else:
                self._sample_group_metadata = group_md
        elif axis == 'observation':
            if self._observation_group_metadata is not None:
                self._observation_group_metadata.update(group_md)
            else:
                self._observation_group_metadata = group_md
        else:
            raise UnknownAxisError(axis)

    def del_metadata(self, keys=None, axis='whole'):
        """Remove metadata from an axis

        Parameters
        ----------
        keys : list of str, optional
            The keys to remove from metadata. If None, all keys from the axis
            are removed.
        axis : {'sample', 'observation', 'whole'}, optional
            The axis to operate on. If 'whole', the operation is applied to
            both the sample and observation axes.

        Raises
        ------
        UnknownAxisError
            If the requested axis does not exist.

        Examples
        --------
        >>> from biom import Table
        >>> import numpy as np
        >>> tab = Table(np.array([[1, 2], [3, 4]]),
        ...             ['O1', 'O2'],
        ...             ['S1', 'S2'],
        ...             sample_metadata=[{'barcode': 'ATGC', 'env': 'A'},
        ...                              {'barcode': 'GGTT', 'env': 'B'}])
        >>> tab.del_metadata(keys=['env'])
        >>> for id, md in zip(tab.ids(), tab.metadata()):
        ...     print(id, list(md.items()))
        S1 [('barcode', 'ATGC')]
        S2 [('barcode', 'GGTT')]
        """
        if axis == 'whole':
            axes = ['sample', 'observation']
        elif axis in ('sample', 'observation'):
            axes = [axis]
        else:
            raise UnknownAxisError("%s is not recognized" % axis)

        if keys is None:
            if axis == 'whole':
                self._sample_metadata = None
                self._observation_metadata = None
            elif axis == 'sample':
                self._sample_metadata = None
            else:
                self._observation_metadata = None
            return

        for ax in axes:
            if self.metadata(axis=ax) is None:
                continue

            for i, md in zip(self.ids(axis=ax), self.metadata(axis=ax)):
                for k in keys:
                    if k in md:
                        del md[k]

            # for consistency with init on absence of metadata
            empties = {True if not md else False
                       for md in self.metadata(axis=ax)}
            if empties == {True, }:
                if ax == 'sample':
                    self._sample_metadata = None
                else:
                    self._observation_metadata = None

    def add_metadata(self, md, axis='sample'):
        """Take a dict of metadata and add it to an axis.

        Parameters
        ----------
        md : dict of dict
            `md` should be of the form ``{id: {dict_of_metadata}}``
        axis : {'sample', 'observation'}, optional
            The axis to operate on
        """
        metadata = self.metadata(axis=axis)
        if metadata is not None:
            for id_, md_entry in viewitems(md):
                if self.exists(id_, axis=axis):
                    idx = self.index(id_, axis=axis)
                    metadata[idx].update(md_entry)
        else:
            ids = self.ids(axis=axis)
            if axis == 'sample':
                self._sample_metadata = tuple(
                    [md[id_] if id_ in md else None for id_ in ids])
            elif axis == 'observation':
                self._observation_metadata = tuple(
                    [md[id_] if id_ in md else None for id_ in ids])
            else:
                raise UnknownAxisError(axis)
        self._cast_metadata()

    def __getitem__(self, args):
        """Handles row or column slices

        Slicing over an individual axis is supported, but slicing over both
        axes at the same time is not supported. Partial slices, such as
        `foo[0, 5:10]` are not supported, however full slices are supported,
        such as `foo[0, :]`.

        Parameters
        ----------
        args : tuple or slice
            The specific element (by index position) to return or an entire
            row or column of the data.

        Returns
        -------
        float or spmatrix
            A float is return if a specific element is specified, otherwise a
            spmatrix object representing a vector of sparse data is returned.

        Raises
        ------
        IndexError
            - If the matrix is empty
            - If the arguments do not appear to be a tuple
            - If a slice on row and column is specified
            - If a partial slice is specified

        Notes
        -----
        Switching between slicing rows and columns is inefficient.  Slicing of
        rows requires a CSR representation, while slicing of columns requires a
        CSC representation, and transforms are performed on the data if the
        data are not in the required representation. These transforms can be
        expensive if done frequently.

        .. shownumpydoc
        """
        if self.is_empty():
            raise IndexError("Cannot retrieve an element from an empty/null "
                             "table.")

        try:
            row, col = args
        except:  # noqa
            raise IndexError("Must specify (row, col).")

        if isinstance(row, slice) and isinstance(col, slice):
            raise IndexError("Can only slice a single axis.")

        if isinstance(row, slice):
            if row.start is None and row.stop is None:
                return self._get_col(col)
            else:
                raise IndexError("Can only handle full : slices per axis.")
        elif isinstance(col, slice):
            if col.start is None and col.stop is None:
                return self._get_row(row)
            else:
                raise IndexError("Can only handle full : slices per axis.")
        else:
            if self._data.getformat() == 'coo':
                self._data = self._data.tocsr()

            return self._data[row, col]

    def _get_row(self, row_idx):
        """Return the row at ``row_idx``.

        A row vector will be returned as a scipy.sparse matrix in csr format.

        Notes
        -----
        Switching between slicing rows and columns is inefficient.  Slicing of
        rows requires a CSR representation, while slicing of columns requires a
        CSC representation, and transforms are performed on the data if the
        data are not in the required representation. These transforms can be
        expensive if done frequently.

        """
        self._data = self._data.tocsr()
        return self._data.getrow(row_idx)

    def _get_col(self, col_idx):
        """Return the column at ``col_idx``.

        A column vector will be returned as a scipy.sparse matrix in csc
        format.

        Notes
        -----
        Switching between slicing rows and columns is inefficient.  Slicing of
        rows requires a CSR representation, while slicing of columns requires a
        CSC representation, and transforms are performed on the data if the
        data are not in the required representation. These transforms can be
        expensive if done frequently.

        """
        self._data = self._data.tocsc()
        return self._data.getcol(col_idx)

    def reduce(self, f, axis):
        """Reduce over axis using function `f`

        Parameters
        ----------
        f : function
            The function to use for the reduce operation
        axis : {'sample', 'observation'}
            The axis on which to operate

        Returns
        -------
        numpy.array
            A one-dimensional array representing the reduced rows
            (observations) or columns (samples) of the data matrix

        Raises
        ------
        UnknownAxisError
            If `axis` is neither "sample" nor "observation"
        TableException
            If the table's data matrix is empty

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 table

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               [{'foo': 'bar'}, {'x': 'y'}], None)

        Create a reduce function

        >>> func = lambda x, y: x + y

        Reduce table on samples

        >>> table.reduce(func, 'sample') # doctest: +NORMALIZE_WHITESPACE
        array([  1.,   3.,  43.])

        Reduce table on observations

        >>> table.reduce(func, 'observation') # doctest: +NORMALIZE_WHITESPACE
        array([  1.,  46.])
        """
        if self.is_empty():
            raise TableException("Cannot reduce an empty table")

        # np.apply_along_axis might reduce type conversions here and improve
        # speed. am opting for reduce right now as I think its more readable
        return asarray([reduce(f, v) for v in self.iter_data(axis=axis)])

    def sum(self, axis='whole'):
        """Returns the sum by axis

        Parameters
        ----------
        axis : {'whole', 'sample', 'observation'}, optional
            The axis on which to operate.

        Returns
        -------
        numpy.array or float
            If `axis` is "whole", returns an float representing the whole
            table sum. If `axis` is either "sample" or "observation", returns a
            numpy.array that holds a sum for each sample or observation,
            respectively.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'])

        Add all values in the table:

        >>> table.sum()
        array(47.0)

        Add all values per sample:

        >>> table.sum(axis='sample') # doctest: +NORMALIZE_WHITESPACE
        array([  1.,  3.,  43.])

        Add all values per observation:

        >>> table.sum(axis='observation') # doctest: +NORMALIZE_WHITESPACE
        array([  1.,  46.])
        """
        if axis == 'whole':
            axis = None
        elif axis == 'sample':
            axis = 0
        elif axis == 'observation':
            axis = 1
        else:
            raise UnknownAxisError(axis)

        matrix_sum = np.squeeze(np.asarray(self._data.sum(axis=axis)))

        # We only want to return a scalar if the whole matrix was summed.
        if axis is not None and matrix_sum.shape == ():
            matrix_sum = matrix_sum.reshape(1)

        return matrix_sum

    def transpose(self):
        """Transpose the contingency table

        The returned table will be an entirely new table, including copies of
        the (transposed) data, sample/observation IDs and metadata.

        Returns
        -------
        Table
            Return a new table that is the transpose of caller table.
        """
        sample_md_copy = deepcopy(self.metadata())
        obs_md_copy = deepcopy(self.metadata(axis='observation'))

        if self._data.getformat() == 'lil':
            # lil's transpose method doesn't have the copy kwarg, but all of
            # the others do.
            self._data = self._data.tocsr()

        # sample ids and observations are reversed becuase we trasposed
        return self.__class__(self._data.transpose(copy=True),
                              self.ids()[:], self.ids(axis='observation')[:],
                              sample_md_copy, obs_md_copy, self.table_id)

    def head(self, n=5, m=5):
        """Get the first n rows and m columns from self

        Parameters
        ----------
        n : int, optional
            The number of rows (observations) to get. This number must be
            greater than 0. If not specified, 5 rows will be retrieved.

        m : int, optional
            The number of columns (samples) to get. This number must be
            greater than 0. If not specified, 5 columns will be
            retrieved.

        Notes
        -----
        Like `head` for Linux like systems, requesting more rows (or columns)
        than exists will silently work.

        Raises
        ------
        IndexError
            If `n` or `m` are <= 0.

        Returns
        -------
        Table
            The subset table.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table
        >>> data = np.arange(100).reshape(5, 20)
        >>> obs_ids = ['O%d' % i for i in range(1, 6)]
        >>> samp_ids = ['S%d' % i for i in range(1, 21)]
        >>> table = Table(data, obs_ids, samp_ids)
        >>> print(table.head())  # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3  S4  S5
        O1  0.0 1.0 2.0 3.0 4.0
        O2  20.0 21.0 22.0 23.0 24.0
        O3  40.0 41.0 42.0 43.0 44.0
        O4  60.0 61.0 62.0 63.0 64.0
        O5  80.0 81.0 82.0 83.0 84.0

        """
        if n <= 0:
            raise IndexError("n cannot be <= 0.")

        if m <= 0:
            raise IndexError("m cannot be <= 0.")

        row_ids = self.ids(axis='observation')[:n]
        col_ids = self.ids(axis='sample')[:m]

        table = self.filter(row_ids, axis='observation', inplace=False)
        return table.filter(col_ids, axis='sample')

    def group_metadata(self, axis='sample'):
        """Return the group metadata of the given axis

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            Axis to search for the group metadata. Defaults to 'sample'

        Returns
        -------
        dict
            The corresponding group metadata for the given axis

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table, with group observation metadata and no group
        sample metadata:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> group_observation_md = {'tree': ('newick', '(O1:0.3,O2:0.4);')}
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               observation_group_metadata=group_observation_md)

        Get the observation group metadata:

        >>> table.group_metadata(axis='observation')
        {'tree': ('newick', '(O1:0.3,O2:0.4);')}

        Get the sample group metadata:

        >> table.group_metadata()
        None
        """
        if axis == 'sample':
            return self._sample_group_metadata
        elif axis == 'observation':
            return self._observation_group_metadata
        else:
            raise UnknownAxisError(axis)

    def ids(self, axis='sample'):
        """Return the ids along the given axis

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            Axis to return ids from. Defaults to 'sample'

        Returns
        -------
        1-D numpy array
            The ids along the given axis

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'])

        Get the ids along the observation axis:

        >>> print(table.ids(axis='observation'))
        ['O1' 'O2']

        Get the ids along the sample axis:

        >>> print(table.ids())
        ['S1' 'S2' 'S3']
        """
        if axis == 'sample':
            return self._sample_ids
        elif axis == 'observation':
            return self._observation_ids
        else:
            raise UnknownAxisError(axis)

    def update_ids(self, id_map, axis='sample', strict=True, inplace=True):
        """Update the ids along the given axis

        Parameters
        ----------
        id_map : dict
            Mapping of old to new ids
        axis : {'sample', 'observation'}, optional
            Axis to search for `id`. Defaults to 'sample'
        strict : bool, optional
            If ``True``, raise an error if an id is present in the given axis
            but is not a key in ``id_map``. If False, retain old identifier
            for ids that are present in the given axis but are not keys in
            ``id_map``.
        inplace : bool, optional
            If ``True`` the ids are updated in ``self``; if ``False`` the ids
            are updated in a new table is returned.

        Returns
        -------
        Table
            Table object where ids have been updated.

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.
        TableException
            If an id from ``self`` is not in ``id_map`` and ``strict`` is
            ``True``.

        Examples
        --------
        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'])

        Define a mapping of old to new sample ids:

        >>> id_map = {'S1':'s1.1', 'S2':'s2.2', 'S3':'s3.3'}

        Get the ids along the sample axis in the table:

        >>> print(table.ids(axis='sample'))
        ['S1' 'S2' 'S3']

        Update the sample ids and get the ids along the sample axis in the
        updated table:

        >>> updated_table = table.update_ids(id_map, axis='sample')
        >>> print(updated_table.ids(axis='sample'))
        ['s1.1' 's2.2' 's3.3']
        """
        updated_ids = zeros(self.ids(axis=axis).size, dtype=object)
        for idx, old_id in enumerate(self.ids(axis=axis)):
            if strict and old_id not in id_map:
                raise TableException(
                    "Mapping not provided for %s identifier: %s. If this "
                    "identifier should not be updated, pass strict=False."
                    % (axis, old_id))

            updated_ids[idx] = id_map.get(old_id, old_id)

        # prepare the result object and update the ids along the specified
        # axis
        result = self if inplace else self.copy()
        if axis == 'sample':
            result._sample_ids = updated_ids
        else:
            result._observation_ids = updated_ids

        result._index_ids()

        # check for errors (specifically, we want to esnsure that duplicate
        # ids haven't been introduced)
        errcheck(result)

        return result

    def _get_sparse_data(self, axis='sample'):
        """Returns the internal data in the correct sparse representation

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            Axis to search for `id`. Defaults to 'sample'

        Returns
        -------
        sparse matrix
            The data in csc (axis='sample') or csr (axis='observation')
            representation
        """
        if axis == 'sample':
            return self._data.tocsc()
        elif axis == 'observation':
            return self._data.tocsr()
        else:
            raise UnknownAxisError(axis)

    def metadata(self, id=None, axis='sample'):
        """Return the metadata of the identified sample/observation.

        Parameters
        ----------
        id : str
            ID of the sample or observation whose index will be returned.
        axis : {'sample', 'observation'}
            Axis to search for `id`.

        Returns
        -------
        defaultdict or None
            The corresponding metadata ``defaultdict`` or ``None`` of that axis
            does not have metadata.

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.
        UnknownIDError
            If provided an unrecognized sample/observation ID.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table, with observation metadata and no sample
        metadata:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               [{'foo': 'bar'}, {'x': 'y'}], None)

        Get the metadata of the observation with ID "O2":

        >>> # casting to `dict` as the return is `defaultdict`
        >>> dict(table.metadata('O2', 'observation'))
        {'x': 'y'}

        Get the metadata of the sample with ID "S1":

        >>> table.metadata('S1', 'sample') is None
        True
        """
        if axis == 'sample':
            md = self._sample_metadata
        elif axis == 'observation':
            md = self._observation_metadata
        else:
            raise UnknownAxisError(axis)

        if id is None:
            return md

        idx = self.index(id, axis=axis)

        return md[idx] if md is not None else None

    def index(self, id, axis):
        """Return the index of the identified sample/observation.

        Parameters
        ----------
        id : str
            ID of the sample or observation whose index will be returned.
        axis : {'sample', 'observation'}
            Axis to search for `id`.

        Returns
        -------
        int
            Index of the sample/observation identified by `id`.

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.
        UnknownIDError
            If provided an unrecognized sample/observation ID.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'])

        Get the index of the observation with ID "O2":

        >>> table.index('O2', 'observation')
        1

        Get the index of the sample with ID "S1":

        >>> table.index('S1', 'sample')
        0
        """
        idx_lookup = self._index(axis=axis)

        if id not in idx_lookup:
            raise UnknownIDError(id, axis)

        return idx_lookup[id]

    def get_value_by_ids(self, obs_id, samp_id):
        """Return value in the matrix corresponding to ``(obs_id, samp_id)``

        Parameters
        ----------
        obs_id : str
            The ID of the observation
        samp_id : str
            The ID of the sample

        Returns
        -------
        float
            The data value corresponding to the specified matrix position

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'Z3'])

        Retrieve the number of counts for observation `O1` in sample `Z3`.

        >>> print(table.get_value_by_ids('O2', 'Z3'))
        42.0

        See Also
        --------
        Table.data
        """
        return self[self.index(obs_id, 'observation'),
                    self.index(samp_id, 'sample')]

    def __str__(self):
        """Stringify self

        Default str output for a Table is just row/col ids and data values
        """
        return self.delimited_self()

    def __repr__(self):
        """Returns a high-level summary of the table's properties

        Returns
        -------
        str
            A string detailing the shape, class, number of nonzero entries, and
            table density
        """
        rows, cols = self.shape
        return '%d x %d %s with %d nonzero entries (%d%% dense)' % (
            rows, cols, repr(self.__class__), self.nnz,
            self.get_table_density() * 100
        )

    def exists(self, id, axis="sample"):
        """Returns whether id exists in axis

        Parameters
        ----------
        id: str
            id to check if exists
        axis : {'sample', 'observation'}, optional
            The axis to check

        Returns
        -------
        bool
            ``True`` if `id` exists, ``False`` otherwise

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'])

        Check whether sample ID is in the table:

        >>> table.exists('S1')
        True
        >>> table.exists('S4')
        False

        Check whether an observation ID is in the table:

        >>> table.exists('O1', 'observation')
        True
        >>> table.exists('O3', 'observation')
        False
        """
        return id in self._index(axis=axis)

    def delimited_self(self, delim=u'\t', header_key=None, header_value=None,
                       metadata_formatter=str,
                       observation_column_name=u'#OTU ID'):
        """Return self as a string in a delimited form

        Default str output for the Table is just row/col ids and table data
        without any metadata

        Including observation metadata in output: If ``header_key`` is not
        ``None``, the observation metadata with that name will be included
        in the delimited output. If ``header_value`` is also not ``None``, the
        observation metadata will use the provided ``header_value`` as the
        observation metadata name (i.e., the column header) in the delimited
        output.

        ``metadata_formatter``: a function which takes a metadata entry and
        returns a formatted version that should be written to file

        ``observation_column_name``: the name of the first column in the output
        table, corresponding to the observation IDs. For example, the default
        will look something like:

            #OTU ID\tSample1\tSample2
            OTU1\t10\t2
            OTU2\t4\t8
        """
        def to_utf8(i):
            if isinstance(i, bytes):
                return i.decode('utf8')
            else:
                return str(i)

        if self.is_empty():
            raise TableException("Cannot delimit self if I don't have data...")

        samp_ids = delim.join([to_utf8(i) for i in self.ids()])
        # 17 hrs of straight programming later...
        if header_key is not None:
            if header_value is None:
                raise TableException(
                    "You need to specify both header_key and header_value")

        if header_value is not None:
            if header_key is None:
                raise TableException(
                    "You need to specify both header_key and header_value")

        if header_value:
            output = [u'# Constructed from biom file',
                      u'%s%s%s\t%s' % (observation_column_name, delim,
                                       samp_ids, header_value)]
        else:
            output = ['# Constructed from biom file',
                      '%s%s%s' % (observation_column_name, delim, samp_ids)]
        obs_metadata = self.metadata(axis='observation')
        for obs_id, obs_values in zip(self.ids(axis='observation'),
                                      self._iter_obs()):
            str_obs_vals = delim.join(map(str, self._to_dense(obs_values)))

            obs_id = to_utf8(obs_id)
            if header_key and obs_metadata is not None:
                md = obs_metadata[self._obs_index[obs_id]]
                md_out = metadata_formatter(md.get(header_key, None))
                output.append(
                    u'%s%s%s\t%s' %
                    (obs_id, delim, str_obs_vals, md_out))
            else:
                output.append(u'%s%s%s' % (obs_id, delim, str_obs_vals))

        return '\n'.join(output)

    def is_empty(self):
        """Check whether the table is empty

        Returns
        -------
        bool
            ``True`` if the table is empty, ``False`` otherwise
        """
        if not self.ids().size or not self.ids(axis='observation').size:
            return True
        else:
            return False

    def __iter__(self):
        """See ``biom.table.Table.iter``"""
        return self.iter()

    def _iter_samp(self):
        """Return sample vectors of data matrix vectors"""
        for c in range(self.shape[1]):
            # this pulls out col vectors but need to convert to the expected
            # row vector
            colvec = self._get_col(c)
            yield colvec.transpose(copy=True)

    def _iter_obs(self):
        """Return observation vectors of data matrix"""
        for r in range(self.shape[0]):
            yield self._get_row(r)

    def get_table_density(self):
        """Returns the fraction of nonzero elements in the table.

        Returns
        -------
        float
            The fraction of nonzero elements in the table
        """
        density = 0.0

        if not self.is_empty():
            density = (self.nnz /
                       (len(self.ids()) * len(self.ids(axis='observation'))))

        return density

    def descriptive_equality(self, other):
        """For use in testing, describe how the tables are not equal"""
        if not isinstance(other, self.__class__):
            return "Tables are not of comparable classes"
        if not self.type == other.type:
            return "Tables are not the same type"
        if not np.array_equal(self.ids(axis='observation'),
                              other.ids(axis='observation')):
            return "Observation IDs are not the same"
        if not np.array_equal(self.ids(), other.ids()):
            return "Sample IDs are not the same"
        if not np.array_equal(self.metadata(axis='observation'),
                              other.metadata(axis='observation')):
            return "Observation metadata are not the same"
        if not np.array_equal(self.metadata(), other.metadata()):
            return "Sample metadata are not the same"
        if not self._data_equality(other._data):
            return "Data elements are not the same"

        return "Tables appear equal"

    def __eq__(self, other):
        """Equality is determined by the data matrix, metadata, and IDs"""
        if not isinstance(other, self.__class__):
            return False
        if self.type != other.type:
            return False
        if not np.array_equal(self.ids(axis='observation'),
                              other.ids(axis='observation')):
            return False
        if not np.array_equal(self.ids(), other.ids()):
            return False
        if not np.array_equal(self.metadata(axis='observation'),
                              other.metadata(axis='observation')):
            return False
        if not np.array_equal(self.metadata(), other.metadata()):
            return False
        if not self._data_equality(other._data):
            return False

        return True

    def _data_equality(self, other):
        """Return ``True`` if both matrices are equal.

        Matrices are equal iff the following items are equal:
        - shape
        - dtype
        - size (nnz)
        - matrix data (more expensive, so checked last)

        The sparse format does not need to be the same between the two
        matrices. ``self`` and ``other`` will be converted to csr format if
        necessary before performing the final comparison.

        """
        if self._data.shape != other.shape:
            return False

        if self._data.dtype != other.dtype:
            return False

        if self._data.nnz != other.nnz:
            return False

        self._data = self._data.tocsr()
        other = other.tocsr()

        if (self._data != other).nnz > 0:
            return False

        return True

    def __ne__(self, other):
        return not (self == other)

    def data(self, id, axis='sample', dense=True):
        """Returns data associated with an `id`

        Parameters
        ----------
        id : str
            ID of the sample or observation whose data will be returned.
        axis : {'sample', 'observation'}
            Axis to search for `id`.
        dense : bool, optional
            If ``True``, return data as dense

        Returns
        -------
        np.ndarray or scipy.sparse.spmatrix
            np.ndarray if ``dense``, otherwise scipy.sparse.spmatrix

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> from biom import example_table
        >>> example_table.data('S1', axis='sample')
        array([ 0.,  3.])

        See Also
        --------
        Table.get_value_by_ids

        """
        if axis == 'sample':
            data = self[:, self.index(id, 'sample')]
        elif axis == 'observation':
            data = self[self.index(id, 'observation'), :]
        else:
            raise UnknownAxisError(axis)

        if dense:
            return self._to_dense(data)
        else:
            return data

    def copy(self):
        """Returns a copy of the table"""
        return self.__class__(self._data.copy(),
                              self.ids(axis='observation').copy(),
                              self.ids().copy(),
                              deepcopy(self.metadata(axis='observation')),
                              deepcopy(self.metadata()),
                              self.table_id,
                              type=self.type)

    def iter_data(self, dense=True, axis='sample'):
        """Yields axis values

        Parameters
        ----------
        dense : bool, optional
            Defaults to ``True``. If ``False``, yield compressed sparse row or
            compressed sparse columns if `axis` is 'observation' or 'sample',
            respectively.
        axis : {'sample', 'observation'}, optional
            Axis to iterate over.

        Returns
        -------
        generator
            Yields list of values for each value in `axis`

        Raises
        ------
        UnknownAxisError
            If axis other than 'sample' or 'observation' passed

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table
        >>> data = np.arange(30).reshape(3,10) # 3 X 10 OTU X Sample table
        >>> obs_ids = ['o1', 'o2', 'o3']
        >>> sam_ids = ['s%i' %i for i in range(1,11)]
        >>> bt = Table(data, observation_ids=obs_ids, sample_ids=sam_ids)

        Lets find the sample with the largest sum

        >>> sample_gen = bt.iter_data(axis='sample')
        >>> max_sample_count = max([sample.sum() for sample in sample_gen])
        >>> print(max_sample_count)
        57.0
        """
        if axis == "sample":
            for samp_v in self._iter_samp():
                if dense:
                    yield self._to_dense(samp_v)
                else:
                    yield samp_v
        elif axis == "observation":
            for obs_v in self._iter_obs():
                if dense:
                    yield self._to_dense(obs_v)
                else:
                    yield obs_v
        else:
            raise UnknownAxisError(axis)

    def iter(self, dense=True, axis='sample'):
        """Yields ``(value, id, metadata)``


        Parameters
        ----------
        dense : bool, optional
            Defaults to ``True``. If ``False``, yield compressed sparse row or
            compressed sparse columns if `axis` is 'observation' or 'sample',
            respectively.
        axis : {'sample', 'observation'}, optional
            The axis to iterate over.

        Returns
        -------
        GeneratorType
            A generator that yields (values, id, metadata)

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'Z3'])

        Iter over samples and keep those that start with an Z:

        >>> [(values, id, metadata)
        ...     for values, id, metadata in table.iter() if id[0]=='Z']
        [(array([  1.,  42.]), 'Z3', None)]

        Iter over observations and add the 2nd column of the values

        >>> col = [values[1] for values, id, metadata in table.iter()]
        >>> sum(col)
        46.0
        """
        ids = self.ids(axis=axis)
        metadata = self.metadata(axis=axis)
        if axis == 'sample':
            iter_ = self._iter_samp()
        elif axis == 'observation':
            iter_ = self._iter_obs()
        else:
            raise UnknownAxisError(axis)

        if metadata is None:
            metadata = (None,) * len(ids)

        iter_ = self.iter_data(axis=axis, dense=dense)

        return zip(iter_, ids, metadata)

    def iter_pairwise(self, dense=True, axis='sample', tri=True, diag=False):
        """Pairwise iteration over self

        Parameters
        ----------
        dense : bool, optional
            Defaults to ``True``. If ``False``, yield compressed sparse row or
            compressed sparse columns if `axis` is 'observation' or 'sample',
            respectively.
        axis : {'sample', 'observation'}, optional
            The axis to iterate over.
        tri : bool, optional
            If ``True``, just yield [i, j] and not [j, i]
        diag : bool, optional
            If ``True``, yield [i, i]

        Returns
        -------
        GeneratorType
            Yields [(val_i, id_i, metadata_i), (val_j, id_j, metadata_j)]

        Raises
        ------
        UnknownAxisError

        Examples
        --------
        >>> from biom import example_table

        By default, only the upper triangle without the diagonal  of the
        resulting pairwise combinations is yielded.

        >>> iter_ = example_table.iter_pairwise()
        >>> for (val_i, id_i, md_i), (val_j, id_j, md_j) in iter_:
        ...     print(id_i, id_j)
        S1 S2
        S1 S3
        S2 S3

        The full pairwise combinations can also be yielded though.

        >>> iter_ = example_table.iter_pairwise(tri=False, diag=True)
        >>> for (val_i, id_i, md_i), (val_j, id_j, md_j) in iter_:
        ...     print(id_i, id_j)
        S1 S1
        S1 S2
        S1 S3
        S2 S1
        S2 S2
        S2 S3
        S3 S1
        S3 S2
        S3 S3

        """
        metadata = self.metadata(axis=axis)
        ids = self.ids(axis=axis)

        if metadata is None:
            metadata = (None,) * len(ids)

        ind = np.arange(len(ids))
        diag_v = 1 - diag  # for offseting tri_f, where a 0 includes the diag

        if tri:
            def tri_f(idx):
                return ind[idx+diag_v:]
        else:
            def tri_f(idx):
                return np.hstack([ind[:idx], ind[idx+diag_v:]])

        for idx, i in enumerate(ind):
            id_i = ids[i]
            md_i = metadata[i]
            data_i = self.data(id_i, axis=axis, dense=dense)

            for j in tri_f(idx):
                id_j = ids[j]
                md_j = metadata[j]
                data_j = self.data(id_j, axis=axis, dense=dense)

                yield ((data_i, id_i, md_i), (data_j, id_j, md_j))

    def sort_order(self, order, axis='sample'):
        """Return a new table with `axis` in `order`

        Parameters
        ----------
        order : iterable
            The desired order for axis
        axis : {'sample', 'observation'}, optional
            The axis to operate on

        Returns
        -------
        Table
            A table where the observations or samples are sorted according to
            `order`

        Examples
        --------

        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[1, 0, 4], [1, 3, 0]])
        >>> table = Table(data, ['O2', 'O1'], ['S2', 'S1', 'S3'])
        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S2  S1  S3
        O2  1.0 0.0 4.0
        O1  1.0 3.0 0.0

        Sort the table using a list of samples:

        >>> sorted_table = table.sort_order(['S2', 'S3', 'S1'])
        >>> print(sorted_table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	S2	S3	S1
        O2	1.0	4.0	0.0
        O1	1.0	0.0	3.0


        Additionally you could sort the table's observations:

        >>> sorted_table = table.sort_order(['O1', 'O2'], axis="observation")
        >>> print(sorted_table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	S2	S1	S3
        O1	1.0	3.0	0.0
        O2	1.0	0.0	4.0

        """
        fancy = np.array([self.index(i, axis=axis) for i in order], dtype=int)
        metadata = self.metadata(axis=axis)
        if metadata is not None:
            metadata = np.array(metadata)[fancy]

        if axis == 'sample':
            mat = self.matrix_data[:, fancy]
            return self.__class__(mat,
                                  self.ids(axis='observation')[:], order[:],
                                  self.metadata(axis='observation'), metadata,
                                  self.table_id, self.type)

        elif axis == 'observation':
            mat = self.matrix_data[fancy, :]
            return self.__class__(mat,
                                  order[:], self.ids()[:],
                                  metadata, self.metadata(), self.table_id,
                                  self.type)
        else:
            raise UnknownAxisError(axis)

    def sort(self, sort_f=natsort, axis='sample'):
        """Return a table sorted along axis

        Parameters
        ----------
        sort_f : function, optional
            Defaults to ``biom.util.natsort``. A function that takes a list of
            values and sorts it
        axis : {'sample', 'observation'}, optional
            The axis to operate on

        Returns
        -------
        biom.Table
            A table whose samples or observations are sorted according to the
            `sort_f` function

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table:

        >>> data = np.asarray([[1, 0, 4], [1, 3, 0]])
        >>> table = Table(data, ['O2', 'O1'], ['S2', 'S1', 'S3'])
        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S2  S1  S3
        O2  1.0 0.0 4.0
        O1  1.0 3.0 0.0

        Sort the order of samples in the table using the default natural
        sorting:

        >>> new_table = table.sort()
        >>> print(new_table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3
        O2  0.0 1.0 4.0
        O1  3.0 1.0 0.0

        Sort the order of observations in the table using the default natural
        sorting:

        >>> new_table = table.sort(axis='observation')
        >>> print(new_table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S2  S1  S3
        O1  1.0 3.0 0.0
        O2  1.0 0.0 4.0

        Sort the samples in reverse order using a custom sort function:

        >>> sort_f = lambda x: list(sorted(x, reverse=True))
        >>> new_table = table.sort(sort_f=sort_f)
        >>> print(new_table)  # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S3  S2  S1
        O2  4.0 1.0 0.0
        O1  0.0 1.0 3.0
        """
        return self.sort_order(sort_f(self.ids(axis=axis)), axis=axis)

    def filter(self, ids_to_keep, axis='sample', invert=False, inplace=True):
        """Filter a table based on a function or iterable.

        Parameters
        ----------
        ids_to_keep : iterable, or function(values, id, metadata) -> bool
            If a function, it will be called with the values of the
            sample/observation, its id (a string) and the dictionary
            of metadata of each sample/observation, and must return a
            boolean. If it's an iterable, it must be a list of ids to
            keep.
        axis : {'sample', 'observation'}, optional
            It controls whether to filter samples or observations and
            defaults to "sample".
        invert : bool, optional
            Defaults to ``False``. If set to ``True``, discard samples or
            observations where `ids_to_keep` returns True
        inplace : bool, optional
            Defaults to ``True``. Whether to return a new table or modify
            itself.

        Returns
        -------
        biom.Table
            Returns itself if `inplace`, else returns a new filtered table.

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table, with observation metadata and sample
        metadata:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               [{'full_genome_available': True},
        ...                {'full_genome_available': False}],
        ...               [{'sample_type': 'a'}, {'sample_type': 'a'},
        ...                {'sample_type': 'b'}])

        Define a function to keep only samples with sample_type == 'a'. This
        will drop sample S3, which has sample_type 'b':

        >>> filter_fn = lambda val, id_, md: md['sample_type'] == 'a'

        Get a filtered version of the table, leaving the original table
        untouched:

        >>> new_table = table.filter(filter_fn, inplace=False)
        >>> print(table.ids())
        ['S1' 'S2' 'S3']
        >>> print(new_table.ids())
        ['S1' 'S2']

        Using the same filtering function, discard all samples with sample_type
        'a'. This will keep only sample S3, which has sample_type 'b':

        >>> new_table = table.filter(filter_fn, inplace=False, invert=True)
        >>> print(table.ids())
        ['S1' 'S2' 'S3']
        >>> print(new_table.ids())
        ['S3']

        Filter the table in-place using the same function (drop all samples
        where sample_type is not 'a'):

        >>> table.filter(filter_fn)
        2 x 2 <class 'biom.table.Table'> with 2 nonzero entries (50% dense)
        >>> print(table.ids())
        ['S1' 'S2']

        Filter out all observations in the table that do not have
        full_genome_available == True. This will filter out observation O2:

        >>> filter_fn = lambda val, id_, md: md['full_genome_available']
        >>> table.filter(filter_fn, axis='observation')
        1 x 2 <class 'biom.table.Table'> with 0 nonzero entries (0% dense)
        >>> print(table.ids(axis='observation'))
        ['O1']

        """
        table = self if inplace else self.copy()

        metadata = table.metadata(axis=axis)
        ids = table.ids(axis=axis)
        index = self._index(axis=axis)
        axis = table._axis_to_num(axis=axis)

        arr = table._data
        arr, ids, metadata = _filter(arr,
                                     ids,
                                     metadata,
                                     index,
                                     ids_to_keep,
                                     axis,
                                     invert=invert)

        table._data = arr
        if axis == 1:
            table._sample_ids = ids
            table._sample_metadata = metadata
        elif axis == 0:
            table._observation_ids = ids
            table._observation_metadata = metadata

        table._index_ids()
        errcheck(table)

        return table

    def partition(self, f, axis='sample'):
        """Yields partitions

        Parameters
        ----------
        f : function
            `f` is given the ID and metadata of the vector and must return
            what partition the vector is part of.
        axis : {'sample', 'observation'}, optional
            The axis to iterate over

        Returns
        -------
        GeneratorType
            A generator that yields (partition, `Table`)

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table
        >>> from biom.util import unzip

        Create a 2x3 BIOM table, with observation metadata and sample
        metadata:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               [{'full_genome_available': True},
        ...                {'full_genome_available': False}],
        ...               [{'sample_type': 'a'}, {'sample_type': 'a'},
        ...                {'sample_type': 'b'}])

        Define a function to bin by sample_type

        >>> f = lambda id_, md: md['sample_type']

        Partition the table and view results

        >>> bins, tables = table.partition(f)
        >>> print(bins[1]) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2
        O1  0.0 0.0
        O2  1.0 3.0
        >>> print(tables[1]) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S3
        O1  1.0
        O2  42.0
        """
        partitions = {}
        # conversion of vector types is not necessary, vectors are not
        # being passed to an arbitrary function
        for vals, id_, md in self.iter(dense=False, axis=axis):
            part = f(id_, md)

            # try to make it hashable...
            if not isinstance(part, Hashable):
                part = tuple(part)

            if part not in partitions:
                partitions[part] = [[], [], []]

            partitions[part][0].append(id_)
            partitions[part][1].append(vals)
            partitions[part][2].append(md)

        md = self.metadata(axis=self._invert_axis(axis))

        for part, (ids, values, metadata) in viewitems(partitions):
            if axis == 'sample':
                data = self._conv_to_self_type(values, transpose=True)
                samp_ids = ids
                samp_md = metadata
                obs_ids = self.ids(axis='observation')[:]
                obs_md = md[:] if md is not None else None

            elif axis == 'observation':
                data = self._conv_to_self_type(values, transpose=False)
                obs_ids = ids
                obs_md = metadata
                samp_ids = self.ids()[:]
                samp_md = md[:] if md is not None else None

            yield part, Table(data, obs_ids, samp_ids, obs_md, samp_md,
                              self.table_id, type=self.type)

    def collapse(self, f, collapse_f=None, norm=True, min_group_size=1,
                 include_collapsed_metadata=True, one_to_many=False,
                 one_to_many_mode='add', one_to_many_md_key='Path',
                 strict=False, axis='sample'):
        """Collapse partitions in a table by metadata or by IDs

        Partition data by metadata or IDs and then collapse each partition into
        a single vector.

        If `include_collapsed_metadata` is ``True``, the metadata for the
        collapsed partition will be a category named 'collapsed_ids', in which
        a list of the original ids that made up the partition is retained

        The remainder is only relevant to setting `one_to_many` to ``True``.

        If `one_to_many` is ``True``, allow vectors to collapse into multiple
        bins if the metadata describe a one-many relationship. Supplied
        functions must allow for iteration support over the metadata key and
        must return a tuple of (path, bin) as to describe both the path in the
        hierarchy represented and the specific bin being collapsed into. The
        uniqueness of the bin is _not_ based on the path but by the name of the
        bin.

        The metadata value for the corresponding collapsed column may include
        more (or less) information about the collapsed data. For example, if
        collapsing "FOO", and there are vectors that span three associations A,
        B, and C, such that vector 1 spans A and B, vector 2 spans B and C and
        vector 3 spans A and C, the resulting table will contain three
        collapsed vectors:

        - A, containing original vectors 1 and 3
        - B, containing original vectors 1 and 2
        - C, containing original vectors 2 and 3

        If a vector maps to the same partition multiple times, it will be
        counted multiple times.

        There are two supported modes for handling one-to-many relationships
        via `one_to_many_mode`: ``add`` and `divide`. ``add`` will add the
        vector counts to each partition that the vector maps to, which may
        increase the total number of counts in the output table. ``divide``
        will divide a vectors's counts by the number of metadata that the
        vector has before adding the counts to each partition. This will not
        increase the total number of counts in the output table.

        If `one_to_many_md_key` is specified, that becomes the metadata
        key that describes the collapsed path. If a value is not specified,
        then it defaults to 'Path'.

        If `strict` is specified, then all metadata pathways operated on
        must be indexable by `metadata_f`.

        `one_to_many` and `norm` are not supported together.

        `one_to_many` and `collapse_f` are not supported together.

        `one_to_many` and `min_group_size` are not supported together.

        A final note on space consumption. At present, the `one_to_many`
        functionality requires a temporary dense matrix representation.

        Parameters
        ----------
        f : function
            Function that is used to determine what partition a vector belongs
            to
        collapse_f : function, optional
            Function that collapses a partition in a one-to-one collapse. The
            expected function signature is:

                dense or sparse_vector <- collapse_f(Table, axis)

            Defaults to a pairwise add.

        norm : bool, optional
            Defaults to ``True``. If ``True``, normalize the resulting table
        min_group_size : int, optional
            Defaults to ``1``. The minimum size of a partition when performing
            a one-to-one collapse
        include_collapsed_metadata : bool, optional
            Defaults to ``True``. If ``True``, retain the collapsed metadata
            keyed by the original IDs of the associated vectors
        one_to_many : bool, optional
            Defaults to ``False``. Perform a one-to-many collapse
        one_to_many_mode : {'add', 'divide'}, optional
            The way to reduce two vectors in a one-to-many collapse
        one_to_many_md_key : str, optional
            Defaults to "Path". If `include_collapsed_metadata` is ``True``,
            store the original vector metadata under this key
        strict : bool, optional
            Defaults to ``False``. Requires full pathway data within a
            one-to-many structure
        axis : {'sample', 'observation'}, optional
            The axis to collapse

        Returns
        -------
        Table
            The collapsed table

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a ``Table``

        >>> dt_rich = Table(
        ...    np.array([[5, 6, 7], [8, 9, 10], [11, 12, 13]]),
        ...    ['1', '2', '3'], ['a', 'b', 'c'],
        ...    [{'taxonomy': ['k__a', 'p__b']},
        ...     {'taxonomy': ['k__a', 'p__c']},
        ...     {'taxonomy': ['k__a', 'p__c']}],
        ...    [{'barcode': 'aatt'},
        ...     {'barcode': 'ttgg'},
        ...     {'barcode': 'aatt'}])
        >>> print(dt_rich) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID a   b   c
        1   5.0 6.0 7.0
        2   8.0 9.0 10.0
        3   11.0    12.0    13.0

        Create Function to determine what partition a vector belongs to

        >>> bin_f = lambda id_, x: x['taxonomy'][1]
        >>> obs_phy = dt_rich.collapse(
        ...    bin_f, norm=False, min_group_size=1,
        ...    axis='observation').sort(axis='observation')
        >>> print(obs_phy) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID a   b   c
        p__b    5.0 6.0 7.0
        p__c    19.0    21.0    23.0
        """
        collapsed_data = []
        collapsed_ids = []

        if include_collapsed_metadata:
            collapsed_md = []
        else:
            collapsed_md = None

        if one_to_many_mode not in ['add', 'divide']:
            raise ValueError("Unrecognized one-to-many mode '%s'. Must be "
                             "either 'add' or 'divide'." % one_to_many_mode)

        # transpose is only necessary in the one-to-one case
        # new_data_shape is only necessary in the one-to-many case
        # axis_slice is only necessary in the one-to-many case
        def axis_ids_md(t):
            return (t.ids(axis=axis), t.metadata(axis=axis))

        if axis == 'sample':
            transpose = True

            def new_data_shape(ids, collapsed):
                return (len(ids), len(collapsed))

            def axis_slice(lookup, key):
                return (slice(None), lookup[key])

        elif axis == 'observation':
            transpose = False

            def new_data_shape(ids, collapsed):
                return (len(collapsed), len(ids))

            def axis_slice(lookup, key):
                return (lookup[key], slice(None))

        else:
            raise UnknownAxisError(axis)

        if one_to_many:
            if norm:
                raise AttributeError(
                    "norm and one_to_many are not supported together")

            # determine the collapsed pathway
            # we drop all other associated metadata
            new_md = {}
            md_count = {}

            for id_, md in zip(*axis_ids_md(self)):
                md_iter = f(id_, md)
                num_md = 0
                while True:
                    try:
                        pathway, partition = next(md_iter)
                    except IndexError:
                        # if a pathway is incomplete
                        if strict:
                            # bail if strict
                            err = "Incomplete pathway, ID: %s, metadata: %s" %\
                                  (id_, md)
                            raise IndexError(err)
                        else:
                            # otherwise ignore
                            continue
                    except StopIteration:
                        break

                    new_md[partition] = pathway
                    num_md += 1

                md_count[id_] = num_md

            idx_lookup = {part: i for i, part in enumerate(sorted(new_md))}

            # We need to store floats, not ints, as things won't always divide
            # evenly.
            dtype = float if one_to_many_mode == 'divide' else self.dtype

            new_data = zeros(new_data_shape(self.ids(self._invert_axis(axis)),
                                            new_md),
                             dtype=dtype)

            # for each vector
            # for each bin in the metadata
            # for each partition associated with the vector
            for vals, id_, md in self.iter(axis=axis):
                md_iter = f(id_, md)

                while True:
                    try:
                        pathway, part = next(md_iter)
                    except IndexError:
                        # if a pathway is incomplete
                        if strict:
                            # bail if strict, should never get here...
                            err = "Incomplete pathway, ID: %s, metadata: %s" %\
                                  (id_, md)
                            raise IndexError(err)
                        else:
                            # otherwise ignore
                            continue
                    except StopIteration:
                        break
                    if one_to_many_mode == 'add':
                        new_data[axis_slice(idx_lookup, part)] += vals
                    else:
                        new_data[axis_slice(idx_lookup, part)] += \
                            vals / md_count[id_]

            if include_collapsed_metadata:
                # reassociate pathway information
                for k, i in sorted(viewitems(idx_lookup), key=itemgetter(1)):
                    collapsed_md.append({one_to_many_md_key: new_md[k]})

            # get the new sample IDs
            collapsed_ids = [k for k, i in sorted(viewitems(idx_lookup),
                                                  key=itemgetter(1))]

            # convert back to self type
            data = self._conv_to_self_type(new_data)
        else:
            if collapse_f is None:
                def collapse_f(t, axis):
                    return t.sum(axis)

            for part, table in self.partition(f, axis=axis):
                axis_ids, axis_md = axis_ids_md(table)

                if len(axis_ids) < min_group_size:
                    continue

                redux_data = collapse_f(table, self._invert_axis(axis))
                if norm:
                    redux_data /= len(axis_ids)

                collapsed_data.append(self._conv_to_self_type(redux_data))
                collapsed_ids.append(part)

                if include_collapsed_metadata:
                    # retain metadata but store by original id
                    collapsed_md.append({'collapsed_ids': axis_ids.tolist()})

            data = self._conv_to_self_type(collapsed_data, transpose=transpose)

        # if the table is empty
        errcheck(self, 'empty')

        md = self.metadata(axis=self._invert_axis(axis))
        if axis == 'sample':
            sample_ids = collapsed_ids
            sample_md = collapsed_md
            obs_ids = self.ids(axis='observation')[:]
            obs_md = md if md is not None else None
        else:
            sample_ids = self.ids()[:]
            obs_ids = collapsed_ids
            obs_md = collapsed_md
            sample_md = md if md is not None else None

        return Table(data, obs_ids, sample_ids, obs_md, sample_md,
                     self.table_id, type=self.type)

    def _invert_axis(self, axis):
        """Invert an axis"""
        if axis == 'sample':
            return 'observation'
        elif axis == 'observation':
            return 'sample'
        else:
            return UnknownAxisError(axis)

    def _axis_to_num(self, axis):
        """Convert str axis to numerical axis"""
        if axis == 'sample':
            return 1
        elif axis == 'observation':
            return 0
        else:
            raise UnknownAxisError(axis)

    def min(self, axis='sample'):
        """Get the minimum nonzero value over an axis

        Parameters
        ----------
        axis : {'sample', 'observation', 'whole'}, optional
            Defaults to "sample". The axis over which to calculate minima.

        Returns
        -------
        scalar of self.dtype or np.array of self.dtype

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> from biom import example_table
        >>> print(example_table.min(axis='sample'))
        [ 3.  1.  2.]

        """
        if axis not in ['sample', 'observation', 'whole']:
            raise UnknownAxisError(axis)

        if axis == 'whole':
            min_val = np.inf
            for data in self.iter_data(dense=False):
                # only min over the actual nonzero values
                min_val = min(min_val, data.data.min())
        else:
            min_val = zeros(len(self.ids(axis=axis)), dtype=self.dtype)

            for idx, data in enumerate(self.iter_data(dense=False, axis=axis)):
                min_val[idx] = data.data.min()

        return min_val

    def max(self, axis='sample'):
        """Get the maximum nonzero value over an axis

        Parameters
        ----------
        axis : {'sample', 'observation', 'whole'}, optional
            Defaults to "sample". The axis over which to calculate maxima.

        Returns
        -------
        scalar of self.dtype or np.array of self.dtype

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> from biom import example_table
        >>> print(example_table.max(axis='observation'))
        [ 2.  5.]

        """
        if axis not in ['sample', 'observation', 'whole']:
            raise UnknownAxisError(axis)

        if axis == 'whole':
            max_val = -np.inf
            for data in self.iter_data(dense=False):
                # only min over the actual nonzero values
                max_val = max(max_val, data.data.max())
        else:
            max_val = np.empty(len(self.ids(axis=axis)), dtype=self.dtype)

            for idx, data in enumerate(self.iter_data(dense=False, axis=axis)):
                max_val[idx] = data.data.max()

        return max_val

    def subsample(self, n, axis='sample', by_id=False, with_replacement=False):
        """Randomly subsample without replacement.

        Parameters
        ----------
        n : int
            Number of items to subsample from `counts`.
        axis : {'sample', 'observation'}, optional
            The axis to sample over
        by_id : boolean, optional
            If `False`, the subsampling is based on the counts contained in the
            matrix (e.g., rarefaction). If `True`, the subsampling is based on
            the IDs (e.g., fetch a random subset of samples). Default is
            `False`.
        with_replacement : boolean, optional
            If `False` (default), subsample without replacement. If `True`,
            resample with replacement via the multinomial distribution.
            Should not be `True` if `by_id` is `True`.

        Returns
        -------
        biom.Table
            A subsampled version of self

        Raises
        ------
        ValueError
            - If `n` is less than zero.
            - If `by_id` and `with_replacement` are both True.

        Notes
        -----
        Subsampling is performed without replacement. If `n` is greater than
        the sum of a given vector, that vector is omitted from the result.

        Adapted from `skbio.math.subsample`, see biom-format/licenses for more
        information about scikit-bio.

        This code assumes absolute abundance if `by_id` is False.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table
        >>> table = Table(np.array([[0, 2, 3], [1, 0, 2]]), ['O1', 'O2'],
        ...               ['S1', 'S2', 'S3'])

        Subsample 1 item over the sample axis by value (e.g., rarefaction):

        >>> print(table.subsample(1).sum(axis='sample'))
        [ 1.  1.  1.]

        Subsample 2 items over the sample axis, note that 'S1' is filtered out:

        >>> ss = table.subsample(2)
        >>> print(ss.sum(axis='sample'))
        [ 2.  2.]
        >>> print(ss.ids())
        ['S2' 'S3']

        Subsample by IDs over the sample axis. For this example, we're going to
        randomly select 2 samples and do this 100 times, and then print out the
        set of IDs observed.

        >>> ids = set([tuple(table.subsample(2, by_id=True).ids())
        ...            for i in range(100)])
        >>> print(sorted(ids))
        [('S1', 'S2'), ('S1', 'S3'), ('S2', 'S3')]

        """
        if n < 0:
            raise ValueError("n cannot be negative.")

        if with_replacement and by_id:
            raise ValueError("by_id and with_replacement cannot both be True")

        table = self.copy()

        if by_id:
            ids = table.ids(axis=axis).copy()
            np.random.shuffle(ids)
            subset = set(ids[:n])
            table.filter(lambda v, i, md: i in subset, axis=axis)
        else:
            data = table._get_sparse_data()
            _subsample(data, n, with_replacement)
            table._data = data

            table.filter(lambda v, i, md: v.sum() > 0, axis=axis)

        inv_axis = self._invert_axis(axis)
        table.filter(lambda v, i, md: v.sum() > 0, axis=inv_axis)

        return table

    def pa(self, inplace=True):
        """Convert the table to presence/absence data

        Parameters
        ----------
        inplace : bool, optional
            Defaults to ``False``

        Returns
        -------
        Table
            Returns itself if `inplace`, else returns a new presence/absence
            table.

        Examples
        --------
        >>> from biom.table import Table
        >>> import numpy as np

        Create a 2x3 BIOM table

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'])

        Convert to presence/absence data

        >>> _ = table.pa()
        >>> print(table.data('O1', 'observation'))
        [ 0.  0.  1.]
        >>> print(table.data('O2', 'observation'))
        [ 1.  1.  1.]
        """
        def transform_f(data, id_, metadata):
            return np.where(data != 0, 1., 0.)

        return self.transform(transform_f, inplace=inplace)

    def transform(self, f, axis='sample', inplace=True):
        """Iterate over `axis`, applying a function `f` to each vector.

        Only non null values can be modified and the density of the
        table can't increase. However, zeroing values is fine.

        Parameters
        ----------
        f : function(data, id, metadata) -> new data
            A function that takes three values: an array of nonzero
            values corresponding to each observation or sample, an
            observation or sample id, and an observation or sample
            metadata entry. It must return an array of transformed
            values that replace the original values.
        axis : {'sample', 'observation'}, optional
            The axis to operate on. Can be "sample" or "observation".
        inplace : bool, optional
            Defaults to ``True``. Whether to return a new table or modify
            itself.

        Returns
        -------
        biom.Table
            Returns itself if `inplace`, else returns a new transformed table.

        Raises
        ------
        UnknownAxisError
            If provided an unrecognized axis.

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 table

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               [{'foo': 'bar'}, {'x': 'y'}], None)
        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3
        O1  0.0 0.0 1.0
        O2  1.0 3.0 42.0

        Create a transform function

        >>> f = lambda data, id_, md: data / 2

        Transform to a new table on samples

        >>> table2 = table.transform(f, 'sample', False)
        >>> print(table2) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3
        O1  0.0 0.0 0.5
        O2  0.5 1.5 21.0

        `table` hasn't changed

        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3
        O1  0.0 0.0 1.0
        O2  1.0 3.0 42.0

        Tranform in place on observations

        >>> table3 = table.transform(f, 'observation', True)

        `table` is different now

        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3
        O1  0.0 0.0 0.5
        O2  0.5 1.5 21.0

        but the table returned (`table3`) is the same as `table`

        >>> print(table3) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2  S3
        O1  0.0 0.0 0.5
        O2  0.5 1.5 21.0

        """
        table = self if inplace else self.copy()

        metadata = table.metadata(axis=axis)
        ids = table.ids(axis=axis)
        arr = table._get_sparse_data(axis=axis)

        axis = table._axis_to_num(axis)

        _transform(arr, ids, metadata, f, axis)
        arr.eliminate_zeros()

        table._data = arr

        return table

    def rankdata(self, axis='sample', inplace=True, method='average'):
        """Convert values to rank abundances from smallest to largest

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            The axis to use for ranking.
        inplace : bool, optional
            Defaults to ``True``. If ``True``, performs the ranking in
            place. Otherwise, returns a new table with ranking applied.
        method : str, optional
            The method for handling ties in counts. This can be any valid
            string that can be passed to `scipy.stats.rankdata`.

        Returns
        -------
        biom.Table
            The rank-abundance-transformed table.

        Raises
        ------
        ValueError
            If unknown ``method`` is provided.

        See Also
        --------
        scipy.stats.rankdata

        Examples
        --------
        >>> import numpy as np
        >>> from biom import Table
        >>> data = np.array([[ 99,  12,   8], [  0,  42,   7],
        ...                  [112,  42,   6], [  5,  75,   5]])
        >>> t = Table(data, sample_ids=['s1', 's2', 's3'],
        ...           observation_ids=['o1', 'o2', 'o3', 'o4'])

        Convert observation counts to their ranked abundance, from smallest
        to largest.

        >>> print(t.rankdata())  # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	s1	s2	s3
        o1	2.0	1.0	4.0
        o2	0.0	2.5	3.0
        o3	3.0	2.5	2.0
        o4	1.0	4.0	1.0

        """
        def f(val, id_, _):
            return scipy.stats.rankdata(val, method=method)
        return self.transform(f, axis=axis, inplace=inplace)

    def norm(self, axis='sample', inplace=True):
        """Normalize in place sample values by an observation, or vice versa.

        Parameters
        ----------
        axis : {'sample', 'observation'}, optional
            The axis to use for normalization.
        inplace : bool, optional
            Defaults to ``True``. If ``True``, performs the normalization in
            place. Otherwise, returns a new table with the normalization
            applied.

        Returns
        -------
        biom.Table
            The normalized table

        Examples
        --------
        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x2 table:

        >>> data = np.asarray([[2, 0], [6, 1]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2'])

        Get a version of the table normalized on the 'sample' axis, leaving the
        original table untouched:

        >>> new_table = table.norm(inplace=False)
        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2
        O1  2.0 0.0
        O2  6.0 1.0
        >>> print(new_table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2
        O1  0.25    0.0
        O2  0.75    1.0

        Get a version of the table normalized on the 'observation' axis,
        again leaving the original table untouched:

        >>> new_table = table.norm(axis='observation', inplace=False)
        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2
        O1  2.0 0.0
        O2  6.0 1.0
        >>> print(new_table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2
        O1  1.0 0.0
        O2  0.857142857143  0.142857142857

        Do the same normalization on 'observation', this time in-place:

        >>> table.norm(axis='observation')
        2 x 2 <class 'biom.table.Table'> with 3 nonzero entries (75% dense)
        >>> print(table) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID S1  S2
        O1  1.0 0.0
        O2  0.857142857143  0.142857142857
        """
        def f(val, id_, _):
            return val / float(val.sum())

        return self.transform(f, axis=axis, inplace=inplace)

    def nonzero(self):
        """Yields locations of nonzero elements within the data matrix

        Returns
        -------
        generator
            Yields ``(observation_id, sample_id)`` for each nonzero element
        """
        csr = self._data.tocsr()
        samp_ids = self.ids()
        obs_ids = self.ids(axis='observation')

        indptr = csr.indptr
        indices = csr.indices
        for row_idx in range(indptr.size - 1):
            start = indptr[row_idx]
            end = indptr[row_idx+1]

            obs_id = obs_ids[row_idx]
            for col_idx in indices[start:end]:
                yield (obs_id, samp_ids[col_idx])

    def nonzero_counts(self, axis, binary=False):
        """Get nonzero summaries about an axis

        Parameters
        ----------
        axis : {'sample', 'observation', 'whole'}
            The axis on which to count nonzero entries
        binary : bool, optional
            Defaults to ``False``. If ``True``, return number of nonzero
            entries. If ``False``, sum the values of the entries.

        Returns
        -------
        numpy.array
            Counts in index order to the axis
        """
        if binary:
            dtype = 'int'

            def op(x):
                return x.nonzero()[0].size
        else:
            dtype = self.dtype

            def op(x):
                return x.sum()

        if axis in ('sample', 'observation'):
            # can use np.bincount for CSMat or ScipySparse
            result = zeros(len(self.ids(axis=axis)), dtype=dtype)
            for idx, vals in enumerate(self.iter_data(axis=axis)):
                result[idx] = op(vals)
        else:
            result = zeros(1, dtype=dtype)
            for vals in self.iter_data():
                result[0] += op(vals)

        return result

    def _union_id_order(self, a, b):
        """Determines merge order for id lists A and B"""
        all_ids = list(a[:])
        all_ids.extend(b[:])
        new_order = {}
        idx = 0
        for id_ in all_ids:
            if id_ not in new_order:
                new_order[id_] = idx
                idx += 1
        return new_order

    def _intersect_id_order(self, a, b):
        """Determines the merge order for id lists A and B"""
        all_b = set(b[:])
        new_order = {}
        idx = 0
        for id_ in a:
            if id_ in all_b:
                new_order[id_] = idx
                idx += 1
        return new_order

    def remove_empty(self, axis='whole', inplace=True):
        """Remove empty samples or observations from the table

        Parameters
        ----------
        axis : {'whole', 'sample', 'observation'}, optional
            The axis on which to operate.
        inplace : bool, optional
            If ``True`` vectors are removed in ``self``; if ``False`` the
            vectors are removed in a new table is returned.

        Raises
        ------
        UnknownAxisError
            If the axis is not recognized.

        Returns
        -------
        Table
            A table object with the zero'd rows, or columns removed as
            specified by the `axis` parameter.
        """
        if axis not in ['sample', 'observation', 'whole']:
            raise UnknownAxisError(axis)

        if inplace:
            table = self
        else:
            table = self.copy()

        if axis == 'whole':
            axes = ['sample', 'observation']
        else:
            axes = [axis]

        for ax in axes:
            table.filter(lambda v, i, md: (v > 0).sum(), axis=ax)

        return table

    def align_to(self, other, axis='detect'):
        """Align self to other over a requested axis

        Parameters
        ----------
        other : biom.Table
            The table to align too
        axis : str, optional, {sample, observation, both, detect}
            If 'sample' or 'observation', align to that axis. If 'both', align
            both axes. If 'detect', align what can be aligned.

        Raises
        ------
        DisjointIDError
            If the requested axis can't be aligned.
        UnknownAxisError
            If an unrecognized axis is specified.

        Examples
        --------
        Align one table to another, for instance a table of 16S data to a table
        of metagenomic data. In this example, we're aligning the samples of the
        two tables.

        >>> from biom import Table
        >>> import numpy as np
        >>> amplicon = Table(np.array([[0, 1, 2], [3, 4, 5]]),
        ...                  ['Ecoli', 'Staphylococcus'],
        ...                  ['S1', 'S2', 'S3'])
        >>> metag = Table(np.array([[6, 7, 8], [9, 10, 11]]),
        ...               ['geneA', 'geneB'],
        ...               ['S3', 'S2', 'S1'])
        >>> amplicon = amplicon.align_to(metag)
        >>> print(amplicon)  # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	S3	S2	S1
        Ecoli	2.0	1.0	0.0
        Staphylococcus	5.0	4.0	3.0
        """
        self_o = set(self.ids(axis='observation'))
        self_s = set(self.ids())
        other_o = set(other.ids(axis='observation'))
        other_s = set(other.ids())

        alignable_o = self_o == other_o
        alignable_s = self_s == other_s

        if axis is 'both' and not (alignable_o and alignable_s):
            raise DisjointIDError("Cannot align both axes")
        elif axis is 'sample' and not alignable_s:
            raise DisjointIDError("Cannot align samples")
        elif axis is 'observation' and not alignable_o:
            raise DisjointIDError("Cannot align observations")
        elif axis is 'detect' and not (alignable_o or alignable_s):
            raise DisjointIDError("Neither axis appears alignable")

        if axis is 'both':
            order = ['observation', 'sample']
        elif axis is 'detect':
            order = []
            if alignable_s:
                order.append('sample')
            if alignable_o:
                order.append('observation')
        elif axis is 'sample':
            order = ['sample']
        elif axis is 'observation':
            order = ['observation']
        else:
            raise UnknownAxisError("Unrecognized axis: %s" % axis)

        table = self
        for aln_axis in order:
            table = table.sort_order(other.ids(axis=aln_axis),
                                     axis=aln_axis)

        return table

    def concat(self, others, axis='sample'):
        """Concatenate tables if axis is disjoint

        Parameters
        ----------
        others : iterable of biom.Table
            Tables to concatenate
        axis : {'sample', 'observation'}, optional
            The axis to concatenate on. i.e., if axis is 'sample', then tables
            will be joined such that the set of sample IDs in the resulting
            table will be the union of sample IDs across all tables in others.

        Raises
        ------
        DisjointIDError
            If IDs over the axis are not disjoint.

        Notes
        -----
        The type of the table is inherited from self.

        Examples
        --------
        Concatenate three tables in which the sample IDs are disjoint. Note
        the observation IDs in this example are not disjoint (although they
        can be):

        >>> from biom import Table
        >>> import numpy as np
        >>> a = Table(np.array([[0, 1, 2], [3, 4, 5]]), ['O1', 'O2'],
        ...                     ['S1', 'S2', 'S3'],
        ...                     [{'taxonomy': 'foo'}, {'taxonomy': 'bar'}])
        >>> b = Table(np.array([[6, 7, 8], [9, 10, 11]]), ['O3', 'O4'],
        ...                     ['S4', 'S5', 'S6'],
        ...                     [{'taxonomy': 'baz'}, {'taxonomy': 'foobar'}])
        >>> c = Table(np.array([[12, 13, 14], [15, 16, 17]]), ['O1', 'O5'],
        ...                     ['S7', 'S8', 'S9'],
        ...                     [{'taxonomy': 'foo'}, {'taxonomy': 'biz'}])
        >>> d = a.concat([b, c])
        >>> print(d)  # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	S1	S2	S3	S4	S5	S6	S7	S8	S9
        O1	0.0	1.0	2.0	0.0	0.0	0.0	12.0	13.0	14.0
        O2	3.0	4.0	5.0	0.0	0.0	0.0	0.0	0.0	0.0
        O3	0.0	0.0	0.0	6.0	7.0	8.0	0.0	0.0	0.0
        O4	0.0	0.0	0.0	9.0	10.0	11.0	0.0	0.0	0.0
        O5	0.0	0.0	0.0	0.0	0.0	0.0	15.0	16.0	17.0

        """
        # we grow along the opposite axis
        invaxis = self._invert_axis(axis)
        if axis == 'sample':
            dim_getter = itemgetter(1)
            stack = hstack
            invstack = vstack
        else:
            dim_getter = itemgetter(0)
            stack = vstack
            invstack = hstack

        axis_ids = set()
        invaxis_ids = set()
        invaxis_metadata = {}

        all_tables = others[:]
        all_tables.insert(0, self)

        # verify disjoint, and fetch all ids from all tables
        for table in all_tables:
            table_axis_ids = table.ids(axis=axis)
            table_invaxis_order = table.ids(axis=invaxis)
            table_invaxis = set(table_invaxis_order)

            # test we have disjoint IDs
            if not axis_ids.isdisjoint(table_axis_ids):
                raise DisjointIDError("IDs are not disjoint")
            axis_ids.update(table_axis_ids)

            if set(table_invaxis) - invaxis_ids:
                for i in (set(table_invaxis) - invaxis_ids):
                    invaxis_metadata[i] = table.metadata(i, axis=invaxis)

                # add to our perspective all inv axis IDs
                invaxis_ids.update(table_invaxis)

        invaxis_order = sorted(invaxis_ids)

        # determine what inv axis IDs do not exist per table, and pad and sort
        # as necessary
        padded_tables = []
        for table in all_tables:
            missing_ids = list(invaxis_ids - set(table.ids(axis=invaxis)))

            if missing_ids:
                # determine new shape
                n_invaxis = len(missing_ids)
                n_axis = len(table.ids(axis=axis))
                if axis == 'sample':
                    shape = (n_invaxis, n_axis)
                else:
                    shape = (n_axis, n_invaxis)

                # create the padded matrix
                zerod = csr_matrix(shape)
                tmp_mat = invstack([table.matrix_data, zerod])

                # resolve invert axis ids and metadata
                tmp_inv_ids = list(table.ids(axis=invaxis))
                tmp_inv_ids.extend(missing_ids)
                tmp_inv_md = table.metadata(axis=invaxis)
                if tmp_inv_md is None:
                    tmp_inv_md = [None] * len(table.ids(axis=invaxis))
                else:
                    tmp_inv_md = list(tmp_inv_md)
                tmp_inv_md.extend([invaxis_metadata[i] for i in missing_ids])

                # resolve axis ids and metadata
                tmp_ids = list(table.ids(axis=axis))
                tmp_md = table.metadata(axis=axis)

                # resolve construction based off axis. This really should be
                # pushed to a classmethod.
                if axis == 'sample':
                    tmp_table = self.__class__(tmp_mat, tmp_inv_ids, tmp_ids,
                                               tmp_inv_md, tmp_md)
                else:
                    tmp_table = self.__class__(tmp_mat, tmp_ids, tmp_inv_ids,
                                               tmp_md, tmp_inv_md)
            else:
                tmp_table = table

            # sort the table if necessary
            if (tmp_table.ids(axis=invaxis) == invaxis_order).all():
                padded_tables.append(tmp_table)
            else:
                padded_tables.append(tmp_table.sort_order(invaxis_order,
                                                          axis=invaxis))

        # actually concatenate the matrices, IDs and metadata
        concat_mat = stack([t.matrix_data for t in padded_tables])
        concat_ids = np.concatenate([t.ids(axis=axis) for t in padded_tables])
        concat_md = []
        for table in padded_tables:
            metadata = table.metadata(axis=axis)
            if metadata is None:
                metadata = [None] * dim_getter(table.shape)
            concat_md.extend(metadata)

        # inverse axis sourced from whatever is in the first table
        inv_md = padded_tables[0].metadata(axis=invaxis)
        if axis == 'sample':
            concat = self.__class__(concat_mat, invaxis_order, concat_ids,
                                    inv_md, concat_md, type=self.type)
        else:
            concat = self.__class__(concat_mat, concat_ids, invaxis_order,
                                    concat_md, inv_md, type=self.type)

        return concat

    def merge(self, other, sample='union', observation='union',
              sample_metadata_f=prefer_self,
              observation_metadata_f=prefer_self):
        """Merge two tables together

        The axes, samples and observations, can be controlled independently.
        Both can work on either "union" or "intersection".

        `sample_metadata_f` and `observation_metadata_f` define how to
        merge metadata between tables. The default is to just keep the metadata
        associated to self if self has metadata otherwise take metadata from
        other. These functions are given both metadata dicts and must return
        a single metadata dict

        Parameters
        ----------
        other : biom.Table
            The other table to merge with this one
        sample : {'union', 'intersection'}, optional
        observation : {'union', 'intersection'}, optional
        sample_metadata_f : function, optional
            Defaults to ``biom.util.prefer_self``. Defines how to handle sample
            metadata during merge.
        obesrvation_metadata_f : function, optional
            Defaults to ``biom.util.prefer_self``. Defines how to handle
            observation metdata during merge.

        Returns
        -------
        biom.Table
            The merged table

        Notes
        -----
        - There is an implicit type conversion to ``float``.
        - The return type is always that of ``self``

        Examples
        --------

        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x2 table and a 3x2 table:

        >>> d_a = np.asarray([[2, 0], [6, 1]])
        >>> t_a = Table(d_a, ['O1', 'O2'], ['S1', 'S2'])
        >>> d_b = np.asarray([[4, 5], [0, 3], [10, 10]])
        >>> t_b = Table(d_b, ['O1', 'O2', 'O3'], ['S1', 'S2'])

        Merging the table results in the overlapping samples/observations (see
        `O1` and `S2`) to be summed and the non-overlapping ones to be added to
        the resulting table (see `S3`).

        >>> merged_table = t_a.merge(t_b)
        >>> print(merged_table)  # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	S1	S2
        O1	6.0	5.0
        O2	6.0	4.0
        O3	10.0	10.0

        """
        # determine the sample order in the resulting table
        if sample is 'union':
            new_samp_order = self._union_id_order(self.ids(), other.ids())
        elif sample is 'intersection':
            new_samp_order = self._intersect_id_order(self.ids(), other.ids())
        else:
            raise TableException("Unknown sample merge type: %s" % sample)

        # determine the observation order in the resulting table
        if observation is 'union':
            new_obs_order = self._union_id_order(
                self.ids(axis='observation'), other.ids(axis='observation'))
        elif observation is 'intersection':
            new_obs_order = self._intersect_id_order(
                self.ids(axis='observation'), other.ids(axis='observation'))
        else:
            raise TableException(
                "Unknown observation merge type: %s" %
                observation)

        # convert these to lists, no need to be dictionaries and reduces
        # calls to items() and allows for pre-caluculating insert order
        new_samp_order = sorted(new_samp_order.items(), key=itemgetter(1))
        new_obs_order = sorted(new_obs_order.items(), key=itemgetter(1))

        # if we don't have any samples, complain loudly. This is likely from
        # performing an intersection without overlapping ids
        if not new_samp_order:
            raise TableException("No samples in resulting table!")
        if not new_obs_order:
            raise TableException("No observations in resulting table!")

        # helper index lookups
        other_obs_idx = other._obs_index
        self_obs_idx = self._obs_index
        other_samp_idx = other._sample_index
        self_samp_idx = self._sample_index

        # pre-calculate sample order from each table. We only need to do this
        # once which dramatically reduces the number of dict lookups necessary
        # within the inner loop
        other_samp_order = []
        self_samp_order = []
        for samp_id, nsi in new_samp_order:  # nsi -> new_sample_index
            other_samp_order.append((nsi, other_samp_idx.get(samp_id, None)))
            self_samp_order.append((nsi, self_samp_idx.get(samp_id, None)))

        # pre-allocate the a list for placing the resulting vectors as the
        # placement id is not ordered
        vals = [None for i in range(len(new_obs_order))]

        # POSSIBLE DECOMPOSITION
        # resulting sample ids and sample metadata
        sample_ids = []
        sample_md = []
        self_sample_md = self.metadata()
        other_sample_md = other.metadata()
        for id_, idx in new_samp_order:
            sample_ids.append(id_)

            # if we have sample metadata, grab it
            if self_sample_md is None or not self.exists(id_):
                self_md = None
            else:
                self_md = self_sample_md[self_samp_idx[id_]]

            # if we have sample metadata, grab it
            if other_sample_md is None or not other.exists(id_):
                other_md = None
            else:
                other_md = other_sample_md[other_samp_idx[id_]]

            sample_md.append(sample_metadata_f(self_md, other_md))

        # POSSIBLE DECOMPOSITION
        # resulting observation ids and sample metadata
        obs_ids = []
        obs_md = []
        self_obs_md = self.metadata(axis='observation')
        other_obs_md = other.metadata(axis='observation')
        for id_, idx in new_obs_order:
            obs_ids.append(id_)

            # if we have observation metadata, grab it
            if self_obs_md is None or not self.exists(id_, axis="observation"):
                self_md = None
            else:
                self_md = self_obs_md[self_obs_idx[id_]]

            # if we have observation metadata, grab it
            if other_obs_md is None or \
                    not other.exists(id_, axis="observation"):
                other_md = None
            else:
                other_md = other_obs_md[other_obs_idx[id_]]

            obs_md.append(observation_metadata_f(self_md, other_md))

        # length used for construction of new vectors
        vec_length = len(new_samp_order)

        # walk over observations in our new order
        for obs_id, new_obs_idx in new_obs_order:
            # create new vector for matrix values
            new_vec = zeros(vec_length, dtype='float')

            # This method allows for the creation of a matrix of self type.
            # See note above
            # new_vec = data_f()

            # see if the observation exists in other, if so, pull it out.
            # if not, set to the placeholder missing
            if other.exists(obs_id, axis="observation"):
                other_vec = other.data(obs_id, 'observation')
            else:
                other_vec = None

            # see if the observation exists in self, if so, pull it out.
            # if not, set to the placeholder missing
            if self.exists(obs_id, axis="observation"):
                self_vec = self.data(obs_id, 'observation')
            else:
                self_vec = None

            # short circuit. If other doesn't have any values, then we can just
            # take all values from self
            if other_vec is None:
                for (n_idx, s_idx) in self_samp_order:
                    if s_idx is not None:
                        new_vec[n_idx] = self_vec[s_idx]

            # short circuit. If self doesn't have any values, then we can just
            # take all values from other
            elif self_vec is None:
                for (n_idx, o_idx) in other_samp_order:
                    if o_idx is not None:
                        new_vec[n_idx] = other_vec[o_idx]

            else:
                # NOTE: DM 7.5.12, no observed improvement at the profile level
                # was made on this inner loop by using self_samp_order and
                # other_samp_order lists.

                # walk over samples in our new order
                for samp_id, new_samp_idx in new_samp_order:
                    # pull out each individual sample value. This is expensive,
                    # but the vectors are in a different alignment. It is
                    # possible that this could be improved with numpy take but
                    # needs to handle missing values appropriately
                    if samp_id not in self_samp_idx:
                        self_vec_value = 0
                    else:
                        self_vec_value = self_vec[self_samp_idx[samp_id]]

                    if samp_id not in other_samp_idx:
                        other_vec_value = 0
                    else:
                        other_vec_value = other_vec[other_samp_idx[samp_id]]

                    new_vec[new_samp_idx] = self_vec_value + other_vec_value

            # convert our new vector to self type as to make sure we don't
            # accidently force a dense representation in memory
            vals[new_obs_idx] = self._conv_to_self_type(new_vec)

        return self.__class__(self._conv_to_self_type(vals), obs_ids[:],
                              sample_ids[:], obs_md, sample_md)

    @classmethod
    def from_hdf5(cls, h5grp, ids=None, axis='sample', parse_fs=None,
                  subset_with_metadata=True):
        """Parse an HDF5 formatted BIOM table

        If ids is provided, only the samples/observations listed in ids
        (depending on the value of axis) will be loaded

        The expected structure of this group is below. A few basic definitions,
        N is the number of observations and M is the number of samples. Data
        are stored in both compressed sparse row (for observation oriented
        operations) and compressed sparse column (for sample oriented
        operations).

        Notes
        -----
        The expected HDF5 group structure is below. An example of an HDF5 file
        in DDL can be found here [3]_.

        - ./id                                                  : str, an \
arbitrary ID
        - ./type                                                : str, the \
table type (e.g, OTU table)
        - ./format-url                                          : str, a URL \
that describes the format
        - ./format-version                                      : two element \
tuple of int32, major and minor
        - ./generated-by                                        : str, what \
generated this file
        - ./creation-date                                       : str, ISO \
format
        - ./shape                                               : two element \
tuple of int32, N by M
        - ./nnz                                                 : int32 or \
int64, number of non zero elems
        - ./observation                                         : Group
        - ./observation/ids                                     : (N,) dataset\
 of str or vlen str
        - ./observation/matrix                                  : Group
        - ./observation/matrix/data                             : (nnz,) \
dataset of float64
        - ./observation/matrix/indices                          : (nnz,) \
dataset of int32
        - ./observation/matrix/indptr                           : (M+1,) \
dataset of int32
        - ./observation/metadata                                : Group
        - [./observation/metadata/foo]                          : Optional, \
(N,) dataset of any valid HDF5 type in index order with IDs.
        - ./observation/group-metadata                          : Group
        - [./observation/group-metadata/foo]                    : Optional, \
(?,) dataset of group metadata that relates IDs
        - [./observation/group-metadata/foo.attrs['data_type']] : attribute of\
 the foo dataset that describes contained type (e.g., newick)
        - ./sample                                              : Group
        - ./sample/ids                                          : (M,) dataset\
 of str or vlen str
        - ./sample/matrix                                       : Group
        - ./sample/matrix/data                                  : (nnz,) \
dataset of float64
        - ./sample/matrix/indices                               : (nnz,) \
dataset of int32
        - ./sample/matrix/indptr                                : (N+1,) \
dataset of int32
        - ./sample/metadata                                     : Group
        - [./sample/metadata/foo]                               : Optional, \
(M,) dataset of any valid HDF5 type in index order with IDs.
        - ./sample/group-metadata                               : Group
        - [./sample/group-metadata/foo]                         : Optional, \
(?,) dataset of group metadata that relates IDs
        - [./sample/group-metadata/foo.attrs['data_type']]      : attribute of\
 the foo dataset that describes contained type (e.g., newick)

        The '?' character on the dataset size means that it can be of arbitrary
        length.

        The expected structure for each of the metadata datasets is a list of
        atomic type objects (int, float, str, ...), where the index order of
        the list corresponds to the index order of the relevant axis IDs.
        Special metadata fields have been defined, and they are stored in a
        specific way. Currently, the available special metadata fields are:

        - taxonomy: (N, ?) dataset of str or vlen str
        - KEGG_Pathways: (N, ?) dataset of str or vlen str
        - collapsed_ids: (N, ?) dataset of str or vlen str

        Parameters
        ----------
        h5grp : a h5py ``Group`` or an open h5py ``File``
        ids : iterable
            The sample/observation ids of the samples/observations that we need
            to retrieve from the hdf5 biom table
        axis : {'sample', 'observation'}, optional
            The axis to subset on
        parse_fs : dict, optional
            Specify custom parsing functions for metadata fields. This dict is
            expected to be {'metadata_field': function}, where the function
            signature is (object) corresponding to a single row in the
            associated metadata dataset. The return from this function an
            object as well, and is the parsed representation of the metadata.
        subset_with_metadata : bool, optional
            When subsetting (i.e., `ids` is `not None`), whether to also parse
            the metadata. By default, the metadata are also subset. The reason
            for exposing this functionality is that, for large tables, there
            exists a very large overhead for this metadata manipulation.

        Returns
        -------
        biom.Table
            A BIOM ``Table`` object

        Raises
        ------
        ValueError
            If `ids` are not a subset of the samples or observations ids
            present in the hdf5 biom table
            If h5grp is not a HDF5 file or group

        References
        ----------
        .. [1] http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/sci\
py.sparse.csr_matrix.html
        .. [2] http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/sci\
py.sparse.csc_matrix.html
        .. [3] http://biom-format.org/documentation/format_versions/biom-2.0.\
html

        See Also
        --------
        Table.to_hdf5

        Examples
        --------
        >>> from biom.table import Table
        >>> from biom.util import biom_open
        >>> with biom_open('rich_sparse_otu_table_hdf5.biom') as f \
# doctest: +SKIP
        >>>     t = Table.from_hdf5(f) # doctest: +SKIP

        Parse a hdf5 biom table subsetting observations
        >>> from biom.util import biom_open # doctest: +SKIP
        >>> from biom.parse import parse_biom_table
        >>> with biom_open('rich_sparse_otu_table_hdf5.biom') as f \
# doctest: +SKIP
        >>>     t = Table.from_hdf5(f, ids=["GG_OTU_1"],
        ...                         axis='observation') # doctest: +SKIP
        """
        if not HAVE_H5PY:
            raise RuntimeError("h5py is not in the environment, HDF5 support "
                               "is not available")

        import h5py
        if not isinstance(h5grp, (h5py.Group, h5py.File)):
            raise ValueError("h5grp does not appear to be an HDF5 file or "
                             "group")

        if axis not in ['sample', 'observation']:
            raise UnknownAxisError(axis)

        if parse_fs is None:
            parse_fs = {}

        if not subset_with_metadata and ids is not None:
            ids = set(ids)

            raw_indices = h5grp['%s/matrix/indices' % axis]
            raw_indptr = h5grp['%s/matrix/indptr' % axis]
            raw_data = h5grp['%s/matrix/data' % axis]
            axis_ids = h5grp['%s/ids' % axis][:]

            to_keep = np.array([i for i, id_ in enumerate(axis_ids)
                                if id_ in ids], dtype=int)
            start_end = [(raw_indptr[i], raw_indptr[i+1]) for i in to_keep]
            indptr = np.empty(len(to_keep) + 1, dtype=np.int32)
            indptr[0] = 0
            indptr[1:] = np.array([e - s for s, e in start_end]).cumsum()
            data = np.concatenate([raw_data[s:e] for s, e in start_end])
            indices = np.concatenate([raw_indices[s:e] for s, e in start_end])

            if axis == 'sample':
                obs_ids = h5grp['observation/ids'][:]
                samp_ids = axis_ids[to_keep]
                shape = (len(obs_ids), len(to_keep))
                mat = csc_matrix((data, indices, indptr), shape=shape)
            else:
                samp_ids = h5grp['sample/ids'][:]
                obs_ids = axis_ids[to_keep]
                shape = (len(to_keep), len(samp_ids))
                mat = csr_matrix((data, indices, indptr), shape=shape)

            return Table(mat, obs_ids, samp_ids)

        id_ = h5grp.attrs['id']
        create_date = h5grp.attrs['creation-date']
        generated_by = h5grp.attrs['generated-by']

        shape = h5grp.attrs['shape']
        type_ = None if h5grp.attrs['type'] == '' else h5grp.attrs['type']

        if isinstance(id_, six.binary_type):
            if six.PY3:
                id_ = id_.decode('ascii')
            else:
                id_ = str(id_)

        if isinstance(type_, six.binary_type):
            if six.PY3:
                type_ = type_.decode('ascii')
            else:
                type_ = str(type_)

        def axis_load(grp):
            """Loads all the data of the given group"""
            # fetch all of the IDs
            ids = grp['ids'][:]

            if ids.size > 0 and isinstance(ids[0], bytes):
                ids = np.array([i.decode('utf8') for i in ids])

            parser = defaultdict(lambda: general_parser)
            parser['taxonomy'] = vlen_list_of_str_parser
            parser['KEGG_Pathways'] = vlen_list_of_str_parser
            parser['collapsed_ids'] = vlen_list_of_str_parser
            parser.update(parse_fs)

            # fetch ID specific metadata
            md = [{} for i in range(len(ids))]
            for category, dset in viewitems(grp['metadata']):
                parse_f = parser[category]
                data = dset[:]
                for md_dict, data_row in zip(md, data):
                    md_dict[category] = parse_f(data_row)

            # If there was no metadata on the axis, set it up as none
            md = md if any(md) else None

            # Fetch the group metadata
            grp_md = {cat: val
                      for cat, val in grp['group-metadata'].items()}
            return ids, md, grp_md

        obs_ids, obs_md, obs_grp_md = axis_load(h5grp['observation'])
        samp_ids, samp_md, samp_grp_md = axis_load(h5grp['sample'])

        # load the data
        data_grp = h5grp[axis]['matrix']
        h5_data = data_grp["data"]
        h5_indices = data_grp["indices"]
        h5_indptr = data_grp["indptr"]

        # Check if we need to subset the biom table
        if ids is not None:
            def _get_ids(source_ids, desired_ids):
                """If desired_ids is not None, makes sure that it is a subset
                of source_ids and returns the desired_ids array-like and a
                boolean array indicating where the desired_ids can be found in
                source_ids"""
                if desired_ids is None:
                    ids = source_ids[:]
                    idx = np.ones(source_ids.shape, dtype=bool)
                else:
                    desired_ids = np.asarray(desired_ids)
                    # Get the index of the source ids to include
                    idx = np.in1d(source_ids, desired_ids)
                    # Retrieve only the ids that we are interested on
                    ids = source_ids[idx]
                    # Check that all desired ids have been found on source ids

                    if ids.shape != desired_ids.shape:
                        raise ValueError("The following ids could not be "
                                         "found in the biom table: %s" %
                                         (set(desired_ids) - set(ids)))
                return ids, idx

            # Get the observation and sample ids that we are interested in
            samp, obs = (ids, None) if axis == 'sample' else (None, ids)
            obs_ids, obs_idx = _get_ids(obs_ids, obs)
            samp_ids, samp_idx = _get_ids(samp_ids, samp)

            # Get the new matrix shape
            shape = (len(obs_ids), len(samp_ids))

            # Fetch the metadata that we are interested in
            def _subset_metadata(md, idx):
                """If md has data, returns the subset indicated by idx, a
                boolean array"""
                if md:
                    md = list(np.asarray(md)[np.where(idx)])
                return md

            obs_md = _subset_metadata(obs_md, obs_idx)
            samp_md = _subset_metadata(samp_md, samp_idx)

            # load the subset of the data
            idx = samp_idx if axis == 'sample' else obs_idx
            keep = np.where(idx)[0]
            indptr_indices = sorted([(h5_indptr[i], h5_indptr[i+1])
                                     for i in keep])
            # Create the new indptr
            indptr_subset = np.array([end - start
                                     for start, end in indptr_indices])
            indptr = np.empty(len(keep) + 1, dtype=np.int32)
            indptr[0] = 0
            indptr[1:] = indptr_subset.cumsum()

            data = np.hstack(h5_data[start:end]
                             for start, end in indptr_indices)
            indices = np.hstack(h5_indices[start:end]
                                for start, end in indptr_indices)
        else:
            # no subset need, just pass all data to scipy
            data = h5_data
            indices = h5_indices
            indptr = h5_indptr

        cs = (data, indices, indptr)

        if axis == 'sample':
            matrix = csc_matrix(cs, shape=shape)
        else:
            matrix = csr_matrix(cs, shape=shape)

        t = Table(matrix, obs_ids, samp_ids, obs_md or None,
                  samp_md or None, type=type_, create_date=create_date,
                  generated_by=generated_by, table_id=id_,
                  observation_group_metadata=obs_grp_md,
                  sample_group_metadata=samp_grp_md)

        if ids is not None:
            # filter out any empty samples or observations which may exist due
            # to subsetting
            def any_value(vals, id_, md):
                return np.any(vals)

            axis = 'observation' if axis == 'sample' else 'sample'
            t.filter(any_value, axis=axis)

        return t

    def to_dataframe(self, dense=False):
        """Convert matrix data to a Pandas SparseDataFrame or DataFrame

        Parameters
        ----------
        dense : bool, optional
            If True, return pd.DataFrame instead of pd.SparseDataFrame.

        Returns
        -------
        pd.DataFrame or pd.SparseDataFrame
            A DataFrame indexed on the observation IDs, with the column
            names as the sample IDs.

        Notes
        -----
        Metadata are not included.

        Examples
        --------
        >>> from biom import example_table
        >>> df = example_table.to_dataframe()
        >>> df
             S1   S2   S3
        O1  0.0  1.0  2.0
        O2  3.0  4.0  5.0
        """
        index = self.ids(axis='observation')
        columns = self.ids()

        if dense:
            mat = self.matrix_data.toarray()
            constructor = pd.DataFrame
        else:
            mat = [pd.SparseSeries(r.toarray().squeeze())
                   for r in self.matrix_data.tocsr()]
            constructor = pd.SparseDataFrame

        return constructor(mat, index=index, columns=columns)

    def metadata_to_dataframe(self, axis):
        """Convert axis metadata to a Pandas DataFrame

        Parameters
        ----------
        axis : {'sample', 'observation'}
            The axis to operate on.

        Returns
        -------
        pd.DataFrame
            A DataFrame indexed by the ids of the desired axis, columns by the
            metadata keys over that axis.

        Raises
        ------
        UnknownAxisError
            If the requested axis isn't recognized
        KeyError
            IF the requested axis does not have metadata
        TypeError
            If a metadata column is a list or tuple, but is jagged over the
            axis.

        Notes
        -----
        Nested metadata (e.g., KEGG_Pathways) is not supported.

        Metadata which are lists or tuples (e.g., taxonomy) are expanded such
        that each index position is a unique column. For instance, the key
        taxonomy will become "taxonomy_0", "taxonomy_1", etc where "taxonomy_0"
        corresponds to the 0th index position of the taxonomy.

        Examples
        --------
        >>> from biom import example_table
        >>> example_table.metadata_to_dataframe('observation')
           taxonomy_0     taxonomy_1
        O1   Bacteria     Firmicutes
        O2   Bacteria  Bacteroidetes
        """
        md = self.metadata(axis=axis)
        if md is None:
            raise KeyError("%s does not have metadata" % axis)

        test = md[0]
        kv_test = sorted(list(test.items()))
        columns = []
        expand = {}
        for key, value in kv_test:
            if isinstance(value, (tuple, list)):
                expand[key] = True
                for idx in range(len(value)):
                    columns.append("%s_%d" % (key, idx))
            else:
                expand[key] = False
                columns.append(key)

        rows = []
        for m in md:
            row = []
            for key, value in sorted(m.items()):
                if expand[key]:
                    for v in value:
                        row.append(v)
                else:
                    row.append(value)
            rows.append(row)

        return pd.DataFrame(rows, index=self.ids(axis=axis), columns=columns)

    def to_hdf5(self, h5grp, generated_by, compress=True, format_fs=None):
        """Store CSC and CSR in place

        The resulting structure of this group is below. A few basic
        definitions, N is the number of observations and M is the number of
        samples. Data are stored in both compressed sparse row [1]_ (CSR, for
        observation oriented operations) and compressed sparse column [2]_
        (CSC, for sample oriented operations).

        Notes
        -----
        The expected HDF5 group structure is below. An example of an HDF5 file
        in DDL can be found here [3]_.

        - ./id                                                  : str, an \
arbitrary ID
        - ./type                                                : str, the \
table type (e.g, OTU table)
        - ./format-url                                          : str, a URL \
that describes the format
        - ./format-version                                      : two element \
tuple of int32, major and minor
        - ./generated-by                                        : str, what \
generated this file
        - ./creation-date                                       : str, ISO \
format
        - ./shape                                               : two element \
tuple of int32, N by M
        - ./nnz                                                 : int32 or \
int64, number of non zero elems
        - ./observation                                         : Group
        - ./observation/ids                                     : (N,) dataset\
 of str or vlen str
        - ./observation/matrix                                  : Group
        - ./observation/matrix/data                             : (nnz,) \
dataset of float64
        - ./observation/matrix/indices                          : (nnz,) \
dataset of int32
        - ./observation/matrix/indptr                           : (M+1,) \
dataset of int32
        - ./observation/metadata                                : Group
        - [./observation/metadata/foo]                          : Optional, \
(N,) dataset of any valid HDF5 type in index order with IDs.
        - ./observation/group-metadata                          : Group
        - [./observation/group-metadata/foo]                    : Optional, \
(?,) dataset of group metadata that relates IDs
        - [./observation/group-metadata/foo.attrs['data_type']] : attribute of\
 the foo dataset that describes contained type (e.g., newick)
        - ./sample                                              : Group
        - ./sample/ids                                          : (M,) dataset\
 of str or vlen str
        - ./sample/matrix                                       : Group
        - ./sample/matrix/data                                  : (nnz,) \
dataset of float64
        - ./sample/matrix/indices                               : (nnz,) \
dataset of int32
        - ./sample/matrix/indptr                                : (N+1,) \
dataset of int32
        - ./sample/metadata                                     : Group
        - [./sample/metadata/foo]                               : Optional, \
(M,) dataset of any valid HDF5 type in index order with IDs.
        - ./sample/group-metadata                               : Group
        - [./sample/group-metadata/foo]                         : Optional, \
(?,) dataset of group metadata that relates IDs
        - [./sample/group-metadata/foo.attrs['data_type']]      : attribute of\
 the foo dataset that describes contained type (e.g., newick)

        The '?' character on the dataset size means that it can be of arbitrary
        length.

        The expected structure for each of the metadata datasets is a list of
        atomic type objects (int, float, str, ...), where the index order of
        the list corresponds to the index order of the relevant axis IDs.
        Special metadata fields have been defined, and they are stored in a
        specific way. Currently, the available special metadata fields are:

        - taxonomy: (N, ?) dataset of str or vlen str
        - KEGG_Pathways: (N, ?) dataset of str or vlen str
        - collapsed_ids: (N, ?) dataset of str or vlen str

        Parameters
        ----------
        h5grp : `h5py.Group` or `h5py.File`
            The HDF5 entity in which to write the BIOM formatted data.
        generated_by : str
            A description of what generated the table
        compress : bool, optional
            Defaults to ``True`` means fields will be compressed with gzip,
            ``False`` means no compression
        format_fs : dict, optional
            Specify custom formatting functions for metadata fields. This dict
            is expected to be {'metadata_field': function}, where the function
            signature is (h5py.Group, str, dict, bool) corresponding to the
            specific HDF5 group the metadata dataset will be associated with,
            the category being operated on, the metadata for the entire axis
            being operated on, and whether to enable compression on the
            dataset.  Anything returned by this function is ignored.

        Notes
        -----
        This method does not return anything and operates in place on h5grp.

        See Also
        --------
        Table.from_hdf5

        References
        ----------
        .. [1] http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/sci\
py.sparse.csr_matrix.html
        .. [2] http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/sci\
py.sparse.csc_matrix.html
        .. [3] http://biom-format.org/documentation/format_versions/biom-2.1.\
html

        Examples
        --------
        >>> from biom.util import biom_open  # doctest: +SKIP
        >>> from biom.table import Table
        >>> from numpy import array
        >>> t = Table(array([[1, 2], [3, 4]]), ['a', 'b'], ['x', 'y'])
        >>> with biom_open('foo.biom', 'w') as f:  # doctest: +SKIP
        ...     t.to_hdf5(f, "example")

        """
        if not HAVE_H5PY:
            raise RuntimeError("h5py is not in the environment, HDF5 support "
                               "is not available")

        if format_fs is None:
            format_fs = {}

        h5grp.attrs['id'] = self.table_id if self.table_id else "No Table ID"
        h5grp.attrs['type'] = self.type if self.type else ""
        h5grp.attrs['format-url'] = "http://biom-format.org"
        h5grp.attrs['format-version'] = self.format_version
        h5grp.attrs['generated-by'] = generated_by
        h5grp.attrs['creation-date'] = datetime.now().isoformat()
        h5grp.attrs['shape'] = self.shape
        h5grp.attrs['nnz'] = self.nnz

        compression = None
        if compress is True:
            compression = 'gzip'

        formatter = defaultdict(lambda: general_formatter)
        formatter['taxonomy'] = vlen_list_of_str_formatter
        formatter['KEGG_Pathways'] = vlen_list_of_str_formatter
        formatter['collapsed_ids'] = vlen_list_of_str_formatter
        formatter.update(format_fs)

        for axis, order in zip(['observation', 'sample'], ['csr', 'csc']):
            grp = h5grp.create_group(axis)

            self._data = self._data.asformat(order)

            ids = self.ids(axis=axis)
            len_ids = len(ids)
            len_indptr = len(self._data.indptr)
            len_data = self.nnz

            md = self.metadata(axis=axis)

            # Create the group for the metadata
            grp.create_group('metadata')
            if md:
                exp = set(md[0])
                for other_id, other_md in zip(ids[1:], md[1:]):
                    if set(other_md) != exp:
                        raise ValueError("%s has inconsistent metadata "
                                         "categories with %s:\n"
                                         "%s: %s\n"
                                         "%s: %s" % (other_id, ids[0],
                                                     other_id, list(other_md),
                                                     ids[0], list(exp)))

                for category in md[0]:
                    # Create the dataset for the current category,
                    # putting values in id order
                    formatter[category](grp, category, md, compression)

            group_md = self.group_metadata(axis)

            # Create the group for the group metadata
            grp.create_group('group-metadata')

            if group_md:
                for key, value in group_md.items():
                    datatype, val = value
                    grp_dataset = grp.create_dataset(
                        'group-metadata/%s' % key,
                        shape=(1,), dtype=H5PY_VLEN_STR,
                        data=val, compression=compression)
                    grp_dataset.attrs['data_type'] = datatype

            grp.create_group('matrix')
            grp.create_dataset('matrix/data', shape=(len_data,),
                               dtype=np.float64,
                               data=self._data.data,
                               compression=compression)
            grp.create_dataset('matrix/indices', shape=(len_data,),
                               dtype=np.int32,
                               data=self._data.indices,
                               compression=compression)
            grp.create_dataset('matrix/indptr', shape=(len_indptr,),
                               dtype=np.int32,
                               data=self._data.indptr,
                               compression=compression)

            if len_ids > 0:
                # if we store IDs in the table as numpy arrays then this store
                # is cleaner, as is the parse
                grp.create_dataset('ids', shape=(len_ids,),
                                   dtype=H5PY_VLEN_STR,
                                   data=[i.encode('utf8') for i in ids],
                                   compression=compression)
            else:
                # Empty H5PY_VLEN_STR datasets are not supported.
                grp.create_dataset('ids', shape=(0, ), data=[],
                                   compression=compression)

    @classmethod
    def from_json(self, json_table, data_pump=None,
                  input_is_dense=False):
        """Parse a biom otu table type

        Parameters
        ----------
        json_table : dict
            A JSON object or dict that represents the BIOM table
        data_pump : tuple or None
            A secondary source of data
        input_is_dense : bool
            If `True`, the data contained will be interpretted as dense

        Returns
        -------
        Table

        Examples
        --------
        >>> from biom import Table
        >>> json_obj = {"id": "None",
        ...             "format": "Biological Observation Matrix 1.0.0",
        ...             "format_url": "http://biom-format.org",
        ...             "generated_by": "foo",
        ...             "type": "OTU table",
        ...             "date": "2014-06-03T14:24:40.884420",
        ...             "matrix_element_type": "float",
        ...             "shape": [5, 6],
        ...             "data": [[0,2,1.0],
        ...                      [1,0,5.0],
        ...                      [1,1,1.0],
        ...                      [1,3,2.0],
        ...                      [1,4,3.0],
        ...                      [1,5,1.0],
        ...                      [2,2,1.0],
        ...                      [2,3,4.0],
        ...                      [2,5,2.0],
        ...                      [3,0,2.0],
        ...                      [3,1,1.0],
        ...                      [3,2,1.0],
        ...                      [3,5,1.0],
        ...                      [4,1,1.0],
        ...                      [4,2,1.0]],
        ...             "rows": [{"id": "GG_OTU_1", "metadata": None},
        ...                      {"id": "GG_OTU_2", "metadata": None},
        ...                      {"id": "GG_OTU_3", "metadata": None},
        ...                      {"id": "GG_OTU_4", "metadata": None},
        ...                      {"id": "GG_OTU_5", "metadata": None}],
        ...             "columns": [{"id": "Sample1", "metadata": None},
        ...                         {"id": "Sample2", "metadata": None},
        ...                         {"id": "Sample3", "metadata": None},
        ...                         {"id": "Sample4", "metadata": None},
        ...                         {"id": "Sample5", "metadata": None},
        ...                         {"id": "Sample6", "metadata": None}]
        ...             }
        >>> t = Table.from_json(json_obj)

        """
        sample_ids = [col['id'] for col in json_table['columns']]
        sample_metadata = [col['metadata'] for col in json_table['columns']]
        obs_ids = [row['id'] for row in json_table['rows']]
        obs_metadata = [row['metadata'] for row in json_table['rows']]
        dtype = MATRIX_ELEMENT_TYPE[json_table['matrix_element_type']]
        if 'matrix_type' in json_table:
            if json_table['matrix_type'] == 'dense':
                input_is_dense = True
            else:
                input_is_dense = False
        type_ = json_table['type']

        if data_pump is None:
            table_obj = Table(json_table['data'], obs_ids, sample_ids,
                              obs_metadata, sample_metadata,
                              shape=json_table['shape'],
                              dtype=dtype,
                              type=type_,
                              generated_by=json_table['generated_by'],
                              input_is_dense=input_is_dense)
        else:
            table_obj = Table(data_pump, obs_ids, sample_ids,
                              obs_metadata, sample_metadata,
                              shape=json_table['shape'],
                              dtype=dtype,
                              type=type_,
                              generated_by=json_table['generated_by'],
                              input_is_dense=input_is_dense)
        return table_obj

    def to_json(self, generated_by, direct_io=None):
        """Returns a JSON string representing the table in BIOM format.

        Parameters
        ----------
        generated_by : str
            a string describing the software used to build the table
        direct_io : file or file-like object, optional
            Defaults to ``None``. Must implementing a ``write`` function. If
            `direct_io` is not ``None``, the final output is written directly
            to `direct_io` during processing.

        Returns
        -------
        str
            A JSON-formatted string representing the biom table
        """
        if not isinstance(generated_by, string_types):
            raise TableException("Must specify a generated_by string")

        # Fill in top-level metadata.
        if direct_io:
            direct_io.write(u'{')
            direct_io.write(u'"id": "%s",' % str(self.table_id))
            direct_io.write(
                u'"format": "%s",' %
                get_biom_format_version_string((1, 0)))  # JSON table -> 1.0.0
            direct_io.write(
                u'"format_url": "%s",' %
                get_biom_format_url_string())
            direct_io.write(u'"generated_by": "%s",' % generated_by)
            direct_io.write(u'"date": "%s",' % datetime.now().isoformat())
        else:
            id_ = u'"id": "%s",' % str(self.table_id)
            format_ = u'"format": "%s",' % get_biom_format_version_string(
                (1, 0))  # JSON table -> 1.0.0
            format_url = u'"format_url": "%s",' % get_biom_format_url_string()
            generated_by = u'"generated_by": "%s",' % generated_by
            date = u'"date": "%s",' % datetime.now().isoformat()

        # Determine if we have any data in the matrix, and what the shape of
        # the matrix is.
        try:
            num_rows, num_cols = self.shape
        except:  # noqa
            num_rows = num_cols = 0
        has_data = True if num_rows > 0 and num_cols > 0 else False

        # Default the matrix element type to test to be an integer in case we
        # don't have any data in the matrix to test.
        test_element = 0
        if has_data:
            test_element = self[0, 0]

        # Determine the type of elements the matrix is storing.
        if isinstance(test_element, int):
            matrix_element_type = u"int"
        elif isinstance(test_element, float):
            matrix_element_type = u"float"
        elif isinstance(test_element, string_types):
            matrix_element_type = u"str"
        else:
            raise TableException("Unsupported matrix data type.")

        # Fill in details about the matrix.
        if direct_io:
            direct_io.write(
                u'"matrix_element_type": "%s",' %
                matrix_element_type)
            direct_io.write(u'"shape": [%d, %d],' % (num_rows, num_cols))
        else:
            matrix_element_type = u'"matrix_element_type": "%s",' % \
                matrix_element_type
            shape = u'"shape": [%d, %d],' % (num_rows, num_cols)

        # Fill in the table type
        if self.type is None:
            type_ = u'"type": null,'
        else:
            type_ = u'"type": "%s",' % self.type

        if direct_io:
            direct_io.write(type_)

        # Fill in details about the rows in the table and fill in the matrix's
        # data. BIOM 2.0+ is now only sparse
        if direct_io:
            direct_io.write(u'"matrix_type": "sparse",')
            direct_io.write(u'"data": [')
        else:
            matrix_type = u'"matrix_type": "sparse",'
            data = [u'"data": [']

        max_row_idx = len(self.ids(axis='observation')) - 1
        max_col_idx = len(self.ids()) - 1
        rows = [u'"rows": [']
        have_written = False
        for obs_index, obs in enumerate(self.iter(axis='observation')):
            # i'm crying on the inside
            if obs_index != max_row_idx:
                rows.append(u'{"id": %s, "metadata": %s},' % (dumps(obs[1]),
                                                              dumps(obs[2])))
            else:
                rows.append(u'{"id": %s, "metadata": %s}],' % (dumps(obs[1]),
                                                               dumps(obs[2])))

            # turns out its a pain to figure out when to place commas. the
            # simple work around, at the expense of a little memory
            # (bound by the number of samples) is to build of what will be
            # written, and then add in the commas where necessary.
            built_row = []
            for col_index, val in enumerate(obs[0]):
                if float(val) != 0.0:
                    built_row.append(u"[%d,%d,%r]" % (obs_index, col_index,
                                                      val))
            if built_row:
                # if we have written a row already, its safe to add a comma
                if have_written:
                    if direct_io:
                        direct_io.write(u',')
                    else:
                        data.append(u',')
                if direct_io:
                    direct_io.write(u','.join(built_row))
                else:
                    data.append(u','.join(built_row))

                have_written = True

        # finalize the data block
        if direct_io:
            direct_io.write(u"],")
        else:
            data.append(u"],")

        # Fill in details about the columns in the table.
        columns = [u'"columns": [']
        for samp_index, samp in enumerate(self.iter()):
            if samp_index != max_col_idx:
                columns.append(u'{"id": %s, "metadata": %s},' % (
                    dumps(samp[1]), dumps(samp[2])))
            else:
                columns.append(u'{"id": %s, "metadata": %s}]' % (
                    dumps(samp[1]), dumps(samp[2])))

        if rows[0] == u'"rows": [' and len(rows) == 1:
            # empty table case
            rows = [u'"rows": [],']
            columns = [u'"columns": []']

        rows = u''.join(rows)
        columns = u''.join(columns)

        if direct_io:
            direct_io.write(rows)
            direct_io.write(columns)
            direct_io.write(u'}')
        else:
            return u"{%s}" % ''.join([id_, format_, format_url, matrix_type,
                                      generated_by, date, type_,
                                      matrix_element_type, shape,
                                      u''.join(data), rows, columns])

    @staticmethod
    def from_tsv(lines, obs_mapping, sample_mapping,
                 process_func, **kwargs):
        """Parse a tab separated (observation x sample) formatted BIOM table

        Parameters
        ----------
        lines : list, or file-like object
            The tab delimited data to parse
        obs_mapping : dict or None
            The corresponding observation metadata
        sample_mapping : dict or None
            The corresponding sample metadata
        process_func : function
            A function to transform the observation metadata

        Returns
        -------
        biom.Table
            A BIOM ``Table`` object

        Examples
        --------
        Parse tab separated data into a table:

        >>> from biom.table import Table
        >>> from io import StringIO
        >>> tsv = 'a\\tb\\tc\\n1\\t2\\t3\\n4\\t5\\t6'
        >>> tsv_fh = StringIO(tsv)
        >>> func = lambda x : x
        >>> test_table = Table.from_tsv(tsv_fh, None, None, func)
        """
        (sample_ids, obs_ids, data, t_md,
            t_md_name) = Table._extract_data_from_tsv(lines, **kwargs)

        # if we have it, keep it
        if t_md is None:
            obs_metadata = None
        else:
            obs_metadata = [{t_md_name: process_func(v)} for v in t_md]

        if sample_mapping is None:
            sample_metadata = None
        else:
            sample_metadata = [sample_mapping[sample_id]
                               for sample_id in sample_ids]

        # will override any metadata from parsed table
        if obs_mapping is not None:
            obs_metadata = [obs_mapping[obs_id] for obs_id in obs_ids]

        return Table(data, obs_ids, sample_ids, obs_metadata, sample_metadata)

    @staticmethod
    def _extract_data_from_tsv(lines, delim='\t', dtype=float, md_parse=None):
        """Parse a classic table into (sample_ids, obs_ids, data, metadata,
        name)

        Parameters
        ----------
        lines: list or file-like object
            delimted data to parse
        delim: string
            delimeter in file lines
        dtype: type
        md_parse:  function or None
            funtion used to parse metdata

        Returns
        -------
        list
            sample_ids
        list
            observation_ids
        array
            data
        list
            metadata
        string
            column name if last column is non-numeric

        Notes
        ------
        This is intended to be close to how QIIME classic OTU tables are parsed
        with the exception of the additional md_name field

        This function is ported from QIIME (http://www.qiime.org), previously
        named parse_classic_otu_table. QIIME is a GPL project, but we obtained
        permission from the authors of this function to port it to the BIOM
        Format project (and keep it under BIOM's BSD license).

        .. shownumpydoc
        """
        if not isinstance(lines, list):
            try:
                hasattr(lines, 'seek')
            except AttributeError:
                raise RuntimeError(
                    "Input needs to support seek or be indexable")

        # find header, the first line that is not empty and does not start
        # with a #
        header = False
        list_index = 0
        for line in lines:
            if not line.strip():
                continue
            if not line.startswith('#'):
                # Covers the case where the first line is the header
                # and there is no indication of it (no comment character)
                if not header:
                    header = line.strip().split(delim)[1:]
                    data_start = list_index + 1
                else:
                    data_start = list_index
                break
            list_index += 1
            header = line.strip().split(delim)[1:]
        # If the first line is the header, then we need to get the next
        # line for the "last column" check
        if isinstance(lines, list):
            line = lines[data_start]
        else:
            lines.seek(0)
            for index in range(0, data_start + 1):
                line = lines.readline()

        # attempt to determine if the last column is non-numeric, ie, metadata
        first_values = line.strip().split(delim)
        last_value = first_values[-1]
        last_column_is_numeric = True

        if '.' in last_value:
            try:
                float(last_value)
            except ValueError:
                last_column_is_numeric = False
        else:
            try:
                int(last_value)
            except ValueError:
                last_column_is_numeric = False

        # determine sample ids
        if last_column_is_numeric:
            md_name = None
            metadata = None
            samp_ids = header[:]
        else:
            md_name = header[-1]
            metadata = []
            samp_ids = header[:-1]

        data = []
        obs_ids = []
        row_number = 0

        # Go back to the beginning if it is a file:
        if hasattr(lines, 'seek'):
            lines.seek(0)
            for index in range(0, data_start):
                line = lines.readline()
        else:
            lines = lines[data_start:]

        for lineno, line in enumerate(lines, data_start):
            line = line.strip()
            if not line:
                continue
            if line.startswith('#'):
                continue

            fields = line.strip().split(delim)
            obs_ids.append(fields[0])

            if last_column_is_numeric:
                try:
                    values = list(map(dtype, fields[1:]))
                except ValueError:
                    badval, badidx = _identify_bad_value(dtype, fields[1:])
                    msg = "Invalid value on line %d, column %d, value %s"
                    raise TypeError(msg % (lineno, badidx+1, badval))
            else:
                try:
                    values = list(map(dtype, fields[1:-1]))
                except ValueError:
                    badval, badidx = _identify_bad_value(dtype, fields[1:])
                    msg = "Invalid value on line %d, column %d, value %s"
                    raise TypeError(msg % (lineno, badidx+1, badval))

                if md_parse is not None:
                    metadata.append(md_parse(fields[-1]))
                else:
                    metadata.append(fields[-1])
            for column_number in range(0, len(values)):
                if values[column_number] != dtype(0):
                    data.append([row_number, column_number,
                                 values[column_number]])
            row_number += 1
        return samp_ids, obs_ids, data, metadata, md_name

    def to_tsv(self, header_key=None, header_value=None,
               metadata_formatter=str, observation_column_name='#OTU ID'):
        """Return self as a string in tab delimited form

        Default ``str`` output for the ``Table`` is just row/col ids and table
        data without any metadata

        Parameters
        ----------
        header_key : str or ``None``, optional
            Defaults to ``None``
        header_value : str or ``None``, optional
            Defaults to ``None``
        metadata_formatter : function, optional
            Defaults to ``str``.  a function which takes a metadata entry and
            returns a formatted version that should be written to file
        observation_column_name : str, optional
            Defaults to "#OTU ID". The name of the first column in the output
            table, corresponding to the observation IDs.

        Returns
        -------
        str
            tab delimited representation of the Table

        Examples
        --------

        >>> import numpy as np
        >>> from biom.table import Table

        Create a 2x3 BIOM table, with observation metadata and no sample
        metadata:

        >>> data = np.asarray([[0, 0, 1], [1, 3, 42]])
        >>> table = Table(data, ['O1', 'O2'], ['S1', 'S2', 'S3'],
        ...               [{'foo': 'bar'}, {'x': 'y'}], None)
        >>> print(table.to_tsv()) # doctest: +NORMALIZE_WHITESPACE
        # Constructed from biom file
        #OTU ID	S1	S2	S3
        O1	0.0	0.0	1.0
        O2	1.0	3.0	42.0
        """
        return self.delimited_self(u'\t', header_key, header_value,
                                   metadata_formatter,
                                   observation_column_name)


def coo_arrays_to_sparse(data, dtype=np.float64, shape=None):
    """Map directly on to the coo_matrix constructor

    Parameters
    ----------
    data : tuple
        data must be (values, (rows, cols))
    dtype : type, optional
        Defaults to ``np.float64``
    shape : tuple or ``None``, optional
        Defaults to ``None``. If `shape` is ``None``, shape will be determined
        automatically from `data`.
    """
    if shape is None:
        values, (rows, cols) = data
        n_rows = max(rows) + 1
        n_cols = max(cols) + 1
    else:
        n_rows, n_cols = shape

    # coo_matrix allows zeros to be added as data, and this affects
    # nnz, items, and iteritems. Clean them out here, as this is
    # the only time these zeros can creep in.
    # Note: coo_matrix allows duplicate entries; the entries will
    # be summed when converted. Not really sure how we want to
    # handle this generally within BIOM- I'm okay with leaving it
    # as undefined behavior for now.
    matrix = coo_matrix(data, shape=(n_rows, n_cols), dtype=dtype)
    matrix = matrix.tocsr()
    matrix.eliminate_zeros()
    return matrix


def list_list_to_sparse(data, dtype=float, shape=None):
    """Convert a list of lists into a scipy.sparse matrix.

    Parameters
    ----------
    data : iterable of iterables
        `data` should be in the format [[row, col, value], ...]
    dtype : type, optional
        defaults to ``float``
    shape : tuple or ``None``, optional
        Defaults to ``None``. If `shape` is ``None``, shape will be determined
        automatically from `data`.

    Returns
    -------
    scipy.csr_matrix
        The newly generated matrix
    """
    rows, cols, values = zip(*data)

    if shape is None:
        n_rows = max(rows) + 1
        n_cols = max(cols) + 1
    else:
        n_rows, n_cols = shape

    matrix = coo_matrix((values, (rows, cols)), shape=(n_rows, n_cols),
                        dtype=dtype)
    matrix = matrix.tocsr()
    matrix.eliminate_zeros()
    return matrix


def nparray_to_sparse(data, dtype=float):
    """Convert a numpy array to a scipy.sparse matrix.

    Parameters
    ----------
    data : numpy.array
        The data to convert into a sparse matrix
    dtype : type, optional
        Defaults to ``float``. The type of data to be represented.

    Returns
    -------
    scipy.csr_matrix
        The newly generated matrix
    """
    if data.shape == (0,):
        # an empty vector. Note, this short circuit is necessary as calling
        # csr_matrix([], shape=(0, 0), dtype=dtype) will result in a matrix
        # has a shape of (1, 0).
        return csr_matrix((0, 0), dtype=dtype)
    elif data.shape in ((1, 0), (0, 1)) and data.size == 0:
        # an empty matrix. This short circuit is necessary for the same reason
        # as the empty vector. While a (1, 0) matrix is _empty_, this does
        # confound code that assumes that (1, 0) means there might be metadata
        # or IDs associated with that singular row
        return csr_matrix((0, 0), dtype=dtype)
    elif len(data.shape) == 1:
        # a vector
        shape = (1, data.shape[0])
    else:
        shape = data.shape

    matrix = coo_matrix(data, shape=shape, dtype=dtype)
    matrix = matrix.tocsr()
    matrix.eliminate_zeros()
    return matrix


def list_nparray_to_sparse(data, dtype=float):
    """Takes a list of numpy arrays and creates a scipy.sparse matrix.

    Parameters
    ----------
    data : iterable of numpy.array
        The data to convert into a sparse matrix
    dtype : type, optional
        Defaults to ``float``. The type of data to be represented.

    Returns
    -------
    scipy.csr_matrix
        The newly generated matrix
    """
    matrix = coo_matrix(data, shape=(len(data), len(data[0])), dtype=dtype)
    matrix = matrix.tocsr()
    matrix.eliminate_zeros()
    return matrix


def list_sparse_to_sparse(data, dtype=float):
    """Takes a list of scipy.sparse matrices and creates a scipy.sparse mat.

    Parameters
    ----------
    data : iterable of scipy.sparse matrices
        The data to convert into a sparse matrix
    dtype : type, optional
        Defaults to ``float``. The type of data to be represented.

    Returns
    -------
    scipy.csr_matrix
        The newly generated matrix
    """
    if isspmatrix(data[0]):
        if data[0].shape[0] > data[0].shape[1]:
            n_cols = len(data)
            n_rows = data[0].shape[0]
        else:
            n_rows = len(data)
            n_cols = data[0].shape[1]
    else:
        all_keys = flatten([d.keys() for d in data])
        n_rows = max(all_keys, key=itemgetter(0))[0] + 1
        n_cols = max(all_keys, key=itemgetter(1))[1] + 1
        if n_rows > n_cols:
            n_cols = len(data)
        else:
            n_rows = len(data)

    data = vstack(data)
    matrix = coo_matrix(data, shape=(n_rows, n_cols),
                        dtype=dtype)
    matrix = matrix.tocsr()
    matrix.eliminate_zeros()
    return matrix


def list_dict_to_sparse(data, dtype=float):
    """Takes a list of dict {(row,col):val} and creates a scipy.sparse mat.

    Parameters
    ----------
    data : iterable of dicts
        The data to convert into a sparse matrix
    dtype : type, optional
        Defaults to ``float``. The type of data to be represented.

    Returns
    -------
    scipy.csr_matrix
        The newly generated matrix
    """
    if isspmatrix(data[0]):
        if data[0].shape[0] > data[0].shape[1]:
            is_col = True
            n_cols = len(data)
            n_rows = data[0].shape[0]
        else:
            is_col = False
            n_rows = len(data)
            n_cols = data[0].shape[1]
    else:
        all_keys = flatten([d.keys() for d in data])
        n_rows = max(all_keys, key=itemgetter(0))[0] + 1
        n_cols = max(all_keys, key=itemgetter(1))[1] + 1
        if n_rows > n_cols:
            is_col = True
            n_cols = len(data)
        else:
            is_col = False
            n_rows = len(data)

    rows = []
    cols = []
    vals = []
    for row_idx, row in enumerate(data):
        for (row_val, col_idx), val in row.items():
            if is_col:
                # transpose
                rows.append(row_val)
                cols.append(row_idx)
                vals.append(val)
            else:
                rows.append(row_idx)
                cols.append(col_idx)
                vals.append(val)

    matrix = coo_matrix((vals, (rows, cols)), shape=(n_rows, n_cols),
                        dtype=dtype)
    matrix = matrix.tocsr()
    matrix.eliminate_zeros()
    return matrix


def dict_to_sparse(data, dtype=float, shape=None):
    """Takes a dict {(row,col):val} and creates a scipy.sparse matrix.

    Parameters
    ----------
    data : dict
        The data to convert into a sparse matrix
    dtype : type, optional
        Defaults to ``float``. The type of data to be represented.

    Returns
    -------
    scipy.csr_matrix
        The newly generated matrix
    """
    if shape is None:
        n_rows = max(data.keys(), key=itemgetter(0))[0] + 1
        n_cols = max(data.keys(), key=itemgetter(1))[1] + 1
    else:
        n_rows, n_cols = shape

    rows = []
    cols = []
    vals = []
    for (r, c), v in viewitems(data):
        rows.append(r)
        cols.append(c)
        vals.append(v)

    return coo_arrays_to_sparse((vals, (rows, cols)),
                                shape=(n_rows, n_cols), dtype=dtype)