This file is indexed.

/usr/share/pyshared/nxs/tree.py is in python-nxs 4.3.2-svn1919-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
#!/usr/bin/env python
# This program is public domain 
# Author: Paul Kienzle, Ray Osborn

"""
NeXus data as Python trees
==========================
The `nexus.tree` modules are designed to accomplish two goals:

    1. To provide convenient access to existing data contained in NeXus files.
    2. To enable new NeXus data to be created and manipulated interactively.

These goals are achieved by mapping hierarchical NeXus data structures directly
into python objects, which either represent NeXus groups or NeXus fields.
Entries in a group are referenced much like fields in a class are referenced in
python. The entire data hierarchy can be referenced at any time, whether the
NeXus data has been loaded in from an existing NeXus file or created dynamically
within the python session. This provides a much more natural scripting interface
to NeXus data than the directory model of the `nexus.napi` interface.

Example 1: Loading a NeXus file
-------------------------------
The following commands loads NeXus data from a file, displays (some of) the
contents as a tree, and then accesses individual data items.

    >>> from nexpy.api import nexus as nx
    >>> a=nx.load('sns/data/ARCS_7326.nxs')
    >>> print a.tree
    root:NXroot
      @HDF5_Version = 1.8.2
      @NeXus_version = 4.2.1
      @file_name = ARCS_7326.nxs
      @file_time = 2010-05-05T01:59:25-05:00
      entry:NXentry
        data:NXdata
          data = float32(631x461x4x825)
            @axes = rotation_angle:tilt_angle:sample_angle:time_of_flight
            @signal = 1
          rotation_angle = float32(632)
            @units = degree
          sample_angle = [ 210.  215.  220.  225.  230.]
            @units = degree
          tilt_angle = float32(462)
            @units = degree
          time_of_flight = float32(826)
            @units = microsecond
        run_number = 7326
        sample:NXsample
          pulse_time = 2854.94747365
            @units = microsecond
    .
    .
    .
    >>> a.entry.run_number
    NXfield(7326)

So the tree returned from load() has an entry for each group, field and
attribute.  You can traverse the hierarchy using the names of the groups.  For
example, tree.entry.instrument.detector.distance is an example of a field
containing the distance to each pixel in the detector. Entries can also be
referenced by NXclass name, such as tree.NXentry[0].instrument. Since there may
be multiple entries of the same NeXus class, the NXclass attribute returns a
(possibly empty) list.

The load() and save() functions are implemented using the class
`nexus.tree.NeXusTree`, a subclass of `nexus.napi.NeXus` which allows all the
usual API functions.

Example 2: Creating a NeXus file dynamically
--------------------------------------------
The second example shows how to create NeXus data dynamically and saves it to a
file. The data are first created as Numpy arrays

    >>> import numpy as np
    >>> x=y=np.linspace(0,2*np.pi,101)
    >>> X,Y=np.meshgrid(y,x)
    >>> z=np.sin(X)*np.sin(Y)

Then a NeXus data groups are created and the data inserted to produce a
NeXus-compliant structure that can be saved to a file.

    >>> root=nx.NXroot(NXentry())
    >>> print root.tree
    root:NXroot
      entry:NXentry
    >>> root.entry.data=nx.NXdata(z,[x,y])

Additional metadata can be inserted before saving the data to a file.

    >>> root.entry.sample=nx.NXsample()
    >>> root.entry.sample.temperature = 40.0
    >>> root.entry.sample.temperature.units = 'K'
    >>> root.save('example.nxs')

NXfield objects have much of the functionality of Numpy arrays. They may be used
in simple arithmetic expressions with other NXfields, Numpy arrays or scalar
values and will be cast as ndarray objects if used as arguments in Numpy
modules.

    >>> x=nx.NXfield(np.linspace(0,10.0,11))
    >>> x
    NXfield([  0.   1.   2. ...,   8.   9.  10.])
    >>> x + 10
    NXfield([ 10.  11.  12. ...,  18.  19.  20.])
    >>> sin(x)
    array([ 0.        ,  0.84147098,  0.90929743, ...,  0.98935825,
        0.41211849, -0.54402111])

If the arithmetic operation is assigned to a NeXus group attribute, it will be
automatically cast as a valid NXfield object with the type and shape determined
by the Numpy array type and shape.

    >>> entry.data.result = sin(x)
    >>> entry.data.result
    NXfield([ 0.          0.84147098  0.90929743 ...,  0.98935825  0.41211849
     -0.54402111])
    >>> entry.data.result.dtype, entry.data.result.shape
    (dtype('float64'), (11,))

NeXus Objects
-------------
Properties of the entry in the tree are referenced by attributes that depend
on the object type, different nx attributes may be available.

Objects (class NXobject) have attributes shared by both groups and fields::
    * nxname   object name
    * nxclass  object class for groups, 'NXfield' for fields
    * nxgroup  group containing the entry, or None for the root
    * attrs    dictionary of NeXus attributes for the object

Groups (class NXgroup) have attributes for accessing children::
    * entries  dictionary of entries within the group
    * component('nxclass')  return group entries of a particular class
    * dir()    print the list of entries in the group
    * tree     return the list of entries and subentries in the group
    * plot()   plot signal and axes for the group, if available

Fields (class NXfield) have attributes for accessing data:
    * shape    dimensions of data in the field
    * dtype    data type
    * nxdata   data in the field

Linked fields or groups (class NXlink) have attributes for accessing the link::
    * nxlink   reference to the linked field or group

NeXus attributes (class NXattr) have a type and a value only::
    * dtype    attribute type
    * nxdata   attribute data

There is a subclass of NXgroup for each group class defined by the NeXus standard,
so it is possible to create an NXgroup of NeXus class NXsample directly using:

    >>> sample = NXsample()

The default group name will be the class name following the 'NX', so the above
group will have an nxname of 'sample'. However, this is overridden by the
attribute name when it is assigned as a group attribute, e.g.,

    >>> entry.sample1 = NXsample()
    >>> entry.sample1.nxname
    sample1

You can traverse the tree by component class instead of component name. Since
there may be multiple components of the same class in one group you will need to
specify which one to use.  For example,

    tree.NXentry[0].NXinstrument[0].NXdetector[0].distance

references the first detector of the first instrument of the first entry.
Unfortunately, there is no guarantee regarding the order of the entries, and it
may vary from call to call, so this is mainly useful in iterative searches.


Unit Conversion
---------------
Data can be stored in the NeXus file in a variety of units, depending on which
facility is storing the file.  This makes life difficult for reduction and
analysis programs which must know the units they are working with.  Our solution
to this problem is to allow the reader to retrieve data from the file in
particular units.  For example, if detector distance is stored in the file using
millimeters you can retrieve them in meters using::

    entry.instrument.detector.distance.convert('m')

See `nexus.unit` for more details on the unit formats supported.

Reading and Writing Slabs
-------------------------
The slab interface to field data works by opening the file handle and keeping it
open as long as the slab interface is needed.  This is done in python 2.5 using
the with statement.  Once the context is entered, get() and put() methods on the
object allow you to read and write data a slab at a time.  For example::

    # Read a Ni x Nj x Nk array one vector at a time
    with root.NXentry[0].data.data as slab:
        Ni,Nj,Nk = slab.shape
        size = [1,1,Nk]
        for i in range(Ni):
            for j in range(Nj):
                value = slab.get([i,j,0],size)

The equivalent can be done in Python 2.4 and lower using the context
functions __enter__ and __exit__::

    slab = data.slab.__enter__()
    ... do the slab functions ...
    data.slab.__exit__()

Plotting NeXus data
-------------------
There is a plot() method for groups that automatically looks for 'signal' and
'axes' attributes within the group in order to determine what to plot. These are
defined by the 'nxsignal' and 'nxaxes' properties of the group. This means that
the method will determine whether the plot should be one- or two- dimensional.
For higher than two dimensions, only the top slice is plotted by default.

The plot method accepts as arguments the standard matplotlib.pyplot.plot format 
strings to customize one-dimensional plots, axis and scale limits, and will
transmit keyword arguments to the matplotlib plotting methods.

    >>> a=nx.load('chopper.nxs')
    >>> a.entry.monitor1.plot()
    >>> a.entry.monitor2.plot('r+', xmax=2600)
    
It is possible to plot over the existing figure with the oplot() method and to
plot with logarithmic intensity scales with the logplot() method. The x- and
y-axes can also be rendered logarithmically using the logx and logy keywards.

Although the plot() method uses matplotlib by default to plot the data, you can replace
this with your own plotter by setting nexus.NXgroup._plotter to your own plotter
class.  The plotter class has one method::

    plot(signal, axes, entry, title, format, **opts)

where signal is the field containing the data, axes are the fields listing the
signal sample points, entry is file/path within the file to the data group and
title is the title of the group or the parent NXentry, if available.
"""
from __future__ import with_statement
from copy import copy, deepcopy

import numpy as np
import napi
from napi import NeXusError

#Memory in MB
NX_MEMORY = 500

__all__ = ['NeXusTree', 'NXobject', 'NXfield', 'NXgroup', 'NXattr',
           'NX_MEMORY', 'setmemory', 'load', 'save', 'tree', 'centers',
           'NXlink', 'NXlinkfield', 'NXlinkgroup', 'SDS', 'NXlinkdata']

#List of defined base classes (later added to __all__)
_nxclasses = ['NXroot', 'NXentry', 'NXsubentry', 'NXdata', 'NXmonitor',
              'NXlog', 'NXsample', 'NXinstrument', 'NXaperture', 'NXattenuator',
              'NXbeam', 'NXbeam_stop', 'NXbending_magnet', 'NXcharacterization',
              'NXcollection', 'NXcollimator', 'NXcrystal', 'NXdetector',
              'NXdisk_chopper', 'NXenvironment', 'NXevent_data',
              'NXfermi_chopper', 'NXfilter', 'NXflipper', 'NXgeometry',
              'NXguide', 'NXinsertion_device', 'NXmirror', 'NXmoderator',
              'NXmonochromator', 'NXnote', 'NXorientation', 'NXparameter',
              'NXpolarizer', 'NXpositioner', 'NXprocess', 'NXsensor', 'NXshape',
              'NXsource', 'NXtranslation', 'NXuser', 'NXvelocity_selector', 'NXtree']

np.set_printoptions(threshold=5)

class NeXusTree(napi.NeXus):

    """
    Structure-based interface to the NeXus file API.

    Usage::

      file = NeXusTree(filename, ['r','rw','w'])
        - open the NeXus file
      root = file.readfile()
        - read the structure of the NeXus file.  This returns a NeXus tree.
      file.writefile(root)
        - write a NeXus tree to the file.
      data = file.readpath(path)
        - read data from a particular path

    Example::

      nx = NeXusTree('REF_L_1346.nxs','r')
      tree = nx.readfile()
      for entry in tree.NXentry:
          process(entry)
      copy = NeXusTree('modified.nxs','w')
      copy.writefile(tree)

    Note that the large datasets are not loaded immediately.  Instead, the
    when the data set is requested, the file is reopened, the data read, and
    the file closed again.  open/close are available for when we want to
    read/write slabs without the overhead of moving the file cursor each time.
    The NXdata objects in the returned tree hold the object values.
    """

    def readfile(self):
        """
        Read the NeXus file structure from the file and return a tree of NXobjects.

        Large datasets are not read until they are needed.
        """
        self.open()
        self.openpath("/")
        root = self._readgroup()
        self.close()
        root._group = None
        # Resolve links (not necessary now that link is set as a property)
        #self._readlinks(root, root)
        root._file = self
        return root

    def writefile(self, tree):
        """
        Write the NeXus file structure to a file.

        The file is assumed to start empty. Updating individual objects can be
        done using the napi interface, with nx.handle as the nexus file handle.
        """
        self.open()
        links = []
        for entry in tree.entries.values():
            links += self._writegroup(entry, path="")
        self._writelinks(links)
        self.close()

    def readpath(self, path):
        """
        Return the data on a particular file path.

        Returns a numpy array containing the data, a python scalar, or a
        string depending on the shape and storage class.
        """
        self.open()
        self.openpath(path)
        try:
            return self.getdata()
        except ValueError:
            return None

    def _readdata(self, name):
        """
        Read a data object and return it as an NXfield or NXlink.
        """
        # Finally some data, but don't read it if it is big
        # Instead record the location, type and size
        self.opendata(name)
        attrs={}
        attrs = self.getattrs()
        if 'target' in attrs and attrs['target'] != self.path:
            # This is a linked dataset; don't try to load it.
            data = NXlinkfield(target=attrs['target'], name=name)
        else:
            dims,type = self.getinfo()
            #Read in the data if it's not too large
            if np.prod(dims) < 1000:# i.e., less than 1k dims
                try:
                    value = self.getdata()
                except ValueError:
                    value = None
            else:
                value = None
            data = NXfield(value=value,name=name,dtype=type,shape=dims,attrs=attrs)
        self.closedata()
        data._infile = data._saved = data._changed = True
        return data

    # These are groups that HDFView explicitly skips
    _skipgroups = ['CDF0.0','_HDF_CHK_TBL_','Attr0.0','RIG0.0','RI0.0',
                   'RIATTR0.0N','RIATTR0.0C']

    def _readchildren(self,n):
        children = {}
        for _item in range(n):
            name,nxclass = self.getnextentry()
            if nxclass in self._skipgroups:
                pass # Skip known bogus classes
            elif nxclass == 'SDS': # NXgetnextentry returns 'SDS' as the class for NXfields
                children[name] = self._readdata(name)
            else:
                self.opengroup(name,nxclass)
                children[name] = self._readgroup()
                self.closegroup()
        return children

    def _readgroup(self):
        """
        Read the currently open group and return it as an NXgroup.
        """
        n,name,nxclass = self.getgroupinfo()
        attrs = {}
        attrs = self.getattrs()
        if 'target' in attrs and attrs['target'] != self.path:
            # This is a linked group; don't try to load it.
            group = NXlinkgroup(target=attrs['target'], name=name)
        else:
            children = self._readchildren(n)
            # If we are subclassed with a handler for the particular
            # NXentry class name use that constructor for the group
            # rather than the generic NXgroup class.
            group = NXgroup(nxclass=nxclass,name=name,attrs=attrs,entries=children)
            # Build chain back structure
            for obj in children.values():
                obj._group = group
        group._infile = group._saved = group._changed = True
        return group

    def _readlinks(self, root, group):
        """
        Convert linked objects into direct references.
        """
        for entry in group.entries.values():
            if isinstance(entry, NXlink):
                link = root
                try:
                    for level in entry._target[1:].split('/'):
                        link = getattr(link,level)
                    entry.nxlink = link
                except AttributeError:
                    pass
            elif isinstance(entry, NXgroup):
                self._readlinks(root, entry)

    def _writeattrs(self, attrs):
        """
        Return the attributes for the currently open group/data.

        If no group or data object is open, the file attributes are returned.
        """
        for name,pair in attrs.iteritems():
            self.putattr(name,pair.nxdata,pair.dtype)

    def _writedata(self, data, path):
        """
        Write the given data to a file.

        NXlinks cannot be written until the linked group is created, so
        this routine returns the set of links that need to be written.
        Call writelinks on the list.
        """

        path = path + "/" + data.nxname

        # If the data is linked then
        if hasattr(data,'_target'):
            return [(path, data._target)]

        shape = data.shape
        if shape == (): shape = (1,)

        #If the array size is too large, their product needs a long integer
        if np.prod(shape) > 10000:
            # Compress the fastest moving dimension of large datasets
            slab_dims = np.ones(len(shape),'i')
            if shape[-1] < 100000:
                slab_dims[-1] = shape[-1]
            else:
                slab_dims[-1] = 100000
            self.compmakedata(data.nxname, data.dtype, shape, 'lzw', slab_dims)
        else:
            # Don't use compression for small datasets
            try:
                self.makedata(data.nxname, data.dtype, shape)
            except StandardError,errortype:
                print "Error in tree, makedata: ",errortype

        self.opendata(data.nxname)
        self._writeattrs(data.attrs)
        value = data.nxdata
        if value is not None:
            self.putdata(data.nxdata)
        self.closedata()
        return []

    def _writegroup(self, group, path):
        """
        Write the given group structure, including the data.

        NXlinks cannot be written until the linked group is created, so
        this routine returns the set of links that need to be written.
        Call writelinks on the list.
        """
        path = path + "/" + group.nxname

        links = []
        self.makegroup(group.nxname, group.nxclass)
        self.opengroup(group.nxname, group.nxclass)
        self._writeattrs(group.attrs)
        if hasattr(group, '_target'):
            links += [(path, group._target)]
        for child in group.entries.values():
            if child.nxclass == 'NXfield':
                links += self._writedata(child,path)
            elif hasattr(child,'_target'):
                links += [(path+"/"+child.nxname,child._target)]
            else:
                links += self._writegroup(child,path)
        self.closegroup()
        return links

    def _writelinks(self, links):
        """
        Create links within the NeXus file.

        THese are defined by the set of pairs returned by _writegroup.
        """
        gid = {}

        # identify targets
        for path,target in links:
            gid[target] = None

        # find gids for targets
        for target in gid.iterkeys():
            self.openpath(target)
            # Can't tell from the name if we are linking to a group or
            # to a dataset, so cheat and rely on getdataID to signal
            # an error if we are not within a group.
            try:
                gid[target] = self.getdataID()
            except NeXusError:
                gid[target] = self.getgroupID()

        # link sources to targets
        for path,target in links:
            if path != target:
                # ignore self-links
                parent = "/".join(path.split("/")[:-1])
                self.openpath(parent)
                self.makelink(gid[target])


def _readaxes(axes):
    """
    Return a list of axis names stored in the 'axes' attribute.

    The delimiter separating each axis can be white space, a comma, or a colon.
    """
    import re
    sep=re.compile('[\[]*(\s*,*:*)+[\]]*')
    return filter(lambda x: len(x)>0, sep.split(axes))


class AttrDict(dict):

    """
    A dictionary class to assign all attributes to the NXattr class.
    """

    def __setitem__(self, key, value):
        if isinstance(value, NXattr):
            dict.__setitem__(self, key, value)
        else:
            dict.__setitem__(self, key, NXattr(value))


class NXattr(object):

    """
    Class for NeXus attributes of a NXfield or NXgroup object.

    This class is only used for NeXus attributes that are stored in a
    NeXus file and helps to distinguish them from Python attributes.
    There are two Python attributes for each NeXus attribute.

    Python Attributes
    -----------------
    nxdata : string, Numpy scalar, or Numpy ndarray
        The value of the NeXus attribute.
    dtype : string
        The data type of the NeXus attribute. This is set to 'char' for
        a string attribute or the string of the corresponding Numpy data type
        for a numeric attribute.

    NeXus Attributes
    ----------------
    NeXus attributes are stored in the 'attrs' dictionary of the parent object,
    NXfield or NXgroup, but can often be referenced or assigned using the
    attribute name as if it were an object attribute.

    For example, after assigning the NXfield, the following three attribute
    assignments are all equivalent::

        >>> entry.sample.temperature = NXfield(40.0)
        >>> entry.sample.temperature.attrs['units'] = 'K'
        >>> entry.sample.temperature.units = NXattr('K')
        >>> entry.sample.temperature.units = 'K'

    The third version above is only allowed for NXfield attributes and is
    not allowed if the attribute has the same name as one of the following
    internally defined attributes, i.e.,

    ['entries', 'attrs', 'dtype','shape']

    or if the attribute name begins with 'nx' or '_'. It is only possible to
    reference attributes with one of the proscribed names using the 'attrs'
    dictionary.

    """

    def __init__(self,value=None,dtype=''):
        if isinstance(value, NXattr):
            self._data,self._dtype = value.nxdata,value.dtype
        elif dtype:
            if dtype in np.typeDict:
                self._data,self._dtype = np.__dict__[dtype](value),dtype
            elif dtype == 'char':
                self._data,self._dtype = str(value),dtype
            else:
                raise NeXusError("Invalid data type")
        else:
            if isinstance(value, str):
                self._data,self._dtype = str(value), 'char'
            elif value is not None:
                if isinstance(value, NXobject):
                    raise NeXusError("A data attribute cannot be a NXfield or NXgroup")
                else:
                    self._data = np.array(value)
                self._dtype = self._data.dtype.name
                if self._data.size == 1:
                    self._data = np.__dict__[self._dtype](self._data)
            else:
                self._data,self._dtype = None, 'char'

    def __str__(self):
        return str(self.nxdata)

    def __repr__(self):
        if str(self.dtype) == 'char':
            return "NXattr('%s')"%self.nxdata
        else:
            return "NXattr(%s)"%self.nxdata

    def __eq__(self, other):
        """
        Return true if the value of the attribute is the same as the other.
        """
        if isinstance(other, NXattr):
            return self.nxdata == other.nxdata
        else:
            return self.nxdata == other

    def _getdata(self):
        """
        Return the attribute value.
        """
        return self._data

    def _getdtype(self):
        return self._dtype

    nxdata = property(_getdata,doc="The attribute values")
    dtype = property(_getdtype, "Data type of NeXus attribute")

_npattrs = filter(lambda x: not x.startswith('_'), np.ndarray.__dict__.keys())

class NXobject(object):

    """
    Abstract base class for elements in NeXus files.

    The object has a subclass of NXfield, NXgroup, or one of the NXgroup
    subclasses. Child nodes should be accessible directly as object attributes.
    Constructors for NXobject objects are defined by either the NXfield or
    NXgroup classes.

    Python Attributes
    -----------------
    nxclass : string
        The class of the NXobject. NXobjects can have class NXfield, NXgroup, or
        be one of the NXgroup subclasses.
    nxname : string
        The name of the NXobject. Since it is possible to reference the same
        Python object multiple times, this is not necessarily the same as the
        object name. However, if the object is part of a NeXus tree, this will
        be the attribute name within the tree.
    nxgroup : NXgroup
        The parent group containing this object within a NeXus tree. If the
        object is not part of any NeXus tree, it will be set to None.
    nxpath : string
        The path to this object with respect to the root of the NeXus tree. For
        NeXus data read from a file, this will be a group of class NXroot, but
        if the NeXus tree was defined interactively, it can be any valid
        NXgroup.
    nxroot : NXgroup
        The root object of the NeXus tree containing this object. For
        NeXus data read from a file, this will be a group of class NXroot, but
        if the NeXus tree was defined interactively, it can be any valid
        NXgroup.
    nxfile : NeXusTree
        The file handle of the root object of the NeXus tree containing this
        object.
    filename : string
        The file name of NeXus object's tree file handle.
    attrs : dict
        A dictionary of the NeXus object's attributes.

    Methods
    -------
    dir(self, attrs=False, recursive=False):
        Print the group directory.

        The directory is a list of NeXus objects within this group, either NeXus
        groups or NXfield data. If 'attrs' is True, NXfield attributes are
        displayed. If 'recursive' is True, the contents of child groups are also
        displayed.

    tree:
        Return the object's tree as a string.

        It invokes the 'dir' method with both 'attrs' and 'recursive'
        set to True. Note that this is defined as a property attribute and
        does not require parentheses.

    save(self, filename, format='w5')
        Save the NeXus group into a file

        The object is wrapped in an NXroot group (with name 'root') and an
        NXentry group (with name 'entry'), if necessary, in order to produce
        a valid NeXus file.

    """

    _class = "unknown"
    _name = "unknown"
    _group = None
    _file = None
    _infile = False
    _saved = False
    _changed = True

    def __str__(self):
        return "%s:%s"%(self.nxclass,self.nxname)

    def __repr__(self):
        return "NXobject('%s','%s')"%(self.nxclass,self.nxname)

    def _setattrs(self, attrs):
        for k,v in attrs.items():
            self._attrs[k] = v

    def _str_name(self,indent=0):
        if self.nxclass == 'NXfield':
            return " "*indent+self.nxname
        else:
            return " "*indent+self.nxname+':'+self.nxclass

    def _str_value(self,indent=0):
        return ""

    def _str_attrs(self,indent=0):
        names = self.attrs.keys()
        names.sort()
        result = []
        for k in names:
            result.append(" "*indent+"@%s = %s"%(k,self.attrs[k].nxdata))
        return "\n".join(result)

    def _str_tree(self,indent=0,attrs=False,recursive=False):
        """
        Print current object and possibly children.
        """
        result = [self._str_name(indent=indent)]
        if attrs and self.attrs:
            result.append(self._str_attrs(indent=indent+2))
        # Print children
        entries = self.entries
        if entries:
            names = entries.keys()
            names.sort()
            if recursive:
                for k in names:
                    result.append(entries[k]._str_tree(indent=indent+2,
                                                       attrs=attrs, recursive=True))
            else:
                for k in names:
                    result.append(entries[k]._str_name(indent=indent+2))
        result
        return "\n".join(result)

    def walk(self):
        if False: yield

    def dir(self,attrs=False,recursive=False):
        """
        Print the object directory.

        The directory is a list of NeXus objects within this object, either
        NeXus groups or NXfields. If 'attrs' is True, NXfield attributes are
        displayed. If 'recursive' is True, the contents of child groups are
        also displayed.
        """
        print self._str_tree(attrs=attrs,recursive=recursive)

    @property
    def tree(self):
        """
        Return the directory tree as a string.

        The tree contains all child objects of this object and their children.
        It invokes the 'dir' method with both 'attrs' and 'recursive' set
        to True.
        """
        return self._str_tree(attrs=True,recursive=True)

    def __enter__(self):
        """
        Open the datapath for reading or writing.

        Note: the results are undefined if you try accessing
        more than one slab at a time.  Don't nest your
        "with data" statements!
        """
        self._close_on_exit = not self.nxfile.isopen
        self.nxfile.open() # Force file open even if closed
        self.nxfile.openpath(self.nxpath)
        self._incontext = True
        return self.nxfile

    def __exit__(self, type, value, traceback):
        """
        Close the file associated with the data.
        """
        self._incontext = False
        if self._close_on_exit:
            self.nxfile.close()

    def save(self, filename=None, format='w5'):
        """
        Save the NeXus object to a data file.

        An error is raised if the object is an NXroot group from an external file
        that has been opened as readonly and no file name is specified.

        The object is wrapped in an NXroot group (with name 'root') and an
        NXentry group (with name 'entry'), if necessary, in order to produce
        a valid NeXus file.
        
        Example
        -------
        >>> data = NXdata(sin(x), x)
        >>> data.save('file.nxs')
        >>> print data.nxroot.tree
        root:NXroot
          @HDF5_Version = 1.8.2
          @NeXus_version = 4.2.1
          @file_name = file.nxs
          @file_time = 2012-01-20T13:14:49-06:00
          entry:NXentry
            data:NXdata
              axis1 = float64(101)
              signal = float64(101)
                @axes = axis1
                @signal = 1              
        >>> root.entry.data.axis1.units = 'meV'
        >>> root.save()
        """
        if filename:
            if self.nxclass == "NXroot":
                root = self
            elif self.nxclass == "NXentry":
                root = NXroot(self)
            else:
                root = NXroot(NXentry(self))
            if root.nxfile: root.nxfile.close()
            file = NeXusTree(filename, format)
            file.writefile(root)
            file.close()
            root._file = NeXusTree(filename, 'rw')
            root._setattrs(root._file.getattrs())
            for node in root.walk():
                node._infile = node._saved = True
            
        elif self.nxfile:
            for entry in self.nxroot.values():
                entry.write()

        else:
            raise NeXusError("No output file specified")

    @property
    def infile(self):
        """
        Returns True if the object has been created in a NeXus file.
        """
        return self._infile
    
    @property
    def saved(self):
        """
        Returns True if the object has been saved to a file.
        """
        return self._saved

    @property
    def changed(self):
        """
        Returns True if the object has been changed.
        
        This property is for use by external scripts that need to track
        which NeXus objects have been changed.
        """
        return self._changed
    
    def set_unchanged(self, recursive=False):
        """
        Set an object's change status to unchanged.
        """
        if recursive:
            for node in self.walk():
                node._changed = False
        else:
            self._changed = False
    
    def _getclass(self):
        return self._class

    def _getname(self):
        return self._name

    def _setname(self, value):
        self._name = str(value)

    def _getgroup(self):
        return self._group

    def _getpath(self):
        if self.nxgroup is None:
            return ""
        elif isinstance(self.nxgroup, NXroot):
            return "/" + self.nxname
        else:
            return self.nxgroup._getpath()+"/"+self.nxname

    def _getroot(self):
        if self.nxgroup is None:
            return self
        elif isinstance(self.nxgroup, NXroot):
            return self.nxgroup
        else:
            return self.nxgroup._getroot()

    def _getfile(self):
        return self.nxroot._file

    def _getfilename(self):
        return self.nxroot._file.filename

    def _getattrs(self):
        return self._attrs

    nxclass = property(_getclass, doc="Class of NeXus object")
    nxname = property(_getname, _setname, doc="Name of NeXus object")
    nxgroup = property(_getgroup, doc="Parent group of NeXus object")
    nxpath = property(_getpath, doc="Path to NeXus object")
    nxroot = property(_getroot, doc="Root group of NeXus object's tree")
    nxfile = property(_getfile, doc="File handle of NeXus object's tree")
    attrs = property(_getattrs, doc="NeXus attributes for an object")


class NXfield(NXobject):

    """
    A NeXus data field.

    This is a subclass of NXobject that contains scalar, array, or string data
    and associated NeXus attributes.

    NXfield(value=None, name='unknown', dtype='', shape=[], attrs={}, file=None,
            path=None, group=None, **attr)

    Input Parameters
    ----------------
    value : scalar value, Numpy array, or string
        The numerical or string value of the NXfield, which is directly
        accessible as the NXfield attribute 'nxdata'.
    name : string
        The name of the NXfield, which is directly accessible as the NXfield
        attribute 'name'. If the NXfield is initialized as the attribute of a
        parent object, the name is automatically set to the name of this
        attribute.
    dtype : string
        The data type of the NXfield value, which is directly accessible as the
        NXfield attribute 'dtype'. Valid input types correspond to standard
        Numpy data types, using names defined by the NeXus API,
        i.e., 'float32' 'float64'
              'int8' 'int16' 'int32' 'int64'
              'uint8' 'uint16' 'uint32' 'uint64'
              'char'
        If the data type is not specified, then it is determined automatically
        by the data type of the 'value' parameter.
    shape : list of ints
        The dimensions of the NXfield data, which is accessible as the NXfield
        attribute 'shape'. This corresponds to the shape of the Numpy array.
        Scalars (numeric or string) are stored as Numpy zero-rank arrays,
        for which shape=[].
    attrs : dict
        A dictionary containing NXfield attributes. The dictionary values should
        all have class NXattr.
    file : filename
        The file from which the NXfield has been read.
    path : string
        The path to this object with respect to the root of the NeXus tree,
        using the convention for unix file paths.
    group : NXgroup or subclass of NXgroup
        The parent NeXus object. If the NXfield is initialized as the attribute
        of a parent group, this attribute is automatically set to the parent group.

    Python Attributes
    -----------------
    nxclass : 'NXfield'
        The class of the NXobject.
    nxname : string
        The name of the NXfield. Since it is possible to reference the same
        Python object multiple times, this is not necessarily the same as the
        object name. However, if the field is part of a NeXus tree, this will
        be the attribute name within the tree.
    nxgroup : NXgroup
        The parent group containing this field within a NeXus tree. If the
        field is not part of any NeXus tree, it will be set to None.
    dtype : string or Numpy dtype
        The data type of the NXfield value. If the NXfield has been initialized
        but the data values have not been read in or defined, this is a string.
        Otherwise, it is set to the equivalent Numpy dtype.
    shape : list or tuple of ints
        The dimensions of the NXfield data. If the NXfield has been initialized
        but the data values have not been read in or defined, this is a list of
        ints. Otherwise, it is set to the equivalent Numpy shape, which is a
        tuple. Scalars (numeric or string) are stored as Numpy zero-rank arrays,
        for which shape=().
    attrs : dict
        A dictionary of all the NeXus attributes associated with the field.
        These are objects with class NXattr.
    nxdata : scalar, Numpy array or string
        The data value of the NXfield. This is normally initialized using the
        'value' parameter (see above). If the NeXus data is contained
        in a file and the size of the NXfield array is too large to be stored
        in memory, the value is not read in until this attribute is directly
        accessed. Even then, if there is insufficient memory, a value of None
        will be returned. In this case, the NXfield array should be read as a
        series of smaller slabs using 'get'.
    nxdata_as('units') : scalar value or Numpy array
        If the NXfield 'units' attribute has been set, the data values, stored
        in 'nxdata', are returned after conversion to the specified units.
    nxpath : string
        The path to this object with respect to the root of the NeXus tree. For
        NeXus data read from a file, this will be a group of class NXroot, but
        if the NeXus tree was defined interactively, it can be any valid
        NXgroup.
    nxroot : NXgroup
        The root object of the NeXus tree containing this object. For
        NeXus data read from a file, this will be a group of class NXroot, but
        if the NeXus tree was defined interactively, it can be any valid
        NXgroup.

    NeXus Attributes
    ----------------
    NeXus attributes are stored in the 'attrs' dictionary of the NXfield, but
    can usually be assigned or referenced as if they are Python attributes, as
    long as the attribute name is not the same as one of those listed above.
    This is to simplify typing in an interactive session and should not cause
    any problems because there is no name clash with attributes so far defined
    within the NeXus standard. When writing modules, it is recommended that the
    attributes always be referenced using the 'attrs' dictionary if there is
    any doubt.

    a) Assigning a NeXus attribute

    In the example below, after assigning the NXfield, the following three
    NeXus attribute assignments are all equivalent:

        >>> entry.sample.temperature = NXfield(40.0)
        >>> entry.sample.temperature.attrs['units'] = 'K'
        >>> entry.sample.temperature.units = NXattr('K')
        >>> entry.sample.temperature.units = 'K'

    b) Referencing a NeXus attribute

    If the name of the NeXus attribute is not the same as any of the Python
    attributes listed above, or one of the methods listed below, or any of the
    attributes defined for Numpy arrays, they can be referenced as if they were
    a Python attribute of the NXfield. However, it is only possible to reference
    attributes with one of the proscribed names using the 'attrs' dictionary.

        >>> entry.sample.temperature.tree = 10.0
        >>> entry.sample.temperature.tree
        temperature = 40.0
          @tree = 10.0
          @units = K
        >>> entry.sample.temperature.attrs['tree']
        NXattr(10.0)

    Numerical Operations on NXfields
    --------------------------------
    NXfields usually consist of arrays of numeric data with associated
    meta-data, the NeXus attributes. The exception is when they contain
    character strings. This makes them similar to Numpy arrays, and this module
    allows the use of NXfields in numerical operations in the same way as Numpy
    ndarrays. NXfields are technically not a sub-class of the ndarray class, but
    most Numpy operations work on NXfields, returning either another NXfield or,
    in some cases, an ndarray that can easily be converted to an NXfield.

        >>> x = NXfield((1.0,2.0,3.0,4.0))
        >>> print x+1
        [ 2.  3.  4.  5.]
        >>> print 2*x
        [ 2.  4.  6.  8.]
        >>> print x/2
        [ 0.5  1.   1.5  2. ]
        >>> print x**2
        [  1.   4.   9.  16.]
        >>> print x.reshape((2,2))
        [[ 1.  2.]
         [ 3.  4.]]
        >>> y = NXfield((0.5,1.5,2.5,3.5))
        >>> x+y
        NXfield(name=x,value=[ 1.5  3.5  5.5  7.5])
        >>> x*y
        NXfield(name=x,value=[  0.5   3.    7.5  14. ])
        >>> (x+y).shape
        (4,)
        >>> (x+y).dtype
        dtype('float64')

    All these operations return valid NXfield objects containing the same
    attributes as the first NXobject in the expression. The 'reshape' and
    'transpose' methods also return NXfield objects.

    It is possible to use the standard slice syntax.

        >>> x=NXfield(np.linspace(0,10,11))
        >>> x
        NXfield([  0.   1.   2. ...,   8.   9.  10.])
        >>> x[2:5]
        NXfield([ 2.  3.  4.])

    In addition, it is possible to use floating point numbers as the slice
    indices. If one of the indices is not integer, both indices are used to
    extract elements in the array with values between the two index values.

        >>> x=NXfield(np.linspace(0,100.,11))
        >>> x
        NXfield([   0.   10.   20. ...,   80.   90.  100.])
        >>> x[20.:50.]
        NXfield([ 20.  30.  40.  50.])

    The standard Numpy ndarray attributes and methods will also work with
    NXfields, but will return scalars or Numpy arrays.

        >>> x.size
        4
        >>> x.sum()
        10.0
        >>> x.max()
        4.0
        >>> x.mean()
        2.5
        >>> x.var()
        1.25
        >>> x.reshape((2,2)).sum(1)
        array([ 3.,  7.])

    Finally, NXfields are cast as ndarrays for operations that require them.
    The returned value will be the same as for the equivalent ndarray
    operation, e.g.,

    >>> np.sin(x)
    array([ 0.84147098,  0.90929743,  0.14112001, -0.7568025 ])
    >>> np.sqrt(x)
    array([ 1.        ,  1.41421356,  1.73205081,  2.        ])

    Methods
    -------
    dir(self, attrs=False):
        Print the NXfield specification.

        This outputs the name, dimensions and data type of the NXfield.
        If 'attrs' is True, NXfield attributes are displayed.

    tree:
        Return the NXfield's tree.

        It invokes the 'dir' method with both 'attrs' and 'recursive'
        set to True. Note that this is defined as a property attribute and
        does not require parentheses.


    save(self, filename, format='w5')
        Save the NXfield into a file wrapped in a NXroot group and NXentry group
        with default names. This is equivalent to

        >>> NXroot(NXentry(NXfield(...))).save(filename)

    Examples
    --------
    >>> x = NXfield(np.linspace(0,2*np.pi,101), units='degree')
    >>> phi = x.nxdata_as(units='radian')
    >>> y = NXfield(np.sin(phi))

    # Read a Ni x Nj x Nk array one vector at a time
    >>> with root.NXentry[0].data.data as slab:
            Ni,Nj,Nk = slab.shape
            size = [1,1,Nk]
            for i in range(Ni):
                for j in range(Nj):
                    value = slab.get([i,j,0],size)

    """

    def __init__(self, value=None, name='field', dtype=None, shape=(), group=None,
                 attrs={}, **attr):
        if isinstance(value, list) or isinstance(value, tuple):
            value = np.array(value)
        self._value = value
        self._class = 'NXfield'
        self._name = name.replace(' ','_')
        self._group = group
        self._dtype = dtype
        if dtype == 'char':
            self._dtype = 'char'
        elif dtype in np.typeDict:
            self._dtype = np.dtype(dtype)
        elif dtype:
            raise NeXusError("Invalid data type: %s" % dtype)
        self._shape = tuple(shape)
        # Append extra keywords to the attribute list
        self._attrs = AttrDict()
        for key in attr.keys():
            attrs[key] = attr[key]
        # Convert NeXus attributes to python attributes
        self._setattrs(attrs)
        if 'units' in attrs:
            units = attrs['units']
        else:
            units = None
        self._incontext = False
        del attrs
        if value is not None and dtype == 'char': value = str(value)
        self._setdata(value)
        self._saved = False
        self._changed = True

    def __repr__(self):
        if self._value is not None:
            if str(self.dtype) == 'char':
                return "NXfield('%s')" % str(self)
            else:
                return "NXfield(%s)" % self._str_value()
        else:
            return "NXfield(dtype=%s,shape=%s)" % (self.dtype,self.shape)

    def __getattr__(self, name):
        """
        Enable standard numpy ndarray attributes if not otherwise defined.
        """
        if name in _npattrs:
            return self.nxdata.__getattribute__(name)
        elif name in self.attrs:
            return self.attrs[name].nxdata
        raise KeyError(name+" not in "+self.nxname)

    def __setattr__(self, name, value):
        """
        Add an attribute to the NXfield 'attrs' dictionary unless the attribute
        name starts with 'nx' or '_', or unless it is one of the standard Python
        attributes for the NXfield class.
        """
        if name.startswith('_') or name.startswith('nx'):
            object.__setattr__(self, name, value)
        elif isinstance(value, NXattr):
            self._attrs[name] = value
            self._saved = False
            self._changed = True
        else:
            self._attrs[name] = NXattr(value)
            self._saved = False
            self._changed = True

    def __getitem__(self, index):
        """
        Returns a slice from the NXfield.

        In most cases, the slice values are applied to the NXfield nxdata array
        and returned within an NXfield object with the same metadata. However,
        if the array is one-dimensional and the index start and stop values
        are real, the nxdata array is returned with values between those limits.
        This is to allow axis arrays to be limited by their actual value. This
        real-space slicing should only be used on monotonically increasing (or
        decreasing) one-dimensional arrays.
        """
        if isinstance(index, slice) and \
           (isinstance(index.start, float) or isinstance(index.stop, float)):
            index = slice(self.index(index.start), self.index(index.stop,max=True)+1)
        if self._value is not None:
            result = self.nxdata.__getitem__(index)
        else:
            offset = np.zeros(len(self.shape),dtype=int)
            size = np.array(self.shape)
            if isinstance(index, int):
                offset[0] = index
                size[0] = 1
            else:
                if isinstance(index, slice): index = [index]
                i = 0
                for ind in index:
                    if isinstance(ind, int):
                        offset[i] = ind
                        size[i] = 1
                    else:
                        if ind.start: offset[i] = ind.start
                        if ind.stop: size[i] = ind.stop - offset[i]
                    i = i + 1
            try:
                result = self.get(offset, size)
            except ValueError:
                result = self.nxdata.__getitem__(index)
        return NXfield(result, name=self.nxname, attrs=self.attrs)

    def __setitem__(self, index, value):
        """
        Assign a slice to the NXfield.
        """
        if self._value is not None:
            self.nxdata[index] = value
            self._saved = False
            self._changed = True
        else:
            raise NeXusError("NXfield dataspace not yet allocated")

    def __deepcopy__(self, memo):
        dpcpy = self.__class__()
        memo[id(self)] = dpcpy
        dpcpy._value = copy(self._value)
        dpcpy._name = copy(self.nxname)
        dpcpy._dtype = copy(self.dtype)
        dpcpy._shape = copy(self.shape)
        for k, v in self.attrs.items():
            dpcpy.attrs[k] = copy(v)
        return dpcpy

    def __len__(self):
        """
        Return the length of the NXfield data.
        """
        return np.prod(self.shape)

    def index(self, value, max=False):
        """
        Return the index of the NXfield nxdata array that is greater than or equal to the value.

        If max, then return the index that is less than or equal to the value.
        This should only be used on one-dimensional monotonically increasing arrays.
        """
        if max:
            return len(self.nxdata)-len(self.nxdata[self.nxdata>=value])
        else:
            return len(self.nxdata[self.nxdata<value])

    def __array__(self):
        """
        Cast the NXfield as an array when it is expected by numpy
        """
        return self.nxdata

    def __eq__(self, other):
        """
        Return true if the values of the NXfield are the same.
        """
        if isinstance(other, NXfield):
            if isinstance(self.nxdata, np.ndarray) and isinstance(other.nxdata, np.ndarray):
                return all(self.nxdata == other.nxdata)
            else:
                return self.nxdata == other.nxdata
        else:
            return False

    def __ne__(self, other):
        """
        Return true if the values of the NXfield are not the same.
        """
        if isinstance(other, NXfield):
            if isinstance(self.nxdata, np.ndarray) and isinstance(other.nxdata, np.ndarray):
                return any(self.nxdata != other.nxdata)
            else:
                return self.nxdata != other.nxdata
        else:
            return True

    def __add__(self, other):
        """
        Return the sum of the NXfield and another NXfield or number.
        """
        if isinstance(other, NXfield):
            return NXfield(value=self.nxdata+other.nxdata, name=self.nxname,
                           attrs=self.attrs)
        else:
            return NXfield(value=self.nxdata+other, name=self.nxname,
                           attrs=self.attrs)

    def __radd__(self, other):
        """
        Return the sum of the NXfield and another NXfield or number.

        This variant makes __add__ commutative.
        """
        return self.__add__(other)

    def __sub__(self, other):
        """
        Return the NXfield with the subtraction of another NXfield or number.
        """
        if isinstance(other, NXfield):
            return NXfield(value=self.nxdata-other.nxdata, name=self.nxname,
                           attrs=self.attrs)
        else:
            return NXfield(value=self.nxdata-other, name=self.nxname,
                           attrs=self.attrs)

    def __mul__(self, other):
        """
        Return the product of the NXfield and another NXfield or number.
        """
        if isinstance(other, NXfield):
            return NXfield(value=self.nxdata*other.nxdata, name=self.nxname,
                           attrs=self.attrs)
        else:
            return NXfield(value=self.nxdata*other, name=self.nxname,
                          attrs=self.attrs)

    def __rmul__(self, other):
        """
        Return the product of the NXfield and another NXfield or number.

        This variant makes __mul__ commutative.
        """
        return self.__mul__(other)

    def __div__(self, other):
        """
        Return the NXfield divided by another NXfield or number.
        """
        if isinstance(other, NXfield):
            return NXfield(value=self.nxdata/other.nxdata, name=self.nxname,
                           attrs=self.attrs)
        else:
            return NXfield(value=self.nxdata/other, name=self.nxname,
                           attrs=self.attrs)

    def __rdiv__(self, other):
        """
        Return the inverse of the NXfield divided by another NXfield or number.
        """
        if isinstance(other, NXfield):
            return NXfield(value=other.nxdata/self.nxdata, name=self.nxname,
                           attrs=self.attrs)
        else:
            return NXfield(value=other/self.nxdata, name=self.nxname,
                           attrs=self.attrs)

    def __pow__(self, power):
        """
        Return the NXfield raised to the specified power.
        """
        return NXfield(value=pow(self.nxdata,power), name=self.nxname,
                       attrs=self.attrs)

    def reshape(self, shape):
        """
        Returns an NXfield with the specified shape.
        """
        return NXfield(value=self.nxdata.reshape(shape), name=self.nxname,
                       attrs=self.attrs)

    def transpose(self):
        """
        Returns an NXfield containing the transpose of the data array.
        """
        return NXfield(value=self.nxdata.transpose(), name=self.nxname,
                       attrs=self.attrs)

    @property
    def T(self):
        return self.transpose()

    def centers(self):
        """
        Returns an NXfield with the centers of a single axis
        assuming it contains bin boundaries.
        """
        return NXfield((self.nxdata[:-1]+self.nxdata[1:])/2,
                        name=self.nxname,attrs=self.attrs)

    def read(self):
        """
        Read the NXfield, including attributes, from the NeXus file.

        The data values are read provided they do not exceed NX_MEMORY. In that
        case, the data have to be read in as slabs using the get method.
        """
        if self.nxfile:
            with self as path:
                self._setattrs(path.getattrs())
                shape, dtype = path.getinfo()
                if dtype == 'char':
                    self._value = path.getdata()
                elif np.prod(shape) * np.dtype(dtype).itemsize <= NX_MEMORY*1024*1024:
                    self._value = path.getdata()
                else:
                    raise MemoryError('Data size larger than NX_MEMORY=%s MB' % NX_MEMORY)
                self._shape = tuple(shape)
                self._dtype = dtype
                if dtype == 'char':
                    self._dtype = 'char'
                elif dtype in np.typeDict:
                    self._dtype = np.dtype(dtype)
                self._infile = self._saved = self._changed = True
        else:
            raise IOError("Data is not attached to a file")

    def write(self):
        """
        Write the NXfield, including attributes, to the NeXus file.
        """
        if self.nxfile:
            if self.nxfile.mode == napi.ACC_READ:
                raise NeXusError("NeXus file is readonly")
            if not self.infile:
                shape = self.shape
                if shape == (): shape = (1,)
                with self.nxgroup as path:
                    if np.prod(shape) > 10000:
                    # Compress the fastest moving dimension of large datasets
                        slab_dims = np.ones(len(shape),'i')
                        if shape[-1] < 100000:
                            slab_dims[-1] = shape[-1]
                        else:
                            slab_dims[-1] = 100000
                        path.compmakedata(self.nxname, self.dtype, shape, 'lzw', 
                                          slab_dims)
                    else:
                    # Don't use compression for small datasets
                        path.makedata(self.nxname, self.dtype, shape)
                self._infile = True
            if not self.saved:            
                with self as path:
                    path._writeattrs(self.attrs)
                    value = self.nxdata
                    if value is not None:
                        path.putdata(value)
                self._saved = True
        else:
            raise IOError("Data is not attached to a file")

    def get(self, offset, size):
        """
        Return a slab from the data array.

        Offsets are 0-origin. Shape can be inferred from the data.
        Offset and shape must each have one entry per dimension.

        Corresponds to NXgetslab(handle,data,offset,shape)
        """
        if self.nxfile:
            with self as path:
                value = path.getslab(offset,size)
                return value
        else:
            raise IOError("Data is not attached to a file")

    def put(self, data, offset, refresh=True):
        """
        Put a slab into the data array.

        Offsets are 0-origin.  Shape can be inferred from the data.
        Offset and shape must each have one entry per dimension.

        Corresponds to NXputslab(handle,data,offset,shape)
        """
        if self.nxfile:
            if self.nxfile.mode == napi.ACC_READ:
                raise NeXusError("NeXus file is readonly")
            with self as path:
                if isinstance(data, NXfield):
                    path.putslab(data.nxdata.astype(self.dtype), offset, data.shape)
                else:
                    data = np.array(data)
                    path.putslab(data.astype(self.dtype), offset, data.shape)
            if refresh: self.read()
        else:
            raise IOError("Data is not attached to a file")

    def add(self, data, offset, refresh=True):
        """
        Add a slab into the data array.

        Calls get to read in existing data before adding the value
        and calling put. It assumes that the two sets of data have
        compatible data types.
        """
        if isinstance(data, NXfield):
            value = self.get(offset, data.shape)
            self.put(data.nxdata.astype(self.dtype)+value, offset)
        else:
            value = self.get(offset, data.shape)
            self.put(data.astype(self.dtype)+value, offset)
        if refresh: self.refresh()

    def refresh(self):
        """
        Rereads the data from the file.

        If put has been called, then nxdata is no longer synchronized with the
        file making a refresh necessary. This will only be performed if nxdata
        already stores the data.
        """
        if self._value is not None:
            if self.nxfile:
                self._value = self.nxfile.readpath(self.nxpath)
                self._infile = self._saved = True
            else:
                raise IOError("Data is not attached to a file")

    def convert(self, units=""):
        """
        Return the data in particular units.
        """
        try:
            import units
        except ImportError:
            raise NeXusError("No conversion utility available")
        if self._value is not None:
            return self._converter(self._value,units)
        else:
            return None

    def __str__(self):
        """
        If value is loaded, return the value as a string.  If value is
        not loaded, return the empty string.  Only the first view values
        for large arrays will be printed.
        """
        if self._value is not None:
            return str(self._value)
        return ""

    def _str_value(self,indent=0):
        v = str(self)
        if '\n' in v:
            v = '\n'.join([(" "*indent)+s for s in v.split('\n')])
        return v

    def _str_tree(self,indent=0,attrs=False,recursive=False):
        dims = 'x'.join([str(n) for n in self.shape])
        s = str(self)
        if '\n' in s or s == "":
            s = "%s(%s)"%(self.dtype, dims)
        v=[" "*indent + "%s = %s"%(self.nxname, s)]
        if attrs and self.attrs: v.append(self._str_attrs(indent=indent+2))
        return "\n".join(v)

    def walk(self):
        yield self

    def _getaxes(self):
        """
        Return a list of NXfields containing axes.

        Only works if the NXfield has the 'axes' attribute
        """
        try:
            return [getattr(self.nxgroup,name) for name in _readaxes(self.axes)]
        except KeyError:
            return None

    def _getdata(self):
        """
        Return the data if it is not larger than NX_MEMORY.
        """
        if self._value is None:
            if self.nxfile:
                if str(self.dtype) == 'char':
                    self._value = self.nxfile.readpath(self.nxpath)
                elif np.prod(self.shape) * np.dtype(self.dtype).itemsize <= NX_MEMORY*1024*1024:
                    self._value = self.nxfile.readpath(self.nxpath)
                else:
                    raise MemoryError('Data size larger than NX_MEMORY=%s MB' % NX_MEMORY)
                self._saved = True
            else:
                return None

        return self._value

    def _setdata(self, value):
        if value is not None:
            if str(self._dtype) == 'char' or isinstance(value,str):
                self._value = str(value)
                self._shape = (len(self._value),)
                self._dtype = 'char'
            else:
                if self.dtype in np.typeDict:
                    self._value = np.array(value,self.dtype)
                else:
                    self._value = np.array(value)
                self._shape = self._value.shape
                self._dtype = self._value.dtype
            self._saved = False
            self._changed = True
       
    def _getdtype(self):
        return self._dtype

    def _getshape(self):
        return self._shape

    def _getsize(self):
        return len(self)

    nxdata = property(_getdata,_setdata,doc="The data values")
    nxaxes = property(_getaxes,doc="The plotting axes")
    dtype = property(_getdtype,doc="Data type of NeXus field")
    shape = property(_getshape,doc="Shape of NeXus field")
    size = property(_getsize,doc="Size of NeXus field")

SDS = NXfield # For backward compatibility

def _fixaxes(signal, axes):
    """
    Remove length-one dimensions from plottable data
    """
    shape = list(signal.shape)
    while 1 in shape: shape.remove(1)
    newaxes = []
    for axis in axes:
        if axis.size > 1: newaxes.append(axis)
    return signal.nxdata.view().reshape(shape), newaxes

class PylabPlotter(object):

    """
    Matplotlib plotter class for NeXus data.
    """

    def plot(self, signal, axes, title, errors, fmt, 
             xmin, xmax, ymin, ymax, zmin, zmax, **opts):
        """
        Plot the data entry.

        Raises NeXusError if the data cannot be plotted.
        """
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            raise NeXusError("Default plotting package (matplotlib) not available.")

        over = False
        if "over" in opts.keys():
            if opts["over"]: over = True
            del opts["over"]

        log = logx = logy = False
        if "log" in opts.keys():
            if opts["log"]: log = True
            del opts["log"]
        if "logy" in opts.keys():
            if opts["logy"]: logy = True
            del opts["logy"]
        if "logx" in opts.keys():
            if opts["logx"]: logx = True
            del opts["logx"]

        if over:
            plt.autoscale(enable=False)
        else:
            plt.autoscale(enable=True)
            plt.clf()

        # Provide a new view of the data if there is a dimension of length 1
        if 1 in signal.shape:
            data, axes = _fixaxes(signal, axes)
        else:
            data = signal.nxdata

        # Find the centers of the bins for histogrammed data
        axis_data = centers(data, axes)

        #One-dimensional Plot
        if len(data.shape) == 1:
            plt.ioff()
            if hasattr(signal, 'units'):
                if not errors and signal.units == 'counts':
                    errors = NXfield(np.sqrt(data))
            if errors:
                ebars = errors.nxdata
                plt.errorbar(axis_data[0], data, ebars, fmt=fmt, **opts)
            else:
                plt.plot(axis_data[0], data, fmt, **opts)
            if not over:
                ax = plt.gca()
                xlo, xhi = ax.set_xlim(auto=True)        
                ylo, yhi = ax.set_ylim(auto=True)                
                if xmin: xlo = xmin
                if xmax: xhi = xmax
                ax.set_xlim(xlo, xhi)
                if ymin: ylo = ymin
                if ymax: yhi = ymax
                ax.set_ylim(ylo, yhi)
                if logx: ax.set_xscale('symlog')
                if log or logy: ax.set_yscale('symlog')
                plt.xlabel(label(axes[0]))
                plt.ylabel(label(signal))
                plt.title(title)
            plt.ion()

        #Two dimensional plot
        else:
            from matplotlib.image import NonUniformImage
            from matplotlib.colors import LogNorm

            if len(data.shape) > 2:
                slab = [slice(None), slice(None)]
                for _dim in data.shape[2:]:
                    slab.append(0)
                data = data[slab].view().reshape(data.shape[:2])
                print "Warning: Only the top 2D slice of the data is plotted"

            x = axis_data[0]
            y = axis_data[1]
            if not zmin: zmin = np.min(data)
            if not zmax: zmax = np.max(data)
            z = np.clip(data,zmin,zmax).T
            
            if log:
                opts["norm"] = LogNorm()
                if z.min() <= 0 and np.issubdtype(z[0,0],int):
                    z = np.clip(z,0.1,zmax)

            ax = plt.gca()
            extent = (x[0],x[-1],y[0],y[-1])
            im = NonUniformImage(ax, extent=extent, origin=None, **opts)
            im.set_data(x,y,z)
            ax.images.append(im)
            xlo, xhi = ax.set_xlim(x[0],x[-1])
            ylo, yhi = ax.set_ylim(y[0],y[-1])
            if xmin: 
                xlo = xmin
            else:
                xlo = x[0]
            if xmax: 
                xhi = xmax
            else:
                xhi = x[-1]
            if ymin: 
                yhi = ymin
            else:
                yhi = y[0]
            if ymax: 
                yhi = ymax
            else:
                yhi = y[-1]
            ax.set_xlim(xlo, xhi)
            ax.set_ylim(ylo, yhi)
            plt.xlabel(label(axes[0]))
            plt.ylabel(label(axes[1]))
            plt.title(title)
            plt.colorbar(im)

        plt.gcf().canvas.draw_idle()

    @staticmethod
    def show():
        import matplotlib.pyplot as plt
        plt.show()    


class NXgroup(NXobject):

    """
    A NeXus group object.

    This is a subclass of NXobject and is the base class for the specific
    NeXus group classes, e.g., NXentry, NXsample, NXdata.

    NXgroup(*items, **opts)

    Parameters
    ----------
    The NXgroup parameters consist of a list of positional and/or keyword
    arguments.

    Positional Arguments : These must be valid NeXus objects, either an NXfield
    or a NeXus group. These are added without modification as children of this
    group.

    Keyword Arguments : Apart from a list of special keywords shown below,
    keyword arguments are used to add children to the group using the keywords
    as attribute names. The values can either be valid NXfields or NXgroups,
    in which case the 'name' attribute is changed to the keyword, or they
    can be numerical or string data, which are converted to NXfield objects.

    Special Keyword Arguments:

    name : string
        The name of the NXgroup, which is directly accessible as the NXgroup
        attribute 'name'. If the NXgroup is initialized as the attribute of
        a parent group, the name is automatically set to the name of this
        attribute. If 'nxclass' is specified and has the usual prefix 'NX',
        the default name is the class name without this prefix.
    nxclass : string
        The class of the NXgroup.
    entries : dict
        A dictionary containing a list of group entries. This is an
        alternative way of adding group entries to the use of keyword
        arguments.
    file : filename
        The file from which the NXfield has been read.
    path : string
        The path to this object with respect to the root of the NeXus tree,
        using the convention for unix file paths.
    group : NXobject (NXgroup or subclass of NXgroup)
        The parent NeXus group, which is accessible as the group attribute
        'group'. If the group is initialized as the attribute of
        a parent group, this is set to the parent group.

    Python Attributes
    -----------------
    nxclass : string
        The class of the NXobject.
    nxname : string
        The name of the NXfield.
    entries : dictionary
        A dictionary of all the NeXus objects contained within an NXgroup.
    attrs : dictionary
        A dictionary of all the NeXus attributes, i.e., attribute with class NXattr.
    entries : dictionary
        A dictionary of all the NeXus objects contained within the group.
    attrs : dictionary
        A dictionary of all the group's NeXus attributes, which all have the
        class NXattr.
    nxpath : string
        The path to this object with respect to the root of the NeXus tree. For
        NeXus data read from a file, this will be a group of class NXroot, but
        if the NeXus tree was defined interactively, it can be any valid
        NXgroup.
    nxroot : NXgroup
        The root object of the NeXus tree containing this object. For
        NeXus data read from a file, this will be a group of class NXroot, but
        if the NeXus tree was defined interactively, it can be any valid
        NXgroup.

    NeXus Group Entries
    -------------------
    Just as in a NeXus file, NeXus groups can contain either data or other
    groups, represented by NXfield and NXgroup objects respectively. To
    distinguish them from regular Python attributes, all NeXus objects are
    stored in the 'entries' dictionary of the NXgroup. However, they can usually
    be assigned or referenced as if they are Python attributes, i.e., using the
    dictionary name directly as the group attribute name, as long as this name
    is not the same as one of the Python attributes defined above or as one of
    the NXfield Python attributes.

    a) Assigning a NeXus object to a NeXus group

    In the example below, after assigning the NXgroup, the following three
    NeXus object assignments to entry.sample are all equivalent:

        >>> entry.sample = NXsample()
        >>> entry.sample['temperature'] = NXfield(40.0)
        >>> entry.sample.temperature = NXfield(40.0)
        >>> entry.sample.temperature = 40.0
        >>> entry.sample.temperature
        NXfield(40.0)

    If the assigned value is not a valid NXobject, then it is cast as an NXfield
    with a type determined from the Python data type.

        >>> entry.sample.temperature = 40.0
        >>> entry.sample.temperature
        NXfield(40.0)
        >>> entry.data.data.x=np.linspace(0,10,11).astype('float32')
        >>> entry.data.data.x
        NXfield([  0.   1.   2. ...,   8.   9.  10.])

    b) Referencing a NeXus object in a NeXus group

    If the name of the NeXus object is not the same as any of the Python
    attributes listed above, or the methods listed below, they can be referenced
    as if they were a Python attribute of the NXgroup. However, it is only possible
    to reference attributes with one of the proscribed names using the group
    dictionary, i.e.,

        >>> entry.sample.tree = 100.0
        >>> print entry.sample.tree
        sample:NXsample
          tree = 100.0
        >>> entry.sample['tree']
        NXfield(100.0)

    For this reason, it is recommended to use the group dictionary to reference
    all group objects within Python scripts.

    NeXus Attributes
    ----------------
    NeXus attributes are not currently used much with NXgroups, except for the
    root group, which has a number of global attributes to store the file name,
    file creation time, and NeXus and HDF version numbers. However, the
    mechanism described for NXfields works here as well. All NeXus attributes
    are stored in the 'attrs' dictionary of the NXgroup, but can be referenced
    as if they are Python attributes as long as there is no name clash.

        >>> entry.sample.temperature = 40.0
        >>> entry.sample.attrs['tree'] = 10.0
        >>> print entry.sample.tree
        sample:NXsample
          @tree = 10.0
          temperature = 40.0
        >>> entry.sample.attrs['tree']
        NXattr(10.0)

    Methods
    -------
    insert(self, NXobject, name='unknown'):
        Insert a valid NXobject (NXfield or NXgroup) into the group.

        If NXobject has a 'name' attribute and the 'name' keyword is not given,
        then the object is inserted with the NXobject name.

    makelink(self, NXobject):
        Add the NXobject to the group entries as a link (NXlink).

    dir(self, attrs=False, recursive=False):
        Print the group directory.

        The directory is a list of NeXus objects within this group, either NeXus
        groups or NXfield data. If 'attrs' is True, NXfield attributes are
        displayed. If 'recursive' is True, the contents of child groups are also
        displayed.

    tree:
        Return the group tree.

        It invokes the 'dir' method with both 'attrs' and 'recursive'
        set to True.

    save(self, filename, format='w5')
        Save the NeXus group into a file

        The object is wrapped in an NXroot group (with name 'root') and an
        NXentry group (with name 'entry'), if necessary, in order to produce
        a valid NeXus file.

    Examples
    --------
    >>> x = NXfield(np.linspace(0,2*np.pi,101), units='degree')
    >>> entry = NXgroup(x, name='entry', nxclass='NXentry')
    >>> entry.sample = NXgroup(temperature=NXfield(40.0,units='K'),
                               nxclass='NXsample')
    >>> print entry.sample.tree
    sample:NXsample
      temperature = 40.0
        @units = K

    Note: All the currently defined NeXus classes are defined as subclasses
          of the NXgroup class. It is recommended that these are used
          directly, so that the above examples become:

    >>> entry = NXentry(x)
    >>> entry.sample = NXsample(temperature=NXfield(40.0,units='K'))

    or

    >>> entry.sample.temperature = 40.0
    >>> entry.sample.temperature.units='K'

    """

    # Plotter to use for plot calls
    _plotter = PylabPlotter()

    def __init__(self, *items, **opts):
        if "name" in opts.keys():
            self._name = opts["name"].replace(' ','_')
            del opts["name"]
        self._entries = {}
        if "entries" in opts.keys():
            for k,v in opts["entries"].items():
                setattr(self, k, v)
            del opts["entries"]
        self._attrs = AttrDict()
        if "attrs" in opts.keys():
            self._setattrs(opts["attrs"])
            del opts["attrs"]
        if "nxclass" in opts.keys():
            self._class = opts["nxclass"]
            del opts["nxclass"]
        if "group" in opts.keys():
            self._group = opts["group"]
            del opts["group"]
        for k,v in opts.items():
            setattr(self, k, v)
        if self.nxclass.startswith("NX"):
            if self.nxname == "unknown": self._name = self.nxclass[2:]
            try: # If one exists, set the class to a valid NXgroup subclass
                self.__class__ = globals()[self.nxclass]
            except KeyError:
                pass
        for item in items:
            try:
                setattr(self, item.nxname, item)
            except AttributeError:
                raise NeXusError("Non-keyword arguments must be valid NXobjects")
        self._saved = False
        self._changed = True

#    def __cmp__(self, other):
#        """Sort groups by their distances or names."""
#        try:
#            return cmp(self.distance, other.distance)
#        except KeyError:
#            return cmp(self.nxname, other.nxname)

    def __repr__(self):
        return "%s('%s')" % (self.__class__.__name__,self.nxname)

    def _str_value(self,indent=0):
        return ""

    def walk(self):
        yield self
        for node in self.entries.values():
            for child in node.walk():
                yield child

    def __getattr__(self, key):
        """
        Provide direct access to groups via nxclass name.
        """
        if key.startswith('NX'):
            return self.component(key)
        elif key in self.entries:
            return self.entries[key]
        elif key in self.attrs:
            return self.attrs[key].nxdata
        raise KeyError(key+" not in "+self.nxclass+":"+self.nxname)

    def __setattr__(self, name, value):
        """
        Set an attribute as an object or regular Python attribute.

        It is assumed that attributes starting with 'nx' or '_' are regular
        Python attributes. All other attributes are converted to valid NXobjects,
        with class NXfield, NXgroup, or a sub-class of NXgroup, depending on the
        assigned value.

        The internal value of the attribute name, i.e., 'name', is set to the
        attribute name used in the assignment.  The parent group of the
        attribute, i.e., 'group', is set to the parent group of the attribute.

        If the assigned value is a numerical (scalar or array) or string object,
        it is converted to an object of class NXfield, whose attribute, 'nxdata',
        is set to the assigned value.
        """
        if name.startswith('_') or name.startswith('nx'):
            object.__setattr__(self, name, value)
        elif isinstance(value, NXattr):
            self._attrs[name] = value
            self._saved = False
            self._changed = True
        else:
            self[name] = value

    def __getitem__(self, index):
        """
        Returns a slice from the NXgroup nxsignal attribute (if it exists) as
        a new NXdata group, if the index is a slice object.

        In most cases, the slice values are applied to the NXfield nxdata array
        and returned within an NXfield object with the same metadata. However,
        if the array is one-dimensional and the index start and stop values
        are real, the nxdata array is returned with values between the limits
        set by those axis values.
        This is to allow axis arrays to be limited by their actual value. This
        real-space slicing should only be used on monotonically increasing (or
        decreasing) one-dimensional arrays.
        """
        if isinstance(index, str): #i.e., requesting a dictionary value
            return self._entries[index]

        if not self.nxsignal:
            raise NeXusError("No plottable signal")
        if not hasattr(self,"nxclass"):
            raise NeXusError("Indexing not allowed for groups of unknown class")
        if isinstance(index, int):
            axes = self.nxaxes
            axes[0] = axes[0][index]
            result = NXdata(self.nxsignal[index], axes)
            if self.nxerrors: result.errors = self.errors[index]
        elif isinstance(index, slice):
            axes = self.nxaxes
            axes[0] = axes[0][index]
            if isinstance(index.start, float) or isinstance(index.stop, float):
                index = slice(self.nxaxes[0].index(index.start),
                              self.nxaxes[0].index(index.stop,max=True)+1)
                result = NXdata(self.nxsignal[index], axes)
                if self.nxerrors: result.errors = self.errors[index]
            else:
                result = NXdata(self.nxsignal[index], axes)
                if self.nxerrors: result.errors = self.errors[index]
        else:
            i = 0
            slices = []
            axes = self.nxaxes
            for ind in index:
                axes[i] = axes[i][ind]
                if isinstance(ind, slice) and \
                   (isinstance(ind.start, float) or isinstance(ind.stop, float)):
                    slices.append(slice(self.nxaxes[i].index(ind.start),
                                        self.nxaxes[i].index(ind.stop)))
                else:
                    slices.append(ind)
                i = i + 1
            result = NXdata(self.nxsignal.__getitem__(tuple(slices)), axes)
            if self.nxerrors: result.errors = self.errors.__getitem__(tuple(slices))
        axes = []
        for axis in result.nxaxes:
            if len(axis) > 1: axes.append(axis)
        result.nxsignal.axes = ":".join([axis.nxname for axis in axes])
        if self.nxtitle:
            result.title = self.nxtitle
        return result

    def __setitem__(self, key, value):
        """
        Adds or modifies an item in the NeXus group.
        """
        if key in self.entries: 
            infile = self._entries[key]._infile
            if isinstance(self._entries[key], NXlink):
                if self._entries[key].nxlink:
                    setattr(self._entries[key].nxlink.nxgroup, key, value)
                return
            attrs = self._entries[key].attrs
        else:
            infile = None
            attrs = {}
        if isinstance(value, NXlink):
            self._entries[key] = value
        elif isinstance(value, NXobject):
            if value.nxgroup is not None:
                memo = {}
                value = deepcopy(value, memo)
                value._attrs = copy(value._attrs)
            value._group = self
            value._name = key
            self._entries[key] = value
        else:
            self._entries[key] = NXfield(value=value, name=key, group=self, attrs=attrs)
        if infile is not None: self[key]._infile = infile
        self._changed = True

    def __deepcopy__(self, memo):
        dpcpy = self.__class__()
        memo[id(self)] = dpcpy
        for k,v in self.items():
            if isinstance(v, NXgroup):
                dpcpy[k] = deepcopy(v, memo)
            else:
                dpcpy[k] = copy(v)
        for k, v in self.attrs.items():
            dpcpy.attrs[k] = copy(v)
        return dpcpy

    def keys(self):
        """
        Returns the names of NeXus objects in the group.
        """
        return self._entries.keys()

    def values(self):
        """
        Returns the values of NeXus objects in the group.
        """
        return self._entries.values()

    def items(self):
        """
        Returns a list of the NeXus objects in the group as (key,value) pairs.
        """
        return self._entries.items()

    def has_key(self, name):
        """
        Returns true if the NeXus object with the specified name is in the group.
        """
        return self._entries.has_key(name)

    def insert(self, value, name='unknown'):
        """
        Adds an attribute to the group.

        If it is not a valid NeXus object (NXfield or NXgroup), the attribute
        is converted to an NXfield.
        """
        if isinstance(value, NXobject):
            if name == 'unknown': name = value.nxname
            if name in self._entries:
                raise NeXusError("'%s' already exists in group" % name)
            value._group = self
            self._entries[name] = value
        else:
            self._entries[name] = NXfield(value=value, name=name, group=self)

    def makelink(self, target):
        """
        Creates a linked NXobject within the group.

        All attributes are inherited from the parent object including the name
        """
        if isinstance(target, NXobject):
            self[target.nxname] = NXlink(target=target, group=self)
        else:
            raise NeXusError("Link target must be an NXobject")

    def read(self):
        """
        Read the NXgroup and all its children from the NeXus file.
        """
        if self.nxfile:
            with self as path:
                n, nxname, nxclass = path.getgroupinfo()
                if nxclass != self.nxclass:
                    raise NeXusError("The NeXus group class does not match the file")
                self._setattrs(path.getattrs())
                entries = path.entries()
            for name,nxclass in entries:
                path = self.nxpath + '/' + name
                if nxclass == 'SDS':
                    attrs = self.nxfile.getattrs()
                    if 'target' in attrs and attrs['target'] != path:
                        self._entries[name] = NXlinkfield(target=attrs['target'])            
                    else:
                        self._entries[name] = NXfield(name=name)
                else:
                    attrs = self.nxfile.getattrs()
                    if 'target' in attrs and attrs['target'] != path:
                        self._entries[name] = NXlinkgroup(name=name,
                                                          target=attrs['target'])
                    else:
                        self._entries[name] = NXgroup(nxclass=nxclass)
                self._entries[name]._group = self
            #Make sure non-linked variables are processed first.
            for entry in self._entries.values():
                for node in entry.walk():
                    if not isinstance(node, NXlink): node.read()
            for entry in self._entries.values():
                for node in entry.walk():
                    if isinstance(node, NXlink): node.read()
            self._infile = self._saved = self._changed = True
        else:
            raise IOError("Data is not attached to a file")

    def write(self):
        """
        Write the NXgroup, including its children, to the NeXus file.
        """
        if self.nxfile:
            if self.nxfile.mode == napi.ACC_READ:
                raise NeXusError("NeXus file is readonly")
            if not self.infile:
                with self.nxgroup as path:
                    path.makegroup(self.nxname, self.nxclass)
                self._infile = True
            with self as path:
                path._writeattrs(self.attrs)
                for entry in self.walk():
                    if entry is not self: entry.write()
                self._infile = self._saved = True
        else:
            raise IOError("Group is not attached to a file")

    def sum(self, axis=None):
        """
        Return the sum of the NXdata group using the Numpy sum method
        on the NXdata signal.

        The result contains a copy of all the metadata contained in
        the NXdata group.
        """
        if not self.nxsignal:
            raise NeXusError("No signal to sum")
        if not hasattr(self,"nxclass"):
            raise NeXusError("Summing not allowed for groups of unknown class")
        if axis is None:
            return self.nxsignal.sum()
        else:
            signal = NXfield(self.nxsignal.sum(axis), name=self.nxsignal.nxname)
            axes = self.nxaxes
            summedaxis = axes.pop(axis)
            units = ""
            if hasattr(summedaxis, "units"): units = summedaxis.units
            signal.long_name = "Integral from %s to %s %s" % \
                               (summedaxis[0], summedaxis[-1], units)
            average = NXfield(0.5*(summedaxis.nxdata[0]+summedaxis.nxdata[-1]), 
                                   name=summedaxis.nxname)
            if units: average.units = units
            result = NXdata(signal, axes, average)
            if self.nxerrors:
                errors = np.sqrt((self.nxerrors.nxdata**2).sum(axis))
                result.errors = NXfield(errors, name="errors")
            if self.nxtitle:
                result.title = self.nxtitle
            return result

    def moment(self, order=1):
        """
        Return an NXfield containing the moments of the NXdata group
        assuming the signal is one-dimensional.

        Currently, only the first moment has been defined. Eventually, the
        order of the moment will be defined by the 'order' parameter.
        """
        if not self.nxsignal:
            raise NeXusError("No signal to calculate")
        elif len(self.nxsignal.shape) > 1:
            raise NeXusError("Operation only possible on one-dimensional signals")
        elif order > 1:
            raise NeXusError("Higher moments not yet implemented")
        if not hasattr(self,"nxclass"):
            raise NeXusError("Operation not allowed for groups of unknown class")
        return (centers(self.nxsignal,self.nxaxes)*self.nxsignal).sum() \
                /self.nxsignal.sum()

    def component(self, nxclass):
        """
        Find all child objects that have a particular class.
        """
        return [E for _name,E in self.entries.items() if E.nxclass==nxclass]

    def signals(self):
        """
        Return a dictionary of NXfield's containing signal data.

        The key is the value of the signal attribute.
        """
        signals = {}
        for obj in self.entries.values():
            if 'signal' in obj.attrs:
                signals[obj.nxsignal.nxdata] = obj
        return signals

    def _signal(self):
        """
        Return the NXfield containing the signal data.
        """
        for obj in self.entries.values():
            if 'signal' in obj.attrs and str(obj.signal) == '1':
#                if isinstance(self[obj.nxname],NXlink):
#                    return self[obj.nxname].nxlink
#                else:
                return self[obj.nxname]
        return None
    
    def _set_signal(self, signal):
        """
        Setter for the signal attribute.
        
        The argument should be a valid NXfield within the group.
        """
        self[signal.nxname].signal = NXattr(1)

    def _axes(self):
        """
        Return a list of NXfields containing the axes.
        """
        try:
            return [getattr(self,name) for name in _readaxes(self.nxsignal.axes)]
        except KeyError:
            axes = {}
            for obj in self.entries:
                if 'axis' in getattr(self,obj).attrs:
                    axes[getattr(self,obj).axis] = getattr(self,obj)
            return [axes[key] for key in sorted(axes.keys())]

    def _set_axes(self, axes):
        """
        Setter for the signal attribute.
        
        The argument should be a list of valid NXfields within the group.
        """
        if not isinstance(axes, list):
            axes = [axes]
        self.nxsignal.axes = NXattr(":".join([axis.nxname for axis in axes]))

    def _errors(self):
        """
        Return the NXfield containing the signal errors.
        """
        try:
            return self.entries['errors']
        except KeyError:
            return None

    def _title(self):
        """
        Return the title as a string.

        If there is no title attribute in the string, the parent
        NXentry group in the group's path is searched.
        """
        title = self.nxpath
        if 'title' in self.entries:
            return str(self.title)
        elif self.nxgroup:
            if 'title' in self.nxgroup.entries:
                return str(self.nxgroup.title)
        return self.nxpath

    def _getentries(self):
        return self._entries

    nxsignal = property(_signal, _set_signal, "Signal NXfield within group")
    nxaxes = property(_axes, _set_axes, "List of axes within group")
    nxerrors = property(_errors, "Errors NXfield within group")
    nxtitle = property(_title, "Title for group plot")
    entries = property(_getentries,doc="NeXus objects within group")

    def plot(self, fmt='bo', xmin=None, xmax=None, ymin=None, ymax=None,
             zmin=None, zmax=None, **opts):
        """
        Plot data contained within the group.

        The format argument is used to set the color and type of the
        markers or lines for one-dimensional plots, using the standard 
        matplotlib syntax. The default is set to blue circles. All 
        keyword arguments accepted by matplotlib.pyplot.plot can be
        used to customize the plot.
        
        In addition to the matplotlib keyword arguments, the following
        are defined:
        
            log = True     - plot the intensity on a log scale
            logy = True    - plot the y-axis on a log scale
            logx = True    - plot the x-axis on a log scale
            over = True    - plot on the current figure

        Raises NeXusError if the data could not be plotted.
        """

        group = self
        if self.nxclass == "NXroot":
            group = group.NXentry[0]
        if group.nxclass == "NXentry":
            try:
                group = group.NXdata[0]
            except IndexError:
                raise NeXusError('No NXdata group found')

        # Find a plottable signal
        signal = group.nxsignal
        if not signal:
            raise NeXusError('No plottable signal defined')

        # Find errors
        errors= group.nxerrors

        # Find the associated axes
        axes = group.nxaxes

        # Construct title
        title = group.nxtitle

        # Plot with the available plotter
        group._plotter.plot(signal, axes, title, errors, fmt, 
                            xmin, xmax, ymin, ymax, zmin, zmax, **opts)
    
    def oplot(self, fmt='bo', **opts):
        """
        Plot the data contained within the group over the current figure.
        """
        self.plot(fmt=fmt, over=True, **opts)

    def logplot(self, fmt='bo', xmin=None, xmax=None, ymin=None, ymax=None,
                zmin=None, zmax=None, **opts):
        """
        Plot the data intensity contained within the group on a log scale.
        """
        self.plot(fmt=fmt, log=True,
                  xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
                  zmin=zmin, zmax=zmax, **opts)

class NXlink(NXobject):

    """
    Class for NeXus linked objects.

    The real object will be accessible by following the link attribute.
    """

    _class = "NXlink"

    def __init__(self, target=None, name='link', group=None):
        self._group = group
        self._class = "NXlink"
        if isinstance(target, NXobject):
            self._name = target.nxname
            self._target = target.nxpath
            self.nxlink.attrs["target"] = target.nxpath
            if target.nxclass == "NXlink":
                raise NeXusError("Cannot link to another NXlink object")
            elif target.nxclass == "NXfield":
                self.__class__ = NXlinkfield
            else:
                self.__class__ = NXlinkgroup
        else:
            self._name = name
            self._target = target

    def __getattr__(self, key):
        try:
            try:
                return self.nxlink.__dict__[key]
            except KeyError:
                return self.nxlink.__getattr__(key)
        except KeyError:
            raise KeyError((key+" not in %s" % self._target))

    def __setattr__(self, name, value):
        if name.startswith('_')  or name.startswith('nx'):
            object.__setattr__(self, name, value)
        elif self.nxlink:
            self.nxlink.__setattr__(name, value)

    def __repr__(self):
        return "NXlink('%s')"%(self._target)

    def __str__(self):
        return str(self.nxlink)

    def _str_tree(self, indent=0, attrs=False, recursive=False):
        if self.nxlink:
            return self.nxlink._str_tree(indent, attrs, recursive)
        else:
            return " "*indent+self.nxname+' -> '+self._target

    def _getlink(self):
        link = self.nxroot
        if link:
            try:
                for level in self._target[1:].split('/'):
                    link = link.entries[level]
                return link
            except AttributeError:
                return None
        else:
            return None

    def _getattrs(self):
        return self.nxlink.attrs

    nxlink = property(_getlink, "Linked object")
    attrs = property(_getattrs,doc="NeXus attributes for object")

    def read(self):
        """
        Read the linked NXobject.
        """
        self.nxlink.read()
        self._infile = self._saved = self._changed = True


class NXlinkfield(NXlink, NXfield):

    """
    Class for a NeXus linked field.

    The real field will be accessible by following the link attribute.
    """

    def write(self):
        """
        Write the linked NXfield.
        """
        self.nxlink.write()
        if not self.infile:
            with self.nxlink as path:
                target = path.getdataID()
            with self.nxgroup as path:
                path.makelink(target)
            self._infile = self._saved = True

    def get(self, offset, size):
        """
        Get a slab from the data array.

        Offsets are 0-origin.  Shape can be inferred from the data.
        Offset and shape must each have one entry per dimension.

        This operation should be performed in a "with group.data"
        conext.

        Raises ValueError cannot convert units.

        Corresponds to NXgetslab(handle,data,offset,shape)
        """
        if self.nxfile:
            with self.nxlink as path:
                value = path.getslab(offset,size)
        else:
            raise IOError("Data is not attached to a file")

NXlinkdata = NXlinkfield # For backward compatibility

class NXlinkgroup(NXlink, NXgroup):

    """
    Class for a NeXus linked group.

    The real group will be accessible by following the link attribute.
    """

    def write(self):
        """
        Write the linked NXgroup.
        """
        self.nxlink.write()
        if not self.infile:
            with self.nxlink as path:
                target = path.getgroupID()
            with self.nxgroup as path:
                path.makelink(target)
            self._infile = self._saved = True

    def _getentries(self):
        return self.nxlink.entries

    entries = property(_getentries,doc="NeXus objects within group")


class NXentry(NXgroup):

    """
    NXentry group. This is a subclass of the NXgroup class.

    Each NXdata and NXmonitor object of the same name will be added
    together, raising an NeXusError if any of the groups do not exist
    in both NXentry groups or if any of the NXdata additions fail.
    The resulting NXentry group contains a copy of all the other metadata
    contained in the first group. Note that other extensible data, such
    as the run duration, are not currently added together.

    See the NXgroup documentation for more details.
    """

    def __init__(self, *items, **opts):
        self._class = "NXentry"
        NXgroup.__init__(self, *items, **opts)

    def __add__(self, other):
        """
        Add two NXentry objects
        """
        result = NXentry(entries=self.entries, attrs=self.attrs)
        try:
            names = [group.nxname for group in self.component("NXdata")]
            for name in names:
                if isinstance(other.entries[name], NXdata):
                    result.entries[name] = self.entries[name] + other.entries[name]
                else:
                    raise KeyError
            names = [group.nxname for group in self.component("NXmonitor")]
            for name in names:
                if isinstance(other.entries[name], NXmonitor):
                    result.entries[name] = self.entries[name] + other.entries[name]
                else:
                    raise KeyError
            return result
        except KeyError:
            raise NeXusError("Inconsistency between two NXentry groups")

    def __sub__(self, other):
        """
        Subtract two NXentry objects
        """
        result = NXentry(entries=self.entries, attrs=self.attrs)
        try:
            names = [group.nxname for group in self.component("NXdata")]
            for name in names:
                if isinstance(other.entries[name], NXdata):
                    result.entries[name] = self.entries[name] - other.entries[name]
                else:
                    raise KeyError
            names = [group.nxname for group in self.component("NXmonitor")]
            for name in names:
                if isinstance(other.entries[name], NXmonitor):
                    result.entries[name] = self.entries[name] - other.entries[name]
                else:
                    raise KeyError
            return result
        except KeyError:
            raise NeXusError("Inconsistency between two NXentry groups")


class NXsubentry(NXentry):

    """
    NXsubentry group. This is a subclass of the NXsubentry class.

    See the NXgroup documentation for more details.
    """

    def __init__(self, *items, **opts):
        self._class = "NXsubentry"
        NXgroup.__init__(self, *items, **opts)


class NXdata(NXgroup):

    """
    NXdata group. This is a subclass of the NXgroup class.

    The constructor assumes that the first argument contains the signal and
    the second contains either the axis, for one-dimensional data, or a list
    of axes, for multidimensional data. These arguments can either be NXfield
    objects or Numpy arrays, which are converted to NXfield objects with default
    names. Alternatively, the signal and axes NXfields can be defined using the
    'nxsignal' and 'nxaxes' properties. See the examples below.
    
    Various arithmetic operations (addition, subtraction, multiplication,
    and division) have been defined for combining NXdata groups with other
    NXdata groups, Numpy arrays, or constants, raising a NeXusError if the
    shapes don't match. Data errors are propagated in quadrature if
    they are defined, i.e., if the 'nexerrors' attribute is not None,

    Attributes
    ----------
    nxsignal : The NXfield containing the attribute 'signal' with value 1
    nxaxes   : A list of NXfields containing the signal axes
    nxerrors : The NXfield containing the errors

    Methods
    -------
    plot(self, fmt, over=False, log=False, logy=False, logx=False, **opts)
        Plot the NXdata group using the defined signal and axes. Valid
        Matplotlib parameters, specifying markers, colors, etc, can be
        specified using format argument or through keyword arguments.

    logplot(self, fmt, over=False, logy=False, logx=False, **opts)
        Plot the NXdata group using the defined signal and axes with
        the intensity plotted on a logarithmic scale. In one-dimensional
        plots, this is the y-axis. In two-dimensional plots, it is the 
        color scale.

    oplot(self, fmt, **opts)
        Plot the NXdata group using the defined signal and axes over
        the current plot.

    moment(self, order=1)
        Calculate moments of the NXdata group. This assumes that the
        signal is one-dimenional. Currently, only the first moment is
        implemented.

    Examples
    --------
    There are three methods of creating valid NXdata groups with the
    signal and axes NXfields defined according to the NeXus standard.
    
    1) Create the NXdata group with Numpy arrays that will be assigned
       default names.
       
    >>> x = np.linspace(0, 2*np.pi, 101)
    >>> line = NXdata(sin(x), x)
    data:NXdata
      signal = float64(101)
        @axes = x
        @signal = 1
      axis1 = float64(101)
      
    2) Create the NXdata group with NXfields that have their internal
       names already assigned.

    >>> x = NXfield(linspace(0,2*pi,101), name='x')
    >>> y = NXfield(linspace(0,2*pi,101), name='y')    
    >>> X, Y = np.meshgrid(x, y)
    >>> z = NXfield(sin(X) * sin(Y), name='z')
    >>> entry = NXentry()
    >>> entry.grid = NXdata(z, (x, y))
    >>> grid.tree()
    entry:NXentry
      grid:NXdata
        x = float64(101)
        y = float64(101)
        z = float64(101x101)
          @axes = x:y
          @signal = 1

    3) Create the NXdata group with keyword arguments defining the names 
       and set the signal and axes using the nxsignal and nxaxes properties.

    >>> x = linspace(0,2*pi,101)
    >>> y = linspace(0,2*pi,101)  
    >>> X, Y = np.meshgrid(x, y)
    >>> z = sin(X) * sin(Y)
    >>> entry = NXentry()
    >>> entry.grid = NXdata(z=sin(X)*sin(Y), x=x, y=y)
    >>> entry.grid.nxsignal = entry.grid.z
    >>> entry.grid.nxaxes = [entry.grid.x.entry.grid.y]
    >>> grid.tree()
    entry:NXentry
      grid:NXdata
        x = float64(101)
        y = float64(101)
        z = float64(101x101)
          @axes = x:y
          @signal = 1
    """

    def __init__(self, signal=None, axes=None, *items, **opts):
        self._class = "NXdata"
        NXgroup.__init__(self, *items, **opts)
        if signal is not None:
            if isinstance(signal,NXfield):
                if signal.nxname == "unknown": signal.nxname = "signal"
                if "signal" not in signal.attrs: signal.signal = 1
                self[signal.nxname] = signal
                signalname = signal.nxname
            else:
                self["signal"] = signal
                self["signal"].signal = 1
                signalname = "signal"
            if axes is not None:
                if not isinstance(axes,tuple) and not isinstance(axes,list):
                    axes = [axes]
                axisnames = {}
                i = 0
                for axis in axes:
                    i = i + 1
                    if isinstance(axis,NXfield):
                        if axis._name == "unknown": axis._name = "axis%s" % i
                        self[axis.nxname] = axis
                        axisnames[i] = axis.nxname
                    else:
                        axisname = "axis%s" % i
                        self[axisname] = axis
                        axisnames[i] = axisname
                self[signalname].axes = ":".join(axisnames.values())

    def __add__(self, other):
        """
        Define a method for adding a NXdata group to another NXdata group
        or to a number. Only the signal data is affected.

        The result contains a copy of all the metadata contained in
        the first NXdata group. The module checks that the dimensions are
        compatible, but does not check that the NXfield names or values are
        identical. This is so that spelling variations or rounding errors
        do not make the operation fail. However, it is up to the user to
        ensure that the results make sense.
        """
        result = NXdata(entries=self.entries, attrs=self.attrs)
        if isinstance(other, NXdata):
            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:
                result.entries[self.nxsignal.nxname] = self.nxsignal + other.nxsignal
                if self.nxerrors:
                    if other.nxerrors:
                        result.errors = np.sqrt(self.errors.nxdata**2+other.errors.nxdata**2)
                    else:
                        result.errors = self.errors
                return result
        elif isinstance(other, NXgroup):
            raise NeXusError("Cannot add two arbitrary groups")
        else:
            result.entries[self.nxsignal.nxname] = self.nxsignal + other
            result.entries[self.nxsignal.nxname].nxname = self.nxsignal.nxname
            return result

    def __sub__(self, other):
        """
        Define a method for subtracting a NXdata group or a number from
        the NXdata group. Only the signal data is affected.

        The result contains a copy of all the metadata contained in
        the first NXdata group. The module checks that the dimensions are
        compatible, but does not check that the NXfield names or values are
        identical. This is so that spelling variations or rounding errors
        do not make the operation fail. However, it is up to the user to
        ensure that the results make sense.
        """
        result = NXdata(entries=self.entries, attrs=self.attrs)
        if isinstance(other, NXdata):
            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:
                result.entries[self.nxsignal.nxname] = self.nxsignal - other.nxsignal
                if self.nxerrors:
                    if other.nxerrors:
                        result.errors = np.sqrt(self.errors.nxdata**2+other.errors.nxdata**2)
                    else:
                        result.errors = self.errors
                return result
        elif isinstance(other, NXgroup):
            raise NeXusError("Cannot subtract two arbitrary groups")
        else:
            result.entries[self.nxsignal.nxname] = self.nxsignal - other
            result.entries[self.nxsignal.nxname].nxname = self.nxsignal.nxname
            return result

    def __mul__(self, other):
        """
        Define a method for multiplying the NXdata group with a NXdata group
        or a number. Only the signal data is affected.

        The result contains a copy of all the metadata contained in
        the first NXdata group. The module checks that the dimensions are
        compatible, but does not check that the NXfield names or values are
        identical. This is so that spelling variations or rounding errors
        do not make the operation fail. However, it is up to the user to
        ensure that the results make sense.
        """
        result = NXdata(entries=self.entries, attrs=self.attrs)
        if isinstance(other, NXdata):

            # error here signal not defined in this scope
            #if self.nxsignal and signal.shape == other.nxsignal.shape:
            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:
                result.entries[self.nxsignal.nxname] = self.nxsignal * other.nxsignal
                if self.nxerrors:
                    if other.nxerrors:
                        result.errors = np.sqrt((self.errors.nxdata*other.nxsignal.nxdata)**2+
                                                (other.errors.nxdata*self.nxsignal.nxdata)**2)
                    else:
                        result.errors = self.errors
                return result
        elif isinstance(other, NXgroup):
            raise NeXusError("Cannot multiply two arbitrary groups")
        else:
            result.entries[self.nxsignal.nxname] = self.nxsignal * other
            result.entries[self.nxsignal.nxname].nxname = self.nxsignal.nxname
            if self.nxerrors:
                result.errors = self.errors * other
            return result

    def __rmul__(self, other):
        """
        Define a method for multiplying NXdata groups.

        This variant makes __mul__ commutative.
        """
        return self.__mul__(other)

    def __div__(self, other):
        """
        Define a method for dividing the NXdata group by a NXdata group
        or a number. Only the signal data is affected.

        The result contains a copy of all the metadata contained in
        the first NXdata group. The module checks that the dimensions are
        compatible, but does not check that the NXfield names or values are
        identical. This is so that spelling variations or rounding errors
        do not make the operation fail. However, it is up to the user to
        ensure that the results make sense.
        """
        result = NXdata(entries=self.entries, attrs=self.attrs)
        if isinstance(other, NXdata):
            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:
                # error here, signal and othersignal not defined here
                #result.entries[self.nxsignal.nxname] = signal / othersignal
                result.entries[self.nxsignal.nxname] = self.nxsignal / other.nxsignal
                resultvalues = result.entries[self.nxsignal.nxname].nxdata
                if self.nxerrors:
                    if other.nxerrors:
                        result.errors = (np.sqrt(self.errors.nxdata**2 +
                                         (resultvalues*other.errors.nxdata)**2)
                                         / other.nxsignal)
                    else:
                        result.errors = self.errors
                return result
        elif isinstance(other, NXgroup):
            raise NeXusError("Cannot divide two arbitrary groups")
        else:
            result.entries[self.nxsignal.nxname] = self.nxsignal / other
            result.entries[self.nxsignal.nxname].nxname = self.nxsignal.nxname
            if self.nxerrors: result.errors = self.errors / other
            return result


class NXmonitor(NXdata):

    """
    NXmonitor group. This is a subclass of the NXdata class.

    See the NXdata and NXgroup documentation for more details.
    """

    def __init__(self, signal=None, axes=(), *items, **opts):
        NXdata.__init__(self, signal=signal, axes=axes, *items, **opts)
        self._class = "NXmonitor"
        if "name" not in opts.keys():
            self._name = "monitor"


class NXlog(NXgroup):

    """
    NXlog group. This is a subclass of the NXgroup class.

    Methods
    -------
    plot(self, **opts)
        Plot the logged values against the elapsed time. Valid
        Matplotlib parameters, specifying markers, colors, etc, can be
        specified using the 'opts' dictionary.

    See the NXgroup documentation for more details.
    """

    def __init__(self, *items, **opts):
        self._class = "NXlog"
        NXgroup.__init__(self, *items, **opts)

    def plot(self, **opts):
        axis = [self.time]
        title = "%s Log" % self.value.nxname.upper()
        self._plotter.plot(self.value, axis, title, **opts)


#-------------------------------------------------------------------------
#Add remaining base classes as subclasses of NXgroup and append to __all__

for _class in _nxclasses:
    if _class not in globals():
        docstring = """
                    %s group. This is a subclass of the NXgroup class.

                    See the NXgroup documentation for more details.
                    """ % _class
        globals()[_class]=type(_class, (NXgroup,),
                               {'_class':_class,'__doc__':docstring})
    __all__.append(_class)

#-------------------------------------------------------------------------


def centers(signal, axes):
    """
    Return the centers of the axes.

    This works regardless if the axes contain bin boundaries or centers.
    """
    def findc(axis, dimlen):
        if axis.shape[0] == dimlen+1:
            return (axis.nxdata[:-1] + axis.nxdata[1:])/2
        else:
            assert axis.shape[0] == dimlen
            return axis.nxdata
    return [findc(a,signal.shape[i]) for i,a in enumerate(axes)]

def setmemory(value):
    """
    Set the memory limit for data arrays (in MB).
    """
    global NX_MEMORY
    NX_MEMORY = value

def label(field):
    """
    Return a label for a data field suitable for use on a graph axis.
    """
    if hasattr(field,'long_name'):
        return field.long_name
    elif hasattr(field,'units'):
        return "%s (%s)"%(field.nxname,field.units)
    else:
        return field.nxname

# File level operations
def load(filename, mode='r'):
    """
    Read a NeXus file returning a tree of objects.

    This is aliased to 'read' because of potential name clashes with Numpy
    """
    file = NeXusTree(filename,mode)
    tree = file.readfile()
    file.close()
    return tree

#Definition for when there are name clashes with Numpy
nxload = load
__all__.append('nxload')

def save(filename, group, format='w5'):
    """
    Write a NeXus file from a tree of objects.
    """
    if group.nxclass == "NXroot":
        tree = group
    elif group.nxclass == "NXentry":
        tree = NXroot(group)
    else:
        tree = NXroot(NXentry(group))
    file = NeXusTree(filename, format)
    file.writefile(tree)
    file.close()

def tree(file):
    """
    Read and summarize the named NeXus file.
    """
    nxfile = load(file)
    nxfile.tree

def demo(argv):
    """
    Process a list of command line commands.

    'argv' should contain program name, command, arguments, where command is one
    of the following:
        copy fromfile.nxs tofile.nxs
        ls f1.nxs f2.nxs ...
    """
    if len(argv) > 1:
        op = argv[1]
    else:
        op = 'help'
    if op == 'ls':
        for f in argv[2:]: dir(f)
    elif op == 'copy' and len(argv)==4:
        tree = load(argv[2])
        save(argv[3], tree)
    elif op == 'plot' and len(argv)==4:
        tree = load(argv[2])
        for entry in argv[3].split('.'):
            tree = getattr(tree,entry)
        tree.plot()
        tree._plotter.show()

    else:
        usage = """
usage: %s cmd [args]
    copy fromfile.nxs tofile.nxs
    ls *.nxs
    plot file.nxs entry.data
        """%(argv[0],)
        print usage


if __name__ == "__main__":
    import sys
    demo(sys.argv)