GammaLib  2.0.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
GCTAModelBackground.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * GCTAModelBackground.cpp - Background model class *
3  * ----------------------------------------------------------------------- *
4  * copyright (C) 2018-2021 by Juergen Knoedlseder *
5  * ----------------------------------------------------------------------- *
6  * *
7  * This program is free software: you can redistribute it and/or modify *
8  * it under the terms of the GNU General Public License as published by *
9  * the Free Software Foundation, either version 3 of the License, or *
10  * (at your option) any later version. *
11  * *
12  * This program is distributed in the hope that it will be useful, *
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15  * GNU General Public License for more details. *
16  * *
17  * You should have received a copy of the GNU General Public License *
18  * along with this program. If not, see <http://www.gnu.org/licenses/>. *
19  * *
20  ***************************************************************************/
21 /**
22  * @file GCTAModelBackground.cpp
23  * @brief Background model class implementation
24  * @author Juergen Knoedlseder
25  */
26 
27 /* __ Includes ___________________________________________________________ */
28 #ifdef HAVE_CONFIG_H
29 #include <config.h>
30 #endif
31 #include "GTools.hpp"
32 #include "GMath.hpp"
33 #include "GModelRegistry.hpp"
36 #include "GModelTemporalConst.hpp"
37 #include "GIntegral.hpp"
39 #include "GCTAModelBackground.hpp"
40 #include "GCTAObservation.hpp"
41 #include "GCTAPointing.hpp"
42 #include "GCTAInstDir.hpp"
43 #include "GCTARoi.hpp"
44 #include "GCTASupport.hpp"
45 
46 /* __ Constants __________________________________________________________ */
47 
48 /* __ Globals ____________________________________________________________ */
50 const GModelRegistry g_cta_background_registry(&g_cta_background_seed);
51 
52 /* __ Method name definitions ____________________________________________ */
53 #define G_EVAL "GCTAModelBackground::eval(GEvent&, GObservation&, bool&)"
54 #define G_NPRED "GCTAModelBackground::npred(GEnergy&, GTime&, GObservation&)"
55 #define G_MC "GCTAModelBackground::mc(GObservation&, GRan&)"
56 #define G_XML_SPATIAL "GCTAModelBackground::xml_spatial(GXmlElement&)"
57 #define G_XML_SPECTRAL "GCTAModelBackground::xml_spectral(GXmlElement&)"
58 #define G_XML_TEMPORAL "GCTAModelBackground::xml_temporal(GXmlElement&)"
59 
60 /* __ Macros _____________________________________________________________ */
61 
62 /* __ Coding definitions _________________________________________________ */
63 
64 /* __ Debug definitions __________________________________________________ */
65 //#define G_DUMP_MC //!< Dump MC information
66 
67 
68 /*==========================================================================
69  = =
70  = Constructors/destructors =
71  = =
72  ==========================================================================*/
73 
74 /***********************************************************************//**
75  * @brief Void constructor
76  *
77  * Constructs an empty background model.
78  ***************************************************************************/
80 {
81  // Initialise members
82  init_members();
83 
84  // Return
85  return;
86 }
87 
88 
89 /***********************************************************************//**
90  * @brief XML constructor
91  *
92  * @param[in] xml XML element.
93  *
94  * Constructs a background model from the information that is found in a XML
95  * element. Please refer to the read() method to learn about the expected
96  * structure of the XML element.
97  ***************************************************************************/
99  GModelData(xml)
100 {
101  // Initialise members
102  init_members();
103 
104  // Read XML
105  read(xml);
106 
107  // Set parameter pointers
108  set_pointers();
109 
110  // Return
111  return;
112 }
113 
114 
115 /***********************************************************************//**
116  * @brief Construct from spatial and spectral components
117  *
118  * @param[in] spatial Spatial model component.
119  * @param[in] spectral Spectral model component.
120  *
121  * Constructs a background model from a @p spatial and a @p spectral model
122  * component. The temporal component is assumed to be constant.
123  ***************************************************************************/
125  const GModelSpectral& spectral) :
126  GModelData()
127 {
128  // Initialise members
129  init_members();
130 
131  // Allocate temporal constant model
133 
134  // Clone model components
135  m_spatial = spatial.clone();
136  m_spectral = spectral.clone();
137  m_temporal = temporal.clone();
138 
139  // Set parameter pointers
140  set_pointers();
141 
142  // Return
143  return;
144 }
145 
146 
147 /***********************************************************************//**
148  * @brief Construct from model components
149  *
150  * @param[in] spatial Spatial model component.
151  * @param[in] spectral Spectral model component.
152  * @param[in] temporal Temporal model component.
153  *
154  * Constructs a background model from a @p spatial, a @p spectral and a
155  * @p temporal model component.
156  ***************************************************************************/
158  const GModelSpectral& spectral,
159  const GModelTemporal& temporal) :
160  GModelData()
161 {
162  // Initialise members
163  init_members();
164 
165  // Clone model components
166  m_spatial = spatial.clone();
167  m_spectral = spectral.clone();
168  m_temporal = temporal.clone();
169 
170  // Set parameter pointers
171  set_pointers();
172 
173  // Return
174  return;
175 }
176 
177 
178 /***********************************************************************//**
179  * @brief Copy constructor
180  *
181  * @param[in] model Background model.
182  *
183  * Constructs a background model by copying information from an existing
184  * model. Note that the copy is a deep copy, so the original object can be
185  * destroyed after the copy without any loss of information.
186  ***************************************************************************/
188  GModelData(model)
189 {
190  // Initialise private members for clean destruction
191  init_members();
192 
193  // Copy members
194  copy_members(model);
195 
196  // Set parameter pointers
197  set_pointers();
198 
199  // Return
200  return;
201 }
202 
203 
204 /***********************************************************************//**
205  * @brief Destructor
206  *
207  * Destroys a background model.
208  ***************************************************************************/
210 {
211  // Free members
212  free_members();
213 
214  // Return
215  return;
216 }
217 
218 
219 /*==========================================================================
220  = =
221  = Operators =
222  = =
223  ==========================================================================*/
224 
225 /***********************************************************************//**
226  * @brief Assignment operator
227  *
228  * @param[in] model Background model.
229  *
230  * Assigns the information from a background model to instance. Note that a
231  * deep copy of the information is performed, so the original instance can be
232  * destroyed after the assignment without any loss of information.
233  ***************************************************************************/
235 {
236  // Execute only if object is not identical
237  if (this != &model) {
238 
239  // Copy base class members
240  this->GModelData::operator=(model);
241 
242  // Free members
243  free_members();
244 
245  // Initialise members
246  init_members();
247 
248  // Copy members (this method also sets the parameter pointers)
249  copy_members(model);
250 
251  } // endif: object was not identical
252 
253  // Return
254  return *this;
255 }
256 
257 
258 /*==========================================================================
259  = =
260  = Public methods =
261  = =
262  ==========================================================================*/
263 
264 /***********************************************************************//**
265  * @brief Clear instance
266  *
267  * Resets the instance to a clean initial state. All information that resided
268  * in the object will be lost.
269  ***************************************************************************/
271 {
272  // Free class members (base and derived classes, derived class first)
273  free_members();
274  this->GModelData::free_members();
275  this->GModel::free_members();
276 
277  // Initialise members
278  this->GModel::init_members();
279  this->GModelData::init_members();
280  init_members();
281 
282  // Return
283  return;
284 }
285 
286 
287 /***********************************************************************//**
288  * @brief Clone instance
289  *
290  * @return Pointer to deep copy of background model.
291  ***************************************************************************/
293 {
294  return new GCTAModelBackground(*this);
295 }
296 
297 
298 /***********************************************************************//**
299  * @brief Set spatial model component
300  *
301  * @param[in] spatial Pointer to spatial model component.
302  *
303  * Sets the spatial model component of the model.
304  ***************************************************************************/
306 {
307  // Free spatial model component only if it differs from current
308  // component. This prevents unintentional deallocation of the argument
309  if ((m_spatial != NULL) && (m_spatial != spatial)) {
310  delete m_spatial;
311  }
312 
313  // Clone spatial model component if it exists, otherwise set pointer
314  // to NULL
315  m_spatial = (spatial != NULL) ? spatial->clone() : NULL;
316 
317  // Set parameter pointers
318  set_pointers();
319 
320  // Return
321  return;
322 }
323 
324 
325 /***********************************************************************//**
326  * @brief Set spectral model component
327  *
328  * @param[in] spectral Pointer to spectral model component.
329  *
330  * Sets the spectral model component of the model.
331  ***************************************************************************/
333 {
334  // Free spectral model component only if it differs from current
335  // component. This prevents unintential deallocation of the argument
336  if ((m_spectral != NULL) && (m_spectral != spectral)) {
337  delete m_spectral;
338  }
339 
340  // Clone spectral model component if it exists, otherwise set pointer
341  // to NULL
342  m_spectral = (spectral != NULL) ? spectral->clone() : NULL;
343 
344  // Set parameter pointers
345  set_pointers();
346 
347  // Return
348  return;
349 }
350 
351 
352 /***********************************************************************//**
353  * @brief Set temporal model component
354  *
355  * @param[in] temporal Pointer to temporal model component.
356  *
357  * Sets the temporal model component of the model.
358  ***************************************************************************/
360 {
361  // Free temporal model component only if it differs from current
362  // component. This prevents unintential deallocation of the argument
363  if ((m_temporal != NULL) && (m_temporal != temporal)) {
364  delete m_temporal;
365  }
366 
367  // Clone temporal model component if it exists, otherwise set pointer
368  // to NULL
369  m_temporal = (temporal != NULL) ? temporal->clone() : NULL;
370 
371  // Set parameter pointers
372  set_pointers();
373 
374  // Return
375  return;
376 }
377 
378 
379 /***********************************************************************//**
380  * @brief Return background rate in units of events MeV\f$^{-1}\f$
381  * s\f$^{-1}\f$ sr\f$^{-1}\f$
382  *
383  * @param[in] event Observed event.
384  * @param[in] obs Observation.
385  * @param[in] gradients Compute gradients?
386  * @return Background rate (events MeV\f$^{-1}\f$ s\f$^{-1}\f$ sr\f$^{-1}\f$).
387  *
388  * Evaluates the background model which is a factorization of a spatial,
389  * spectral and temporal model component. The method returns a real rate,
390  * defined as the number of counts per MeV, steradian and ontime.
391  *
392  * If the @p gradients flag is true the method will also set the parameter
393  * gradients of the model parameters.
394  *
395  * @todo Add bookkeeping of last value and evaluate only if argument
396  * changed
397  * @todo Verify that CTA instrument direction pointer is valid, or better,
398  * add an offset method to GCTAPointing. Ideally, we should precompute
399  * all offset angles (for an event cube this may only be done easily
400  * if the pointing has been fixed; otherwise we need a structure
401  * similar to the Fermi/LAT livetime cube that provides the effective
402  * sky exposure as function of offset angle).
403  ***************************************************************************/
404 double GCTAModelBackground::eval(const GEvent& event,
405  const GObservation& obs,
406  const bool& gradients) const
407 {
408  // Get reference on CTA instrument direction from event
409  const GCTAInstDir& dir = gammalib::cta_dir(G_EVAL, event);
410 
411  // Evaluate function and gradients
412  double spat = (spatial() != NULL)
413  ? spatial()->eval(dir, event.energy(), event.time(), gradients) : 1.0;
414  double spec = (spectral() != NULL)
415  ? spectral()->eval(event.energy(), event.time(), gradients)
416  : 1.0;
417  double temp = (temporal() != NULL)
418  ? temporal()->eval(event.time(), gradients) : 1.0;
419 
420  // Compute value
421  double value = spat * spec * temp;
422 
423  // Optionally compute partial derivatives
424  if (gradients) {
425 
426  // Multiply factors to radial gradients
427  if (spatial() != NULL) {
428  double fact = spec * temp;
429  if (fact != 1.0) {
430  for (int i = 0; i < spatial()->size(); ++i)
431  (*spatial())[i].factor_gradient((*spatial())[i].factor_gradient() * fact);
432  }
433  }
434 
435  // Multiply factors to spectral gradients
436  if (spectral() != NULL) {
437  double fact = spat * temp;
438  if (fact != 1.0) {
439  for (int i = 0; i < spectral()->size(); ++i)
440  (*spectral())[i].factor_gradient((*spectral())[i].factor_gradient() * fact);
441  }
442  }
443 
444  // Multiply factors to temporal gradients
445  if (temporal() != NULL) {
446  double fact = spat * spec;
447  if (fact != 1.0) {
448  for (int i = 0; i < temporal()->size(); ++i)
449  (*temporal())[i].factor_gradient((*temporal())[i].factor_gradient() * fact);
450  }
451  }
452 
453  } // endif: computed partial derivatives
454 
455  // Return
456  return value;
457 }
458 
459 
460 /***********************************************************************//**
461  * @brief Return spatially integrated background rate in units of
462  * events MeV\f$^{-1}\f$ s\f$^{-1}\f$
463  *
464  * @param[in] energy Measured event energy.
465  * @param[in] time Measured event time.
466  * @param[in] obs Observation.
467  * @return Spatially integrated background rate
468  * (events MeV\f$^{-1}\f$ s\f$^{-1}\f$)
469  *
470  * Spatially integrates the background model for a given measured event
471  * energy and event time. The method returns a real rate, defined as the
472  * number of counts per MeV and ontime.
473  ***************************************************************************/
474 double GCTAModelBackground::npred(const GEnergy& energy,
475  const GTime& time,
476  const GObservation& obs) const
477 {
478  // Get spatially integrated model component
479  double npred = spatial()->npred(energy, time, obs);
480 
481  // Multiply in spectral and temporal components
482  npred *= spectral()->eval(energy, time);
483  npred *= temporal()->eval(time);
484 
485  // Return Npred
486  return npred;
487 }
488 
489 
490 /***********************************************************************//**
491  * @brief Return simulated list of events
492  *
493  * @param[in] obs Observation.
494  * @param[in] ran Random number generator.
495  * @return Pointer to list of simulated events (needs to be de-allocated by
496  * client)
497  *
498  * Draws a sample of events from the background model using a Monte
499  * Carlo simulation. The region of interest, the energy boundaries and the
500  * good time interval for the sampling will be extracted from the observation
501  * argument that is passed to the method. The method also requires a random
502  * number generator of type GRan which is passed by reference, hence the
503  * state of the random number generator will be changed by the method.
504  *
505  * For each event in the returned event list, the sky direction, the nominal
506  * coordinates (DETX and DETY), the energy and the time will be set.
507  *
508  * @todo Handle special case of cube spatial model
509  ***************************************************************************/
511  GRan& ran) const
512 {
513  // Initialise new event list
514  GCTAEventList* list = new GCTAEventList;
515 
516  // Continue only if model is valid)
517  if (valid_model()) {
518 
519  // Get reference on CTA pointing, background response and event list
520  // from observation
521  const GCTAObservation& cta = gammalib::cta_obs(G_MC, obs);
522  const GCTAEventList& events = gammalib::cta_event_list(G_MC, obs);
523 
524  // Get simulation region
525  const GCTARoi& roi = events.roi();
526  const GEbounds& ebounds = events.ebounds();
527  const GGti& gti = events.gti();
528 
529  // Set simulation region for result event list
530  list->roi(roi);
531  list->ebounds(ebounds);
532  list->gti(gti);
533 
534  // Set spectral model
536 
537  // TODO: Handle special case of cube spatial model. This will
538  // replace the spectral model by a spectral nodes model.
539 
540  // Get solid angle of spatial model. This only works for an energy
541  // independent spatial model!!!
542  double solidangle = m_spatial->npred(GEnergy(), GTime(), obs);
543 
544  // Loop over all energy boundaries
545  for (int ieng = 0; ieng < ebounds.size(); ++ieng) {
546 
547  // Compute the background rate in model within the energy
548  // boundaries from spectral component (units: cts/s/sr).
549  double flux = spectral->flux(ebounds.emin(ieng), ebounds.emax(ieng));
550 
551  // Derive expecting rate (units: cts/s). Note that the time here
552  // is good time. Deadtime correction will be done later.
553  double rate = flux * solidangle;
554 
555  // Debug option: dump rate
556  #if defined(G_DUMP_MC)
557  std::cout << "GCTAModelBackground::mc(\"" << name() << "\": ";
558  std::cout << "flux=" << flux << " cts/s/sr, ";
559  std::cout << "solidangle=" << solidangle << " sr, ";
560  std::cout << "rate=" << rate << " cts/s)" << std::endl;
561  #endif
562 
563  // If the rate is not positive then skip this energy bins
564  if (rate <= 0.0) {
565  continue;
566  }
567 
568  // Loop over all good time intervals
569  for (int itime = 0; itime < gti.size(); ++itime) {
570 
571  // Get Monte Carlo event arrival times from temporal model
572  GTimes times = m_temporal->mc(rate,
573  gti.tstart(itime),
574  gti.tstop(itime),
575  ran);
576 
577  // Get number of events
578  int n_events = times.size();
579 
580  // Reserve space for events
581  if (n_events > 0) {
582  list->reserve(n_events);
583  }
584 
585  // Debug option: provide number of times and initialize
586  // statisics
587  #if defined(G_DUMP_MC)
588  std::cout << " Interval " << itime;
589  std::cout << " events=" << n_events << std::endl;
590  int n_trial_outside_roi = 0;
591  #endif
592 
593  // Loop over events
594  for (int i = 0; i < n_events; ++i) {
595 
596  // Get Monte Carlo event energy from spectral model
597  GEnergy energy = spectral->mc(ebounds.emin(ieng),
598  ebounds.emax(ieng),
599  times[i],
600  ran);
601 
602  // Get an instrument direction within the RoI. This is
603  // potentially tried 100 times so that if we really can't
604  // a valid instrument direction the code is not locked up
605  for (int k = 0; k < 100; ++k) {
606 
607  // Get Monte Carlo event direction from spatial model.
608  GCTAInstDir dir = m_spatial->mc(energy, times[i], cta, ran);
609 
610  // Allocate event
611  GCTAEventAtom event;
612 
613  // Set event attributes
614  event.dir(dir);
615  event.energy(energy);
616  event.time(times[i]);
617 
618  // Append event to list if it falls in RoI and break
619  // the look
620  if (events.roi().contains(event)) {
621  list->append(event);
622  break;
623  }
624 
625  // ... otherwise optionally bookkeep the trial
626  #if defined(G_DUMP_MC)
627  else {
628  n_trial_outside_roi++;
629  }
630  #endif
631 
632  } // endfor: trial look for instrument direction within RoI
633 
634  } // endfor: looped over all events
635 
636  // Debug option: provide statisics
637  #if defined(G_DUMP_MC)
638  std::cout << " Trials outside RoI=";
639  std::cout << n_trial_outside_roi << std::endl;
640  #endif
641 
642  } // endfor: looped over all GTIs
643 
644  } // endfor: looped over all energy boundaries
645 
646  } // endif: model was valid
647 
648  // Return
649  return list;
650 }
651 
652 
653 /***********************************************************************//**
654  * @brief Read model from XML element
655  *
656  * @param[in] xml XML element.
657  *
658  * Reads the sky model from an XML element. The XML element is expected to
659  * respect the following format:
660  *
661  * <source name=".." type=".." instrument=".." id="..">
662  * <spectrum type="..">
663  * ..
664  * </spectrum>
665  * <spatialModel type="..">
666  * ..
667  * </spatialModel>
668  * <temporal type="..">
669  * ..
670  * </temporal>
671  * </source>
672  *
673  * The temporal element is optional. In no temporal element is specified a
674  * constant component with unity normalization will be assumed.
675  ***************************************************************************/
677 {
678  // Clear model
679  clear();
680 
681  // Get pointers on spatial and spectral model components
682  const GXmlElement* spat = xml.element("spatialModel", 0);
683  const GXmlElement* spec = xml.element("spectrum", 0);
684 
685  // Set spatial and spectral model components
686  m_spatial = xml_spatial(*spat);
687  m_spectral = xml_spectral(*spec);
688 
689  // Handle optional temporal model
690  if (xml.elements("temporal") > 0) {
691  const GXmlElement* temp = xml.element("temporal", 0);
692  m_temporal = xml_temporal(*temp);
693  }
694  else {
696  m_temporal = temporal.clone();
697  }
698 
699  // Read model attributes
700  read_attributes(xml);
701 
702  // Set parameter pointers
703  set_pointers();
704 
705  // Return
706  return;
707 }
708 
709 
710 /***********************************************************************//**
711  * @brief Write model into XML element
712  *
713  * @param[in] xml XML element.
714  *
715  * Writes the sky model into an XML source library. The format written to
716  * the @p xml element is as follows:
717  *
718  * <source name=".." type=".." instrument=".." id="..">
719  * <spectrum type="..">
720  * ..
721  * </spectrum>
722  * <spatialModel type="..">
723  * ..
724  * </spatialModel>
725  * <temporal type="..">
726  * ..
727  * </temporal>
728  * </source>
729  *
730  * For compatibility reasons the temporal element will only be written if it
731  * is a non-constant component or a constant component with a normalization
732  * that differs from unity.
733  ***************************************************************************/
735 {
736  // Initialise pointer on source
737  GXmlElement* src = NULL;
738 
739  // Search corresponding source
740  int n = xml.elements("source");
741  for (int k = 0; k < n; ++k) {
742  GXmlElement* element = xml.element("source", k);
743  if (element->attribute("name") == name()) {
744  src = element;
745  break;
746  }
747  }
748 
749  // If the temporal model is not a constant with unit normalization then
750  // set cons to a NULL pointer
751  GModelTemporalConst* cons = dynamic_cast<GModelTemporalConst*>(temporal());
752  if (cons != NULL) {
753  if (cons->norm() != 1.0) {
754  cons = NULL;
755  }
756  }
757 
758  // If no source with corresponding name was found then append one
759  if (src == NULL) {
760  src = xml.append("source");
761  if (spatial() != NULL) src->append(GXmlElement("spatialModel"));
762  if (spectral() != NULL) src->append(GXmlElement("spectrum"));
763  if (temporal() != NULL && cons == NULL) src->append(GXmlElement("temporal"));
764  }
765 
766  // Write spatial model
767  if (spatial() != NULL) {
768  GXmlElement* spat = src->element("spatialModel", 0);
769  spatial()->write(*spat);
770  }
771 
772  // Write spectral model
773  if (spectral() != NULL) {
774  GXmlElement* spec = src->element("spectrum", 0);
775  spectral()->write(*spec);
776  }
777 
778  // Write temporal model (only if not a constant with unit normalization
779  // factor)
780  if (temporal() != NULL && cons == NULL) {
781  GXmlElement* temp = src->element("temporal", 0);
782  temporal()->write(*temp);
783  }
784 
785  // Write model attributes
786  write_attributes(*src);
787 
788  // Return
789  return;
790 }
791 
792 
793 /***********************************************************************//**
794  * @brief Print model information
795  *
796  * @param[in] chatter Chattiness.
797  * @return String containing model information.
798  ***************************************************************************/
799 std::string GCTAModelBackground::print(const GChatter& chatter) const
800 {
801  // Initialise result string
802  std::string result;
803 
804  // Continue only if chatter is not silent
805  if (chatter != SILENT) {
806 
807  // Append header
808  result.append("=== GCTAModelBackground ===");
809 
810  // Determine number of parameters per type
811  int n_spatial = (spatial() != NULL) ? spatial()->size() : 0;
812  int n_spectral = (spectral() != NULL) ? spectral()->size() : 0;
813  int n_temporal = (temporal() != NULL) ? temporal()->size() : 0;
814 
815  // Append attributes
816  result.append("\n"+print_attributes());
817 
818  // Append model type
819  result.append("\n"+gammalib::parformat("Model type")+type());
820 
821  // Append model type
822  result.append("\n"+gammalib::parformat("Model components"));
823  if (n_spatial > 0) {
824  result.append("\""+spatial()->type()+"\"");
825  if (n_spectral > 0 || n_temporal > 0) {
826  result.append(" * ");
827  }
828  }
829  if (n_spectral > 0) {
830  result.append("\""+spectral()->type()+"\"");
831  if (n_temporal > 0) {
832  result.append(" * ");
833  }
834  }
835  if (n_temporal > 0) {
836  result.append("\""+temporal()->type()+"\"");
837  }
838 
839  // Append parameters
840  result.append("\n"+gammalib::parformat("Number of parameters") +
841  gammalib::str(size()));
842  result.append("\n"+gammalib::parformat("Number of spatial par's") +
843  gammalib::str(n_spatial));
844  for (int i = 0; i < n_spatial; ++i) {
845  result.append("\n"+(*spatial())[i].print());
846  }
847  result.append("\n"+gammalib::parformat("Number of spectral par's") +
848  gammalib::str(n_spectral));
849  for (int i = 0; i < n_spectral; ++i) {
850  result.append("\n"+(*spectral())[i].print());
851  }
852  result.append("\n"+gammalib::parformat("Number of temporal par's") +
853  gammalib::str(n_temporal));
854  for (int i = 0; i < n_temporal; ++i) {
855  result.append("\n"+(*temporal())[i].print());
856  }
857 
858  } // endif: chatter was not silent
859 
860  // Return result
861  return result;
862 }
863 
864 
865 /*==========================================================================
866  = =
867  = Private methods =
868  = =
869  ==========================================================================*/
870 
871 /***********************************************************************//**
872  * @brief Initialise class members
873  ***************************************************************************/
875 {
876  // Initialise members
877  m_spatial = NULL;
878  m_spectral = NULL;
879  m_temporal = NULL;
880 
881  // Return
882  return;
883 }
884 
885 
886 /***********************************************************************//**
887  * @brief Copy class members
888  *
889  * @param[in] model Background model.
890  ***************************************************************************/
892 {
893  // Clone radial, spectral and temporal model components
894  m_spatial = (model.m_spatial != NULL) ? model.m_spatial->clone() : NULL;
895  m_spectral = (model.m_spectral != NULL) ? model.m_spectral->clone() : NULL;
896  m_temporal = (model.m_temporal != NULL) ? model.m_temporal->clone() : NULL;
897 
898  // Set parameter pointers
899  set_pointers();
900 
901  // Return
902  return;
903 }
904 
905 
906 /***********************************************************************//**
907  * @brief Delete class members
908  ***************************************************************************/
910 {
911  // Free memory
912  if (m_spatial != NULL) delete m_spatial;
913  if (m_spectral != NULL) delete m_spectral;
914  if (m_temporal != NULL) delete m_temporal;
915 
916  // Signal free pointers
917  m_spatial = NULL;
918  m_spectral = NULL;
919  m_temporal = NULL;
920 
921  // Return
922  return;
923 }
924 
925 
926 /***********************************************************************//**
927  * @brief Set pointers
928  *
929  * Set pointers to all model parameters. The pointers are stored in a vector
930  * that is member of the GModelData base class.
931  ***************************************************************************/
933 {
934  // Clear parameters
935  m_pars.clear();
936 
937  // Determine the number of parameters
938  int n_spatial = (spatial() != NULL) ? spatial()->size() : 0;
939  int n_spectral = (spectral() != NULL) ? spectral()->size() : 0;
940  int n_temporal = (temporal() != NULL) ? temporal()->size() : 0;
941  int n_pars = n_spatial + n_spectral + n_temporal;
942 
943  // Continue only if there are parameters
944  if (n_pars > 0) {
945 
946  // Gather spatial parameter pointers
947  for (int i = 0; i < n_spatial; ++i) {
948  m_pars.push_back(&((*spatial())[i]));
949  }
950 
951  // Gather spectral parameters
952  for (int i = 0; i < n_spectral; ++i) {
953  m_pars.push_back(&((*spectral())[i]));
954  }
955 
956  // Gather temporal parameters
957  for (int i = 0; i < n_temporal; ++i) {
958  m_pars.push_back(&((*temporal())[i]));
959  }
960 
961  }
962 
963  // Return
964  return;
965 }
966 
967 
968 /***********************************************************************//**
969  * @brief Return pointer to spatial model from XML element
970  *
971  * @param[in] spatial XML element.
972  * @return Pointer to spatial model.
973  *
974  * Returns pointer to a spatial model that is defined in an XML element.
975  ***************************************************************************/
977 {
978  // Get radial model
979  GCTAModelSpatialRegistry registry;
980  GCTAModelSpatial* ptr = registry.alloc(spatial);
981 
982  // Return pointer
983  return ptr;
984 }
985 
986 
987 /***********************************************************************//**
988  * @brief Return pointer to spectral model from XML element
989  *
990  * @param[in] spectral XML element.
991  * @return Pointer to spectral model.
992  *
993  * Returns pointer to spectral model that is defined in an XML element.
994  ***************************************************************************/
996 {
997  // Get spectral model
998  GModelSpectralRegistry registry;
999  GModelSpectral* ptr = registry.alloc(spectral);
1000 
1001  // Return pointer
1002  return ptr;
1003 }
1004 
1005 
1006 /***********************************************************************//**
1007  * @brief Return pointer to temporal model from XML element
1008  *
1009  * @param[in] temporal XML element.
1010  * @return Pointer to temporal model.
1011  *
1012  * Returns pointer to temporal model that is defined in an XML element.
1013  ***************************************************************************/
1015 {
1016  // Get temporal model
1017  GModelTemporalRegistry registry;
1018  GModelTemporal* ptr = registry.alloc(temporal);
1019 
1020  // Return pointer
1021  return ptr;
1022 }
1023 
1024 
1025 /***********************************************************************//**
1026  * @brief Verifies if model has all components
1027  *
1028  * Returns 'true' if models has a spatial, a spectral and a temporal
1029  * component. Otherwise returns 'false'.
1030  ***************************************************************************/
1032 {
1033  // Set result
1034  bool result = ((spatial() != NULL) &&
1035  (spectral() != NULL) &&
1036  (temporal() != NULL));
1037 
1038  // Return result
1039  return result;
1040 }
virtual void write(GXmlElement &xml) const =0
Constant temporal model class interface definition.
GCTAModelBackground(void)
Void constructor.
virtual GCTAInstDir mc(const GEnergy &energy, const GTime &time, const GCTAObservation &obs, GRan &ran) const
Returns MC instrument direction.
#define G_MC
Abstract spatial model class.
void free_members(void)
Delete class members.
Definition: GModel.cpp:672
GModelTemporal * xml_temporal(const GXmlElement &temporal) const
Return pointer to temporal model from XML element.
virtual GTimes mc(const double &rate, const GTime &tmin, const GTime &tmax, GRan &ran) const =0
virtual GEnergy mc(const GEnergy &emin, const GEnergy &emax, const GTime &time, GRan &ran) const =0
const GCTAInstDir & cta_dir(const std::string &origin, const GEvent &event)
Retrieve CTA instrument direction from generic event.
int size(void) const
Return number of times.
Definition: GTimes.hpp:100
std::string print_attributes(void) const
Print model attributes.
Definition: GModel.cpp:770
Abstract spectral model base class.
Interface definition for the model registry class.
virtual void read(const GXmlElement &xml)
Read model from XML element.
Abstract temporal model base class.
virtual void roi(const GRoi &roi)
Set ROI.
GModelTemporal * m_temporal
Temporal model.
int size(void) const
Return number of parameters.
void ebounds(const GEbounds &ebounds)
Set energy boundaries.
Definition: GEvents.cpp:136
int size(void) const
Return number of energy boundaries.
Definition: GEbounds.hpp:163
virtual double eval(const GEnergy &srcEng, const GTime &srcTime=GTime(), const bool &gradients=false) const =0
virtual void write(GXmlElement &xml) const =0
void append(const GCTAEventAtom &event)
Append event to event list.
virtual double npred(const GEnergy &energy, const GTime &time, const GObservation &obs) const
Return spatially integrated background rate in units of events MeV s .
bool valid_model(void) const
Verifies if model has all components.
Abstract interface for the event classes.
Definition: GEvent.hpp:71
CTA event list class.
XML element node class.
Definition: GXmlElement.hpp:48
void gti(const GGti &gti)
Set Good Time Intervals.
Definition: GEvents.cpp:154
CTA pointing class interface definition.
void free_members(void)
Delete class members.
Definition: GModelData.cpp:300
Spectral model registry class definition.
virtual void write(GXmlElement &xml) const =0
GModelSpectral * spectral(void) const
Return spectral model component.
Random number generator class.
Definition: GRan.hpp:44
Interface for the CTA region of interest class.
Definition: GCTARoi.hpp:49
virtual int elements(void) const
Return number of GXMLElement children of node.
Definition: GXmlNode.cpp:586
Time class.
Definition: GTime.hpp:55
Gammalib tools definition.
virtual GModelTemporalConst * clone(void) const
Clone constant temporal model.
virtual const GTime & time(void) const =0
GModelSpectral * m_spectral
Spectral model.
int size(void) const
Return number of Good Time Intervals.
Definition: GGti.hpp:154
Interface definition for the spatial model registry class.
Time container class.
Definition: GTimes.hpp:45
std::vector< GModelPar * > m_pars
Pointers to all model parameters.
Definition: GModel.hpp:178
int size(void) const
Return number of parameters in model.
Definition: GModel.hpp:233
void init_members(void)
Initialise class members.
Definition: GModel.cpp:622
void copy_members(const GCTAModelBackground &model)
Copy class members.
Definition of support function used by CTA classes.
void free_members(void)
Delete class members.
virtual GCTAEventList * mc(const GObservation &obs, GRan &ran) const
Return simulated list of events.
Energy boundaries container class.
Definition: GEbounds.hpp:60
const GXmlAttribute * attribute(const int &index) const
Return attribute.
const std::string & name(void) const
Return parameter name.
Definition: GModel.hpp:261
void reserve(const int &number)
Reserves space for events.
const GEnergy & emin(void) const
Return minimum energy of all intervals.
Definition: GEbounds.hpp:187
GCTAModelSpatial * spatial(void) const
Return spatial model component.
void set_pointers(void)
Set pointers.
int size(void) const
Return number of parameters.
GModelTemporal * alloc(const GXmlElement &xml) const
Allocate temporal model that is found in XML element.
virtual const GEnergy & energy(void) const =0
Abstract data model class.
Definition: GModelData.hpp:55
CTA instrument direction class interface definition.
const GCTAEventList & cta_event_list(const std::string &origin, const GObservation &obs)
Retrieve CTA event list from generic observation.
GModelSpectral * alloc(const GXmlElement &xml) const
Allocate spectral model that is found in XML element.
virtual GCTAModelBackground & operator=(const GCTAModelBackground &model)
Assignment operator.
virtual GModelData & operator=(const GModelData &model)
Assignment operator.
Definition: GModelData.cpp:125
int size(void) const
Return number of model parameters.
GChatter
Definition: GTypemaps.hpp:33
Good Time Interval class.
Definition: GGti.hpp:62
GCTAModelSpatial * xml_spatial(const GXmlElement &spatial) const
Return pointer to spatial model from XML element.
virtual double eval(const GTime &srcTime, const bool &gradients=false) const =0
const GCTAObservation & cta_obs(const std::string &origin, const GObservation &obs)
Retrieve CTA observation from generic observation.
Abstract observation base class.
void init_members(void)
Initialise class members.
const GTime & tstop(void) const
Returns latest stop time in Good Time Intervals.
Definition: GGti.hpp:207
const GTime & tstart(void) const
Returns earliest start time in Good Time Intervals.
Definition: GGti.hpp:194
CTA region of interest class interface definition.
CTA observation class interface definition.
Interface definition for the spectral model registry class.
Interface definition for the temporal model registry class.
void write_attributes(GXmlElement &xml) const
Write model attributes.
Definition: GModel.cpp:723
virtual GModelSpectral * clone(void) const =0
Clones object.
Background model class.
virtual GCTAModelBackground * clone(void) const
Clone instance.
virtual void write(GXmlElement &xml) const
Write model into XML element.
virtual GXmlElement * element(const int &index)
Return pointer to GXMLElement child.
Definition: GXmlNode.cpp:640
GCTAModelSpatial * m_spatial
Spatial model.
GModelTemporal * temporal(void) const
Return temporal model component.
Temporal model registry class definition.
const GCTAModelBackground g_cta_background_seed
CTA event atom class.
virtual double eval(const GCTAInstDir &dir, const GEnergy &energy, const GTime &time, const bool &gradients=false) const =0
virtual GModelTemporal * clone(void) const =0
Clones object.
void read_attributes(const GXmlElement &xml)
Read model attributes.
Definition: GModel.cpp:684
CTA instrument direction class.
Definition: GCTAInstDir.hpp:63
GCTAModelSpatial * alloc(const GXmlElement &xml) const
Allocate spatial model that is found in XML element.
double norm(void) const
Return normalization factor.
const GEnergy & emax(void) const
Return maximum energy of all intervals.
Definition: GEbounds.hpp:199
virtual double flux(const GEnergy &emin, const GEnergy &emax) const =0
Model registry class definition.
virtual GCTAModelSpatial * clone(void) const =0
Clones object.
virtual GXmlNode * append(const GXmlNode &node)
Append XML child node.
Definition: GXmlNode.cpp:287
CTA observation class.
std::string parformat(const std::string &s, const int &indent=0)
Convert string in parameter format.
Definition: GTools.cpp:1143
#define G_EVAL
GModelSpectral * xml_spectral(const GXmlElement &spectral) const
Return pointer to spectral model from XML element.
virtual double npred(const GEnergy &energy, const GTime &time, const GObservation &obs) const
Return integral of spatial model component.
Integration class interface definition.
virtual double eval(const GEvent &event, const GObservation &obs, const bool &gradients=false) const
Return background rate in units of events MeV s sr .
Spatial model registry class definition.
virtual std::string print(const GChatter &chatter=NORMAL) const
Print model information.
void init_members(void)
Initialise class members.
Definition: GModelData.cpp:278
virtual ~GCTAModelBackground(void)
Destructor.
Constant temporal model class.
const GCTAInstDir & dir(void) const
Return instrument direction.
Mathematical function definitions.
virtual void clear(void)
Clear instance.
Class that handles energies in a unit independent way.
Definition: GEnergy.hpp:48
virtual std::string type(void) const
Return model type.
Background model class interface definition.
std::string str(const unsigned short int &value)
Convert unsigned short integer value into string.
Definition: GTools.cpp:489