Example #1
0
/***********************************************************************//**
 * @brief Set pointers
 *
 * Set pointers to all model parameters. The pointers are stored in a vector
 * that is member of the GModelData base class.
 ***************************************************************************/
void GCTAModelCubeBackground::set_pointers(void)
{
    // Clear parameters
    m_pars.clear();

    // Determine the number of parameters
    int n_spectral = (spectral() != NULL) ? spectral()->size() : 0;
    int n_temporal = (temporal() != NULL) ? temporal()->size() : 0;
    int n_pars     = n_spectral + n_temporal;

    // Continue only if there are parameters
    if (n_pars > 0) {

        // Gather spectral parameters
        for (int i = 0; i < n_spectral; ++i) {
            m_pars.push_back(&((*spectral())[i]));
        }

        // Gather temporal parameters
        for (int i = 0; i < n_temporal; ++i) {
            m_pars.push_back(&((*temporal())[i]));
        }

    }

    // Return
    return;
}
/***********************************************************************//**
 * @brief Write CTA instrument background model into XML element
 *
 * @param[in] xml XML element.
 *
 * Write CTA instrument background model information into an XML element.
 * The XML element will have the following structure
 *
 *     <source name="..." type="..." instrument="...">
 *       <spectrum type="...">
 *         ...
 *       </spectrum>
 *     </source>
 *
 * If the model contains a non-constant temporal model, the temporal
 * component will also be written following the syntax
 *
 *     <source name="..." type="..." instrument="...">
 *       <spectrum type="...">
 *         ...
 *       </spectrum>
 *       <temporalModel type="...">
 *         ...
 *       </temporalModel>
 *     </source>
 *
 * If no temporal component is found a constant model is assumed.
 ***************************************************************************/
void GCTAModelIrfBackground::write(GXmlElement& xml) const
{
    // Initialise pointer on source
    GXmlElement* src = NULL;

    // Search corresponding source
    int n = xml.elements("source");
    for (int k = 0; k < n; ++k) {
        GXmlElement* element = xml.element("source", k);
        if (element->attribute("name") == name()) {
            src = element;
            break;
        }
    }

    // If we have a temporal model that is either not a constant, or a
    // constant with a normalization value that differs from 1.0 then
    // write the temporal component into the XML element. This logic
    // assures compatibility with the Fermi/LAT format as this format
    // does not handle temporal components.
    bool write_temporal = ((m_temporal != NULL) &&
                           (m_temporal->type() != "Constant" ||
                            (*m_temporal)[0].value() != 1.0));

    // If no source with corresponding name was found then append one
    if (src == NULL) {
        src = xml.append("source");
        if (spectral() != NULL) src->append(GXmlElement("spectrum"));
        if (write_temporal)     src->append(GXmlElement("temporalModel"));
    }

    // Set model type, name and optionally instruments
    src->attribute("name", name());
    src->attribute("type", type());
    if (instruments().length() > 0) {
        src->attribute("instrument", instruments());
    }
    std::string identifiers = ids();
    if (identifiers.length() > 0) {
        src->attribute("id", identifiers);
    }

    // Write spectral model
    if (spectral() != NULL) {
        GXmlElement* spec = src->element("spectrum", 0);
        spectral()->write(*spec);
    }

    // Optionally write temporal model
    if (write_temporal) {
        if (dynamic_cast<GModelTemporalConst*>(temporal()) == NULL) {
            GXmlElement* temp = src->element("temporalModel", 0);
            temporal()->write(*temp);
        }
    }

    // Return
    return;
}
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            Specified observation is not of the expected type.
 *
 * @todo Make sure that DETX and DETY are always set in GCTAInstDir.
 ***************************************************************************/
double GCTAModelIrfBackground::eval(const GEvent& event,
                                    const GObservation& obs) const
{
    // 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_EVAL, 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_EVAL, 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_EVAL, msg);
    }

    // Extract CTA instrument direction from event
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Set DETX and DETY in instrument direction
    GCTAInstDir inst_dir = cta->pointing().instdir(dir->dir());

    // Evaluate function
    double logE = event.energy().log10TeV();
    double spat = (*bgd)(logE, inst_dir.detx(), inst_dir.dety());
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time()) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    value *= obs.deadc(event.time());

    // Return value
    return value;
}
Example #4
0
/***********************************************************************//**
 * @brief Print model information
 ***************************************************************************/
std::string GModelSky::print_model(void) const
{
    // Initialise result string
    std::string result;

    // Determine number of parameters per type
    int n_spatial  = (m_spatial  != NULL) ? m_spatial->size()  : 0;
    int n_spectral = (m_spectral != NULL) ? m_spectral->size() : 0;
    int n_temporal = (m_temporal != NULL) ? m_temporal->size() : 0;

    // Append attributes
    result.append(print_attributes());

    // Append model type
    result.append("\n"+parformat("Model type"));
    if (n_spatial > 0) {
        result.append("\""+spatial()->type()+"\"");
        if (n_spectral > 0 || n_temporal > 0) {
            result.append(" * ");
        }
    }
    if (n_spectral > 0) {
        result.append("\""+spectral()->type()+"\"");
        if (n_temporal > 0) {
            result.append(" * ");
        }
    }
    if (n_temporal > 0) {
        result.append("\""+temporal()->type()+"\"");
    }

    // Append parameters
    result.append("\n"+parformat("Number of parameters")+str(size()));
    result.append("\n"+parformat("Number of spatial par's")+str(n_spatial));
    for (int i = 0; i < n_spatial; ++i) {
        result.append("\n"+(*spatial())[i].print());
    }
    result.append("\n"+parformat("Number of spectral par's")+str(n_spectral));
    for (int i = 0; i < n_spectral; ++i) {
        result.append("\n"+(*spectral())[i].print());
    }
    result.append("\n"+parformat("Number of temporal par's")+str(n_temporal));
    for (int i = 0; i < n_temporal; ++i) {
        result.append("\n"+(*temporal())[i].print());
    }

    // Return result
    return result;
}
Example #5
0
/***********************************************************************//**
 * @brief Print CTA cube background model information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing CTA cube background model information.
 ***************************************************************************/
std::string GCTAModelCubeBackground::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("=== GCTAModelCubeBackground ===");

        // Determine number of parameters per type
        int n_spectral = (spectral() != NULL) ? spectral()->size() : 0;
        int n_temporal = (temporal() != NULL) ? temporal()->size() : 0;

        // Append attributes
        result.append("\n"+print_attributes());

        // Append model type
        result.append("\n"+gammalib::parformat("Model type"));
        if (n_spectral > 0) {
            result.append("\""+spectral()->type()+"\"");
            if (n_temporal > 0) {
                result.append(" * ");
            }
        }
        if (n_temporal > 0) {
            result.append("\""+temporal()->type()+"\"");
        }

        // Append parameters
        result.append("\n"+gammalib::parformat("Number of parameters") +
                      gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Number of spectral par's") +
                      gammalib::str(n_spectral));
        for (int i = 0; i < n_spectral; ++i) {
            result.append("\n"+(*spectral())[i].print());
        }
        result.append("\n"+gammalib::parformat("Number of temporal par's") +
                      gammalib::str(n_temporal));
        for (int i = 0; i < n_temporal; ++i) {
            result.append("\n"+(*temporal())[i].print());
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
uint8_t ADMVideoMPD3Dlow::configure(AVDMGenericVideoStream *instream)
{

        _in=instream;
        ELEM_TYPE_FLOAT fluma,fchroma,ftemporal;
#define PX(x) &x
#define OOP(x,y) f##x=(ELEM_TYPE_FLOAT )_param->y;
        
        OOP(luma,param1);
        OOP(chroma,param2);
        OOP(temporal,param3);
        
    diaElemFloat   luma(PX(fluma),QT_TR_NOOP("_Spatial luma strength:"),0.,100.);
    diaElemFloat   chroma(PX(fchroma),QT_TR_NOOP("S_patial chroma strength:"),0.,100.);
    diaElemFloat   temporal(PX(ftemporal),QT_TR_NOOP("_Temporal strength:"),0.,100.);
    
       diaElem *elems[3]={&luma,&chroma,&temporal};
  
   if(  diaFactoryRun(QT_TR_NOOP("MPlayer denoise3d"),3,elems))
        {
#undef OOP
#define OOP(x,y) _param->y=(double) f##x
                OOP(luma,param1);
                OOP(chroma,param2);
                OOP(temporal,param3);
          
                setup();
                return 1;
        }
        return 0;
}
Example #7
0
/***********************************************************************//**
 * @brief Evaluate model
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 *
 * This method evaluates the source model for a given event within a given
 * observation.
 ***************************************************************************/
double GModelSky::eval(const GEvent& event, const GObservation& obs) const
{
    // Evaluate function
    double value = temporal(event, obs, false);

    // Return
    return value;
}
Example #8
0
/***********************************************************************//**
 * @brief Verifies if model has all components
 *
 * Returns 'true' if models has a spectral and a temporal component.
 * Otherwise returns 'false'.
 ***************************************************************************/
bool GCTAModelCubeBackground::valid_model(void) const
{
    // Set result
    bool result = ((spectral() != NULL) && (temporal() != NULL));

    // Return result
    return result;
}
Example #9
0
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            Specified observation is not of the expected type.
 ***************************************************************************/
double GCTAModelCubeBackground::eval(const GEvent&       event,
                                     const GObservation& obs) const
{
    // 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.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Get pointer on CTA IRF response
    const GCTAResponseCube* rsp = dynamic_cast<const GCTAResponseCube*>(cta->response());
    if (rsp == NULL) {
        std::string msg = "Specified observation does not contain a cube response.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Extract CTA instrument direction from event
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Retrieve reference to CTA cube background
    const GCTACubeBackground& bgd = rsp->background();

    // Evaluate function
    //double logE = event.energy().log10TeV();
    double spat = bgd((*dir), event.energy());
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time()) : 1.0;

    // Compute value. Note that background rates are already per
    // livetime, hence no deadtime correction is needed here.
    double value = spat * spec * temp;

    // Return value
    return value;
}
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            No CTA instrument direction found in event.
 *
 * Evaluates tha CTA background model which is a factorization of a
 * spatial, spectral and temporal model component. This method also applies
 * a deadtime correction factor, so that the normalization of the model is
 * a real rate (counts/exposure time).
 *
 * @todo Add bookkeeping of last value and evaluate only if argument 
 *       changed
 ***************************************************************************/
double GCTAModelBackground::eval(const GEvent& event,
                                 const GObservation& obs) const
{
    // Get pointer on CTA observation
    const GCTAObservation* ctaobs = dynamic_cast<const GCTAObservation*>(&obs);
    if (ctaobs == NULL) {
        std::string msg = "Specified observation is not a CTA observation.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Extract CTA instrument direction
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Create a Photon from the event.
    // We need the GPhoton to evaluate the spatial model.
    // For the background, GEvent and GPhoton are identical
    // since the IRFs are not folded in
    GPhoton photon(dir->dir(), event.energy(), event.time());

    // Evaluate function and gradients
    double spat = (spatial() != NULL)
                  ? spatial()->eval(photon) : 1.0;
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time()) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    value *= obs.deadc(event.time());

    // Return
    return value;
}
Example #11
0
/***********************************************************************//**
 * @brief Return spatially integrated sky model
 *
 * @param[in] obsEng Measured photon energy.
 * @param[in] obsTime Measured photon arrival time.
 * @param[in] obs Observation.
 *
 * @exception GException::no_response
 *            No valid instrument response function defined.
 *
 * Computes
 * \f[N"_{\rm pred} = \int_{\rm ROI}
 *    S(\vec{p}, E, t) PSF(\vec{p'}, E', t' | \vec{d}, \vec{p}, E, t) \,
 *    {\rm d}\vec{p'}\f]
 * where
 * \f$S(\vec{p}, E, t)\f$ is the source model,
 * \f$PSF(\vec{p'}, E', t' | \vec{d}, \vec{p}, E, t)\f$ is the point
 * spread function,
 * \f$\vec{p'}\f$ is the measured photon direction,
 * \f$E'\f$ is the measured photon energy,
 * \f$t'\f$ is the measured photon arrival time,
 * \f$\vec{p}\f$ is the true photon arrival direction,
 * \f$E\f$ is the true photon energy,
 * \f$t\f$ is the true photon arrival time, and
 * \f$d\f$ is the instrument pointing.
 *
 * \f${\rm ROI}\f$ is the region of interest that is stored in the
 * GObservation::m_roi member. The integration over the ROI is performed
 * by the GResponse::npred() method.
 *
 * @todo The actual method is only correct if no energy and time dispersion
 *       exists. For the moment we set srcEng=obsEng and srcTime=obsTime.
 *       Formally, Equation (2) of the instrument document has to be
 *       computed, which is an integration over source energy, time
 *       and arrival direction. For the moment, only the integration over
 *       arrival direction is performed by GResponse::npred().
 ***************************************************************************/
double GModelSky::npred(const GEnergy& obsEng, const GTime& obsTime,
                        const GObservation& obs) const
{
    // Initialise result
    double npred = 0.0;

    // Continue only if model is valid)
    if (valid_model()) {

        // Get response function
        GResponse* rsp = obs.response();
        if (rsp == NULL) {
            throw GException::no_response(G_NPRED);
        }

        // Here we make the simplifying approximations
        // srcEng=obsEng and srcTime=obsTime. To be fully correct we should
        // integrate over true energy and true time here ... at least true
        // time if we want to consider energy dispersion ...
        GEnergy srcEng  = obsEng;
        GTime   srcTime = obsTime;

        // Set source
        GSource source(this->name(), *m_spatial, srcEng, srcTime);

        // Compute response components
        double npred_spatial  = rsp->npred(source, obs);
        double npred_spectral = spectral()->eval(srcEng);
        double npred_temporal = temporal()->eval(srcTime);

        // Compute response
        npred = npred_spatial * npred_spectral * npred_temporal;

        // Compile option: Check for NaN/Inf
#if defined(G_NAN_CHECK)
        if (isnotanumber(npred) || isinfinite(npred)) {
            std::cout << "*** ERROR: GModelSky::npred:";
            std::cout << " NaN/Inf encountered";
            std::cout << " (npred=" << npred;
            std::cout << ", npred_spatial=" << npred_spatial;
            std::cout << ", npred_spectral=" << npred_spectral;
            std::cout << ", npred_temporal=" << npred_temporal;
            std::cout << ", srcEng=" << srcEng;
            std::cout << ", srcTime=" << srcTime;
            std::cout << ")" << std::endl;
        }
#endif

    } // endif: model was valid

    // Return npred
    return npred;
}
Example #12
0
void* Monitoring::MonitorThread(void* arg){
  
  //std::cout<<"d1"<<std::endl;
  monitor_thread_args* args= static_cast<monitor_thread_args*>(arg);  

  std::string outpath=args->outputpath;
  zmq::socket_t Ireceive (*(args->context), ZMQ_PAIR);
  Ireceive.connect("inproc://MonitorThread");
  
  //  std::vector<CardData*> carddata;

  std::map<int,std::vector<TH1F> > PedTime;
  std::map<int,std::vector<TH1F> > PedRMSTime;
  std::vector<TH1F> rates;
  std::vector<TH1F> averagesize;

  std::vector<TH1I> tfreqplots;
  std::map<int,std::vector<std::vector<float > > > pedpars;
  TCanvas c1("c1","c1",600,400);
  
  
  bool running=true;
  bool init=true;    

  std::vector<PMT> PMTInfo;
  /////////////////// Connect to sql ///////////////////////
//std::cout<<"d2"<<std::endl;

  pqxx::connection *C;
  std::stringstream tmp;
  tmp<<"dbname=annie"<<" hostaddr=127.0.0.1"<<" port=5432" ;
  C=new pqxx::connection(tmp.str().c_str());
  if (C->is_open()) {
    // std::cout << "Opened database successfully: " << C->dbname() << std::endl;
  }
  else {
    std::cout << "Can't open database" << std::endl;
    return false;
  }

  tmp.str("");

  pqxx::nontransaction N(*C);

  tmp<<"select gx,gy,gz,vmecard,vmechannel from pmtconnections order by channel; ";


  /* Execute SQL query */
  pqxx::result R( N.exec( tmp.str().c_str() ));

  //pqxx::result::const_iterator c = R.begin();


  ///////// Fill PMT Info//////////////// 
  for ( pqxx::result::const_iterator c = R.begin(); c != R.end(); ++c) {

    PMT tmp;
    tmp.gx= c[0].as<int>();
    tmp.gy= c[1].as<int>();
    tmp.gz= c[2].as<int>();
    tmp.card= c[3].as<int>();
    tmp.channel= c[4].as<int>()-1;
    PMTInfo.push_back(tmp);
  }

//std::cout<<"d3"<<std::endl;

  
  while (running){
    //std::cout<<"d4"<<std::endl;

    
    zmq::message_t comm;
    Ireceive.recv(&comm);
	
    std::istringstream iss(static_cast<char*>(comm.data()));
    std::string arg1="";
    iss>>arg1;

    //std::cout<<"d5"<<std::endl;
    

    if(arg1=="Data"){

      ////////// Setting up plots/////////
      std::vector<TGraph2D*> mg;
      TH2I EventDisplay ("Event Display", "Event Display", 10, -1, 8, 10, -1, 8);
      TH2I RMSDisplay ("RMS Display", "RMS Display", 10, -1, 8, 10, -1, 8);
      std::vector<TH1F> temporalplots;
      std::vector<TH1I> freqplots;
      CardData* carddata;
      int size=0;
      iss>>size;  
      
      //freqplots.clear();
  //std::cout<<"d6"<<std::endl;
  
      for(int i=0;i<size;i++){
	//std::cout<<"d7"<<std::endl;

	long long unsigned int pointer;
	iss>>std::hex>>pointer;
	
	carddata=(reinterpret_cast<CardData *>(pointer));
	
	if(init){ ////make initial freq  plot and ped vector ped time and ped rms////
	  for(int j=0;j<carddata->channels;j++){
	    std::stringstream tmp;
	    tmp<<"Channel "<<(i*4)+j<<" frequency";
	    TH1I tmpfreq(tmp.str().c_str(),tmp.str().c_str(),10,0,9);
	    tfreqplots.push_back(tmpfreq);

	    tmp.str("");
	    tmp<<"Channel "<<(i*4)+j<<" Pedistal";
	    TH1F tmppedtime(tmp.str().c_str(),tmp.str().c_str(),100,0,99);
	    PedTime[carddata->CardID].push_back(tmppedtime);

	    tmp.str("");
	    tmp<<"Channel "<<(i*4)+j<<" Pedistal RMS";
	    TH1F tmppedrmstime(tmp.str().c_str(),tmp.str().c_str(),100,0,99);
	    PedRMSTime[carddata->CardID].push_back(tmppedrmstime);
	    std::vector<float> tmppedpars;
	    tmppedpars.push_back(0);
	    tmppedpars.push_back(0);
	    pedpars[carddata->CardID].push_back(tmppedpars);
	  }
	  if(i==size-1)init=false;
	}

	//std::cout<<"d8"<<std::endl;

	//	std::cout<<"d1"<<std::endl;

	///////Make temporal plot //////////
	for(int j=0;j<carddata->channels;j++){
	  std::stringstream tmp;
	  tmp<<"Channel "<<(i*4)+j<<" temporal";
	  
	  TH1F temporal(tmp.str().c_str(),tmp.str().c_str(),carddata->buffersize,0,carddata->buffersize-1);
	  long sum=0;

	  //////////Make freq plot///////////////
	  tmp.str("");
	  tmp<<"Channel "<<(i*4)+j<<" frequency";
	  TH1I freq(tmp.str().c_str(),tmp.str().c_str(),200,200,399);

	
	  //  std::cout<<"d2"<<std::endl;

	  //std::cout<<"d9"<<std::endl;

	
	  ///// Calculate sum for event dispkay and fill freq plots /////////


	for(int k=0;k<carddata->buffersize;k++){
	  //std::cout<<"d10"<<std::endl;

	  //	  std::cout<<"i="<<i<<" j="<<j<<std::endl;
	  //std::cout<<"d2.5 "<<(i*4)+j<<" feqplot.size = "<<freqplots.size()<<std::endl;
	  if(carddata->Data[(j*carddata->buffersize)+k]>pedpars[carddata->CardID].at(j).at(0)+(pedpars[carddata->CardID].at(j).at(1)*5))sum+=carddata->Data[(j*carddata->buffersize)+k];  
	  freq.Fill(carddata->Data[(j*carddata->buffersize)+k]);

	  //temporal.SetBinContent(k,carddata->Data[(j*carddata->buffersize)+k]);	      
	}

	freqplots.push_back(freq);
	//////// find pedistall fill ped temporals//////////
	freq.Fit("gaus");
	TF1 *gaus = freq.GetFunction("gaus");
        pedpars[carddata->CardID].at(j).at(0)=(gaus->GetParameter(1));
        pedpars[carddata->CardID].at(j).at(1)=(gaus->GetParameter(2));
	gaus->SetLineColor(j+1);
       
	//std::cout<<"d11"<<std::endl;

	for(int bin=99;bin>0;bin--){
	  PedTime[carddata->CardID].at(j).SetBinContent(bin,PedTime[carddata->CardID].at(j).GetBinContent(bin-1));
	  PedRMSTime[carddata->CardID].at(j).SetBinContent(bin,PedRMSTime[carddata->CardID].at(j).GetBinContent(bin-1));
	}
	PedTime[carddata->CardID].at(j).SetBinContent(0, pedpars[carddata->CardID].at(j).at(0));
	PedRMSTime[carddata->CardID].at(j).SetBinContent(0, pedpars[carddata->CardID].at(j).at(1));

	//////// fill temporal plot/////////
	for(int k=0;k<carddata->buffersize/4;k++){
	  //std::cout<<"d12"<<std::endl;

          //std::cout<<"j*4 = "<<j*4<<std::endl;
          //std::cout<<"(i*BufferSize)+(j*4) = "<<(i*BufferSize)+(j*4)<<std::endl;
          //std::cout<<"i*BufferSize)+(j*4)+(BufferSize/2) = "<<(i*BufferSize)+(j*4)+(BufferSize/2)<<std::endl;
          //std::cout<<"(i*BufferSize)+(j*4)+(BufferSize/2)+1 = "<<(i*BufferSize)+(j*4)+(BufferSize/2)+1<<std::endl;
	  int offset=pedpars[carddata->CardID].at(j).at(0);
          double conversion=2.415/pow(2.0, 12.0);
	  temporal.SetBinContent(k*4,(carddata->Data[(j*carddata->buffersize)+(k*2)]-offset)*conversion);
	  temporal.SetBinContent((k*4)+1,(carddata->Data[(j*carddata->buffersize)+(k*2)+1]-offset)*conversion);
	  temporal.SetBinContent((k*4)+2,(carddata->Data[(j*carddata->buffersize)+(k*2)+(carddata->buffersize/2)]-offset)*conversion);
	  temporal.SetBinContent((k*4)+3,(carddata->Data[(j*carddata->buffersize)+(k*2)+(carddata->buffersize/2)+1]-offset)*conversion);

        }

	//std::cout<<"d13"<<std::endl;

	//std::cout<<"d3"<<std::endl;
	
	temporalplots.push_back(temporal);


	////// find x,y,z fill event display /////////
	int x=-10;
	int z=-10;
	int y=-10;
	for(int pmt=0;pmt<PMTInfo.size();pmt++){
	  //std::cout<<"d4"<<std::endl;

	  if(PMTInfo.at(pmt).card==carddata->CardID && PMTInfo.at(pmt).channel==j){
	    x=PMTInfo.at(pmt).gx;
	    z=PMTInfo.at(pmt).gz;
	    y=PMTInfo.at(pmt).gy;
	    //std::cout<<"d15"<<std::endl;
	  
}
	}

	/*
	int x=(((i*4)+j)%8);
	int y=(floor(((i*4)+j)/8.0));
	if(x==0 && y==0){x=-10;y=-10;}
	if(x==7 && y==0){x=-10;y=-10;}
	if(x==0 && y==7){x=-10;y=-10;}
	if(x==7 && y==7){x=-10;y=-10;}
	if (y>7){x=-10;y=-10;}
	std::cout<<"i="<<i<<" j="<<j<<" (i*4)+j)="<<((i*4)+j)<<" x="<<x<<" y="<<y<<" sum="<<sum<<std::endl;
	EventDisplay.SetBinContent(x+1,y+1,sum);
	//EventDisplay.SetBinContent(((i*4)+j),sum);
	*/
	//std::cout<<"d16"<<std::endl;

	if(x!=-10 && z!=-10){
	  //std::cout<<"d17"<<std::endl;

	  //std::cout<<"gx = "<<x<<" , gz="<<z<<std::endl;
	  EventDisplay.SetBinContent(x+2,z+2,sum);
	  RMSDisplay.SetBinContent(x+2,z+2,gaus->GetParameter(2)*100);

	  //// Attempted 2ne event display ///
	  TGraph2D *dt=new TGraph2D(1);
	  dt->SetPoint(0,x,z,z);
	  dt->SetMarkerStyle(20);
	  //dt->GetXaxis()->SetRangeUser(-1,8);
	  // dt->GetYaxis()->SetRangeUser(-1,8);
	  //dt->GetZaxis()->SetRangeUser(-1,8);
	  mg.push_back(dt);
	}	
	
	}
	
	//std::cout<<"d18"<<std::endl;

	

	///////Find max freq for scaling//////////

	int maxplot=0;
	long maxvalue=0;
	
	//std::cout<<"i="<<i<<" (i*4)="<<(i*4)<<" (i*4)+4="<<(i*4)+4<<" size="<<freqplots.size()<<std::endl;
	for(int j=(i*4);j<(i*4)+4;j++){
	  if (freqplots.at(j).GetMaximum()>maxvalue){
	    //std::cout<<"d19"<<std::endl;
	 
   maxvalue=freqplots.at(j).GetMaximum();
	    maxplot=j;
	  }
	}
	

	//std::cout<<"d20"<<std::endl;

	////////Find current time and plot frewuency plot

	time_t t = time(0);   // get time now
	struct tm * now = localtime( & t );
	std::stringstream title;
	title<<"Card "<<carddata->CardID<<" frequency: "<<(now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' <<  now->tm_mday<<','<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec;
	//std::cout<<"d21"<<std::endl;
	freqplots.at(maxplot).SetTitle(title.str().c_str());
	freqplots.at(maxplot).GetXaxis()->SetTitle("ADC Value");
	freqplots.at(maxplot).GetYaxis()->SetTitle("Frequency");	
	freqplots.at(maxplot).SetLineColor((maxplot%4)+1);
	freqplots.at(maxplot).Draw();
	TLegend leg(0.8,0.4,1.0,0.7);
	//leg.SetHeader("The Legend Title");
	
	//std::cout<<"d22"<<std::endl;
for(int j=(i*4);j<(i*4)+4;j++){
  //std::cout<<"d23"<<std::endl;
	  std::stringstream legend;
	  legend<<"Channel "<<j-(i*4);
	  leg.AddEntry(&freqplots.at(j),legend.str().c_str(),"l");	  
	  freqplots.at(j).SetLineColor((j%4)+1);
	  if(j==maxplot){;}//freqplots.at(i).Draw();                                  
	  else freqplots.at(j).Draw("same");
	  
	}
	leg.Draw();
	//std::cout<<"d24"<<std::endl;
	std::stringstream tmp;
	tmp<<outpath<<carddata->CardID<<"freq.jpg";
	c1.SaveAs(tmp.str().c_str());


	//std::cout<<"d25"<<std::endl;



	///////find max tmporal plot for scaling
	
	///temporal
	maxplot=0;
	maxvalue=0;

	//std::cout<<"i="<<i<<" (i*4)="<<(i*4)<<" (i*4)+4="<<(i*4)+4<<" size="<<freqplots.size()<<std::endl;
        for(int j=(i*4);j<(i*4)+4;j++){
	  //std::cout<<"d26"<<std::endl;
          if (temporalplots.at(j).GetMaximum()>maxvalue){
            maxvalue=temporalplots.at(j).GetMaximum();
            maxplot=j;
          }
        }

	//std::cout<<"d27"<<std::endl;


	//////// Find time and plot temporal plot

	t = time(0);   // get time now
        now = localtime( & t );
	std::stringstream title2;
        title2<<"Card "<<carddata->CardID<<" Temporal: "<<(now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' <<  now->tm_mday<<','<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec;
	//std::cout<<"d28"<<std::endl;
        temporalplots.at(maxplot).SetTitle(title2.str().c_str());
	temporalplots.at(maxplot).GetXaxis()->SetTitle("Samples");
	temporalplots.at(maxplot).GetYaxis()->SetTitle("Volate (V)");
        temporalplots.at(maxplot).SetLineColor((maxplot%4)+1);
        temporalplots.at(maxplot).Draw();
	TLegend leg2(0.8,0.4,1.0,0.7);
	//std::cout<<"d29"<<std::endl;
	for(int j=(i*4);j<(i*4)+4;j++){
	  //std::cout<<"d30"<<std::endl;
	  std::stringstream legend;
	  legend<<"Channel "<<j-(i*4);	  
	  leg2.AddEntry(&temporalplots.at(j),legend.str().c_str(),"l");
	  temporalplots.at(j).SetLineColor((j%4)+1);
	  if(j==0){;}
	  else temporalplots.at(j).Draw("same");

	}
	//std::cout<<"d31"<<std::endl;
	leg2.Draw();
	//std::cout<<"d6"<<std::endl;

	std::stringstream tmp2;
	tmp2<<outpath<<carddata->CardID<<"temporal.jpg";
	c1.SaveAs(tmp2.str().c_str());
	//std::cout<<"d32"<<std::endl;


	///////plotting PED time and ped rms time //////
        maxplot=0;
        maxvalue=0;

      
        for(int j=0;j<4;j++){
          //std::cout<<"d26"<<std::endl;
          if ( PedTime[carddata->CardID].at(j).GetMaximum()>maxvalue){
            maxvalue=PedTime[carddata->CardID].at(j).GetMaximum();
            maxplot=j;
          }
        }

	t = time(0);   // get time now
        now = localtime( & t );
	title2.str("");
        title2<<"Card "<<carddata->CardID<<" Pedistal Variation: "<<(now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' <<  now->tm_mday<<','<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec;
        //std::cout<<"d28"<<std::endl;
        PedTime[carddata->CardID].at(maxplot).SetTitle(title2.str().c_str());
	PedTime[carddata->CardID].at(maxplot).GetXaxis()->SetTitle("Samples");
	PedTime[carddata->CardID].at(maxplot).GetYaxis()->SetTitle("ADC Value");
	PedTime[carddata->CardID].at(maxplot).SetLineColor((maxplot%4)+1);
	PedTime[carddata->CardID].at(maxplot).Draw();
        TLegend leg3(0.8,0.4,1.0,0.7);
        //std::cout<<"d29"<<std::endl;
	for(int j=0;j<4;j++){
          //std::cout<<"d30"<<std::endl;
	  std::stringstream legend;
          legend<<"Channel "<<j;
          leg3.AddEntry(&PedTime[carddata->CardID].at(j),legend.str().c_str(),"l");
	  PedTime[carddata->CardID].at(j).SetLineColor((j%4)+1);
          PedTime[carddata->CardID].at(j).Draw("same");

        }
        //std::cout<<"d31"<<std::endl;
        leg3.Draw();
        //std::cout<<"d6"<<std::endl;

	tmp2.str("");
	tmp2<<outpath<<"plots2/"<<carddata->CardID<<"PedTime.jpg";
	c1.SaveAs(tmp2.str().c_str());



	PedRMSTime[carddata->CardID].at(0).Draw();
	for (int channel=1;channel<4;channel++){
	  PedRMSTime[carddata->CardID].at(channel).Draw("same");
	}
	tmp2.str("");
	tmp2<<outpath<<"plots2/"<<carddata->CardID<<"PedRMSTime.jpg";
	c1.SaveAs(tmp2.str().c_str());

	delete carddata;

	
      } /// size i
      
      /*
      //std::cout<<"d4"<<std::endl;

      int maxplot=0;
      long maxvalue=0;
      for(int i=0;i<freqplots.size();i++){
	if (freqplots.at(i).GetMaximum()>maxvalue){
	  maxvalue=freqplots.at(i).GetMaximum();
	  maxplot=i;
	}
      }

      freqplots.at(maxplot).SetLineColor(maxplot+1);
      freqplots.at(maxplot).Draw();
      for(int i=0;i<freqplots.size();i++){

	//	Double_t scale = 1/freqplots.at(i).GetMaximum();
	//	freqplots.at(i).Scale(scale);
	freqplots.at(i).SetLineColor(i+1);
	if(i==maxplot);//freqplots.at(i).Draw();
	else freqplots.at(i).Draw("same");

	//freqplots.at(i).Scale((1.0/scale));
      }
      std::cout<<"d5"<<std::endl;

      std::stringstream tmp;
      tmp<<outpath<<"freq.jpg";
      c1.SaveAs(tmp.str().c_str());
      
      for(int i=0;i<temporalplots.size();i++){
	temporalplots.at(i).SetLineColor(i+1);
	if(i==0)temporalplots.at(i).Draw();
	else temporalplots.at(i).Draw("same");
	
      }	  

      std::cout<<"d6"<<std::endl;

      std::stringstream tmp2;
      tmp2<<outpath<<"temporal.jpg";
      c1.SaveAs(tmp2.str().c_str());
      */
      //std::cout<<"d33"<<std::endl;


      /////////plot event display /////////

      EventDisplay.Draw("COLZ");
      std::stringstream tmp3;
      tmp3<<outpath<<"0EventDisplay.jpg";
      c1.SaveAs(tmp3.str().c_str());
      

      //std::cout<<"d34 ="<<mg.size()<<std::endl;

/////////plot RMS display /////////
      RMSDisplay.Draw("COLZ");
      tmp3.str("");
      tmp3<<outpath<<"0RMSDisplay.jpg";
      c1.SaveAs(tmp3.str().c_str());

      ///plot  atempted 3d event display///////

      tmp3.str("");
      if(mg.size()>0)      mg.at(0)->Draw();
      for(int plots=1;plots<mg.size();plots++){
	mg.at(plots)->Draw("same");
	//std::cout<<"d35"<<std::endl;
      }
      tmp3<<outpath<<"0EventDisplay3D.jpg";
      //c1.SaveAs(tmp3.str().c_str());





    }
    
    
    
    else if(arg1=="Quit"){
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @param[in] gradients Compute gradients?
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            Specified observation is not of the expected type.
 *
 * If the @p gradients flag is true the method will also set the parameter
 * gradients of the model parameters.
 *
 * @todo Make sure that DETX and DETY are always set in GCTAInstDir.
 ***************************************************************************/
double GCTAModelAeffBackground::eval(const GEvent&       event,
                                     const GObservation& obs,
                                     const bool&         gradients) const
{
    // 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_EVAL, 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_EVAL, msg);
    }

    // Retrieve 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_EVAL, msg);
    }

    // Extract CTA instrument direction from event
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Set DETX and DETY in instrument direction
    GCTAInstDir inst_dir = cta->pointing().instdir(dir->dir());

    // Set theta and phi from instrument coordinates
    double theta = std::sqrt(inst_dir.detx() * inst_dir.detx() +
                             inst_dir.dety() * inst_dir.dety());
    double phi   = gammalib::atan2d(inst_dir.dety(), inst_dir.detx()) *
                   gammalib::deg2rad;

    // Evaluate function
    double logE = event.energy().log10TeV();
    double spat = (*aeff)(logE, theta, phi,
                          cta->pointing().zenith(),
                          cta->pointing().azimuth(), false);
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time(), gradients)
                  : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time(), gradients) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    double deadc = obs.deadc(event.time());
    value       *= deadc;

    // Optionally compute partial derivatives
    if (gradients) {

        // Multiply factors to spectral gradients
        if (spectral() != NULL) {
            double fact = spat * temp * deadc;
            if (fact != 1.0) {
                for (int i = 0; i < spectral()->size(); ++i)
                    (*spectral())[i].factor_gradient((*spectral())[i].factor_gradient() * fact );
            }
        }

        // Multiply factors to temporal gradients
        if (temporal() != NULL) {
            double fact = spat * spec * deadc;
            if (fact != 1.0) {
                for (int i = 0; i < temporal()->size(); ++i)
                    (*temporal())[i].factor_gradient((*temporal())[i].factor_gradient() * fact );
            }
        }

    } // endif: computed partial derivatives

    // Return value
    return value;
}
/***********************************************************************//**
 * @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;
}
Example #15
0
/***********************************************************************//**
 * @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 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 data 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
 *            No CTA event list found in observation.
 *            No CTA pointing found in observation.
 *
 * Spatially integrates the data 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/exposure time).
 ***************************************************************************/
double GCTAModelBackground::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 << "GCTAModelBackground::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 was found
    if (!has_npred) {

        // Evaluate only if model is valid
        if (valid_model()) {

            // 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);
            }

            #if !defined(G_NPRED_AROUND_ROI)
			// Get CTA pointing direction
			GCTAPointing* pnt = dynamic_cast<GCTAPointing*>(obs.pointing());
            if (pnt == NULL) {
                std::string msg = "No CTA pointing found in observation.\n" +
                                  obs.print();
                throw GException::invalid_argument(G_NPRED, msg);
            }
            #endif

            // 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 distance from ROI centre in radians
            #if defined(G_NPRED_AROUND_ROI)
			double roi_distance = 0.0;
            #else
			double roi_distance = roi_centre.dist(pnt->dir());
            #endif

			// Initialise rotation matrix to transform from ROI system to
            // celestial coordinate system
			GMatrix ry;
			GMatrix rz;
			ry.eulery(roi_centre.dec_deg() - 90.0);
			rz.eulerz(-roi_centre.ra_deg());
			GMatrix rot = (ry * rz).transpose();

			// Compute position angle of ROI centre with respect to model
			// centre (radians)
            #if defined(G_NPRED_AROUND_ROI)
            double omega0 = 0.0;
            #else
			double omega0 = pnt->dir().posang(events->roi().centre().dir());
            #endif

			// Setup integration function
			GCTAModelBackground::npred_roi_kern_theta integrand(spatial(),
                                                                obsEng,
                                                                obsTime,
                                                                rot,
                                                                roi_radius,
                                                                roi_distance,
                                                                omega0);

			// Setup integrator
			GIntegral integral(&integrand);
			integral.eps(1e-3);

			// Setup integration boundaries
            #if defined(G_NPRED_AROUND_ROI)
			double rmin = 0.0;
			double rmax = roi_radius;
            #else
			double rmin = (roi_distance > roi_radius) ? roi_distance-roi_radius : 0.0;
			double rmax = roi_radius + roi_distance;
            #endif

			// Spatially integrate radial component
			npred = integral.romb(rmin, rmax);

	        // 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::cout << "*** ERROR: GCTAModelBackground::npred:";
	            std::cout << " NaN/Inf encountered";
	            std::cout << " (npred=" << npred;
	            std::cout << ", roi_radius=" << roi_radius;
	            std::cout << ")" << std::endl;
	        }
	        #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 Evaluate function and gradients
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            No CTA instrument direction found in event.
 *
 * Evaluates tha CTA background model and parameter gradients. The CTA
 * background model is a factorization of a spatial, spectral and
 * temporal model component. This method also applies a deadtime correction
 * factor, so that the normalization of the model is a real rate
 * (counts/exposure time).
 *
 * @todo Add bookkeeping of last value and evaluate only if argument 
 *       changed
 ***************************************************************************/
double GCTAModelBackground::eval_gradients(const GEvent& event,
                                           const GObservation& obs) const
{
    // Get pointer on CTA observation
    const GCTAObservation* ctaobs = dynamic_cast<const GCTAObservation*>(&obs);
    if (ctaobs == NULL) {
        std::string msg = "Specified observation is not a CTA observation.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL_GRADIENTS, msg);
    }

    // Extract CTA instrument direction
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL_GRADIENTS, msg);
    }

    // Create a Photon from the event
    // We need the photon to evaluate the spatial model
    // For the background, GEvent and GPhoton are identical
    // since the IRFs are not folded in
    GPhoton photon = GPhoton(dir->dir(), event.energy(),event.time());

    // Evaluate function and gradients
    double spat = (spatial() != NULL)
                  ? spatial()->eval_gradients(photon) : 1.0;
    double spec = (spectral() != NULL)
                  ? spectral()->eval_gradients(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval_gradients(event.time()) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    double deadc = obs.deadc(event.time());
    value       *= deadc;

    // Multiply factors to spatial gradients
    if (spatial() != NULL) {
        double fact = spec * temp * deadc;
        if (fact != 1.0) {
            for (int i = 0; i < spatial()->size(); ++i)
                (*spatial())[i].factor_gradient( (*spatial())[i].factor_gradient() * fact );
        }
    }

    // Multiply factors to spectral gradients
    if (spectral() != NULL) {
        double fact = spat * temp * deadc;
        if (fact != 1.0) {
            for (int i = 0; i < spectral()->size(); ++i)
                (*spectral())[i].factor_gradient( (*spectral())[i].factor_gradient() * fact );
        }
    }

    // Multiply factors to temporal gradients
    if (temporal() != NULL) {
        double fact = spat * spec * deadc;
        if (fact != 1.0) {
            for (int i = 0; i < temporal()->size(); ++i)
                (*temporal())[i].factor_gradient( (*temporal())[i].factor_gradient() * fact );
        }
    }

    // Return value
    return value;
}
Example #19
0
/***********************************************************************//**
 * @brief Returns spatial model component
 *
 * @param[in] event Observed event.
 * @param[in] srcEng True photon energy.
 * @param[in] srcTime True photon arrival time.
 * @param[in] obs Observation.
 * @param[in] grad Evaluate gradients.
 *
 * @exception GException::no_response
 *            Observation has no valid instrument response
 *
 * This method computes the spatial model component for a given true photon
 * energy and arrival time.
 ***************************************************************************/
double GModelSky::spatial(const GEvent& event,
                          const GEnergy& srcEng, const GTime& srcTime,
                          const GObservation& obs, bool grad) const
{
    // Initialise result
    double value = 0.0;

    // Continue only if the model has a spatial component
    if (m_spatial != NULL) {

        // Get response function
        GResponse* rsp = obs.response();
        if (rsp == NULL) {
            throw GException::no_response(G_SPATIAL);
        }

        // Set source
        GSource source(this->name(), *m_spatial, srcEng, srcTime);

        // Get IRF value. This method returns the spatial component of the
        // source model.
        double irf = rsp->irf(event, source, obs);

        // Case A: evaluate gradients
        if (grad) {

            // Evaluate source model
            double spec = (spectral() != NULL) ? spectral()->eval_gradients(srcEng)  : 1.0;
            double temp = (temporal() != NULL) ? temporal()->eval_gradients(srcTime) : 1.0;

            // Set value
            value = spec * temp * irf;

            // Compile option: Check for NaN/Inf
#if defined(G_NAN_CHECK)
            if (isnotanumber(value) || isinfinite(value)) {
                std::cout << "*** ERROR: GModelSky::spatial:";
                std::cout << " NaN/Inf encountered";
                std::cout << " (value=" << value;
                std::cout << ", spec=" << spec;
                std::cout << ", temp=" << temp;
                std::cout << ", irf=" << irf;
                std::cout << ")" << std::endl;
            }
#endif

            // Multiply factors to spectral gradients
            if (spectral() != NULL) {
                double fact = temp * irf;
                if (fact != 1.0) {
                    for (int i = 0; i < spectral()->size(); ++i) {
                        (*spectral())[i].gradient((*spectral())[i].gradient() * fact);
                    }
                }
            }

            // Multiply factors to temporal gradients
            if (temporal() != NULL) {
                double fact = spec * irf;
                if (fact != 1.0) {
                    for (int i = 0; i < temporal()->size(); ++i) {
                        (*temporal())[i].gradient((*temporal())[i].gradient() * fact);
                    }
                }
            }

        } // endif: gradient evaluation has been requested

        // Case B: evaluate no gradients
        else {

            // Evaluate source model
            double spec = (m_spectral != NULL) ? m_spectral->eval(srcEng) : 1.0;
            double temp = (m_temporal != NULL) ? m_temporal->eval(srcTime) : 1.0;

            // Set value
            value = spec * temp * irf;

            // Compile option: Check for NaN/Inf
#if defined(G_NAN_CHECK)
            if (isnotanumber(value) || isinfinite(value)) {
                std::cout << "*** ERROR: GModelSky::spatial:";
                std::cout << " NaN/Inf encountered";
                std::cout << " (value=" << value;
                std::cout << ", spec=" << spec;
                std::cout << ", temp=" << temp;
                std::cout << ", irf=" << irf;
                std::cout << ")" << std::endl;
            }
#endif

        }

    } // endif: Gamma-ray source model had a spatial component

    // Return value
    return value;
}