GEbounds.cpp 39.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
/***************************************************************************
 *                  GEbounds.cpp - Energy boundary class                   *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2009-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 GEbounds.cpp
 * @brief Energy boundary class implementation
 * @author Juergen Knoedlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cmath>
#include "GException.hpp"
#include "GTools.hpp"
#include "GFilename.hpp"
#include "GEbounds.hpp"
#include "GEnergies.hpp"
#include "GFits.hpp"
#include "GFitsTable.hpp"
#include "GFitsBinTable.hpp"
#include "GFitsTableDoubleCol.hpp"
#include "GXmlElement.hpp"

/* __ Method name definitions ____________________________________________ */
#define G_READ_XML                             "GEbounds::read(GXmlElement&)"
#define G_WRITE_XML                           "GEbounds::write(GXmlElement&)"
#define G_REMOVE                                     "GEbounds::remove(int&)"
#define G_EMIN                                         "GEbounds::emin(int&)"
#define G_EMAX                                         "GEbounds::emax(int&)"
#define G_EMEAN                                       "GEbounds::emean(int&)"
#define G_ELOGMEAN                                 "GEbounds::elogmean(int&)"
#define G_EWIDTH                                     "GEbounds::ewidth(int&)"
#define G_INSERT_ENG         "GEbounds::insert_eng(int&, GEnergy&, GEnergy&)"

/* __ Macros _____________________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Debug definitions __________________________________________________ */


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

/***********************************************************************//**
 * @brief Constructor
 ***************************************************************************/
GEbounds::GEbounds(void)
{
    // Initialise class members for clean destruction
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief FITS file constructor
 *
 * @param[in] filename FITS file name.
 *
 * Constructs energy boundaries from a FITS file.
 ***************************************************************************/
GEbounds::GEbounds(const GFilename& filename)
{
    // Initialise members
    init_members();

    // Load FITS file
    load(filename);

    // Return
    return;
}


/***********************************************************************//**
 * @brief XML element constructor
 *
 * @param[in] xml XML element.
 *
 * Constructs energy boundaries from an XML element.
 ***************************************************************************/
GEbounds::GEbounds(const GXmlElement& xml)
{
    // Initialise members
    init_members();

    // Read energy boundaries from XML element
    read(xml);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Energy container constructor
 *
 * @param[in] energies Energy container.
 *
 * Constructs energy boundaries from an energy container.
 ***************************************************************************/
GEbounds::GEbounds(const GEnergies& energies)
{
    // Initialise members
    init_members();

    // Set energy boundaries from energy container
    set(energies);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] ebds Energy boundaries.
 ***************************************************************************/
GEbounds::GEbounds(const GEbounds& ebds)
{
    // Initialise class members for clean destruction
    init_members();

    // Copy members
    copy_members(ebds);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Single energy band constructor
 *
 * @param[in] emin Minimum energy of the interval.
 * @param[in] emax Maximum energy of the interval.
 *
 * Constructs energy boundaries for one (emin, emax) energy band.
 ***************************************************************************/
GEbounds::GEbounds(const GEnergy& emin, const GEnergy& emax)
{
    // Initialise members
    init_members();

    // Append energies
    append(emin, emax);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Interval constructor
 *
 * @param[in] num Number of energy intervals.
 * @param[in] emin Minimum energy of first interval.
 * @param[in] emax Maximum energy of last interval.
 * @param[in] log Use logarithmic spacing? (defaults to true).
 *
 * Constructs energy boundaries by defining @p num successive energy
 * intervals between @p emin and @p emax. The @p log parameter controls
 * whether the energy spacing is logarihmic (default) or linear.
 ***************************************************************************/
GEbounds::GEbounds(const int& num, const GEnergy& emin, const GEnergy& emax,
                   const bool& log)
{
    // Initialise members
    init_members();

    // Set intervals
    if (log) {
        this->set_log(num, emin, emax);
    }
    else {
        this->set_lin(num, emin, emax);
    }

    // Return
    return;
}


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

    // Return
    return;
}


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

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] ebds Energy boundaries to be assigned.
 * @return Energy boundaries.
 ***************************************************************************/
GEbounds& GEbounds::operator=(const GEbounds& ebds)
{
    // Execute only if object is not identical
    if (this != &ebds) {

        // Free members
        free_members();

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

        // Copy members
        copy_members(ebds);

    } // endif: object was not identical

    // Return this object
    return *this;
}


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

/***********************************************************************//**
 * @brief Clear energy boundaries
 ***************************************************************************/
void GEbounds::clear(void)
{
    // Free members
    free_members();

    // Initialise private members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Clone energy boundaries
 *
 * @return Pointer to deep copy of energy boundaries.
 ***************************************************************************/
GEbounds* GEbounds::clone(void) const
{
    return new GEbounds(*this);
}


/***********************************************************************//**
 * @brief Append energy interval
 *
 * @param[in] emin Minimum energy of interval.
 * @param[in] emax Maximum energy of interval.
 *
 * Appends an energy interval to the end of the energy boundaries
 * container.
 ***************************************************************************/
void GEbounds::append(const GEnergy& emin, const GEnergy& emax)
{
    // Append interval at the end
    insert_eng(m_num, emin, emax);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Insert energy interval
 *
 * @param[in] emin Minimum energy of interval.
 * @param[in] emax Maximum energy of interval.
 *
 * Inserts an energy interval into the energy boundaries after the first
 * boundary that has a minimum energy smaller than @p emin. The method
 * implicitely assumes that the intervals are ordered by increasing minimum
 * energy.
 ***************************************************************************/
void GEbounds::insert(const GEnergy& emin, const GEnergy& emax)
{
    // Determine index at which interval should be inserted
    int inx = 0;
    for (; inx < m_num; ++inx) {
        if (emin < m_min[inx])
            break;
    }

    // Insert interval
    insert_eng(inx, emin, emax);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Merge all overlapping or connecting successive energy intervals
 *
 * Merges all overlapping or connecting successive energy intervals. The
 * method implicitely assumes that the intervals are ordered by increasing
 * minimum energy.
 *
 * Note that the method does not actually reduce the memory size but just
 * updates the information on the number of elements in the array.
 ***************************************************************************/
void GEbounds::merge(void)
{
    // Find overlaps
    int i   = 0;
    int num = m_num;
    while (i < num-1) {

        // If current energy interval overlaps with successor then merge both
        // intervals, move all remaining intervals one position up, and
        // reduce the number of elements
        if (m_min[i+1] <= m_max[i]) {
            m_min[i] = (m_min[i] < m_min[i+1]) ? m_min[i] : m_min[i+1];
            m_max[i] = (m_max[i] > m_max[i+1]) ? m_max[i] : m_max[i+1];
            for (int k = i+2; k < num; ++k) {
                m_min[k-1] = m_min[k];
                m_max[k-1] = m_max[k];
            }
            num--;
        }

        // Otherwise increment interval index
        else {
            i++;
        }

    } // endwhile: there were still intervals to check

    // Update number of elements in object
    m_num = num;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Merge energy interval into energy boundaries
 *
 * @param[in] emin Minimum energy of interval.
 * @param[in] emax Maximum energy of interval.
 *
 * Inserts an energy interval into the energy boundaries after the first
 * boundary that has a minimum energy smaller than @p emin and then merges
 * any overlapping or connecting energy boundaries. The method implicitely
 * assumes that the intervals are ordered by increasing minimum energy.
 ***************************************************************************/
void GEbounds::merge(const GEnergy& emin, const GEnergy& emax)
{
    // Determine index at which interval should be inserted
    int inx = 0;
    for (; inx < m_num; ++inx) {
        if (emin < m_min[inx])
            break;
    }

    // Insert interval
    insert_eng(inx, emin, emax);

    // Merge any overlapping energy intervals
    merge();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Remove energy interval
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 *
 * Removes energy interval at @p index from the energy boundaries container.
 * All intervals after the specified @p index are moved forward by one
 * position.
 *
 * Note that the method does not actually reduce the memory size but just
 * updates the information on the number of elements in the array.
 ***************************************************************************/
void GEbounds::remove(const int& index)
{
    #if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_REMOVE, index, 0, m_num-1);
    }
    #endif

    // Move all elements located after index forward
    for (int i = index+1; i < m_num; ++i) {
        m_min[i-1] = m_min[i];
        m_min[i-1] = m_max[i];
    }

    // Reduce number of elements by one
    m_num--;

    // Update attributes
    set_attributes();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Reserve space for energy intervals
 *
 * @param[in] num Number of elements.
 *
 * This method does nothing (it is needed to satisfy the GContainer
 * interface).
 ***************************************************************************/
void GEbounds::reserve(const int& num)
{
    // Return
    return;
}


/***********************************************************************//**
 * @brief Append energy boundaries
 *
 * @param[in] ebds Energy boundaries.
 *
 * Append energy boundaries to the container.
 ***************************************************************************/
void GEbounds::extend(const GEbounds& ebds)
{
    // Do nothing if energy boundaries are empty
    if (!ebds.is_empty()) {

        // Allocate new intervals
        int      num = m_num+ebds.size();
        GEnergy* min = new GEnergy[num];
        GEnergy* max = new GEnergy[num];

        // Initialise index
        int inx = 0;
        
        // Copy existing intervals
        for (; inx < m_num; ++inx) {
            min[inx] = m_min[inx];
            max[inx] = m_max[inx];
        }

        // Append intervals
        for (int i = 0; i < ebds.size(); ++i, ++inx) {
            min[inx] = ebds.m_min[i];
            max[inx] = ebds.m_max[i];
        }

        // Free memory
        if (m_min != NULL) delete [] m_min;
        if (m_max != NULL) delete [] m_max;

        // Set new memory
        m_min = min;
        m_max = max;

        // Set number of elements
        m_num = num;

        // Set attributes
        set_attributes();

    } // endif: energy boundaries were not empty

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set energy boundaries from energy container
 *
 * @param[in] energies Energy container.
 *
 * Sets the energy boundaries from an energy container. Each two subsequent
 * energies in the energy container will form an energy boundary. This
 * means that n energies will lead to n-1 energy boundaries with the
 * following mapping:
 *
 *      [energies[0], energies[1]]
 *      [energies[1], energies[2]]
 *      ...
 *      [energies[n-2], energies[n-1]]
 *
 * If there is only one energy in the container the following empty energy
 * boundary will be appended:
 *
 *      [energies[0], energies[0]]
 ***************************************************************************/
void GEbounds::set(const GEnergies& energies)
{
    // Initialise members
    clear();

    // Get number of energies in container
    int num = energies.size();

    // If there is only one energy in the container then append an empty
    // energy boundary
    if (num == 1) {
        append(energies[0], energies[0]);
    }

    // ... otherwise if there is more than one energy in the container
    // then append subsequent energies as boundaries
    else if (num > 1) {
        for (int i = 0; i < num-1; ++i) {
            append(energies[i], energies[i+1]);
        }
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set linearly spaced energy intervals
 *
 * @param[in] num Number of energy intervals.
 * @param[in] emin Minimum energy of first interval.
 * @param[in] emax Maximum energy of last interval.
 *
 * Creates @p num linearly spaced energy boundaries running from @p emin to
 * @p emax.
 ***************************************************************************/
void GEbounds::set_lin(const int& num, const GEnergy& emin, const GEnergy& emax)
{
    // Initialise members
    clear();

    // Compute bin width
    GEnergy ebin = (emax - emin)/double(num); 

    // Append boundaries
    GEnergy min = emin;
    GEnergy max = emin + ebin;
    for (int i = 0; i < num; ++i) {
        append(min, max);
        min += ebin;
        max += ebin;
    }

    // Set attributes
    set_attributes();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set logarithmically spaced energy intervals
 *
 * @param[in] num Number of energy intervals.
 * @param[in] emin Minimum energy of first interval.
 * @param[in] emax Maximum energy of last interval.
 *
 * Creates @p num logarithmically spaced energy boundaries running from
 * @p emin to @p emax.
 ***************************************************************************/
void GEbounds::set_log(const int& num, const GEnergy& emin, const GEnergy& emax)
{
    // Initialise members
    clear();

    // Compute bin width
    double elogmin = std::log10(emin.MeV());
    double elogmax = std::log10(emax.MeV());
    double elogbin = (elogmax - elogmin)/double(num);

    // Append boundaries
    GEnergy min;
    GEnergy max;
    for (int i = 0; i < num; ++i) {
        min.MeV(std::pow(10.0, double(i)*elogbin   + elogmin));
        max.MeV(std::pow(10.0, double(i+1)*elogbin + elogmin));
        append(min, max);
    }

    // Set attributes
    set_attributes();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Load energy boundaries from FITS file
 *
 * @param[in] filename FITS file name.
 *
 * Loads the energy boundaries from a FITS file.
 *
 * If no extension name is provided, the energy boundaries are loaded from
 * the `EBOUNDS` extension.
 ***************************************************************************/
void GEbounds::load(const GFilename& filename)
{
    // Open FITS file
    GFits fits(filename);

    // Get energy boundary table
    const GFitsTable& table = *fits.table(filename.extname(gammalib::extname_ebounds));

    // Read energy boundaries from table
    read(table);

    // Close FITS file
    fits.close();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Save energy boundaries into FITS file
 *
 * @param[in] filename FITS file name.
 * @param[in] clobber Overwrite an existing energy boundaries extension?
 * @param[in] unit Energy unit
 *
 * Saves energy boundaries 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. Energy boundaries can only be appended to an
 * existing file if the @p clobber flag is set to "true" (otherwise an
 * exception is thrown).
 *
 * The method will append a binary FITS table containing the energy
 * boundaries to the FITS file. The extension name can be specified as part
 * of the @p filename. For example the @p filename
 *
 *      myfile.fits[ENERGY BOUNDARIES]
 *
 * will save the energy boundaries in the `ENERGY BOUNDARIES` extension of
 * the "myfile.fits" file. If the extension exists already in the file it
 * will be replaced, otherwise a new extension will be created. If no
 * extension name is provided, the method will use `EBOUNDS` as the default
 * extension name for energy boundaries.
 ***************************************************************************/
void GEbounds::save(const GFilename&   filename,
                    const bool&        clobber,
                    const std::string& unit) const
{
    // Open or create FITS file (without extension name since the requested
    // extension may not yet exist in the file)
    GFits fits(filename.url(), true);

    // Write energy boundaries to FITS file
    write(fits, filename.extname(gammalib::extname_ebounds), unit);

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

    // Return
    return;
}


/***********************************************************************//**
 * @brief Read energy boundaries from FITS table
 *
 * @param[in] table FITS table.
 *
 * Reads the energy boundaries from a FITS table. The method interprets the
 * energy units provide in the FITS header. If no energy units are found it
 * is assumed that the energies are stored in units of keV.
 ***************************************************************************/
void GEbounds::read(const GFitsTable& table)
{
    // Free members
    free_members();

    // Initialise attributes
    init_members();

    // Extract energy boundary information from FITS table
    m_num = table.integer("NAXIS2");
    if (m_num > 0) {

        // Allocate memory
        m_min = new GEnergy[m_num];
        m_max = new GEnergy[m_num];

        // Get units
        std::string emin_unit = table["E_MIN"]->unit();
        std::string emax_unit = table["E_MAX"]->unit();
        if (emin_unit.empty()) {
            emin_unit = "keV";
        }
        if (emax_unit.empty()) {
            emax_unit = "keV";
        }

        // Copy information
        for (int i = 0; i < m_num; ++i) {
            m_min[i](table["E_MIN"]->real(i), emin_unit);
            m_max[i](table["E_MAX"]->real(i), emax_unit);
        }

        // Set attributes
        set_attributes();

    } // endif: there were channels to read

    // Return
    return;
}


/***********************************************************************//**
 * @brief Write energy boundaries into FITS object
 *
 * @param[in] fits FITS file.
 * @param[in] extname Energy boundary extension name.
 * @param[in] unit Energy units.
 *
 * Writes the energy boundaries into a FITS object. The @p unit parameter
 * specifies in which unit the energies are written. By default, the energy
 * units are keV.
 *
 * @todo Write header keywords.
 ***************************************************************************/
void GEbounds::write(GFits&             fits,
                     const std::string& extname,
                     const std::string& unit) const
{
    // Create energy boundary columns
    GFitsTableDoubleCol cemin("E_MIN", m_num);
    GFitsTableDoubleCol cemax("E_MAX", m_num);

    // Fill energy boundary columns
    for (int i = 0; i < m_num; ++i) {
        cemin(i) = m_min[i](unit);
        cemax(i) = m_max[i](unit);
    }

    // Set energy units
    cemin.unit(unit);
    cemax.unit(unit);

    // Create binary table
    GFitsBinTable table(m_num);
    table.append(cemin);
    table.append(cemax);
    table.extname(extname);

    // If the FITS object contains already an extension with the same
    // name then remove now this extension
    if (fits.contains(extname)) {
        fits.remove(extname);
    }

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

    // Return
    return;
}


/***********************************************************************//**
 * @brief Read energy boundaries from XML element
 *
 * @param[in] xml XML element.
 *
 * @exception GException::invalid_value
 *            Invalid XML format encountered.
 *
 * Read energy boundaries from an XML element. The format of the energy
 * boundaries is
 *
 *     <parameter name="EnergyBoundaries" emin="0.1" emax="10.0"/>
 *
 * The units of the @a emin and @a emax parameters are MeV.
 ***************************************************************************/
void GEbounds::read(const GXmlElement& xml)
{
    // Clear energy boundaries
    clear();

    // Get energy boundaries parameter
    const GXmlElement* par = gammalib::xml_get_par(G_READ_XML, xml,
                                                   "EnergyBoundaries");

    // Extract position attributes
    if (par->has_attribute("emin") && par->has_attribute("emax")) {
        double emin = gammalib::todouble(par->attribute("emin"));
        double emax = gammalib::todouble(par->attribute("emax"));
        append(GEnergy(emin, "MeV"), GEnergy(emax, "MeV"));
    }
    else {
        std::string msg = "Attributes \"emin\" and/or \"emax\" not found"
                          " in XML parameter \"EnergyBoundaries\"."
                          " Please verify the XML format.";
        throw GException::invalid_value(G_READ_XML, msg);
    }

    // Set attribues
    set_attributes();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Write energy boundaries into XML element
 *
 * @param[in] xml XML element.
 *
 * Writes energy boundaries into an XML element. The format of the energy
 * boundaries is
 *
 *     <parameter name="EnergyBoundaries" emin="0.1" emax="10.0"/>
 *
 * The units of the @a emin and @a emax parameters are MeV.
 *
 * This method does nothing if the energy boundaries are empty.
 ***************************************************************************/
void GEbounds::write(GXmlElement& xml) const
{
    // Continue only if there are energy boundaries
    if (!is_empty()) {

        // Get parameter
        GXmlElement* par = gammalib::xml_need_par(G_WRITE_XML, xml,
                                                  "EnergyBoundaries");

        // Write attributes
        par->attribute("emin", gammalib::str(emin().MeV()));
        par->attribute("emax", gammalib::str(emax().MeV()));

    } // endif: energy boundaries were not empty
        
    // Return
    return;
}


/***********************************************************************//**
 * @brief Returns energy bin index for a given energy
 *
 * @param[in] eng Energy.
 * @return Bin index.
 *
 * Returns the energy boundary bin index for a given energy. By convention,
 * the limits for an energy bin are defined as
 *
 *      min <= energy < max
 *
 * i.e. and energy equals to max falls above the largest energy.
 *
 * If the energy falls outside all boundaries, -1 is returned.
 ***************************************************************************/
int GEbounds::index(const GEnergy& eng) const
{
    // Initialise index with 'not found'
    int index = -1;

    // Search all energy boundaries for containment
    for (int i = 0; i < m_num; ++i) {
        if (eng >= m_min[i] && eng < m_max[i]) {
            index = i;
            break;
        }
    }

    // Return index
    return index;
}


/***********************************************************************//**
 * @brief Returns minimum energy for a given energy interval
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 * @return Minimum energy of interval.
 *
 * @exception GException::out_of_range
 *            Specified index is out of range.
 ***************************************************************************/
GEnergy GEbounds::emin(const int& index) const
{
    #if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_EMIN, index, 0, m_num-1);
    }
    #endif

    // Return
    return (m_min[index]);
}


/***********************************************************************//**
 * @brief Returns maximum energy for a given energy interval
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 * @return Maximum energy of interval.
 *
 * @exception GException::out_of_range
 *            Specified index is out of range.
 ***************************************************************************/
GEnergy GEbounds::emax(const int& index) const
{
    #if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_EMAX, index, 0, m_num-1);
    }
    #endif

    // Return
    return (m_max[index]);
}


/***********************************************************************//**
 * @brief Returns mean energy for a given energy interval
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 * @return Mean energy of interval.
 *
 * @exception GException::out_of_range
 *            Specified index is out of range.
 *
 * Computes the mean energy
 * \f$0.5 * (E_{\rm min} + E_{\rm max})\f$
 * for the energy interval @p index.
 ***************************************************************************/
GEnergy GEbounds::emean(const int& index) const
{
    #if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_EMEAN, index, 0, m_num-1);
    }
    #endif

    // Compute mean energy
    GEnergy emean = 0.5 * (m_min[index] + m_max[index]);

    // Return
    return emean;
}


/***********************************************************************//**
 * @brief Returns logarithmic mean energy for a given energy interval
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 * @return Logarithmic mean energy of interval.
 *
 * @exception GException::out_of_range
 *            Specified index is out of range.
 *
 * Computes the logarithmic mean energy
 * \f$10^{0.5 * (\log E_{\rm min} + \log E_{\rm max})}\f$
 * for the energy interval @p index.
 ***************************************************************************/
GEnergy GEbounds::elogmean(const int& index) const
{
    #if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_ELOGMEAN, index, 0, m_num-1);
    }
    #endif

    // Compute logarithmic mean energy
    GEnergy elogmean;
    elogmean.MeV(std::sqrt(m_min[index].MeV() * m_max[index].MeV()));

    // Return
    return elogmean;
}


/***********************************************************************//**
 * @brief Returns energy interval width
 *
 * @param[in] index Energy interval index (0,...,size()-1).
 * @return Energy interval width.
 *
 * @exception GException::out_of_range
 *            Specified index is out of range.
 ***************************************************************************/
GEnergy GEbounds::ewidth(const int& index) const
{
    #if defined(G_RANGE_CHECK)
    // If index is outside boundary then throw an error
    if (index < 0 || index >= m_num) {
        throw GException::out_of_range(G_EWIDTH, index, 0, m_num-1);
    }
    #endif

    // Return
    return (m_max[index]-m_min[index]);
}




/***********************************************************************//**
 * @brief Checks whether energy boundaries contain energy
 *
 * @param[in] eng Energy to be checked.
 * @return True if energy falls in at least one interval, false otherwise.
 *
 * Checks if the energy @p eng falls in at least one of the energy intervals.
 * The method exits when the first matching interval has been found.
 ***************************************************************************/
bool GEbounds::contains(const GEnergy& eng) const
{
    // Initialise test
    bool found = false;

    // Test all energy boundaries
    for (int i = 0; i < m_num; ++i) {
        if (eng >= m_min[i] && eng <= m_max[i]) {
            found = true;
            break;
        }
    }

    // Return result
    return found;
}


/***********************************************************************//**
 * @brief Checks whether energy boundaries contain and energy bin
 *
 * @param[in] emin Minimum energy of bin to be checked.
 * @param[in] emax Maximum energy of bin to be checked.
 * @return True if energy bin [emin, emax] is fully contained inside energy
 * the boundaries, false otherwiese
 *
 * Checks if the energy interval [@p emin, @p emax ] falls is fully contained
 * by energy boundaries
 *
 * @todo This method is so far only correct for contiguous energy boundaries.
 ***************************************************************************/
bool GEbounds::contains(const GEnergy& emin, const GEnergy& emax) const
{
    // Initialise result
    bool contained = false;

    // Check if emin, emax is fully contained within this ebounds
    if (emin >= m_emin && emax <= m_emax) {
        contained = true;
    }

    // Return result
    return contained;
}


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

        // Append information
        result.append("\n"+gammalib::parformat("Number of intervals"));
        result.append(gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Energy range"));
        result.append(emin().print());
        result.append(" - ");
        result.append(emax().print());
    
        // If there are multiple energy bins then append them
        if (chatter >= EXPLICIT) {
            if (size() > 1) {
                for (int i = 0; i < size(); ++i) {
                    result.append("\n");
                    result.append(gammalib::parformat("Energy interval "+
                                  gammalib::str(i)));
                    result.append(emin(i).print());
                    result.append(" - ");
                    result.append(emax(i).print());
                }
            }
        } // endif: chatter was less than explicit

    } // endif: chatter was not silent

    // Return
    return result;
}


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

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void GEbounds::init_members(void)
{
    // Initialise members
    m_num = 0;
    m_emin.clear();
    m_emax.clear();
    m_min = NULL;
    m_max = NULL;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] ebds Energy boundaries.
 ***************************************************************************/
void GEbounds::copy_members(const GEbounds& ebds)
{
    // Copy attributes
    m_num  = ebds.m_num;
    m_emin = ebds.m_emin;
    m_emax = ebds.m_emax;

    // Copy arrays
    if (m_num > 0) {
        m_min = new GEnergy[m_num];
        m_max = new GEnergy[m_num];
        for (int i = 0; i < m_num; ++i) {
            m_min[i] = ebds.m_min[i];
            m_max[i] = ebds.m_max[i];
        }
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete class members
 ***************************************************************************/
void GEbounds::free_members(void)
{
    // Free memory
    if (m_min != NULL) delete [] m_min;
    if (m_max != NULL) delete [] m_max;

    // Signal free pointers
    m_min = NULL;
    m_max = NULL;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Set class attributes
 *
 * Determines the minimum and maximum energy from all intervals. If no
 * interval is present the minimum and maximum energies are cleared.
 ***************************************************************************/
void GEbounds::set_attributes(void)
{
    // If there are intervals then determine the minimum and maximum
    // energy from these intervals ...
    if (m_num > 0) {
        m_emin = m_min[0];
        m_emax = m_max[0];
        for (int i = 1; i < m_num; ++i) {
            if (m_min[i] < m_emin) m_emin = m_min[i];
            if (m_max[i] > m_emax) m_emax = m_max[i];
        }
    }

    // ... otherwise clear the minimum and maximum energy
    else {
        m_emin.clear();
        m_emax.clear();
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Insert energy interval
 *
 * @param[in] index Index after with interval is inserted.
 * @param[in] emin Minimum energy of interval.
 * @param[in] emax Maximum energy of interval.
 *
 * @exception GException::invalid_argument
 *            Minimum energy larger than maximum energy
 *
 * Inserts an energy interval after the specified @p index in the energy
 * boundaries. The method does not reorder the intervals by energy, instead
 * the client needs to determine the approriate @p index.
 *
 * Invalid parameters do not produce any exception, but are handled
 * transparently. If the interval is invalid (i.e. @p emin > @p emax) an
 * exception is thrown. If the @p index is out of the valid range, the
 * index will be adjusted to either the first or the last element.
 ***************************************************************************/
void GEbounds::insert_eng(const int&     index,
                          const GEnergy& emin,
                          const GEnergy& emax)
{
    // Throw an exception if energy interval is invalid
    if (emin > emax) {
        std::string msg = "Invalid energy interval specified. Minimum"
                          " energy "+emin.print(NORMAL)+" can not be"
                          " larger than maximum energy "+
                          emax.print(NORMAL)+".";
        throw GException::invalid_argument(G_INSERT_ENG, msg);
    }

    // Set index
    int inx = index;

    // If inx is out of range then adjust it
    if (inx < 0)     inx = 0;
    if (inx > m_num) inx = m_num;

    // Allocate new intervals
    int      num = m_num+1;
    GEnergy* min = new GEnergy[num];
    GEnergy* max = new GEnergy[num];

    // Copy intervals before index to be inserted
    for (int i = 0; i < inx; ++i) {
        min[i] = m_min[i];
        max[i] = m_max[i];
    }

    // Insert interval
    min[inx] = emin;
    max[inx] = emax;

    // Copy intervals after index to be inserted
    for (int i = inx+1; i < num; ++i) {
        min[i] = m_min[i-1];
        max[i] = m_max[i-1];
    }

    // Free memory
    if (m_min != NULL) delete [] m_min;
    if (m_max != NULL) delete [] m_max;

    // Set new memory
    m_min = min;
    m_max = max;

    // Set number of elements
    m_num = num;

    // Set attributes
    set_attributes();

    // Return
    return;
}