ctfindvar.cpp 44.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
/***************************************************************************
 *                ctfindvar - Time variability search tool                 *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2018-2020 by Simon Bonnefoy                              *
 * ----------------------------------------------------------------------- *
 *                                                                         *
 *  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 ctfindvar.cpp
 * @brief Time variability search tool implementation
 * @author Simon Bonnefoy
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "ctfindvar.hpp"
#include "GammaLib.hpp"
#include "GCTALib.hpp"
#include <cmath>

/* __ OpenMP section _____________________________________________________ */
#ifdef _OPENMP
#include <omp.h>
#endif

/* __ Method name definitions ____________________________________________ */
#define G_INX2GTI                                  "ctfindvar::inx2gti(int&)"
#define G_FILL_CUBE                  "ctfindvar::fill_cube(GCTAObservation*)"
#define G_FILL_ALPHA_VECTOR       "ctfindvar::fill_alpha_vector(const int&, "\
                                                           "vector<double>&)"
#define G_INIT_CUBE                              "ctfindvar::init_cube(void)"
#define G_INIT_GTIS                              "ctfindvar::init_gtis(void)"

/* __ Debug definitions __________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Constants __________________________________________________________ */


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

/***********************************************************************//**
 * @brief Void constructor
 *
 * Constructs empty time variability search tool.
 ***************************************************************************/
ctfindvar::ctfindvar(void) : ctobservation(CTFINDVAR_NAME, VERSION)
{
    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Observations constructor
 *
 * param[in] obs Observation container.
 *
 * Constructs time variability search tool from an observation container.
 ***************************************************************************/
ctfindvar::ctfindvar(const GObservations& obs) :
           ctobservation(CTFINDVAR_NAME, VERSION, obs)
{
    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Command line constructor
 *
 * @param[in] argc Number of arguments in command line.
 * @param[in] argv Array of command line arguments.
 *
 * Constructs time variability search tool using command line arguments for
 * user parameter setting.
 ***************************************************************************/
ctfindvar::ctfindvar(int argc, char *argv[]) :
           ctobservation(CTFINDVAR_NAME, VERSION, argc, argv)
{
    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] app search time variability tool.
 *
 * Constructs time variability search  tool from another time variability
 * search tool.
 ***************************************************************************/
ctfindvar::ctfindvar(const ctfindvar& app) : ctobservation(app)
{
    // Initialise members
    init_members();

    // Copy members
    copy_members(app);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Destructor
 *
 * Destructs search time variability tool.
 ***************************************************************************/
ctfindvar::~ctfindvar(void)
{
    // Free members
    free_members();

    // Return
    return;
}


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

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] app Time variability search tool.
 * @return Time variability search tool.
 *
 * Assigns time variability search tool.
 ***************************************************************************/
ctfindvar& ctfindvar::operator=(const ctfindvar& app)
{
    // Execute only if object is not identical
    if (this != &app) {

        // Copy base class members
        this->ctobservation::operator=(app);

        // Free members
        free_members();

        // Initialise members
        init_members();

        // Copy members
        copy_members(app);

    } // endif: object was not identical

    // Return this object
    return *this;
}


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

/***********************************************************************//**
 * @brief Clear time variability search tool
 *
 * Clears time variability search tool.
 ***************************************************************************/
void ctfindvar::clear(void)
{
    // Free members
    free_members();
    this->ctobservation::free_members();
    this->ctool::free_members();

    // Clear base class (needed to conserve tool name and version)
    this->GApplication::clear();

    // Initialise members
    this->ctool::init_members();
    this->ctobservation::init_members();
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Run time variability search tool
 ***************************************************************************/
void ctfindvar::run(void)
{
    // If we're in debug mode then all output is also dumped on the screen
    if (logDebug()) {
        log.cout(true);
    }

    // Get task parameters
    get_parameters();

    // Write input observation container into logger
    log_observations(NORMAL, m_obs, "Input observation");

    // Create GTIs
    init_gtis();

    // Create counts cube
    create_cube();

    // Analyse cube
    analyse_cube();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Save peak significance map and significance distributions
 *
 * Saves the peak significance and source signficance distributions.
 * Optionally, the generated counts cube can also be saved if 'outcube' has
 * been specified.
 ***************************************************************************/
void ctfindvar::save(void)
{
    // Write header
    log_header1(TERSE, "Saving results");

    // Save counts cube if a valid filename is given and the counts cube is
    // not empty
    if ((*this)["outcube"].is_valid()) {

        // Get counts cube output filename
        GFilename outcube = (*this)["outcube"].filename();

        // Save counts cube if it is not empty. Otherwise signal that no
        // counts cube was saved.
        if (!m_counts.is_empty()) {
            m_counts.save(outcube, (*this)["clobber"].boolean());
            log_value(TERSE, "Counts cube file", outcube.url());
        }
        else {
            log_value(TERSE, "Counts cube file",
                      outcube.url()+" (cube is empty, no file created)");
        }

    }

    // Get output map and model filenames
    GFilename outmap   = (*this)["outmap"].filename();
    GFilename outmodel = (*this)["outmodel"].filename();

    // Save output map if the significance map is not empty
    if (!m_peaksigmap.is_empty()) {

        // Create a FITS file for storing the output
        GFits fits;

        // Write the most significant values for each pixel
        m_peaksigmap.write(fits, "PEAKSIGMAP");

        // Write source histograms
        write_source_histograms(fits);

        // Save significance map
        fits.saveto(outmap, (*this)["clobber"].boolean());

        // Log saving
        log_value(TERSE, "Output map file", outmap.url());

    }
    else {
        log_value(TERSE, "Output map file",
                  outmap.url()+" (map is empty, no file created)");
    }

    // Save model definiton XML file if the significance map is not empty.
    // This may store an empty model in case that none of the pixels is
    // above threshold.
    if (!m_peaksigmap.is_empty()) {

        // Save model
        m_model_above_thr.save(outmodel);

        // Log saving
        log_value(TERSE, "Model definition file", outmodel.url());

    }
    else {
        log_value(TERSE, "Model definition file",
                  outmodel.url()+" (map is empty, no file created)");
    }

    // Return
    return;
}


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

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void ctfindvar::init_members(void)
{
    // Initialise members
    m_counts.clear();
    m_gti.clear();
    m_inmodel.clear();
    m_max_sig_dir.clear();
    m_minoff        = 0.0;
    m_sig_threshold = 0.0;
    m_peaksigmap.clear();
    m_pixsigsrc.clear();
    m_tstart.clear();
    m_tstop.clear();
    m_emin.clear();
    m_emax.clear();
    m_model_above_thr.clear();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] app search time variability tool.
 ***************************************************************************/
void ctfindvar::copy_members(const ctfindvar& app)
{
    // Copy members
    m_counts          = app.m_counts;
    m_gti             = app.m_gti;
    m_inmodel         = app.m_inmodel;
    m_max_sig_dir     = app.m_max_sig_dir;
    m_minoff          = app.m_minoff;
    m_sig_threshold   = app.m_sig_threshold;
    m_peaksigmap      = app.m_peaksigmap;
    m_pixsigsrc       = app.m_pixsigsrc;
    m_tstart          = app.m_tstart;
    m_tstop           = app.m_tstop;
    m_emin            = app.m_emin;
    m_emax            = app.m_emax;
    m_model_above_thr = app.m_model_above_thr;

    // Return
    return;
}


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


/***********************************************************************//**
 * @brief Get application parameters
 ***************************************************************************/
void ctfindvar::get_parameters(void)
{
    // Load the observations
    setup_observations(m_obs, true, true, false);

    // Either load model or query source position parameters
    if ((*this)["inmodel"].is_valid()) {
        m_inmodel = GModels((*this)["inmodel"].filename());
    }
    else {
        (*this)["coordsys"].string();
        (*this)["xsrc"].real();
        (*this)["ysrc"].real();
    }

    // Query time limit parameters
    (*this)["tinterval"].real();
    if ((*this)["tmin"].is_valid()) {
        (*this)["tmin"].time();
    }
    if ((*this)["tmax"].is_valid()) {
        (*this)["tmax"].time();
    }

    // Create map to query spatial parameters
    create_map(m_obs);

    // Read energy limits
    m_emin = GEnergy((*this)["emin"].real(), "TeV");
    m_emax = GEnergy((*this)["emax"].real(), "TeV");

    // Get minimum counts for a bin to be considered in Noff calculation
    m_minoff = (*this)["minoff"].real();

    // Get minimum significance to set a source as variable
    m_sig_threshold = (*this)["threshold"].real();

    // Query (hidden) smoothing parameters
    (*this)["smooth_kernel"].string();
    (*this)["smooth_rad"].real();

    // If needed later, query output filenames now
    if (read_ahead()) {
        (*this)["outcube"].query();
        (*this)["outmap"].query();
        (*this)["outmodel"].query();
    }

    // Set number of OpenMP threads
    #ifdef _OPENMP
    int nthreads = (*this)["nthreads"].integer();
    if (nthreads > 0) {
        omp_set_num_threads(nthreads);
    }
    #endif

    // Write parameters into logger
    log_parameters(TERSE);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Initialize Good Time Intervals
 *
 * @exception GException::invalid_value
 *            Invalid start or stop time or insufficient time bins
 *
 * Initialise Good Time Intervals for the variability search.
 ***************************************************************************/
void ctfindvar::init_gtis(void)
{
    // Log header
    log_header1(NORMAL, "Initialise Good Time Intervals");

    // Clear time intervals
    m_gti.clear();

    // Set start and stop times
    m_tstart = get_tstart();
    m_tstop  = get_tstop();

    // Query time interval
    double tinterval = (*this)["tinterval"].real();

    // Compute time bins
    double tstart_sec = m_tstart.secs();
    double tstop_sec  = m_tstop.secs();
    int    bins       = (tstop_sec - tstart_sec) / tinterval + 0.5;

    // Log information
    log_value(NORMAL, "Reference time (mjd)", m_tstart.reference().mjdref());
    log_value(NORMAL, "Start time (sec)",    tstart_sec);
    log_value(NORMAL, "Stop time (sec)",     tstop_sec);
    log_value(NORMAL, "Total time (sec)",    tstop_sec-tstart_sec);
    log_value(NORMAL, "Time interval (sec)", tinterval);
    log_value(NORMAL, "Number of time bins", bins);

    // Throw exception if tstart == tstop
    if (m_tstart == m_tstop) {
        throw GException::invalid_value(G_INIT_GTIS,
                                        "Start time is equal to stop time");
    }
    else if (bins < 2) {
        std::string msg = "Method requires at least two time bins (" +
                          gammalib::str(bins) + " bins found).";
        throw GException::invalid_value(G_INIT_GTIS, msg);
    }

    // Set up Good Time Intervals by appending all intervals that overlap
    // with at least one of the observations
    for (int i = 0; i < bins; ++i) {

        // Get time interval
        GTime tstart(m_tstart + i*tinterval);
        GTime tstop(m_tstart + (i+1.0)*tinterval);
        GGti  gti(tstart, tstop);

        // Make sure there's an observation that overlaps with this GTI
        for (int k = 0; k < m_obs.size(); ++k) {

            // Get CTA observation
            GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[k]);

            // Continue only if observation is valid
            if (obs != NULL) {

                // Add GTI is the time intervals overlap
                if (gti_overlap(obs->gti(), gti) > 0.0) {
                    m_gti.push_back(gti);
                    break;
                }

            } // endif: observation was valid

        } // endfor: looped over observations

    } // endfor: looped over Good Time Intervals

    // Return
    return;
}


/***********************************************************************//**
 * @brief Create counts cube
 *
 * Creates a counts cube comprising a sky map for each Good Time Interval.
 ***************************************************************************/
void ctfindvar::create_cube(void)
{
    // Log header
    log_header1(NORMAL, "Create counts cube");

    // Create the basic skymap
    m_counts = create_map(m_obs);

    // Resize to the appropriate number of time intervals
    m_counts.nmaps(m_gti.size());

    // Create the peaksigmap
    m_peaksigmap = m_counts.extract(1);

    // Loop over all unbinned CTA observations in the container
    #pragma omp parallel for
    for (int i = 0; i < m_obs.size(); ++i) {

        // Get pointer to observation
        GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[i]);

        // Fill the cube
        fill_cube(obs);

        // Dispose events to free memory
        obs->dispose_events();

    } // endfor: looped over observations

    // Smooth the maps if requested
    if ((*this)["smooth_kernel"].string() != "NONE") {
        m_counts.smooth((*this)["smooth_kernel"].string(),
                        (*this)["smooth_rad"].real());
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Fill the cube from the events in an observation
 *
 * @param[in] obs Pointer to CTA observation.
 *
 * Fills the cube from the events in an observation.
 ***************************************************************************/
void ctfindvar::fill_cube(GCTAObservation* obs)
{
    // Make sure that the observation holds a CTA event list. If this
    // is not the case then throw an exception.
    const GCTAEventList* events = dynamic_cast<const GCTAEventList*>
                                  (obs->events());
    if (events == NULL) {
        std::string msg = "CTA Observation does not contain an event "
                          "list. An event list is needed to fill the "
                          "counts cube.";
        throw GException::invalid_value(G_FILL_CUBE, msg);
    }

    // Get the RoI
    const GCTARoi& roi = events->roi();

    // Check for RoI sanity
    if (!roi.is_valid()) {
        std::string msg = "No valid RoI found in input observation "
                          "\""+obs->name()+"\". Run ctselect to specify "
                          "an RoI for this observation before running "
                          "ctbin.";
        throw GException::invalid_value(G_FILL_CUBE, msg);
    }

    // Initialise binning statistics
    int num_outside_roi  = 0;
    int num_invalid_wcs  = 0;
    int num_outside_ecut = 0;
    int num_outside_map  = 0;
    int num_outside_time = 0;
    int num_in_map       = 0;

    // Fill counts sky map
    for (int i = 0; i < events->size(); ++i) {

        // Get event
        const GCTAEventAtom* event = (*events)[i];

        // Check that the energy is valid
        if ((event->energy() < m_emin) || (event->energy() > m_emax)) {
            num_outside_ecut++;
            continue;
        }

        // Determine event time index
        int time_indx = time2inx(event->time());

        // Check if event is in the GTIs
        if ((time_indx > -1) && (time_indx < m_counts.nmaps())) {

            // Get event direction
            GSkyDir evnt_dir = GCTAInstDir(event->dir()).dir();

            // Skip event if it is outside the RoI
            if (roi.centre().dir().dist_deg(evnt_dir) > roi.radius()) {
                num_outside_roi++;
                continue;
            }

            // Determine sky pixel
            GSkyPixel pixel;
            try {
                pixel = m_counts.dir2pix(evnt_dir);
            }
            catch (std::exception &e) {
                num_invalid_wcs++;
                continue;
            }

            // Skip event if corresponding counts cube pixel is outside the
            // counts cube map range
            if (pixel.x() < -0.5 || pixel.x() > (m_counts.nx()-0.5) ||
                pixel.y() < -0.5 || pixel.y() > (m_counts.ny()-0.5)) {
                num_outside_map++;
                continue;
            }

            // Fill event in skymap
            #pragma omp critical(ctfindvar_fill_cube)
            m_counts(pixel, time_indx) += 1.0;

            // Increment number of maps
            num_in_map++;

        }

        // ... otherwise, event falls outside the specified time range
        else {
            num_outside_time++;
        }

    } // endfor: looped over all events

    // Log filling results
    #pragma omp critical(ctfindvar_fill_cube)
    {
        log_header3(TERSE, get_obs_header(obs));
        log_value(NORMAL, "Events in list", obs->events()->size());
        log_value(NORMAL, "Events in cube", num_in_map);
        log_value(NORMAL, "Events outside RoI", num_outside_roi);
        log_value(NORMAL, "Events outside energy", num_outside_ecut);
        log_value(NORMAL, "Events with invalid WCS", num_invalid_wcs);
        log_value(NORMAL, "Events outside cube area", num_outside_map);
        log_value(NORMAL, "Events outside time bins", num_outside_time);
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Analyse all pixels of counts cube
 ***************************************************************************/
void ctfindvar::analyse_cube(void)
{
    // Log header
    log_header1(NORMAL, "Analyse sky map pixels");

    // Get number of GTIs
    const int nbins = m_gti.size();

    // Get relevant sky map pixels
    std::vector<int> srcInxPix = get_pixels();

    // Preparing the histogram with significance evolution for the source
    // center and the highest sig-pix
    m_pixsigsrc = GNdarray(srcInxPix.size(), nbins);
    m_pixsigmax = GNdarray(nbins);

    // Initialise maximum significance
    double max_sig = 0;

    // looping over all the pixels in the cube
    #pragma omp parallel for
    for (int ipix = 0; ipix < m_counts.npix(); ++ipix) {

        // Getting the variability significance for the current pixel
        GNdarray pixSig = get_variability_sig(ipix);

        // Getting the significance evolution for the source
        for (int src = 0; src < srcInxPix.size(); ++src) {

            // Store the distribution if the source is located at this position
            if (srcInxPix[src] == ipix) {

                #pragma omp critical(ctfindvar_analyse_cube)
                for (int i = 0; i < nbins; i++) {
                    m_pixsigsrc(src,i) = pixSig(i);
                }
            }

        } // endfor: looped over sources

        // Make sure that this code is not executed in parallel
        #pragma omp critical(ctfindvar_analyse_cube)
        {  
            // Determine the pixel with the highest significance
            if (max(pixSig) > max_sig) {
                max_sig       = max(pixSig);
                m_max_sig_dir = m_counts.inx2dir(ipix);
                m_pixsigmax   = pixSig;
            }

            // Storing sig in skymap
            m_peaksigmap(ipix) = max(pixSig);

            // If the significance is greater than the significance threshold,
            // the position is stored in a model
            if (max(pixSig) > m_sig_threshold) {
                GSkyDir dir_pix = m_counts.inx2dir(ipix);
                m_model_above_thr.append(sky_model(dir_pix));
            }
        }

    } // endfor: looped over pixels

    // Log results
    log_value(NORMAL, "Maximum significance", max_sig);
    log_value(NORMAL, "Right Ascension of maximum", m_max_sig_dir.ra_deg());
    log_value(NORMAL, "Declination of maximum", m_max_sig_dir.dec_deg());

    // Return
    return;
}


/***********************************************************************//**
 * @brief Return pixel vector
 *
 * @return Vector of sky map pixels
 *
 * Returns a vector of sky map pixels that corresponds to the source model
 * positions.
 ***************************************************************************/
std::vector<int> ctfindvar::get_pixels(void)
{
    // Initialise pixel array
    std::vector<int> srcInxPix;

    // If there are input models then extract
    if (m_inmodel.size() > 0) {

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

            // Extract the model
            GModelSky* model = dynamic_cast<GModelSky*>(m_inmodel[i]);

            // If model is a sky model then extract the model centre. Note
            // that this only works for a model that results a GSkyRegionCircle
            // object as region.
            if (model != NULL) {

                // Get the source position
                const GModelSpatial*    spatial = model->spatial();
                const GSkyRegion*       region  = spatial->region();
                const GSkyRegionCircle* circle  = dynamic_cast<const GSkyRegionCircle*>(region);

                // If region circle is valid then
                if (circle != NULL) {
                    int ipix = m_counts.dir2inx(circle->centre());
                    srcInxPix.push_back(ipix);
                    continue;
                }

            } // endif: model was a sky model

            // If we are still alive then remove the model since it is neither
            // a sky model, nor does it have a region circle
            m_inmodel.remove(i);
            i--;

        } // endfor: looped over all models

    } // endif: there were input models

    // ... otherwise query the source position
    else {

        // Query source direction
        GSkyDir dir;
        if ((*this)["coordsys"].string() == "CEL") {
            dir.radec_deg((*this)["xsrc"].real(),(*this)["ysrc"].real());
        }
        else {
            dir.lb_deg((*this)["xsrc"].real(),(*this)["ysrc"].real());
        }

        // Store the index of this source
        int ipix = m_counts.dir2inx(dir);
        srcInxPix.push_back(ipix);

    } // endelse: queried source position

    // Return pixel array
    return srcInxPix;
}


/***********************************************************************//**
 * @brief Return sky model for a given sky direction
 *
 * @param[in]  dir Sky direction
 * @return Sky model for a given sky direction
 *
 * Returns a point source sky model at the position of the current pixel
 * with a power law spectral model corresponding to 1% of the Crab flux.
 *
 * The model name is built from the celestial coordinates of the source.
 ***************************************************************************/
GModelSky ctfindvar::sky_model(const GSkyDir& dir) const
{
    // Set point source spatial component from sky direction
    GModelSpatialPointSource spatial(dir);

    // Set fake spectral component (powerlaw with 1% of Crab)
    GModelSpectralPlaw spectral(5.7e-18, -2.48, GEnergy(0.3, "TeV"));

    // Create a sky model
    GModelSky model(spatial, spectral);

    // Build model name from celestial coordinates
    double      ra   = dir.ra_deg();
    double      dec  = dir.dec_deg();
    std::string name = gammalib::str(ra, 4);
    if (dec < 0.0) {
        name += "-";
    }
    else {
        name += "+";
    }
    name += gammalib::str(std::abs(dec), 4);

    // Set model name
    model.name(name);

    // Return model
    return model;
}


/***********************************************************************//**
 * @brief Get the significance of variability for a given skymap pixel
 * 
 * @param[in] ipix Sky map pixel index.
 * @return Histogram of significances.
 * 
 * Significance is computed according to Li & Ma equation 17:
 *    see: https://doi.org/10.1086/161295
 * Some modification is made in order to handle the case where Non = 0, 
 * but Noff != 0.
 ***************************************************************************/
GNdarray ctfindvar::get_variability_sig(const int& ipix)
{
    // Initialise result
    GNdarray sig_histogram(m_gti.size());

    // Initialise vectors
    std::vector<bool> accepted_bin_bckg_vector(m_gti.size(), true);

    // Get alpha values for specified pixel
    std::vector<double> alphas = get_alphas(ipix);

    // Exclude all bins from the background estimate for which the
    // number of events is below "minoff" or for which alpha is zero
    for (int i = 0; i < m_gti.size(); ++i) {
        if (m_counts(ipix, i) < m_minoff || alphas[i] == 0.0) {
            accepted_bin_bckg_vector[i] = false;
        }
    }

    // Loop over pixels until all background pixels are removed
    bool background_validated = false;
    while (background_validated == false) {

        // Signal that background was validated
        background_validated = true;

        // Loop over all the GTIs of the pixel
        for (int i = 0; i < m_gti.size(); ++i) {

            // The GTI is discarded from background calculation and not
            // checked again
            if (!accepted_bin_bckg_vector[i]) {
                continue;
            }

            // ... otherwise GTI is selected, and we loop over all the
            // others
            double noff  = 0.0;
            double alpha = 0.0;
            for (int j = 0; j < m_gti.size(); ++j) {
                if (j != i && accepted_bin_bckg_vector[j]) {
                    noff  += m_counts(ipix, j);
                    alpha += alphas[j];
                }
            }

            // The background is averaged on the number of bins -1
            double non = m_counts(ipix, i);
            alpha      = alphas[i]/alpha;

            // Compute sensitivity in Gaussian sigma using Li & Ma
            double alpha1 = alpha + 1.0;
            double ntotal = non+noff;
            double arg1   = non/ntotal;
            double arg2   = noff/ntotal;
            double sig    = 0.0;
            if (alpha != 0.0) {
                if (noff == 0.0) {
                    sig = 0.0;
                }
                else if (non > 0.0) {
                    double term1  = non  * std::log((alpha1/alpha)*arg1);
                    double term2  = noff * std::log(alpha1*arg2);
                    sig  = std::sqrt(2.0 * (term1 + term2));
                }
                else {
                    sig = std::sqrt(2.0 * noff * std::log(alpha1));
                }
                sig *= (non < alpha*noff) ? -1.0 : 1.0;
            }

            // Update the significance
            sig_histogram(i) = sig;

            // If bin is significant, it's removed from the background and
            // we loop again
            if (sig > m_sig_threshold) {
                accepted_bin_bckg_vector[i] = false;
                background_validated        = false;
            }

        } // endfor: looped over all GTIs

    } // endwhile: iterate until converged

    // Return significance histogram
    return sig_histogram;
}


/***********************************************************************//**
 * @brief Get alpha vector
 *
 * @param[in] ipix Sky map pixel index
 * @return Vector containing effective exposure
 ***************************************************************************/
std::vector<double> ctfindvar::get_alphas(const int& ipix) const
{
    // Initialise alpha vector
    std::vector<double> alphas(m_gti.size(), 0.0);

    // Convert pixel index into sky direction
    GSkyDir pix_dir = m_counts.inx2dir(ipix);

    // Loop over all observations
    for (int i = 0; i < m_obs.size(); ++i) {

        // Get CTA observation
        const GCTAObservation* obs = dynamic_cast<const GCTAObservation*>(m_obs[i]);

        // Fall through if observation is not valid
        if (obs == NULL) {
            continue;
        }

        // Get RoI. Fall through if  observation does not overlap with this
        // pixel position
        GCTARoi roi        = obs->roi();
        GSkyDir roi_centre = roi.centre().dir();
        if (roi_centre.dist_deg(pix_dir) > roi.radius()) {
            continue;
        }

        // Convert sky direction to instrument direction
        GCTAInstDir instdir = obs->pointing().instdir(pix_dir);

        // Extract the good time intervals of the observation
        const GGti& obs_gti(obs->gti());

        // Loop over all time bins
        for (int j = 0; j < m_gti.size(); ++j) {

            // Make sure observation overlaps with this time interval
            double exposure = gti_overlap(m_gti[j], obs_gti);
            if (exposure > 0.0) {

                // Get IRF response
                const GCTAResponseIrf* rsp =
                      dynamic_cast<const GCTAResponseIrf*>(obs->response());

                // Throw an exception if observation has no instrument response function
                if (rsp == NULL) {
                    std::string msg = 
                        "No response information available for "+
                        get_obs_header(obs)+" to compute IRF background. "
                        "Please specify response information or use "
                        "another background subtraction method.";
                    throw GException::invalid_value(G_FILL_ALPHA_VECTOR, msg);
                }

                // Get IRF background template
                const GCTABackground* bkg = rsp->background();

                // Throw an exception if observation has no IRF background template
                if (bkg == NULL) {
                    std::string msg = 
                        "No IRF background template found in instrument "
                        "response function for "+
                        get_obs_header(obs)+". Please specify an instrument "
                        "response function containing a background template.";
                    throw GException::invalid_value(G_FILL_ALPHA_VECTOR, msg);
                }

                // Add up background rate
                #pragma omp critical(ctfindvar_get_alphas) 
                alphas[j] += exposure * bkg->rate_ebin(instdir, m_emin, m_emax);

            } // endif: exposure was positive

        } // endfor: looped over all time bins

    } // endfor: looped over all observations

    // Return alphas
    return alphas;
} 


/***********************************************************************//**
 * @brief Returns number of seconds that two GTIs overlap
 *
 * @param[in] gti1      First GTI
 * @param[in] gti2      Second GTI
 * @return Number of seconds that @p gti1 and @p gti2 overlap
 ***************************************************************************/
double ctfindvar::gti_overlap(const GGti& gti1, const GGti& gti2) const
{
    // Initialise no overlap
    double overlap = 0.0;

    // Set first and second GTI so that gti_1st starts before gti_2nd
    const GGti& gti_1st = (gti1.tstart() <= gti2.tstart()) ? gti1 : gti2;
    const GGti& gti_2nd = (gti1.tstart()  > gti2.tstart()) ? gti1 : gti2;

    // Compute overlap
    if (gti_1st.tstop() > gti_2nd.tstart()) {
        if (gti_1st.tstop() <= gti_2nd.tstop()) {
            overlap = gti_1st.tstop() - gti_2nd.tstart();
        }
        else if (gti_1st.tstop() > gti_2nd.tstop()) {
            overlap = gti_2nd.tstop() - gti_2nd.tstart();
        }
    }

    // Return overlap
    return overlap;
}


/***********************************************************************//**
 * @brief Get start time
 *
 * @return Start time
 ***************************************************************************/
GTime ctfindvar::get_tstart(void)
{
    // Initialise start time with large unreasonable Julian date
    GTime tstart("JD 999999999");

    // If tmin parameter is valid then set the start time
    if ((*this)["tmin"].is_valid()) {

        // Query tmin parameter
        tstart = (*this)["tmin"].time();

        // Log action
        log_string(NORMAL, "Setting start time \"tmin\" parameter");

    } // endif: tmin parameter was valid

    // ... otherwise set start time from observations
    else {

        // Loop over all observations
        for (int k = 0; k < m_obs.size(); ++k) {

            // Get CTA observation
            GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[k]);

            // Continue only if observation is valid
            if (obs != NULL) {

                // Update start time if the start time of the observation is
                // smaller than the current start time
                if (obs->gti().tstart() < tstart) {
                    tstart = obs->gti().tstart();
                }

            } // endif: observation was valid

        } // endfor: looped over observations

        // Log action
        log_string(NORMAL, "Setting start time from observations");

    } // endelse: no valid time specified

    // Return start time
    return tstart;
}


/***********************************************************************//**
 * @brief Get stop time
 *
 * @return Stop time
 ***************************************************************************/
GTime ctfindvar::get_tstop(void)
{
    // Initialise stop time with small unreasonable Julian date
    GTime tstop("JD 0");

    // If tmax parameter is valid then set the stop time
    if ((*this)["tmax"].is_valid()) {

        // Query tmax parameter
        tstop = (*this)["tmax"].time();

        // Log action
        log_string(NORMAL, "Setting stop time \"tmax\" parameter");

    } // endif: tmax parameter was valid

    // ... otherwise set stop time from observations
    else {

        // Loop over all observations
        for (int k = 0; k < m_obs.size(); ++k) {

            // Get CTA observation
            GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[k]);

            // Continue only if observation is valid
            if (obs != NULL) {

                // Update stop time if the stop time of the observation is
                // larger than the current stop time
                if (obs->gti().tstop() > tstop) {
                    tstop = obs->gti().tstop();
                }

            } // endif: observation was valid

        } // endfor: looped over observations

        // Log action
        log_string(NORMAL, "Setting stop time from observations");

    } // endelse: no valid time specified

    // Return stop time
    return tstop;
}


/***********************************************************************//**
 * @brief Write source histograms in FITS format
 * 
 * @param[in,out] fits FITS file
 *
 * This method creates two FITS binary table extensions and appends them to
 * the FITS file.
 *
 * The first extension is named "SOURCE SIGNIFICANCE" and contains the
 * significance of the variability as function of time bin for the pixel
 * with the maximum significance and for each source.
 *
 * The second extension is named "SOURCE POSITION" and contains the Right
 * Ascension and Declination for the maximum significance pixel and for each
 * source.
 ***************************************************************************/
void ctfindvar::write_source_histograms(GFits& fits)
{
    // Setup data storage for time and source significances
    double   tinterval = (*this)["tinterval"].real();
    int      nbins     = (m_tstop-m_tstart) / tinterval + 0.5;
    int      nsrc      = m_pixsigsrc.shape()[0];
    GNdarray time_info(2, nbins);
    GNdarray max_pixel_info(nbins);
    GNdarray src_info(nsrc, nbins);

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

        // Set time bin mid point
        GTime tstart_bin(m_tstart + i * tinterval);
        GTime tstop_bin(m_tstart + (i+1) * tinterval);
        GTime midpoint((tstop_bin.secs()+tstart_bin.secs())*0.5);

        // Store the time of this bin
        time_info(0,i) = tstart_bin.mjd();
        time_info(1,i) = tstop_bin.mjd();

        // Get the index associated with this time
        int index = time2inx(midpoint);

        // Loop over every source
        for (int k = 0; k < nsrc; ++k) {
            src_info(k,i) = (index >= 0) ? m_pixsigsrc(k,index) : 0.0;
        }

        // Fill maximum pixel information
        max_pixel_info(i) = (index >= 0) ? m_pixsigmax(index) : 0.0;

    } // endfor: looped over time bins

    // Create binary tables
    GFitsBinTable table_signif(nbins);
    GFitsBinTable table_pos(nsrc+1);
    table_signif.extname("SOURCE SIGNIFICANCE");
    table_pos.extname("SOURCE POSITION");

    // Create columns for time bins
    GFitsTableDoubleCol time_start("TSTART", nbins);
    GFitsTableDoubleCol time_stop("TSTOP", nbins);
    GFitsTableDoubleCol time_sigma("MAXSIGPIXEL", nbins);
    time_start.unit("MJD");
    time_stop.unit("MJD");
    time_sigma.unit("sigma");

    // Create columns for source position
    GFitsTableStringCol pos_name("SOURCE", nsrc+1, 20);
    GFitsTableDoubleCol pos_ra("RA", nsrc+1);
    GFitsTableDoubleCol pos_dec("DEC", nsrc+1);
    pos_ra.unit("deg");
    pos_dec.unit("deg");

    // Fill time bin columns
    for (int i = 0; i < nbins; ++i) {
        time_start(i) = time_info(0,i);
        time_stop(i)  = time_info(1,i);
        time_sigma(i) = max_pixel_info(i);
    }

    // Fill source columns
    pos_name(0) = "MAXSIGPIXEL";
    pos_ra(0)   = m_max_sig_dir.ra_deg();
    pos_dec(0)  = m_max_sig_dir.dec_deg();

    // Append columns to tables
    table_signif.append(time_start);
    table_signif.append(time_stop);
    table_signif.append(time_sigma);

    // Append the distribution for each source
    for (int k = 0; k < nsrc; ++k) {

        // Initialise source name and direction
        std::string src_name("SOURCE");
        GSkyDir     src_dir;

        // Get the name from the input model file
        if (m_inmodel.size() > k) {

            // Extract the model
            GModelSky* model = dynamic_cast<GModelSky*>(m_inmodel[k]);

            // If model is a sky model then extract the model centre. Note
            // that this only works for a model that results a GSkyRegionCircle
            // object as region.
            if (model != NULL) {

                // Get the source position
                const GModelSpatial*    spatial = model->spatial();
                const GSkyRegion*       region  = spatial->region();
                const GSkyRegionCircle* circle  = dynamic_cast<const GSkyRegionCircle*>(region);

                // If region circle is valid then extract source name and
                // sky direction
                if (circle != NULL) {
                    src_name = m_inmodel[k]->name();
                    src_dir  = circle->centre();
                }

            } // endif: model was a sky model

        } // endif: there were enough models in the input model

        // ... otherwise set the position from the xsrc and ysrc parameters
        else {
            if ((*this)["coordsys"].string() == "CEL") {
                src_dir.radec_deg((*this)["xsrc"].real(), (*this)["ysrc"].real());
            }
            else {
                src_dir.lb_deg((*this)["xsrc"].real(), (*this)["ysrc"].real());
            }
        }

        // Create new time column for source
        GFitsTableDoubleCol column(src_name, nbins);
        column.unit("sigma");

        // Fill column
        for (int i = 0; i < nbins; ++i) {
            column(i) = src_info(k, i);
        }

        // Append column to time table
        table_signif.append(column);

        // Store source infirmation
        pos_name(k+1) = src_name;
        pos_ra(k+1)   = src_dir.ra_deg();
        pos_dec(k+1)  = src_dir.dec_deg();

    } // endfor: looped over sources

    // Append columns to tables
    table_pos.append(pos_name);
    table_pos.append(pos_ra);
    table_pos.append(pos_dec);

    // Append tables to FITS file
    fits.append(table_signif);
    fits.append(table_pos);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Get the map index associated with a given time
 *
 * @param[in] time Time
 * @return Index of map in counts cube
 ***************************************************************************/
int ctfindvar::time2inx(const GTime& time) const
{
    // Set default return value
    int map_index = -1;

    // Loop over all GTIs
    for (int i = 0; i < m_gti.size(); ++i) {

        // If interval contains the time then break
        if (m_gti[i].contains(time)) {
            map_index = i;
            break;
        }

    }

    // Return map index
    return map_index;
}