GCTABackground3D.cpp 36.6 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
/***************************************************************************
 *              GCTABackground3D.cpp - CTA 3D background class             *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2014-2017 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 GCTABackground3D.cpp
 * @brief CTA 3D background class implementation
 * @author Juergen Knoedlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "GTools.hpp"
#include "GException.hpp"
#include "GFilename.hpp"
#include "GMath.hpp"
#include "GRan.hpp"
#include "GFits.hpp"
#include "GFitsBinTable.hpp"
#include "GCTABackground3D.hpp"

/* __ Method name definitions ____________________________________________ */
#define G_READ                          "GCTABackground3D::read(GFitsTable&)"
#define G_MC                  "GCTABackground3D::mc(GEnergy&, GTime&, GRan&)"

/* __ Macros _____________________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Debug definitions __________________________________________________ */
//#define G_DEBUG_MC_INIT
//#define G_DEBUG_CACHE

/* __ Constants __________________________________________________________ */


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

/***********************************************************************//**
 * @brief Void constructor
 *
 * Constructs empty background.
 ***************************************************************************/
GCTABackground3D::GCTABackground3D(void) : GCTABackground()
{
    // Initialise class members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief File constructor
 *
 * @param[in] filename FITS file name.
 *
 * Constructs background from a FITS file.
 ***************************************************************************/
GCTABackground3D::GCTABackground3D(const GFilename& filename) :
                  GCTABackground()
{
    // Initialise class members
    init_members();

    // Load background from file
    load(filename);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] bgd Background.
 *
 * Constructs background by copying from another background.
 ***************************************************************************/
GCTABackground3D::GCTABackground3D(const GCTABackground3D& bgd) :
                  GCTABackground(bgd)
{
    // Initialise class members
    init_members();

    // Copy members
    copy_members(bgd);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Destructor
 *
 * Destructs background.
 ***************************************************************************/
GCTABackground3D::~GCTABackground3D(void)
{
    // Free members
    free_members();

    // Return
    return;
}


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

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] bgd Background.
 * @return Background.
 *
 * Assigns background.
 ***************************************************************************/
GCTABackground3D& GCTABackground3D::operator=(const GCTABackground3D& bgd)
{
    // Execute only if object is not identical
    if (this != &bgd) {

        // Copy base class members
        this->GCTABackground::operator=(bgd);

        // Free members
        free_members();

        // Initialise private members
        init_members();

        // Copy members
        copy_members(bgd);

    } // endif: object was not identical

    // Return this object
    return *this;
}


/***********************************************************************//**
 * @brief Return background rate in units of events/s/MeV/sr
 *
 * @param[in] logE Log10 of the true photon energy (TeV).
 * @param[in] detx Tangential X coordinate in nominal system (radians).
 * @param[in] dety Tangential Y coordinate in nominal system (radians).
 *
 * Returns the background rate in units of events/s/MeV/sr for a given energy
 * and detector coordinates. The operator interpolates linearly in DETX and
 * DETY, and logarithmically in energy.
 *
 * The operator assures that the background rate never becomes negative. For
 * invalid background models or detector coordinates outside the range
 * covered by the response cube, the operator returns a rate of zero.
 ***************************************************************************/
double GCTABackground3D::operator()(const double& logE, 
                                    const double& detx, 
                                    const double& dety) const
{
    // Initialise background rate
    double rate = 0.0;

    // Continue only if background model is valid and if the DETX and DETY
    // values are in validity range
    if (is_valid() && (detx >= m_detx_min) && (detx <= m_detx_max) &&
                      (dety >= m_dety_min) && (dety <= m_dety_max)) {

        // Retrieve references to node arrays
        const GNodeArray& detx_nodes   = m_background.axis_nodes(m_inx_detx);
        const GNodeArray& dety_nodes   = m_background.axis_nodes(m_inx_dety);
        const GNodeArray& energy_nodes = m_background.axis_nodes(m_inx_energy);

        // Set values for node arrays
        detx_nodes.set_value(detx);
        dety_nodes.set_value(dety);
        energy_nodes.set_value(logE);

        // Set weighting factors for bi-linear interpolation in DETX-DETY plane
        double wgt_ll = detx_nodes.wgt_left()  * dety_nodes.wgt_left();
        double wgt_lr = detx_nodes.wgt_left()  * dety_nodes.wgt_right();
        double wgt_rl = detx_nodes.wgt_right() * dety_nodes.wgt_left();
        double wgt_rr = detx_nodes.wgt_right() * dety_nodes.wgt_right();

        // Set weighting factors for energy interpolation
        double wgt_emin = energy_nodes.wgt_left();
        double wgt_emax = energy_nodes.wgt_right();

        // Get bin indices
        int inx_ll_emin = index(detx_nodes.inx_left(),  dety_nodes.inx_left(),
                                energy_nodes.inx_left());
        int inx_lr_emin = index(detx_nodes.inx_left(),  dety_nodes.inx_right(),
                                energy_nodes.inx_left());
        int inx_rl_emin = index(detx_nodes.inx_right(), dety_nodes.inx_left(),
                                energy_nodes.inx_left());
        int inx_rr_emin = index(detx_nodes.inx_right(), dety_nodes.inx_right(),
                                energy_nodes.inx_left());
        int inx_ll_emax = index(detx_nodes.inx_left(),  dety_nodes.inx_left(),
                                energy_nodes.inx_right());
        int inx_lr_emax = index(detx_nodes.inx_left(),  dety_nodes.inx_right(),
                                energy_nodes.inx_right());
        int inx_rl_emax = index(detx_nodes.inx_right(), dety_nodes.inx_left(),
                                energy_nodes.inx_right());
        int inx_rr_emax = index(detx_nodes.inx_right(), dety_nodes.inx_right(),
                                energy_nodes.inx_right());

        // Bi-linearly interpolate the rates in both energy layers
        double rate_emin = wgt_ll * m_background(m_inx_bgd, inx_ll_emin) +
                           wgt_lr * m_background(m_inx_bgd, inx_lr_emin) +
                           wgt_rl * m_background(m_inx_bgd, inx_rl_emin) +
                           wgt_rr * m_background(m_inx_bgd, inx_rr_emin);
        double rate_emax = wgt_ll * m_background(m_inx_bgd, inx_ll_emax) +
                           wgt_lr * m_background(m_inx_bgd, inx_lr_emax) +
                           wgt_rl * m_background(m_inx_bgd, inx_rl_emax) +
                           wgt_rr * m_background(m_inx_bgd, inx_rr_emax);

        // If both rates are positive then perform a logarithmic interpolation
        // in energy
        if (rate_emin > 0.0 && rate_emax > 0.0) {
            rate = std::exp(wgt_emin * std::log(rate_emin) +
                            wgt_emax * std::log(rate_emax));
        }
        else {
            rate = 0.0;
        }

        // Make sure that background rate is not negative
        if (rate < 0.0) {
            rate = 0.0;
        }

    } // endif: background model was valid

    // Return background rate
    return rate;
}


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

/***********************************************************************//**
 * @brief Clear background
 *
 * Clears background.
 ***************************************************************************/
void GCTABackground3D::clear(void)
{
    // Free class members
    free_members();
    this->GCTABackground::free_members();

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

    // Return
    return;
}


/***********************************************************************//**
 * @brief Clone background
 *
 * @return Deep copy of background.
 *
 * Returns a pointer to a deep copy of the background.
 ***************************************************************************/
GCTABackground3D* GCTABackground3D::clone(void) const
{
    return new GCTABackground3D(*this);
}


/***********************************************************************//**
 * @brief Read background from FITS table
 *
 * @param[in] table FITS table.
 *
 * @exception GException::invalid_value
 *            Response table is not three-dimensional.
 *
 * Reads the background form the FITS @p table. The following column names
 * are mandatory:
 *
 *     DETX_LO  - DETX lower bin boundaries
 *     DETX_HI  - DETX upper bin boundaries
 *     DETY_LO  - DETY lower bin boundaries
 *     DETY_HI  - DETY upper bin boundaries
 *     ENERG_LO - Energy lower bin boundaries
 *     ENERG_HI - Energy upper bin boundaries
 *     BGD      - Background template
 *
 * The data are stored in the m_background member. The DETX and DETY axes
 * will be set to radians, the energy axis will be set to log10.
 ***************************************************************************/
void GCTABackground3D::read(const GFitsTable& table)
{
    // Clear response table
    m_background.clear();

    // Read background table
    m_background.read(table);

    // Throw an exception if the table is not three-dimensional
    if (m_background.axes() != 3) {
        std::string msg = "Expected three-dimensional background "
                          "response table but found "+
                          gammalib::str(m_background.axes())+
                          " dimensions. Please specify a three-dimensional "
                          "background.";
        throw GException::invalid_value(G_READ, msg);
    }

    // Get mandatory indices (throw exception if not found)
    m_inx_detx   = m_background.axis("DETX");
    m_inx_dety   = m_background.axis("DETY");
    m_inx_energy = m_background.axis("ENERG");
    m_inx_bgd    = m_background.table("BGD");

    // Get axes dimensions
    m_num_detx   = m_background.axis_bins(m_inx_detx);
    m_num_dety   = m_background.axis_bins(m_inx_dety);
    m_num_energy = m_background.axis_bins(m_inx_energy);

    // Set dimension array
    m_num[m_inx_detx]   = m_num_detx;
    m_num[m_inx_dety]   = m_num_dety;
    m_num[m_inx_energy] = m_num_energy;

    // Set DETX and DETY axis to radians
    m_background.axis_radians(m_inx_detx);
    m_background.axis_radians(m_inx_dety);

    // Set energy axis to logarithmic scale
    m_background.axis_log10(m_inx_energy);

    // Set DETX and DETY limits
    set_limits();

    // Return
    return;
}

/***********************************************************************//**
 * @brief Write background into FITS table
 *
 * @param[in] table FITS binary table.
 *
 * Writes background into a FITS binary @p table.
 *
 * @todo Add necessary keywords.
 ***************************************************************************/
void GCTABackground3D::write(GFitsBinTable& table) const
{
    // Write background table
    m_background.write(table);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Load background from FITS file
 *
 * @param[in] filename FITS file name.
 *
 * Loads the background from a FITS file.
 *
 * If no extension name is provided, the background will be loaded from the
 * `BACKGROUND` extension.
 ***************************************************************************/
void GCTABackground3D::load(const GFilename& filename)
{
    // Open FITS file
    GFits fits(filename);

    // Get background table
    const GFitsTable& table =
          *fits.table(filename.extname(gammalib::extname_cta_background3d));

    // Read effective area from table
    read(table);

    // Close FITS file
    fits.close();

    // Store filename
    m_filename = filename;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Save background into FITS file
 *
 * @param[in] filename Background table FITS file name.
 * @param[in] clobber Overwrite existing file? (default: false)
 *
 * Saves background into a FITS file. If a file with the given @p filename
 * does not yet exist it will be created, otherwise the method opens the
 * existing file. The method will create a (or replace an existing)
 * background extension. The extension name can be specified as part
 * of the @p filename, or if no extension name is given, is assumed to be
 * `BACKGROUND`.
 *
 * An existing file will only be modified if the @p clobber flag is set to
 * true.
 ***************************************************************************/
void GCTABackground3D::save(const GFilename& filename, const bool& clobber) const
{
    // Get extension name
    std::string extname = filename.extname(gammalib::extname_cta_background3d);

    // Open or create FITS file (without extension name since the requested
    // extension may not yet exist in the file)
    GFits fits(filename.url(), true);

    // Remove extension if it exists already
    if (fits.contains(extname)) {
        fits.remove(extname);
    }

    // Create binary table
    GFitsBinTable table;

    // Write the background table
    write(table);

    // Set binary table extension name
    table.extname(extname);

    // Append table to FITS file
    fits.append(table);

    // Save to file
    fits.save(clobber);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Returns MC instrument direction
 *
 * @param[in] energy Event energy.
 * @param[in] time Event trigger time.
 * @param[in,out] ran Random number generator.
 * @return CTA instrument direction.
 *
 * Returns a Monte Carlo simulated instrument direction for a given @p energy
 * and event trigger @p time. The simulation is done using a rejection
 * method that makes use of the background rate access operator. This assures
 * that the simulation is consistent with the background rate interpolation
 * that is done by the access operator.
 ***************************************************************************/
GCTAInstDir GCTABackground3D::mc(const GEnergy& energy,
                                 const GTime&   time,
                                 GRan&          ran) const
{
    // If Monte Carlo has not been initialised then initialise the cache now
    if (m_mc_max.empty()) {
        init_mc_cache();
    }

    // Determine energy range of response table
    GEnergy emin = m_mc_spectrum.energy(0);
    GEnergy emax = m_mc_spectrum.energy(m_mc_spectrum.nodes()-1);
    if (energy < emin || energy > emax) {
        std::string msg = "Event energy "+energy.print()+" is outside the "
                          "energy range ["+emin.print()+", "+emax.print()+"] "
                          "covered by the background response table. Please "
                          "restrict the energy range of the simulation to the "
                          "validity range of the background response table.";
        throw GException::invalid_value(G_MC, msg);
    }

    // Allocate instrument direction
    GCTAInstDir dir;

    // Continue only if are maps
    if (!m_mc_max.empty()) {

        // Get reference to node array for the energy axis
        const GNodeArray& energy_nodes = m_background.axis_nodes(m_inx_energy);

        // Get log10(energy) in TeV
        double logE = energy.log10TeV();

        // Set values for node arrays
        energy_nodes.set_value(logE);

        // Get indices for energy interpolation
        int inx_left  = energy_nodes.inx_left();
        int inx_right = energy_nodes.inx_right();

        // Get maximum background rate as the maximum of the left and the right
        // energy node
        double max_rate = m_mc_max[inx_left];
        if (m_mc_max[inx_right] > max_rate) {
            max_rate = m_mc_max[inx_right];
        }

        // Get instrument direction using a rejection method. This assures
        // that the Monte Carlo sample follows the model distribution
        while (true) {

            // Get randomized detx and dety in radians. If the direction falls
            // outside the validity range then get another pair of detx and
            // dety values.
            double theta = std::acos(1.0 - ran.uniform() * m_mc_one_minus_costheta);
            double phi   = gammalib::twopi * ran.uniform();
            double detx  = theta * std::cos(phi);
            double dety  = theta * std::sin(phi);
            if ((detx < m_detx_min) || (detx > m_detx_max) ||
                (dety < m_dety_min) || (dety > m_dety_max)) {
                continue;
            }

            // Get background rate for these coordinates. If the background
            // rate is zero then get other coordinates.
            double value = this->operator()(logE, detx, dety);
            if (value <= 0.0) {
                continue;
            }

            // Get uniform random number
            double uniform = ran.uniform() * max_rate;

            // Exit loop if we're not larger than the background rate value
            if (uniform <= value) {
                dir.detx(detx);
                dir.dety(dety);
                break;
            }

        } // endwhile: loop until instrument direction was accepted

    } // endif: there were cube pixels and maps

    // Return instrument direction
    return dir;
}


/***********************************************************************//**
 * @brief Print background information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing background information.
 ***************************************************************************/
std::string GCTABackground3D::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("=== GCTABackground3D ===");

        // Append information
        result.append("\n"+gammalib::parformat("Filename")+m_filename);

        // If background model is valid then print information
        if (is_valid()) {

            // Compute DETX boundaries in deg
            double detx_min = m_background.axis_lo(m_inx_detx, 0);
            double detx_max = m_background.axis_hi(m_inx_detx, m_num_detx-1);

            // Compute DETY boundaries in deg
            double dety_min = m_background.axis_lo(m_inx_dety,0);
            double dety_max = m_background.axis_hi(m_inx_dety, m_num_dety-1);

            // Compute energy boundaries in TeV
            double emin = m_background.axis_lo(m_inx_energy, 0);
            double emax = m_background.axis_hi(m_inx_energy, m_num_energy-1);

            // Append information
            result.append("\n"+gammalib::parformat("Number of DETX bins") +
                          gammalib::str(m_num_detx));
            result.append("\n"+gammalib::parformat("Number of DETY bins") +
                          gammalib::str(m_num_dety));
            result.append("\n"+gammalib::parformat("Number of energy bins") +
                          gammalib::str(m_num_energy));
            result.append("\n"+gammalib::parformat("DETX range"));
            result.append(gammalib::str(detx_min)+" - "+gammalib::str(detx_max)+" deg");
            result.append("\n"+gammalib::parformat("DETX range"));
            result.append(gammalib::str(dety_min)+" - "+gammalib::str(dety_max)+" deg");
            result.append("\n"+gammalib::parformat("Energy range"));
            result.append(gammalib::str(emin)+" - "+gammalib::str(emax)+" TeV");

        } // endif: there were 3 axis

        // ... otherwise show empty array
        else {
            result.append("\n"+gammalib::parformat("Number of DETX bins") +
                          gammalib::str(0));
            result.append("\n"+gammalib::parformat("Number of DETY bins") +
                          gammalib::str(0));
            result.append("\n"+gammalib::parformat("Number of energy bins") +
                          gammalib::str(0));
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}


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

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void GCTABackground3D::init_members(void)
{
    // Initialise members
    m_filename.clear();
    m_background.clear();
    m_inx_detx   = 0;
    m_inx_dety   = 1;
    m_inx_energy = 2;
    m_inx_bgd    = 0;
    m_num_detx   = 0;
    m_num_dety   = 0;
    m_num_energy = 0;
    m_num[0]     = 0;
    m_num[1]     = 0;
    m_num[2]     = 0;
    m_detx_min   = 0.0;
    m_detx_max   = 0.0;
    m_dety_min   = 0.0;
    m_dety_max   = 0.0;
    m_logE_min   = 0.0;
    m_logE_max   = 0.0;

    // Initialise MC cache
    m_mc_max.clear();
    m_mc_spectrum.clear();
    m_mc_one_minus_costheta = 0.0;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] bgd Background.
 ***************************************************************************/
void GCTABackground3D::copy_members(const GCTABackground3D& bgd)
{
    // Copy members
    m_filename   = bgd.m_filename;
    m_background = bgd.m_background;
    m_inx_detx   = bgd.m_inx_detx;
    m_inx_dety   = bgd.m_inx_dety;
    m_inx_energy = bgd.m_inx_energy;
    m_inx_bgd    = bgd.m_inx_bgd;
    m_num_detx   = bgd.m_num_detx;
    m_num_dety   = bgd.m_num_dety;
    m_num_energy = bgd.m_num_energy;
    m_num[0]     = bgd.m_num[0];
    m_num[1]     = bgd.m_num[1];
    m_num[2]     = bgd.m_num[2];
    m_detx_min   = bgd.m_detx_min;
    m_detx_max   = bgd.m_detx_max;
    m_dety_min   = bgd.m_dety_min;
    m_dety_max   = bgd.m_dety_max;
    m_logE_min   = bgd.m_logE_min;
    m_logE_max   = bgd.m_logE_max;

    // Copy MC cache
    m_mc_max                = bgd.m_mc_max;
    m_mc_spectrum           = bgd.m_mc_spectrum;
    m_mc_one_minus_costheta = bgd.m_mc_one_minus_costheta;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set DETX, DETY and log10(E/TeV) limits
 *
 * Set the DETX, DETY and log10(E/TeV) limits.
 ***************************************************************************/
void GCTABackground3D::set_limits(void)
{
    // Compute DETX boundaries in radians
    m_detx_min = m_background.axis_lo(m_inx_detx, 0) *
                 gammalib::deg2rad;
    m_detx_max = m_background.axis_hi(m_inx_detx, m_num_detx-1) *
                 gammalib::deg2rad;

    // Compute DETY boundaries in radians
    m_dety_min = m_background.axis_lo(m_inx_dety, 0) *
                 gammalib::deg2rad;
    m_dety_max = m_background.axis_hi(m_inx_dety, m_num_dety-1) *
                 gammalib::deg2rad;

    // Compute energy boundaries in log10(TeV)
    GEnergy emin(m_background.axis_lo(m_inx_energy, 0),
                 m_background.axis_lo_unit(m_inx_energy));
    GEnergy emax(m_background.axis_hi(m_inx_energy, m_num_energy-1),
                 m_background.axis_hi_unit(m_inx_energy));
    m_logE_min = emin.log10TeV();
    m_logE_max = emax.log10TeV();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return background rate bin index
 *
 * @param[in] idetx DETX index.
 * @param[in] idety DETY index.
 * @param[in] iebin Energy index.
 * @return Background rate bin index.
 *
 * Returns the background rate bin index independent of the ordering.
 ***************************************************************************/
int GCTABackground3D::index(const int& idetx,
                            const int& idety,
                            const int& iebin) const
{
    // Set index arrays
    int inx[3];
    inx[m_inx_detx]   = idetx;
    inx[m_inx_dety]   = idety;
    inx[m_inx_energy] = iebin;

    // Compute index
    int index = inx[0] + (inx[1] + inx[2] * m_num[1]) * m_num[0];

    // Return index
    return index;
}


/***********************************************************************//**
 * @brief Delete class members
 ***************************************************************************/
void GCTABackground3D::free_members(void)
{
    // Return
    return;
}


/***********************************************************************//**
 * @brief Initialise Monte Carlo cache
 *
 * @exception GException::invalid_value
 *            Background response table was empty.
 *
 * Initialises the cache for Monte Carlo sampling.
 ***************************************************************************/
void GCTABackground3D::init_mc_cache(void) const
{
    // Initialise cache
    m_mc_max.clear();
    m_mc_spectrum.clear();

    // Initialise maximum rate array
    init_mc_max_rate();

    // Compute 1-cos(theta_max)
    double theta1 = std::sqrt(m_detx_min * m_detx_min + m_dety_min * m_dety_min);
    double theta2 = std::sqrt(m_detx_min * m_detx_min + m_dety_max * m_dety_max);
    double theta3 = std::sqrt(m_detx_max * m_detx_max + m_dety_min * m_dety_min);
    double theta4 = std::sqrt(m_detx_max * m_detx_max + m_dety_max * m_dety_max);
    double theta = theta1;
    if (theta2 > theta) {
        theta = theta2;
    }
    if (theta3 > theta) {
        theta = theta3;
    }
    if (theta4 > theta) {
        theta = theta4;
    }
    m_mc_one_minus_costheta = 1.0 - std::cos(theta);

    // Set number of energy bins. Make sure that we compute at least 100 energy
    // bins
    int nbins = m_num_energy * 10;
    if (nbins < 100) {
        nbins = 100;
    }

    // Compute DETX and DETY binsize in radians and energy binsize in log10(TeV)
    double detx_bin = (m_detx_max - m_detx_min) / m_num_detx;
    double dety_bin = (m_dety_max - m_dety_min) / m_num_dety;
    double logE_bin = (m_logE_max - m_logE_min) / (nbins+1);

    // Loop over all energy bins
    for (int i = 0; i < nbins; ++i) {

        // Get logE of energy bin
        double logE = m_logE_min + i * logE_bin;

        // Initialise cache with cumulative pixel fluxes and compute total flux
        // in response table for normalization. Negative pixels are excluded
        // from the cumulative map.
        double total_flux = 0.0; // units: events/s/MeV
        double dx         = 0.5 * detx_bin;
        double dy         = 0.5 * dety_bin;
        double detx       = m_detx_min + dx;
        for (int ix = 0; ix < m_num_detx; ++ix, detx += detx_bin) {
            double dety = m_dety_min + dy;
            for (int iy = 0; iy < m_num_dety; ++iy, dety += dety_bin) {

                // Compute intensities
                double i0 = (*this)(logE, detx,    dety);
                double i1 = (*this)(logE, detx-dx, dety-dy);
                double i2 = (*this)(logE, detx,    dety-dy);
                double i3 = (*this)(logE, detx+dx, dety-dy);
                double i4 = (*this)(logE, detx+dx, dety);
                double i5 = (*this)(logE, detx+dx, dety+dy);
                double i6 = (*this)(logE, detx,    dety+dy);
                double i7 = (*this)(logE, detx-dx, dety+dy);
                double i8 = (*this)(logE, detx-dx, dety);

                // Compute solid angle of the 8 pixel wedges
                double s1 = solid_angle(detx, dety, detx-dx, dety-dy, detx,    dety-dy);
                double s2 = solid_angle(detx, dety, detx,    dety-dy, detx+dx, dety-dy);
                double s3 = solid_angle(detx, dety, detx+dx, dety-dy, detx+dx, dety);
                double s4 = solid_angle(detx, dety, detx+dx, dety,    detx+dx, dety+dy);
                double s5 = solid_angle(detx, dety, detx+dx, dety+dy, detx,    dety+dy);
                double s6 = solid_angle(detx, dety, detx,    dety+dy, detx-dx, dety+dy);
                double s7 = solid_angle(detx, dety, detx-dx, dety+dy, detx-dx, dety);
                double s8 = solid_angle(detx, dety, detx-dx, dety,    detx-dx, dety-dy);

                // Compute flux by summing the flux in 8 pixel wedges
                double flux1 = s1 * (i1 + i2 + i0);
                double flux2 = s2 * (i2 + i3 + i0);
                double flux3 = s3 * (i3 + i4 + i0);
                double flux4 = s4 * (i4 + i5 + i0);
                double flux5 = s5 * (i5 + i6 + i0);
                double flux6 = s6 * (i6 + i7 + i0);
                double flux7 = s7 * (i7 + i8 + i0);
                double flux8 = s8 * (i8 + i1 + i0);
                double flux  = (flux1 + flux2  + flux3  + flux4 +
                                flux5 + flux6  + flux7  + flux8) / 3.0;

                // Sum flux
                if (flux > 0.0) {
                    total_flux += flux;
                }

            } // endfor: loop over DETY

        } // endfor: loop over DETX

        // Set energy value (unit independent)
        GEnergy energy;
        energy.log10(logE, m_background.axis_lo_unit(m_inx_energy));

        // Only append node if flux is positive
        if (total_flux > 0.0) {
            m_mc_spectrum.append(energy, total_flux);
        }

        // Dump spectrum for debugging
        #if defined(G_DEBUG_MC_INIT)
        std::cout << "Energy=" << energy;
        std::cout << " Rate_total=" << total_flux;
        std::cout << " events/s/MeV" << std::endl;
        #endif

    } // endfor: looped over energy bins

    // Make sure that spectrum is not empty (if this is the case the entire
    // background response table was empty)
    if (m_mc_spectrum.nodes() == 0) {
        std::string msg = "Background response table is empty. Please provide "
                          "a valid three-dimensional background template.";
        throw GException::invalid_value(G_READ, msg);
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Initialise array of maximum background rate
 *
 * Initialises the array m_mc_max that holds the maximum background rate in
 * each DETX-DETY plane of the background model.
 ***************************************************************************/
void GCTABackground3D::init_mc_max_rate(void) const
{
    // Initialise cache
    m_mc_max.clear();

    // Loop over all maps to determine the maximum map intensity in units
    // of events/s/sr/MeV
    for (int iebin = 0; iebin < m_num_energy; ++iebin) {

        // Initialise maximum rate
        double max_rate = 0.0;

        // Loop over DETX-DETY plane
        for (int ix = 0; ix < m_num_detx; ++ix) {
            for (int iy = 0; iy < m_num_dety; ++iy) {

                // Get bin index
                int inx = index(ix, iy, iebin);

                // Get background rate
                double rate = m_background(m_inx_bgd, inx);
                
                // If background rate is larger than maximum then store the
                // background rate as new maximum
                if (rate > max_rate) {
                    max_rate = rate;
                }

            } // endfor: looped over DETY
        } // endfor: looped over DETX

        // Append maximum rate
        m_mc_max.push_back(max_rate);

    } // endif: looped over all maps

    // Return
    return;
}


/***********************************************************************//**
 * @brief Compute solid angle of pixel wedge
 *
 * @param[in] detx1 DETX of first edge.
 * @param[in] dety1 DETY of first edge.
 * @param[in] detx2 DETX of second edge.
 * @param[in] dety2 DETY of second edge.
 * @param[in] detx3 DETX of third edge.
 * @param[in] dety3 DETY of third edge.
 * @return Solid angle (steradians).
 *
 * Estimate the solid angle subtended by 3 coordinates using Huilier's
 * theorem.
 *
 * Below, the definiton of the pixel cornes and sides are shown as used
 * within the code.
 *
 *             a12
 *         1---------2
 *         |        / 
 *         |       /  
 *         |      /   
 *         |     /    
 *      a13|    /a23
 *         |   / 
 *         |  / 
 *         | /
 *         |/
 *         3
 *
 ***************************************************************************/
double GCTABackground3D::solid_angle(const double& detx1, const double& dety1,
                                     const double& detx2, const double& dety2,
                                     const double& detx3, const double& dety3) const
{
    // Initialise solid angle
    double solidangle = 0.0;

    // Set sky directions
	double  theta1 = std::sqrt(detx1 * detx1 + dety1 * dety1);
	double  phi1   = std::atan2(dety1, detx1);
	double  theta2 = std::sqrt(detx2 * detx2 + dety2 * dety2);
	double  phi2   = std::atan2(dety2, detx2);
	double  theta3 = std::sqrt(detx3 * detx3 + dety3 * dety3);
	double  phi3   = std::atan2(dety3, detx3);
    GSkyDir dir1;
    GSkyDir dir2;
    GSkyDir dir3;
    dir1.radec(phi1, gammalib::pihalf - theta1);
    dir2.radec(phi2, gammalib::pihalf - theta2);
    dir3.radec(phi3, gammalib::pihalf - theta3);

    // Compute angular distances between pixel corners
    double a12 = dir1.dist(dir2);
    double a13 = dir1.dist(dir3);
    double a23 = dir2.dist(dir3);

    // Compute solid angle
    double s   = 0.5 * (a12 + a23 + a13);
    solidangle = 4.0 * std::atan(std::sqrt(std::tan(0.5*s) *
                                           std::tan(0.5*(s-a12)) *
                                           std::tan(0.5*(s-a23)) *
                                           std::tan(0.5*(s-a13))));

    // Return solid angle
    return solidangle;
}