GModelSky.cpp 71.8 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
/***************************************************************************
 *                    GModelSky.cpp - Sky model class                      *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2011-2020 by Juergen Knoedlseder                         *
 * ----------------------------------------------------------------------- *
 *                                                                         *
 *  This program is free software: you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation, either version 3 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 *                                                                         *
 ***************************************************************************/
/**
 * @file GModelSky.cpp
 * @brief Sky model class implementation
 * @author Juergen Knoedlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "GTools.hpp"
#include "GException.hpp"
#include "GIntegral.hpp"
#include "GEnergies.hpp"
#include "GModelRegistry.hpp"
#include "GModelSky.hpp"
#include "GModelSpatialPointSource.hpp"
#include "GModelSpatialDiffuseCube.hpp"
#include "GModelSpatialRadial.hpp"
#include "GModelSpatialElliptical.hpp"
#include "GModelSpatialComposite.hpp"
#include "GModelSpatialRegistry.hpp"
#include "GModelSpectralRegistry.hpp"
#include "GModelTemporalRegistry.hpp"
#include "GModelTemporalConst.hpp"
#include "GSource.hpp"
#include "GResponse.hpp"

/* __ Globals ____________________________________________________________ */
const GModelSky         g_pointsource_seed("PointSource");
const GModelSky         g_extendedsource_seed("ExtendedSource");
const GModelSky         g_diffusesource_seed("DiffuseSource");
const GModelSky         g_compositesource_seed("CompositeSource");
const GModelRegistry    g_pointsource_registry(&g_pointsource_seed);
const GModelRegistry    g_extendedsource_registry(&g_extendedsource_seed);
const GModelRegistry    g_diffusesource_registry(&g_diffusesource_seed);
const GModelRegistry    g_compositesource_registry(&g_compositesource_seed);

/* __ Method name definitions ____________________________________________ */
#define G_NPRED           "GModelSky::npred(GEnergy&, GTime&, GObservation&)"
#define G_XML_SPATIAL                  "GModelSky::xml_spatial(GXmlElement&)"
#define G_XML_SPECTRAL                "GModelSky::xml_spectral(GXmlElement&)"
#define G_XML_TEMPORAL                "GModelSky::xml_temporal(GXmlElement&)"
#define G_INTEGRATE_TIME  "GModelSky::integrate_time(GEvent&, GObservation&,"\
                                                                     " bool)"
#define G_INTEGRATE_ENERGY     "GModelSky::integrate_energy(GEvent&, GTime&," \
                                                      " GObservation&, bool)"
#define G_INTEGRATE_DIR "GModelSky::integrate_dir(GEvent&, GEnergy&, GTime&,"\
                                                       " GObservation, bool)"

/* __ Macros _____________________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Debug definitions __________________________________________________ */
//#define G_DUMP_MC                                  //!< Dump MC information
//#define G_DUMP_MC_DETAIL                  //!< Dump detailed MC information


/*==========================================================================
 =                                                                         =
 =                         Constructors/destructors                        =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Void constructor
 *
 * Construct an empty sky model. An empty sky model has no type.
 ***************************************************************************/
GModelSky::GModelSky(void) : GModel()
{
    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Type constructor
 *
 * @param[in] type Model type.
 *
 * Construct an empty sky model of the specified @p type. This constructor
 * does basically the same than the void constructor with the only difference
 * that the m_type member of the class is set to the specified @p type
 * string.
 ***************************************************************************/
GModelSky::GModelSky(const std::string& type) : GModel()
{
    // Initialise members
    init_members();

    // Set model type
    m_type = type;

    // Return
    return;
}


/***********************************************************************//**
 * @brief XML constructor
 *
 * @param[in] xml XML element.
 *
 * Constructs a sky model from the model information that is found in the
 * @p xml element. Only the spatial and spectral information is handled by
 * this constructor. For the temporal component, a constant model of type
 * GModelTemporalConst will be allocated.
 ***************************************************************************/
GModelSky::GModelSky(const GXmlElement& xml) : GModel(xml)
{
    // Initialise members
    init_members();

    // Get pointers on spectrum and spatial model
    const GXmlElement* spec = xml.element("spectrum", 0);
    const GXmlElement* spat = xml.element("spatialModel", 0);

    // Allocate constant
    GModelTemporalConst temporal;

    // Clone spatial and spectral models
    m_spatial  = xml_spatial(*spat);
    m_spectral = xml_spectral(*spec);
    m_temporal = temporal.clone();

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Construct sky model from spatial and spectral XML elements
 *
 * @param[in] spatial Spatial XML element.
 * @param[in] spectral Spectral XML element.
 *
 * Constructs a sky model from the @p spatial and @p spectral information
 * that is found in the respective XML elements. For the temporal component,
 * a constant model of type GModelTemporalConst will be allocated.
 ***************************************************************************/
GModelSky::GModelSky(const GXmlElement& spatial, const GXmlElement& spectral) :
           GModel()
{
    // Initialise private members for clean destruction
    init_members();

    // Allocate constant
    GModelTemporalConst temporal;

    // Clone spatial and spectral models
    m_spatial  = xml_spatial(spatial);
    m_spectral = xml_spectral(spectral);
    m_temporal = temporal.clone();

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Construct sky model from spatial, spectral and temporal XML elements
 *
 * @param[in] spatial Spatial XML element.
 * @param[in] spectral Spectral XML element.
 * @param[in] temporal Temporal XML element.
 *
 * Constructs a sky model from the @p spatial, @p spectral and @p temporal
 * information that is found in the respective XML elements.
 ***************************************************************************/
GModelSky::GModelSky(const GXmlElement& spatial,
                     const GXmlElement& spectral,
                     const GXmlElement& temporal) :
           GModel()
{
    // Initialise private members for clean destruction
    init_members();

    // Clone spatial and spectral models
    m_spatial  = xml_spatial(spatial);
    m_spectral = xml_spectral(spectral);
    m_temporal = xml_temporal(temporal);

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Construct sky model from spatial and spectral components
 *
 * @param[in] spatial Spatial model component.
 * @param[in] spectral Spectral model component.
 *
 * Constructs a sky model from @p spatial and @p spectral model components.
 * For the temporal component, a constant model of type GModelTemporalConst
 * will be allocated.
 ***************************************************************************/
GModelSky::GModelSky(const GModelSpatial&  spatial,
                     const GModelSpectral& spectral) : 
           GModel()
{
    // Initialise members
    init_members();

    // Allocate temporal constant model
    GModelTemporalConst temporal;

    // Clone model components
    m_spatial  = spatial.clone();
    m_spectral = spectral.clone();
    m_temporal = temporal.clone();

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Construct sky model from spatial, spectral and temporal components
 *
 * @param[in] spatial Spatial model component.
 * @param[in] spectral Spectral model component.
 * @param[in] temporal Temporal model component.
 *
 * Constructs a sky model from @p spatial, @p spectral and @p temporal model
 * components.
 ***************************************************************************/
GModelSky::GModelSky(const GModelSpatial& spatial,
                     const GModelSpectral& spectral,
                     const GModelTemporal& temporal) : 
           GModel()
{
    // Initialise members
    init_members();

    // Clone model components
    m_spatial  = spatial.clone();
    m_spectral = spectral.clone();
    m_temporal = temporal.clone();

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] model Sky model.
 ***************************************************************************/
GModelSky::GModelSky(const GModelSky& model) : GModel(model)
{
    // Initialise private members for clean destruction
    init_members();

    // Copy members
    copy_members(model);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Destructor
 ***************************************************************************/
GModelSky::~GModelSky(void)
{
    // Free members
    free_members();

    // Return
    return;
}


/*==========================================================================
 =                                                                         =
 =                                Operators                                =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] model Sky model.
 * @return Sky model.
 ***************************************************************************/
GModelSky& GModelSky::operator= (const GModelSky& model)
{
    // Execute only if object is not identical
    if (this != &model) {

        // Copy base class members
        this->GModel::operator=(model);

        // Free members
        free_members();

        // Initialise private members for clean destruction
        init_members();

        // Copy members
        copy_members(model);

    } // endif: object was not identical

    // Return
    return *this;
}


/*==========================================================================
 =                                                                         =
 =                             Public methods                              =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Clear sky model
 *
 * This method properly resets the sky model to an initial state.
 ***************************************************************************/
void GModelSky::clear(void)
{
    // Free class members
    free_members();
    this->GModel::free_members();

    // Initialise members
    this->GModel::init_members();
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Clone sky model
 *
 * @return Pointer to deep copy of sky model.
 ***************************************************************************/
GModelSky* GModelSky::clone(void) const
{
    // Clone sky model
    return new GModelSky(*this);
}


/***********************************************************************//**
 * @brief Set spatial model component
 *
 * @param[in] spatial Pointer to spatial model component.
 *
 * Sets the spatial model component of the model.
 ***************************************************************************/
void GModelSky::spatial(const GModelSpatial* spatial)
{
    // Free spatial model component only if it differs from current
    // component. This prevents unintential deallocation of the argument
    if ((m_spatial != NULL) && (m_spatial != spatial)) {
        delete m_spatial;
    }

    // Clone spatial model component if it exists, otherwise set pointer
    // to NULL
    m_spatial = (spatial != NULL) ? spatial->clone() : NULL;

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set spectral model component
 *
 * @param[in] spectral Pointer to spectral model component.
 *
 * Sets the spectral model component of the model.
 ***************************************************************************/
void GModelSky::spectral(const GModelSpectral* spectral)
{
    // Free spectral model component only if it differs from current
    // component. This prevents unintential deallocation of the argument
    if ((m_spectral != NULL) && (m_spectral != spectral)) {
        delete m_spectral;
    }

    // Clone spectral model component if it exists, otherwise set pointer
    // to NULL
    m_spectral = (spectral != NULL) ? spectral->clone() : NULL;

    // Set parameter pointers
    set_pointers();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set temporal model component
 *
 * @param[in] temporal Pointer to temporal model component.
 *
 * Sets the temporal model component of the model.
 ***************************************************************************/
void GModelSky::temporal(const GModelTemporal* temporal)
{
    // Free temporal model component only if it differs from current
    // component. This prevents unintential deallocation of the argument
    if ((m_temporal != NULL) && (m_temporal != temporal)) {
        delete m_temporal;
    }

    // Clone temporal model component if it exists, otherwise set pointer
    // to NULL
    m_temporal = (temporal != NULL) ? temporal->clone() : NULL;

    // Set parameter pointers
    set_pointers();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return value of sky model for a given photon
 *
 * @param[in] photon Photon.
 * @return Value of sky model.
 *
 * Returns the value of the sky model for a given @p photon. If no model
 * components exist the model will return a value of 1.
 *
 * @todo We probably should return a value of 0 is no model components exist.
 * But we may also make sure that the model never has NULL pointers, which
 * would avoid all the pointer checks.
 ***************************************************************************/
double GModelSky::value(const GPhoton& photon)
{
    // Initialise source model
    double source = 1.0;

    // Evaluate source model
    if (m_spatial  != NULL) source *= m_spatial->eval(photon);
    if (m_spectral != NULL) source *= m_spectral->eval(photon.energy(),
                                                       photon.time());
    if (m_temporal != NULL) source *= m_temporal->eval(photon.time());

    // Return
    return source;
}


/***********************************************************************//**
 * @brief Return parameter gradients of sky model for a given photon
 *
 * @param[in] photon Photon.
 * @return Vector of parameter gradients
 *
 * Returns a vector of parameter gradients for the sky model for a given
 * @p photon. If there are no parameters in the sky model, an empty vector
 * will be returned.
 ***************************************************************************/
GVector GModelSky::gradients(const GPhoton& photon)
{
    // Evaluate source model gradients
    if (m_spatial  != NULL) m_spatial->eval(photon, true);
    if (m_spectral != NULL) m_spectral->eval(photon.energy(), photon.time(),
                                             true);
    if (m_temporal != NULL) m_temporal->eval(photon.time(), true);

    // Set vector of gradients
    GVector gradients;
    if (size() > 0) {
        gradients = GVector(size());
        for (int i = 0; i < size(); ++i) {
            gradients[i] = m_pars[i]->factor_gradient();
        }
    }

    // Return gradients
    return gradients;
}


/***********************************************************************//**
 * @brief Evaluate sky model for a given event of an observation
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @param[in] gradients Compute gradients?
 * @return Value of sky model.
 *
 * Evalutes the value of the sky model for an @p event of a specific
 * observation @p obs.
 *
 * If the @p gradients flag is true the method will also compute the
 * parameter gradients for all model parameters.
 ***************************************************************************/
double GModelSky::eval(const GEvent&       event,
                       const GObservation& obs,
                       const bool&         gradients) const
{
    // Evaluate model
    double value = obs.response()->convolve(*this, event, obs, gradients);

    // If gradients were requested then signal all computed analytical
    // gradients
    if (gradients) {
        signal_analytical_gradients(obs);
    }

    // Return
    return value;
}


/***********************************************************************//**
 * @brief Evaluate sky model for all events of an observation
 *
 * @param[in] obs Observation.
 * @param[out] gradients Pointer to sparse matrix holding model gradients.
 * @return Values of sky model.
 *
 * Evalutes the value of the sky model for an @p event of a specific
 * observation @p obs.
 *
 * If the @p gradients flag is true the method will also compute the
 * parameter gradients for all model parameters.
 ***************************************************************************/
GVector GModelSky::eval(const GObservation& obs,
                        GMatrixSparse*      gradients) const
{
    // Evaluate model
    GVector values = obs.response()->convolve(*this, obs, gradients);

    // If gradients were requested then signal all computed analytical
    // gradients
    if (gradients) {
        signal_analytical_gradients(obs);
    }

    // Return
    return values;
}


/***********************************************************************//**
 * @brief Return spatially integrated sky model
 *
 * @param[in] obsEng Measured photon energy.
 * @param[in] obsTime Measured photon arrival time.
 * @param[in] obs Observation.
 * @return Spatially integrated sky model.
 *
 * Computes
 *
 * \f[
 *    N_{\rm pred}(E',t') = \int_{\rm ROI}
 *                          P(p',E',t') \, dp' \, dE'
 * \f]
 *
 * of the event probability
 *
 * \f[
 *    P(p',E',t') = \int \int \int
 *                  S(p,E,t) \times R(p',E',t'|p,E,t) \, dp \, dE \, dt
 * \f]
 *
 * where
 * \f$S(p,E,t)\f$ is the source model,
 * \f$R(p',E',t'|p,E,t)\f$ is the instrument response function,
 * \f$p'\f$ is the measured photon direction,
 * \f$E'\f$ is the measured photon energy,
 * \f$t'\f$ is the measured photon arrival time,
 * \f$p\f$ is the true photon arrival direction,
 * \f$E\f$ is the true photon energy, and
 * \f$t\f$ is the true photon arrival time.
 *
 * The method calls the GResponse::nroi() method that does the relevant
 * integration.
 ***************************************************************************/
double GModelSky::npred(const GEnergy&      obsEng,
                        const GTime&        obsTime,
                        const GObservation& obs) const
{
    // Initialise result
    double npred = 0.0;

    // Continue only if model is valid)
    if (valid_model()) {

        // Compute Nroi
        npred = obs.response()->nroi(*this, obsEng, obsTime, obs);

        // Compile option: Check for NaN/Inf
        #if defined(G_NAN_CHECK)
        if (gammalib::is_notanumber(npred) || gammalib::is_infinite(npred)) {
            std::cout << "*** ERROR: GModelSky::npred:";
            std::cout << " NaN/Inf encountered";
            std::cout << " (npred=" << npred;
            std::cout << ", obsEng=" << obsEng;
            std::cout << ", obsTime=" << obsTime;
            std::cout << ")" << std::endl;
        }
        #endif

    } // endif: model was valid

    // Return npred
    return npred;
}


/***********************************************************************//**
 * @brief Read sky model from XML element
 *
 * @param[in] xml XML element.
 *
 * Reads the sky model from an XML element. The XML element is expected to
 * respect the following format:
 *
 *     <source name=".." type=".." instrument=".." id=".." ts="..">
 *       <spectrum type="..">
 *         ..
 *       </spectrum>
 *       <spatialModel type="..">
 *         ..
 *       </spatialModel>
 *       <temporal type="..">
 *         ..
 *       </temporal>
 *     </source>
 *
 * The temporal element is optional. In no temporal element is specified a
 * constant component with unity normalization will be assumed.
 *
 * Optionally, the model may also contain scale parameters following the
 * format:
 *
 *     <source name=".." type=".." instrument=".." id=".." ts="..">
 *       <spectrum type="..">
 *         ..
 *       </spectrum>
 *       <spatialModel type="..">
 *         ..
 *       </spatialModel>
 *       <temporal type="..">
 *         ..
 *       </temporal>
 *       <scaling>
 *         <instrument name=".." scale="1.0" min="0.1" max="10.0" value="1.0" free="0"/>
 *         <instrument name=".." scale="1.0" min="0.1" max="10.0" value="0.5" free="0"/>
 *       </scaling>
 *     </source>
 *
 * (see GModel::read_scales() for more information on instrument scales).
 ***************************************************************************/
void GModelSky::read(const GXmlElement& xml)
{
    // Clear sky model
    clear();

    // Get pointers on spectrum and spatial model
    const GXmlElement* spec = xml.element("spectrum", 0);
    const GXmlElement* spat = xml.element("spatialModel", 0);

    // Set spatial and spectral models
    m_spatial  = xml_spatial(*spat);
    m_spectral = xml_spectral(*spec);

    // Handle optional temporal model
    if (xml.elements("temporal") > 0) {
        const GXmlElement* temp = xml.element("temporal", 0);
        m_temporal = xml_temporal(*temp);
    }
    else {
        GModelTemporalConst temporal;
        m_temporal = temporal.clone();
    }

    // Read model attributes
    read_attributes(xml);

    // Set parameter pointers
    set_pointers();

    // Set model type dependent on spatial model type
    set_type();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Write model into XML element
 *
 * @param[in] xml Source library.
 *
 * Writes the sky model into an XML source library. The format written to
 * the @p xml element is as follows:
 *
 *     <source name=".." type=".." instrument=".." id=".." ts="..">
 *       <spectrum type="..">
 *         ..
 *       </spectrum>
 *       <spatialModel type="..">
 *         ..
 *       </spatialModel>
 *       <temporal type="..">
 *         ..
 *       </temporal>
 *       <scaling>
 *         <instrument name=".." scale="1.0" min="0.1" max="10.0" value="1.0" free="0"/>
 *         <instrument name=".." scale="1.0" min="0.1" max="10.0" value="0.5" free="0"/>
 *       </scaling>
 *     </source>
 *
 * For compatibility reasons the temporal element will only be written if it
 * is a non-constant component or a constant component with a normalization
 * that differs from unity.
 *
 * The scaling element will only be written optionally in case that instrument
 * dependent scaling factors exist (see GModel::write_scales() for more
 * information on instrument scales).
 ***************************************************************************/
void GModelSky::write(GXmlElement& xml) const
{
    // Initialise pointer on source
    GXmlElement* src = NULL;

    // Search corresponding source
    int n = xml.elements("source");
    for (int k = 0; k < n; ++k) {
        GXmlElement* element = static_cast<GXmlElement*>(xml.element("source", k));
        if (element->attribute("name") == name()) {
            src = element;
            break;
        }
    }

    // If the temporal model is not a constant with unit normalization then
    // set cons to a NULL pointer
    GModelTemporalConst* cons = dynamic_cast<GModelTemporalConst*>(temporal());
    if (cons != NULL) {
        if (cons->norm() != 1.0) {
            cons = NULL;
        }
    }

    // If no source with corresponding name was found then append one
    if (src == NULL) {
        src = xml.append("source");
        if (spectral() != NULL) src->append(GXmlElement("spectrum"));
        if (spatial()  != NULL) src->append(GXmlElement("spatialModel"));
        if (temporal() != NULL && cons == NULL) src->append(GXmlElement("temporal"));
    }

    // Write spectral model
    if (spectral() != NULL) {
        GXmlElement* spec = src->element("spectrum", 0);
        spectral()->write(*spec);
    }

    // Write spatial model
    if (spatial() != NULL) {
        GXmlElement* spat = src->element("spatialModel", 0);
        spatial()->write(*spat);
    }

    // Write temporal model (only if not a constant with unit normalization
    // factor)
    if (temporal() != NULL && cons == NULL) {
        GXmlElement* temp = src->element("temporal", 0);
        temporal()->write(*temp);
    }

    // Write model attributes
    write_attributes(*src);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return simulated list of photons
 *
 * @param[in] area Simulation surface area (cm2).
 * @param[in] dir Centre of simulation cone.
 * @param[in] radius Radius of simulation cone (deg).
 * @param[in] emin Minimum photon energy.
 * @param[in] emax Maximum photon energy.
 * @param[in] tmin Minimum photon arrival time.
 * @param[in] tmax Maximum photon arrival time.
 * @param[in,out] ran Random number generator.
 * @return List of photons
 *
 * Returns a list of photons that has been derived by Monte Carlo simulation
 * from the model. A simulation region is define by specification of
 * - a simulation cone, which is a circular region on the sky defined by
 *   a centre direction @p dir and a @p radius,
 * - an energy range [@p emin, @p emax], and
 * - a time interval [@p tmin, @p tmax].
 *
 * Only photons with parameters in the simulation region will be returned
 * by the method.
 *
 * The simulation cone may eventually cover the entire sky (by setting
 * the radius to 180 degrees), yet simulations will be more efficient if
 * only the sky region will be simulated that is actually observed by the
 * telescope.
 *
 * @todo Implement unique model ID to assign as Monte Carlo ID
 ***************************************************************************/
GPhotons GModelSky::mc(const double& area,
                       const GSkyDir& dir,  const double&  radius,
                       const GEnergy& emin, const GEnergy& emax,
                       const GTime&   tmin, const GTime&   tmax,
                       GRan& ran) const
{
    // Allocate photons
    GPhotons photons;

    // Continue only if model is valid)
    if (valid_model()) {

        // Determine the spatial model normalization within the simulation
        // cone and check whether the model will produce any photons in that
        // cone.
        double norm      = m_spatial->mc_norm(dir, radius);
        bool   use_model = (norm > 0.0) ? true : false;

        // Continue only if model overlaps with simulation region
        if (use_model) {

            // Initialise de-allocation flag
            bool free_spectral = false;

            // Set pointer to spectral model
            GModelSpectral* spectral = m_spectral;

            // If the spectral model is a diffuse cube then create a node
            // function spectral model that is the product of the diffuse
            // cube node function and the spectral model evaluated at the
            // energies of the node function
            GModelSpatialDiffuseCube* cube =
                         dynamic_cast<GModelSpatialDiffuseCube*>(m_spatial);
            if (cube != NULL) {

                // Set MC cone
                cube->mc_cone(GSkyRegionCircle(dir, radius));

                // Allocate node function to replace the spectral component
                GModelSpectralNodes* nodes =
                                     new GModelSpectralNodes(cube->spectrum());
                for (int i = 0; i < nodes->nodes(); ++i) {
                    GEnergy energy    = nodes->energy(i);
                    double  intensity = nodes->intensity(i);
                    double  value     = m_spectral->eval(energy, tmin);
                    nodes->intensity(i, value*intensity);
                }

                // Signal that node function needs to be de-allocated later
                free_spectral = true;

                // Set the spectral model pointer to the node function
                spectral = nodes;

                // Kluge: if there are no nodes then the spectral->flux method
                // will throw an exception. We therefore set here the use_model
                // flag to false in case that there are no spectral nodes
                if (nodes->nodes() == 0) {
                    use_model = false;
                }

            } // endif: spatial model was a diffuse cube

            // Compute flux within [emin, emax] in model from spectral
            // component (units: ph/cm2/s)
            double flux = (use_model) ? spectral->flux(emin, emax) : 0.0;

            // Derive expecting counting rate within simulation surface
            // (units: ph/s)
            double rate = flux * area * norm;

            // Debug option: dump rate
            #if defined(G_DUMP_MC)
            std::cout << "GModelSky::mc(\"" << name() << "\": ";
            std::cout << "flux=" << flux << " ph/cm2/s, ";
            std::cout << "rate=" << rate << " ph/s, ";
            std::cout << "norm=" << norm << ")" << std::endl;
            #endif

            // Continue only if rate is positive
            if (rate > 0.0) {

                // Get photon arrival times from temporal model
                GTimes times = m_temporal->mc(rate, tmin, tmax, ran);

                // Debug option: dump number of times
                #if defined(G_DUMP_MC_DETAIL)
                std::cout << "  Times=" << times.size() << std::endl;
                #endif

                // Reserve space for photons
                if (times.size() > 0) {
                    photons.reserve(times.size());
                }

                // Loop over photons
                for (int i = 0; i < times.size(); ++i) {

                    // Debug option: dump photon index
                    #if defined(G_DUMP_MC_DETAIL)
                    std::cout << "  Photon=" << i << std::endl;
                    #endif

                    // Allocate photon
                    GPhoton photon;

                    // Set photon arrival time
                    photon.time(times[i]);

                    // Debug option: dump time
                    #if defined(G_DUMP_MC_DETAIL)
                    std::cout << "    Time=" << times[i] << std::endl;
                    #endif

                    // Set photon energy. If an invalid_return_value exception
                    // occurs the energy returned by the spectral Monte Carlo
                    // method is invalid and the photon is skipped.
                    try {
                        photon.energy(spectral->mc(emin, emax, photon.time(),
                                                   ran));
                    }
                    catch (GException::invalid_return_value) {
                        continue;
                    }

                    // Debug option: dump energy
                    #if defined(G_DUMP_MC_DETAIL)
                    std::cout << "    Energy=" << photon.energy() << std::endl;
                    #endif

                    // Set incident photon direction. If an invalid_return_value
                    // exception occurs the sky direction returned by the
                    // spatial Monte Carlo method is invalid and the photon is
                    // skipped.
                    try {
                        photon.dir(m_spatial->mc(photon.energy(), photon.time(),
                                                 ran));
                    }
                    catch (GException::invalid_return_value) {
                        continue;
                    }

                    // Debug option: dump direction
                    #if defined(G_DUMP_MC_DETAIL)
                    std::cout << "    Direction=" << photon.dir() << std::endl;
                    #endif

                    // Append photon
                    if (dir.dist_deg(photon.dir()) <= radius) {
                        photons.append(photon);
                    }

                } // endfor: looped over photons

            } // endif: rate was positive

            // Free spectral model if required
            if (free_spectral) delete spectral;

        } // endif: model was used

    } // endif: model was valid

    // Return photon list
    return photons;
}


/***********************************************************************//**
 * @brief Return sky model photon flux
 *
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model photon flux (cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the spatially integrate photon flux in the sky model.
 *
 * @todo Take spatial photon flux normalisation into account
 ***************************************************************************/
double GModelSky::flux(const GEnergy& emin, const GEnergy& emax) const
{
    // Initialise flux
    double flux = 0.0;

    // Get pointer on diffuse cube spatial model component
    const GModelSpatialDiffuseCube* cube =
          dynamic_cast<const GModelSpatialDiffuseCube*>(spatial());

    // If spatial model is a diffuse cube then compute the flux by
    // multiplying the spectrum of the spatial and spectral components
    // using a node function
    if (cube != NULL) {

        // Get spectral nodes
        GModelSpectralNodes nodes = cube->spectrum();

        // Multiply spectral nodes with spectral model
        for (int i = 0; i < nodes.nodes(); ++i) {

            // Get energy and intensity
            GEnergy energy    = nodes.energy(i);
            double  intensity = nodes.intensity(i);

            // Multiply intensity with spectral model
            intensity *= spectral()->eval(energy);

            // Store intensity
            nodes.intensity(i, intensity);

        } // endfor: multiplied spectral nodes with spectral model

        // Compute flux
        flux = nodes.flux(emin, emax);

    } // endif: spatial model was a diffuse cube

    // ... otherwise assume that the spatial model is unity and compute
    // flux from the spectral component
    else {
        flux = spectral()->flux(emin, emax);
    }

    // Return flux
    return flux;
}


/***********************************************************************//**
 * @brief Return sky model photon flux within sky region
 *
 * @param[in] region Sky region.
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model photon flux (cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the photon flux of the sky model within a given sky region.
 ***************************************************************************/
double GModelSky::flux(const GSkyRegion& region,
                       const GEnergy&    emin,
                       const GEnergy&    emax) const
{
    // Initialise flux
    double flux = 0.0;

    // Signal for which models the spatial component depends on energy
    bool dependence = (spatial()->classname() == "GModelSpatialDiffuseCube") ||
                      (spatial()->classname() == "GModelSpatialComposite");

    // If the spatial component depends on energy then use
    if (dependence) {

        // Set 100 logarithmically-spaced energy nodes for node model
        GEnergies energies(100, emin, emax, "LOG");

        // Allocate spectral nodes
        GModelSpectralNodes nodes(*spectral(), energies);

        // Multiply spectral nodes with spatial flux within region
        for (int i = 0; i < nodes.nodes(); ++i) {

            // Get energy and intensity
            GEnergy energy    = nodes.energy(i);
            double  intensity = nodes.intensity(i);

            // Multiply intensity with spatial flux within region. Note that
            // this correctly takes the spatial normalisation into account
            // since the flux() method does this.
            intensity *= spatial()->flux(region, energy);

            // Store intensity
            nodes.intensity(i, intensity);

        } // endfor: multiplied spectral nodes with spectral model

        // Compute flux
        flux = nodes.flux(emin, emax);

    } // endif: spatial model was a diffuse cube

    // ... otherwise the spatial model does not depend on energy, hence
    // the flux is computed as the product between the spatial and
    // spectral flux. Note that this correctly takes the spatial
    // normalisation into account since the flux() method does this.
    else {
        flux = spatial()->flux(region) * spectral()->flux(emin, emax);
    }

    // Return flux
    return flux;
}


/***********************************************************************//**
 * @brief Return sky model energy flux
 *
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model energy flux (erg cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the spatially integrate energy flux in the sky model.
 ***************************************************************************/
double GModelSky::eflux(const GEnergy& emin, const GEnergy& emax) const
{
    // Initialise energy flux
    double eflux = 0.0;

    // Get pointer on diffuse cube spatial model component
    const GModelSpatialDiffuseCube* cube =
          dynamic_cast<const GModelSpatialDiffuseCube*>(spatial());

    // If spatial model is a diffuse cube then compute the flux by
    // multiplying the spectrum of the spatial and spectral components
    // using a node function
    if (cube != NULL) {

        // Get spectral nodes
        GModelSpectralNodes nodes = cube->spectrum();

        // Multiply spectral nodes with spectral model
        for (int i = 0; i < nodes.nodes(); ++i) {

            // Get energy and intensity
            GEnergy energy    = nodes.energy(i);
            double  intensity = nodes.intensity(i);

            // Multiply intensity with spectral model
            intensity *= spectral()->eval(energy);

            // Store intensity
            nodes.intensity(i, intensity);

        } // endfor: multiplied spectral nodes with spectral model

        // Compute energy flux
        eflux = nodes.eflux(emin, emax);

    } // endif: spatial model was a diffuse cube

    // ... otherwise assume that the spatial model is unity and compute
    // energy flux from the spectral component
    else {
        eflux = spectral()->eflux(emin, emax);
    }

    // Return energy flux
    return eflux;
}


/***********************************************************************//**
 * @brief Return sky model energy flux within sky region
 *
 * @param[in] region Sky region.
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model energy flux (erg cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the energy flux of the sky model within a given sky region.
 ***************************************************************************/
double GModelSky::eflux(const GSkyRegion& region,
                        const GEnergy&    emin,
                        const GEnergy&    emax) const
{
    // Initialise flux
    double eflux = 0.0;

    // Signal for which models the spatial component depends on energy
    bool dependence = (spatial()->classname() == "GModelSpatialDiffuseCube") ||
                      (spatial()->classname() == "GModelSpatialComposite");

    // If the spatial component depends on energy then use
    if (dependence) {

        // Set 100 logarithmically-spaced energy nodes for node model
        GEnergies energies(100, emin, emax, "LOG");

        // Allocate spectral nodes
        GModelSpectralNodes nodes(*spectral(), energies);

        // Multiply spectral nodes with spatial flux within region
        for (int i = 0; i < nodes.nodes(); ++i) {

            // Get energy and intensity
            GEnergy energy    = nodes.energy(i);
            double  intensity = nodes.intensity(i);

            // Multiply intensity with spatial flux within region. Note that
            // this correctly takes the spatial normalisation into account
            // since the flux() method does this.
            intensity *= spatial()->flux(region, energy);

            // Store intensity
            nodes.intensity(i, intensity);

        } // endfor: multiplied spectral nodes with spectral model

        // Compute flux
        eflux = nodes.eflux(emin, emax);

    } // endif: spatial model was a diffuse cube

    // ... otherwise the spatial model does not depend on energy, hence
    // the flux is computed as the product between the spatial and
    // spectral flux. Note that this correctly takes the spatial
    // normalisation into account since the flux() method does this.
    else {
        eflux = spatial()->flux(region) * spectral()->eflux(emin, emax);
    }

    // Return flux
    return eflux;
}


/***********************************************************************//**
 * @brief Return sky model photon flux error
 *
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model photon flux error (cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the spatially integrate photon flux error in the sky model. The
 * photon flux error is computed using Gaussian error propagation
 *
 * \f[
 *    \Delta F_{ph} = \sqrt{
 *    \sum_i \left( \frac{\partial F_{ph}}{\partial p_i} \right)^2
 *    \left( \Delta p_i \right)^2 }
 * \f]
 *
 * where
 * \f$F_{ph}\f$ is the sky model photon flux and
 * \f$p_i\f$ are the sky model parameters.
 ***************************************************************************/
double GModelSky::flux_error(const GEnergy& emin, const GEnergy& emax) const
{
    // Initialise flux error
    double flux_error = 0.0;

    // Loop over all model parameters
    for (int ipar = 0; ipar < size(); ++ipar) {

        // Get non-const model pointer
        GModelPar* par = const_cast<GModelPar*>(&(*this)[ipar]);

        // Consider only free parameters
        if (par->is_free()) {

            // Save current model parameter
            GModelPar current = *par;

            // Autoscale model parameter
            par->autoscale();

            // Get actual parameter value
            double x = par->factor_value();

            // Set fixed step size for computation of derivative.
            const double step_size = 0.0002;
            double       h         = step_size;

            // Re-adjust the step-size h in case that the initial step size is
            // larger than the allowed parameter range
            if (par->has_min() && par->has_max()) {
                double par_h = par->factor_max() - par->factor_min();
                if (par_h < h) {
                    h = par_h;
                }
            }

            // Initialise derivative
            double derivative = 0.0;

            // Continue only if step size is positive
            if (h > 0.0) {

                // If we are too close to the minimum boundary use a right
                // sided difference ...
                if (par->has_min() && ((x-par->factor_min()) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = flux(emin, emax);

                    // Compute fs2
                    par->factor_value(x+h);
                    double fs2 = flux(emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise if we are too close to the maximum boundary use
                // a left sided difference ...
                else if (par->has_max() && ((par->factor_max()-x) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = flux(emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = flux(emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise use a symmetric difference
                else {

                    // Compute fs1
                    par->factor_value(x+h);
                    double fs1 = flux(emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = flux(emin, emax);

                    // Compute derivative
                    derivative = 0.5 * (fs1 - fs2) / h;

                }

            } // endif: step size was positive

            // Add contribution
            if (derivative > 0.0) {
                double factor = derivative * par->factor_error();
                flux_error   += factor * factor;
            }

            // Restore current model parameter
            *par = current;

        } // endif: parameter was free

    } // endfor: looped over all parameters

    // Take square root if required
    if (flux_error > 0.0) {
        flux_error = std::sqrt(flux_error);
    }

    // Return flux error
    return flux_error;
}


/***********************************************************************//**
 * @brief Return sky model photon flux error within sky region
 *
 * @param[in] region Sky region.
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model photon flux error (cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the spatially integrate photon flux error in the sky model. The
 * photon flux error is computed using Gaussian error propagation
 *
 * \f[
 *    \Delta F_{ph} = \sqrt{
 *    \sum_i \left( \frac{\partial F_{ph}}{\partial p_i} \right)^2
 *    \left( \Delta p_i \right)^2 }
 * \f]
 *
 * where
 * \f$F_{ph}\f$ is the sky model photon flux and
 * \f$p_i\f$ are the sky model parameters.
 ***************************************************************************/
double GModelSky::flux_error(const GSkyRegion& region,
                             const GEnergy&    emin,
                             const GEnergy&    emax) const
{
    // Initialise flux error
    double flux_error = 0.0;

    // Loop over all model parameters
    for (int ipar = 0; ipar < size(); ++ipar) {

        // Get non-const model pointer
        GModelPar* par = const_cast<GModelPar*>(&(*this)[ipar]);

        // Consider only free parameters
        if (par->is_free()) {

            // Save current model parameter
            GModelPar current = *par;

            // Autoscale model parameter
            par->autoscale();

            // Get actual parameter value
            double x = par->factor_value();

            // Set fixed step size for computation of derivative.
            const double step_size = 0.0002;
            double       h         = step_size;

            // Re-adjust the step-size h in case that the initial step size is
            // larger than the allowed parameter range
            if (par->has_min() && par->has_max()) {
                double par_h = par->factor_max() - par->factor_min();
                if (par_h < h) {
                    h = par_h;
                }
            }

            // Initialise derivative
            double derivative = 0.0;

            // Continue only if step size is positive
            if (h > 0.0) {

                // If we are too close to the minimum boundary use a right
                // sided difference ...
                if (par->has_min() && ((x-par->factor_min()) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = flux(region, emin, emax);

                    // Compute fs2
                    par->factor_value(x+h);
                    double fs2 = flux(region, emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise if we are too close to the maximum boundary use
                // a left sided difference ...
                else if (par->has_max() && ((par->factor_max()-x) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = flux(region, emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = flux(region, emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise use a symmetric difference
                else {

                    // Compute fs1
                    par->factor_value(x+h);
                    double fs1 = flux(region, emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = flux(region, emin, emax);

                    // Compute derivative
                    derivative = 0.5 * (fs1 - fs2) / h;

                }

            } // endif: step size was positive

            // Add contribution
            if (derivative > 0.0) {
                double factor = derivative * par->factor_error();
                flux_error   += factor * factor;
            }

            // Restore current model parameter
            *par = current;

        } // endif: parameter was free

    } // endfor: looped over all parameters

    // Take square root if required
    if (flux_error > 0.0) {
        flux_error = std::sqrt(flux_error);
    }
    // Return flux error
    return flux_error;
}


/***********************************************************************//**
 * @brief Return sky model energy flux error
 *
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model energy flux error (erg cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the spatially integrate energy flux error in the sky model. The
 * energy flux error is computed using Gaussian error propagation
 *
 * \f[
 *    \Delta F_E = \sqrt{
 *    \sum_i \left( \frac{\partial F_E}{\partial p_i} \right)^2
 *    \left( \Delta p_i \right)^2 }
 * \f]
 *
 * where
 * \f$F_E\f$ is the sky model energy flux and
 * \f$p_i\f$ are the sky model parameters.
 ***************************************************************************/
double GModelSky::eflux_error(const GEnergy& emin, const GEnergy& emax) const
{
    // Initialise flux error
    double eflux_error = 0.0;

    // Loop over all model parameters
    for (int ipar = 0; ipar < size(); ++ipar) {

        // Get non-const model pointer
        GModelPar* par = const_cast<GModelPar*>(&(*this)[ipar]);

        // Consider only free parameters
        if (par->is_free()) {

            // Save current model parameter
            GModelPar current = *par;

            // Autoscale model parameter
            par->autoscale();

            // Get actual parameter value
            double x = par->factor_value();

            // Set fixed step size for computation of derivative.
            const double step_size = 0.0002;
            double       h         = step_size;

            // Re-adjust the step-size h in case that the initial step size is
            // larger than the allowed parameter range
            if (par->has_min() && par->has_max()) {
                double par_h = par->factor_max() - par->factor_min();
                if (par_h < h) {
                    h = par_h;
                }
            }

            // Initialise derivative
            double derivative = 0.0;

            // Continue only if step size is positive
            if (h > 0.0) {

                // If we are too close to the minimum boundary use a right
                // sided difference ...
                if (par->has_min() && ((x-par->factor_min()) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = eflux(emin, emax);

                    // Compute fs2
                    par->factor_value(x+h);
                    double fs2 = eflux(emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise if we are too close to the maximum boundary use
                // a left sided difference ...
                else if (par->has_max() && ((par->factor_max()-x) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = eflux(emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = eflux(emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise use a symmetric difference
                else {

                    // Compute fs1
                    par->factor_value(x+h);
                    double fs1 = eflux(emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = eflux(emin, emax);

                    // Compute derivative
                    derivative = 0.5 * (fs1 - fs2) / h;

                }

            } // endif: step size was positive

            // Add contribution
            if (derivative > 0.0) {
                double factor = derivative * par->factor_error();
                eflux_error  += factor * factor;
            }

            // Restore current model parameter
            *par = current;

        } // endif: parameter was free

    } // endfor: looped over all parameters

    // Take square root if required
    if (eflux_error > 0.0) {
        eflux_error = std::sqrt(eflux_error);
    }

    // Return flux error
    return eflux_error;
}


/***********************************************************************//**
 * @brief Return sky model energy flux error within sky region
 *
 * @param[in] region Sky region.
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @return Sky model energy flux error (erg cm\f$^{-2}\f$ s\f$^{-1}\f$)
 *
 * Returns the spatially integrate energy flux error in the sky model. The
 * energy flux error is computed using Gaussian error propagation
 *
 * \f[
 *    \Delta F_E = \sqrt{
 *    \sum_i \left( \frac{\partial F_E}{\partial p_i} \right)^2
 *    \left( \Delta p_i \right)^2 }
 * \f]
 *
 * where
 * \f$F_E\f$ is the sky model energy flux and
 * \f$p_i\f$ are the sky model parameters.
 ***************************************************************************/
double GModelSky::eflux_error(const GSkyRegion& region,
                              const GEnergy&    emin,
                              const GEnergy&    emax) const
{
    // Initialise flux error
    double eflux_error = 0.0;

    // Loop over all model parameters
    for (int ipar = 0; ipar < size(); ++ipar) {

        // Get non-const model pointer
        GModelPar* par = const_cast<GModelPar*>(&(*this)[ipar]);

        // Consider only free parameters
        if (par->is_free()) {

            // Save current model parameter
            GModelPar current = *par;

            // Autoscale model parameter
            par->autoscale();

            // Get actual parameter value
            double x = par->factor_value();

            // Set fixed step size for computation of derivative.
            const double step_size = 0.0002;
            double       h         = step_size;

            // Re-adjust the step-size h in case that the initial step size is
            // larger than the allowed parameter range
            if (par->has_min() && par->has_max()) {
                double par_h = par->factor_max() - par->factor_min();
                if (par_h < h) {
                    h = par_h;
                }
            }

            // Initialise derivative
            double derivative = 0.0;

            // Continue only if step size is positive
            if (h > 0.0) {

                // If we are too close to the minimum boundary use a right
                // sided difference ...
                if (par->has_min() && ((x-par->factor_min()) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = eflux(region, emin, emax);

                    // Compute fs2
                    par->factor_value(x+h);
                    double fs2 = eflux(region, emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise if we are too close to the maximum boundary use
                // a left sided difference ...
                else if (par->has_max() && ((par->factor_max()-x) < h)) {

                    // Compute fs1
                    par->factor_value(x);
                    double fs1 = eflux(region, emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = eflux(region, emin, emax);

                    // Compute derivative
                    derivative = (fs1 - fs2) / h;

                }

                // ... otherwise use a symmetric difference
                else {

                    // Compute fs1
                    par->factor_value(x+h);
                    double fs1 = eflux(region, emin, emax);

                    // Compute fs2
                    par->factor_value(x-h);
                    double fs2 = eflux(region, emin, emax);

                    // Compute derivative
                    derivative = 0.5 * (fs1 - fs2) / h;

                }

            } // endif: step size was positive

            // Add contribution
            if (derivative > 0.0) {
                double factor = derivative * par->factor_error();
                eflux_error  += factor * factor;
            }

            // Restore current model parameter
            *par = current;

        } // endif: parameter was free

    } // endfor: looped over all parameters

    // Take square root if required
    if (eflux_error > 0.0) {
        eflux_error = std::sqrt(eflux_error);
    }
    // Return flux error
    return eflux_error;
}


/***********************************************************************//**
 * @brief Print model information
 *
 * @param[in] chatter Chattiness.
 * @return String containing model information.
 ***************************************************************************/
std::string GModelSky::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GModelSky ===");

        // Determine number of parameters per type
        int n_spatial  = (m_spatial  != NULL) ? m_spatial->size()  : 0;
        int n_spectral = (m_spectral != NULL) ? m_spectral->size() : 0;
        int n_temporal = (m_temporal != NULL) ? m_temporal->size() : 0;

        // Append attributes
        result.append("\n"+print_attributes());

        // Append model type
        result.append("\n"+gammalib::parformat("Model type")+type());

        // Append model components
        result.append("\n"+gammalib::parformat("Model components"));
        if (n_spatial > 0) {
            result.append("\""+spatial()->type()+"\"");
            if (n_spectral > 0 || n_temporal > 0) {
                result.append(" * ");
            }
        }
        if (n_spectral > 0) {
            result.append("\""+spectral()->type()+"\"");
            if (n_temporal > 0) {
                result.append(" * ");
            }
        }
        if (n_temporal > 0) {
            result.append("\""+temporal()->type()+"\"");
        }

        // Append parameters
        result.append("\n"+gammalib::parformat("Number of parameters"));
        result.append(gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Number of spatial par's"));
        result.append(gammalib::str(n_spatial));
        for (int i = 0; i < n_spatial; ++i) {
            result.append("\n"+(*spatial())[i].print());
        }
        result.append("\n"+gammalib::parformat("Number of spectral par's"));
        result.append(gammalib::str(n_spectral));
        for (int i = 0; i < n_spectral; ++i) {
            result.append("\n"+(*spectral())[i].print());
        }
        result.append("\n"+gammalib::parformat("Number of temporal par's"));
        result.append(gammalib::str(n_temporal));
        for (int i = 0; i < n_temporal; ++i) {
            result.append("\n"+(*temporal())[i].print());
        }
        result.append("\n"+gammalib::parformat("Number of scale par's"));
        result.append(gammalib::str(scales()));
        for (int i = 0; i < scales(); ++i) {
            result.append("\n"+scale(i).print());
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}


/*==========================================================================
 =                                                                         =
 =                             Private methods                             =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void GModelSky::init_members(void)
{
    // Initialise members
    m_type.clear();
    m_spatial  = NULL;
    m_spectral = NULL;
    m_temporal = NULL;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] model Sky model.
 ***************************************************************************/
void GModelSky::copy_members(const GModelSky& model)
{
    // Copy attributes
    m_type = model.m_type;

    // Clone model components
    m_spatial  = (model.m_spatial  != NULL) ? model.m_spatial->clone()  : NULL;
    m_spectral = (model.m_spectral != NULL) ? model.m_spectral->clone() : NULL;
    m_temporal = (model.m_temporal != NULL) ? model.m_temporal->clone() : NULL;

    // Set parameter pointers
    set_pointers();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete class members
 ***************************************************************************/
void GModelSky::free_members(void)
{
    // Free memory
    if (m_spatial  != NULL) delete m_spatial;
    if (m_spectral != NULL) delete m_spectral;
    if (m_temporal != NULL) delete m_temporal;

    // Signal free pointers
    m_spatial  = NULL;
    m_spectral = NULL;
    m_temporal = NULL;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set parameter pointers
 *
 * Gathers all parameter pointers from the model into a flat array of model
 * pointers. 
 ***************************************************************************/
void GModelSky::set_pointers(void)
{
    // Clear parameters
    m_pars.clear();

    // Determine the number of parameters
    int n_spatial  = (spatial()  != NULL) ? spatial()->size()  : 0;
    int n_spectral = (spectral() != NULL) ? spectral()->size() : 0;
    int n_temporal = (temporal() != NULL) ? temporal()->size() : 0;
    int n_pars     = n_spatial + n_spectral + n_temporal;
    int n_scales   = m_scales.size();

    // Continue only if there are parameters
    if (n_pars > 0) {

        // Gather spatial parameter pointers
        for (int i = 0; i < n_spatial; ++i) {
            m_pars.push_back(&((*spatial())[i]));
        }

        // Gather spectral parameters
        for (int i = 0; i < n_spectral; ++i) {
            m_pars.push_back(&((*spectral())[i]));
        }

        // Gather temporal parameters
        for (int i = 0; i < n_temporal; ++i) {
            m_pars.push_back(&((*temporal())[i]));
        }

    }

    // Append scales if they exist
    if (n_scales > 0) {
        for (int i = 0; i < n_scales; ++i) {
            m_pars.push_back(&m_scales[i]);
        }
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set model type based on spatial model component
 *
 * Set the model type depending on the class type of the spatial model
 * component.
 *
 * @todo A method could be implemented in the GModelSpatial class that
 *       determines the model type. This is however not very critical.
 ***************************************************************************/
void GModelSky::set_type(void)
{
    // Clear model type
    m_type.clear();

    // Continue only if we have a spatial model component
    if (m_spatial != NULL) {

        // Is spatial model a point source?
        if (dynamic_cast<const GModelSpatialPointSource*>(m_spatial) != NULL) {
            m_type = "PointSource";
        }

        // ... otherwise, is spatial model a radial source?
        else if (dynamic_cast<const GModelSpatialRadial*>(m_spatial) != NULL) {
            m_type = "ExtendedSource";
        }

        // ... otherwise, is spatial model an elliptical source?
        else if (dynamic_cast<const GModelSpatialElliptical*>(m_spatial) != NULL) {
            m_type = "ExtendedSource";
        }

        // ... otherwise, is spatial model a composite source?
        else if (dynamic_cast<const GModelSpatialComposite*>(m_spatial) != NULL) {
            m_type = "CompositeSource";
        }

        // ... otherwise we have a diffuse model
        else {
            m_type = "DiffuseSource";
        }

    } // endif: there was a spatial model component

    // Return
    return;
}


/***********************************************************************//**
 * @brief Signal all parameters that have analytical gradients for a given
 *        observation
 *
 * @param[in] obs Observation.
 *
 * This method signals all spectral, temporal and model scaling parameters
 * for which analytical gradients exist for a given observation. Analytical
 * gradients will be signalled for all of these parameters that are free
 * and for which `has_grad()` is `true`.
 *
 * Note that spatial analytical gradients are excluded. These will be
 * signalled by the underlying convolution method as analytical gradients
 * are not (yet) supported by all convolution methods.
 ***************************************************************************/
void GModelSky::signal_analytical_gradients(const GObservation& obs) const
{
    // If the model has a spectral component then signal all free parameters
    // with analytical gradients
    if (spectral() != NULL) {
        for (int i = 0; i < spectral()->size(); ++i) {
            GModelPar& par = (*(spectral()))[i];
            if (par.is_free() && par.has_grad()) {
                obs.computed_gradient(*this, par);
            }
        }
    }

    // If the model has a temporal component then signal all free parameters
    // with analytical gradients
    if (temporal() != NULL) {
        for (int i = 0; i < temporal()->size(); ++i) {
            GModelPar& par = (*(temporal()))[i];
            if (par.is_free() && par.has_grad()) {
                obs.computed_gradient(*this, par);
            }
        }
    }

    // If the model has a scales then signal all free parameters with
    // analytical gradients
    if (has_scales()) {
        for (int i = 0; i < scales(); ++i) {
            const GModelPar& par = scale(i);
            if (par.name() == obs.instrument()) {
                if (par.is_free() && par.has_grad()) {
                    obs.computed_gradient(*this, par);
                }
            }
        }
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return pointer to spatial model from XML element
 *
 * @param[in] spatial XML element.
 * @return Pointer to spatial model.
 *
 * Returns pointer to spatial model that is defined in an XML element.
 ***************************************************************************/
GModelSpatial* GModelSky::xml_spatial(const GXmlElement& spatial) const
{
    // Get spatial model
    GModelSpatialRegistry registry;
    GModelSpatial*        ptr = registry.alloc(spatial);

    // Return pointer
    return ptr;
}


/***********************************************************************//**
 * @brief Return pointer to spectral model from XML element
 *
 * @param[in] spectral XML element.
 * @return Pointer to spectral model.
 *
 * Returns pointer to spectral model that is defined in an XML element.
 ***************************************************************************/
GModelSpectral* GModelSky::xml_spectral(const GXmlElement& spectral) const
{
    // Get spectral model
    GModelSpectralRegistry registry;
    GModelSpectral*        ptr = registry.alloc(spectral);

    // Return pointer
    return ptr;
}


/***********************************************************************//**
 * @brief Return pointer to temporal model from XML element
 *
 * @param[in] temporal XML element.
 * @return Pointer to temporal model.
 *
 * Returns pointer to temporal model that is defined in an XML element.
 ***************************************************************************/
GModelTemporal* GModelSky::xml_temporal(const GXmlElement& temporal) const
{
    // Get temporal model
    GModelTemporalRegistry registry;
    GModelTemporal*        ptr = registry.alloc(temporal);

    // Return pointer
    return ptr;
}


/***********************************************************************//**
 * @brief Verifies if model has all components
 *
 * @return True is model is valid, false otherwise.
 ***************************************************************************/
bool GModelSky::valid_model(void) const
{
    // Set result
    bool result = ((m_spatial  != NULL) &&
                   (m_spectral != NULL) &&
                   (m_temporal != NULL));

    // Return result
    return result;
}