GObservations.cpp 37.5 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
/***************************************************************************
 *                GObservations.cpp - Observation container class          *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2009-2019 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 GObservations.cpp
 * @brief Observations container class implementation
 * @author Juergen Knoedlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "GTools.hpp"
#include "GException.hpp"
#include "GFilename.hpp"
#include "GObservations.hpp"
#include "GObservationRegistry.hpp"
#include "GMatrixSparse.hpp"
#include "GOptimizer.hpp"

/* __ Method name definitions ____________________________________________ */
#define G_AT                                        "GObservations::at(int&)"
#define G_SET                       "GObservations::set(int&, GObservation&)"
#define G_APPEND                       "GObservations::append(GObservation&)"
#define G_INSERT                 "GObservations::insert(int&, GObservation&)"
#define G_REMOVE                                "GObservations::remove(int&)"
#define G_EXTEND                      "GObservations::extend(GObservations&)"
#define G_READ                                   "GObservations::read(GXml&)"
#define G_NPRED            "GObservations::npred(std::string&, std::string&)"

/* __ Macros _____________________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Debug definitions __________________________________________________ */


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

/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
GObservations::GObservations(void)
{
    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param obs Observation container.
 ***************************************************************************/
GObservations::GObservations(const GObservations& obs)
{
    // Initialise members
    init_members();

    // Copy members
    copy_members(obs);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Load constructor
 *
 * @param[in] filename XML filename.
 *
 * Construct the observation container by loading all relevant information
 * from a XML file. Please refer to the read() method for more information
 * about the structure of the XML file.
 ***************************************************************************/
GObservations::GObservations(const GFilename& filename)
{
    // Initialise members
    init_members();

    // Load XML file
    load(filename);

    // Return
    return;
}


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

    // Return
    return;
}


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

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

        // Free members
        free_members();

        // Initialise members
        init_members();

        // Copy members
        copy_members(obs);

    } // endif: object was not identical

    // Return this object
    return *this;
}


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

/***********************************************************************//**
 * @brief Clear observations
 ***************************************************************************/
void GObservations::clear(void)
{
    // Free members
    free_members();

    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Clone observations
 *
 * @return Pointer to deep copy of observation container.
 ***************************************************************************/
GObservations* GObservations::clone(void) const
{
    // Clone observations
    return new GObservations(*this);
}


/***********************************************************************//**
 * @brief Return pointer to observation
 *
 * @param[in] index Observation index [0,...,size()-1].
 * @return Observation.
 *
 * @exception GException::out_of_range
 *            Operation index is out of range.
 *
 * Returns a pointer to the observation with specified @p index.
 ***************************************************************************/
GObservation* GObservations::at(const int& index)
{
    // Raise exception if index is out of range
    if (index < 0 || index >= size()) {
        throw GException::out_of_range(G_AT, index, 0, size()-1);
    }

    // Return pointer
    return m_obs[index];
}


/***********************************************************************//**
 * @brief Return pointer to observation (const version)
 *
 * @param[in] index Observation index [0,...,size()-1].
 *
 * @exception GException::out_of_range
 *            Operation index is out of range.
 *
 * Returns a const pointer to the observation with specified @p index.
 ***************************************************************************/
const GObservation* GObservations::at(const int& index) const
{
    // Raise exception if index is out of range
    if (index < 0 || index >= size()) {
        throw GException::out_of_range(G_AT, index, 0, size()-1);
    }

    // Return pointer
    return m_obs[index];
}


/***********************************************************************//**
 * @brief Set observation in container
 *
 * @param[in] index Observation index [0,...,size()-1].
 * @param[in] obs Observation.
 * @return Pointer to deep copy of observation.
 *
 * @exception GException::out_of_range
 *            Observation index is out of range.
 * @exception GException::invalid_value
 *            Observation with same instrument and identifier already
 *            exists in container.
 *
 * Set a deep copy and observation @p obs at the specified @p index in the
 * container.
 ***************************************************************************/
GObservation* GObservations::set(const int& index, const GObservation& obs)
{
    // Compile option: raise exception if index is out of range
    #if defined(G_RANGE_CHECK)
    if (index < 0 || index >= size()) {
        throw GException::out_of_range(G_SET, index, 0, size()-1);
    }
    #endif

    // Raise an exception if an observation with specified instrument and
    // identifier already exists
    int inx = get_index(obs.instrument(), obs.id());
    if (inx != -1 && inx != index) {
        std::string msg =
            "Attempt to set \""+obs.instrument()+"\" observation with"
            " identifier \""+obs.id()+"\" in observation container at"
            " index "+gammalib::str(index)+", but an observation with the"
            " same attributes exists already at index "+gammalib::str(inx)+
            " in the container.\n"
            "Every observation for a given instrument in the observation"
            " container needs a unique identifier.";
        throw GException::invalid_value(G_SET, msg);
    }

    // Delete existing observation
    if (m_obs[index] != NULL) delete m_obs[index];

    // Store pointer to a deep copy of the observation
    m_obs[index] = obs.clone();

    // Return pointer
    return m_obs[index];
}


/***********************************************************************//**
 * @brief Append observation to container
 *
 * @param[in] obs Observation.
 * @return Pointer to deep copy of observation.
 *
 * @exception GException::invalid_value
 *            Observation with same instrument and identifier already
 *            exists in container.
 *
 * Appends a deep copy of an observation to the container.
 ***************************************************************************/
GObservation* GObservations::append(const GObservation& obs)
{
    // Raise an exception if an observation with specified instrument and
    // identifier already exists
    int inx = get_index(obs.instrument(), obs.id());
    if (inx != -1) {
        std::string msg =
            "Attempt to append \""+obs.instrument()+"\" observation with"
            " identifier \""+obs.id()+"\" to observation container, but an"
            " observation with the same attributes exists already at"
            " index "+gammalib::str(inx)+" in the container.\n"
            "Every observation for a given instrument in the observation"
            " container needs a unique identifier.";
        throw GException::invalid_value(G_APPEND, msg);
    }

    // Clone observation
    GObservation* ptr = obs.clone();

    // Append to list
    m_obs.push_back(ptr);

    // Return pointer
    return ptr;
}


/***********************************************************************//**
 * @brief Insert observation into container
 *
 * @param[in] index Observation index [0,...,size()-1].
 * @param[in] obs Observation.
 * @return Pointer to deep copy of observation.
 *
 * @exception GException::out_of_range
 *            Observation index is out of range.
 * @exception GException::invalid_value
 *            Observation with same instrument and identifier already
 *            exists in container.
 *
 * Inserts a deep copy of an observation into the container before the
 * observation with the specified @p index.
 ***************************************************************************/
GObservation* GObservations::insert(const int& index, const GObservation& obs)
{
    // Compile option: raise exception if index is out of range
    #if defined(G_RANGE_CHECK)
    if (is_empty()) {
        if (index > 0) {
            throw GException::out_of_range(G_INSERT, index, 0, size()-1);
        }
    }
    else {
        if (index < 0 || index >= size()) {
            throw GException::out_of_range(G_INSERT, index, 0, size()-1);
        }
    }
    #endif

    // Raise an exception if an observation with specified instrument and
    // identifier already exists
    int inx = get_index(obs.instrument(), obs.id());
    if (inx != -1 && inx != index) {
        std::string msg =
            "Attempt to insert \""+obs.instrument()+"\" observation with"
            " identifier \""+obs.id()+"\" in observation container before"
            " index "+gammalib::str(index)+", but an observation with the"
            " same attributes exists already at index "+gammalib::str(inx)+
            " in the container.\n"
            "Every observation for a given instrument in the observation"
            " container needs a unique identifier.";
        throw GException::invalid_value(G_INSERT, msg);
    }

    // Clone observation
    GObservation* ptr = obs.clone();

    // Clone observation and insert into list
    m_obs.insert(m_obs.begin()+index, ptr);

    // Return pointer
    return ptr;
}


/***********************************************************************//**
 * @brief Remove observation from container
 *
 * @param[in] index Observation index [0,...,size()-1].
 *
 * @exception GException::out_of_range
 *            Observation index is out of range.
 *
 * Removes observation of specified @p index from the container.
 ***************************************************************************/
void GObservations::remove(const int& index)
{
    // Compile option: If index is outside boundary then raise exception
    #if defined(G_RANGE_CHECK)
    if (index < 0 || index >= size()) {
        throw GException::out_of_range(G_REMOVE, index, 0, size()-1);
    }
    #endif

    // Delete observation
    delete m_obs[index];

    // Erase observation component from container
    m_obs.erase(m_obs.begin() + index);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Append observations from observation container
 *
 * @param[in] obs Observations.
 *
 * @exception GException::invalid_value
 *            Observation with same instrument and identifier already
 *            exists in container.
 *
 * Appends deep copies of observations to the container.
 ***************************************************************************/
void GObservations::extend(const GObservations& obs)
{
    // Do nothing if observation container is empty
    if (!obs.is_empty()) {

        // Get size. Note that we extract the size first to avoid an
        // endless loop that arises when a container is appended to
        // itself.
        int num = obs.size();

        // Reserve enough space
        reserve(size() + num);

        // Loop over all observations, clone them and append them to the
        // list
        for (int i = 0; i < num; ++i) {

            // Raise an exception if an observation with specified
            // instrument and identifier already exists
            int inx = get_index(obs[i]->instrument(), obs[i]->id());
            if (inx != -1) {
                std::string msg =
                    "Attempt to append \""+obs[i]->instrument()+"\""
                    " observation with identifier \""+obs[i]->id()+"\""
                    " to observation container, but an observation with the"
                    " same attributes exists already at index "+
                    gammalib::str(inx)+" in the container.\n"
                    "Every observation for a given instrument in the"
                    " observation container needs a unique identifier.";
                throw GException::invalid_value(G_EXTEND, msg);
            }

            // Append observation to container
            m_obs.push_back(obs[i]->clone());
        }

    } // endif: observation container was not empty

    // Return
    return;
}


/***********************************************************************//**
 * @brief Signals if observation exists
 *
 * @param[in] instrument Instrument.
 * @param[in] id Observation identifier.
 * @return True if observation with specified @p instrument and identifier
 *         @p id exists.
 *
 * Searches all observations for a match with the specified @p instrument
 * and @p identifier. If the specified attributes have been found, true is
 * returned.
 ***************************************************************************/
bool GObservations::contains(const std::string& instrument,
                             const std::string& id) const
{
    // Get observation index
    int index = get_index(instrument, id);

    // Return
    return (index != -1);
}


/***********************************************************************//**
 * @brief Load observations from XML file
 *
 * @param[in] filename XML filename.
 *
 * Loads observation from a XML file into the container. Please refer to the
 * read() method for more information about the structure of the XML file.
 ***************************************************************************/
void GObservations::load(const GFilename& filename)
{
    // Clear any existing observations
    clear();

    // Load XML document
    GXml xml(filename.url());

    // Read observations from XML document
    read(xml);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Save observations into XML file
 *
 * @param[in] filename XML filename.
 *
 * Saves observations into a XML file. Please refer to the read() method for
 * more information about the structure of the XML file.
 ***************************************************************************/
void GObservations::save(const GFilename& filename) const
{
    // Declare empty XML document
    GXml xml;

    // Write observations into XML file
    write(xml);

    // Save XML document
    xml.save(filename);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Read observations from XML document
 *
 * @param[in] xml XML document.
 *
 * @exception GException::invalid_instrument
 *            Invalid instrument encountered in XML file.
 *
 * Reads observations from the first observation list that is found in the
 * XML document. The decoding of the instrument specific observation
 * definition is done within the observation's GObservation::read() method.
 * The following file structure is expected:
 *
 *     <observation_list title="observation library">
 *       <observation name="..." id="..." instrument="...">
 *         ...
 *       </observation>
 *       <observation name="..." id="..." instrument="...">
 *         ...
 *       </observation>
 *       ...
 *     </observation_list>
 *
 * The @p name and @p id attributes allow for a unique identification of an
 * observation within the observation container. The @p instrument
 * attributes specifies the instrument to which the observation applies.
 * This attribute will be used to allocate the appropriate instrument
 * specific GObservation class variant by using the GObservationRegistry
 * class.
 *
 * The structure within the @p observation tag is defined by the instrument
 * specific GObservation class.
 *
 * @todo Observation names and IDs are not verified so far for uniqueness.
 *       This would be required to achieve an unambiguous update of parameters
 *       in an already existing XML file when using the write method.
 ***************************************************************************/
void GObservations::read(const GXml& xml)
{
    // Get pointer on observation library
    const GXmlElement* lib = xml.element("observation_list", 0);

    // Loop over all observations
    int n = lib->elements("observation");
    for (int i = 0; i < n; ++i) {

        // Get pointer on observation
        const GXmlElement* obs = lib->element("observation", i);

        // Get attributes
        std::string name       = obs->attribute("name");
        std::string id         = obs->attribute("id");
        std::string instrument = obs->attribute("instrument");

        // Allocate instrument specific observation
        GObservationRegistry registry;
        GObservation*        ptr = registry.alloc(instrument);

        // If observation is valid then read its definition from XML file
        if (ptr != NULL) {

            // Read definition
            ptr->read(*obs);

            // Set attributes
            ptr->name(name);
            ptr->id(id);

        } // endif: observation was valid

        // ... otherwise throw an exception
        else {
            throw GException::invalid_instrument(G_READ, instrument);
        }

        // Append observation to container
        append(*ptr);

        // Free observation (the append method made a deep copy)
        delete ptr;

    } // endfor: looped over all observations

    // Return
    return;
}


/***********************************************************************//**
 * @brief Write observations into XML document
 *
 * @param[in] xml XML document.
 *
 * Write observations into the first observation library that is found in the
 * XML document. In case that no observation library exists, one is added to
 * the document. Please refer to the read() method for more information
 * about the structure of the XML document.
 ***************************************************************************/
void GObservations::write(GXml& xml) const
{
    // If there is no observation library then append one
    if (xml.elements("observation_list") == 0) {
        xml.append(GXmlElement("observation_list title=\"observation list\""));
    }

    // Get pointer on observation library
    GXmlElement* lib = xml.element("observation_list", 0);

    // Write all observations into library
    for (int i = 0; i < size(); ++i) {

        // Initialise pointer on observation
        GXmlElement* obs = NULL;

        // Search corresponding observation
        int n = xml.elements("observation");
        for (int k = 0; k < n; ++k) {
            GXmlElement* element = xml.element("observation", k);
            if (element->attribute("name")       == m_obs[i]->name() &&
                element->attribute("id")         == m_obs[i]->id()   &&
                element->attribute("instrument") == m_obs[i]->instrument()) {
                obs = element;
                break;
            }
        }

        // If no observation with corresponding name, ID and instrument was
        // found then append one now
        if (obs == NULL) {
            obs = lib->append("observation");
            obs->attribute("name", m_obs[i]->name());
            obs->attribute("id", m_obs[i]->id());
            obs->attribute("instrument", m_obs[i]->instrument());
        }

        // Write now observation
        m_obs[i]->write(*obs);

    } // endfor: looped over all observaitons

    // Return
    return;
}


/***********************************************************************//**
 * @brief Load models from XML file
 *
 * @param[in] filename XML filename.
 *
 * Loads the models from a XML file. Please refer to the GModels::read()
 * method for more information about the expected structure of the XML
 * file. 
 ***************************************************************************/
void GObservations::models(const GFilename& filename)
{
    // Load models
    m_models.load(filename);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Optimize model parameters using optimizer
 *
 * @param[in] opt Optimizer.
 *
 * Optimizes the free parameters of the models by using the optimizer
 * that has been provided by the @p opt argument.
 ***************************************************************************/
void GObservations::optimize(GOptimizer& opt)
{
    // Extract optimizer parameter container from model container
    GOptimizerPars pars = m_models.pars();

    // Optimize model parameters
    opt.optimize(m_fct, pars);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Computes parameter errors using optimizer
 *
 * @param[in] opt Optimizer.
 *
 * Calculates the errors of the free parameters of the models by using
 * the optimizer that has been provided by the @p opt argument.
 ***************************************************************************/
void GObservations::errors(GOptimizer& opt)
{
    // Extract optimizer parameter container from model container
    GOptimizerPars pars = m_models.pars();

    // Compute model parameter errors
    opt.errors(m_fct, pars);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Computes parameter errors using hessian matrix and optimizer
 *
 * Calculates the errors of the free model parameters as the square roots
 * of the diagonal elements of the inverse Hessian matrix. The Hessian
 * matrix is computed using finite differences.
 ***************************************************************************/
void GObservations::errors_hessian(void)
{
    // Extract optimizer parameter container from model container
    GOptimizerPars pars = m_models.pars();

    // Get number of parameters
    int npars = pars.size();

    // Compute Hessian matrix
    GMatrixSparse hessian = m_fct.hessian(pars);

    // Signal no diagonal element loading
    bool diag_loaded = false;

    // Loop over error computation (maximum 2 passes)
    for (int i = 0; i < 2; ++i) {

        // Solve: hessian * X = unit
        try {
            GMatrixSparse decomposition = hessian.cholesky_decompose(true);
            GVector unit(npars);
            for (int ipar = 0; ipar < npars; ++ipar) {
                unit[ipar] = 1.0;
                GVector x  = decomposition.cholesky_solver(unit, true);
                if (x[ipar] >= 0.0) {
                    pars[ipar]->factor_error(sqrt(x[ipar]));
                }
                else {
                    pars[ipar]->factor_error(0.0);
                }
                unit[ipar] = 0.0;
            }
        }
        catch (GException::matrix_zero &e) {
            std::cout << "GObservations::errors_hessian: "
                      << "All hessian matrix elements are zero."
                      << std::endl;
            break;
        }
        catch (GException::matrix_not_pos_definite &e) {

            // Load diagonal if this has not yet been tried
            if (!diag_loaded) {

                // Flag errors as inaccurate
                std::cout << "Non-Positive definite hessian matrix encountered."
                          << std::endl;
                std::cout << "Load diagonal elements with 1e-10."
                          << " Fit errors may be inaccurate."
                          << std::endl;

                // Try now with diagonal loaded matrix
                for (int ipar = 0; ipar < npars; ++ipar) {
                    hessian(ipar,ipar) += 1.0e-10;
                }

                // Signal loading
                diag_loaded = true;

                // Try again
                continue;

            } // endif: diagonal has not yet been loaded

            // ... otherwise signal an error
            else {
                std::cout << "Non-Positive definite hessian matrix encountered,"
                          << " even after diagonal loading." << std::endl;
                break;
            }
        }
        catch (std::exception &e) {
            throw;
        }

        // If no error occured then break now
        break;

    } // endfor: looped over error computation

    // Return
    return;
}


/***********************************************************************//**
 * @brief Evaluate function
 *
 * Evaluates the likelihood funtion at the actual set of parameters.
 ***************************************************************************/
void GObservations::eval(void)
{
    // Extract optimizer parameter container from model container
    GOptimizerPars pars = m_models.pars();

    // Compute log-likelihood
    m_fct.eval(pars);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return total number of observed events
 *
 * @return Total number of observed events.
 *
 * Returns the total number of observed events that is container in the
 * observation container.
 ***************************************************************************/
int GObservations::nobserved(void) const
{
    // Initialise number of observed events
    int nobserved = 0;

    // Compute number of observed events
    for (int i = 0; i < size(); ++i) {
        nobserved += (*this)[i]->nobserved();
    }

    // Return number of observed events
    return nobserved;
}


/***********************************************************************//**
 * @brief Return number of predicted events for model with a given @p name
 *
 * @param[in] name Model name.
 * @param[in] instrument Instrument name.
 * @return Total number of predicted events for model.
 *
 * @exception GException::invalid_argument
 *            Model with @p name not found.
 *
 * Returns the total number of predicted events for the model with a given
 * @p name.
 ***************************************************************************/
double GObservations::npred(const std::string& name,
                            const std::string& instrument) const
{
    // Initialise number of predicted events
    double npred = 0.0;

    // Throw an exception if model does not exist
    if (!m_models.contains(name)) {
        std::string msg = "Model \""+name+"\" not found in observation "
                          "container. Please specify a valid model name.";
        throw GException::invalid_argument(G_NPRED, msg);
    }

    // Get pointer to model
    const GModel* model = m_models[name];

    // Continue only if pointer is valid
    if (model != NULL) {
        npred = this->npred(*model, instrument);
    }

    // Return number of predicted events
    return npred;
}


/***********************************************************************//**
 * @brief Return number of predicted events for a given model
 *
 * @param[in] model Model.
 * @param[in] instrument Instrument name.
 * @return Total number of predicted events for model.
 *
 * @exception GException::invalid_argument
 *            Model with @p name not found.
 *
 * Returns the total number of predicted events for the model with a given
 * @p name.
 ***************************************************************************/
double GObservations::npred(const GModel&      model,
                            const std::string& instrument) const
{
    // Initialise number of predicted events
    double npred = 0.0;

    // Compute number of predicted events
    for (int i = 0; i < size(); ++i) {

        // Skip observation if it does not correspond to the specified
        // instrument
        if (!instrument.empty()) {
            if ((*this)[i]->instrument() != instrument) {
                continue;
            }
        }

        // Add only relevant events
        if (model.is_valid(instrument, "")) {
            npred += (*this)[i]->npred(model);
        }

    } // endfor: looped over observations

    // Return number of predicted events
    return npred;
}


/***********************************************************************//**
 * @brief Remove response cache for all models
 *
 * Remove response cache for all models in the container.
 ***************************************************************************/
void GObservations::remove_response_cache(void)
{
    // Loop over all models and remove response cache for each model
    for (int i = 0; i < m_models.size(); ++i) {
        remove_response_cache(m_models[i]->name());
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Remove response cache for model
 *
 * @param[in] name Model name.
 *
 * Remove response cache for model @p name in the container.
 ***************************************************************************/
void GObservations::remove_response_cache(const std::string& name)
{
    // Loop over all observations and remove response cache for the
    // specified source
    for (int i = 0; i < size(); ++i) {
        (*this)[i]->remove_response_cache(name);
    }

    // Return
    return;
}


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

        // Append information
        result.append("\n"+gammalib::parformat("Number of observations"));
        result.append(gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Number of models"));
        result.append(gammalib::str(m_models.size()));
        result.append("\n"+gammalib::parformat("Number of observed events"));
        result.append(gammalib::str(nobserved()));
        result.append("\n"+gammalib::parformat("Number of predicted events"));
        result.append(gammalib::str(npred()));

        // Get reduced chatter level for detailed information
        GChatter reduced_chatter = gammalib::reduce(chatter);

        // Append observations for chatter >= EXPLICIT
        if (chatter >= EXPLICIT) {
            for (int i = 0; i < size(); ++i) {
                result.append("\n");
                result.append((*this)[i]->print(reduced_chatter));
            }
        }

        // Append models for chatter >= VERBOSE
        if (chatter >= VERBOSE) {
            result.append("\n"+m_models.print(reduced_chatter));
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}


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

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void GObservations::init_members(void)
{
    // Initialise members
    m_obs.clear();
    m_models.clear();
    m_fct.set(this);  //!< Makes sure that optimizer points to this instance

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] obs Observation container.
 *
 * Copies all class members. Deep copies are created for the observations,
 * which is what is needed to have a real physical copy of the members.
 ***************************************************************************/
void GObservations::copy_members(const GObservations& obs)
{
    // Copy attributes
    m_models = obs.m_models;
    m_fct    = obs.m_fct;

    // Copy observations
    m_obs.clear();
    for (int i = 0; i < obs.m_obs.size(); ++i) {
        m_obs.push_back((obs.m_obs[i]->clone()));
    }

    // Set likelihood function pointer to this instance. This makes sure
    // that the optimizer points to this instance
    m_fct.set(this);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete class members
 *
 * Deallocates all observations. Since container classes that hold pointers
 * need to handle the proper deallocation of memory, we loop here over all
 * pointers and make sure that we deallocate all observations in the
 * container.
 ***************************************************************************/
void GObservations::free_members(void)
{
    // Free observations
    for (int i = 0; i < m_obs.size(); ++i) {
        delete m_obs[i];
        m_obs[i] = NULL;
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return observation index by instrument and identifier
 *
 * @param[in] instrument Instrument.
 * @param[in] id Observation identifier.
 * @return Observation index (-1 of instrument and observation identifier
 *         has not been found)
 *
 * Returns observation index based on the specified @p instrument and
 * observation identifier @p id. If no observation with the specified
 * attributes has been found, the method returns -1.
 ***************************************************************************/
int GObservations::get_index(const std::string& instrument,
                             const std::string& id) const
{
    // Initialise index
    int index = -1;

    // Search observation with specified instrument and id
    for (int i = 0; i < size(); ++i) {
        if ((m_obs[i]->instrument() == instrument) &&
            (m_obs[i]->id()         == id)) {
            index = i;
            break;
        }
    }

    // Return index
    return index;
}