//=============================================================================
// Fill the tuple
//=============================================================================
StatusCode TupleToolTrackPosition::fill( const LHCb::Particle *, const LHCb::Particle *   part,
                                         const std::string &   head, Tuples::Tuple &   tuple )
{

  const std::string prefix=fullName(head);
  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Fill" << endmsg;

  bool test=true;

  double X=-999999;
  double Y=-999999;


  if( part && part->proto() && part->proto()->track() )
  {

    if ( msgLevel(MSG::VERBOSE) ) verbose() << "extrapolating track to Z="<< m_Z << endmsg;

    LHCb::State aState=LHCb::State();
    //const LHCb::Track aTrack= *(part->proto()->track());
    StatusCode sc=m_extrapolator->stateFromTrajectory(aState,*(part->proto()->track()),m_Z);
    if(sc.isSuccess())
    {
      X=aState.x();
      Y=aState.y();
    }

  }

  test &= tuple->column( prefix+"_X", X );
  test &= tuple->column( prefix+"_Y", Y );

  return StatusCode(test);
}
Пример #2
0
//=============================================================================
// Main execution
//=============================================================================
StatusCode EventNodeKiller::execute() {

  if (msgLevel() <= MSG::DEBUG) debug() << "==> Execute" << endmsg;

  std::vector<std::string>::iterator itS;
  for( itS=m_nodes.begin(); itS != m_nodes.end(); itS++ ) {
    if (msgLevel() <= MSG::DEBUG) debug() << "Killing node " << *itS << endmsg;
    eventSvc()->unlinkObject( *itS ).ignore();
  }

  return StatusCode::SUCCESS;
}
Пример #3
0
//=============================================================================
// Initialization
//=============================================================================
StatusCode PatPixelHitManager::initialize() {
	m_event_number = 0;
	m_max_hits = 0;
  StatusCode sc = GaudiTool::initialize(); // must be executed first
  if ( sc.isFailure() ) return sc;  // error printed already by GaudiAlgorithm

  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Initialize" << endmsg;

  m_veloPix      = getDet<DeVeloPix>( DeVeloPixLocation::Default );

  // make sure we are up-to-date on populated VELO stations
  registerCondition( (*(m_veloPix->leftSensorsBegin()))->geometry(), &PatPixelHitManager::rebuildGeometry );
  registerCondition( (*(m_veloPix->rightSensorsBegin()))->geometry(), &PatPixelHitManager::rebuildGeometry );

  // first update
  sc = updMgrSvc()->update(this);
  if(!sc.isSuccess()) {
    return Error( "Failed to update station structure." );
  }

  // invalidate measurements at the beginning of each event
  incSvc()->addListener(this, IncidentType::BeginEvent);

  m_pool.resize( 10000 );
  m_nextInPool = m_pool.begin();
  m_maxSize = 0;
  m_eventReady = false;

  return StatusCode::SUCCESS;
}
Пример #4
0
/// Initialization.
StatusCode CpuHungryAlg::initialize() {
  StatusCode sc = GaudiAlgorithm::initialize(); // must be executed first
  if ( sc.isFailure() ) return sc; // error printed already by GaudiAlgorithm

  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Initialize" << endmsg;
  return StatusCode::SUCCESS;
}
Пример #5
0
//=========================================================================
//  Execute the endRun() of every algorithm
//=========================================================================
StatusCode GaudiSequencer::endRun ( ) {

  if ( !isEnabled() ) return StatusCode::SUCCESS;

  if (msgLevel(MSG::DEBUG)) debug() << "==> endRun" << endmsg;
  return StatusCode::SUCCESS;
}
Пример #6
0
StatusCode CreatePositionedHit::execute() {

  //Get the input caloHits collection
  const fcc::CaloHitCollection* calocells = m_caloCells.get();
  debug() << "Input caloCells collection size: " << calocells->size() << endmsg;

  //Initialize output CaloClusterCollection
  auto edmPositionedHitCollection = m_caloPositionedHits.createAndPut();

  //Intialize value of the half size in r
  double r_cell_size_half = -1.;
  uint64_t id = 0;
  auto decoder = m_geoSvc->lcdd()->readout(m_readoutName).idSpec().decoder();
  //Loop though CaloHits, calculate position from cellID, create and fill information in a CaloCluster
  for (const auto& cell : *calocells) {
    id = cell.core().cellId;

    //Current active layer r-minimum r
    //Volume dimensions of Tube - det::utils::tubeDimensions(volumeID) - ThreeVector rmin, rmax, dz (half-length)
    double rmin_layer = det::utils::tubeDimensions(id).x();
    //Next active layer [ needed for r_cell = middle of the cell (active + passive) ]
    //If half size of cell in r not known, calculate it from the next layer r-min
    decoder->setValue(id);
    if (r_cell_size_half < 0) {
      if ((*decoder)[m_activeFieldName] < m_numLayers - 1) {
        (*decoder)[m_activeFieldName] = (*decoder)[m_activeFieldName] + 1;
        uint64_t cellID_next = decoder->getValue();
        double rmin_layer_next = det::utils::tubeDimensions(cellID_next).x();
        r_cell_size_half = (rmin_layer_next - rmin_layer)*0.5;
      }
      else {
        info() << "Cell size in r not defined!!!! " << endmsg;
      }
    }
    //r_cell: middle of the cell (active + passive)
    double r_cell = rmin_layer+r_cell_size_half;

    //Global position of the cell
    auto position =  m_segmentation->positionFromREtaPhi( r_cell, m_segmentation->eta(id), m_segmentation->phi(id) );
    auto edmPos = fcc::Point();
    edmPos.x = position.x();
    edmPos.y = position.y();
    edmPos.z = position.z();

    auto positionedHit = edmPositionedHitCollection->create(edmPos, cell.core());

    //Debug information about cells
    if ( msgLevel ( MSG::DEBUG ) ) {
      debug() << "cellID " << id <<" energy " << cell.core().energy << " decoder: all fields "
              << decoder->valueString() << " r " << r_cell << " eta " <<  m_segmentation->eta(id)
              << " phi " <<  m_segmentation->phi(id)<< endmsg;
    }
  }
  debug() << "Output CaloCluster collection size: " << edmPositionedHitCollection->size() << endmsg;


  return StatusCode::SUCCESS;
}
//=============================================================================
// Initialization
//=============================================================================
StatusCode TupleToolTrackPosition::initialize()
{
  const StatusCode sc = TupleToolBase::initialize();
  if ( sc.isFailure() ) return sc;

  m_extrapolator=tool<ITrackStateProvider>(m_extrapolatorName,this);

  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Initialize" << endmsg;

  return sc;
}
Пример #8
0
//=============================================================================
// Initialization
//=============================================================================
StatusCode ReadTES::initialize() {
    StatusCode sc = GaudiAlgorithm::initialize(); // must be executed first
    if ( sc.isFailure() ) return sc;  // error printed already by GaudiAlgorithm

    if ( msgLevel(MSG::DEBUG) ) debug() << "==> Initialize" << endmsg;

    if ( m_locations.empty() )
        return Error( "You must define at least one TES Location" );

    return StatusCode::SUCCESS;
}
Пример #9
0
//=============================================================================
// Main execution
//=============================================================================
StatusCode ReadTES::execute() {

    if ( msgLevel(MSG::DEBUG) ) debug() << "==> Execute" << endmsg;

    for ( std::vector<std::string>::iterator it  = m_locations.begin();
            it != m_locations.end(); it++ ) {
        DataObject* pTES = get<DataObject>( *it );
        info() << "Found object " << *it << " at " << pTES << endmsg;
    }

    return StatusCode::SUCCESS;
}
Пример #10
0
// ============================================================================
// Main execution
// ============================================================================
StatusCode RecordOutputStream::execute() {
  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Execute" << endmsg;

  getOrCreate<DataObject, DataObject>(m_flagLocation, false);
  /*
  if (!exist(m_flagLocation, false)) {
    DataObject *obj = new DataObject();
    put(obj, m_flagLocation, false);
  }
  */
  return StatusCode::SUCCESS;
}
Пример #11
0
// ============================================================================
// Initialization
// ============================================================================
StatusCode RecordOutputStream::initialize() {
  StatusCode sc = GaudiAlgorithm::initialize(); // must be executed first
  if ( sc.isFailure() ) return sc; // error printed already by GaudiAlgorithm

  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Initialize" << endmsg;

  if (m_streamName.empty()) {
    m_streamName = "Deferred:" + name();
    debug() << "Using default OutputStreamName: '"
            << m_streamName << "'" << endmsg;
  }

  m_flagLocation = locationRoot() + "/" + m_streamName;
  return StatusCode::SUCCESS;
}
Пример #12
0
StatusCode CpuHungryAlg::execute() {
  m_nevent++;
  double result = 0;
  if (name() == "Alg1") {
    result = mysin();
  }else if (name() == "Alg2") {
    result = mycos();
  }else {
    result = mytan();
  }
  // This part is pointless, but prevent a warning about a
  // set, but unused, variable (result).
  if ( msgLevel(MSG::DEBUG) )
    debug() << "Result = " << result << endmsg;
  return StatusCode::SUCCESS;
}
Пример #13
0
//=========================================================================
//  Rebuild the geometry. Needed in case something changes in the Velo during the run...
//=========================================================================
StatusCode PatPixelHitManager::rebuildGeometry ( ) {

  for ( std::vector<PatPixelSensor*>::iterator itS = m_sensors.begin(); m_sensors.end() != itS; ++itS ) {
    if ( NULL != *itS ) delete *itS;
  }
  m_sensors.clear();
  m_firstSensor = 999;
  m_lastSensor  = 0;

  std::vector<int> previous(2,-1);

  for ( std::vector<DeVeloPixSensor*>::const_iterator itS = m_veloPix->sensorsBegin();
        m_veloPix->sensorsEnd() > itS; ++itS ) {
    //== TO BE DONE ===   if ( !(*itS)->isReadOut() ) continue;
    PatPixelSensor* sens = new PatPixelSensor( *itS );
    while ( m_sensors.size() < sens->number() ) {
      m_sensors.push_back( 0 );
    }
    m_sensors.push_back( sens );
    int side = 0;
    unsigned int number = sens->number();
    if ( sens->isRight() ) side = 1;
    if ( m_firstSensor > number ) m_firstSensor = number;
    if ( m_lastSensor  < number ) m_lastSensor  = number;
    sens->setPrevious( previous[side] );
    previous[side] = number;
  }

  previous[0] = -1;
  previous[1] = -1;


  if ( msgLevel( MSG::DEBUG ) ) {
    info() << "Found sensors from " << m_firstSensor << " to " << m_lastSensor << endmsg;

    for ( std::vector<PatPixelSensor*>::iterator itS = m_sensors.begin(); m_sensors.end() != itS; ++itS ) {
      if ( 0 != *itS) {
        info() << "   Sensor " << (*itS)->number() << " prev " << (*itS)->previous() << endmsg;
      }
    }
  }
  return StatusCode::SUCCESS;
}
Пример #14
0
/*
    Called when the connection to the server changes (connected/disconnected)
*/
void
Museek::SearchManager::onServerLoggedInStateChanged(bool loggedIn)
{
    if(loggedIn) {
        uint level = branchLevel();
        uint depth = branchLevel();
        DistributedSocket * parentSocket = parent();
        std::string parentName = museekd()->server()->username();
        if (parentSocket)
            parentName = parentSocket->user();

        NNLOG("museekd.peers.debug", "Asking parents (level: %d, root: %s, child depth:%d)", level, parentName.c_str(), depth);

        SHaveNoParents msgNoParents(true);
        museekd()->server()->sendMessage(msgNoParents.make_network_packet());

        SBranchLevel msgLevel(level);
        museekd()->server()->sendMessage(msgLevel.make_network_packet());

        SBranchRoot msgRoot(parentName);
        museekd()->server()->sendMessage(msgRoot.make_network_packet());

        SChildDepth msgDepth(depth);
        museekd()->server()->sendMessage(msgDepth.make_network_packet());

        SAcceptChildren msgAccept(true);
        museekd()->server()->sendMessage(msgAccept.make_network_packet());

        // We want to know our own transfer speed. Ask the server for it.
        museekd()->peers()->requestUserData(museekd()->server()->username());
    }
    else if(!parent()) {
        // If we're the root of our branch and we get disconnected, we should disconnect from our children to let them go on a living branch
        std::map<std::string, std::pair<NewNet::RefPtr<DistributedSocket>, uint> >::iterator it;
        for (it = m_Children.begin(); it != m_Children.end(); it++) {
            if (it->second.first)
                it->second.first->stop();
        }
        m_Children.clear();
    }
}
Пример #15
0
// ============================================================================
// standard finalization method
// ============================================================================
StatusCode    GaudiTool::finalize   ()
{
  if ( msgLevel(MSG::DEBUG) )
    debug() << " ==> Finalize the base class GaudiTool " << endmsg;

  // clear "explicit services"
    m_evtSvc    = 0 ;
    m_detSvc    = 0 ;
    m_chronoSvc = 0 ;
    m_incSvc    = 0 ;
    m_histoSvc  = 0 ;

  // finalize the base class
  const StatusCode sc = GaudiCommon<AlgTool>::finalize() ;
  if ( sc.isFailure() ) { return sc; }

  // Decrement the counter
  GaudiToolLocal::s_FinalizeCounter.decrement( m_local ) ;

  // return
  return sc;
}
Пример #16
0
StatusCode EventSelector::finalize()    {

  if (msgLevel(MSG::DEBUG)) {
    MsgStream log(msgSvc(), name());
    log << MSG::DEBUG << "finalize()" << endmsg;
  }

  m_incidentSvc = 0;

  if (m_streamtool) {
    if (m_toolSvc.isValid()) {
      m_toolSvc->releaseTool(m_streamtool).ignore();
    } else {
      // It should not be possible to get here
      m_streamtool->release();
    }
    m_streamtool = 0;
  }

  m_toolSvc = 0;

  return Service::finalize();
}
Пример #17
0
//=============================================================================
// Initialization
//=============================================================================
StatusCode VertexCompare::initialize() {
  StatusCode sc = GaudiTupleAlg::initialize(); // Must be executed first
  if(msgLevel(MSG::DEBUG)) debug() << "==> Initialize" << endmsg;

  m_forcedBtool = tool<IForcedBDecayTool> ( "ForcedBDecayTool", this );
  if( ! m_forcedBtool ) {
    fatal() << "Unable to retrieve ForcedBDecayTool tool "<< endmsg;
    return StatusCode::FAILURE;
  }

  // Access PVOfflineTool
//   m_pvsfit = tool<IPVOfflineTool>("PVOfflineTool",this);
//   if(!m_pvsfit) {
//     err() << "Unable to retrieve the PVOfflineTool" << endmsg;
//     return  StatusCode::FAILURE;
//   }

  m_nevt      = 0;
  m_nVtx      = 0;
  m_nPartVtx  = 0;

  return StatusCode::SUCCESS;
}
Пример #18
0
//=============================================================================
// Initialisation. Check parameters
//=============================================================================
StatusCode GaudiSequencer::initialize() {
  GaudiAlgorithm::initialize();

  if (msgLevel(MSG::DEBUG)) debug() << "==> Initialise" << endmsg;

  StatusCode status = decodeNames();
  if ( !status.isSuccess() ) return status;

  m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" );
  if ( m_timerTool->globalTiming() ) m_measureTime = true;

  if ( m_measureTime ) {
    m_timer = m_timerTool->addTimer( name() );
    m_timerTool->increaseIndent();
  } else {
    release( m_timerTool );
    m_timerTool = 0;
  }

  //== Initialize the algorithms
  std::vector<AlgorithmEntry>::iterator itE;
  for ( itE = m_entries.begin(); m_entries.end() != itE; itE++ ) {
    if ( m_measureTime ) {
      itE->setTimer( m_timerTool->addTimer( itE->algorithm()->name() ) );
    }

    status = itE->algorithm()->sysInitialize();
    if ( !status.isSuccess() ) {
      return Error( "Can not initialize " + itE->algorithm()->name(),
                    status );
    }
  }
  if ( m_measureTime ) m_timerTool->decreaseIndent();

  return StatusCode::SUCCESS;
}
Пример #19
0
//
// Convert internal Delphes objects: MCParticles to FCC EDM: MCParticle & GenVertices
//
void DelphesSimulation::ConvertMCParticles(const TObjArray* Input,
                                           fcc::MCParticleCollection* colMCParticles,
                                           fcc::GenVertexCollection* colGenVertices) {

  //Initialize MC particle vertex mapping: production & decay vertex
  std::vector<std::pair<int, int>> vecPartProdVtxIDDecVtxID;

  vecPartProdVtxIDDecVtxID.resize(Input->GetEntries());
  for(int j=0; j<Input->GetEntries(); j++) {
    vecPartProdVtxIDDecVtxID[j].first  = -1;
    vecPartProdVtxIDDecVtxID[j].second = -1;
  }

  // Find true daughters of the colliding particles (necessary fix for missing links
  // between primary colliding particles and their daughters if LHE file used within Pythia)
  std::set<int> primary1Daughters;
  std::set<int> primary2Daughters;

  for(int j=0; j<Input->GetEntries(); j++) {

    auto cand = static_cast<Candidate *>(m_allParticles->At(j));

    // Go through all not primary particles
    if (cand->M1!=-1) {
      for (int iMother=cand->M1; iMother<=cand->M2; iMother++) {

        if (iMother==0) primary1Daughters.insert(j);
        if (iMother==1) primary2Daughters.insert(j);
      }
    }
  } // Fix

  // Save MC particles and vertices
  for(int j=0; j<Input->GetEntries(); j++) {

    auto cand     = static_cast<Candidate *>(m_allParticles->At(j));
    auto particle = colMCParticles->create();

    auto barePart     = fcc::BareParticle();
    barePart.Type     = cand->PID;
    barePart.Status   = cand->Status;
    barePart.P4.Px    = cand->Momentum.Px();
    barePart.P4.Py    = cand->Momentum.Py();
    barePart.P4.Pz    = cand->Momentum.Pz();
    barePart.P4.Mass  = cand->Momentum.M();
    barePart.Charge   = cand->Charge;
    barePart.Vertex.X = cand->Position.X();
    barePart.Vertex.Y = cand->Position.Y();
    barePart.Vertex.Z = cand->Position.Z();

    if (cand->M1==-1)      barePart.Bits = static_cast<unsigned>(ParticleStatus::kBeam);
    else if (cand->D1==-1) barePart.Bits = static_cast<unsigned>(ParticleStatus::kStable);
    else                   barePart.Bits = static_cast<unsigned>(ParticleStatus::kDecayed);

    particle.Core(barePart);

    // Mapping the vertices
    int& idPartStartVertex = vecPartProdVtxIDDecVtxID[j].first;
    int& idPartEndVertex   = vecPartProdVtxIDDecVtxID[j].second;

    // Production vertex
    if (cand->M1!=-1) {
      if (idPartStartVertex!=-1) {
        particle.StartVertex(colMCParticles->at(idPartStartVertex).EndVertex());
      }
      else {
        fcc::Point point;
        point.X = cand->Position.X();
        point.Y = cand->Position.Y();
        point.Z = cand->Position.Z();

        auto vertex = colGenVertices->create();
        vertex.Position(point);
        vertex.Ctau(cand->Position.T());
        particle.StartVertex(vertex);

        idPartStartVertex = j;
      }
      for (int iMother=cand->M1; iMother<=cand->M2; iMother++) {
        if (vecPartProdVtxIDDecVtxID[iMother].second==-1) vecPartProdVtxIDDecVtxID[iMother].second = j;
      }
    }
    // Decay vertex
    if (cand->D1!=-1) {
      Candidate* daughter  = static_cast<Candidate *>(Input->At(cand->D1));

      if (idPartEndVertex!=-1) {
        particle.EndVertex(colMCParticles->at(idPartEndVertex).StartVertex());
      }
      else {
        fcc::Point point;
        point.X  = daughter->Position.X();
        point.Y  = daughter->Position.Y();
        point.Z  = daughter->Position.Z();

        auto vertex = colGenVertices->create();
        vertex.Position(point);
        vertex.Ctau(cand->Position.T());
        particle.EndVertex(vertex);

        idPartEndVertex = cand->D1;
      }

      // Option for colliding particles -> broken daughters range -> use only D1, which is correctly set (D2 & D2-D1 is wrong!!!)
      if (cand->M1==-1) {

        // Primary particle 0 correction
        if (j==0) for (const int& iDaughter : primary1Daughters) {

          if (iDaughter>=0 && vecPartProdVtxIDDecVtxID[iDaughter].first==-1) vecPartProdVtxIDDecVtxID[iDaughter].first = j;
        }
        // Primary particle 1 correction
        else if (j==1) for (const int& iDaughter : primary2Daughters) {

          if (iDaughter>=0 && vecPartProdVtxIDDecVtxID[iDaughter].first==-1) vecPartProdVtxIDDecVtxID[iDaughter].first = j;
        }
      }
      // Option for all other particles
      else {
        for (int iDaughter=cand->D1; iDaughter<=cand->D2; iDaughter++) {

          if (iDaughter>=0 && vecPartProdVtxIDDecVtxID[iDaughter].first==-1) vecPartProdVtxIDDecVtxID[iDaughter].first = j;
        }
      }
    }

    // Debug: print FCC-EDM MCParticle and GenVertex
    if (msgLevel() <= MSG::DEBUG) {

      double partE = sqrt(particle.Core().P4.Px*particle.Core().P4.Px +
                          particle.Core().P4.Py*particle.Core().P4.Py +
                          particle.Core().P4.Pz*particle.Core().P4.Pz +
                          particle.Core().P4.Mass*particle.Core().P4.Mass);

      debug() << "MCParticle: "
              << " Id: "       << std::setw(3)  << j+1
              << " Pdg: "      << std::setw(5)  << particle.Core().Type
              << " Stat: "     << std::setw(2)  << particle.Core().Status
              << " Bits: "     << std::setw(2)  << particle.Core().Bits
              << std::scientific
              << " Px: "       << std::setprecision(2) << std::setw(9) << particle.Core().P4.Px
              << " Py: "       << std::setprecision(2) << std::setw(9) << particle.Core().P4.Py
              << " Pz: "       << std::setprecision(2) << std::setw(9) << particle.Core().P4.Pz
              << " E: "        << std::setprecision(2) << std::setw(9) << partE
              << " M: "        << std::setprecision(2) << std::setw(9) << particle.Core().P4.Mass;
      if (particle.StartVertex().isAvailable()) {
        debug() << " VSId: "     << std::setw(3)  << vecPartProdVtxIDDecVtxID[j].first+1;
                //<< " Vx: "       << std::setprecision(2) << std::setw(9) << particle.StartVertex().Position().X
                //<< " Vy: "       << std::setprecision(2) << std::setw(9) << particle.StartVertex().Position().Y
                //<< " Vz: "       << std::setprecision(2) << std::setw(9) << particle.StartVertex().Position().Z
                //<< " T: "        << std::setprecision(2) << std::setw(9) << particle.StartVertex().Ctau();
      }
      if (particle.EndVertex().isAvailable()) {
        debug() << " VEId: "     << std::setw(3)  << vecPartProdVtxIDDecVtxID[j].second+1;
                //<< " Vx: "       << std::setprecision(2) << std::setw(9) << particle.EndVertex().Position().X
                //<< " Vy: "       << std::setprecision(2) << std::setw(9) << particle.EndVertex().Position().Y
                //<< " Vz: "       << std::setprecision(2) << std::setw(9) << particle.EndVertex().Position().Z
                //<< " T: "        << std::setprecision(2) << std::setw(9) << particle.EndVertex().Ctau();
      }
      debug() << std::fixed << endmsg;

    } // Debug
  }
}
Пример #20
0
StatusCode DelphesSaveGenJets::saveOutput(Delphes& delphes, const fcc::MCParticleCollection& mcParticles) {
  // Create the collections
  auto colGenJets = m_genJets.createAndPut();
  auto colTaggedJets = m_taggedGenJets.createAndPut();

  const TObjArray* delphesColl = delphes.ImportArray(m_delphesArrayName.c_str());
  if (delphesColl == nullptr) {
    warning() << "Delphes collection " << m_delphesArrayName << " not present. Skipping it." << endmsg;
    return StatusCode::SUCCESS;
  }

  for(int j = 0; j < delphesColl->GetEntries(); ++j) {

    auto cand = static_cast<Candidate *>(delphesColl->At(j));

    // Jet info
    auto jet         = colGenJets->create();
    auto bareJet     = fcc::BareJet();
    bareJet.area     = -1;
    bareJet.p4.px    = cand->Momentum.Px();
    bareJet.p4.py    = cand->Momentum.Py();
    bareJet.p4.pz    = cand->Momentum.Pz();
    bareJet.p4.mass  = cand->Mass;
    jet.core(bareJet);

    // Flavor-tag info
    auto flavorGenJet = colTaggedJets->create();
    flavorGenJet.tag(cand->Flavor);
    flavorGenJet.jet(jet);

    // Debug: print FCC-EDM jets info
    if (msgLevel() <= MSG::DEBUG) {

      double energy = sqrt(jet.p4().px*jet.p4().px +
                           jet.p4().py*jet.p4().py +
                           jet.p4().pz*jet.p4().pz +
                           jet.p4().mass*jet.p4().mass);

      debug() << "Gen Jet: "
              << " Id: "       << std::setw(3)  << j+1
              << " Flavor: "   << std::setw(3)  << flavorGenJet.tag()
              << std::scientific
              << " Px: "       << std::setprecision(2) << std::setw(9) << jet.p4().px
              << " Py: "       << std::setprecision(2) << std::setw(9) << jet.p4().py
              << " Pz: "       << std::setprecision(2) << std::setw(9) << jet.p4().pz
              << " E: "        << std::setprecision(2) << std::setw(9) << energy
              << " M: "        << std::setprecision(2) << std::setw(9) << jet.p4().mass
              << std::fixed
              << std::endl;
    }

    // Reference to MC - Delphes holds references to all objects related to the Jet object,
    // several relations might exist -> find "recursively" in a tree history the MC particle.
    // Add index to the reference index field to avoid double counting
    std::set<int> idRefMCPart; // Avoid double counting when referencingh MC particles

    // Recursive procedure stops after the relation found is the one to MC particle and not to
    // a particle object. If particle not related to MC particle (<0 value)
    findJetPartMC(cand, mcParticles.size(), idRefMCPart);

    // Debug: print variable
    double totSimE = 0;

    for (auto id : idRefMCPart) {
      auto& mcParticle = mcParticles.at(id);
      jet.addparticles(mcParticles.at(id));

      // Debug: print FCC-EDM jet relation info
      if (msgLevel() <= MSG::DEBUG) {
        double recE   = sqrt(jet.p4().px*jet.p4().px +
                             jet.p4().py*jet.p4().py +
                             jet.p4().pz*jet.p4().pz +
                             jet.p4().mass*jet.p4().mass);
        double simE   = sqrt(mcParticle.p4().px*mcParticle.p4().px +
                             mcParticle.p4().py*mcParticle.p4().py +
                             mcParticle.p4().pz*mcParticle.p4().pz +
                             mcParticle.p4().mass*mcParticle.p4().mass);
        totSimE += simE;
        debug() << " RefId: " << std::setw(3)            << id+1
                << " Rel E: " << std::setprecision(2)
                              << std::scientific
                              << std::setw(9) << simE    << " "
                              << std::setw(9) << totSimE << " <-> "
                              << std::setw(9) << recE
                              << std::fixed
                              << std::endl;
      } // Debug
    }

    // Debug: print end-line
    if (msgLevel() <= MSG::DEBUG) debug() << endmsg;
  } // For - jets
  return StatusCode::SUCCESS;
}
Пример #21
0
// ============================================================================
// Finalize
// ============================================================================
StatusCode RecordOutputStream::finalize() {
  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Finalize" << endmsg;

  return GaudiAlgorithm::finalize(); // must be called after all other actions
}
Пример #22
0
//=============================================================================
//  Finalize
//=============================================================================
StatusCode GaudiSequencer::finalize() {

  if (msgLevel(MSG::DEBUG)) debug() << "==> Finalize" << endmsg;
  return  GaudiAlgorithm::finalize();
}
Пример #23
0
//=============================================================================
// Main execution
//=============================================================================
StatusCode GaudiSequencer::execute() {

  if ( m_measureTime ) m_timerTool->start( m_timer );

  if (msgLevel(MSG::DEBUG)) debug() << "==> Execute" << endmsg;

  StatusCode result = StatusCode::SUCCESS;

  bool seqPass = !m_modeOR; //  for OR, result will be false, unless (at least) one is true
                            //  for AND, result will be true, unless (at least) one is false
                            //    also see comment below ....

  std::vector<AlgorithmEntry>::const_iterator itE;
  for ( itE = m_entries.begin(); m_entries.end() != itE; ++itE ) {
    Algorithm* myAlg = itE->algorithm();
    if ( ! myAlg->isEnabled() ) continue;
    if ( ! myAlg->isExecuted() ) {
      if ( m_measureTime ) m_timerTool->start( itE->timer() );
      result = myAlg->sysExecute();
      if ( m_measureTime ) m_timerTool->stop( itE->timer() );
      myAlg->setExecuted( true );
      if ( ! result.isSuccess() ) break;  //== Abort and return bad status
    }
    //== Check the returned status
    if ( !m_ignoreFilter ) {
      bool passed = myAlg->filterPassed();
      if (msgLevel(MSG::VERBOSE))
        verbose() << "Algorithm " << myAlg->name() << " returned filter passed "
                  << (passed ? "true" : "false") << endmsg;
      if ( itE->reverse() ) passed = !passed;


      //== indicate our own result. For OR, exit as soon as true.
      //        If no more, will exit with false.
      //== for AND, exit as soon as false. Else, will be true (default)

      // if not short-circuiting, make sure we latch iPass to 'true' in
      // OR mode (i.e. it is sufficient for one item to be true in order
      // to be true at the end, and thus we start out at 'false'), and latch
      // to 'false' in AND mode (i.e. it is sufficient for one item to
      // be false to the false in the end, and thus we start out at 'true')
      // -- i.e. we should not just blindly return the 'last' passed status!

      // or to put it another way: in OR mode, we don't care about things
      // which are false, as they leave our current state alone (provided
      // we stared as 'false'!), and in AND mode, we keep our current
      // state until someone returns 'false' (provided we started as 'true')
      if ( m_modeOR ? passed : !passed ) {
        seqPass = passed;
        if (msgLevel(MSG::VERBOSE))
          verbose() << "SeqPass is now " << (seqPass ? "true" : "false") << endmsg;
        if (m_shortCircuit) break;
      }
    }

  }
  if (msgLevel(MSG::VERBOSE))
      verbose() << "SeqPass is " << (seqPass ? "true" : "false") << endmsg;
  if ( !m_ignoreFilter && !m_entries.empty() ) setFilterPassed( seqPass );
  setExecuted( true );

  if ( m_measureTime ) m_timerTool->stop( m_timer );

  return m_returnOK ? StatusCode::SUCCESS : result;
}
Пример #24
0
/// Finalize
StatusCode CpuHungryAlg::finalize() {
  if ( msgLevel(MSG::DEBUG) ) debug() << "==> Finalize" << endmsg;

  return GaudiAlgorithm::finalize(); // must be called after all other actions
}
Пример #25
0
StatusCode DelphesSimulation::execute() {

  //
  // Read event & initialize event variables
  TStopwatch readStopWatch;
  readStopWatch.Start();

  StatusCode sc;

  // Read event
  const HepMC::GenEvent *hepMCEvent = m_hepmcHandle.get();
  sc = m_hepMCConverter->hepMCEventToArrays(hepMCEvent, *m_Delphes->GetFactory(), *m_allParticles, *m_stableParticles, *m_partons);
  if (!sc.isSuccess()) {
    return sc;
  }
  // Print debug: HepMC event info
  if (msgLevel() <= MSG::DEBUG) {

    for (auto ipart=hepMCEvent->particles_begin(); ipart!=hepMCEvent->particles_end(); ++ipart) {

      int motherID        = 0;
      int motherIDRange   = 0;
      int daughterID      = 0;
      int daughterIDRange = 0;
      if ((*ipart)->production_vertex()!=nullptr) {

        motherID      = (*((*ipart)->production_vertex()->particles_in_const_begin()))->barcode();
        motherIDRange = (*ipart)->production_vertex()->particles_in_size() -1;
      }
      if ((*ipart)->end_vertex()!=nullptr) {

        daughterID      = (*((*ipart)->end_vertex()->particles_out_const_begin()))->barcode();
        daughterIDRange = (*ipart)->end_vertex()->particles_out_size() -1;
      }

      debug() << "HepMC: "
              << " Id: "       << std::setw(3)  << (*ipart)->barcode()
              << " Pdg: "      << std::setw(5)  << (*ipart)->pdg_id()
              << " Mothers: "  << std::setw(4)  << motherID   << " -> " << std::setw(4) << motherID  +motherIDRange
              << " Daughters: "<< std::setw(4)  << daughterID << " -> " << std::setw(4) << daughterID+daughterIDRange
              << " Stat: "     << std::setw(2)  << (*ipart)->status()
              << std::scientific
              << " Px: "       << std::setprecision(2) << std::setw(9) << (*ipart)->momentum().px()
              << " Py: "       << std::setprecision(2) << std::setw(9) << (*ipart)->momentum().py()
              << " Pz: "       << std::setprecision(2) << std::setw(9) << (*ipart)->momentum().pz()
              << " E: "        << std::setprecision(2) << std::setw(9) << (*ipart)->momentum().e()
              << " M: "        << std::setprecision(2) << std::setw(9) << (*ipart)->momentum().m();
      if ((*ipart)->production_vertex()!=nullptr) {
        debug() << " Vx: "       << std::setprecision(2) << std::setw(9) << (*ipart)->production_vertex()->position().x()
                << " Vy: "       << std::setprecision(2) << std::setw(9) << (*ipart)->production_vertex()->position().y()
                << " Vz: "       << std::setprecision(2) << std::setw(9) << (*ipart)->production_vertex()->position().z()
                << " T: "        << std::setprecision(2) << std::setw(9) << (*ipart)->production_vertex()->position().t();
      }
      debug() << std::fixed << endmsg;
    }
  } // Debug

  // Print debug: Delphes event info
  if (msgLevel() <= MSG::DEBUG) {

    for (auto i=0; i<m_allParticles->GetEntries(); i++) {

      Candidate *candidate = static_cast<Candidate *>(m_allParticles->At(i));

      debug() << "DelphesMC: "
              << " Id: "       << std::setw(3)  << i+1
              << " Pdg: "      << std::setw(5)  << candidate->PID
              << " Mothers: "  << std::setw(4)  << candidate->M1+1 << " -> " << std::setw(4) << candidate->M2+1
              << " Daughters: "<< std::setw(4)  << candidate->D1+1 << " -> " << std::setw(4) << candidate->D2+1
              << " Stat: "     << std::setw(2)  << candidate->Status
              << std::scientific
              << " Px: "       << std::setprecision(2) << std::setw(9) << candidate->Momentum.Px()
              << " Py: "       << std::setprecision(2) << std::setw(9) << candidate->Momentum.Py()
              << " Pz: "       << std::setprecision(2) << std::setw(9) << candidate->Momentum.Pz()
              << " E: "        << std::setprecision(2) << std::setw(9) << candidate->Momentum.E()
              << " M: "        << std::setprecision(2) << std::setw(9) << candidate->Mass
              << " Vx: "       << std::setprecision(2) << std::setw(9) << candidate->Position.X()
              << " Vy: "       << std::setprecision(2) << std::setw(9) << candidate->Position.Y()
              << " Vz: "       << std::setprecision(2) << std::setw(9) << candidate->Position.Z()
              << " T: "        << std::setprecision(2) << std::setw(9) << candidate->Position.T()
              << std::fixed
              << endmsg;
    }
  } // Debug

  m_eventCounter++;
  readStopWatch.Stop();

  //
  // Process event
  TStopwatch procStopWatch;

  // Delphes process
  procStopWatch.Start();
  m_Delphes->ProcessTask();
  procStopWatch.Stop();

  // Generate Delphes branch: Event
  // m_hepMCConverter->MakeEventBranch(m_branchEvent, &readStopWatch, &procStopWatch);
  if (m_outRootFile!=nullptr) m_treeWriter->Fill();

  // FCC EDM (event-data model) based output
  auto genParticles       = m_handleGenParticles.createAndPut();
  auto genVertices        = m_handleGenVertices.createAndPut();

  if (m_allParticles !=nullptr) DelphesSimulation::ConvertMCParticles(m_allParticles , genParticles  , genVertices);

  for(auto saveTool : m_saveTools) {
    saveTool->saveOutput(*m_Delphes, *genParticles);
  }

  // Initialize for next event reading (Will also zero Delphes arrays)
  m_treeWriter->Clear();
  m_Delphes->Clear();

  return StatusCode::SUCCESS;
}
Пример #26
0
//=============================================================================
// Main execution
//=============================================================================
StatusCode PrTrackAssociator::execute() {

  // Retrieve the MCParticles
  LHCb::MCParticles* mcParts = getIfExists<LHCb::MCParticles> ( LHCb::MCParticleLocation::Default );
  if ( NULL == mcParts ) {
    if( msgLevel(MSG::ERROR) ) error() << "MCParticles at " << LHCb::MCParticleLocation::Default << "' do not exist" <<endmsg;
    return StatusCode::SUCCESS;
  }

  // Get the LHCbID to MCParticle linker
  LinkedTo<LHCb::MCParticle> idLinker( evtSvc(), msgSvc(), "Pr/LHCbID" );

  std::vector<std::string> trackContainers;
  if ( "" != m_singleContainer ) {
    trackContainers.push_back( m_singleContainer );
  } else {
    //== Scan the root directory and make a list of containers to process.
    DataObject* root =  getIfExists<DataObject*>( m_rootOfContainers );
    if ( NULL == root ) {
      if( msgLevel(MSG::DEBUG) ) debug() << "Root-of-Containers directory " <<   m_rootOfContainers << "' does not exist. Skipping." <<endmsg;
      return StatusCode::SUCCESS;
    }

    SmartIF<IDataManagerSvc> mgr( eventSvc() );
    typedef std::vector<IRegistry*> Leaves;
    Leaves leaves;
    StatusCode sc = mgr->objectLeaves( root, leaves );
    if ( sc ) {
      for ( Leaves::const_iterator iL = leaves.begin(); leaves.end() != iL; ++iL ) {
        const std::string& id = (*iL)->identifier();
        DataObject* tmp(NULL);
        sc = eventSvc()->findObject( id, tmp );
        if ( sc && NULL != tmp ) {
          for( unsigned int clID : m_containerIDs){
            if ( tmp->clID() == clID ) {
              trackContainers.push_back( id );
            }
          }
        }
      }
    }
  }

  for ( std::vector<std::string>::iterator itS = trackContainers.begin();
        trackContainers.end() != itS; ++itS ) {
    if( msgLevel(MSG::DEBUG) ) 
      debug() << "processing container: " << *itS << endreq ;

    // Create the Linker table from Track to MCParticle
    // Sorted by decreasing weight, so first retrieved has highest weight
    // This has to be done, even if there are no tracks in the event, to satisfy the DST writer
    LinkerWithKey<LHCb::MCParticle,LHCb::Track> myLinker( evtSvc(), msgSvc(), *itS );
    myLinker.reset() ;
    

    // Retrieve the Tracks
    LHCb::Track::Range tracks = getIfExists<LHCb::Track::Range> ( *itS );
    if ( tracks.empty() ) {
      if( msgLevel(MSG::DEBUG) ) debug() << "No tracks in container " <<  *itS << "' . Skipping." <<endmsg;
      continue;
    }

    // Loop over the Tracks
    for( auto tr  : tracks ) {
      m_total.reset();
      m_truthCounters.clear();

      // Loop over the LHCbIDs of the Track
      unsigned int nMeas = 0;
      for( std::vector<LHCb::LHCbID>::const_iterator iId = tr->lhcbIDs().begin();
           tr->lhcbIDs().end() != iId; ++iId ) {

        if( (*iId).isVelo() || (*iId).isVP() ) {
          ++nMeas;
          m_total.nVelo += 1.;       // Count number of Velo hits
          LHCb::MCParticle* part = idLinker.first( (*iId).lhcbID() );
          while( 0 != part ) {
            if( mcParts == part->parent() ) incrementVelo( part  );
            part = idLinker.next();
          }

        } else if ( (*iId).isTT() || (*iId).isUT() ) {
          ++nMeas;
          m_total.nTT += 1.;       // Count number of TT hits
          LHCb::MCParticle* part = idLinker.first( (*iId).lhcbID() );
          while( 0 != part ) {
            if( mcParts == part->parent() ) incrementTT( part  );
            part = idLinker.next();
          }

        } else if ( (*iId).isIT() || (*iId).isOT() || (*iId).isFT() ) {
          ++nMeas;
          m_total.nT += 1.;       // Count number of T hits
          LHCb::MCParticle* part = idLinker.first( (*iId).lhcbID() );
          while( 0 != part ) {
            if( mcParts == part->parent() ) incrementT( part  );
            part = idLinker.next();
          }
        }
      }

      // If the Track has total # Velo hits > 2 AND total # T hits > 2, cumul mother and daughter
      if( ( 2 < m_total.nVelo ) &&
          ( 2 < m_total.nT    ) ) {
        for ( std::vector<TruthCounter>::iterator it1 = m_truthCounters.begin();
              m_truthCounters.end() != it1; ++it1 ) {
          if ( (*it1).nT == 0 ) continue;
          const LHCb::MCVertex* vOrigin = (*it1).particle->originVertex();
          if ( 0 != vOrigin ) {
            const LHCb::MCParticle* mother = vOrigin->mother();
            if( 0 == mother ) continue; // no ancestor;
            for ( std::vector<TruthCounter>::iterator it2 = m_truthCounters.begin();
                  m_truthCounters.end() != it2; ++it2 ) {
              if( mother == (*it2).particle ) {
                if ( (*it2).nVelo == 0 ) continue;

                if( msgLevel(MSG::DEBUG) ) 
                  debug() << "  *** Particle " << (*it1).particle->key()
                          << "[" << (*it1).particle->particleID().pid()
                          << "] (" << (*it1).nVelo << "," << (*it1).nTT << "," << (*it1).nT << ")"
                          << " is daughter of " << (*it2).particle->key()
                          << "[" << (*it2).particle->particleID().pid()
                          << "] (" << (*it2).nVelo << "," << (*it2).nTT << "," << (*it2).nT << ")"
                          << " type " << vOrigin->type()
                          << ". Merge hits to tag both." << endmsg;

                //== Daughter hits are added to mother.
                (*it2).nVelo += (*it1).nVelo;
                (*it2).nTT   += (*it1).nTT;
                (*it2).nT    += (*it1).nT;
                if ( (*it2).nVelo > m_total.nVelo ) (*it2).nVelo = m_total.nVelo;
                if ( (*it2).nTT   > m_total.nTT   ) (*it2).nTT   = m_total.nTT;
                if ( (*it2).nT    > m_total.nT    ) (*it2).nT    = m_total.nT;

                //== Mother hits overwrite Daughter hits
                (*it1).nVelo = (*it2).nVelo;
                (*it1).nTT   = (*it2).nTT;
                (*it1).nT    = (*it2).nT;
              }
            }
          }
        }
      }

      //===============================================================
      // Association definition
      // Velo matching:
      //      * either less than 2 hits in total (no Velo on track)
      //      * or at least 'm_fractionOK' of the Velo hits are associated to this MCParticle.
      // TT matching:
      //      * this MC particle has at least nTT-2 hits.
      //      * or this track has both Velo and T stations: TT not used for long tracks.
      // T matching:
      //      * either less than 2 hits in total (no T station hits on track)
      //      * or at least 'm_fractionOK' of the T station hits are associated to this MCParticle.
      //
      // A MCParticle matches if all 4 criteria are OK.
      //===============================================================

      double ratio;
      for ( std::vector<TruthCounter>::iterator it = m_truthCounters.begin();
            m_truthCounters.end() != it; ++it ) {
        bool veloOK = true;
        if( 2 < m_total.nVelo ) {
          veloOK = false;
          ratio = (*it).nVelo / m_total.nVelo;
          if( m_fractionOK <= ratio ) { veloOK = true; }
        }

        bool tOK = true;
        if( 2 < m_total.nT ) {
          tOK = false;
          ratio =  (*it).nT / m_total.nT;
          if( m_fractionOK <= ratio ) { tOK = true; }
        }

        bool ttOK = (*it).nTT > m_total.nTT - 2;
        if( 2 < m_total.nVelo && 2 < m_total.nT ) { ttOK = true; }

        if( msgLevel(MSG::DEBUG) ) 
          debug() << "Track " << tr->key()
                  << " MC "   << (*it).particle->key()
                  << " Velo " << (*it).nVelo << "/" << m_total.nVelo
                  << " TT "   << (*it).nTT   << "/" << m_total.nTT
                  << " T "    << (*it).nT    << "/" << m_total.nT
                  << endmsg;

        //=== Decision. Fill Linker
        if( veloOK && tOK && ttOK && (0 < nMeas) ) {
          ratio = ( (*it).nVelo + (*it).nTT + (*it).nT ) / nMeas;
          myLinker.link( tr, (*it).particle, ratio );
        }
      }
    } // End loop over Tracks
  }

  return StatusCode::SUCCESS;
}
Пример #27
0
//=============================================================================
// Main execution
//=============================================================================
StatusCode VertexCompare::execute() {
  if(msgLevel(MSG::DEBUG)) debug() << "==> Execute" << endmsg;

  std::vector<LHCb::RecVertex*> vecOfVertices1;
  std::vector<LHCb::RecVertex*> vecOfVertices2;

  bool vertices_ok = getInputVertices(vecOfVertices1, vecOfVertices2);

  std::vector<LHCb::RecVertex> fullVrt1, fullVrt2;

  if (!vertices_ok) {
    return StatusCode::SUCCESS; // return SUCCESS anyway
  }
  if (debugLevel()) debug() << 
     "  Vtx Properities       x       y       z      chi2/ndof     ntracks" 
                            << endmsg;
  // Fill reconstructed PV info
  std::vector<LHCb::RecVertex*>::iterator itRecV1;
  for(itRecV1 = vecOfVertices1.begin(); vecOfVertices1.end() != itRecV1;
               itRecV1++) {
    LHCb::RecVertex* pv;
    pv = *itRecV1;
    fullVrt1.push_back(*pv);
//     int nTracks      = pv->tracks().size();
    if (debugLevel()) debug() << m_inputVerticesName1 << endmsg;
    if (debugLevel()) debug() << "              " << pv->position().x() << "   " 
                              << pv->position().y() << "   " << pv->position().z()  
                              << "   " << pv->chi2PerDoF()  << "   " << pv->tracks().size() << endmsg;
  } // end of loop over vertices1

  std::vector<LHCb::RecVertex*>::iterator itRecV2;
  for(itRecV2 = vecOfVertices2.begin(); vecOfVertices2.end() != itRecV2;
               itRecV2++) {
    LHCb::RecVertex* pv;
    pv = *itRecV2;
    fullVrt2.push_back(*pv);
//     int nTracks      = pv->tracks().size();
    if (debugLevel()) debug() << m_inputVerticesName2 << endmsg;
    if (debugLevel()) debug() << "              " 
                              << pv->position().x() << "   " 
                              << pv->position().y() << "   " 
                              << pv->position().z()  << "   " 
                              << pv->chi2PerDoF()  << "   " 
                              << pv->tracks().size() << endmsg;
  } // end of loop over vertices2
  if (debugLevel()) debug() << "fullVrt1 size   " << fullVrt1.size() << endmsg;
  if (debugLevel()) debug() << "fullVrt2 size   " << fullVrt2.size() << endmsg;
  int size_diff = fullVrt1.size() - fullVrt2.size();
  if(m_produceHistogram) {
    plot(double(size_diff), 1001, "size_diff", -5.5, 5.5, 11);
  }
  if(m_produceNtuple) {
    Tuple myTuple_evt = nTuple(101, "PV_nTuple_evt", CLID_ColumnWiseTuple);
    myTuple_evt->column("size_diff",  double(size_diff));
    myTuple_evt->column("size_1",  double(fullVrt1.size()));
    myTuple_evt->column("size_2",  double(fullVrt2.size()));
    myTuple_evt->write();
  }
  double dx          = -99999.;
  double dy          = -99999.;
  double dz          = -99999.;
  double errx        = -99999.;
  double erry        = -99999.;
  double errz        = -99999.;
  double covxx1      = -99999.;
  double covyy1      = -99999.;
  double covzz1      = -99999.;
  double covxy1      = -99999.;
  double covxz1      = -99999.;  
  double covyz1      = -99999.;

  double covxx2      = -99999.;
  double covyy2      = -99999.;
  double covzz2      = -99999.;
  double covxy2      = -99999.;
  double covxz2      = -99999.;  
  double covyz2      = -99999.;

  int ntracks_part  = 0;
  int ntracks_part2 = 0;
  int dtracks = 0;

  std::vector<LHCb::RecVertex>::iterator fullIter;
  int oIt=0;
  std::vector<int> link;
  if (fullVrt1.size()!=0 && fullVrt2.size()!=0) matchByDistance(fullVrt1, fullVrt2, link);
  else return StatusCode::SUCCESS;
  for (fullIter=fullVrt1.begin(); fullIter!=fullVrt1.end(); fullIter++){
    LHCb::RecVertex vrtf = *fullIter;
    m_nVtx++;
    if (link.at(oIt)==-1) continue;
    Gaudi::SymMatrix3x3 covPV_part1 = vrtf.covMatrix();
    double sigx_part1 = (covPV_part1(0,0));
    double sigy_part1 = (covPV_part1(1,1));
    double sigz_part1 = (covPV_part1(2,2));
    covxx1 = sigx_part1;
    covyy1 = sigy_part1;
    covzz1 = sigz_part1;
    covxy1 = (covPV_part1(0,1));
    covxz1 = (covPV_part1(0,2));
    covyz1 = (covPV_part1(1,2));
    

    Gaudi::SymMatrix3x3 covPV_part2 = fullVrt2.at(link.at(oIt)).covMatrix();
    double sigx_part2 = (covPV_part2(0,0));
    double sigy_part2 = (covPV_part2(1,1));
    double sigz_part2 = (covPV_part2(2,2));

    covxx2 = sigx_part2;
    covyy2 = sigy_part2;
    covzz2 = sigz_part2;
    covxy2 = (covPV_part2(0,1));
    covxz2 = (covPV_part2(0,2));
    covyz2 = (covPV_part2(1,2));
    
    double x1 = vrtf.position().x();
    double y1 = vrtf.position().y();
    double z1 = vrtf.position().z();
    
    double x2 = fullVrt2.at(link.at(oIt)).position().x();
    double y2 = fullVrt2.at(link.at(oIt)).position().y();
    double z2 = fullVrt2.at(link.at(oIt)).position().z();
                
    dx = vrtf.position().x()-fullVrt2.at(link.at(oIt)).position().x();
    dy = vrtf.position().y()-fullVrt2.at(link.at(oIt)).position().y();
    dz = vrtf.position().z()-fullVrt2.at(link.at(oIt)).position().z();

    errx = sqrt(sigx_part1 + sigx_part2);
    erry = sqrt(sigy_part1 + sigy_part2);
    errz = sqrt(sigz_part1 + sigz_part2);
    ntracks_part  = vrtf.tracks().size();
    ntracks_part2 = fullVrt2.at(link.at(oIt)).tracks().size();
    dtracks = ntracks_part - ntracks_part2;

    if(m_produceHistogram) {
      plot(dx, 1021, "dx", -0.25, 0.25, 50);
      plot(dy, 1022, "dy", -0.25, 0.25, 50);
      plot(dz, 1023, "dz", -1.5, 1.5, 60);
      plot(x1, 2021, "x1", -0.25, 0.25, 50);
      plot(y1, 2022, "y1", -0.25, 0.25, 50);
      plot(z1, 2023, "z1", -100., 100., 50);
      plot(x2, 3021, "x2", -0.25, 0.25, 50);
      plot(y2, 3022, "y2", -0.25, 0.25, 50);
      plot(z2, 3023, "z2", -100., 100., 50);
      plot(std::sqrt(sigx_part1), 4011, "x err 1",0., .1, 50);
      plot(std::sqrt(sigy_part1), 4012, "y err 1",0., .1, 50);
      plot(std::sqrt(sigz_part1), 4013, "z err 1",0., .5, 50);
      plot(std::sqrt(sigx_part2), 4021, "x err 2",0., .1, 50);
      plot(std::sqrt(sigy_part2), 4022, "y err 2",0., .1, 50);
      plot(std::sqrt(sigz_part2), 4023, "z err 2",0., .5, 50);
      plot(dx/errx, 1031, "pullx", -5., 5., 50);
      plot(dy/erry, 1032, "pully", -5., 5., 50);
      plot(dz/errz, 1033, "pullz", -5., 5., 50);
      plot(double(ntracks_part) , 1041, "ntracks_part1", 0., 150., 50);
      plot(double(ntracks_part2), 1042, "ntracks_part2", 0., 150., 50);
      plot(double(dtracks), 1043, "dtracks", 0., 150., 50);
      // dz to get false vertex rate from data
      if ( vecOfVertices1.size() > 1 ) {
        for ( unsigned int i1 = 0; i1 < vecOfVertices1.size(); i1++ ) {
          for ( unsigned int i2 = 0; i2 < vecOfVertices1.size(); i2++ ) {
            if (i2 != i1) {  
              double vdz = vecOfVertices1[i1]->position().z() - vecOfVertices1[i2]->position().z();
                plot(vdz,1201,"dz vertices 1", -150.,150.,100);
            }
          }
        }        
      }
      if ( vecOfVertices2.size() > 1 ) {
        for ( unsigned int i1 = 0; i1 < vecOfVertices2.size(); i1++ ) {
          for ( unsigned int i2 = 0; i2 < vecOfVertices2.size(); i2++ ) {
            if (i2 != i1) {  
              double vdz = vecOfVertices2[i1]->position().z() - vecOfVertices2[i2]->position().z();
              plot(vdz, 1202, "dz vertices 2", -150.,150.,100);
            }
          }
        }        
      }

    }
    if(m_produceNtuple) {
      Tuple myTuple = nTuple(102, "PV_nTuple", CLID_ColumnWiseTuple);
      myTuple->column("ntracks_part",  double(ntracks_part));
      myTuple->column("ntracks_part2",  double(ntracks_part2));
      myTuple->column("dtracks", double(dtracks));
      myTuple->column("dx",       dx);
      myTuple->column("dy",       dy);
      myTuple->column("dz",       dz);
      myTuple->column("x1",       x1);
      myTuple->column("y1",       y1);
      myTuple->column("z1",       z1);
      myTuple->column("x2",       x2);
      myTuple->column("y2",       y2);
      myTuple->column("z2",       z2);
      myTuple->column("errx",     errx);
      myTuple->column("erry",     erry);
      myTuple->column("errz",     errz);
      myTuple->column("covxx1",   covxx1);
      myTuple->column("covyy1",   covyy1);
      myTuple->column("covzz1",   covzz1);
      myTuple->column("covxy1",   covxy1);
      myTuple->column("covxz1",   covxz1);
      myTuple->column("covyz1",   covyz1);
      myTuple->column("covxx2",   covxx2);
      myTuple->column("covyy2",   covyy2);
      myTuple->column("covzz2",   covzz2);
      myTuple->column("covxy2",   covxy2);
      myTuple->column("covxz2",   covxz2);
      myTuple->column("covyz2",   covyz2);

      myTuple->write();
    }
    oIt++;
  }

  return StatusCode::SUCCESS;
}
Пример #28
0
StatusCode CreateFCChhCaloNoiseLevelMap::initialize() {
  // Initialize necessary Gaudi components
  if (Service::initialize().isFailure()) {
    error() << "Unable to initialize Service()" << endmsg;
    return StatusCode::FAILURE;
  }
  m_geoSvc = service("GeoSvc");
  if (!m_geoSvc) {
    error() << "Unable to locate Geometry Service. "
            << "Make sure you have GeoSvc and SimSvc in the right order in the configuration." << endmsg;
    return StatusCode::FAILURE;
  }
  std::unordered_map<uint64_t, std::pair<double,double>> map;

  //////////////////////////////////
  /// SEGMENTED ETA-PHI VOLUMES  ///
  //////////////////////////////////
  
  for (uint iSys = 0; iSys < m_readoutNamesSegmented.size(); iSys++) {
    // Check if readouts exist
    info() << "Readout: " << m_readoutNamesSegmented[iSys] << endmsg;
    if (m_geoSvc->lcdd()->readouts().find(m_readoutNamesSegmented[iSys]) == m_geoSvc->lcdd()->readouts().end()) {
      error() << "Readout <<" << m_readoutNamesSegmented[iSys] << ">> does not exist." << endmsg;
      return StatusCode::FAILURE;
    }
    // get PhiEta segmentation
    dd4hep::DDSegmentation::FCCSWGridPhiEta* segmentation;
    segmentation = dynamic_cast<dd4hep::DDSegmentation::FCCSWGridPhiEta*>(
        m_geoSvc->lcdd()->readout(m_readoutNamesSegmented[iSys]).segmentation().segmentation());
    if (segmentation == nullptr) {
      error() << "There is no phi-eta segmentation!!!!" << endmsg;
      return StatusCode::FAILURE;
    }

    info() << "GridPhiEta: size in eta " << segmentation->gridSizeEta() << " , bins in phi " << segmentation->phiBins()
           << endmsg;
    info() << "GridPhiEta: offset in eta " << segmentation->offsetEta() << " , offset in phi "
           << segmentation->offsetPhi() << endmsg;

    auto decoder = m_geoSvc->lcdd()->readout(m_readoutNamesSegmented[iSys]).idSpec().decoder();
    // Loop over all cells in the calorimeter and retrieve existing cellIDs
    // Loop over active layers
    std::vector<std::pair<int, int>> extrema;
    extrema.push_back(std::make_pair(0, m_activeVolumesNumbersSegmented[iSys] - 1));
    extrema.push_back(std::make_pair(0, 0));
    extrema.push_back(std::make_pair(0, 0));
    for (unsigned int ilayer = 0; ilayer < m_activeVolumesNumbersSegmented[iSys]; ilayer++) {
      dd4hep::DDSegmentation::CellID volumeId = 0;
      // Get VolumeID
      (*decoder)[m_fieldNamesSegmented[iSys]].set(volumeId, m_fieldValuesSegmented[iSys]);
      (*decoder)[m_activeFieldNamesSegmented[iSys]].set(volumeId, ilayer);
      (*decoder)["eta"].set(volumeId, 0);
      (*decoder)["phi"].set(volumeId, 0);
      // Get number of segmentation cells within the active volume
      auto numCells = det::utils::numberOfCells(volumeId, *segmentation);
      extrema[1] = std::make_pair(0, numCells[0] - 1);
      if(m_fieldNamesSegmented[iSys] == "system" &&
	      m_fieldValuesSegmented[iSys] == 8){
	uint cellsEta = ceil(( 2*m_activeVolumesEta[ilayer] - segmentation->gridSizeEta() ) / 2 / segmentation->gridSizeEta()) * 2 + 1; //ceil( 2*m_activeVolumesRadii[ilayer] / segmentation->gridSizeEta());
	uint minEtaID = int(floor(( - m_activeVolumesEta[ilayer] + 0.5 * segmentation->gridSizeEta() - segmentation->offsetEta()) / segmentation->gridSizeEta()));
	numCells[1]=cellsEta;
	numCells[2]=minEtaID;
      }
      debug() << "Number of segmentation cells in (phi,eta): " << numCells << endmsg;
      // Loop over segmenation cells
      for (unsigned int iphi = 0; iphi < numCells[0]; iphi++) {
        for (unsigned int ieta = 0; ieta < numCells[1]; ieta++) {
	  dd4hep::DDSegmentation::CellID cellId = volumeId;
	  decoder->set(cellId, "phi", iphi);
	  decoder->set(cellId, "eta", ieta + numCells[2]);  // start from the minimum existing eta cell in this layer
	  uint64_t id = cellId;
	  double noise = 0.;
	  double noiseOffset = 0.;
	  if (m_fieldValuesSegmented[iSys] == 8){
	    noise = m_hcalBarrelNoiseTool->getNoiseConstantPerCell(id);
	    noiseOffset = m_hcalBarrelNoiseTool->getNoiseOffsetPerCell(id);
	  } else if (m_fieldValuesSegmented[iSys] == 5){
	    noise = m_ecalBarrelNoiseTool->getNoiseConstantPerCell(id);
            noiseOffset = m_ecalBarrelNoiseTool->getNoiseOffsetPerCell(id);
	  }
          map.insert( std::pair<uint64_t, std::pair<double, double> >(id, std::make_pair(noise, noiseOffset) ) );
        }
      }
    }
  }

  //////////////////////////////////
  ///      NESTED VOLUMES        ///
  //////////////////////////////////

  for (uint iSys = 0; iSys < m_readoutNamesNested.size(); iSys++) {
    // Sanity check
    if (m_activeFieldNamesNested.size() != 3) {
      error() << "Property activeFieldNamesNested requires 3 names." << endmsg;
      return StatusCode::FAILURE;
    }
    // Check if readouts exist
    info() << "Readout: " << m_readoutNamesNested[iSys] << endmsg;
    if (m_geoSvc->lcdd()->readouts().find(m_readoutNamesNested[iSys]) == m_geoSvc->lcdd()->readouts().end()) {
      error() << "Readout <<" << m_readoutNamesNested[iSys] << ">> does not exist." << endmsg;
      return StatusCode::FAILURE;
    }
    auto decoder = m_geoSvc->lcdd()->readout(m_readoutNamesNested[iSys]).idSpec().decoder();
    // Get VolumeID
    dd4hep::DDSegmentation::CellID volumeId = 0;
    decoder->set(volumeId, m_fieldNameNested, m_fieldValuesNested[iSys]);
    // Get the total number of given hierarchy of active volumes
    auto highestVol = gGeoManager->GetTopVolume();
    std::vector<unsigned int> numVolumes;
    numVolumes.reserve(m_activeVolumeNamesNested.size());
    for (const auto& volName : m_activeVolumeNamesNested) {
      numVolumes.push_back(det::utils::countPlacedVolumes(highestVol, volName));
      info() << "Number of active volumes named " << volName << " is " << numVolumes.back() << endmsg;
      if (numVolumes.back() == 0) {
        error() << "Volume name " << volName << " not found! Check naming in detector description." << endmsg;
        return StatusCode::FAILURE;
      }
    }
    // First sort to figure out which volume is inside which one
    std::vector<std::pair<std::string, uint>> numVolumesMap;
    for (unsigned int it = 0; it < m_activeVolumeNamesNested.size(); it++) {
      // names of volumes (m_activeVolumeNamesNested) not needed anymore, only corresponding bitfield names are used
      // (m_activeFieldNamesNested)
      numVolumesMap.push_back(std::pair<std::string, uint>(m_activeFieldNamesNested[it], numVolumes[it]));
    }
    std::sort(
        numVolumesMap.begin(), numVolumesMap.end(),
        [](std::pair<std::string, uint> vol1, std::pair<std::string, uint> vol2) { return vol1.second < vol2.second; });
    // now recompute how many volumes exist within the larger volume
    for (unsigned int it = numVolumesMap.size() - 1; it > 0; it--) {
      if (numVolumesMap[it].second % numVolumesMap[it - 1].second != 0) {
        error() << "Given volumes are not nested in each other!" << endmsg;
        return StatusCode::FAILURE;
      }
      numVolumesMap[it].second /= numVolumesMap[it - 1].second;
    }
    // Debug calculation of total number of cells
    if (msgLevel() <= MSG::DEBUG) {
      unsigned int checkTotal = 1;
      for (const auto& vol : numVolumesMap) {
        debug() << "Number of active volumes named " << vol.first << " is " << vol.second << endmsg;
        checkTotal *= vol.second;
      }
      debug() << "Total number of cells ( " << numVolumesMap.back().first << " ) is " << checkTotal << endmsg;
    }
    // make sure the ordering above is as in property activeFieldNamesNested
    std::map<std::string, uint> activeVolumesNumbersNested;
    for (const auto& name : m_activeFieldNamesNested) {
      for (const auto& number : numVolumesMap) {
        if (name == number.first) {
          activeVolumesNumbersNested.insert(std::make_pair(number.first, number.second));
        }
      }
    }

    // Loop over all cells in the calorimeter and retrieve existing cellIDs
    // Loop over active layers
    std::vector<std::pair<int, int>> extrema;
    extrema.push_back(std::make_pair(0, activeVolumesNumbersNested.find(m_activeFieldNamesNested[0])->second - 1));
    extrema.push_back(std::make_pair(0, activeVolumesNumbersNested.find(m_activeFieldNamesNested[1])->second - 1));
    extrema.push_back(std::make_pair(0, activeVolumesNumbersNested.find(m_activeFieldNamesNested[2])->second - 1));
    for (unsigned int ilayer = 0; ilayer < activeVolumesNumbersNested.find(m_activeFieldNamesNested[0])->second;
         ilayer++) {
      for (unsigned int iphi = 0; iphi < activeVolumesNumbersNested.find(m_activeFieldNamesNested[1])->second; iphi++) {
        for (unsigned int iz = 0; iz < activeVolumesNumbersNested.find(m_activeFieldNamesNested[2])->second; iz++) {

	  dd4hep::DDSegmentation::CellID cID = volumeId;
          decoder->set(cID, m_activeFieldNamesNested[0], ilayer);
	  decoder->set(cID, m_activeFieldNamesNested[1], iphi);
	  decoder->set(cID, m_activeFieldNamesNested[2], iz);
	  
	  double noise = m_hcalBarrelNoiseTool->getNoiseConstantPerCell(cID);
	  double noiseOffset = m_hcalBarrelNoiseTool->getNoiseOffsetPerCell(cID);
	  
	  map.insert( std::pair<uint64_t, std::pair<double, double> >(cID, std::make_pair(noise, noiseOffset) ) );
        }
      }
    }
  }

  TFile file(m_outputFileName.c_str(), "RECREATE");
  file.cd();
  TTree tree("noisyCells", "Tree with map of noise per cell");
  uint64_t saveCellId;
  double saveNoiseLevel;
  double saveNoiseOffset;
  tree.Branch("cellId", &saveCellId, "cellId/l");
  tree.Branch("noiseLevel", &saveNoiseLevel);
  tree.Branch("noiseOffset", &saveNoiseOffset);
  for (const auto& item : map) {
    saveCellId = item.first;
    saveNoiseLevel = item.second.first;
    saveNoiseOffset = item.second.second;
    tree.Fill();
  }
  file.Write();
  file.Close();

  return StatusCode::SUCCESS;
}
Пример #29
0
//=============================================================================
//  Finalize
//=============================================================================
StatusCode VertexCompare::finalize() {

  if(msgLevel(MSG::DEBUG)) debug() << "==> Finalize" << endmsg;


  info() << " ============================================" << endmsg;
  info() << " Efficiencies for reconstructed vertices:    " << endmsg;
  info() << " ============================================" << endmsg;
  info() << " " << endmsg;

  info() << " There are " << m_nVtx
         << " pairs of vertices in processed events" << endmsg;
//   info() << " PV is isolated if dz to closest reconstructible MC PV >  "
//          << m_dzIsolated << " mm" << endmsg;
//   std::string ff = "by counting tracks";
// /*  if ( !m_matchByTracks )*/ ff = "by dz distance";
//   info() << " Two splited vertices matched:  "
//          <<  ff << endmsg;


//   info() << " " << endmsg;
//     printRat("All",       m_nPartVtx,       m_nVtx );

  const AIDA::IHistogram1D* dx = histo( HistoID(1021) ) ;
  const AIDA::IHistogram1D* pullx = histo( HistoID(1031) ) ;
  const AIDA::IHistogram1D* dy = histo( HistoID(1022) ) ;
  const AIDA::IHistogram1D* pully = histo( HistoID(1032) ) ;
  const AIDA::IHistogram1D* dz = histo( HistoID(1023) ) ;
  const AIDA::IHistogram1D* pullz = histo( HistoID(1033) ) ;
  if( dx ) {
    info() << "      ---------------------------------------" << endmsg;
    info() << "dx:    "
     << format( "mean =  %5.3f +/- %5.3f, RMS =  %5.3f +/- %5.3f",
          dx->mean(), Gaudi::Utils::HistoStats::meanErr(dx),
          dx->rms(), Gaudi::Utils::HistoStats::rmsErr(dx)) << endmsg ;
  }
  if( dy ) {
    info() << "dy:    "
     << format( "mean =  %5.3f +/- %5.3f, RMS =  %5.3f +/- %5.3f",
          dy->mean(), Gaudi::Utils::HistoStats::meanErr(dy),
          dy->rms(), Gaudi::Utils::HistoStats::rmsErr(dy)) << endmsg ;
  }
  if( dz ) {
    info() << "dz:    "
     << format( "mean =  %5.3f +/- %5.3f, RMS =  %5.3f +/- %5.3f",
          dz->mean(), Gaudi::Utils::HistoStats::meanErr(dz),
          dz->rms(), Gaudi::Utils::HistoStats::rmsErr(dz)) << endmsg ;
  }
  info() << "      ---------------------------------------" << endmsg;
  if( pullx ) {
    info() << "pullx: "
     << format( "mean =  %5.3f +/- %5.3f, RMS =  %5.3f +/- %5.3f",
          pullx->mean(), Gaudi::Utils::HistoStats::meanErr(pullx),
          pullx->rms(), Gaudi::Utils::HistoStats::rmsErr(pullx)) << endmsg ;
  }
  if( pully ) {
    info() << "pully: "
     << format( "mean =  %5.3f +/- %5.3f, RMS =  %5.3f +/- %5.3f",
          pully->mean(), Gaudi::Utils::HistoStats::meanErr(pully),
          pully->rms(), Gaudi::Utils::HistoStats::rmsErr(pully)) << endmsg ;
  }
  if( pullz ) {
    info() << "pullz: "
     << format( "mean =  %5.3f +/- %5.3f, RMS =  %5.3f +/- %5.3f",
          pullz->mean(), Gaudi::Utils::HistoStats::meanErr(pullz),
          pullz->rms(), Gaudi::Utils::HistoStats::rmsErr(pullz)) << endmsg ;
  }
  info() << " ============================================" << endmsg;
//
  return GaudiTupleAlg::finalize();  // Must be called after all other actions
}