GCTACubeBackground.cpp
21.7 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
/***************************************************************************
* GCTACubeBackground.cpp - CTA cube background class *
* ----------------------------------------------------------------------- *
* copyright (C) 2015-2016 by Michael Mayer *
* ----------------------------------------------------------------------- *
* *
* 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 GCTACubeBackground.cpp
* @brief CTA cube background class implementation
* @author Michael Mayer
*/
/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "GTools.hpp"
#include "GException.hpp"
#include "GMath.hpp"
#include "GRan.hpp"
#include "GFits.hpp"
#include "GFitsBinTable.hpp"
#include "GObservations.hpp"
#include "GCTAEventCube.hpp"
#include "GCTAObservation.hpp"
#include "GCTARoi.hpp"
#include "GCTAInstDir.hpp"
#include "GCTACubeBackground.hpp"
#include "GLog.hpp"
/* __ Method name definitions ____________________________________________ */
#define G_READ "GCTACubeBackground::read(GFits&)"
#define G_MC "GCTACubeBackground::mc(GEnergy&, GTime&, GRan&)"
#define G_FILL "GCTACubeBackground::fill(GObservations&, GLog*)"
/* __ Macros _____________________________________________________________ */
/* __ Coding definitions _________________________________________________ */
#define G_LOG_INTERPOLATION //!< Energy interpolate log10(background rate)
/* __ Debug definitions __________________________________________________ */
//#define G_DEBUG_MC_INIT
//#define G_DEBUG_CACHE
/* __ Constants __________________________________________________________ */
const GEnergy g_energy_margin(1.0e-12, "TeV");
/*==========================================================================
= =
= Constructors/destructors =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Void constructor
***************************************************************************/
GCTACubeBackground::GCTACubeBackground(void)
{
// Initialise class members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief File constructor
*
* @param[in] filename FITS file name.
*
* Construct instance by loading the background information from a FITS file.
***************************************************************************/
GCTACubeBackground::GCTACubeBackground(const GFilename& filename)
{
// Initialise class members
init_members();
// Load background from file
load(filename);
// Return
return;
}
/***********************************************************************//**
* @brief Event cube constructor
*
* @param[in] cube Event cube.
*
* Construct background cube using the same binning and sky projection that
* is used for the event cube.
***************************************************************************/
GCTACubeBackground::GCTACubeBackground(const GCTAEventCube& cube)
{
// Initialise class members
init_members();
// Store energy boundaries
int nebins = cube.ebounds().size();
for (int i = 0; i < nebins; ++i) {
m_energies.append(cube.ebounds().emin(i));
}
if (nebins > 0) {
m_energies.append(cube.ebounds().emax(nebins-1));
}
// Set GNodeArray used for interpolation
set_eng_axis();
// Set background cube to event cube
m_cube = cube.counts();
m_cube.nmaps(m_energies.size());
// Set all background cube pixels to zero as we want to have a clean map
// upon construction
m_cube = 0.0;
// Return
return;
}
/***********************************************************************//**
* @brief Copy constructor
*
* @param[in] bgd Background.
***************************************************************************/
GCTACubeBackground::GCTACubeBackground(const GCTACubeBackground& bgd)
{
// Initialise class members
init_members();
// Copy members
copy_members(bgd);
// Return
return;
}
/***********************************************************************//**
* @brief Destructor
***************************************************************************/
GCTACubeBackground::~GCTACubeBackground(void)
{
// Free members
free_members();
// Return
return;
}
/*==========================================================================
= =
= Operators =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Assignment operator
*
* @param[in] bgd Background cube.
* @return Background cube.
***************************************************************************/
GCTACubeBackground& GCTACubeBackground::operator=(const GCTACubeBackground& bgd)
{
// Execute only if object is not identical
if (this != &bgd) {
// Free members
free_members();
// Initialise private members
init_members();
// Copy members
copy_members(bgd);
} // endif: object was not identical
// Return this object
return *this;
}
/***********************************************************************//**
* @brief Return background rate in units of events/s/MeV/sr
*
* @param[in] dir Reconstructed event position where rate should be computed
* @param[in] energy Energy at which the rate should be computed
*
* Returns the background rate in units of events/s/MeV/sr for a given energy
* and sky coordinate. The method assures that the background rate
* never becomes negative.
*
* The method interpolates logarithmically in the energy direction.
***************************************************************************/
double GCTACubeBackground::operator()(const GCTAInstDir& dir,
const GEnergy& energy) const
{
// Set indices and weighting factors for interpolation
update(energy.log10TeV());
// Perform interpolation
double background = m_wgt_left * m_cube(dir.dir(), m_inx_left) +
m_wgt_right * m_cube(dir.dir(), m_inx_right);
// Make sure that background rate does not become negative
if (background < 0.0) {
background = 0.0;
}
// Return background rate
return background;
}
/*==========================================================================
= =
= Public methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Clear background
*
* This method properly resets the background to an initial state.
***************************************************************************/
void GCTACubeBackground::clear(void)
{
// Free class members (base and derived classes, derived class first)
free_members();
// Initialise members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Clone background
*
* @return Pointer to deep copy of background.
***************************************************************************/
GCTACubeBackground* GCTACubeBackground::clone(void) const
{
return new GCTACubeBackground(*this);
}
/***********************************************************************//**
* @brief Fill background cube from observation container
*
* @param[in] obs Observation container.
* @param[in] log Pointer to logger (optional).
*
* @exception GException::invalid_value
* No event list found in CTA observations.
*
* Set the background cube by computing the livetime weighted background rate
* for all CTA observations in an observation container. The cube pixel
* values are computed as the sum over the background rates.
***************************************************************************/
void GCTACubeBackground::fill(const GObservations& obs, GLog* log)
{
// Clear background cube
m_cube = 0.0;
// Setup energy boundaries at the energy values of the background cube
GEbounds ebounds;
for (int i = 0; i < m_energies.size(); ++i) {
ebounds.append(m_energies[i], m_energies[i]);
}
// Initialise event cube to evaluate models
GCTAEventCube eventcube = GCTAEventCube(m_cube, ebounds, obs[0]->events()->gti());
// Initialise total livetime
double total_livetime = 0.0;
// Loop over all observations in container
for (int i = 0; i < obs.size(); ++i) {
// Get observation and continue only if it is a CTA observation
const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(obs[i]);
// Skip observation if it's not CTA
if (cta == NULL) {
if (log != NULL) {
*log << "Skipping ";
*log << obs[i]->instrument();
*log << " observation ";
*log << "\"" << obs[i]->name() << "\"";
*log << " (id=" << obs[i]->id() << ")" << std::endl;
}
continue;
}
// Skip observation if we have a binned observation
if (cta->eventtype() == "CountsCube") {
if (log != NULL) {
*log << "Skipping binned ";
*log << cta->instrument();
*log << " observation ";
*log << "\"" << cta->name() << "\"";
*log << " (id=" << cta->id() << ")" << std::endl;
}
continue;
}
// Announce observation usage
if (log != NULL) {
*log << "Including ";
*log << cta->instrument();
*log << " observation \"" << cta->name();
*log << "\" (id=" << cta->id() << ")";
*log << " in background cube computation." << std::endl;
}
// Set GTI of actual observations as the GTI of the event cube
eventcube.gti(cta->gti());
// Get observation livetime
double livetime = cta->livetime();
// Loop over all bins in background cube
for (int i = 0; i < eventcube.size(); ++i) {
// Get event bin
GCTAEventBin* bin = eventcube[i];
// Compute model value for event bin. The model value is
// given in counts/MeV/s/sr.
double model = obs.models().eval(*bin, *cta);
// Multiply by livetime to get the correct weighting for
// each observation. We divide by the total livetime later
// to get the background model in units of counts/MeV/s/sr.
model *= livetime;
// Add existing number of counts
model += bin->counts();
// Store cumulated value (units: counts/MeV/sr)
bin->counts(model);
} // endfor: looped over all bins
// Accumulate livetime
total_livetime += livetime;
} // endfor: looped over all observations
// Re-normalize cube to get units of counts/MeV/s/sr
if (total_livetime > 0.0) {
// Loop over all bins in background cube and divide the content
// by the total livetime.
for (int i = 0; i < eventcube.size(); ++i) {
GCTAEventBin* bin = eventcube[i];
double rate = bin->counts() / total_livetime;
bin->counts(rate);
}
// Set background cube values from event cube
m_cube = eventcube.counts();
} // endif: livetime was positive
// Return
return;
}
/***********************************************************************//**
* @brief Compute spatially integrated background rate for a given energy
*
* @param[in] logE Logarithm (base 10) of energy in TeV
* @return Spatially integrated background rate in units of counts/MeV/s
*
* Spatially integrates the background cube at a given energy. This method
* performs an interpolation between the energy maps. The integration is
* performed by summing over all bin contents multiplied by the solid angle
* of the bin.
***************************************************************************/
double GCTACubeBackground::integral(const double& logE) const
{
// Update interpolation cache
update(logE);
// Initialise result
double result = 0.0;
// Loop over all map pixels
for (int i = 0; i < m_cube.npix(); ++i) {
// Get bin value
double value = m_wgt_left * m_cube(i, m_inx_left) +
m_wgt_right * m_cube(i, m_inx_right);
// Sum bin contents
result += value * m_cube.solidangle(i);
}
// Return result
return result;
}
/***********************************************************************//**
* @brief Read background cube from FITS object
*
* @param[in] fits FITS object.
*
* Read the background cube from a FITS object.
***************************************************************************/
void GCTACubeBackground::read(const GFits& fits)
{
// Clear object
clear();
// Get HDUs
const GFitsImage& hdu_bgdcube = *fits.image("Primary");
const GFitsTable& hdu_energies = *fits.table("ENERGIES");
// Read cube
m_cube.read(hdu_bgdcube);
// Read energies
m_energies.read(hdu_energies);
// Set energy node array
set_eng_axis();
// Return
return;
}
/***********************************************************************//**
* @brief Write CTA background cube into FITS object.
*
* @param[in] fits FITS file.
***************************************************************************/
void GCTACubeBackground::write(GFits& fits) const
{
// Write cube
m_cube.write(fits);
// Write energies
m_energies.write(fits);
// Return
return;
}
/***********************************************************************//**
* @brief Load background cube from FITS file
*
* @param[in] filename FITS file.
*
* Loads the background cube from a FITS file.
***************************************************************************/
void GCTACubeBackground::load(const GFilename& filename)
{
// Open FITS file
GFits fits(filename);
// Read background cube
read(fits);
// Close FITS file
fits.close();
// Store filename
m_filename = filename;
// Return
return;
}
/***********************************************************************//**
* @brief Save background cube into FITS file
*
* @param[in] filename background cube FITS file name.
* @param[in] clobber Overwrite existing file? (default: false)
*
* Save the background cube into a FITS file.
***************************************************************************/
void GCTACubeBackground::save(const GFilename& filename,
const bool& clobber) const
{
// Open or create FITS file
GFits fits;
// Write background cube
write(fits);
// Save FITS file
fits.saveto(filename, clobber);
// Store filename
m_filename = filename;
// Return
return;
}
/***********************************************************************//**
* @brief Print background information
*
* @param[in] chatter Chattiness (defaults to NORMAL).
* @return String containing background information.
***************************************************************************/
std::string GCTACubeBackground::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("=== GCTACubeBackground ===");
// Append parameters
result.append("\n"+gammalib::parformat("Cube file")+m_filename);
// Append detailed information only if a map cube exists
if (m_cube.npix() > 0) {
// NORMAL: Append sky map
if (chatter >= NORMAL) {
result.append("\n"+m_cube.print(chatter));
}
// EXPLICIT: Append energy nodes
if (chatter >= EXPLICIT && m_elogmeans.size() > 0) {
result.append("\n"+gammalib::parformat("Cube energy values"));
if (m_elogmeans.size() > 0) {
for (int i = 0; i < m_elogmeans.size(); ++i) {
result.append("\n"+gammalib::parformat(" Map "+gammalib::str(i+1)));
result.append(gammalib::str(std::pow(10.0, m_elogmeans[i])));
result.append(" MeV (log10E=");
result.append(gammalib::str(m_elogmeans[i]));
result.append(")");
}
}
else {
result.append("not specified");
}
}
} // endif: map cube exists
} // endif: chatter was not silent
// Return result
return result;
}
/*==========================================================================
= =
= Private methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Initialise class members
***************************************************************************/
void GCTACubeBackground::init_members(void)
{
// Initialise members
m_filename.clear();
m_cube.clear();
m_energies.clear();
m_elogmeans.clear();
// Initialise cache
m_inx_left = 0;
m_inx_right = 0;
m_wgt_left = 0.0;
m_wgt_right = 0.0;
// Return
return;
}
/***********************************************************************//**
* @brief Copy class members
*
* @param[in] bgd Background.
***************************************************************************/
void GCTACubeBackground::copy_members(const GCTACubeBackground& bgd)
{
// Copy members
m_filename = bgd.m_filename;
m_cube = bgd.m_cube;
m_energies = bgd.m_energies;
m_elogmeans = bgd.m_elogmeans;
// Copy cache
m_inx_left = bgd.m_inx_left;
m_inx_right = bgd.m_inx_right;
m_wgt_left = bgd.m_wgt_left;
m_wgt_right = bgd.m_wgt_right;
// Return
return;
}
/***********************************************************************//**
* @brief Delete class members
***************************************************************************/
void GCTACubeBackground::free_members(void)
{
// Return
return;
}
/***********************************************************************//**
* @brief Set nodes for a logarithmic (base 10) energy axis
*
*
* Set axis nodes so that each node is the logarithm of the energy values.
***************************************************************************/
void GCTACubeBackground::set_eng_axis(void)
{
// Get number of bins
int bins = m_energies.size();
// Clear node array
m_elogmeans.clear();
// Compute nodes
for (int i = 0; i < bins; ++i) {
// Get logE/TeV
m_elogmeans.append(m_energies[i].log10TeV());
} // endfor: looped over energy bins
// Return
return;
}
/***********************************************************************//**
* @brief Update 1D cache
*
* @param[in] logE Log10 energy in TeV.
*
* Updates the 1D interpolation cache. The interpolation cache is composed
* of two indices and weights that define 2 data values of the 2D skymap
* that are used for linear interpolation.
*
* @todo Write down formula
***************************************************************************/
void GCTACubeBackground::update(const double& logE) const
{
// Set value for node array
m_elogmeans.set_value(logE);
// Set indices and weighting factors for interpolation
m_inx_left = m_elogmeans.inx_left();
m_inx_right = m_elogmeans.inx_right();
m_wgt_left = m_elogmeans.wgt_left();
m_wgt_right = m_elogmeans.wgt_right();
// Return
return;
}