/usr/include/vigra/hdf5impex.hxx is in libvigraimpex-dev 1.10.0+dfsg-11ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 | /************************************************************************/
/* */
/* Copyright 2009 by Michael Hanselmann and Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_HDF5IMPEX_HXX
#define VIGRA_HDF5IMPEX_HXX
#include <string>
#define H5Gcreate_vers 2
#define H5Gopen_vers 2
#define H5Dopen_vers 2
#define H5Dcreate_vers 2
#define H5Acreate_vers 2
#include <hdf5.h>
#if (H5_VERS_MAJOR == 1 && H5_VERS_MINOR <= 6)
# ifndef H5Gopen
# define H5Gopen(a, b, c) H5Gopen(a, b)
# endif
# ifndef H5Gcreate
# define H5Gcreate(a, b, c, d, e) H5Gcreate(a, b, 1)
# endif
# ifndef H5Dopen
# define H5Dopen(a, b, c) H5Dopen(a, b)
# endif
# ifndef H5Dcreate
# define H5Dcreate(a, b, c, d, e, f, g) H5Dcreate(a, b, c, d, f)
# endif
# ifndef H5Acreate
# define H5Acreate(a, b, c, d, e, f) H5Acreate(a, b, c, d, e)
# endif
# ifndef H5Pset_obj_track_times
# define H5Pset_obj_track_times(a, b) do {} while (0)
# endif
# include <H5LT.h>
#else
# include <hdf5_hl.h>
#endif
#include "impex.hxx"
#include "multi_array.hxx"
#include "multi_iterator_coupled.hxx"
#include "multi_impex.hxx"
#include "utilities.hxx"
#include "error.hxx"
#include <algorithm>
#if defined(_MSC_VER)
# include <io.h>
#else
# include <unistd.h>
#endif
namespace vigra {
/** \addtogroup VigraHDF5Impex Import/Export of Images and Arrays in HDF5 Format
Supports arrays with arbitrary element types and arbitrary many dimensions.
See the <a href="http://www.hdfgroup.org/HDF5/">HDF5 Website</a> for more
information on the HDF5 file format.
*/
//@{
/** \brief Check if given filename refers to a HDF5 file.
*/
inline bool isHDF5(char const * filename)
{
#ifdef _MSC_VER
return _access(filename, 0) != -1 && H5Fis_hdf5(filename);
#else
return access(filename, F_OK) == 0 && H5Fis_hdf5(filename);
#endif
}
/** \brief Wrapper for hid_t objects.
Newly created or opened HDF5 handles are usually stored as objects of type 'hid_t'. When the handle
is no longer needed, the appropriate close function must be called. However, if a function is
aborted by an exception, this is difficult to ensure. Class HDF5Handle is a smart pointer that
solves this problem by calling the close function in the destructor (This is analogous to how
VIGRA_UNIQUE_PTR calls 'delete' on the contained pointer). A pointer to the close function must be
passed to the constructor, along with an error message that is raised when creation/opening fails.
Since HDF5Handle objects are convertible to hid_t, they can be used in the code in place
of the latter.
<b>Usage:</b>
\code
HDF5Handle file_id(H5Fopen(filename, H5F_ACC_RDWR, H5P_DEFAULT),
&H5Fclose,
"Error message.");
... // use file_id in the same way as a plain hid_t object
\endcode
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
*/
class HDF5Handle
{
public:
typedef herr_t (*Destructor)(hid_t);
private:
hid_t handle_;
Destructor destructor_;
public:
/** \brief Default constructor.
Creates a NULL handle.
**/
HDF5Handle()
: handle_( 0 ),
destructor_(0)
{}
/** \brief Create a wrapper for a hid_t object.
The hid_t object \a h is assumed to be the return value of an open or create function.
It will be closed with the given close function \a destructor as soon as this
HDF5Handle is destructed, except when \a destructor is a NULL pointer (in which
case nothing happens at destruction time). If \a h has a value that indicates
failed opening or creation (by HDF5 convention, this means if it is a negative number),
an exception is raised by calling <tt>vigra_fail(error_message)</tt>.
<b>Usage:</b>
\code
HDF5Handle file_id(H5Fopen(filename, H5F_ACC_RDWR, H5P_DEFAULT),
&H5Fclose,
"Error message.");
... // use file_id in the same way
\endcode
*/
HDF5Handle(hid_t h, Destructor destructor, const char * error_message)
: handle_( h ),
destructor_(destructor)
{
if(handle_ < 0)
vigra_fail(error_message);
}
/** \brief Copy constructor.
Hands over ownership of the RHS handle (analogous to VIGRA_UNIQUE_PTR).
*/
HDF5Handle(HDF5Handle const & h)
: handle_( h.handle_ ),
destructor_(h.destructor_)
{
const_cast<HDF5Handle &>(h).handle_ = 0;
}
/** \brief Assignment.
Calls close() for the LHS handle and hands over ownership of the
RHS handle (analogous to VIGRA_UNIQUE_PTR).
*/
HDF5Handle & operator=(HDF5Handle const & h)
{
if(h.handle_ != handle_)
{
close();
handle_ = h.handle_;
destructor_ = h.destructor_;
const_cast<HDF5Handle &>(h).handle_ = 0;
}
return *this;
}
/** \brief Destructor.
Calls close() for the contained handle.
*/
~HDF5Handle()
{
close();
}
/** \brief Explicitly call the stored function (if one has been stored within
this object) for the contained handle and set the handle to NULL.
*/
herr_t close()
{
herr_t res = 1;
if(handle_ && destructor_)
res = (*destructor_)(handle_);
handle_ = 0;
return res;
}
/** \brief Get a temporary hid_t object for the contained handle.
Do not call a close function on the return value - a crash will be likely
otherwise.
*/
hid_t get() const
{
return handle_;
}
/** \brief Convert to a plain hid_t object.
This function ensures that hid_t objects can be transparently replaced with
HDF5Handle objects in user code. Do not call a close function on the return
value - a crash will be likely otherwise.
*/
operator hid_t() const
{
return handle_;
}
/** \brief Equality comparison of the contained handle.
*/
bool operator==(HDF5Handle const & h) const
{
return handle_ == h.handle_;
}
/** \brief Equality comparison of the contained handle.
*/
bool operator==(hid_t h) const
{
return handle_ == h;
}
/** \brief Inequality comparison of the contained handle.
*/
bool operator!=(HDF5Handle const & h) const
{
return handle_ != h.handle_;
}
/** \brief Inequality comparison of the contained handle.
*/
bool operator!=(hid_t h) const
{
return handle_ != h;
}
};
/********************************************************/
/* */
/* HDF5ImportInfo */
/* */
/********************************************************/
/** \brief Argument object for the function readHDF5().
See \ref readHDF5() for a usage example. This object must be
used to read an image or array from an HDF5 file
and enquire about its properties.
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
*/
class HDF5ImportInfo
{
public:
enum PixelType { UINT8, UINT16, UINT32, UINT64,
INT8, INT16, INT32, INT64,
FLOAT, DOUBLE };
/** Construct HDF5ImportInfo object.
The dataset \a pathInFile in the HDF5 file \a filename is accessed to
read its properties. \a pathInFile may contain '/'-separated group
names, but must end with the name of the desired dataset:
\code
HDF5ImportInfo info(filename, "/group1/group2/my_dataset");
\endcode
*/
VIGRA_EXPORT HDF5ImportInfo( const char* filePath, const char* pathInFile );
VIGRA_EXPORT ~HDF5ImportInfo();
/** Get the filename of this HDF5 object.
*/
VIGRA_EXPORT const std::string& getFilePath() const;
/** Get the dataset's full name in the HDF5 file.
*/
VIGRA_EXPORT const std::string& getPathInFile() const;
/** Get a handle to the file represented by this info object.
*/
VIGRA_EXPORT hid_t getH5FileHandle() const;
/** Get a handle to the dataset represented by this info object.
*/
VIGRA_EXPORT hid_t getDatasetHandle() const;
/** Get the number of dimensions of the dataset represented by this info object.
*/
VIGRA_EXPORT MultiArrayIndex numDimensions() const;
/** Get the shape of the dataset represented by this info object.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This function therefore reverses the axis
order relative to the file contents. That is, when the axes in the file are
ordered as 'z', 'y', 'x', this function will return the shape in the order
'x', 'y', 'z'.
*/
VIGRA_EXPORT ArrayVector<hsize_t> const & shape() const
{
return m_dims;
}
/** Get the shape (length) of the dataset along dimension \a dim.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This function therefore reverses the axis
order relative to the file contents. That is, when the axes in the file are
ordered as 'z', 'y', 'x', this function will return the shape in the order
'x', 'y', 'z'.
*/
VIGRA_EXPORT MultiArrayIndex shapeOfDimension(const int dim) const;
/** Query the pixel type of the dataset.
Possible values are:
<DL>
<DT>"INT8"<DD> 8-bit signed integer (unsigned char)
<DT>"UINT8"<DD> 8-bit unsigned integer (unsigned char)
<DT>"INT16"<DD> 16-bit signed integer (short)
<DT>"UINT16"<DD> 16-bit unsigned integer (unsigned short)
<DT>"INT32"<DD> 32-bit signed integer (long)
<DT>"UINT32"<DD> 32-bit unsigned integer (unsigned long)
<DT>"INT64"<DD> 64-bit signed integer (long long)
<DT>"UINT64"<DD> 64-bit unsigned integer (unsigned long long)
<DT>"FLOAT"<DD> 32-bit floating point (float)
<DT>"DOUBLE"<DD> 64-bit floating point (double)
</DL>
*/
VIGRA_EXPORT const char * getPixelType() const;
/** Query the pixel type of the dataset.
Same as getPixelType(), but the result is returned as a
ImageImportInfo::PixelType enum. This is useful to implement
a switch() on the pixel type.
Possible values are:
<DL>
<DT>UINT8<DD> 8-bit unsigned integer (unsigned char)
<DT>INT16<DD> 16-bit signed integer (short)
<DT>UINT16<DD> 16-bit unsigned integer (unsigned short)
<DT>INT32<DD> 32-bit signed integer (long)
<DT>UINT32<DD> 32-bit unsigned integer (unsigned long)
<DT>FLOAT<DD> 32-bit floating point (float)
<DT>DOUBLE<DD> 64-bit floating point (double)
</DL>
*/
VIGRA_EXPORT PixelType pixelType() const;
private:
HDF5Handle m_file_handle, m_dataset_handle;
std::string m_filename, m_path, m_pixeltype;
hssize_t m_dimensions;
ArrayVector<hsize_t> m_dims;
};
namespace detail {
template<class type>
inline hid_t getH5DataType()
{
std::runtime_error("getH5DataType(): invalid type");
return 0;
}
#define VIGRA_H5_DATATYPE(type, h5type) \
template<> \
inline hid_t getH5DataType<type>() \
{ return h5type;}
VIGRA_H5_DATATYPE(char, H5T_NATIVE_CHAR)
VIGRA_H5_DATATYPE(float, H5T_NATIVE_FLOAT)
VIGRA_H5_DATATYPE(double, H5T_NATIVE_DOUBLE)
VIGRA_H5_DATATYPE(long double, H5T_NATIVE_LDOUBLE)
// char arrays with flexible length require 'handcrafted' H5 datatype
template<>
inline hid_t getH5DataType<char*>()
{
hid_t stringtype = H5Tcopy (H5T_C_S1);
H5Tset_size(stringtype, H5T_VARIABLE);
return stringtype;
}
template<>
inline hid_t getH5DataType<const char*>()
{
hid_t stringtype = H5Tcopy (H5T_C_S1);
H5Tset_size(stringtype, H5T_VARIABLE);
return stringtype;
}
#undef VIGRA_H5_DATATYPE
template <unsigned int SIZE>
struct HDF5TypeBySize;
template <>
struct HDF5TypeBySize<1>
{
static hid_t signed_type() { return H5T_NATIVE_INT8; }
static hid_t unsigned_type() { return H5T_NATIVE_UINT8; }
};
template <>
struct HDF5TypeBySize<2>
{
static hid_t signed_type() { return H5T_NATIVE_INT16; }
static hid_t unsigned_type() { return H5T_NATIVE_UINT16; }
};
template <>
struct HDF5TypeBySize<4>
{
static hid_t signed_type() { return H5T_NATIVE_INT32; }
static hid_t unsigned_type() { return H5T_NATIVE_UINT32; }
};
template <>
struct HDF5TypeBySize<8>
{
static hid_t signed_type() { return H5T_NATIVE_INT64; }
static hid_t unsigned_type() { return H5T_NATIVE_UINT64; }
};
#define VIGRA_H5_SIGNED_DATATYPE(type) \
template<> \
inline hid_t getH5DataType<type>() \
{ return HDF5TypeBySize<sizeof(type)>::signed_type(); }
VIGRA_H5_SIGNED_DATATYPE(signed char)
VIGRA_H5_SIGNED_DATATYPE(signed short)
VIGRA_H5_SIGNED_DATATYPE(signed int)
VIGRA_H5_SIGNED_DATATYPE(signed long)
VIGRA_H5_SIGNED_DATATYPE(signed long long)
#undef VIGRA_H5_SIGNED_DATATYPE
#define VIGRA_H5_UNSIGNED_DATATYPE(type) \
template<> \
inline hid_t getH5DataType<type>() \
{ return HDF5TypeBySize<sizeof(type)>::unsigned_type(); }
VIGRA_H5_UNSIGNED_DATATYPE(unsigned char)
VIGRA_H5_UNSIGNED_DATATYPE(unsigned short)
VIGRA_H5_UNSIGNED_DATATYPE(unsigned int)
VIGRA_H5_UNSIGNED_DATATYPE(unsigned long)
VIGRA_H5_UNSIGNED_DATATYPE(unsigned long long)
#undef VIGRA_H5_UNSIGNED_DATATYPE
#if 0
template<>
inline hid_t getH5DataType<FFTWComplex<float> >()
{
hid_t complex_id = H5Tcreate (H5T_COMPOUND, sizeof (FFTWComplex<float>));
H5Tinsert (complex_id, "real", 0, H5T_NATIVE_FLOAT);
H5Tinsert (complex_id, "imaginary", sizeof(float), H5T_NATIVE_FLOAT);
return complex_id;
}
template<>
inline hid_t getH5DataType<FFTWComplex<double> >()
{
hid_t complex_id = H5Tcreate (H5T_COMPOUND, sizeof (FFTWComplex<double>));
H5Tinsert (complex_id, "real", 0, H5T_NATIVE_DOUBLE);
H5Tinsert (complex_id, "imaginary", sizeof(double), H5T_NATIVE_DOUBLE);
return complex_id;
}
#endif
} // namespace detail
// helper friend function for callback HDF5_ls_inserter_callback()
void HDF5_ls_insert(void*, const std::string &);
// callback function for ls(), called via HDF5File::H5Literate()
// see http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2
// for as to why.
VIGRA_EXPORT H5O_type_t HDF5_get_type(hid_t, const char*);
extern "C" VIGRA_EXPORT herr_t HDF5_ls_inserter_callback(hid_t, const char*, const H5L_info_t*, void*);
/********************************************************/
/* */
/* HDF5File */
/* */
/********************************************************/
/** \brief Access to HDF5 files
HDF5File provides a convenient way of accessing data in HDF5 files. vigra::MultiArray
structures of any dimension can be stored to / loaded from HDF5 files. Typical
HDF5 features like subvolume access, chunks and data compression are available,
string attributes can be attached to any dataset or group. Group- or dataset-handles
are encapsulated in the class and managed automatically. The internal file-system like
structure can be accessed by functions like "cd()" or "mkdir()".
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a VIGRA MultiArray,
whose indices represent the 'x'-, 'y'-, and 'z'-axis in that order, is reversed
upon writing to an HDF5 file, i.e. in the file the axis order is 'z', 'y', 'x'.
Likewise, the order is reversed upon reading.
<b>Example:</b>
Write the MultiArray out_multi_array to file. Change the current directory to
"/group" and read in the same MultiArray as in_multi_array.
\code
HDF5File file("/path/to/file",HDF5File::New);
file.mkdir("group");
file.write("/group/dataset", out_multi_array);
file.cd("/group");
file.read("dataset", in_multi_array);
\endcode
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
*/
class HDF5File
{
protected:
HDF5Handle fileHandle_;
// current group handle
HDF5Handle cGroupHandle_;
private:
// time tagging of datasets, turned off (= 0) by default.
int track_time;
// helper class for ls()
struct ls_closure
{
virtual void insert(const std::string &) = 0;
virtual ~ls_closure() {}
};
// datastructure to hold a list of dataset and group names
struct lsOpData : public ls_closure
{
std::vector<std::string> & objects;
lsOpData(std::vector<std::string> & o) : objects(o) {}
void insert(const std::string & x)
{
objects.push_back(x);
}
};
// (associative-)container closure
template<class Container>
struct ls_container_data : public ls_closure
{
Container & objects;
ls_container_data(Container & o) : objects(o) {}
void insert(const std::string & x)
{
objects.insert(std::string(x));
}
};
public:
// helper for callback HDF5_ls_inserter_callback(), used by ls()
friend void HDF5_ls_insert(void*, const std::string &);
/** \brief Set how a file is opened.
OpenMode::New creates a new file. If the file already exists, overwrite it.
OpenMode::Open opens a file for reading/writing. The file will be created,
if necessary.
*/
enum OpenMode {
New, // Create new empty file (existing file will be deleted).
Open, // Open file. Create if not existing.
OpenReadOnly // Open file in read-only mode.
};
/** \brief Default constructor.
A file can later be opened via the open() function.
If \a track_creation_times is non-zero, time tagging of datasets will be enabled (it is disabled
by default).
*/
HDF5File(int track_creation_times = 0)
: track_time(track_creation_times)
{}
/** \brief Open or create an HDF5File object.
Creates or opens HDF5 file with given filename.
The current group is set to "/".
Note that the HDF5File class is not copyable (the copy constructor is
private to enforce this).
*/
HDF5File(std::string filename, OpenMode mode, int track_creation_times = 0)
: track_time(track_creation_times)
{
open(filename, mode);
}
/** \brief The destructor flushes and closes the file.
*/
~HDF5File()
{
// The members fileHandle_ and cGroupHandle_ are automatically closed
// as they are of type HDF5Handle and are properly initialised.
// The closing of fileHandle_ implies flushing the file to
// the operating system, see
// http://www.hdfgroup.org/HDF5/doc/RM/RM_H5F.html#File-Close .
}
// copying is not permitted.
private:
HDF5File(const HDF5File &);
void operator=(const HDF5File &);
public:
/** \brief Open or create the given file in the given mode and set the group to "/".
If another file is currently open, it is first closed.
*/
void open(std::string filename, OpenMode mode)
{
close();
std::string errorMessage = "HDF5File.open(): Could not open or create file '" + filename + "'.";
fileHandle_ = HDF5Handle(createFile_(filename, mode), &H5Fclose, errorMessage.c_str());
cGroupHandle_ = HDF5Handle(openCreateGroup_("/"), &H5Gclose, "HDF5File.open(): Failed to open root group.");
}
/** \brief Close the current file.
*/
void close()
{
bool success = cGroupHandle_.close() >= 0 && fileHandle_.close() >= 0;
vigra_postcondition(success, "HDF5File.close() failed.");
}
/** \brief Change current group to "/".
*/
inline void root()
{
std::string message = "HDF5File::root(): Could not open group '/'.";
cGroupHandle_ = HDF5Handle(H5Gopen(fileHandle_, "/", H5P_DEFAULT),&H5Gclose,message.c_str());
}
/** \brief Change the current group.
Both absolute and relative group names are allowed.
*/
inline void cd(std::string groupName)
{
cGroupHandle_ = getGroupHandle(groupName, "HDF5File::cd()");
}
/** \brief Change the current group to its parent group.
Returns true if successful, false otherwise. If unsuccessful,
the group will not change.
*/
inline bool cd_up()
{
std::string groupName = currentGroupName_();
//do not try to move up if we already in "/"
if(groupName == "/"){
return false;
}
size_t lastSlash = groupName.find_last_of('/');
std::string parentGroup (groupName.begin(), groupName.begin()+lastSlash+1);
cd(parentGroup);
return true;
}
/** \brief Change the current group to its parent group.
Returns true if successful, false otherwise. If unsuccessful,
the group will not change.
*/
inline bool cd_up(int levels)
{
std::string groupName = currentGroupName_();
for(int i = 0; i<levels; i++)
{
if(!cd_up())
{
// restore old group if neccessary
if(groupName != currentGroupName_())
cd(groupName);
return false;
}
}
return true;
}
/** \brief Create a new group.
If the first character is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
inline void mkdir(std::string groupName)
{
std::string message = "HDF5File::mkdir(): Could not create group '" + groupName + "'.\n";
// make groupName clean
groupName = get_absolute_path(groupName);
HDF5Handle(openCreateGroup_(groupName.c_str()),&H5Gclose,message.c_str());
}
/** \brief Change the current group; create it if necessary.
If the first character is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
inline void cd_mk(std::string groupName)
{
std::string message = "HDF5File::cd_mk(): Could not create group '" + groupName + "'.";
// make groupName clean
groupName = get_absolute_path(groupName);
cGroupHandle_ = HDF5Handle(openCreateGroup_(groupName.c_str()),&H5Gclose,message.c_str());
}
// helper function for the various ls() variants.
void ls_H5Literate(ls_closure & data) const
{
H5Literate(cGroupHandle_, H5_INDEX_NAME, H5_ITER_NATIVE, NULL,
HDF5_ls_inserter_callback, static_cast<void*>(&data));
}
/** \brief List the contents of the current group.
The function returns a vector of strings holding the entries of the
current group. Only datasets and groups are listed, other objects
(e.g. datatypes) are ignored. Group names always have a trailing "/".
*/
inline std::vector<std::string> ls() const
{
std::vector<std::string> list;
lsOpData data(list);
ls_H5Literate(data);
return list;
}
/** \brief List the contents of the current group into a container-like
object via insert().
Only datasets and groups are inserted, other objects (e.g., datatypes) are ignored.
Group names always have a trailing "/".
The argument cont is presumably an associative container, however,
only its member function <tt>cont.insert(std::string)</tt> will be
called.
\param cont reference to a container supplying a member function
<tt>insert(const i_type &)</tt>, where <tt>i_type</tt>
is convertible to <tt>std::string</tt>.
*/
template<class Container>
void ls(Container & cont) const
{
ls_container_data<Container> data(cont);
ls_H5Literate(data);
}
/** \brief Get the path of the current group.
*/
inline std::string pwd() const
{
return currentGroupName_();
}
/** \brief Get the name of the associated file.
*/
inline std::string filename() const
{
return fileName_();
}
/** \brief Check if given datasetName exists.
*/
inline bool existsDataset(std::string datasetName)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
return (H5Lexists(fileHandle_, datasetName.c_str(), H5P_DEFAULT) > 0);
}
/** \brief Get the number of dimensions of a certain dataset
If the first character is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
hssize_t getDatasetDimensions(std::string datasetName)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
//Open dataset and dataspace
std::string errorMessage = "HDF5File::getDatasetDimensions(): Unable to open dataset '" + datasetName + "'.";
HDF5Handle datasetHandle = HDF5Handle(getDatasetHandle_(datasetName), &H5Dclose, errorMessage.c_str());
errorMessage = "HDF5File::getDatasetDimensions(): Unable to access dataspace.";
HDF5Handle dataspaceHandle(H5Dget_space(datasetHandle), &H5Sclose, errorMessage.c_str());
//return dimension information
return H5Sget_simple_extent_ndims(dataspaceHandle);
}
/** \brief Get the shape of each dimension of a certain dataset.
Normally, this function is called after determining the dimension of the
dataset using \ref getDatasetDimensions().
If the first character is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This function therefore reverses the axis
order relative to the file contents. That is, when the axes in the file are
ordered as 'z', 'y', 'x', this function will return the shape in the order
'x', 'y', 'z'.
*/
ArrayVector<hsize_t> getDatasetShape(std::string datasetName)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
//Open dataset and dataspace
std::string errorMessage = "HDF5File::getDatasetShape(): Unable to open dataset '" + datasetName + "'.";
HDF5Handle datasetHandle = HDF5Handle(getDatasetHandle_(datasetName), &H5Dclose, errorMessage.c_str());
errorMessage = "HDF5File::getDatasetShape(): Unable to access dataspace.";
HDF5Handle dataspaceHandle(H5Dget_space(datasetHandle), &H5Sclose, errorMessage.c_str());
//get dimension information
ArrayVector<hsize_t>::size_type dimensions = H5Sget_simple_extent_ndims(dataspaceHandle);
ArrayVector<hsize_t> shape(dimensions);
ArrayVector<hsize_t> maxdims(dimensions);
H5Sget_simple_extent_dims(dataspaceHandle, shape.data(), maxdims.data());
// invert the dimensions to guarantee VIGRA-compatible order.
std::reverse(shape.begin(), shape.end());
return shape;
}
/** Query the pixel type of the dataset.
Possible values are:
<DL>
<DT>"INT8"<DD> 8-bit signed integer (unsigned char)
<DT>"UINT8"<DD> 8-bit unsigned integer (unsigned char)
<DT>"INT16"<DD> 16-bit signed integer (short)
<DT>"UINT16"<DD> 16-bit unsigned integer (unsigned short)
<DT>"INT32"<DD> 32-bit signed integer (long)
<DT>"UINT32"<DD> 32-bit unsigned integer (unsigned long)
<DT>"INT64"<DD> 64-bit signed integer (long long)
<DT>"UINT64"<DD> 64-bit unsigned integer (unsigned long long)
<DT>"FLOAT"<DD> 32-bit floating point (float)
<DT>"DOUBLE"<DD> 64-bit floating point (double)
<DT>"UNKNOWN"<DD> any other type
</DL>
*/
std::string getDatasetType(std::string const & datasetName)
{
HDF5Handle datasetHandle = getDatasetHandle(datasetName);
hid_t datatype = H5Dget_type(datasetHandle);
H5T_class_t dataclass = H5Tget_class(datatype);
size_t datasize = H5Tget_size(datatype);
H5T_sign_t datasign = H5Tget_sign(datatype);
if(dataclass == H5T_FLOAT)
{
if(datasize == 4)
return "FLOAT";
else if(datasize == 8)
return "DOUBLE";
}
else if(dataclass == H5T_INTEGER)
{
if(datasign == H5T_SGN_NONE)
{
if(datasize == 1)
return "UINT8";
else if(datasize == 2)
return "UINT16";
else if(datasize == 4)
return "UINT32";
else if(datasize == 8)
return "UINT64";
}
else
{
if(datasize == 1)
return "INT8";
else if(datasize == 2)
return "INT16";
else if(datasize == 4)
return "INT32";
else if(datasize == 8)
return "INT64";
}
}
return "UNKNOWN";
}
/** \brief Obtain the HDF5 handle of a dataset.
*/
inline HDF5Handle getDatasetHandle(std::string const & datasetName)
{
std::string errorMessage = "HDF5File::getDatasetHandle(): Unable to open dataset '" + datasetName + "'.";
return HDF5Handle(getDatasetHandle_(get_absolute_path(datasetName)), &H5Dclose, errorMessage.c_str());
}
/** \brief Obtain the HDF5 handle of a group.
*/
inline HDF5Handle getGroupHandle(std::string group_name, std::string function_name = "HDF5File::getGroupHandle()")
{
std::string errorMessage = function_name + ": Group '" + group_name + "' not found.";
// make group_name clean
group_name = get_absolute_path(group_name);
// group must exist
vigra_precondition(group_name == "/" || H5Lexists(fileHandle_, group_name.c_str(), H5P_DEFAULT) != 0,
errorMessage.c_str());
// open group and return group handle
return HDF5Handle(openCreateGroup_(group_name), &H5Gclose, "Internal error");
}
/** \brief Obtain the HDF5 handle of a attribute.
*/
inline HDF5Handle getAttributeHandle(std::string dataset_name, std::string attribute_name)
{
std::string message = "HDF5File::getAttributeHandle(): Attribute '" + attribute_name + "' not found.";
return HDF5Handle(H5Aopen(getDatasetHandle(dataset_name), attribute_name.c_str(), H5P_DEFAULT),
&H5Aclose, message.c_str());
}
/* Writing Attributes */
/** \brief Write MultiArray Attributes.
* In contrast to datasets, subarray access, chunks and compression are not available.
*/
template<unsigned int N, class T, class Stride>
inline void writeAttribute(std::string object_name,
std::string attribute_name,
const MultiArrayView<N, T, Stride> & array)
{
// make object_name clean
object_name = get_absolute_path(object_name);
write_attribute_(object_name, attribute_name, array, detail::getH5DataType<T>(), 1);
}
template<unsigned int N, class T, int SIZE, class Stride>
inline void writeAttribute(std::string datasetName,
std::string attributeName,
const MultiArrayView<N, TinyVector<T, SIZE>, Stride> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
write_attribute_(datasetName, attributeName, array, detail::getH5DataType<T>(), SIZE);
}
template<unsigned int N, class T, class Stride>
inline void writeAttribute(std::string datasetName,
std::string attributeName,
const MultiArrayView<N, RGBValue<T>, Stride> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
write_attribute_(datasetName, attributeName, array, detail::getH5DataType<T>(), 3);
}
/** \brief Write a single value.
Specialization of the write function for simple datatypes
*/
inline void writeAttribute(std::string object_name, std::string attribute_name, char data)
{ writeAtomicAttribute(object_name,attribute_name,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, signed char data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, signed short data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, signed int data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, signed long data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, signed long long data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, unsigned char data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, unsigned short data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, unsigned int data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, unsigned long data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, unsigned long long data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, float data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, double data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, long double data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, const char* data)
{ writeAtomicAttribute(datasetName,attributeName,data); }
inline void writeAttribute(std::string datasetName, std::string attributeName, std::string const & data)
{ writeAtomicAttribute(datasetName,attributeName,data.c_str()); }
/** \brief Test if attribute exists.
*/
bool existsAttribute(std::string object_name, std::string attribute_name)
{
std::string obj_path = get_absolute_path(object_name);
htri_t exists = H5Aexists_by_name(fileHandle_, obj_path.c_str(),
attribute_name.c_str(), H5P_DEFAULT);
vigra_precondition(exists >= 0, "HDF5File::existsAttribute(): "
"object '" + object_name + "' "
"not found.");
return exists != 0;
}
// Reading Attributes
/** \brief Read MultiArray Attributes.
* In contrast to datasets, subarray access is not available.
*/
template<unsigned int N, class T, class Stride>
inline void readAttribute(std::string object_name,
std::string attribute_name,
MultiArrayView<N, T, Stride> array)
{
// make object_name clean
object_name = get_absolute_path(object_name);
read_attribute_(object_name, attribute_name, array, detail::getH5DataType<T>(), 1);
}
template<unsigned int N, class T, int SIZE, class Stride>
inline void readAttribute(std::string datasetName,
std::string attributeName,
MultiArrayView<N, TinyVector<T, SIZE>, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
read_attribute_(datasetName, attributeName, array, detail::getH5DataType<T>(), SIZE);
}
template<unsigned int N, class T, class Stride>
inline void readAttribute(std::string datasetName,
std::string attributeName,
MultiArrayView<N, RGBValue<T>, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
read_attribute_(datasetName, attributeName, array, detail::getH5DataType<T>(), 3);
}
/** \brief Read a single value.
Specialization of the read function for simple datatypes
*/
inline void readAttribute(std::string object_name, std::string attribute_name, char &data)
{ readAtomicAttribute(object_name,attribute_name,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, signed char &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, signed short &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, signed int &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, signed long &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, signed long long &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, unsigned char &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, unsigned short &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, unsigned int &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, unsigned long &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, unsigned long long &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, float &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, double &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, long double &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
inline void readAttribute(std::string datasetName, std::string attributeName, std::string &data)
{ readAtomicAttribute(datasetName,attributeName,data); }
// Writing data
/** \brief Write multi arrays.
Chunks can be activated by setting
\code iChunkSize = size; //size \> 0
\endcode .
The chunks will be hypercubes with edge length size. When <tt>iChunkSize == 0</tt>
(default), the behavior depends on the <tt>compression</tt> setting: If no
compression is requested, the data is written without chunking. Otherwise,
chuning is required, and the chunk size is automatically selected such that
each chunk contains about 300k pixels.
Compression can be activated by setting
\code compression = parameter; // 0 \< parameter \<= 9
\endcode
where 0 stands for no compression and 9 for maximum compression.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a VIGRA MultiArray,
whose indices represent the 'x'-, 'y'-, and 'z'-axis in that order, is reversed
upon writing to an HDF5 file, i.e. in the file the axis order is 'z', 'y', 'x'.
*/
template<unsigned int N, class T, class Stride>
inline void write(std::string datasetName,
const MultiArrayView<N, T, Stride> & array,
int iChunkSize = 0, int compression = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
typename MultiArrayShape<N>::type chunkSize;
for(unsigned int i = 0; i < N; i++){
chunkSize[i] = iChunkSize;
}
write_(datasetName, array, detail::getH5DataType<T>(), 1, chunkSize, compression);
}
/** \brief Write multi arrays.
Chunks can be activated by providing a MultiArrayShape as chunkSize.
chunkSize must have equal dimension as array.
Compression can be activated by setting
\code compression = parameter; // 0 \< parameter \<= 9
\endcode
where 0 stands for no compression and 9 for maximum compression.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a VIGRA MultiArray,
whose indices represent the 'x'-, 'y'-, and 'z'-axis in that order, is reversed
upon writing to an HDF5 file, i.e. in the file the axis order is 'z', 'y', 'x'.
*/
template<unsigned int N, class T, class Stride>
inline void write(std::string datasetName,
const MultiArrayView<N, T, Stride> & array,
typename MultiArrayShape<N>::type chunkSize, int compression = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
write_(datasetName, array, detail::getH5DataType<T>(), 1, chunkSize, compression);
}
/** \brief Write a multi array into a larger volume.
blockOffset determines the position, where array is written.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a VIGRA MultiArray,
whose indices represent the 'x'-, 'y'-, and 'z'-axis in that order, is reversed
upon writing to an HDF5 file, i.e. in the file the axis order is 'z', 'y', 'x'.
*/
template<unsigned int N, class T, class Stride>
inline void writeBlock(std::string datasetName,
typename MultiArrayShape<N>::type blockOffset,
const MultiArrayView<N, T, Stride> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
writeBlock_(datasetName, blockOffset, array, detail::getH5DataType<T>(), 1);
}
// non-scalar (TinyVector) and unstrided multi arrays
template<unsigned int N, class T, int SIZE, class Stride>
inline void write(std::string datasetName,
const MultiArrayView<N, TinyVector<T, SIZE>, Stride> & array,
int iChunkSize = 0, int compression = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
typename MultiArrayShape<N>::type chunkSize;
for(int i = 0; i < N; i++){
chunkSize[i] = iChunkSize;
}
write_(datasetName, array, detail::getH5DataType<T>(), SIZE, chunkSize, compression);
}
template<unsigned int N, class T, int SIZE, class Stride>
inline void write(std::string datasetName,
const MultiArrayView<N, TinyVector<T, SIZE>, Stride> & array,
typename MultiArrayShape<N>::type chunkSize, int compression = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
write_(datasetName, array, detail::getH5DataType<T>(), SIZE, chunkSize, compression);
}
/** \brief Write array vectors.
Compression can be activated by setting
\code compression = parameter; // 0 \< parameter \<= 9
\endcode
where 0 stands for no compression and 9 for maximum compression.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
template<class T>
void write(const std::string & datasetName,
const ArrayVectorView<T> & array,
int compression = 0)
{
// convert to a (trivial) MultiArrayView and forward.
MultiArrayShape<1>::type shape(array.size());
const MultiArrayView<1, T> m_array(shape, const_cast<T*>(array.data()));
write(datasetName, m_array, compression);
}
template<unsigned int N, class T, int SIZE, class Stride>
inline void writeBlock(std::string datasetName,
typename MultiArrayShape<N>::type blockOffset,
const MultiArrayView<N, TinyVector<T, SIZE>, Stride> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
writeBlock_(datasetName, blockOffset, array, detail::getH5DataType<T>(), SIZE);
}
// non-scalar (RGBValue) and unstrided multi arrays
template<unsigned int N, class T, class Stride>
inline void write(std::string datasetName,
const MultiArrayView<N, RGBValue<T>, Stride> & array,
int iChunkSize = 0, int compression = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
typename MultiArrayShape<N>::type chunkSize;
for(int i = 0; i < N; i++){
chunkSize[i] = iChunkSize;
}
write_(datasetName, array, detail::getH5DataType<T>(), 3, chunkSize, compression);
}
template<unsigned int N, class T, class Stride>
inline void write(std::string datasetName,
const MultiArrayView<N, RGBValue<T>, Stride> & array,
typename MultiArrayShape<N>::type chunkSize, int compression = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
write_(datasetName, array, detail::getH5DataType<T>(), 3, chunkSize, compression);
}
template<unsigned int N, class T, class Stride>
inline void writeBlock(std::string datasetName,
typename MultiArrayShape<N>::type blockOffset,
const MultiArrayView<N, RGBValue<T>, Stride> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
writeBlock_(datasetName, blockOffset, array, detail::getH5DataType<T>(), 3);
}
/** \brief Write a single value.
Specialization of the write function for simple datatypes
*/
inline void write(std::string datasetName, char data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, signed char data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, signed short data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, signed int data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, signed long data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, signed long long data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, unsigned char data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, unsigned short data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, unsigned int data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, unsigned long data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, unsigned long long data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, float data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, double data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, long double data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, const char* data) { writeAtomic(datasetName,data); }
inline void write(std::string datasetName, std::string const & data) { writeAtomic(datasetName,data.c_str()); }
// Reading data
/** \brief Read data into a multi array.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a HDF5 dataset,
whose indices represent the 'z'-, 'y'-, and 'x'-axis in that order, is reversed
upon reading into a MultiArrayView, i.e. in the array axis order must be 'x', 'y', 'z'.
*/
template<unsigned int N, class T, class Stride>
inline void read(std::string datasetName, MultiArrayView<N, T, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
read_(datasetName, array, detail::getH5DataType<T>(), 1);
}
/** \brief Read data into a MultiArray. Resize MultiArray to the correct size.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a HDF5 dataset,
whose indices represent the 'z'-, 'y'-, and 'x'-axis in that order, is reversed
upon reading into a MultiArray, i.e. in the array axis order will be 'x', 'y', 'z'.
*/
template<unsigned int N, class T, class Alloc>
inline void readAndResize(std::string datasetName, MultiArray<N, T, Alloc> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
// get dataset dimension
ArrayVector<hsize_t> dimshape = getDatasetShape(datasetName);
// check if dimensions are correct
vigra_precondition(N == MultiArrayIndex(dimshape.size()), // the object in the HDF5 file may have one additional dimension which we then interpret as the pixel type bands
"HDF5File::readAndResize(): Array dimension disagrees with dataset dimension.");
// reshape target MultiArray
typename MultiArrayShape<N>::type shape;
for(int k=0; k < (int)dimshape.size(); ++k)
shape[k] = (MultiArrayIndex)dimshape[k];
array.reshape(shape);
read_(datasetName, array, detail::getH5DataType<T>(), 1);
}
/** \brief Read data into an array vector.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
template<class T>
inline void read(const std::string & datasetName, ArrayVectorView<T> array)
{
// convert to a (trivial) MultiArrayView and forward.
MultiArrayShape<1>::type shape(array.size());
MultiArrayView<1, T> m_array(shape, (array.data()));
read(datasetName, m_array);
}
/** \brief Read data into an array vector. Resize the array vector to the correct size.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
template<class T>
inline void readAndResize(std::string datasetName,
ArrayVector<T> & array)
{
// make dataset name clean
datasetName = get_absolute_path(datasetName);
// get dataset dimension
ArrayVector<hsize_t> dimshape = getDatasetShape(datasetName);
// check if dimensions are correct
vigra_precondition(1 == MultiArrayIndex(dimshape.size()),
"HDF5File::readAndResize(): Array dimension disagrees with Dataset dimension must equal one for vigra::ArrayVector.");
// resize target array vector
array.resize((typename ArrayVector<T>::size_type)dimshape[0]);
// convert to a (trivial) MultiArrayView and forward.
MultiArrayShape<1>::type shape(array.size());
MultiArrayView<1, T> m_array(shape, (array.data()));
read_(datasetName, m_array, detail::getH5DataType<T>(), 1);
}
/** \brief Read a block of data into a multi array.
This function allows to read a small block out of a larger volume stored
in an HDF5 dataset.
blockOffset determines the position of the block.
blockSize determines the size in each dimension of the block.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a HDF5 dataset,
whose indices represent the 'z'-, 'y'-, and 'x'-axis in that order, is reversed
upon reading into a MultiArray, i.e. in the array axis order will be 'x', 'y', 'z'.
*/
template<unsigned int N, class T, class Stride>
inline void readBlock(std::string datasetName,
typename MultiArrayShape<N>::type blockOffset,
typename MultiArrayShape<N>::type blockShape,
MultiArrayView<N, T, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
readBlock_(datasetName, blockOffset, blockShape, array, detail::getH5DataType<T>(), 1);
}
// non-scalar (TinyVector) and unstrided target MultiArrayView
template<unsigned int N, class T, int SIZE, class Stride>
inline void read(std::string datasetName, MultiArrayView<N, TinyVector<T, SIZE>, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
read_(datasetName, array, detail::getH5DataType<T>(), SIZE);
}
// non-scalar (TinyVector) MultiArray
template<unsigned int N, class T, int SIZE, class Alloc>
inline void readAndResize(std::string datasetName, MultiArray<N, TinyVector<T, SIZE>, Alloc> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
// get dataset dimension
ArrayVector<hsize_t> dimshape = getDatasetShape(datasetName);
// check if dimensions are correct
vigra_precondition((N+1) == MultiArrayIndex(dimshape.size()) &&
SIZE == dimshape[0], // the object in the HDF5 file must have one additional dimension which we interpret as the pixel type bands
"HDF5File::readAndResize(): Array dimension disagrees with dataset dimension.");
// reshape target MultiArray
typename MultiArrayShape<N>::type shape;
for(int k=1; k < (int)dimshape.size(); ++k)
shape[k-1] = (MultiArrayIndex)dimshape[k];
array.reshape(shape);
read_(datasetName, array, detail::getH5DataType<T>(), SIZE);
}
template<unsigned int N, class T, int SIZE, class Stride>
inline void readBlock(std::string datasetName,
typename MultiArrayShape<N>::type blockOffset,
typename MultiArrayShape<N>::type blockShape,
MultiArrayView<N, TinyVector<T, SIZE>, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
readBlock_(datasetName, blockOffset, blockShape, array, detail::getH5DataType<T>(), SIZE);
}
// non-scalar (RGBValue) and unstrided target MultiArrayView
template<unsigned int N, class T, class Stride>
inline void read(std::string datasetName, MultiArrayView<N, RGBValue<T>, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
read_(datasetName, array, detail::getH5DataType<T>(), 3);
}
// non-scalar (RGBValue) MultiArray
template<unsigned int N, class T, class Alloc>
inline void readAndResize(std::string datasetName, MultiArray<N, RGBValue<T>, Alloc> & array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
// get dataset dimension
ArrayVector<hsize_t> dimshape = getDatasetShape(datasetName);
// check if dimensions are correct
vigra_precondition((N+1) == MultiArrayIndex(dimshape.size()) &&
3 == dimshape[0], // the object in the HDF5 file must have one additional dimension which we interpret as the pixel type bands
"HDF5File::readAndResize(): Array dimension disagrees with dataset dimension.");
// reshape target MultiArray
typename MultiArrayShape<N>::type shape;
for(int k=1; k < (int)dimshape.size(); ++k)
shape[k-1] = (MultiArrayIndex)dimshape[k];
array.reshape(shape);
read_(datasetName, array, detail::getH5DataType<T>(), 3);
}
template<unsigned int N, class T, class Stride>
inline void readBlock(std::string datasetName,
typename MultiArrayShape<N>::type blockOffset,
typename MultiArrayShape<N>::type blockShape,
MultiArrayView<N, RGBValue<T>, Stride> array)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
readBlock_(datasetName, blockOffset, blockShape, array, detail::getH5DataType<T>(), 3);
}
/** \brief Read a single value.
Specialization of the read function for simple datatypes
*/
inline void read(std::string datasetName, char &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, signed char &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, signed short &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, signed int &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, signed long &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, signed long long &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, unsigned char &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, unsigned short &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, unsigned int &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, unsigned long &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, unsigned long long &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, float &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, double &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, long double &data) { readAtomic(datasetName,data); }
inline void read(std::string datasetName, std::string &data) { readAtomic(datasetName,data); }
/** \brief Create a new dataset.
This function can be used to create a dataset filled with a default value,
for example before writing data into it using \ref writeBlock().
Attention: only atomic datatypes are provided. For spectral data, add an
dimension (case RGB: add one dimension of size 3).
shape determines the dimension and the size of the dataset.
Chunks can be activated by providing a MultiArrayShape as chunkSize.
chunkSize must have equal dimension as array.
Compression can be activated by setting
\code compression = parameter; // 0 \< parameter \<= 9
\endcode
where 0 stands for no compression and 9 for maximum compression.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
Note that the memory order between VIGRA and HDF5 files differs: VIGRA uses
Fortran-order, while HDF5 uses C-order. This means that a VIGRA MultiArray,
whose indices represent the 'x'-, 'y'-, and 'z'-axis in that order, is reversed
upon writing to an HDF5 file, i.e. in the file the axis order is 'z', 'y', 'x'.
*/
template<unsigned int N, class T>
inline void createDataset(std::string datasetName,
typename MultiArrayShape<N>::type shape,
T init = T(),
int iChunkSize = 0,
int compressionParameter = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
typename MultiArrayShape<N>::type chunkSize;
for(int i = 0; i < N; i++){
chunkSize[i] = iChunkSize;
}
createDataset<N,T>(datasetName, shape, init, chunkSize, compressionParameter);
}
template<unsigned int N, class T>
inline void createDataset(std::string datasetName,
typename MultiArrayShape<N>::type shape,
T init,
typename MultiArrayShape<N>::type chunkSize,
int compressionParameter = 0)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
std::string groupname = SplitString(datasetName).first();
std::string setname = SplitString(datasetName).last();
hid_t parent = openCreateGroup_(groupname);
// delete the dataset if it already exists
deleteDataset_(parent, setname);
// create dataspace
// add an extra dimension in case that the data is non-scalar
HDF5Handle dataspaceHandle;
// invert dimensions to guarantee c-order
hsize_t shape_inv[N];
for(unsigned int k=0; k<N; ++k)
shape_inv[N-1-k] = shape[k];
// create dataspace
dataspaceHandle = HDF5Handle(H5Screate_simple(N, shape_inv, NULL),
&H5Sclose, "HDF5File::createDataset(): unable to create dataspace for scalar data.");
// set fill value
HDF5Handle plist ( H5Pcreate(H5P_DATASET_CREATE), &H5Pclose, "HDF5File::createDataset(): unable to create property list." );
H5Pset_fill_value(plist,detail::getH5DataType<T>(), &init);
// turn off time tagging of datasets by default.
H5Pset_obj_track_times(plist, track_time);
// enable chunks
ArrayVector<hsize_t> chunks(defineChunks(chunkSize, shape, 1, compressionParameter));
if(chunks.size() > 0)
{
std::reverse(chunks.begin(), chunks.end());
H5Pset_chunk (plist, chunks.size(), chunks.begin());
}
// enable compression
if(compressionParameter > 0)
{
H5Pset_deflate(plist, compressionParameter);
}
//create the dataset.
HDF5Handle datasetHandle ( H5Dcreate(parent, setname.c_str(), detail::getH5DataType<T>(), dataspaceHandle, H5P_DEFAULT, plist, H5P_DEFAULT),
&H5Dclose, "HDF5File::createDataset(): unable to create dataset.");
if(parent != cGroupHandle_)
H5Gclose(parent);
}
/** \brief Immediately write all data to disk
*/
inline void flushToDisk()
{
H5Fflush(fileHandle_, H5F_SCOPE_GLOBAL);
}
private:
/* Simple extension of std::string for splitting into two parts
*
* Strings (in particular: file/dataset paths) will be split into two
* parts. The split is made at the last occurrence of the delimiter.
*
* For example, "/path/to/some/file" will be split (delimiter = "/") into
* first() = "/path/to/some" and last() = "file".
*/
class SplitString: public std::string {
public:
SplitString(std::string &sstring): std::string(sstring) {};
// return the part of the string before the delimiter
std::string first(char delimiter = '/')
{
size_t last = find_last_of(delimiter);
if(last == std::string::npos) // delimiter not found --> no first
return "";
return std::string(begin(), begin()+last+1);
}
// return the part of the string after the delimiter
std::string last(char delimiter = '/')
{
size_t last = find_last_of(delimiter);
if(last == std::string::npos) // delimiter not found --> only last
return std::string(*this);
return std::string(begin()+last+1, end());
}
};
template <class Shape>
ArrayVector<hsize_t>
defineChunks(Shape const & chunks, Shape const & shape, int numBands, int compression = 0)
{
if(chunks[0] > 0)
{
ArrayVector<hsize_t> res(chunks.begin(), chunks.end());
if(numBands > 1)
res.insert(res.begin(), numBands);
return res;
}
else if(compression > 0)
{
// set default chunks to enable compression
// (arbitrarily include about 300k pixels into each chunk, but make sure
// that the chunk size doesn't exceed the shape)
ArrayVector<hsize_t> res(shape.begin(), shape.end());
hsize_t chunk_length = (hsize_t)std::pow(300000.0, 1.0 / shape.size());
for(unsigned int k=0; k < shape.size(); ++k)
if(res[k] > chunk_length)
res[k] = chunk_length;
if(numBands > 1)
res.insert(res.begin(), numBands);
return res;
}
else
{
return ArrayVector<hsize_t>();
}
}
public:
/** \brief takes any path and converts it into an absolute path
in the current file.
Elements like "." and ".." are treated as expected.
Links are not supported or resolved.
*/
inline std::string get_absolute_path(std::string path) const {
// check for empty input or "." and return the current folder
if(path.length() == 0 || path == "."){
return currentGroupName_();
}
std::string str;
// convert to absolute path
if(relativePath_(path)){
std::string cname = currentGroupName_();
if (cname == "/")
str = currentGroupName_()+path;
else
str = currentGroupName_()+"/"+path;
}else{
str = path;
}
// cut out "./"
std::string::size_type startpos = 0;
while(str.find(std::string("./"), startpos) != std::string::npos){
std::string::size_type pos = str.find(std::string("./"), startpos);
startpos = pos+1;
// only cut if "./" is not part of "../" (see below)
if(str.substr(pos-1,3) != "../"){
// cut out part of the string
str = str.substr(0,pos) + str.substr(pos+2,str.length()-pos-2);
startpos = pos;
}
}
// cut out pairs of "bla/../"
while(str.find(std::string("..")) != std::string::npos){
std::string::size_type pos = str.find(std::string(".."));
// find first slash after ".."
std::string::size_type end = str.find("/",pos);
if(end != std::string::npos){
// also include slash
end++;
}else{
// no "/" after ".." --> this is a group, add a "/"
str = str + "/";
end = str.length();
}
// find first slash before ".."
std::string::size_type prev_slash = str.rfind("/",pos);
// if the root slash is the first before ".." --> Error
vigra_invariant(prev_slash != 0 && prev_slash != std::string::npos,
"Error parsing path: "+str);
// find second slash before ".."
std::string::size_type begin = str.rfind("/",prev_slash-1);
// cut out part of the string
str = str.substr(0,begin+1) + str.substr(end,str.length()-end);
}
return str;
}
protected:
/* checks if the given path is a relative path.
*/
inline bool relativePath_(std::string & path) const
{
std::string::size_type pos = path.find('/') ;
if(pos == 0)
return false;
return true;
}
/* return the name of the current group
*/
inline std::string currentGroupName_() const
{
int len = H5Iget_name(cGroupHandle_,NULL,1000);
ArrayVector<char> name (len+1,0);
H5Iget_name(cGroupHandle_,name.begin(),len+1);
return std::string(name.begin());
}
/* return the name of the current file
*/
inline std::string fileName_() const
{
int len = H5Fget_name(fileHandle_,NULL,1000);
ArrayVector<char> name (len+1,0);
H5Fget_name(fileHandle_,name.begin(),len+1);
return std::string(name.begin());
}
/* create an empty file and open is
*/
inline hid_t createFile_(std::string filePath, OpenMode mode = Open)
{
// try to open file
FILE * pFile;
pFile = fopen ( filePath.c_str(), "r" );
hid_t fileId;
// check if opening was successful (= file exists)
if ( pFile == NULL )
{
fileId = H5Fcreate(filePath.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
}
else if(mode == Open)
{
fclose( pFile );
fileId = H5Fopen(filePath.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
}
else if(mode == OpenReadOnly) {
fclose( pFile );
fileId = H5Fopen(filePath.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
}
else
{
fclose(pFile);
std::remove(filePath.c_str());
fileId = H5Fcreate(filePath.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
}
return fileId;
}
/* open a group and subgroups. Create if necessary.
*/
inline hid_t openCreateGroup_(std::string groupName)
{
// make groupName clean
groupName = get_absolute_path(groupName);
// open root group
hid_t parent = H5Gopen(fileHandle_, "/", H5P_DEFAULT);
if(groupName == "/")
{
return parent;
}
// remove leading /
groupName = std::string(groupName.begin()+1, groupName.end());
// check if the groupName has finishing slash
if( groupName.size() != 0 && *groupName.rbegin() != '/')
{
groupName = groupName + '/';
}
// open or create subgroups one by one
std::string::size_type begin = 0, end = groupName.find('/');
while (end != std::string::npos)
{
std::string group(groupName.begin()+begin, groupName.begin()+end);
hid_t prevParent = parent;
if(H5LTfind_dataset(parent, group.c_str()) == 0)
{
parent = H5Gcreate(prevParent, group.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
} else {
parent = H5Gopen(prevParent, group.c_str(), H5P_DEFAULT);
}
H5Gclose(prevParent);
if(parent < 0)
{
return parent;
}
begin = end + 1;
end = groupName.find('/', begin);
}
return parent;
}
/* delete a dataset by unlinking it from the file structure. This does not
delete the data!
*/
inline void deleteDataset_(hid_t parent, std::string datasetName)
{
// delete existing data and create new dataset
if(H5LTfind_dataset(parent, datasetName.c_str()))
{
#if (H5_VERS_MAJOR == 1 && H5_VERS_MINOR <= 6)
if(H5Gunlink(parent, datasetName.c_str()) < 0)
{
vigra_postcondition(false, "HDF5File::deleteDataset_(): Unable to delete existing data.");
}
#else
if(H5Ldelete(parent, datasetName.c_str(), H5P_DEFAULT ) < 0)
{
vigra_postcondition(false, "HDF5File::deleteDataset_(): Unable to delete existing data.");
}
#endif
}
}
/* get the handle of a dataset specified by a string
*/
inline hid_t getDatasetHandle_(std::string datasetName)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
std::string groupname = SplitString(datasetName).first();
std::string setname = SplitString(datasetName).last();
if(H5Lexists(fileHandle_, datasetName.c_str(), H5P_DEFAULT) <= 0)
{
std::cerr << "HDF5File::getDatasetHandle_(): Dataset '" << datasetName << "' does not exist.\n";
return -1;
}
// Open parent group
HDF5Handle groupHandle(openCreateGroup_(groupname), &H5Gclose, "HDF5File::getDatasetHandle_(): Internal error");
return H5Dopen(groupHandle, setname.c_str(), H5P_DEFAULT);
}
/* get the type of an object specified by a string
*/
H5O_type_t get_object_type_(std::string name)
{
name = get_absolute_path(name);
std::string group_name = SplitString(name).first();
std::string object_name = SplitString(name).last();
if (!object_name.size())
return H5O_TYPE_GROUP;
htri_t exists = H5Lexists(fileHandle_, name.c_str(), H5P_DEFAULT);
vigra_precondition(exists > 0, "HDF5File::get_object_type_(): "
"object \"" + name + "\" "
"not found.");
// open parent group
HDF5Handle group_handle(openCreateGroup_(group_name), &H5Gclose, "Internal error");
return HDF5_get_type(group_handle, name.c_str());
}
/* low-level write function to write vigra MultiArray data as an attribute
*/
template<unsigned int N, class T, class Stride>
void write_attribute_(std::string name,
const std::string & attribute_name,
const MultiArrayView<N, T, Stride> & array,
const hid_t datatype,
const int numBandsOfType);
/* Write single value attribute
This function allows to write data of atomic datatypes (int, long, double)
as an attribute in the HDF5 file. So it is not necessary to create a MultiArray
of size 1 to write a single number.
*/
template<class T>
inline void writeAtomicAttribute(std::string datasetName, std::string attributeName, const T data)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
typename MultiArrayShape<1>::type chunkSize;
chunkSize[0] = 0;
MultiArray<1,T> array(MultiArrayShape<1>::type(1));
array[0] = data;
write_attribute_(datasetName, attributeName, array, detail::getH5DataType<T>(), 1);
}
/* low-level read function to read vigra MultiArray data from attributes
*/
template<unsigned int N, class T, class Stride>
void read_attribute_(std::string datasetName,
std::string attributeName,
MultiArrayView<N, T, Stride> array,
const hid_t datatype, const int numBandsOfType);
/* Read a single value attribute.
This functions allows to read a single value attribute of atomic datatype (int, long, double)
from the HDF5 file. So it is not necessary to create a MultiArray
of size 1 to read a single number.
*/
template<class T>
inline void readAtomicAttribute(std::string datasetName, std::string attributeName, T & data)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
MultiArray<1,T> array(MultiArrayShape<1>::type(1));
read_attribute_(datasetName, attributeName, array, detail::getH5DataType<T>(), 1);
data = array[0];
}
inline void readAtomicAttribute(std::string datasetName, std::string attributeName, std::string & data)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
MultiArray<1,const char *> array(MultiArrayShape<1>::type(1));
read_attribute_(datasetName, attributeName, array, detail::getH5DataType<const char *>(), 1);
data = std::string(array[0]);
}
/* low-level write function to write vigra unstrided MultiArray data
*/
template<unsigned int N, class T, class Stride>
void write_(std::string &datasetName,
const MultiArrayView<N, T, Stride> & array,
const hid_t datatype,
const int numBandsOfType,
typename MultiArrayShape<N>::type &chunkSize,
int compressionParameter = 0);
/* Write single value as dataset.
This functions allows to write data of atomic datatypes (int, long, double)
as a dataset in the HDF5 file. So it is not necessary to create a MultiArray
of size 1 to write a single number.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
template<class T>
inline void writeAtomic(std::string datasetName, const T data)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
typename MultiArrayShape<1>::type chunkSize;
chunkSize[0] = 0;
MultiArray<1,T> array(MultiArrayShape<1>::type(1));
array[0] = data;
write_(datasetName, array, detail::getH5DataType<T>(), 1, chunkSize,0);
}
/* low-level read function to read vigra unstrided MultiArray data
*/
template<unsigned int N, class T, class Stride>
void read_(std::string datasetName,
MultiArrayView<N, T, Stride> array,
const hid_t datatype, const int numBandsOfType);
/* Read a single value.
This functions allows to read a single datum of atomic datatype (int, long, double)
from the HDF5 file. So it is not necessary to create a MultiArray
of size 1 to read a single number.
If the first character of datasetName is a "/", the path will be interpreted as absolute path,
otherwise it will be interpreted as path relative to the current group.
*/
template<class T>
inline void readAtomic(std::string datasetName, T & data)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
MultiArray<1,T> array(MultiArrayShape<1>::type(1));
read_(datasetName, array, detail::getH5DataType<T>(), 1);
data = array[0];
}
inline void readAtomic(std::string datasetName, std::string & data)
{
// make datasetName clean
datasetName = get_absolute_path(datasetName);
MultiArray<1,const char *> array(MultiArrayShape<1>::type(1));
read_(datasetName, array, detail::getH5DataType<const char *>(), 1);
data = std::string(array[0]);
}
/* low-level write function to write vigra unstrided MultiArray data into a sub-block of a dataset
*/
template<unsigned int N, class T, class Stride>
void writeBlock_(std::string datasetName,
typename MultiArrayShape<N>::type &blockOffset,
const MultiArrayView<N, T, Stride> & array,
const hid_t datatype,
const int numBandsOfType);
/* low-level read function to read vigra unstrided MultiArray data from a sub-block of a dataset.
The array must have the same shape as the block.
*/
template<unsigned int N, class T, class Stride>
void readBlock_(std::string datasetName,
typename MultiArrayShape<N>::type &blockOffset,
typename MultiArrayShape<N>::type &blockShape,
MultiArrayView<N, T, Stride> &array,
const hid_t datatype, const int numBandsOfType);
}; /* class HDF5File */
/********************************************************************/
template<unsigned int N, class T, class Stride>
void HDF5File::write_(std::string &datasetName,
const MultiArrayView<N, T, Stride> & array,
const hid_t datatype,
const int numBandsOfType,
typename MultiArrayShape<N>::type &chunkSize,
int compressionParameter)
{
std::string groupname = SplitString(datasetName).first();
std::string setname = SplitString(datasetName).last();
// shape of the array. Add one dimension, if array contains non-scalars.
ArrayVector<hsize_t> shape(array.shape().begin(), array.shape().end());
std::reverse(shape.begin(), shape.end());
if(numBandsOfType > 1)
shape.push_back(numBandsOfType);
HDF5Handle dataspace(H5Screate_simple(shape.size(), shape.begin(), NULL), &H5Sclose,
"HDF5File::write(): Can not create dataspace.");
// create and open group:
std::string errorMessage ("HDF5File::write(): can not create group '" + groupname + "'.");
HDF5Handle groupHandle(openCreateGroup_(groupname), &H5Gclose, errorMessage.c_str());
// delete dataset, if it already exists
deleteDataset_(groupHandle, setname.c_str());
// set up properties list
HDF5Handle plist(H5Pcreate(H5P_DATASET_CREATE), &H5Pclose,
"HDF5File::write(): unable to create property list." );
// turn off time tagging of datasets by default.
H5Pset_obj_track_times(plist, track_time);
// enable chunks
ArrayVector<hsize_t> chunks(defineChunks(chunkSize, array.shape(), numBandsOfType, compressionParameter));
if(chunks.size() > 0)
{
std::reverse(chunks.begin(), chunks.end());
H5Pset_chunk (plist, chunks.size(), chunks.begin());
}
// enable compression
if(compressionParameter > 0)
{
H5Pset_deflate(plist, compressionParameter);
}
// create dataset
HDF5Handle datasetHandle(H5Dcreate(groupHandle, setname.c_str(), datatype, dataspace,H5P_DEFAULT, plist, H5P_DEFAULT),
&H5Dclose, "HDF5File::write(): Can not create dataset.");
herr_t status = 0;
if(array.isUnstrided())
{
// Write the data directly from the array data buffer
status = H5Dwrite(datasetHandle, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, array.data());
}
else
{
// otherwise, we need an intermediate buffer
// FIXME: right now, the buffer has the same size as the array to be read
// incomplete code for better solutions is below
// MultiArray<N, T> buffer(array);
// status = H5Dwrite(datasetHandle, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer.data());
int offset = numBandsOfType > 1 ? 1 : 0;
std::reverse(shape.begin(), shape.end());
if(chunks.size() > 0)
{
// if the file is chunked, we use a buffer that matches the chunk size.
std::reverse(chunks.begin(), chunks.end());
}
else
{
// otherwise, we compute a suitable chunk size.
ArrayVector<hsize_t>(shape.size(), 1).swap(chunks);
chunks[0] = numBandsOfType;
MultiArrayIndex prod = 1;
for(unsigned int k=0; k<N; ++k)
{
chunks[k+offset] = array.shape(k);
prod *= array.shape(k);
if(prod > 300000)
break;
}
}
ArrayVector<hsize_t> null(shape.size(), 0),
start(shape.size(), 0),
count(shape.size(), 1);
count[N-1-offset] = numBandsOfType;
typedef typename MultiArrayShape<N>::type Shape;
Shape chunkCount, chunkMaxShape;
for(unsigned int k=offset; k<chunks.size(); ++k)
{
chunkMaxShape[k-offset] = chunks[k];
chunkCount[k-offset] = (MultiArrayIndex)std::ceil(double(shape[k]) / chunks[k]);
}
typename CoupledIteratorType<N>::type chunkIter = createCoupledIterator(chunkCount),
chunkEnd = chunkIter.getEndIterator();
for(; chunkIter != chunkEnd; ++chunkIter)
{
Shape chunkStart(chunkIter.point() * chunkMaxShape),
chunkStop(min(chunkStart + chunkMaxShape, array.shape()));
MultiArray<N, T> buffer(array.subarray(chunkStart, chunkStop));
for(unsigned int k=0; k<N; ++k)
{
start[N-1-k] = chunkStart[k];
count[N-1-k] = buffer.shape(k);
}
if(offset == 1)
{
start[N] = 0;
count[N] = numBandsOfType;
}
HDF5Handle filespace(H5Dget_space(datasetHandle),
&H5Sclose, "HDF5File::write(): unable to create hyperslabs.");
status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, start.data(), NULL, count.data(), NULL);
if(status < 0)
break;
HDF5Handle dataspace(H5Screate_simple(count.size(), count.data(), NULL),
&H5Sclose, "HDF5File::write(): unable to create hyperslabs.");
status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, null.data(), NULL, count.data(), NULL);
if(status < 0)
break;
status = H5Dwrite(datasetHandle, datatype, dataspace, filespace, H5P_DEFAULT, buffer.data());
if(status < 0)
break;
}
}
vigra_postcondition(status >= 0,
"HDF5File::write(): write to dataset '" + datasetName + "' via H5Dwrite() failed.");
}
/********************************************************************/
template<unsigned int N, class T, class Stride>
void HDF5File::writeBlock_(std::string datasetName,
typename MultiArrayShape<N>::type &blockOffset,
const MultiArrayView<N, T, Stride> & array,
const hid_t datatype,
const int numBandsOfType)
{
// open dataset if it exists
std::string errorMessage = "HDF5File::writeBlock(): Error opening dataset '" + datasetName + "'.";
HDF5Handle datasetHandle (getDatasetHandle_(datasetName), &H5Dclose, errorMessage.c_str());
// hyperslab parameters for position, size, ...
hsize_t boffset [N];
hsize_t bshape [N];
hsize_t bones [N];
for(int i = 0; i < N; i++){
boffset[i] = blockOffset[N-1-i];
bshape[i] = array.size(N-1-i);
bones[i] = 1;
}
// create a target dataspace in memory with the shape of the desired block
HDF5Handle memspace_handle (H5Screate_simple(N,bshape,NULL),&H5Sclose,"Unable to get origin dataspace");
// get file dataspace and select the desired block
HDF5Handle dataspaceHandle (H5Dget_space(datasetHandle),&H5Sclose,"Unable to create target dataspace");
H5Sselect_hyperslab(dataspaceHandle, H5S_SELECT_SET, boffset, bones, bones, bshape);
herr_t status = 0;
if(array.isUnstrided())
{
// when the array is unstrided, we can read the data directly from the array buffer
status = H5Dwrite( datasetHandle, datatype, memspace_handle, dataspaceHandle, H5P_DEFAULT, array.data());
}
else
{
// otherwise, we must copy the data into an unstrided extra buffer
MultiArray<N, T> buffer(array);
status = H5Dwrite( datasetHandle, datatype, memspace_handle, dataspaceHandle, H5P_DEFAULT, buffer.data());
}
vigra_postcondition(status >= 0,
"HDF5File::writeBlock(): write to dataset '" + datasetName + "' via H5Dwrite() failed.");
}
/********************************************************************/
template<unsigned int N, class T, class Stride>
void HDF5File::write_attribute_(std::string name,
const std::string & attribute_name,
const MultiArrayView<N, T, Stride> & array,
const hid_t datatype,
const int numBandsOfType)
{
// shape of the array. Add one dimension, if array contains non-scalars.
ArrayVector<hsize_t> shape(array.shape().begin(), array.shape().end());
std::reverse(shape.begin(), shape.end());
if(numBandsOfType > 1)
shape.push_back(numBandsOfType);
HDF5Handle dataspace(H5Screate_simple(shape.size(),
shape.begin(), NULL),
&H5Sclose, "HDF5File::writeAttribute(): Can not"
" create dataspace.");
std::string errorMessage ("HDF5File::writeAttribute(): can not find "
"object '" + name + "'.");
H5O_type_t h5_type = get_object_type_(name);
bool is_group = h5_type == H5O_TYPE_GROUP;
if (!is_group && h5_type != H5O_TYPE_DATASET)
vigra_precondition(0, "HDF5File::writeAttribute(): object \""
+ name + "\" is neither a group nor a "
"dataset.");
// get parent object handle
HDF5Handle object_handle(is_group
? openCreateGroup_(name)
: getDatasetHandle_(name),
is_group
? &H5Gclose
: &H5Dclose,
errorMessage.c_str());
// create / open attribute
bool exists = existsAttribute(name, attribute_name);
HDF5Handle attributeHandle(exists
? H5Aopen(object_handle,
attribute_name.c_str(),
H5P_DEFAULT)
: H5Acreate(object_handle,
attribute_name.c_str(), datatype,
dataspace, H5P_DEFAULT,
H5P_DEFAULT),
&H5Aclose,
"HDF5File::writeAttribute(): Can not create"
" attribute.");
herr_t status = 0;
if(array.isUnstrided())
{
// write the data directly from the array data buffer
status = H5Awrite(attributeHandle, datatype, array.data());
}
else
{
// write the data via an unstrided copy
// (we assume that attributes are small arrays, so that the wasted memory is uncritical)
MultiArray<N, T> buffer(array);
status = H5Awrite(attributeHandle, datatype, buffer.data());
}
vigra_postcondition(status >= 0,
"HDF5File::writeAttribute(): write to attribute '" + attribute_name + "' via H5Awrite() failed.");
}
/********************************************************************/
template<unsigned int N, class T, class Stride>
void HDF5File::read_(std::string datasetName,
MultiArrayView<N, T, Stride> array,
const hid_t datatype, const int numBandsOfType)
{
//Prepare to read without using HDF5ImportInfo
ArrayVector<hsize_t> dimshape = getDatasetShape(datasetName);
std::string errorMessage ("HDF5File::read(): Unable to open dataset '" + datasetName + "'.");
HDF5Handle datasetHandle(getDatasetHandle_(datasetName), &H5Dclose, errorMessage.c_str());
// the object in the HDF5 file may have one additional dimension which we
// interprete as the pixel type's bands
int offset = (numBandsOfType > 1)
? 1
: 0;
vigra_precondition((N + offset ) == MultiArrayIndex(dimshape.size()),
"HDF5File::read(): Array dimension disagrees with dataset dimension.");
typename MultiArrayShape<N>::type shape;
for(int k=offset; k < (int)dimshape.size(); ++k)
shape[k-offset] = (MultiArrayIndex)dimshape[k];
vigra_precondition(shape == array.shape(),
"HDF5File::read(): Array shape disagrees with dataset shape.");
if (offset)
vigra_precondition(dimshape[0] == static_cast<hsize_t>(numBandsOfType),
"HDF5File::read(): Band count doesn't match destination array compound type.");
herr_t status = 0;
if(array.isUnstrided())
{
// when the array is unstrided, we can read the data directly into the array buffer
status = H5Dread(datasetHandle, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, array.data() );
}
else
{
// otherwise, we need an intermediate buffer
ArrayVector<hsize_t> null(dimshape.size(), 0),
chunks(dimshape.size(), 1),
start(dimshape.size(), 0),
count(dimshape.size(), 1);
HDF5Handle properties(H5Dget_create_plist(datasetHandle),
&H5Pclose, "HDF5File::read(): failed to get property list");
if(H5D_CHUNKED == H5Pget_layout(properties))
{
// if the file is chunked, we use a buffer that matches the chunk size.
H5Pget_chunk(properties, chunks.size(), chunks.data());
std::reverse(chunks.begin(), chunks.end());
}
else
{
// otherwise, we compute a suitable chunk size.
chunks[0] = numBandsOfType;
MultiArrayIndex prod = 1;
for(unsigned int k=0; k<N; ++k)
{
chunks[k+offset] = array.shape(k);
prod *= array.shape(k);
if(prod > 300000)
break;
}
}
count[N-1-offset] = numBandsOfType;
typedef typename MultiArrayShape<N>::type Shape;
Shape chunkCount, chunkMaxShape;
for(unsigned int k=offset; k<chunks.size(); ++k)
{
chunkMaxShape[k-offset] = chunks[k];
chunkCount[k-offset] = (MultiArrayIndex)std::ceil(double(dimshape[k]) / chunks[k]);
}
typename CoupledIteratorType<N>::type chunkIter = createCoupledIterator(chunkCount),
chunkEnd = chunkIter.getEndIterator();
for(; chunkIter != chunkEnd; ++chunkIter)
{
Shape chunkStart(chunkIter.point() * chunkMaxShape),
chunkStop(min(chunkStart + chunkMaxShape, array.shape()));
MultiArray<N, T> buffer(chunkStop - chunkStart);
for(unsigned int k=0; k<N; ++k)
{
start[N-1-k] = chunkStart[k];
count[N-1-k] = buffer.shape(k);
}
if(offset == 1)
{
start[N] = 0;
count[N] = numBandsOfType;
}
HDF5Handle filespace(H5Dget_space(datasetHandle),
&H5Sclose, "HDF5File::read(): unable to create hyperslabs.");
status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, start.data(), NULL, count.data(), NULL);
if(status < 0)
break;
HDF5Handle dataspace(H5Screate_simple(count.size(), count.data(), NULL),
&H5Sclose, "HDF5File::read(): unable to create hyperslabs.");
status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, null.data(), NULL, count.data(), NULL);
if(status < 0)
break;
status = H5Dread(datasetHandle, datatype, dataspace, filespace, H5P_DEFAULT, buffer.data());
if(status < 0)
break;
array.subarray(chunkStart, chunkStop) = buffer;
}
}
vigra_postcondition(status >= 0,
"HDF5File::read(): read from dataset '" + datasetName + "' via H5Dread() failed.");
}
/********************************************************************/
template<unsigned int N, class T, class Stride>
void HDF5File::readBlock_(std::string datasetName,
typename MultiArrayShape<N>::type &blockOffset,
typename MultiArrayShape<N>::type &blockShape,
MultiArrayView<N, T, Stride> &array,
const hid_t datatype, const int numBandsOfType)
{
//Prepare to read without using HDF5ImportInfo
//ArrayVector<hsize_t> dimshape = getDatasetShape(datasetName) ;
hssize_t dimensions = getDatasetDimensions(datasetName);
std::string errorMessage ("HDF5File::readBlock(): Unable to open dataset '" + datasetName + "'.");
HDF5Handle datasetHandle (getDatasetHandle_(datasetName), &H5Dclose, errorMessage.c_str());
int offset = (numBandsOfType > 1)
? 1
: 0;
vigra_precondition(( (N + offset ) == MultiArrayIndex(dimensions)), // the object in the HDF5 file may have one additional dimension which we then interpret as the pixel type bands
"HDF5File::readBlock(): Array dimension disagrees with data dimension.");
vigra_precondition(blockShape == array.shape(),
"HDF5File::readBlock(): Array shape disagrees with block size.");
// hyperslab parameters for position, size, ...
hsize_t boffset [N];
hsize_t bshape [N];
hsize_t bones [N];
for(int i = 0; i < N; i++){
// vigra and hdf5 use different indexing
boffset[i] = blockOffset[N-1-i];
//bshape[i] = blockShape[i];
bshape[i] = blockShape[N-1-i];
//boffset[i] = blockOffset[N-1-i];
bones[i] = 1;
}
// create a target dataspace in memory with the shape of the desired block
HDF5Handle memspace_handle(H5Screate_simple(N,bshape,NULL),&H5Sclose,
"Unable to create target dataspace");
// get file dataspace and select the desired block
HDF5Handle dataspaceHandle(H5Dget_space(datasetHandle),&H5Sclose,
"Unable to get dataspace");
H5Sselect_hyperslab(dataspaceHandle, H5S_SELECT_SET, boffset, bones, bones, bshape);
herr_t status = 0;
if(array.isUnstrided())
{
// when the array is unstrided, we can read the data directly into the array buffer
status = H5Dread( datasetHandle, datatype, memspace_handle, dataspaceHandle, H5P_DEFAULT, array.data());
}
else
{
// otherwise, we need an unstrided extra buffer ...
MultiArray<N, T> buffer(array.shape());
status = H5Dread( datasetHandle, datatype, memspace_handle, dataspaceHandle, H5P_DEFAULT, buffer.data());
// ... and must copy the values
if(status >= 0)
array = buffer;
}
vigra_postcondition(status >= 0,
"HDF5File::readBlock(): read from dataset '" + datasetName + "' via H5Dread() failed.");
}
/********************************************************************/
template<unsigned int N, class T, class Stride>
void HDF5File::read_attribute_(std::string datasetName,
std::string attributeName,
MultiArrayView<N, T, Stride> array,
const hid_t datatype, const int numBandsOfType)
{
std::string dataset_path = get_absolute_path(datasetName);
// open Attribute handle
std::string message = "HDF5File::readAttribute(): could not get handle for attribute '"+attributeName+"'' of object '"+dataset_path+"'.";
HDF5Handle attr_handle (H5Aopen_by_name(fileHandle_,dataset_path.c_str(),attributeName.c_str(),H5P_DEFAULT,H5P_DEFAULT),&H5Aclose, message.c_str());
// get Attribute dataspace
message = "HDF5File::readAttribute(): could not get dataspace for attribute '"+attributeName+"'' of object '"+dataset_path+"'.";
HDF5Handle attr_dataspace_handle (H5Aget_space(attr_handle),&H5Sclose,message.c_str());
// obtain Attribute shape
int raw_dims = H5Sget_simple_extent_ndims(attr_dataspace_handle);
int dims = std::max(raw_dims, 1); // scalar attributes may be stored with raw_dims==0
ArrayVector<hsize_t> dimshape(dims);
if(raw_dims > 0)
H5Sget_simple_extent_dims(attr_dataspace_handle, dimshape.data(), NULL);
else
dimshape[0] = 1;
// invert the dimensions to guarantee VIGRA-compatible order
std::reverse(dimshape.begin(), dimshape.end());
int offset = (numBandsOfType > 1)
? 1
: 0;
message = "HDF5File::readAttribute(): Array dimension disagrees with dataset dimension.";
// the object in the HDF5 file may have one additional dimension which we then interpret as the pixel type bands
vigra_precondition((N + offset) == MultiArrayIndex(dims), message);
for(int k=offset; k < (int)dimshape.size(); ++k)
vigra_precondition(array.shape()[k-offset] == (MultiArrayIndex)dimshape[k],
"HDF5File::readAttribute(): Array shape disagrees with dataset shape");
herr_t status = 0;
if(array.isUnstrided())
{
// when the array is unstrided, we can read the data directly into the array buffer
status = H5Aread( attr_handle, datatype, array.data());
}
else
{
// otherwise, we need an unstrided extra buffer ...
// (we assume that attributes are small arrays, so that the wasted memory is uncritical)
MultiArray<N, T> buffer(array.shape());
status = H5Aread( attr_handle, datatype, buffer.data() );
// ... and must copy the values
if(status >= 0)
array = buffer;
}
vigra_postcondition(status >= 0,
"HDF5File::readAttribute(): read from attribute '" + attributeName + "' via H5Aread() failed.");
}
/********************************************************************/
/** \brief Read the data specified by the given \ref vigra::HDF5ImportInfo object
and write the into the given 'array'.
The array must have the correct number of dimensions and shape for the dataset
represented by 'info'. When the element type of 'array' differs from the stored element
type, HDF5 will convert the type on the fly (except when the HDF5 version is 1.6 or below,
in which case an error will result). Multi-channel element types (i.e. \ref vigra::RGBValue,
\ref vigra::TinyVector, and \ref vigra::FFTWComplex) are recognized and handled correctly.
<b> Declaration:</b>
\code
namespace vigra {
template<unsigned int N, class T, class StrideTag>
void
readHDF5(const HDF5ImportInfo &info, MultiArrayView<N, T, StrideTag> array);
}
\endcode
<b> Usage:</b>
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
\code
HDF5ImportInfo info(filename, dataset_name);
vigra_precondition(info.numDimensions() == 3, "Dataset must be 3-dimensional.");
MultiArrayShape<3>::type shape(info.shape().begin());
MultiArray<3, int> array(shape);
readHDF5(info, array);
\endcode
*/
doxygen_overloaded_function(template <...> void readHDF5)
template<unsigned int N, class T, class StrideTag>
inline void readHDF5(const HDF5ImportInfo &info, MultiArrayView<N, T, StrideTag> array)
{
readHDF5(info, array, 0, 0); // last two arguments are not used
}
template<unsigned int N, class T, class StrideTag>
void readHDF5(const HDF5ImportInfo &info, MultiArrayView<N, T, StrideTag> array, const hid_t datatype, const int numBandsOfType)
{
HDF5File file(info.getFilePath(), HDF5File::OpenReadOnly);
file.read(info.getPathInFile(), array);
file.close();
}
inline hid_t openGroup(hid_t parent, std::string group_name)
{
//std::cout << group_name << std::endl;
size_t last_slash = group_name.find_last_of('/');
if (last_slash == std::string::npos || last_slash != group_name.size() - 1)
group_name = group_name + '/';
std::string::size_type begin = 0, end = group_name.find('/');
int ii = 0;
while (end != std::string::npos)
{
std::string group(group_name.begin()+begin, group_name.begin()+end);
hid_t prev_parent = parent;
parent = H5Gopen(prev_parent, group.c_str(), H5P_DEFAULT);
if(ii != 0) H5Gclose(prev_parent);
if(parent < 0) return parent;
++ii;
begin = end + 1;
end = group_name.find('/', begin);
}
return parent;
}
inline hid_t createGroup(hid_t parent, std::string group_name)
{
if(group_name.size() == 0 ||*group_name.rbegin() != '/')
group_name = group_name + '/';
if(group_name == "/")
return H5Gopen(parent, group_name.c_str(), H5P_DEFAULT);
std::string::size_type begin = 0, end = group_name.find('/');
int ii = 0;
while (end != std::string::npos)
{
std::string group(group_name.begin()+begin, group_name.begin()+end);
hid_t prev_parent = parent;
if(H5LTfind_dataset(parent, group.c_str()) == 0)
{
parent = H5Gcreate(prev_parent, group.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
} else {
parent = H5Gopen(prev_parent, group.c_str(), H5P_DEFAULT);
}
if(ii != 0) H5Gclose(prev_parent);
if(parent < 0) return parent;
++ii;
begin = end + 1;
end = group_name.find('/', begin);
}
return parent;
}
inline void deleteDataset(hid_t parent, std::string dataset_name)
{
// delete existing data and create new dataset
if(H5LTfind_dataset(parent, dataset_name.c_str()))
{
//std::cout << "dataset already exists" << std::endl;
#if (H5_VERS_MAJOR == 1 && H5_VERS_MINOR <= 6)
if(H5Gunlink(parent, dataset_name.c_str()) < 0)
{
vigra_postcondition(false, "writeToHDF5File(): Unable to delete existing data.");
}
#else
if(H5Ldelete(parent, dataset_name.c_str(), H5P_DEFAULT ) < 0)
{
vigra_postcondition(false, "createDataset(): Unable to delete existing data.");
}
#endif
}
}
inline hid_t createFile(std::string filePath, bool append_ = true)
{
FILE * pFile;
pFile = fopen ( filePath.c_str(), "r" );
hid_t file_id;
if ( pFile == NULL )
{
file_id = H5Fcreate(filePath.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
}
else if(append_)
{
fclose( pFile );
file_id = H5Fopen(filePath.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
}
else
{
fclose(pFile);
std::remove(filePath.c_str());
file_id = H5Fcreate(filePath.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
}
return file_id;
}
template<unsigned int N, class T, class Tag>
void createDataset(const char* filePath, const char* pathInFile, const MultiArrayView<N, T, Tag> & array, const hid_t datatype, const int numBandsOfType, HDF5Handle & file_handle, HDF5Handle & dataset_handle)
{
std::string path_name(pathInFile), group_name, data_set_name, message;
std::string::size_type delimiter = path_name.rfind('/');
//create or open file
file_handle = HDF5Handle(createFile(filePath), &H5Fclose,
"createDataset(): unable to open output file.");
// get the groupname and the filename
if(delimiter == std::string::npos)
{
group_name = "/";
data_set_name = path_name;
}
else
{
group_name = std::string(path_name.begin(), path_name.begin()+delimiter);
data_set_name = std::string(path_name.begin()+delimiter+1, path_name.end());
}
// create all groups
HDF5Handle group(createGroup(file_handle, group_name), &H5Gclose,
"createDataset(): Unable to create and open group. generic v");
// delete the dataset if it already exists
deleteDataset(group, data_set_name);
// create dataspace
// add an extra dimension in case that the data is non-scalar
HDF5Handle dataspace_handle;
if(numBandsOfType > 1) {
// invert dimensions to guarantee c-order
hsize_t shape_inv[N+1]; // one additional dimension for pixel type channel(s)
for(unsigned int k=0; k<N; ++k) {
shape_inv[N-1-k] = array.shape(k); // the channels (eg of an RGB image) are represented by the first dimension (before inversion)
//std::cout << shape_inv[N-k] << " (" << N << ")";
}
shape_inv[N] = numBandsOfType;
// create dataspace
dataspace_handle = HDF5Handle(H5Screate_simple(N+1, shape_inv, NULL),
&H5Sclose, "createDataset(): unable to create dataspace for non-scalar data.");
} else {
// invert dimensions to guarantee c-order
hsize_t shape_inv[N];
for(unsigned int k=0; k<N; ++k)
shape_inv[N-1-k] = array.shape(k);
// create dataspace
dataspace_handle = HDF5Handle(H5Screate_simple(N, shape_inv, NULL),
&H5Sclose, "createDataset(): unable to create dataspace for scalar data.");
}
//alloc memory for dataset.
dataset_handle = HDF5Handle(H5Dcreate(group,
data_set_name.c_str(),
datatype,
dataspace_handle,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT),
&H5Dclose, "createDataset(): unable to create dataset.");
}
/** \brief Store array data in an HDF5 file.
The number of dimensions, shape and element type of the stored dataset is automatically
determined from the properties of the given \a array. Strided arrays are stored in an
unstrided way, i.e. in contiguous scan-order. Multi-channel element types
(i.e. \ref vigra::RGBValue, \ref vigra::TinyVector and \ref vigra::FFTWComplex)
are recognized and handled correctly
(in particular, the will form the innermost dimension of the stored dataset).
\a pathInFile may contain '/'-separated group names, but must end with the name
of the dataset to be created.
<b> Declaration:</b>
\code
namespace vigra {
template<unsigned int N, class T, class StrideTag>
void
writeHDF5(const char* filePath, const char* pathInFile,
MultiArrayView<N, T, StrideTag>const & array);
}
\endcode
<b> Usage:</b>
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
\code
MultiArrayShape<3>::type shape(100, 200, 20);
MultiArray<3, int> array(shape);
... // fill array with data
writeHDF5("mydata.h5", "/group1/my_dataset", array);
\endcode
*/
doxygen_overloaded_function(template <...> void writeHDF5)
template<unsigned int N, class T, class StrideTag>
inline void writeHDF5(const char* filePath, const char* pathInFile, const MultiArrayView<N, T, StrideTag> & array)
{
//last two arguments are not used
writeHDF5(filePath, pathInFile, array, 0, 0);
}
template<unsigned int N, class T, class StrideTag>
void writeHDF5(const char* filePath, const char* pathInFile, const MultiArrayView<N, T, StrideTag> & array, const hid_t datatype, const int numBandsOfType)
{
HDF5File file(filePath, HDF5File::Open);
file.write(pathInFile, array);
file.close();
}
namespace detail
{
struct MaxSizeFnc
{
size_t size;
MaxSizeFnc()
: size(0)
{}
void operator()(std::string const & in)
{
size = in.size() > size ?
in.size() :
size;
}
};
}
#if (H5_VERS_MAJOR == 1 && H5_VERS_MINOR == 8) || DOXYGEN
/** Write a numeric MultiArray as an attribute with name \a name
of the dataset specified by the handle \a loc.
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
*/
template<size_t N, class T, class C>
void writeHDF5Attr(hid_t loc,
const char* name,
MultiArrayView<N, T, C> const & array)
{
if(H5Aexists(loc, name) > 0)
H5Adelete(loc, name);
ArrayVector<hsize_t> shape(array.shape().begin(),
array.shape().end());
HDF5Handle
dataspace_handle(H5Screate_simple(N, shape.data(), NULL),
&H5Sclose,
"writeToHDF5File(): unable to create dataspace.");
HDF5Handle attr(H5Acreate(loc,
name,
detail::getH5DataType<T>(),
dataspace_handle,
H5P_DEFAULT ,H5P_DEFAULT ),
&H5Aclose,
"writeHDF5Attr: unable to create Attribute");
//copy data - since attributes are small - who cares!
ArrayVector<T> buffer;
for(int ii = 0; ii < array.size(); ++ii)
buffer.push_back(array[ii]);
H5Awrite(attr, detail::getH5DataType<T>(), buffer.data());
}
/** Write a string MultiArray as an attribute with name \a name
of the dataset specified by the handle \a loc.
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
*/
template<size_t N, class C>
void writeHDF5Attr(hid_t loc,
const char* name,
MultiArrayView<N, std::string, C> const & array)
{
if(H5Aexists(loc, name) > 0)
H5Adelete(loc, name);
ArrayVector<hsize_t> shape(array.shape().begin(),
array.shape().end());
HDF5Handle
dataspace_handle(H5Screate_simple(N, shape.data(), NULL),
&H5Sclose,
"writeToHDF5File(): unable to create dataspace.");
HDF5Handle atype(H5Tcopy (H5T_C_S1),
&H5Tclose,
"writeToHDF5File(): unable to create type.");
detail::MaxSizeFnc max_size;
max_size = std::for_each(array.data(),array.data()+ array.size(), max_size);
H5Tset_size (atype, max_size.size);
HDF5Handle attr(H5Acreate(loc,
name,
atype,
dataspace_handle,
H5P_DEFAULT ,H5P_DEFAULT ),
&H5Aclose,
"writeHDF5Attr: unable to create Attribute");
std::string buf ="";
for(int ii = 0; ii < array.size(); ++ii)
{
buf = buf + array[ii]
+ std::string(max_size.size - array[ii].size(), ' ');
}
H5Awrite(attr, atype, buf.c_str());
}
/** Write a numeric ArrayVectorView as an attribute with name \a name
of the dataset specified by the handle \a loc.
<b>\#include</b> \<vigra/hdf5impex.hxx\><br>
Namespace: vigra
*/
template<class T>
inline void writeHDF5Attr( hid_t loc,
const char* name,
ArrayVectorView<T> & array)
{
writeHDF5Attr(loc, name,
MultiArrayView<1, T>(MultiArrayShape<1>::type(array.size()),
array.data()));
}
/** write an Attribute given a file and a path in the file.
the path in the file should have the format
[attribute] or /[subgroups/]dataset.attribute or
/[subgroups/]group.attribute.
The attribute is written to the root group, a dataset or a subgroup
respectively
*/
template<class Arr>
inline void writeHDF5Attr( std::string filePath,
std::string pathInFile,
Arr & ar)
{
std::string path_name(pathInFile), group_name, data_set_name, message, attr_name;
std::string::size_type delimiter = path_name.rfind('/');
//create or open file
HDF5Handle file_id(createFile(filePath), &H5Fclose,
"writeToHDF5File(): unable to open output file.");
// get the groupname and the filename
if(delimiter == std::string::npos)
{
group_name = "/";
data_set_name = path_name;
}
else
{
group_name = std::string(path_name.begin(), path_name.begin()+delimiter);
data_set_name = std::string(path_name.begin()+delimiter+1, path_name.end());
}
delimiter = data_set_name.rfind('.');
if(delimiter == std::string::npos)
{
attr_name = path_name;
data_set_name = "/";
}
else
{
attr_name = std::string(data_set_name.begin()+delimiter+1, data_set_name.end());
data_set_name = std::string(data_set_name.begin(), data_set_name.begin()+delimiter);
}
HDF5Handle group(openGroup(file_id, group_name), &H5Gclose,
"writeToHDF5File(): Unable to create and open group. attr ver");
if(data_set_name != "/")
{
HDF5Handle dset(H5Dopen(group, data_set_name.c_str(), H5P_DEFAULT), &H5Dclose,
"writeHDF5Attr():unable to open dataset");
writeHDF5Attr(hid_t(dset), attr_name.c_str(), ar);
}
else
{
writeHDF5Attr(hid_t(group), attr_name.c_str(), ar);
}
}
#endif
//@}
} // namespace vigra
#endif // VIGRA_HDF5IMPEX_HXX
|