/***********************************************************************//** * @brief Initialise Monte Carlo cache * * @todo Verify assumption made about the solid angles of the response table * elements. * @todo Add optional sampling on a finer spatial grid. ***************************************************************************/ void GCTABackgroundPerfTable::init_mc_cache(void) const { // Initialise cache m_mc_spectrum.clear(); // Compute solid angle of model double solidangle = this->solidangle(); // Loop over nodes for (int i = 0; i < size(); ++i) { // Set energy GEnergy energy; energy.log10TeV(m_logE[i]); // Compute total rate #if defined(G_LOG_INTERPOLATION) double total_rate = std::pow(10.0, m_background[i]) * solidangle; #else double total_rate = m_background[i] * solidangle; #endif // Set node if (total_rate > 0.0) { m_mc_spectrum.append(energy, total_rate); } } // Return return; }
/***********************************************************************//** * @brief Test CTA psf computation * * The Psf computation is tested by integrating numerically the Psf * function. Integration is done in a rather simplistic way, by stepping * radially away from the centre. The integration is done for a set of * energies from 0.1-10 TeV. ***************************************************************************/ void TestGCTAResponse::test_response_psf(void) { // Load response GCTAResponse rsp; rsp.caldb(cta_caldb); rsp.load(cta_irf); // Integrate Psf GEnergy eng; for (double e = 0.1; e < 10.0; e *= 2.0) { eng.TeV(e); double r = 0.0; double dr = 0.001; int steps = int(1.0/dr); double sum = 0.0; for (int i = 0; i < steps; ++i) { r += dr; sum += rsp.psf(r*deg2rad, 0.0, 0.0, 0.0, 0.0, eng.log10TeV()) * twopi * std::sin(r*deg2rad) * dr*deg2rad; } test_value(sum, 1.0, 0.001, "PSF integration for "+eng.print()); } // Return return; }
/***********************************************************************//** * @brief Test CTA npsf computation ***************************************************************************/ void TestGCTAResponse::test_response_npsf(void) { // Setup CTA response GCTAResponse rsp; rsp.caldb(cta_caldb); rsp.load(cta_irf); // Setup npsf computation GSkyDir srcDir; GEnergy srcEng; GTime srcTime; GCTAPointing pnt; GCTARoi roi; GCTAInstDir instDir; instDir.radec_deg(0.0, 0.0); roi.centre(instDir); roi.radius(2.0); srcEng.TeV(0.1); // Test PSF centred on ROI srcDir.radec_deg(0.0, 0.0); double npsf = rsp.npsf(srcDir, srcEng.log10TeV(), srcTime, pnt, roi); test_value(npsf, 1.0, 1.0e-3, "PSF(0,0) integration"); // Test PSF offset but inside ROI srcDir.radec_deg(1.0, 1.0); npsf = rsp.npsf(srcDir, srcEng.log10TeV(), srcTime, pnt, roi); test_value(npsf, 1.0, 1.0e-3, "PSF(1,1) integration"); // Test PSF outside and overlapping ROI srcDir.radec_deg(0.0, 2.0); npsf = rsp.npsf(srcDir, srcEng.log10TeV(), srcTime, pnt, roi); test_value(npsf, 0.492373, 1.0e-3, "PSF(0,2) integration"); // Test PSF outside ROI srcDir.radec_deg(2.0, 2.0); npsf = rsp.npsf(srcDir, srcEng.log10TeV(), srcTime, pnt, roi); test_value(npsf, 0.0, 1.0e-3, "PSF(2,2) integration"); // Return return; }
/***********************************************************************//** * @brief Return exposure (in units of cm2 s) * * @param[in] dir Coordinate of the true photon position. * @param[in] energy Energy of the true photon. * @return Exposure (in units of cm2 s) ***************************************************************************/ double GCTACubeExposure::operator()(const GSkyDir& dir, const GEnergy& energy) const { // Set indices and weighting factors for interpolation update(energy.log10TeV()); // Perform interpolation double exposure = m_wgt_left * m_cube(dir, m_inx_left) + m_wgt_right * m_cube(dir, m_inx_right); // Make sure that exposure does not become negative if (exposure < 0.0) { exposure = 0.0; } // Return exposure return exposure; }
/***********************************************************************//** * @brief Test CTA Aeff computation ***************************************************************************/ void TestGCTAResponse::test_response_aeff(void) { // Load response GCTAResponse rsp; rsp.caldb(cta_caldb); rsp.load(cta_irf); // Sum over effective area for control GEnergy eng; double sum = 0.0; double ref = 154124059000.00006; //!< Adjust to actual value for (int i = 0; i < 30; ++i) { eng.TeV(pow(10.0, -1.7 + 0.1*double(i))); double aeff = rsp.aeff(0.0, 0.0, 0.0, 0.0, eng.log10TeV()); //std::cout << eng << " " << eng.log10TeV() << " " << aeff << std::endl; sum += aeff; } test_value(sum, ref, 0.1, "Effective area verification"); // Return return; }
/***********************************************************************//** * @brief Return spatially integrated background model * * @param[in] obsEng Measured event energy. * @param[in] obsTime Measured event time. * @param[in] obs Observation. * @return Spatially integrated model. * * @exception GException::invalid_argument * The specified observation is not a CTA observation. * * Spatially integrates the cube background model for a given measured event * energy and event time. This method also applies a deadtime correction * factor, so that the normalization of the model is a real rate * (counts/MeV/s). ***************************************************************************/ double GCTAModelCubeBackground::npred(const GEnergy& obsEng, const GTime& obsTime, const GObservation& obs) const { // Initialise result double npred = 0.0; bool has_npred = false; // Build unique identifier std::string id = obs.instrument() + "::" + obs.id(); // Check if Npred value is already in cache #if defined(G_USE_NPRED_CACHE) if (!m_npred_names.empty()) { // Search for unique identifier, and if found, recover Npred value // and break for (int i = 0; i < m_npred_names.size(); ++i) { if (m_npred_names[i] == id && m_npred_energies[i] == obsEng) { npred = m_npred_values[i]; has_npred = true; #if defined(G_DEBUG_NPRED) std::cout << "GCTAModelCubeBackground::npred:"; std::cout << " cache=" << i; std::cout << " npred=" << npred << std::endl; #endif break; } } } // endif: there were values in the Npred cache #endif // Continue only if no Npred cache value has been found if (!has_npred) { // Evaluate only if model is valid if (valid_model()) { // Get pointer on CTA observation const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(&obs); if (cta == NULL) { std::string msg = "Specified observation is not a CTA" " observation.\n" + obs.print(); throw GException::invalid_argument(G_NPRED, msg); } // Get pointer on CTA cube response const GCTAResponseCube* rsp = dynamic_cast<const GCTAResponseCube*>(cta->response()); if (rsp == NULL) { std::string msg = "Specified observation does not contain" " a cube response.\n" + obs.print(); throw GException::invalid_argument(G_NPRED, msg); } // Get log10 of energy in TeV double logE = obsEng.log10TeV(); // Retrieve CTA background const GCTACubeBackground bgd = rsp->background(); // Integrate the background map at a certain energy npred = bgd.integral(logE); // Store result in Npred cache #if defined(G_USE_NPRED_CACHE) m_npred_names.push_back(id); m_npred_energies.push_back(obsEng); m_npred_times.push_back(obsTime); m_npred_values.push_back(npred); #endif // Debug: Check for NaN #if defined(G_NAN_CHECK) if (gammalib::is_notanumber(npred) || gammalib::is_infinite(npred)) { std::string origin = "GCTAModelCubeBackground::npred"; std::string message = " NaN/Inf encountered (npred=" + gammalib::str(npred) + ")"; gammalib::warning(origin, message); } #endif } // endif: model was valid } // endif: Npred computation required // Multiply in spectral and temporal components npred *= spectral()->eval(obsEng, obsTime); npred *= temporal()->eval(obsTime); // Apply deadtime correction npred *= obs.deadc(obsTime); // Return Npred return npred; }
/***********************************************************************//** * @brief Return simulated list of events * * @param[in] obs Observation. * @param[in] ran Random number generator. * @return Pointer to list of simulated events (needs to be de-allocated by * client) * * @exception GException::invalid_argument * Specified observation is not a CTA observation. * * Draws a sample of events from the background model using a Monte * Carlo simulation. The region of interest, the energy boundaries and the * good time interval for the sampling will be extracted from the observation * argument that is passed to the method. The method also requires a random * number generator of type GRan which is passed by reference, hence the * state of the random number generator will be changed by the method. * * The method also applies a deadtime correction using a Monte Carlo process, * taking into account temporal deadtime variations. For this purpose, the * method makes use of the time dependent GObservation::deadc method. * * For each event in the returned event list, the sky direction, the nominal * coordinates (DETX and DETY), the energy and the time will be set. ***************************************************************************/ GCTAEventList* GCTAModelAeffBackground::mc(const GObservation& obs, GRan& ran) const { // Initialise new event list GCTAEventList* list = new GCTAEventList; // Continue only if model is valid) if (valid_model()) { // Retrieve CTA observation const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(&obs); if (cta == NULL) { std::string msg = "Specified observation is not a CTA " "observation.\n" + obs.print(); throw GException::invalid_argument(G_MC, msg); } // Get pointer on CTA IRF response const GCTAResponseIrf* rsp = dynamic_cast<const GCTAResponseIrf*>(cta->response()); if (rsp == NULL) { std::string msg = "Specified observation does not contain" " an IRF response.\n" + obs.print(); throw GException::invalid_argument(G_MC, msg); } // Retrieve CTA response and pointing const GCTAPointing& pnt = cta->pointing(); // Get pointer to CTA effective area const GCTAAeff* aeff = rsp->aeff(); if (aeff == NULL) { std::string msg = "Specified observation contains no effective area" " information.\n" + obs.print(); throw GException::invalid_argument(G_MC, msg); } // Retrieve event list to access the ROI, energy boundaries and GTIs const GCTAEventList* events = dynamic_cast<const GCTAEventList*>(obs.events()); if (events == NULL) { std::string msg = "No CTA event list found in observation.\n" + obs.print(); throw GException::invalid_argument(G_MC, msg); } // Get simulation region const GCTARoi& roi = events->roi(); const GEbounds& ebounds = events->ebounds(); const GGti& gti = events->gti(); // Get maximum offset value for simulations double max_theta = pnt.dir().dist(roi.centre().dir()) + roi.radius() * gammalib::deg2rad; double cos_max_theta = std::cos(max_theta); // Set simulation region for result event list list->roi(roi); list->ebounds(ebounds); list->gti(gti); // Set up spectral model to draw random energies from. Here we use // a fixed energy sampling for an instance of GModelSpectralNodes. // This is analogous to to the GCTAModelIrfBackground::mc method. // We make sure that only non-negative nodes get appended. GEbounds spectral_ebounds = GEbounds(m_n_mc_energies, ebounds.emin(), ebounds.emax(), true); GModelSpectralNodes spectral; for (int i = 0; i < spectral_ebounds.size(); ++i) { GEnergy energy = spectral_ebounds.elogmean(i); double intensity = aeff_integral(obs, energy.log10TeV()); double norm = m_spectral->eval(energy, events->tstart()); double arg = norm * intensity; if (arg > 0.0) { spectral.append(energy, arg); } } // Loop over all energy bins for (int ieng = 0; ieng < ebounds.size(); ++ieng) { // Compute the background rate in model within the energy // boundaries from spectral component (units: cts/s). // Note that the time here is ontime. Deadtime correction will // be done later. double rate = spectral.flux(ebounds.emin(ieng), ebounds.emax(ieng)); // Debug option: dump rate #if defined(G_DUMP_MC) std::cout << "GCTAModelAeffBackground::mc(\"" << name() << "\": "; std::cout << "rate=" << rate << " cts/s)" << std::endl; #endif // If the rate is not positive then skip this energy bins if (rate <= 0.0) { continue; } // Loop over all good time intervals for (int itime = 0; itime < gti.size(); ++itime) { // Get Monte Carlo event arrival times from temporal model GTimes times = m_temporal->mc(rate, gti.tstart(itime), gti.tstop(itime), ran); // Get number of events int n_events = times.size(); // Reserve space for events if (n_events > 0) { list->reserve(n_events); } // Debug option: provide number of times and initialize // statisics #if defined(G_DUMP_MC) std::cout << " Interval " << itime; std::cout << " times=" << n_events << std::endl; int n_killed_by_deadtime = 0; int n_killed_by_roi = 0; #endif // Loop over events for (int i = 0; i < n_events; ++i) { // Apply deadtime correction double deadc = obs.deadc(times[i]); if (deadc < 1.0) { if (ran.uniform() > deadc) { #if defined(G_DUMP_MC) n_killed_by_deadtime++; #endif continue; } } // Get Monte Carlo event energy from spectral model GEnergy energy = spectral.mc(ebounds.emin(ieng), ebounds.emax(ieng), times[i], ran); // Get maximum effective area for rejection method double max_aeff = aeff->max(energy.log10TeV(), pnt.zenith(), pnt.azimuth(), false); // Skip event if the maximum effective area is not positive if (max_aeff <= 0.0) { continue; } // Initialise randomised coordinates double offset = 0.0; double phi = 0.0; // Initialise acceptance fraction and counter of zeros for // rejection method double acceptance_fraction = 0.0; int zeros = 0; // Start rejection method loop do { // Throw random offset and azimuth angle in // considered range offset = std::acos(1.0 - ran.uniform() * (1.0 - cos_max_theta)); phi = ran.uniform() * gammalib::twopi; // Compute function value at this offset angle double value = (*aeff)(energy.log10TeV(), offset, phi, pnt.zenith(), pnt.azimuth(), false); // If the value is not positive then increment the // zeros counter and fall through. The counter assures // that this loop does not lock up. if (value <= 0.0) { zeros++; continue; } // Value is non-zero so reset the zeros counter zeros = 0; // Compute acceptance fraction acceptance_fraction = value / max_aeff; } while ((ran.uniform() > acceptance_fraction) && (zeros < 1000)); // If the zeros counter is non-zero then the loop was // exited due to exhaustion and the event is skipped if (zeros > 0) { continue; } // Convert CTA pointing direction in instrument system GCTAInstDir mc_dir(pnt.dir()); // Rotate pointing direction by offset and azimuth angle mc_dir.dir().rotate_deg(phi * gammalib::rad2deg, offset * gammalib::rad2deg); // Compute DETX and DETY coordinates double detx(0.0); double dety(0.0); if (offset > 0.0 ) { detx = offset * std::cos(phi); dety = offset * std::sin(phi); } // Set DETX and DETY coordinates mc_dir.detx(detx); mc_dir.dety(dety); // Allocate event GCTAEventAtom event; // Set event attributes event.dir(mc_dir); event.energy(energy); event.time(times[i]); // Append event to list if it falls in ROI if (events->roi().contains(event)) { list->append(event); } #if defined(G_DUMP_MC) else { n_killed_by_roi++; } #endif } // endfor: looped over all events // Debug option: provide statisics #if defined(G_DUMP_MC) std::cout << " Killed by deadtime="; std::cout << n_killed_by_deadtime << std::endl; std::cout << " Killed by ROI="; std::cout << n_killed_by_roi << std::endl; #endif } // endfor: looped over all GTIs } // endfor: looped over all energy boundaries } // endif: model was valid // Return return list; }
/***********************************************************************//** * @brief Return spatially integrated background model * * @param[in] obsEng Measured event energy. * @param[in] obsTime Measured event time. * @param[in] obs Observation. * @return Spatially integrated model. * * @exception GException::invalid_argument * The specified observation is not a CTA observation. * * Spatially integrates the effective area background model for a given * measured event energy and event time. This method also applies a deadtime * correction factor, so that the normalization of the model is a real rate * (counts/MeV/s). ***************************************************************************/ double GCTAModelAeffBackground::npred(const GEnergy& obsEng, const GTime& obsTime, const GObservation& obs) const { // Set number of iterations for Romberg integration. //static const int iter_theta = 6; //static const int iter_phi = 6; // Initialise result double npred = 0.0; bool has_npred = false; // Build unique identifier std::string id = obs.instrument() + "::" + obs.id(); // Check if Npred value is already in cache #if defined(G_USE_NPRED_CACHE) if (!m_npred_names.empty()) { // Search for unique identifier, and if found, recover Npred value // and break for (int i = 0; i < m_npred_names.size(); ++i) { if (m_npred_names[i] == id && m_npred_energies[i] == obsEng) { npred = m_npred_values[i]; has_npred = true; #if defined(G_DEBUG_NPRED) std::cout << "GCTAModelAeffBackground::npred:"; std::cout << " cache=" << i; std::cout << " npred=" << npred << std::endl; #endif break; } } } // endif: there were values in the Npred cache #endif // Continue only if no Npred cache value has been found if (!has_npred) { // Evaluate only if model is valid if (valid_model()) { // Get log10 of energy in TeV double logE = obsEng.log10TeV(); // Spatially integrate effective area component npred = this->aeff_integral(obs, logE); // Store result in Npred cache #if defined(G_USE_NPRED_CACHE) m_npred_names.push_back(id); m_npred_energies.push_back(obsEng); m_npred_times.push_back(obsTime); m_npred_values.push_back(npred); #endif // Debug: Check for NaN #if defined(G_NAN_CHECK) if (gammalib::is_notanumber(npred) || gammalib::is_infinite(npred)) { std::string origin = "GCTAModelAeffBackground::npred"; std::string message = " NaN/Inf encountered (npred=" + gammalib::str(npred) + ")"; gammalib::warning(origin, message); } #endif } // endif: model was valid } // endif: Npred computation required // Multiply in spectral and temporal components npred *= spectral()->eval(obsEng, obsTime); npred *= temporal()->eval(obsTime); // Apply deadtime correction npred *= obs.deadc(obsTime); // Return Npred return npred; }
/***********************************************************************//** * @brief Return spatially integrated background model * * @param[in] obsEng Measured event energy. * @param[in] obsTime Measured event time. * @param[in] obs Observation. * @return Spatially integrated model. * * @exception GException::invalid_argument * The specified observation is not a CTA observation. * * Spatially integrates the instrumental background model for a given * measured event energy and event time. This method also applies a deadtime * correction factor, so that the normalization of the model is a real rate * (counts/MeV/s). ***************************************************************************/ double GCTAModelIrfBackground::npred(const GEnergy& obsEng, const GTime& obsTime, const GObservation& obs) const { // Initialise result double npred = 0.0; bool has_npred = false; // Build unique identifier std::string id = obs.instrument() + "::" + obs.id(); // Check if Npred value is already in cache #if defined(G_USE_NPRED_CACHE) if (!m_npred_names.empty()) { // Search for unique identifier, and if found, recover Npred value // and break for (int i = 0; i < m_npred_names.size(); ++i) { if (m_npred_names[i] == id && m_npred_energies[i] == obsEng) { npred = m_npred_values[i]; has_npred = true; #if defined(G_DEBUG_NPRED) std::cout << "GCTAModelIrfBackground::npred:"; std::cout << " cache=" << i; std::cout << " npred=" << npred << std::endl; #endif break; } } } // endif: there were values in the Npred cache #endif // Continue only if no Npred cache value has been found if (!has_npred) { // Evaluate only if model is valid if (valid_model()) { // Get pointer on CTA observation const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(&obs); if (cta == NULL) { std::string msg = "Specified observation is not a CTA" " observation.\n" + obs.print(); throw GException::invalid_argument(G_NPRED, msg); } // Get pointer on CTA IRF response const GCTAResponseIrf* rsp = dynamic_cast<const GCTAResponseIrf*>(cta->response()); if (rsp == NULL) { std::string msg = "Specified observation does not contain" " an IRF response.\n" + obs.print(); throw GException::invalid_argument(G_NPRED, msg); } // Retrieve pointer to CTA background const GCTABackground* bgd = rsp->background(); if (bgd == NULL) { std::string msg = "Specified observation contains no background" " information.\n" + obs.print(); throw GException::invalid_argument(G_NPRED, msg); } // Get CTA event list const GCTAEventList* events = dynamic_cast<const GCTAEventList*>(obs.events()); if (events == NULL) { std::string msg = "No CTA event list found in observation.\n" + obs.print(); throw GException::invalid_argument(G_NPRED, msg); } // Get reference to ROI centre const GSkyDir& roi_centre = events->roi().centre().dir(); // Get ROI radius in radians double roi_radius = events->roi().radius() * gammalib::deg2rad; // Get log10 of energy in TeV double logE = obsEng.log10TeV(); // Setup integration function GCTAModelIrfBackground::npred_roi_kern_theta integrand(bgd, logE); // Setup integrator GIntegral integral(&integrand); integral.eps(g_cta_inst_background_npred_theta_eps); // Spatially integrate radial component npred = integral.romberg(0.0, roi_radius); // Store result in Npred cache #if defined(G_USE_NPRED_CACHE) m_npred_names.push_back(id); m_npred_energies.push_back(obsEng); m_npred_times.push_back(obsTime); m_npred_values.push_back(npred); #endif // Debug: Check for NaN #if defined(G_NAN_CHECK) if (gammalib::is_notanumber(npred) || gammalib::is_infinite(npred)) { std::string origin = "GCTAModelIrfBackground::npred"; std::string message = " NaN/Inf encountered (npred=" + gammalib::str(npred) + ", roi_radius=" + gammalib::str(roi_radius) + ")"; gammalib::warning(origin, message); } #endif } // endif: model was valid } // endif: Npred computation required // Multiply in spectral and temporal components npred *= spectral()->eval(obsEng, obsTime); npred *= temporal()->eval(obsTime); // Apply deadtime correction npred *= obs.deadc(obsTime); // Return Npred return npred; }