nod3_pub.py 117 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2012 MPIfR
# Peter Mueller
# contact: peter@mpifr.de

# Copyright © 2010-2011 CEA
# Pierre Raybaut
# Licensed under the terms of the CECILL License
# (see guiqwt/__init__.py for details)

"""
NOD3 single dish data reduction software
Image processing application on FITS data (NOD3FITS)
"""

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

import sys, platform, os.path as osp, os, re
import signal
#try:
#   import pywcs
#except:
#   if hash('a') < 0:
#      sys.path.append("/homes/peter/NOD3/32bit/lib/python2.6/site-packages")
#   else:
#      sys.path.append("/homes/peter/NOD3/64bit/lib/python2.6/site-packages")
if sys.path[0] == "": sys.path.pop(0)
if hash('a') < 0:
   sys.path.insert(1, sys.path[0]+"/32bit/lib/python2.6/site-packages")
else:
   sys.path.insert(1, sys.path[0]+"/64bit/lib/python2.6/site-packages")

import pyfits
NOD3DIR = os.getenv("HOME")
#NOD3DIR = os.getenv("HOME") + '/NOD3/Fits/'

NOD3_toolbar = ("EffRedu", "Processing", "Polarization", "Baseline", "MapEdit", "Filter", "Fit", "Misc", "Transform", "Colors", "User")

from guidata.qt.QtGui import (QMainWindow, QMessageBox, QSplitter, QListWidget,
                              QVBoxLayout, QHBoxLayout, QWidget, QTabWidget, QPainter,
                              QMenu, QApplication, QCursor, QFont, QColor)
from guidata.qt.QtCore import Qt, QObject, QT_VERSION_STR, PYQT_VERSION_STR, SIGNAL, QSizeF
from guidata.qt.QtGui import QPrinter, QPrintDialog, QPixmap
from guidata.qt.compat import getopenfilenames, getsavefilename
import guiqwt.colormap as cm
from guiqwt.curve import CurvePlot
from guiqwt.tools import (SelectPointTool, SelectTool, InteractiveTool, ColormapTool, 
                          ContrastPanelTool, CrossSectionTool, ItemListPanelTool,
                          AnnotatedRectangle, SaveAsTool, PrintTool, HelpTool, #PrintFilter,
                          XCSPanelTool, YCSPanelTool, SnapshotTool, AspectRatioTool,
                          ReverseYAxisTool, RectangularActionTool, RectangularShapeTool,
                          AnnotatedEllipseTool, BaseCursorTool, ImageStatsTool, ImageStatsRectangle)

import numpy as np
import copy as cp
import cPickle
from nod3tools import MapSelectTool, PolygonTool, ContrastTool, TimeAxisTool

from guiqwt.image import pixelround, INTERP_NEAREST, INTERP_LINEAR
from guidata.dataset.datatypes import DataSet, ValueProp
from guidata.dataset.dataitems import (IntItem, FloatArrayItem, StringItem, TextItem,
                                       ChoiceItem, FloatItem, DictItem, ButtonItem,
                                       BoolItem)
from guidata.dataset.qtwidgets import DataSetEditGroupBox, DataSetEditLayout, FloatArrayWidget
from guidata.configtools import get_icon
from guidata.qthelpers import create_action, add_actions, get_std_icon
from guidata.qtwidgets import DockableWidget, DockableWidgetMixin
from guidata.utils import update_dataset, restore_dataset

from guiqwt.transitional import QwtLinearColorMap, QwtPlotPrintFilter
from guiqwt.config import CONF, _
from guiqwt.plot import ImageWidget, ImageDialog, CurveDialog
from guiqwt.builder import make
from guiqwt.signals import (SIG_LUT_CHANGED, SIG_CLICK_EVENT, SIG_ITEM_REMOVED, 
                            SIG_VALIDATE_TOOL,
                            SIG_TOOL_JOB_FINISHED, SIG_AXIS_DIRECTION_CHANGED)
from guiqwt.events import (ClickHandler, QtDragHandler, ObjectHandler, KeyEventMatch, 
                           setup_standard_tool_filter)
from guiqwt.signals import (SIG_START_TRACKING, SIG_MOVE, SIG_STOP_NOT_MOVING, SIG_STOP_MOVING)
from guiqwt.styles import ItemParameters, ImageFilterParam, LabelParam
from guiqwt.image import ImageFilterItem
from guiqwt.geometry import (compute_center, compute_rect_size,
                             compute_distance, compute_angle)
from guiqwt.label import DataInfoLabel
from guiqwt.interfaces import IColormapImageItemType, IVoiImageItemType


APP_NAME = _("NOD3 single dish data reduction system")
APP_DESC = _("""NOD3 is a data reduction and filtering tool<br>
with applications on FITS data""")
VERSION = '0.2.3'

def TimeDelta(val, typ):
    '''returns h:m:s or d:m:s for axis labels'''
    if val < 0:
       val = -val
       S = "-"
    else:
       S = ""
    h = int(val/3600)
    m = int((val-3600*h)/60)
    s = int((val-3600*h-60*m))
    if typ == "d": 
       #return str(u"%s%2.2dd%2.2d%s:%2.2d%s" % (S,h,m,"'",s,'"'))
       return "".join(["%s" % S, u"%2.2d°" % h, u"%2.2d'" % m, u'%2.2d"' % s])
    else:
       return u"%s%2.2d<sup>h</sup>%2.2d<sup>m</sup>%2.2d<sup>s</sup>" % (S,h,m,s)

def nint(x):
    if x > 0: return int(x+0.5)
    else: return int(x-0.5)

def _add_all_supported_files(filters):
    extlist = re.findall(r'\*.[a-zA-Z0-9]*', filters)
    allfiles = '%s (%s)\n' % (_("All supported files"), ' '.join(extlist))
    return allfiles+filters

class SignalParam(DataSet):

    #FloatArrayItem.format_string
    #title = StringItem(_("Title"), default=_("Untitled"))
    #data = FloatArrayItem(_("Data"), transpose=True, minmax="both")

    def copy_data_from(self, other, dtype=None):
        self.xydata = np.array(other.xydata, copy=True, dtype=dtype)
    def change_data_type(self, dtype):
        self.xydata = np.array(self.xydata, dtype=dtype)
    def get_data(self):
        if self.xydata is not None:
            return self.xydata[1]
    def set_data(self, data):
        self.xydata[1] = data
    data = property(get_data, set_data)

def update_fits_metadata(obj):
    # update new fits metadata from properties menu
    for key in obj.metadata:
        if type(key) == type(u'test'):
           key = str(key)
        if type(obj.metadata[key]) == type(u'test'):
           obj.metadata[key] = str(obj.metadata[key])
        obj.header.update(key, obj.metadata[key])

class NOD3ImageStatsRectangle(ImageStatsRectangle):
    LABEL_ANCHOR = "C"
    def __init__(self, x1=0, y1=0, x2=0, y2=0, annotationparam=None):
        super(NOD3ImageStatsRectangle, self).__init__(x1, y1, x2, y2,
                                                  annotationparam)
        self.image_item = None

    def set_image_item(self, image_item):
        self.image_item = image_item
        self.LABEL_ANCHOR = self.image_item.LABEL_ANCHOR
        self.label = self.create_label()
        self.set_label_position()

    def create_label(self):
        """Return the label object associated to this annotated shape object"""
        label_param = LabelParam(_("Label"), icon='label.png')
        label_param.read_config(CONF, "plot", "shape/label")
        label_param.anchor = self.LABEL_ANCHOR
        return DataInfoLabel(label_param, [self])


class NOD3FloatArrayWidget(FloatArrayWidget):
    """
    FloatArrayItem widget
    """
    def __init__(self, item, parent_layout):
        super(NOD3FloatArrayWidget, self).__init__(item, parent_layout)
        _label = item.get_prop_value("display", "label")

    def update(self, arr):
        """Override AbstractDataSetWidget method"""
        shape = arr.shape
        if len(shape) == 1:
            shape = (1,) + shape
        dim = " x ".join( [ str(d) for d in shape ])
        self.dim_label.setText(dim)

        format = self.item.get_prop_value("display", "format")
        minmax = self.item.get_prop_value("display", "minmax")
        try:
            if minmax == "all":
                mint = format % np.nanmin(arr)
                maxt = format % np.nanmax(arr)
            elif minmax == "columns":
                mint = ", ".join([format % np.nanmin(arr[r, :])
                                  for r in range(arr.shape[0])])
                maxt = ", ".join([format % np.nanmax(arr[r, :])
                                  for r in range(arr.shape[0])])
            else:
                mint = ", ".join([format % np.nanmin(arr[:, r])
                                  for r in range(arr.shape[1])])
                maxt = ", ".join([format % np.nanmax(arr[:, r])
                                  for r in range(arr.shape[1])])
        except (TypeError, IndexError):
            mint, maxt = "-", "-"
        self.min_label.setText(mint)
        self.max_label.setText(maxt)

class ImageParam(DataSet):

    DataSetEditLayout.register(FloatArrayItem, NOD3FloatArrayWidget)
    data = FloatArrayItem(_("Data"), transpose=True, format="%.10g")
    metadata = DictItem(_("Header"), default=None, help="Edit FITS header elements")
    history = DictItem(_("NOD3 history"), default=None, help="Shows FITS history lines")

    def copy_data_from(self, other, dtype=None):
        self.data = np.array(other.data, copy=True, dtype=dtype)
        if hasattr(other, 'header'):
           # update new fits metadata from properties menu
           update_fits_metadata(other)
           self.header = other.header.copy()
        if hasattr(other, 'parmap'):
           self.parmap = np.array(other.parmap, copy=True, dtype=dtype)
        if hasattr(other, 'sidmap'):
           self.sidmap = np.array(other.sidmap, copy=True, dtype=dtype)
    def change_data_type(self, dtype):
        self.data = np.array(self.data, dtype=dtype)


class ObjectFT(QSplitter):

    """Object handling the item list, the selected item properties and plot"""

    PARAMCLASS = None
    PREFIX = None
    def __init__(self, parent, plot):
        super(ObjectFT, self).__init__(Qt.Vertical, parent)
        self.Take = False
        self.Pixel = False
        self.Alpha = 1.0
        self.AlphaMask = False
        self.Outliers = 2.5
        self.Separate = True
        #self.InterpolationMode = INTERP_NEAREST
        self.IntSize = None
        self.plot = plot
        self.objects = [] # signals or images
        self.items = [] # associated plot items
        self.listwidget = None
        self.properties = None
        self._hsplitter = None
        
        self.file_actions = None
        self.edit_actions = None
        self.view_actions = None
        self.operation_actions = None
        self.processing_actions = None
        self.baseline_actions = None
        self.fit_actions = None
        self.color_actions = None
        self.transform_actions = None
        self.user_actions = None
        self.imagewidget = parent.imagewidget
        
        # Object selection dependent actions
        self.actlist_1more = []
        self.actlist_2more = []
        self.actlist_1 = []
        self.actlist_2 = []

        # set grid invisible
        if self.plot.grid.isVisible():
           self.plot.grid.hide() 
        
        # keyboard interaction
        self.KEY = None
        def _KeyEvent(event):
            self.KEY = event.key()
        self.STOP = False
        self.plot.keyPressEvent = _KeyEvent
        self.original_sigint = signal.getsignal(signal.SIGINT)
        signal.signal(signal.SIGINT, self.signal_handler)

        # special patches to make life easier
        self.plot.do_autoscale = self.do_autoscale
        self.plot.do_zoom_view = self.do_zoom_view
        self.plot.do_move_marker = self.do_move_marker
        self.plot.cross_marker.update_label = self.update_label
        self.plot.Aspect = True

    def select(self):
        self.item.selected = True
        self.item.border_rect.unselect()

    def do_zoom_view(self, dx, dy):
        """Reimplement CurvePlot method"""
        CurvePlot.do_zoom_view(self.plot, dx, dy, lock_aspect_ratio=True)

    def do_move_marker(self, event):
        pos = event.pos()
        self.plot.set_marker_axes()
        if event.modifiers() & self.plot.curve_pointer:
           self.plot.curve_marker.setZ(self.plot.get_max_z()+1)
           self.plot.cross_marker.setVisible(False)
           self.plot.curve_marker.setVisible(True)
           self.plot.curve_marker.move_local_point_to(0, pos)
           self.plot.replot()
           #self.move_curve_marker(self.curve_marker, xc, yc)
        elif event.modifiers() & Qt.ShiftModifier or self.plot.canvas_pointer:
           self.plot.cross_marker.setZ(self.plot.get_max_z()+1)
           self.plot.cross_marker.setVisible(True)
           self.plot.curve_marker.setVisible(False)
           self.plot.cross_marker.move_local_point_to(0, pos)
           self.plot.replot()
           #self.move_canvas_marker(self.cross_marker, xc, yc)
        elif event.modifiers() & Qt.AltModifier or self.plot.canvas_pointer:
           self.plot.cross_marker.setZ(self.plot.get_max_z()+1)
           self.plot.cross_marker.setVisible(True)
           self.plot.curve_marker.setVisible(False)
           self.plot.cross_marker.move_local_point_to(0, pos)
           self.plot.replot()
           #self.move_canvas_marker(self.cross_marker, xc, yc)
        else:
           vis_cross = self.plot.cross_marker.isVisible()
           vis_curve = self.plot.curve_marker.isVisible()
           self.plot.cross_marker.setVisible(False)
           self.plot.curve_marker.setVisible(False)
           if vis_cross or vis_curve:
              self.plot.replot()

    def get_coordinates_label(self, xc, yc):
        z = self.items[self.row].get_data(xc, yc)
        return "x = %d<br>y = %d<br>z = %g" % (xc, yc, z) 

    def update_label(self):
        cm = self.plot.cross_marker
        x, y = cm.xValue(), cm.yValue()
        if not hasattr(self, 'row'):
           return
        xmin = min(self.items[self.row].xmin, self.items[self.row].xmax)
        xmax = max(self.items[self.row].xmin, self.items[self.row].xmax)
        ymin = min(self.items[self.row].ymin, self.items[self.row].ymax)
        ymax = max(self.items[self.row].ymin, self.items[self.row].ymax)
        if xmin <= x and xmax >= x and ymin <= y and ymax >= y:
           z = self.items[self.row].get_data(x,y)
        else:
           z = np.nan
        if cm.label_cb:
            label = cm.label_cb(x, y)
            if label is None:
                return
        elif cm.is_vertical():
            label = "x = %g" % x
        elif cm.is_horizontal():
            label = "y = %g" % y
        elif not self.AxesUseTime:
            label = u"x = %g°<br>y = %g°<br>z = %g" % (x, y, z)
        else:
            if self.AxisUseHour:
               label = "x = %s<br>y = %s<br>z = %g" % (TimeDelta(x/15.0, 'h'), TimeDelta(y, 'd'), z)
            else:
               label = "x = %s<br>y = %s<br>z = %g" % (TimeDelta(x, 'd'), TimeDelta(y, 'd'), z)
        text = cm.label()
        text.setText(label)
        cm.setLabel(text)
        plot = cm.plot()
        if plot is not None:
            xaxis = plot.axisScaleDiv(cm.xAxis())
            xmap = plot.canvasMap(cm.xAxis())
            x_left, x_right = xmap.s1(), xmap.s2()
            if x < (xaxis.upperBound()+xaxis.lowerBound())/2:
                if x_left < x_right:
                   hor_alignment = Qt.AlignRight
                else:
                   hor_alignment = Qt.AlignLeft
            else:
                if x_left < x_right:
                   hor_alignment = Qt.AlignLeft
                else:
                   hor_alignment = Qt.AlignRight
            yaxis = plot.axisScaleDiv(cm.yAxis())
            ymap = plot.canvasMap(cm.yAxis())
            y_top, y_bottom = ymap.s1(), ymap.s2()
            if y < (yaxis.upperBound()+yaxis.lowerBound())/2:
                if y_top > y_bottom:
                    ver_alignment = Qt.AlignBottom
                else:
                    ver_alignment = Qt.AlignTop
            else:
                if y_top > y_bottom:
                    ver_alignment = Qt.AlignTop
                else:
                    ver_alignment = Qt.AlignBottom
            cm.setLabelAlignment(hor_alignment|ver_alignment)

    def signal_handler(self, signum, frame):
        #signal.signal(signum, self.original_sigint)
        #print "Signal ^C pressed in nod3"
        self.STOP = True
        #signal.signal(signal.SIGINT, self.signal_handler)

#------Setup widget, menus, actions
    def setup(self, toolbar):
        self.listwidget = QListWidget()
        #self.listwidget.setMinimumHeight(400)
        self.listwidget.setAlternatingRowColors(True)
        self.listwidget.setSelectionMode(QListWidget.ExtendedSelection)
        self.properties = DataSetEditGroupBox(_("Properties"), self.PARAMCLASS)
        self.properties.setEnabled(False)

        self.connect(self.listwidget, SIGNAL("currentRowChanged(int)"),
                     self.current_item_changed)
        self.connect(self.listwidget, SIGNAL("itemSelectionChanged()"),
                     self.selection_changed)
        self.connect(self.properties, SIGNAL("apply_button_clicked()"),
                     self.properties_changed)
        
        properties_stretched = QWidget()
        properties_stretched.setMaximumHeight(260)
        hlayout = QHBoxLayout()
        hlayout.addWidget(self.properties)
        #hlayout.addStretch()
        vlayout = QVBoxLayout()
        vlayout.addLayout(hlayout)
        vlayout.addStretch()
        properties_stretched.setLayout(vlayout)
        
        self.addWidget(self.listwidget)
        self.addWidget(properties_stretched)

        # Edit actions
        duplicate_action = create_action(self, _("Duplicate"),
                                         icon=get_icon('copy.png'),
                                         tip=_("Duplicate selected rows"),
                                         triggered=self.duplicate_object)
        self.actlist_1 += [duplicate_action]
        createscript_action = create_action(self, _("CreateScript"),
                                         icon=get_icon('edit.png'),
                                         tip=_("Create script from history"),
                                         triggered=self.create_script)
        self.actlist_1 += [createscript_action]
        remove_all_action = create_action(self, _("Remove ALL!"),
                                      icon=get_icon('delete.png'),
                                      tip=_("Remove all rows"),
                                      triggered=self.remove_all_object)
        #self.actlist_1 += [remove_all_action]
        self.actlist_1more += [remove_all_action]
        remove_action = create_action(self, _("Remove"),
                                      icon=get_icon('delete.png'),
                                      tip=_("Remove selected rows"),
                                      triggered=self.remove_object)
        self.actlist_1more += [remove_action]
        self.edit_actions = [createscript_action, duplicate_action, remove_all_action, remove_action]
        
        # Operation actions
        sum_action = create_action(self, _("Sum"), triggered=self.compute_sum)
        average_action = create_action(self, _("Average"),
                                       triggered=self.compute_average)
        diff_action = create_action(self, _("Difference"),
                                    triggered=self.compute_difference)
        prod_action = create_action(self, _("Product"),
                                    triggered=self.compute_product)
        div_action = create_action(self, _("Division"),
                                   triggered=self.compute_division)
        self.actlist_2more += [sum_action, average_action, prod_action]
        self.actlist_2 += [diff_action, div_action]
        self.operation_actions = [sum_action, average_action,
                                  diff_action, prod_action, div_action]
        limit_action = create_action(self, _("Plot_Limits"),
                                   triggered=self.view_limits)
        outlier_action = create_action(self, _("Plot_Outliers"),
                                   triggered=self.view_outlier)
        alpha_action = create_action(self, _("Plot_Transparency"),
                                   triggered=self.view_alpha)
        separate_action = create_action(self, _("Plot_Separate"),
                                   triggered=self.view_separate)
        format_action = create_action(self, _("Plot_Formats"),
                                   triggered=self.view_plot_formats)
        nearestpixel_action = create_action(self, _("NearestPixel"),
                                   triggered=self.view_nearest_pixel)
        interpolation_action = create_action(self, _("Linear Interpolation"),
                                   triggered=self.view_interpolation)
        pixel_action = create_action(self, _("Axes:Pixel"),
                                   triggered=self.view_axes_pixel)
        coordinate_action = create_action(self, _("Axes:Coordinates"),
                                   triggered=self.view_axes_coordinate)
        self.view_actions = [limit_action, outlier_action, alpha_action, separate_action, 
                             format_action, pixel_action, coordinate_action,
                             nearestpixel_action, interpolation_action]

    #------GUI refresh/setup
    def current_item_changed(self, row):
        if row != -1:
           update_dataset(self.properties.dataset, self.objects[row])
           self.properties.get()
           #self.del_polygon()
           self.hide_polygon()

    def _get_selected_rows(self):
        return [index.row() for index in
                self.listwidget.selectionModel().selectedRows()]
        
    def selection_changed(self):
        """Signal list: selection changed"""
        row = self.listwidget.currentRow()
        self.properties.setDisabled(row == -1)
        # reset to standard (default) tools
        self._set_default_tools()
        self.refresh_plot()
        selected_rows = self._get_selected_rows()
        nbrows = len(selected_rows)
        for act in self.actlist_1more:
            act.setEnabled(nbrows >= 1)
        for act in self.actlist_2more:
            act.setEnabled(nbrows >= 2)
        for act in self.actlist_1:
            act.setEnabled(nbrows == 1)
        for act in self.actlist_2:
            act.setEnabled(nbrows == 2)
        # select items for colormaps
        for row in selected_rows:
            item = self.items[row]
            item.selected = True    # is not self.item, item.select() will not work
            #self.item.select()

    def set_axis_coodinates(self, m):
        if hasattr(m, 'header'):
           self.has_coords = True
           if m.header.has_key('SCANDIR'):
           #if 'SCANDIR' in m.header:
              self.scandir = m.header['SCANDIR']
           else:
              self.scandir = "unknown"
           B, L = m.data.shape
           # corrects coordinates to pixel and plot
           if self.InterpolationMode == INTERP_LINEAR:
              off = 1.0
           else: 
              off = 0.5
           if self.scandir[:2] == "AL":
              if m.header.has_key("PATLONG"):
                 xoff = m.header['PATLONG']
              else:
                 xoff = 0.0
              if m.header.has_key("PATLAT"):
                 yoff= m.header['PATLAT']
              else:
                 yoff = 0.0
           else:
              xoff = yoff = 0.0
           l1 = (0-m.header['CRPIX1']+off)*m.header['CDELT1']
           l2 = (L-m.header['CRPIX1']+off)*m.header['CDELT1']
           b1 = (0-m.header['CRPIX2']+off)*m.header['CDELT2']
           b2 = (B-m.header['CRPIX2']+off)*m.header['CDELT2']
           if  m.header['CTYPE1'][-3:] == "DES" or m.header['CTYPE1'][-3:] == "XRC":
               self.descript = True
           else:
               self.descript = False 
           #if m.header['CTYPE1'].split("-")[0] == "RA" and self.scandir[:2] != "AL" \
           #   and not self.descript: 
           if self.descript:
              fu = "deg"
           #elif m.header['CTYPE2'][:3] in ("DEC", "LAT"):
           #elif m.header['CTYPE2'][:3] == "DEC" and self.scandir != "ALON":
           elif m.header['CTYPE2'][:3] == "DEC" and self.scandir[:2] != "AL":
              fu = "hour"
           else: 
              fu = "deg"

           # set title bold:
           #for axis_id in range(4):
           #    font = self.plot.axes_styles[axis_id].title_font.build_font()
           #    font.setBold(True)
           #    self.plot.axes_styles[axis_id].title_font.update_param(font)
               
           # set colorbar unit
           if m.header.has_key('CALUNIT'):
              calunit = m.header['CALUNIT']
              if calunit.find(" / ") < 0 and calunit.find("/") > 0:
                 calunit = calunit.replace("/", " / ")
              self.plot.set_axis_title("right", calunit)

           #self.plot.lock_aspect_ratio = self.Pixel
           self.plot.lock_aspect_ratio = self.plot.Aspect
           self.plot.apply_aspect_ratio()

           if self.scandir[:2] == "AL":
              self.plot.set_axis_title("bottom", "dAzimuth")
              self.plot.set_axis_title("left", "dElevation")
           elif m.header.has_key('CROTA2') and m.header['CROTA2'] != 0.0:
              self.plot.set_axis_title("bottom", "Longitude")
              self.plot.set_axis_title("left", "Latitude")
           elif self.descript:
              self.plot.set_axis_title("bottom", "d"+m.header['CTYPE1'].split("-")[0])
              self.plot.set_axis_title("left", "d"+m.header['CTYPE2'].split("-")[0])
           else:
              self.plot.set_axis_title("bottom", m.header['CTYPE1'].split("-")[0])
              self.plot.set_axis_title("left", m.header['CTYPE2'].split("-")[0])
           # change to Time Scale
           if m.header['CTYPE2'][:3] in ("DEC", "ALA", "LAT"):
              self.AxesUseTime = True
              self.AxisUseHour = False
           else:
              self.AxesUseTime = False
              self.AxisUseHour = True
           #if m.header['CTYPE1'].find("DES") > 0 or self.scandir[:2] == "AL":
           if self.descript or self.scandir[:2] == "AL":
              if self.AxesUseTime:
                 vu = 3600.0
                 self.vu = vu
                 #self.plot.set_axis_unit("bottom", "d:m:s")
                 #self.plot.set_axis_unit("left", "d:m:s")
              else:
                 if max(abs(l2-l1), abs(b2-b1)) > 1:
                    fu = "deg"
                    vu = 1.0
                 elif max(abs(l2-l1), abs(b2-b1)) > 0.02:
                    fu = "arcmin"
                    vu = 60.0
                 else:
                    fu = "arcsec"
                    vu = 3600.0
                 self.vu = vu
                 #self.plot.set_axis_unit("bottom", "deg")
                 #self.plot.set_axis_unit("left", "deg")
              return l1*vu, l2*vu, b1*vu, b2*vu
           elif m.header['CTYPE2'][:3] in ("DEC"):
              l0 = m.header['CRVAL1']
              b0 = m.header['CRVAL2']
              vu = 3600.0
              self.vu = vu
              if m.header.has_key('EPOCH'):
                 if int(m.header['EPOCH']) == 2000: epoch = 'J2000'
                 elif int(m.header['EPOCH']) == 1950: epoch = 'B1950'
                 elif int(m.header['EPOCH']) == 1900: epoch = 'B1900'
                 else: epoch = "J"+str(int(m.header['EPOCH']))
                 self.AxisUseHour = True
                 self.plot.set_axis_unit("bottom", "%s" % epoch)
                 self.plot.set_axis_unit("left", "%s" % epoch)
              else:
                 self.AxisUseHour = True
                 #self.plot.set_axis_unit("bottom", "h:m:s")
                 #self.plot.set_axis_unit("left", "d:m:s")
              return vu*(l1+l0), vu*(l2+l0), vu*(b1+b0), vu*(b2+b0)
           else:
              l0 = m.header['CRVAL1']
              b0 = m.header['CRVAL2']
              self.plot.set_axis_unit("bottom", fu)
              self.plot.set_axis_unit("left", "deg")
              self.vu = 1.0
              return (l1+l0), (l2+l0), b1+b0, b2+b0
        else:
           self.has_coords = False
           b2, l2 = m.data.shape
           return 0, l2, 0, b2

    def update_coordinates(self, item):
        itemparams = ItemParameters(multiselection=True)
        self.AxesUseTime = False
        self.AxesUseHour = False
        self.descript = False
        #if self.Pixel or not item.header.has_key('CRVAL1'):
        if self.Pixel or not item.header.has_key('CDELT1'):
           # corrects coordinates to pixel and plot
           if self.InterpolationMode == INTERP_LINEAR:
              off = 0.5
           else:
              off = 0.0
           self.plot.set_axis_title("left", 'Pixel')
           self.plot.set_axis_unit("left", None)
           self.plot.set_axis_title("bottom", 'Pixel')
           self.plot.set_axis_unit("bottom", None)
           irows, icols = item.data.shape
           item.set_xdata(0+off, icols-1+off)
           item.set_ydata(0+off, irows-1+off)
           self.plot.set_axis_direction('bottom', reverse=False)
        else:
           l1, l2, b1, b2 = self.set_axis_coodinates(item)
           item.set_xdata(l1, l2)
           if item.header['CDELT1'] > 0.0:
              self.plot.set_axis_direction('bottom', reverse=False)
           else:
              self.plot.set_axis_direction('bottom', reverse=True)
           if item.header['CDELT2'] > 0.0:
              self.plot.set_axis_direction('left', reverse=False)
           else:
              self.plot.set_axis_direction('left', reverse=True)
           #if self.scandir[:2] == "AL":
           #   self.plot.set_axis_direction('bottom', reverse=False)
           #else:
           #   self.plot.set_axis_direction('bottom', reverse=True)
           item.set_ydata(b1, b2)
        self.plot.AxesUseTime = self.AxesUseTime 
        self.plot.AxisUseHour = self.AxisUseHour
        self.plot.Descript = self.descript
        self.plot.NewPlot = True
        item.update_bounds()
        item.update_border()
        item.bounds = item.boundingRect()
        item.get_item_parameters(itemparams)
        item.set_item_parameters(itemparams)
        item.get_coordinates_label = self.get_coordinates_label
        # reverse x-axis
        #self.plot.set_axis_direction('bottom', reverse=True)

    def set_NOD3_Title(self, m):
        TITLE = ""
        if hasattr(m, 'header'): 
           if m.header.has_key('OBJECT'):
           #if 'OBJECT' in m.header:
              TITLE = m.header['OBJECT']
           if m.header.has_key('MAPTYPE'):
           #if 'MAPTYPE' in m.header:
              TITLE += str("[%s]" % m.header['MAPTYPE'])
           if m.header.has_key('CRVAL3'):
           #if 'CRVAL3' in m.header:
              TITLE += str(" @ %-0.2f GHz" % (m.header['CRVAL3']*1.e-9))
           if m.header.has_key('FILENAME') and  m.header.has_key('SCANNUM'):
              snum = int(m.header['SCANNUM'])
              fname = m.header['FILENAME'].split("/")[-1]
              TITLE += str("  # %4.4d  %s" % (snum, fname))
           elif m.header.has_key('FILENAME'):
              fname = m.header['FILENAME'].split("/")[-1]
              TITLE += str("  # %s" % (fname))
           elif m.header.has_key('SCANNUM'):
           #if 'SCANNUM' in m.header:
              TITLE += str("  #%4.4d" % int(m.header['SCANNUM']))
        if m.header.has_key('TITLE'):
           TITLE = m.header['TITLE']
        self.plot.setTitle(TITLE)

    def do_autoscale(self, replot=True):
        """Do autoscale on all axes"""
        #
        # PyQt4.Qwt5.QwtPlot.setAxisAutoScale
        #
        # XXX implement the case when axes are synchronised
        vxmax = None
        for axis_id in self.plot.AXIS_IDS:
            vmin, vmax = None, None
            if not self.plot.axisEnabled(axis_id):
                continue
            for item in self.plot.get_items():
                if isinstance(item, self.plot.AUTOSCALE_TYPES) \
                   and not item.is_empty() and item.isVisible():
                    bounds = item.boundingRect()
                    if axis_id == item.xAxis():
                        xmin, xmax = bounds.left(), bounds.right()
                        if vmin is None or xmin < vmin:
                            vmin = xmin
                        if vmax is None or xmax > vmax:
                            vmax = xmax
                    elif axis_id == item.yAxis():
                        ymin, ymax = bounds.top(), bounds.bottom()
                        if vmin is None or ymin < vmin:
                            vmin = ymin
                        if vmax is None or ymax > vmax:
                            vmax = ymax
            if vmin is None or vmax is None:
                continue
            if vmin == vmax: # same behavior as MATLAB
                vmin -= 1
                vmax += 1
            elif vmin > 0 and vmax > 0: # log scale
                vmin = 10**(np.log10(vmin))
                vmax = 10**(np.log10(vmax))
            if axis_id == item.xAxis():
               vxmin = vmin
               vxmax = vmax
               step = -1
            elif axis_id == item.yAxis():
               vymin = vmin
               vymax = vmax
               step = 1
            self.plot.set_axis_limits(axis_id, vmin, vmax, stepsize=step)
        if vxmax != None: # and abs(vxmax-vxmin) < abs(vymax-vymin):
           if abs(vxmax-vxmin) < abs(vymax-vymin):
              ddx = ((vymax-vymin) - (vxmax-vxmin))/2.0
              self.plot.set_axis_limits(item.xAxis(), vxmin-ddx, vxmax+ddx)
           else:
              ddy = ((vxmax-vxmin) - (vymax-vymin))/2.0
              self.plot.set_axis_limits(item.yAxis(), vymin-ddy, vymax+ddy)
        else:
           return
        self.plot.updateAxes()
        self.emit(SIG_AXIS_DIRECTION_CHANGED, self, self.plot.get_axis_id(item.xAxis()))
        self.emit(SIG_AXIS_DIRECTION_CHANGED, self, self.plot.get_axis_id(item.yAxis()))
        if self.plot.lock_aspect_ratio:
           # has to be False !!
           self.plot.apply_aspect_ratio(full_scale=False)
        if replot:
           self.plot.replot()

    def all_items(self):
        for row in range(len(self.items)):
            self.update_item(row) 

    def refresh_plot(self):
        for item in self.items:
            if item is not None:
                item.hide()
        if hasattr(self, 'REMOVE'):
           del self.REMOVE
           return
        for row in self._get_selected_rows():
            # don't show all images on display, just the first
            if row != self._get_selected_rows()[0]: break
            self.row = row
            item = self.items[row]
            if item is None:
                item = self.make_item(row)
                self.update_coordinates(item)
                # reset y-flip for NOD3 FITS images
                #self.plot.set_axis_direction('left', False)
                self.plot.add_item(item)
            else:
                self.update_item(row)
                # don't show all images on display, just the first
                if self._get_selected_rows()[0] == row: 
                   self.plot.set_item_visible(item, True)
                self.update_coordinates(item)
            self.set_NOD3_Title(item)
            # activates image on start
            self.plot.set_active_item(item)
        #self.plot.do_autoscale(replot=True)
        self.do_autoscale(replot=True)

    def _set_default_tools(self):
        # reset cursor selecton
        active_tool = self.imagewidget.get_active_tool()
        if active_tool == self.get_tool(SelectPointTool):
           if hasattr(self, 'cursor_activ'):
              if self.cursor_activ:
                 QApplication.restoreOverrideCursor()
                 #QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))
                 self.selpos.end_callback = None
                 self.selpos.cursor = None
                 self.selpos.win.set_pointer(None)
                 self.selpos.deactivate()
                 self.cursor_activ = False
           else:
              self.cursor_activ = False
        else:
           # reset to SelectTool 
           self.imagewidget.set_default_tool = self.get_tool(SelectTool)
           self.imagewidget.activate_default_tool()
        # deactivate special tools:
        Tools = ("CrossSectionTool", "ContrastPanelTool", "ImageStatsTool", "XCSPanelTool", "YCSPanelTool")
        ###for tool in self.imagewidget.tools:
        for tool in Tools:
            t = self.get_tool(eval(tool))
            if hasattr(t, 'activate_command'):
               t.activate_command(None, False)
        # deactivate all other items but grid and image
        item_list = []
        for item in self.plot.items:
            if str(item).find("curve.GridItem") < 0  and \
               str(item).find("curve.PolygonMapItem") < 0  and \
               str(item).find("image.ImageItem") < 0:
               self.plot.del_item(item)
               self.plot.emit(SIG_ITEM_REMOVED, item)
            elif str(item).find("curve.GridItem") > 0:
               self.griditem = item

    def refresh_list(self, new_current_row='current'):
        """new_current_row: integer, 'first', 'last', 'current'"""
        # reset to standard (default) tools
        self._set_default_tools()

        row = self.listwidget.currentRow()
        self.listwidget.clear()
        self.listwidget.addItems(["%s%03d: %s" % (self.PREFIX, i+1, obj.title)
                                  for i, obj in enumerate(self.objects)])
        if new_current_row == 'first':
            row = 0
        elif new_current_row == 'last':
            row = self.listwidget.count()-1
        elif isinstance(new_current_row, int):
            row = new_current_row
        else:
            assert new_current_row == 'current'
        if row < self.listwidget.count():
            self.listwidget.setCurrentRow(row)
        # check for grid entry
        if hasattr(self, 'griditem') and self.griditem in self.plot.items:
           self.plot.del_items([self.griditem])
        self.plot.add_item(self.griditem)
        self.plot.replot()
        
    def clears_display(self):
        """The properties 'Apply' button was clicked: updating signal"""
        try:
           self.hide_overlay = True
           self.del_polygon()
           row = self.listwidget.currentRow()
           # update new fits metadata from properties menu
           update_fits_metadata(self.objects[row])
           # does not work with dummy (nan) check
           update_dataset(self.objects[row], self.properties.dataset)
           self.refresh_list(new_current_row='current')
           self.listwidget.setCurrentRow(row)
           #self.refresh_plot()
        except:
           pass
    
    def properties_changed(self):
        """The properties 'Apply' button was clicked: updating signal"""
        try:
           self.hide_overlay = False
           row = self.listwidget.currentRow()
           # update new fits metadata from properties menu
           update_fits_metadata(self.objects[row])
           # does not work with dummy (nan) check
           update_dataset(self.objects[row], self.properties.dataset)
           self.refresh_list(new_current_row='current')
           self.listwidget.setCurrentRow(row)
           #self.refresh_plot()
           self.hide_overlay = True
        except:
           pass
    
    def add_object(self, obj):
        if hasattr(obj, 'header'):
           obj.metadata, obj.history = self.set_metadata(obj.header)
        self.objects.append(obj)
        self.items.append(None)
        self.refresh_list(new_current_row='last')
        self.listwidget.setCurrentRow(len(self.objects)-1)
        self.emit(SIGNAL('object_added()'))
        
    def replace_object(self, obj):
        if hasattr(obj, 'header'):
           obj.metadata, obj.history = self.set_metadata(obj.header)
        self.objects.pop()
        self.items.pop()
        self.objects.append(obj)
        self.items.append(None)
        self.refresh_list(new_current_row='last')
        self.listwidget.setCurrentRow(len(self.objects)-1)
        self.emit(SIGNAL('object_replaced()'))
        
    #------Edit operations
    def duplicate_object(self):
        rows = self._get_selected_rows()
        if rows != []:
           row = rows[0]
           obj = self.objects[row]
           objcopy = self.PARAMCLASS()
           objcopy.title = obj.title
           objcopy.copy_data_from(obj)
           self.objects.insert(row+1, objcopy)
           self.items.insert(row+1, None)
           self.refresh_list(new_current_row=row+1)
           self.refresh_plot()
    
    def create_script(self):
        rows = self._get_selected_rows()
        if rows != []:
           row = rows[0]
           obj = self.objects[row]
           hlines = []
           hcont = False
           for h in obj.header.get_history():
               h = str(h)
               if h.find("NOD3:") >=0:
                  hlines.append(h.split("NOD3:")[1])
                  if len(h) > 79: hcont = True
                  else: hcont = False
               elif hcont:
                  hlines[-1] += h[8:].strip()
                  if len(h) > 79: hcont = True
                  else: hcont = False
           if hlines == []:
              import traceback
              msg = "Sorry, no NOD3 history lines found in selected row     "
              QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
           else:
              self.save_script(hlines)

    def remove_all_object(self):
        if self.Ask("Really remove ALL maps?"):
           self.REMOVE = True
           self.listwidget.selectAll()
           self.remove_object()
        
    def remove_object(self):
        self.REMOVE = True
        rows = sorted(self._get_selected_rows(), reverse=True)
        row1 = max(rows[-1]-1, 0)
        if rows != []:
           for row in rows:
               self.objects.pop(row)
               item = self.items.pop(row)
               self.plot.del_item(item)
           #self.refresh_list(new_current_row='first')
           #self.refresh_list(new_current_row='last')
           #self.refresh_list(new_current_row='current')
           self.refresh_list(new_current_row=row1)
           self.refresh_plot()
        
    #------Operations
    def compute_sum(self):
        rows = self._get_selected_rows()
        sumobj = self.PARAMCLASS()
        sumobj.title = "+".join(["%s%03d" % (self.PREFIX, row+1) for row in rows])
        try:
            for row in rows:
                obj = self.objects[row]
                if sumobj.data is None:
                    sumobj.copy_data_from(obj)
                else:
                    sumobj.data += obj.data
                    #sumobj.data = np.nansum([sumobj.data, obj.data], axis=0)
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
            return
        # write new history entry
        sumobj.header.add_history("NOD3:"+sumobj.title)
        self.add_object(sumobj)
    
    def compute_average(self):
        from scipy import stats
        rows = self._get_selected_rows()
        sumobj = self.PARAMCLASS()
        title = ", ".join(["%s%03d" % (self.PREFIX, row+1) for row in rows])
        sumobj.title = _("Average")+("(%s)" % title)
        original_dtype = self.objects[rows[0]].data.dtype
        objs = []
        try:
            for row in rows:
                obj = self.objects[row]
                if sumobj.data is None:
                    sumobj.copy_data_from(obj, dtype=np.float64)
                    objs.append(obj.data)
                else:
                    #sumobj.data += obj.data
                    objs.append(obj.data)
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
            return
        #sumobj.data /= float(len(rows))
        try:
           sumobj.data = stats.nanmean(np.array(objs), axis=0)
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
            return
        sumobj.change_data_type(dtype=original_dtype)
        # write new history entry
        sumobj.header.add_history("NOD3:"+str(sumobj.title))
        self.add_object(sumobj)
    
    def compute_product(self):
        rows = self._get_selected_rows()
        sumobj = self.PARAMCLASS()
        sumobj.title = "*".join(["%s%03d" % (self.PREFIX, row+1) for row in rows])
        try:
            for row in rows:
                obj = self.objects[row]
                if sumobj.data is None:
                    sumobj.copy_data_from(obj)
                else:
                    sumobj.data *= obj.data
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
            return
        # write new history entry
        sumobj.header.add_history("NOD3:"+sumobj.title)
        self.add_object(sumobj)
    
    def compute_difference(self):
        rows = self._get_selected_rows()
        diffobj = self.PARAMCLASS()
        diffobj.title = "-".join(["%s%03d" % (self.PREFIX, row+1)
                                  for row in rows])
        try:
            obj0, obj1 = self.objects[rows[0]], self.objects[rows[1]]
            diffobj.copy_data_from(obj0)
            diffobj.data = obj0.data-obj1.data
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
            return
        # write new history entry
        diffobj.header.add_history("NOD3:"+diffobj.title)
        self.add_object(diffobj)
    
    def compute_division(self):
        rows = self._get_selected_rows()
        diffobj = self.PARAMCLASS()
        diffobj.title = "/".join(["%s%03d" % (self.PREFIX, row+1)
                                  for row in rows])
        try:
            obj0, obj1 = self.objects[rows[0]], self.objects[rows[1]]
            diffobj.copy_data_from(obj0)
            diffobj.data = obj0.data/obj1.data
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
            return
        # write new history entry
        diffobj.header.add_history("NOD3:"+diffobj.title)
        self.add_object(diffobj)
                                     
    def view_alpha(self):
        class AlphaParam(DataSet):
              Alpha = FloatItem(_("Alpha"), default=1.0, min=0.0, max=1.0)
        param = AlphaParam("Set transparency value", "alpha:")
        param = self.read_defaults(param)
        if not param.edit():
           return
        self.write_defaults(param)
        self.Alpha = param.Alpha
        if self.Alpha < 1.0:
           self.AlphaMask = True
        else:
           self.AlphaMask = False
        self.Take = False
        self.Separate = False
        self.all_items()
        self.refresh_plot()

    def view_outlier(self, data):
        class OutlierParam(DataSet):
              Outliers = FloatItem(_("Outliers"), default=2.5)
        param = OutlierParam("Set outliers", "Percent value:")
        param = self.read_defaults(param)
        if not param.edit():
           return
        self.write_defaults(param)
        self.Outliers = param.Outliers
        self.Take = False
        self.Separate = False
        self.all_items()
        self.refresh_plot()

    def view_limits(self):
        dmin = 0.0
        dmax = 1000.0
        class LimitParam(DataSet):
              Lower = FloatItem(_("Lower Limit"), default=dmin)
              Upper = FloatItem(_("Upper Limit"), default=dmax)
              #Take = BoolItem("Take", default=False)
        param = LimitParam("Set plot range")
        param = self.read_defaults(param)
        param.Take = True
        if not param.edit():
           return
        self.write_defaults(param)
        self.Lower = param.Lower
        self.Upper = param.Upper
        self.Take = param.Take
        self.Separate = False
        self.all_items()
        self.refresh_plot()

    def view_separate(self):
        self.Separate = True
        self.all_items()
        self.refresh_plot()

    def view_plot_formats(self):
        xformat = "%.3f"
        yformat = "%.3f"
        zformat = "%.3f"
        class LimitParam(DataSet):
              Xformat = StringItem(_("xformt"), default=xformat)
              Yformat = StringItem(_("yformt"), default=yformat)
              Zformat = StringItem(_("zformt"), default=zformat)
        param = LimitParam("Set plot range")
        param = self.read_defaults(param)
        param.Take = True
        if not param.edit():
           return
        self.write_defaults(param)
        self.xformat = param.Xformat
        self.yformat = param.Yformat
        self.zformat = param.Zformat
        self.all_items()
        self.refresh_plot()

    def view_nearest_pixel(self):
        self.InterpolationMode = INTERP_NEAREST
        self.IntSize = None
        #self.all_items()
        self.refresh_plot()

    def view_interpolation(self):
        self.InterpolationMode = INTERP_LINEAR
        self.IntSize = None
        #self.all_items()
        self.refresh_plot()

    def view_axes_coordinate(self):
        self.Pixel = False
        #self.all_items()
        #self.plot.lock_aspect_ratio = self.Pixel
        #self.plot.lock_aspect_ratio = True
        #self.plot.apply_aspect_ratio()
        self.refresh_plot()

    def view_axes_pixel(self):
        self.Pixel = True
        #self.all_items()
        #self.plot.lock_aspect_ratio = self.Pixel
        #self.plot.apply_aspect_ratio()
        self.refresh_plot()

    #------ROI selection
    def func1(self, data):
        return data.shape

    def _roi_show(self, x, y, data, filter_area):
        from scipy.ndimage import gaussian_filter
        img = make.xyimage(x, y, data)
        plot = self.imagewidget.get_plot()
        xmin, xmax, ymin, ymax = filter_area
        flt = make.imagefilter(xmin, xmax, ymin, ymax, img,
                   #filter=lambda x, y, data: gaussian_filter(data, 5))
                   filter=lambda x, y, data: gaussian_filter(data, 15))
                   #filter=lambda x, y, data: self.func(self.obj.data, self.obj.header, x, y))
                   #filter=self.func(self.obj.data, self.obj.header, x, y))
                   #filter=lambda x, y, data: self.func1(data))
        plot.add_item(flt, z=1)
        plot.set_active_item(flt)
        plot.replot()

    def roi_selection(self, name, func):
        self.func = func
        self.imagewidget.get_default_tool().deactivate()
        row = self.listwidget.currentRow()
        if row < 0: return
        suffix = None
        if row > -1:
           self.image = self.items[row]
           self.orig = self.objects[row]
           self.obj = self.PARAMCLASS()
           self.obj.title = "%s(%s%03d)" % (name, self.PREFIX, row+1)
           if suffix is not None:
              self.obj.title += " "+suffix(param)
              title = str("%s(%s)" % (name, suffix(param)))
           else:
              title = str("%s()" % name)
           self.obj.copy_data_from(self.orig)
           self.obj.header = cp.copy(self.orig.header)
           self.plot.unselect_all()
        x = np.linspace(0, 30., self.obj.data.shape[1])
        y = np.linspace(0, 30., self.obj.data.shape[0])
        x0 = self.obj.data.shape[1]/2
        y0 = self.obj.data.shape[0]/2
        dx = int(x0/10.0)
        dy = int(y0/10.0)
        x1 = x0-dx
        x2 = x0+dx
        y1 = y0-dy
        y2 = y0+dy
        self._roi_show(x, y, self.obj.data, filter_area=(x1, x2, y1, y2))

    def get_polyline(self, name, funct, param, addmap=True, onein=True):
        row = self.listwidget.currentRow()
        if row < 0: return
        self.row = row
        suffix = None
        polyline = PolygonTool(self.plot.manager)
        polyline.funct = funct
        polyline.param = param
        polyline.nextpoints = []
        polyline._last_item = self.last_item
        polyline.register_plot(self.plot) 
        polyline.activate()
        polyline.setup_filter(self.plot)
        if row == -1: return
        self.objs = []
        for row in self._get_selected_rows():
           self.orig = self.objects[row]
           self.obj = self.PARAMCLASS()
           self.obj.title = "%s(%s%03d)" % (name, self.PREFIX, row+1)
           if suffix is not None:
              self.obj.title += " "+suffix(param)
              title = str("%s(%s)" % (name, suffix(param)))
           else:
              title = str("%s()" % name)
           self.obj.copy_data_from(self.orig)
           self.objs.append(self.obj)
        polyline.obj = self.objs[-1]
        polyline.Finis = False
        polyline.name = name
        polyline.handle_input_output = self.handle_input_output
        polyline.listwidget = self.listwidget

    def get_box_positions(self, name, funct, param, nextbox=True, mshape="box", onein=True):
        row = self.listwidget.currentRow()
        if row < 0: return
        self.row = row
        suffix = None
        rect = MapSelectTool(self.plot.manager, shape_cb=mshape)
        rect.ratio = 1.0
        rect.funct = funct
        rect.param = param
        rect.nextbox = nextbox
        rect.nextpos = []
        rect._last_item = self.last_item
        rect.register_plot(self.plot)
        rect.activate()
        # activate <space> event because tool switches from MapSelectTool to SelectItem (???!)
        rect.KeyEvent(parent=self.imagewidget.get_default_tool())
        if row == -1: return
        self.objs = []
        for row in self._get_selected_rows():
           self.orig = self.objects[row]
           self.obj = self.PARAMCLASS()
           self.obj.title = "%s(%s%03d)" % (name, self.PREFIX, row+1)
           if suffix is not None:
              self.obj.title += " "+suffix(param)
              title = str("%s(%s)" % (name, suffix(param)))
           else:
              title = str("%s()" % name)
           self.obj.copy_data_from(self.orig)
           self.objs.append(self.obj)
        rect.obj = self.objs[-1]
        rect.Finis = False
        rect.name = name
        rect.handle_input_output = self.handle_input_output
        rect.listwidget = self.listwidget
    
    #------Cursor action
    def get_tool(self, ToolKlass):
        """Return tool instance from its class"""
        for tool in self.imagewidget.tools:
            if isinstance(tool, ToolKlass):
               return tool

    def get_pixel_coordinates(self, l, b):
        return self.items[self.row].get_pixel_coordinates(l, b)

    def get_plot_coordinates(self, x, y):
        # corrects coordinates to pixel and plot
        if self.InterpolationMode == INTERP_LINEAR:
           off = 0.0
        else:
           off = 0.5
        l, b = self.items[self.row].get_plot_coordinates(x+off, y+off)
        return l/self.vu, b/self.vu

    def read_cursor(self, tool):
        l, b = tool.get_coordinates()
        x, y = self.get_pixel_coordinates(l, b) 
        self.func(self.objs, self.param, x, y)
        self.cursor_activ = True

    def _close_cursor(self, filter, event):
        #print "cursor closed"
        QApplication.restoreOverrideCursor()
        self.plot.canvas_pointer = False
        #QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))
        if hasattr(self, 'selpos'):
           self.selpos.end_callback = None
           #self.selpos.cursor = None
           #self.selpos.win.set_pointer(None)
           #self.selpos.deactivate()
           del self.selpos
        self.cursor_activ = False
        self.imagewidget.set_default_tool = self.get_tool(SelectTool)
        self.imagewidget.activate_default_tool()

    def Ask(self, msg):
        ask = QMessageBox.question(self.parent(), 'NOD3', msg,
                             QMessageBox.Yes, QMessageBox.No)
        if ask == QMessageBox.Yes: return True
        else: return False

    def get_cursor_positions(self, name, func, param, addmap=False, onein=True):
        self.func = func
        self.param = param
        row = self.listwidget.currentRow()
        if row < 0: return
        self.row = row
        suffix = None
        QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))
        #QApplication.setOverrideCursor(QCursor(Qt.BlankCursor))
        self.selpos = self.get_tool(SelectPointTool)
        self.selpos.TITLE = name
        self.selpos.TIP = "click on left button"
        self.selpos.mode = "reuse"
        self.selpos.marker = self.plot.cross_marker
        self.selpos.end_callback = self.read_cursor
        self.selpos.activate()
        self.setup_KeyEvent(self.selpos, 'Cursor')
        if hasattr(self.selpos, 'get_active_plot'):
           self.selpos.win = self.selpos.get_active_plot()
           self.selpos.win.set_pointer("canvas")
        if row == -1: return
        self.objs = []
        for row in self._get_selected_rows():
           self.orig = self.objects[row]
           self.obj = self.PARAMCLASS()
           self.obj.title = "%s(%s%03d)" % (name, self.PREFIX, row+1)
           if suffix is not None:
              self.obj.title += " "+suffix(param)
              title = str("%s(%s)" % (name, suffix(param)))
           else:
              title = str("%s()" % name)
           self.obj.copy_data_from(self.orig)
           self.objs.append(self.obj)
        if len(self.objs) == 1: self.objs = self.objs[0]
        if addmap:
           self.compute_11(name, lambda m, p: (self.objs, None), None, onein=onein)

    #------Setup Key Event
    def _key_end(self, filter, event):
        #print "key stop event"
        self.key_stop = True

    def setup_KeyEvent(self, parent, action):
        baseplot, start_state = parent.start_state.items()[-1]
        filter = baseplot.filter 
        if action == "Cursor":
           filter.add_event(start_state,
                         KeyEventMatch((Qt.Key_Space,)),
                         self._close_cursor, start_state)
        elif action == "Stop":
           self.key_stop = False
           filter.removeEventFilter(filter)
           filter.add_event(start_state,
                         KeyEventMatch((Qt.Key_Space,)),
                         self._key_end, start_state)

    #------Data Processing
    class ScriptParameter:
          def __init__(self, title, params):
             self._name = title
             self._items = params
             self.title = title
             for p in params:
                 setattr(self, p, params[p])
          def get_title(self):
              return self.title    
          def edit(self, parent=None):
              return True 

    def read_defaults(self, param):
        if param == None: return param
        filename = os.getenv("HOME") + "/.nod3/" + param.get_title().replace(" ","")
        if osp.exists(filename):
           f = open(filename, "r")
           try:
              pdict = cPickle.load(f)
              for p in pdict:
                  setattr(param, p, pdict[p])
           except:
              pass
           f.close()
        return param

    def write_defaults(self, param):
        if param != None:
           # do not write script parameters as next defaults
           if type(param._items) == dict: return
           directory = os.getenv("HOME") + "/.nod3"
           if not osp.exists(directory):
              os.mkdir(directory)
           filename = os.getenv("HOME") + "/.nod3/" + param.get_title().replace(" ","")
           f = open(filename, "w")
           pdict = {}
           for i in param._items:
               pdict[i._name] = getattr(param, i._name)
           cPickle.dump(pdict, f)
           f.close()

    def apply_11_func(self, objs, func, param, onein):
        newobjs = []
        if not onein: objs = [objs]
        for obj in objs:
            x, param = func(obj, param)
            # check for array (cursor)
            if hasattr(x, 'shape'):
               objs.data = x 
            else:
               objs = x
            if type(objs) != list: objs = [objs]
            for obj in objs:
                # setup metadata dictionary from header
                if hasattr(obj, 'header'):
                   obj.header.update("DATAMAX", np.nanmax(obj.data), "MAX VALUE OF ARRAY")
                   obj.header.update("DATAMIN", np.nanmin(obj.data), "MIN VALUE OF ARRAY")
                   obj.metadata, obj.history = self.set_metadata(obj.header)
                newobjs.append(obj)
        return newobjs
    
    def handle_input_output(self, objs, func, param, onein=True):
        try:
           newobjs = self.apply_11_func(objs, func, param, onein)
           self.write_defaults(param)
        except Exception, msg:
           import traceback
           traceback.print_exc()
           QMessageBox.critical(self.parent(), APP_NAME,
                              _(u"Error:")+"\n%s" % str(msg))
           return
        finally:
            self.emit(SIGNAL("status_message(QString)"), "")
            QApplication.restoreOverrideCursor()
        for obj in newobjs:
            if self.display: self.add_object(obj)
            else: self.replace_object(obj)
            if hasattr(self, 'ids'):
               self.ids.append(self.listwidget.selectionModel().currentIndex())

    def compute_11(self, name, func, param=None, onein=True, extern=False, MType=False,
                   one_param_for_all=True, suffix=None):
        # close source list box if open 
        if hasattr(self, 'LView'): 
           if hasattr(self, 'N'): del self.N
           if self.LView.isVisible():
              self.LView.close()
        # close pyplot figure if open 
        if hasattr(self, 'fig'):
           if hasattr(self, 'N'): del self.N
           if self.fig.win.isVisible(): 
              self.fig.win.close()
              del self.fig
        #self.APP_NAME = APP_NAME
        self.APP_NAME = name
        param = self.read_defaults(param)
        if extern:
           self.param = cp.copy(param)
           param = None
        if param is not None and one_param_for_all:
            if not param.edit(parent=self.parent()):
                return
        if param is None: htext=None
        else:
           htext = ""
           for i in param._items:
               if hasattr(i, '_name'):
                  val = getattr(param, i._name)
                  if type(i) in (StringItem, ChoiceItem):
                     val = str("'%s'" % val)
                  htext += str("%s=%s, " % (i._name, val))
               else:
                  val = getattr(param, i)
                  if type(val) == str:
                     val = str("'%s'" % val)
                  htext += str("%s=%s, " % (i, val))
           htext = htext[:-2]
        rows = self._get_selected_rows()
        if onein == 2: onein = False
        in_objs = []
        self.ids = []
        for row in rows:
            self.cmap = self.items[row].imageparam.colormap
            self.row = row
            if param is not None and not one_param_for_all:
                if not param.edit(parent=self.parent()):
                    return
            orig = self.objects[row]
            obj = self.PARAMCLASS()
            obj.copy_data_from(orig)
            if onein:
               obj.title = "%s(%s%03d)" % (name, self.PREFIX, row+1)
               delim = ":"
            else:
               mtype = ""
               if obj.header.has_key('MAPTYPE'): mtype += obj.header['MAPTYPE']
               #if 'MAPTYPE' in obj.header: mtype += obj.header['MAPTYPE']
               if obj.header.has_key('RXHORN'): mtype += str("-%d" % obj.header['RXHORN'])
               #if 'RXHORN' in obj.header: mtype += str("-%d" % obj.header['RXHORN'])
               # changed 2013/06/14 displays maps rather than maptype!
               #if mtype != "":
               if mtype == "":
                  #title = str("%s%s" % (self.PREFIX, mtype))
                  title = mtype
               else:
                  if MType:
                     title = ", ".join(["%s" % (mtype.split("-")[0])])
                  else:
                     title = ", ".join(["%s%03d" % (self.PREFIX, row+1) for row in self._get_selected_rows()])
               obj.title = name + "(%s)" % title
               #delim = ">"
               delim = ":"
            #obj.copy_data_from(orig)
            if htext is not None:
                obj.title += " "+htext
                title = str("NOD3%s%s(%s)" % (delim, name, htext))
            else:
                title = str("NOD3%s%s()" % (delim, name))
            # write new history entry
            if not extern: obj.header.add_history(title)
            self.repaint()
            if onein:
               self.emit(SIGNAL("status_message(QString)"),
                         _("Computing:")+" "+obj.title)
               QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
               self.handle_input_output([obj], func, param, onein)
            else:
               in_objs.append(obj)
        if rows != [] and not onein:
           self.emit(SIGNAL("status_message(QString)"),
                     _("Computing:")+" "+obj.title)
           QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
           self.handle_input_output(in_objs, func, param, onein)
        # add output objects to row selection
        for id in self.ids:
            self.listwidget.selectionModel().select(id, self.listwidget.selectionModel().Select)
        
    def hide_polygon(self):
        if not hasattr(self, 'plot'): return
        if hasattr(self, 'hide_overlay') and not self.hide_overlay: return
        items = self.plot.get_items()
        for item in items:
            itm = str(item).split()[0].split(".")[-1]
            if itm == "PolygonMapItem":
               if item.isVisible():
                  item.hide()

    def del_polygon(self):
        if not hasattr(self, 'plot'): return
        items = self.plot.get_items()
        for item in items:
            itm = str(item).split()[0].split(".")[-1]
            if itm == "PolygonMapItem":
               self.plot.del_items([item])

    def removeNANedges(self, obj):
        rows, cols = obj.data.shape
        r = []
        for row in range(rows):
            if False in np.isnan(obj.data[row]): r.append(row)
        c = []
        for col in range(cols):
            if False in np.isnan(obj.data[:,col]): c.append(col)
        if r == [] or c == []:
           return obj
        j1 = r[0]
        j2 = r[-1]+1
        i1 = c[0]
        i2 = c[-1]+1
        obj.header['CRPIX1'] -= i1
        obj.header['CRPIX2'] -= j1
        obj.data = obj.data[j1:j2,i1:i2]
        if hasattr(obj, 'sidmap'): obj.sidmap = obj.sidmap[j1:j2,i1:i2]
        if hasattr(obj, 'parmap'): obj.parmap = obj.parmap[j1:j2,i1:i2]
        newrows, newcols = obj.data.shape
        obj.header['NAXIS1'] = newcols
        obj.header['NAXIS2'] = newrows
        return obj


class ImageFT(ObjectFT):

    PARAMCLASS = ImageParam
    PREFIX = "map"
    #------ObjectFT API
    def setup(self, toolbar):
        ObjectFT.setup(self, toolbar)
        self.display = True
 
        # File actions
        open_action = create_action(self, _("Open image..."),
                                    icon=get_icon('fileopen.png'),
                                    tip=_("Open an image"),
                                    triggered=self.open_image)
        script_action = create_action(self, _("Open script..."),
                                    icon=get_icon('edit.png'),
                                    tip=_("Open a script"),
                                    triggered=self.open_script)
        save_action = create_action(self, _("Save image..."),
                                    icon=get_icon('filesave.png'),
                                    tip=_("Save selected FITS map(s)"),
                                    triggered=self.save_image)
        self.actlist_1more += [save_action]
        self.file_actions = [open_action, script_action, save_action]

        # Operation actions
        rotate_menu = QMenu(_("Rotation"), self)
        hflip_action = create_action(self, _("Flip horizontally"),
                                     triggered=self.HFlip)
        vflip_action = create_action(self, _("Flip vertically"),
                                     triggered=self.VFlip)
        rot90_action = create_action(self, _("Rotate 90° right"),
                                     triggered=self.Rotate270)
        rot270_action = create_action(self, _("Rotate 90° left"),
                                      triggered=self.Rotate90)
        rotate_action = create_action(self, _("Rotate arbitrarily..."),
                                      triggered=self.Rotate)
        resize_action = create_action(self, _("Resize"),
                                      triggered=self.Resize)
        roi_action = create_action(self, _("ROI extraction"),
                                    triggered=self.ROI)
        swapaxes_action = create_action(self, _("Swap X/Y axes"),
                                        triggered=self.SwapAxes)
        self.actlist_1 += [resize_action]
        self.actlist_1more += [roi_action, swapaxes_action,
                               hflip_action, vflip_action,
                               rot90_action, rot270_action, rotate_action]
        add_actions(rotate_menu, [hflip_action, vflip_action,
                                  rot90_action, rot270_action, rotate_action])
        self.operation_actions += [None, rotate_menu, None,
                                   resize_action, roi_action, swapaxes_action]
        
        # NOD3 actions
        self.NOD3_all_actions()

        add_actions(toolbar, [open_action, script_action, save_action])
        
        
    def NOD3_all_actions(self):

        self.cwd = os.getcwd() + "/"
        if sys.path[0] == "": sys.path.pop(0)
        self.Nod3AppList = {}
        for toolb in NOD3_toolbar:
            if toolb == "User": 
               toolpath = os.getenv("HOME") + "/Nod3Apps"
            else: 
               toolpath = sys.path[0] + "/" + toolb
            sys.path.insert(2, toolpath)
            tasklist = []
            if osp.exists(toolpath):
               all_tasks = os.listdir(toolpath)
               all_tasks.sort()
               tasklist = []
               for task in all_tasks:
                   if task[-3:] == ".py":
                      taskname = task[:-3]
                      exec "import " + taskname
                      title = eval(taskname + ".title")
                      tip = eval(taskname + ".tip")
                      try: onein = eval(taskname + ".onein")
                      except AttributeError: onein = True
                      setattr(self, taskname, eval(taskname+".NOD3_App(self)"))
                      xtask = create_action(self, _(title),
                             tip = _(tip),
                             #checkable=True,
                             #enabled=True,
                             triggered = eval("self."+taskname+".compute_app"))
                      xtask.setStatusTip(tip)
                      #xtask.statusTip()
                      xtask.toolTip = tip
                      if onein == 2: self.actlist_2 += [xtask]
                      elif onein == -1: self.actlist_1 += [xtask]
                      elif onein: self.actlist_1more += [xtask]
                      else: self.actlist_2more += [xtask]
                      tasklist.append(xtask)
                      self.Nod3AppList[title.replace(" ", "")] = "self."+taskname+".compute_app"
            #self.actlist_1more += tasklist
            setattr(self, toolb + "_actions", tasklist)

    def hist_range_threshold(self, hist, bin_edges, percent):
        hist = np.concatenate((hist, [0]))
        threshold = .5*percent/100*hist.sum()
        i_bin_min = np.cumsum(hist).searchsorted(threshold)
        i_bin_max = -1-np.cumsum(np.flipud(hist)).searchsorted(threshold)
        return bin_edges[i_bin_min], bin_edges[i_bin_max]

    def lut_range_threshold(self, item, bins, percent):
        hist, bin_edges = self.color_get_histogram(item, bins)
        return self.hist_range_threshold(hist, bin_edges, percent)

    def color_get_histogram(self, item, nbins):
        """interface de IHistDataSource"""
        from guiqwt._scaler import _histogram
        if item.data is None:
            return [0,], [0,1]
        _min = np.nanmin(item.data)
        _max = np.nanmax(item.data)
        if item.data.dtype in (np.float64, np.float32):
           bins = np.unique(np.array(np.linspace(_min, _max, nbins+1),
                                      dtype=item.data.dtype))
        else:
           bins = np.arange(_min, _max+2, dtype=item.data.dtype)
        res2 = np.zeros((bins.size+1,), np.uint32)
        _histogram(item.data.flatten(), bins, res2)
        res = res2[1:-1], bins
        return res

    def make_item(self, row):
        image = self.objects[row]
        class DirParam(DataSet):
              cmap = StringItem("ColorMap:", default='gray')
        param = DirParam("cmap", "Setup of last choosen color map")
        if hasattr(self, 'cmap'):
           cmap = self.cmap
           param.cmap = cmap
        #elif hasattr(self, 'last_item'):
        #   cmap = self.last_item.get_color_map_name()
        #   param.cmap = cmap
        #   self.cmap = cmap
        else:
           param = self.read_defaults(param)
           if param != None: cmap = param.cmap
           self.cmap = cmap
        self.write_defaults(param)
        ##print 'cmap in make_item', cmap
        data = cp.copy(image.data.real)
        #item = make.image(image.data.real, title=image.title, colormap=cmap, \
        try:
           item = make.image(image.data.real, title="", colormap=cmap, \
                          interpolation='nearest',
                          xformat='%.3f', yformat='%.3f', zformat='%.3f',
                          alpha = self.Alpha, alpha_mask=self.AlphaMask,
                          eliminate_outliers=self.Outliers)
                          #eliminate_outliers=None)
        except:
           item = make.image(image.data.real, title="",
                          interpolation='nearest',
                          xformat='%.3f', yformat='%.3f', zformat='%.3f',
                          alpha = self.Alpha, alpha_mask=self.AlphaMask,
                          eliminate_outliers=self.Outliers)
        #print dir(item)
        if self.Take:
           lut_range = [self.Lower, self.Upper] 
        else:
           lut_range = self.lut_range_threshold(item, 256, self.Outliers)
        self.item = item
        # hide border_rect patch self.select
        self.item.select = self.select
        # new get_stats patch self.get_stats 
        self.item.get_stats = self.get_stats
        item.set_interpolation(self.InterpolationMode, self.IntSize)
        item.set_data(image.data.real, lut_range=lut_range)
        item.header = image.header
        self.items[row] = item
        self.last_item = item
        if item.header.has_key('CDELT1'):
           if item.header['CDELT1'] < 0:
              self.item.LABEL_ANCHOR = "BR"
           else:
              self.item.LABEL_ANCHOR = "BL"
        return item
        
    def get_closest_index_rect(self, x0, y0, x1, y1):
        px0, py0 = self.items[self.row].get_pixel_coordinates(x0, y0)
        px1, py1 = self.items[self.row].get_pixel_coordinates(x1, y1)
        i0 = min(nint(px0), nint(px1))
        i1 = max(nint(px0), nint(px1))
        j0 = min(nint(py0), nint(py1))
        j1 = max(nint(py0), nint(py1))
        return i0, j0, i1, j1

    def get_stats(self, xx0, yy0, xx1, yy1):
        """Return formatted string with stats on image rectangular area
        (output should be compatible with AnnotatedShape.get_infos)"""
        ix0, iy0, ix1, iy1 = self.get_closest_index_rect(xx0, yy0, xx1, yy1)
        #ix0, iy0, ix1, iy1 = self.items[self.row].get_closest_index_rect(xx0, yy0, xx1, yy1)
        data = np.array(self.items[self.row].data[iy0:iy1, ix0:ix1])
        x0 = min(xx0,xx1)
        x1 = max(xx0,xx1)
        y0 = min(yy0,yy1)
        y1 = max(yy0,yy1)
        rows, cols = data.shape
        mask = ~np.isnan(data)
        xfmt = self.item.imageparam.xformat
        yfmt = self.item.imageparam.yformat
        zfmt = self.item.imageparam.zformat
        if len(data[mask]) > 0:
           mean = data[mask].mean()
           std = data[mask].std()
           zmin = np.nanmin(data)
           zmax = np.nanmax(data)
        else: 
           mean = np.nan
           std = np.nan
           zmin = np.nan
           zmax = np.nan
        if self.AxesUseTime:
           if self.AxisUseHour:
              tx0 = TimeDelta(x0/15.0,'h')
              tx1 = TimeDelta(x1/15.0,'h')
           else:   
              tx0 = TimeDelta(x0,'d')
              tx1 = TimeDelta(x1,'d')
           ty0 = TimeDelta(y0,'d')
           ty1 = TimeDelta(y1,'d')
           return "<br>".join([
                            u"Box:%dx%d" % (cols, rows),
                            u"<b>σ(z) = " + zfmt % std + "</b>",
                            u"‹z› = " + zfmt % mean,
                            u"z_min = " + zfmt % zmin,
                            u"z_max = " + zfmt % zmax,
                            ])
        else:
           return "<br>".join([
                            u"Box:%dx%d" % (cols, rows),
                            u"σ(z) = " + zfmt % std,
                            u"‹z› = " + zfmt % mean,
                            u"z_min = " + zfmt % zmin,
                            u"z_max = " + zfmt % zmax,
                            ])

    def update_item(self, row):
        image = self.objects[row]
        item = self.items[row]
        #lut_range = [item.min, item.max]
        if not self.Separate:
           if self.Take:
              lut_range = [self.Lower, self.Upper] 
           else:
              #lut_range = [np.nanmin(item.data), np.nanmax(item.data)]
              lut_range = self.lut_range_threshold(item, 256, self.Outliers)
           item.set_data(image.data.real, lut_range=lut_range)
        item.set_interpolation(self.InterpolationMode, self.IntSize)
        item.imageparam.label = "" #image.title
        if hasattr(self, 'xformat'):
           item.imageparam.xformat = self.xformat
           item.imageparam.yformat = self.yformat
           item.imageparam.zformat = self.zformat
        try:
           item.plot().update_colormap_axis(item)
        except: pass
        ##print self.cmap, 'update', row, self.items[row].imageparam.colormap
        
    #------Image operations
    def Rotate(self):
        boundaries = ('constant', 'nearest', 'reflect', 'wrap')
        prop = ValueProp(False)
        class RotateParam(DataSet):
            angle = FloatItem(u"%s (°)" % _(u"Angle"))
            mode = ChoiceItem(_(u"Mode"), zip(boundaries, boundaries),
                              default=boundaries[0])
            #cval = FloatItem(_("cval"), default=-1.0,
            #                 help=_(u"Value used for points outside the "
            #                        u"boundaries of the input if mode is "
            #                        u"'constant'"))
            reshape = BoolItem(_(u"Reshape the output array"), default=True,
                               help=_(u"Reshape the output array "
                                      u"so that the input array is "
                                      u"contained completely in the output"))
            prefilter = BoolItem(_(u"Prefilter the input image"),
                                 default=True).set_prop("display", store=prop)
            order = IntItem(_(u"Order"), default=3, min=0, max=5,
                            help=_("Spline interpolation order")
                            ).set_prop("display", active=prop)
        param = RotateParam(_("Rotation"))
        def function(m, p):
            if not m.header.has_key('CRPIX1'):
               m.data = map_rotate(m.data, p)
               m = self.removeNANedges(m)
               return m,p
            rows1, cols1 = m.data.shape
            m.data = map_rotate(m.data, p)
            m = self.removeNANedges(m)
            if p.reshape:
               RAD = np.pi/180
               rows, cols = m.data.shape
               xpix1 = m.header['CRPIX1'] - cols1/2
               ypix1 = m.header['CRPIX2'] - rows1/2
               sina = np.sin(RAD*p.angle)
               cosa = np.cos(RAD*p.angle)
               xpix, ypix = np.dot([xpix1, ypix1], [[cosa, -sina], [sina, cosa]])
               m.header['CRPIX1'] = cols/2 + xpix
               m.header['CRPIX2'] = rows/2 + ypix
            return m, p

        #import scipy.ndimage as spi
        from nodmath import map_rotate
        self.compute_11("Rotate", lambda m, p: function(m, p), param)
    
    def Rotate90(self):
        def function(m, p):
            m.data = np.rot90(m.data)
            helem = ['NAXIS', 'CTYPE', 'CRVAL', 'CRPIX', 'CDELT', 'CROTA']
            for h in helem:
                if m.header.has_key(h+'1') and m.header.has_key(h+'2'):
                #if h+'1' in m.header and h+'2' in m.header:
                   n1 = m.header[h+'1']
                   n2 = m.header[h+'2']
                   m.header[h+'1'] = n2
                   m.header[h+'2'] = n1
            return m, p
        self.compute_11("Rotate90", lambda m, p: function(m, p))
        
    def Rotate270(self):
        def function(m, p):
            m.data = np.rot90(m.data, 3)
            helem = ['NAXIS', 'CTYPE', 'CRVAL', 'CRPIX', 'CDELT', 'CROTA']
            for h in helem:
                if m.header.has_key(h+'1') and m.header.has_key(h+'2'):
                #if h+'1' in m.header and h+'2' in m.header:
                   n1 = m.header[h+'1']
                   n2 = m.header[h+'2']
                   m.header[h+'1'] = n2
                   m.header[h+'2'] = n1
            #m.header['CDELT1'] *= -1
            #m.header['CDELT2'] *= -1
            return m, p
        self.compute_11("Rotate270", lambda m, p: function(m, p))
        
    def HFlip(self):
        def function(m, p):
            m.data = np.fliplr(m.data)
            #m.header['CDELT1'] *= -1
            return m, p
        self.compute_11("HFlip", lambda m, p: function(m, p))
        
    def VFlip(self):
        def function(m, p):
            m.data = np.flipud(m.data)
            #m.header['CDELT2'] *= -1
            return m, p
        self.compute_11("VFlip", lambda m, p: function(m, p))
        
    def Resize(self):
        rows = self._get_selected_rows()
        obj = self.objects[rows[0]]
        original_size = obj.data.shape[1], obj.data.shape[0]
        from guiqwt.resizedialog import ResizeDialog
        dlg = ResizeDialog(self.plot, new_size=original_size,
                           old_size=original_size,
                           text=_("Destination size:"))
        if not dlg.exec_():
            return
        boundaries = ('constant', 'nearest', 'reflect', 'wrap')
        prop = ValueProp(False)
        class ResizeParam(DataSet):
            #zoom = FloatItem(_(u"Zoom"), default=dlg.get_zoom())
            mode = ChoiceItem(_(u"Mode"), zip(boundaries, boundaries),
                              default=boundaries[0])
            cval = FloatItem(_("cval"), default=-1.0,
                             help=_(u"Value used for points outside the "
                                    u"boundaries of the input if mode is "
                                    u"'constant'"))
            prefilter = BoolItem(_(u"Prefilter the input image"),
                                 default=True).set_prop("display", store=prop)
            order = IntItem(_(u"Order"), default=4, min=0, max=5,
                            help=_("Spline interpolation order")
                            ).set_prop("display", active=prop)
        param = ResizeParam(_("Resize"))
        import scipy.ndimage as spi
        def function(m, p):
            if not hasattr(p, 'zoom'):
               p.zoom = dlg.get_zoom()
            if p.cval < 0.0: p.cval = np.nan
            m.data = spi.interpolation.zoom(m.data, p.zoom, order=p.order,
                                               mode=p.mode, cval=p.cval,
                                               prefilter=p.prefilter)
            m.header['NAXIS2'], m.header['NAXIS1'] = m.data.shape
            m.header['CRPIX1'] *= p.zoom
            m.header['CRPIX2'] *= p.zoom
            m.header['CDELT1'] /= p.zoom
            m.header['CDELT2'] /= p.zoom

            return m, p
        self.compute_11("Resize", lambda m, p: function(m, p),
                        param, suffix=lambda p: u"zoom=%.3f" % p.zoom)
                        
    def ROI(self):
        class ROIParam(DataSet):
            row1 = IntItem(_("First row index"), default=0, min=-1)
            row2 = IntItem(_("Last row index"), default=-1, min=-1)
            col1 = IntItem(_("First column index"), default=0, min=-1)
            col2 = IntItem(_("Last column index"), default=-1, min=-1)
        param = ROIParam(_("ROI extraction"))
        def function(m, p):
            m.data = m.data.copy()[p.row1:p.row2, p.col1:p.col2]
            return m, p
        self.compute_11("ROI", lambda m, p: function(m, p),
                        param, suffix=lambda p: u"rows=%d:%d,cols=%d:%d" 
                        % (p.row1, p.row2, p.col1, p.col2))
    
    def SwapAxes(self):
        def function(m, p):
            m.data = m.data.T
            helem = ['NAXIS', 'CTYPE', 'CRVAL', 'CRPIX', 'CDELT', 'CROTA']
            for h in helem:
                if m.header.has_key(h+'1') and m.header.has_key(h+'2'):
                   n1 = m.header[h+'1']
                   n2 = m.header[h+'2']
                   m.header[h+'1'] = n2
                   m.header[h+'2'] = n1
            m.header['CDELT2'] *= -1
            return m, p
        self.compute_11("SwapAxes", lambda m, p: function(m, p))
        
        
    def set_metadata(self, header):
        metadata = {}
        # patch for old nod2-fits structure
        for key in ('IDENT1', 'IDENT2', 'IDENT3', 'IDENT4'):
            if header.has_key(key): header[key] = "old nod2 header replacement"
            #if key in header: header[key] = "old nod2 header replacement"
        if header.has_key("OBS LAT"): header.rename_key("OBS LAT", "OBSLAT")
        #if "OBS LAT" in header: header.rename_key("OBS LAT", "OBSLAT")
        if header != None:
           try:
              for key in header.keys():
                  if key != "HISTORY" and key != "COMMENT" and key != "":
                     try:
                        value = header[key]
                        metadata[key] = value
                     except:
                        pass
           except:
              for item in header.items():
                  if len(item) == 2:
                     key = item[0]
                     if key != "HISTORY" and key != "COMMENT" and key != "":
                        value = item[1]
                        metadata[key] = value 
          
           history = {}
           n = 0
           for h in header.get_history():
               h = str(h)
               if h.find("NOD3:") >=0 or h.find("NOD3>") >=0:
                  #history.append(h.split("NOD3:")[1]) 
                  n += 1
                  if h.find(":") > 0:
                     history[str("%4.4d" % n)]  = h.split("NOD3:")[1]
                  elif h.find(">") > 0:
                     history[str("%4.4d" % n)]  = h.split("NOD3:")[1]
        return metadata, history

    def save_script(self, hlines):
        """Save script file"""
        from nod3scripting import exec_script_save_dialog
        class DirParam(DataSet):
              MyNOD3SCR = StringItem("MyNOD3SCR:", default=NOD3DIR)
        param = DirParam("MyNOD3SCR", "Setup the NOD3 Script directory name")
        param = self.read_defaults(param)
        if param != None: MyNOD3SCR = param.MyNOD3SCR
        scriptname = exec_script_save_dialog(self, hlines, outdir=MyNOD3SCR, app_name=APP_NAME)
        if scriptname:
           os.chdir(osp.dirname(scriptname))
           param.MyNOD3SCR = osp.dirname(scriptname)
        self.write_defaults(param)

    def check_app_input(self, app):
        for each in self.actlist_2more:
            if each.text() == app:
               return self._get_selected_rows()
               #return  3
        for each in self.actlist_2:
            if each.text() == app:
               return 2
        return 1

    def open_script(self):
        """Open script file"""
        from nod3scripting import exec_script_open_dialog
        class DirParam(DataSet):
              NOD3SCR = StringItem("NOD3SCR:", default=NOD3DIR)
        param = DirParam("NOD3SCR", "Setup the NOD3 Script directory name")
        param = self.read_defaults(param)
        if param != None: NOD3SCR = param.NOD3SCR
        self.selrows = self.listwidget.selectionModel().selectedRows()
        rows = self._get_selected_rows()
        if rows == []: return
        for scriptname in exec_script_open_dialog(self, basedir=NOD3SCR, app_name=APP_NAME):
            param.NOD3SCR = osp.dirname(scriptname)
            fin = open(scriptname, "r")
            apps = fin.readlines()
            fin.close()
            first = True
            for app in apps:
                if app.strip() != "" and app.strip()[0] != "#":
                   app = app.replace("\n", "")
                   try: 
                      appname, apparam =  app.split("(")
                      apparam = "(" + apparam
                   except ValueError: 
                      appname =  app
                      apparam = "()"
                   nselect = self.check_app_input(appname)
                   #if first:
                   #   if nselect < len(rows):
                   #      msg = str("too many rows selected\nonly %d row(s) allowed" % nselect)
                   #      QMessageBox.critical(self.parent(), APP_NAME,
                   #                 _(u"Error:")+"\n%s" % msg)
                   #      break
                   first = False
                   if self.Nod3AppList.has_key(appname):
                      apptask = self.Nod3AppList[appname]
                      apparam = apparam[:apparam.find(")")+1]
                      try: 
                         eval(apptask+apparam) 
                         #self.display = False
                      except Exception, msg:
                         import traceback
                         traceback.print_exc()
                         QMessageBox.critical(self.parent(), APP_NAME,
                                    _(u"Error:")+"\n%s" % msg)
                         break
                   elif hasattr(self, appname):
                      apparam = apparam[:apparam.find(")")+1]
                      eval("self."+appname+apparam)
                   else:
                      msg = str("no such application:   %s" % app)
                      QMessageBox.critical(self.parent(), APP_NAME,
                                    _(u"Error:")+"\n%s" % str(msg))
                      break
                #self.refresh_list(new_current_row='last')
        self.write_defaults(param)

    def open_image(self, infile=None):
        """Open image file"""
        from nod3fits import exec_fits_open_dialog
        class DirParam(DataSet):
              NOD3DIR = StringItem("NOD3DIR:", default=NOD3DIR)
        param = DirParam("NOD3DIR", "Setup the NOD3FITS directory name")
        param = self.read_defaults(param)
        if param != None: NOD3DIR = param.NOD3DIR
        for filename, metadata, data, s, p in exec_fits_open_dialog(self, basedir=NOD3DIR,
                                        app_name=APP_NAME, mapnum=0, infile=infile ):
            if data == None or metadata == None:
               msg = "Data not in NOD3 FITS format"
               QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
               return
            param.NOD3DIR = osp.dirname(filename)
            try: os.chdir(osp.dirname(filename))
            except: pass
            fname = os.path.split(filename)[-1]
            if metadata != None:
               if metadata.has_key('EXTNAME'): extname = metadata['EXTNAME']
               #if 'EXTNAME' in metadata: extname = metadata['EXTNAME']
               else: extname = "MAP-I"
               extname = extname.replace("MAP-", "")
               if metadata.has_key('RXHORN'): horn = metadata['RXHORN']
               #if 'RXHORN' in metadata: horn = metadata['RXHORN']
               else: horn = 0
            image = ImageParam()
            #image.title = filename
            #image.title = str("%s(%s,h=%i)" % (fname, extname, horn))
            image.title = str("%s(%s)" % (fname, extname))
            image.data = data
            image.header = metadata
            # setup sidereal time and parallactic angle
            if s != None:
               image.sidmap = s
            if p != None:
               image.parmap = p
            # setup metadata dictionary from header
            image.metadata, image.history = self.set_metadata(metadata)
            if data != None:
               self.add_object(image)
            else:
               msg = "Data not in NOD3 FITS format"
               QMessageBox.critical(self.parent(), APP_NAME,
                                 _(u"Error:")+"\n%s" % str(msg))
        self.write_defaults(param)

    #def save_image(self):
    def save_image(self, dim=2):
        """Save selected image"""
        from nod3fits import exec_fits_save_dialog
        class DirParam(DataSet):
              NOD3OUT = StringItem("NOD3OUT:", default=NOD3DIR)
        param = DirParam("NOD3OUT", "Setup the NOD3FITS directory name")
        param = self.read_defaults(param)
        if param != None: NOD3OUT = param.NOD3OUT
        rows = self._get_selected_rows()
        self.VERSION = VERSION
        from guiqwt.qthelpers import exec_image_save_dialog
        if not dim: dim = 2
        filename = exec_fits_save_dialog(self, rows, outdir=NOD3OUT,
                                               #app_name=APP_NAME)
                                               app_name=APP_NAME, dim=dim)
        if filename:
           os.chdir(osp.dirname(filename))
           param.NOD3OUT = osp.dirname(filename)
        self.write_defaults(param)
        
    def old_save_image(self):
        """Save selected image"""
        from nod3fits import exec_fits_save_dialog
        class DirParam(DataSet):
              NOD3OUT = StringItem("NOD3OUT:", default=NOD3DIR)
        param = DirParam("NOD3OUT", "Setup the NOD3FITS directory name")
        param = self.read_defaults(param)
        if param != None: NOD3OUT = param.NOD3OUT
        rows = self._get_selected_rows()
        for row in rows:
            obj = self.objects[row]
            # update new fits metadata from properties menu
            update_fits_metadata(obj)
            obj.header.update('NOD3VERS', VERSION, 'NOD3 software version')
            from guiqwt.qthelpers import exec_image_save_dialog
            filename = exec_fits_save_dialog(obj.data, obj.header, self, outdir=NOD3OUT,
                                              app_name=APP_NAME, dim=dim)
            if filename:
                os.chdir(osp.dirname(filename))
                param.NOD3OUT = osp.dirname(filename)
        self.write_defaults(param)

    def nan_check(self, data, val, weight=False):
        Data = data.copy()
        mask = np.isfinite(Data)
        Data[-mask] = val
        if weight:
           return Data, np.array(mask, dtype=float)
        else:
           return Data
        

class DockablePlotWidget(DockableWidget):

    LOCATION = Qt.RightDockWidgetArea
    def __init__(self, parent, plotwidgetclass, toolbar):
        super(DockablePlotWidget, self).__init__(parent)
        self.toolbar = toolbar
        layout = QVBoxLayout()
        self.plotwidget = plotwidgetclass()
        layout.addWidget(self.plotwidget)
        self.setLayout(layout)
        self.setup()
        
    def get_plot(self):
        return self.plotwidget.plot
        
    def setup(self):
        title = unicode(self.toolbar.windowTitle())
        self.plotwidget.add_toolbar(self.toolbar, title)
        if isinstance(self.plotwidget, ImageWidget):
            self.plotwidget.register_all_image_tools()
        else:
            self.plotwidget.register_all_curve_tools()
        
    #------DockableWidget API
    def visibility_changed(self, enable):
        """DockWidget visibility has changed"""
        DockableWidget.visibility_changed(self, enable)
        self.toolbar.setVisible(enable)
            

class DockableTabWidget(QTabWidget, DockableWidgetMixin):
    LOCATION = Qt.LeftDockWidgetArea
    def __init__(self, parent):
        QTabWidget.__init__(self, parent)
        DockableWidgetMixin.__init__(self, parent)


try:
    from spyderlib.widgets.internalshell import InternalShell
    class DockableConsole(InternalShell, DockableWidgetMixin):
        LOCATION = Qt.BottomDockWidgetArea
        def __init__(self, parent, namespace, message, commands=[]):
            InternalShell.__init__(self, parent=parent, namespace=namespace,
                                   message=message, commands=commands,
                                   multithreaded=True)
            DockableWidgetMixin.__init__(self, parent)
            self.setup()
            
        def setup(self):
            font = QFont("Courier new")
            font.setPointSize(10)
            self.set_font(font)
            self.set_codecompletion_auto(True)
            self.set_calltips(True)
            self.setup_calltips(size=600, font=font)
            self.setup_completion(size=(300, 180), font=font)
except ImportError:
    DockableConsole = None


class NOD3Proxy(object):
    def __init__(self, win):
        self.win = win
        self.obj = self.win.mainwidget.imageft.objects
        

class CentralWidget(QSplitter):
    def __init__(self, parent, toolbar, status):
        QSplitter.__init__(self, parent)
        self.setContentsMargins(10, 10, 10, 10)
        #self.setStyleSheet("background-color: rgb(155,155,155); border:0px solid rgb(0, 0, 0)")
        self.setOrientation(Qt.Horizontal)

        #self.imagewidget = ImageWidget(self, colormap=None, otherOptionsAvailable)
        self.imagewidget = ImageWidget(self)
        self.imagewidget.autoscale_mode = False
        self.imageft = ImageFT(self, self.imagewidget.get_plot())
        self.imageft.setup(toolbar)
        self.connect(self.imageft, SIG_LUT_CHANGED, self.lut_range_changed)
        self.item = None # image item

        # add statusBar to show progress in NOD3 tools
        self.imagewidget.Progress = status

        self.imagewidget.add_toolbar(toolbar, "default")

        self.register_tools(toolbar)
        #self.imagewidget.register_all_image_tools()

        self.addWidget(self.imagewidget)

        self.images = [] # List of ImageParam instances
        self.lut_ranges = [] # List of LUT ranges

        self.setStretchFactor(0, 0)

    def nod3_colormaps(self):
        try: 
            import nod3luts
        except:
            return
        cmlist = []
        for name in dir(nod3luts):
            if name.endswith("_data"):
                obj = getattr(nod3luts, name)
                if isinstance(obj, dict):
                    cmlist.append(name[1:-5])
        for cmap_name in cmlist:
            cmap = QwtLinearColorMap()
            cmdata = getattr(nod3luts, "_"+cmap_name+"_data")
            cm._setup_colormap(cmap, cmdata)
            cm.register_extra_colormap(cmap_name, cmap) 
        self.cmlist = cmlist

    def create_shape(self):
        return NOD3ImageStatsRectangle(0, 0, 1, 1), 0, 2

    def printer_command(self, plot, checked):
        """Activate tool"""
        class PrintFilter(QwtPlotPrintFilter):
              def __init__(self):
                  QwtPlotPrintFilter.__init__(self)
              def color(self, c, item):
                  if not (self.options() & QwtPlotPrintFilter.CanvasBackground):
                      if item == QwtPlotPrintFilter.MajorGrid:
                          return Qt.darkGray
                      elif item == QwtPlotPrintFilter.MinorGrid:
                          return Qt.gray
                  if item == QwtPlotPrintFilter.Title:
                      return Qt.black
                  elif item == QwtPlotPrintFilter.AxisScale:
                      return Qt.black
                  elif item == QwtPlotPrintFilter.AxisTitle:
                      return Qt.black
                  return c
              def font(self, f, _):
                  result = QFont(f)
                  result.setPointSize(int(f.pointSize()*1.25))
                  return result
        printer = QPrinter(QPrinter.ScreenResolution)
        m1, m2, m3, m4 = printer.getPageMargins(printer.Millimeter)
        printer.setPageMargins(m1, 50.0+m2, m3, 50.0+m4, printer.Millimeter)
        printer.setFullPage(False)
        printer.setDoubleSidedPrinting(False)
        printer.setCreator('NOD3')
        printer.setOrientation(printer.Portrait)
        printer.setColorMode(printer.Color)
        #try: plot.setCanvasBackground = Qt.black
        #except: pass
        dialog = QPrintDialog(printer, plot)
        saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
        sys.stdout = None
        diag = dialog.exec_()
        sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
        if diag:
            filter = PrintFilter()
            if (QPrinter.GrayScale == printer.colorMode()):
               filter.setOptions(QwtPlotPrintFilter.PrintAll
                                  & ~QwtPlotPrintFilter.PrintBackground
                                  | QwtPlotPrintFilter.PrintFrameWithScales)
            self.patch_pdf(plot, printer, filter)
            #plot.print_(printer, filter)

    def patch_pdf(self, plot, printer, filter, off=0.045):
        from nodmath import extract
        if plot.get_active_item() == None:
           return
        data = plot.get_active_item().data
        rows, cols = data.shape
        coff = cols*0.10
        roff = rows*0.045
        shape = (nint(rows + roff), nint(cols + coff))
        pos = (nint(float(rows + roff)/2.0), nint(float(cols - coff)/2.0))
        plot.get_active_item().data = extract(data, shape=shape, position=pos)
        plot.print_(printer, filter)
        plot.get_active_item().data = data
        
    def save_widget(self, fname):
        """Grab widget's window and save it to filename (*.png, *.pdf)"""
        fname = unicode(fname)
        if fname.lower().endswith('.ps'):
            printer = QPrinter()
            printer.setOutputFormat(QPrinter.PostScriptFormat)
            printer.setOrientation(QPrinter.Portrait)
            #printer.setOrientation(QPrinter.Landscape)
            printer.setPageMargins(2.5, 50.0, 10.0, 50.0, QPrinter.Millimeter)
            printer.setOutputFileName(fname)
            printer.setCreator('NOD3')
            self.Plot.print_(printer)
        elif fname.lower().endswith('.pdf'):
            printer = QPrinter()
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOrientation(QPrinter.Portrait)
            #printer.setOrientation(QPrinter.Landscape)
            printer.setPageMargins(2.5, 50.0, 10.0, 50.0, QPrinter.Millimeter)
            printer.setOutputFileName(fname)
            printer.setCreator('NOD3')
            self.Plot.print_(printer)
        elif fname.lower().endswith('.png'):
            pixmap = QPixmap.grabWidget(self.Plot)
            pixmap.save(fname, 'PNG')
        elif fname.lower().endswith('.jpg'):
            pixmap = QPixmap.grabWidget(self.Plot)
            pixmap.save(fname, 'JPG')
        elif fname.lower().endswith('.bmp'):
            pixmap = QPixmap.grabWidget(self.Plot)
            pixmap.save(fname, 'BMP')
        else:
            raise RuntimeError(_("Unknown file extensions"))

    def save_as_command(self, plot, checked):
        """Activate tool"""
        #FIXME: Qt's PDF printer is unable to print plots including images
        # --> until this bug is fixed internally, disabling PDF output format
        #     when plot has image items.
        self.Plot = plot
        #print dir(QPrinter)
        formats = '\n%s (*.bmp)' % _('BMP images')
        formats += '\n%s (*.jpg)' % _('JPG images')
        formats += '%s (*.png)' % _('PNG image')
        #formats += '\n%s (*.ps)' % _('PS document')
        #formats += '\n%s (*.pdf)' % _('PDF document')
        #formats = '%s (*.png *.jpg)\n%s (*.pdf)' % (_('Images'), _('PDF document'))
        formats =  _add_all_supported_files(formats)
        from guiqwt.interfaces import IImageItemType
        for item in plot.get_items():
            if IImageItemType in item.types():
               break
        else:
            formats += '\n%s (*.pdf)' % _('PDF document')
        fname, _f = getsavefilename(plot,  _("Save as pixelmap"), _('pixelmap.png'), formats)
        if fname:
           #plot.get_active_item().unselect()
           #plot.replot()
           background = str(plot.canvasBackground().name())
           self.setStyleSheet("background-color: rgb(255,255,255); border:0px solid rgb(0, 0, 0)")
           plot.setCanvasBackground(QColor(background))
           self.save_widget(fname)
           self.setStyleSheet("")

    def register_tools(self, toolbar):

        self.imagewidget.add_separator_tool()
        self.imagewidget.register_standard_tools()
        #self.imagewidget.add_separator_tool()
        #self.register_nod3_tools(self.imagewidget)
        # NOD3 defs
        self.nod3_colormaps()
        self.imagewidget.add_tool(ColormapTool)
        self.imagewidget.add_tool(ContrastTool)
        #self.imagewidget.add_tool(ContrastPanelTool)
        self.imagewidget.add_tool(ItemListPanelTool)
        self.imagewidget.add_tool(ReverseYAxisTool)
        self.imagewidget.add_tool(AspectRatioTool)
        if self.imagewidget.get_xcs_panel() and self.imagewidget.get_ycs_panel():
           self.imagewidget.add_tool(XCSPanelTool)
           self.imagewidget.add_tool(YCSPanelTool)
           self.imagewidget.add_tool(CrossSectionTool)
        ImageStatsTool.create_shape = self.create_shape
        self.imagewidget.add_tool(ImageStatsTool)
        self.imagewidget.add_separator_tool()
        #
        SaveAsTool.activate_command = self.save_as_command
        self.imagewidget.add_tool(SaveAsTool)
        PrintTool.activate_command = self.printer_command
        self.imagewidget.add_tool(PrintTool)
        self.imagewidget.add_tool(HelpTool)
        #self.imagewidget.add_tool(SnapshotTool)
        #self.imagewidget.register_other_tools()
        self.imagewidget.add_separator_tool()
        self.imagewidget.get_default_tool().activate()
        #
        # more NOD3 tools
        self.imagewidget.add_tool(TimeAxisTool)
        self.default_cmaps = cm.get_colormap_list()
        item_list = create_action(self, _("Item list..."),
                                    icon=get_icon('item_list.png'),
                                    tip=_("Item list manager"),
                                    triggered=self.item_list)
        clear_toggle = create_action(self, _("Clear overlays..."),
                                    icon=get_icon('delete.png'),
                                    tip=_("Clears display from all overlays and applications"),
                                    triggered=self.imageft.clears_display)
        grid_toggle = create_action(self, _("Grid toggle..."),
                                    icon=get_icon('grid.png'),
                                    tip=_("Toggles grid on and off"),
                                    triggered=self.grid_toggle)
        #add_actions(toolbar, [item_list, grid_toggle])
        add_actions(toolbar, [item_list, clear_toggle])

    def item_list(self):
        if self.imagewidget.get_itemlist_panel().isVisible():
           self.imagewidget.get_itemlist_panel().hide()
        else:
           self.imagewidget.get_itemlist_panel().show()
        self.imagewidget.get_itemlist_panel().update()

    def grid_toggle(self):
        self.imagewidget.plot.grid.set_selectable(True)
        if self.imagewidget.plot.grid.isVisible():
           self.imagewidget.plot.grid.hide()
        else:
           self.imagewidget.plot.grid.show()
        self.imagewidget.plot.replot()
        #print self.imagewidget.get_itemlist_panel().isEnabled()

    def lut_range_changed(self):
        row = self.imagewidget.currentRow()
        self.lut_ranges[row] = self.item.get_lut_range()


class MainWindow(QMainWindow):

    def __init__(self, options):

        QMainWindow.__init__(self)

        if sys.path[0] == "": sys.path.pop(0)
        self.setWindowIcon(get_icon(sys.path[0]+'/MPIfR.svg'))
        self.setWindowTitle(APP_NAME)
                
        # Welcome message in statusbar:
        status = self.statusBar()
        status.showMessage(_("Welcome to %s!") % APP_NAME, 10000)

        toolbar = self.addToolBar(_("Data Processing Toolbar"))
        self.mainwidget = CentralWidget(self, toolbar, status)
        self.setCentralWidget(self.mainwidget)
        self.connect(self.mainwidget, SIGNAL("status_message(QString)"),
                     status.showMessage)

        # set InterpolationMode 
        if options.linear:
           self.mainwidget.imageft.InterpolationMode = INTERP_LINEAR
        else:
           self.mainwidget.imageft.InterpolationMode = INTERP_NEAREST

        # File menu
        self.quit_action = create_action(self, _("Quit"), shortcut="Ctrl+Q",
                                    icon=get_std_icon("DialogCloseButton"),
                                    tip=_("Quit application"),
                                    #triggered=self.close)
                                    triggered=self.Quit)
        self.file_menu = self.menuBar().addMenu(_("File"))
        self.connect(self.file_menu, SIGNAL("aboutToShow()"),
                     self.update_file_menu)
        
        # Edit menu
        self.edit_menu = self.menuBar().addMenu(_("&Edit"))
        self.connect(self.edit_menu, SIGNAL("aboutToShow()"),
                     self.update_edit_menu)
        
        # Operation menu
        self.operation_menu = self.menuBar().addMenu(_("Operations"))
        self.connect(self.operation_menu, SIGNAL("aboutToShow()"),
                     self.update_operation_menu)

        # NOD3 menu
        self.nod3_actions = []
        for tool in NOD3_toolbar:
            setattr(self, tool+"_menu", self.menuBar().addMenu(_(tool)))
            self.connect(eval("self."+tool+"_menu"), SIGNAL("aboutToShow()"),
                         lambda t=tool: self.update_nod3_menu(t))
            self.nod3_actions.append(tool)

        # View menu
        self.view_menu = view_menu = self.createPopupMenu()
        view_menu.setTitle(_(u"&View"))
        self.menuBar().addMenu(view_menu)
        self.connect(self.view_menu, SIGNAL("aboutToShow()"),
                     self.update_view_menu)
        
        # Help menu
        help_menu = self.menuBar().addMenu("?")
        about_action = create_action(self, _("About..."),
                                     icon=get_std_icon('MessageBoxInformation'),
                                     triggered=self.about)
        add_actions(help_menu, (about_action,))
        
        # Eventually add an internal console (requires 'spyderlib')
        self.nod3_proxy = NOD3Proxy(self)
        if DockableConsole is None:
           self.console = None
        if options.console:
           import time, scipy.signal as sps, scipy.ndimage as spi
           import pyfits as pf
           ns = {'nod3': self.nod3_proxy,
                 'np': np, 'sps': sps, 'spi': spi,
                 'os': os, 'sys': sys, 'osp': osp, 'time': time}
           msg = "NOD3 single dish radio contiuum data reduction tools\n\n"\
                 "Modules imported at startup: "\
                 "os, sys, os.path as osp, time, "\
                 "numpy as np, scipy.signal as sps, scipy.ndimage as spi"\
                 "pyfits as pf"
           self.console = DockableConsole(self, namespace=ns, message=msg)
           self.console.setMinimumHeight(200)
           self.add_dockwidget(self.console, _(u"Console"))
        else:
           self.console = None
        
        # Show main window image plot panel
        self.show()
                
        # Input file defined
        if options.filename:
           self.filename =  "./" + options.filename
           self.mainwidget.imageft.open_image(infile=self.filename)
        else:
           self.filename = None

    #------GUI refresh/setup

    def Ask(self, msg):
        ask = QMessageBox.question(self.parent(), 'NOD3', msg,
                             QMessageBox.Yes, QMessageBox.No)
        if ask == QMessageBox.Yes: return True
        else: return False

    def Quit(self):
        if self.Ask("Really want to quit without saveing images?"):
           self.close()

    def add_dockwidget(self, child, title):
        """Add QDockWidget and toggleViewAction"""
        dockwidget, location = child.create_dockwidget(title)
        self.addDockWidget(location, dockwidget)
        return dockwidget
        
    def update_file_menu(self):        
        self.file_menu.clear()
        objectft = self.mainwidget.imageft
        actions = objectft.file_actions+[None, self.quit_action]
        add_actions(self.file_menu, actions)

    def update_edit_menu(self):        
        self.edit_menu.clear()
        objectft = self.mainwidget.imageft
        add_actions(self.edit_menu, objectft.edit_actions)
        
    def update_operation_menu(self):
        self.operation_menu.clear()
        objectft = self.mainwidget.imageft
        add_actions(self.operation_menu, objectft.operation_actions)

    def update_view_menu(self):
        self.view_menu.clear()
        objectft = self.mainwidget.imageft
        add_actions(self.view_menu, objectft.view_actions)
        
    # update NOD3 GUI menu
    def update_nod3_menu(self, tool):
        eval("self."+tool+"_menu.clear()")
        objectft = self.mainwidget.imageft
        add_actions(eval("self."+tool+"_menu"), eval("objectft."+tool+"_actions"))


    #------?
    def about(self):
        from guiqwt import __version__ as qwtvers
        from guidata import __version__ as datvers
        from pyfits import __version__ as fitsvers
        QMessageBox.about( self, _("About ")+APP_NAME,
              """<b>%s</b> v%s<br>%s<p>%s Peter M&uuml;ller
              <br>Copyright &copy; 2012 MPIfR Bonn, Germany
              <br>contact: peter@mpifr.de
              <br>
              <br>Based on guiqwt and guidata by Pierre Raybault
              <br>Copyright &copy; 2010 CEA
              <p>Python %s, Qt %s, PyQt %s %s %s
              <br>GUIqwt %s,  GUIdata %s,  PyFits %s """ % \
              (APP_NAME, VERSION, APP_DESC, _("Developed and maintained by"),
               platform.python_version(),
               QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system(), 
               qwtvers, datvers, fitsvers) )
               
    def closeEvent(self, event):
        rows = self.mainwidget.imageft._get_selected_rows()
        if rows != []:
           item = self.mainwidget.imageft.items[rows[-1]]
           class DirParam(DataSet):
              cmap = StringItem("ColorMap:", default='gray')
           param = DirParam("cmap", "Setup of last choosen color map")
           cmap = item.get_color_map_name()
           if cmap in self.mainwidget.default_cmaps:
              param.cmap = cmap
              self.mainwidget.imageft.write_defaults(param)
        if self.console is not None:
            self.console.exit_interpreter()
        if hasattr(self.mainwidget.imageft, 'LView'): 
           if self.mainwidget.imageft.LView.isVisible():
              self.mainwidget.imageft.LView.close()
        if hasattr(self.mainwidget.imageft, 'fig'): 
           if self.mainwidget.imageft.fig.win.isVisible():
              self.mainwidget.imageft.fig.win.close()
        event.accept()


def get_options():
    """
    Convert options into commands
    return commands, message
    """
    import optparse
    parser = optparse.OptionParser(usage="nod3.py [options]")
    parser.add_option('-l', '--linear', dest="linear", action='store_true',
                      default=False,
                      help="Linear interpolation of display data")
    parser.add_option('--session', dest="startup_session", default='',
                      help="Startup session")
    parser.add_option('--defaults', dest="reset_to_defaults",
                      action='store_true', default=False,
                      help="Reset to configuration settings to defaults")
    parser.add_option('--reset', dest="reset_session",
                      action='store_true', default=False,
                      help="Remove all configuration files!")
    parser.add_option('--optimize', dest="optimize",
                      action='store_true', default=False,
                      help="Optimize Spyder bytecode (this may require "
                           "administrative privileges)")
    parser.add_option('-w', '--workdir', dest="working_directory", default=None,
                      help="Default working directory")
    parser.add_option('-d', '--debug', dest="debug", action='store_true',
                      default=False,
                      help="Debug mode (stds are not redirected)")
    parser.add_option('--showconsole', dest="show_console",
                      action='store_true', default=False,
                      help="Show parent console (Windows only)")
    parser.add_option('--multithread', dest="multithreaded",
                      action='store_true', default=False,
                      help="Internal console is executed in another thread "
                           "(separate from main application thread)")
    parser.add_option('--profile', dest="profile", action='store_true',
                      default=False,
                      help="Profile mode (internal test, "
                           "not related with Python profiling)")
    parser.add_option('-c', '--console', dest="console", action='store_true',
                      default=False,
                      help="Displays python console in an extra window")
    parser.add_option('-f', '--file', dest="filename", default=False,
                      help="Default input file name")
    options, _args = parser.parse_args()
    return options


def main():

    from guidata import qapplication
    # **** Collect command line options ****
    # Note regarding Options:
    # It's important to collect options before monkey patching sys.exit,
    # otherwise, optparse won't be able to exit if --help option is passed
    options = get_options()

    app = qapplication()
    window = MainWindow(options)
    if options.console: window.setGeometry(0,0,1200,940)
    else: window.setGeometry(0,0,1200,760)
    window.show()
    app.exec_()


if __name__ == '__main__':
    main()