CMS 3D CMS Logo

RunManagerMTWorker.cc
Go to the documentation of this file.
13 
15 
24 
30 
34 
37 
39 
45 
46 #include "G4Timer.hh"
47 #include "G4Event.hh"
48 #include "G4Run.hh"
49 #include "G4SystemOfUnits.hh"
50 #include "G4Threading.hh"
51 #include "G4UImanager.hh"
52 #include "G4WorkerThread.hh"
53 #include "G4WorkerRunManagerKernel.hh"
54 #include "G4StateManager.hh"
55 #include "G4TransportationManager.hh"
56 #include "G4Field.hh"
57 #include "G4FieldManager.hh"
58 #include "G4ScoringManager.hh"
59 
60 #include <atomic>
61 #include <memory>
62 
63 #include <thread>
64 #include <sstream>
65 #include <vector>
66 
67 static std::once_flag applyOnce;
68 static std::once_flag applyOnceEnd;
69 
70 // from https://hypernews.cern.ch/HyperNews/CMS/get/edmFramework/3302/2.html
71 namespace {
72  std::atomic<int> thread_counter{0};
73 
74  int get_new_thread_index() { return thread_counter++; }
75 
76  bool createWatchers(const edm::ParameterSet& iP,
77  SimActivityRegistry* iReg,
78  std::vector<std::shared_ptr<SimWatcher>>& oWatchers,
79  std::vector<std::shared_ptr<SimProducer>>& oProds,
80  int threadID) {
81  std::vector<edm::ParameterSet> ws = iP.getParameter<std::vector<edm::ParameterSet>>("Watchers");
82  if (ws.empty()) {
83  return false;
84  }
85 
86  for (auto& watcher : ws) {
87  std::unique_ptr<SimWatcherMakerBase> maker(
88  SimWatcherFactory::get()->create(watcher.getParameter<std::string>("type")));
89  if (maker == nullptr) {
90  throw cms::Exception("Configuration")
91  << "RunManagerMTWorker::createWatchers: "
92  << "Unable to find the requested Watcher " << watcher.getParameter<std::string>("type");
93  } else {
94  std::shared_ptr<SimWatcher> watcherTemp;
95  std::shared_ptr<SimProducer> producerTemp;
96  maker->make(watcher, *(iReg), watcherTemp, producerTemp);
97  if (nullptr != watcherTemp) {
98  if (!watcherTemp->isMT() && 0 < threadID) {
99  throw cms::Exception("Configuration")
100  << "RunManagerMTWorker::createWatchers: "
101  << "Unable to use Watcher " << watcher.getParameter<std::string>("type") << " if number of threads > 1";
102  } else {
103  oWatchers.push_back(watcherTemp);
104  if (nullptr != producerTemp) {
105  oProds.push_back(producerTemp);
106  }
107  }
108  }
109  }
110  }
111  return (!oWatchers.empty());
112  }
113 } // namespace
114 
116  std::unique_ptr<G4RunManagerKernel> kernel; //must be deleted last
117  std::unique_ptr<RunAction> userRunAction;
118  std::unique_ptr<SimRunInterface> runInterface;
119  std::unique_ptr<SimActivityRegistry> registry;
120  std::unique_ptr<SimTrackManager> trackManager;
121  std::vector<SensitiveTkDetector*> sensTkDets;
122  std::vector<SensitiveCaloDetector*> sensCaloDets;
123  std::vector<std::shared_ptr<SimWatcher>> watchers;
124  std::vector<std::shared_ptr<SimProducer>> producers;
125  // G4Run can only be deleted if there is a G4RunManager
126  // on the thread where the G4Run is being deleted,
127  // else it causes a segmentation fault
128  G4Run* currentRun = nullptr;
129  std::unique_ptr<G4Event> currentEvent;
131  bool threadInitialized = false;
132  bool runTerminated = false;
133 
134  TLSData() {}
135 
136  ~TLSData() = default;
137 };
138 
139 // This can not be a smart pointer since we must delete some of the members
140 // before leaving main() else we get a segmentation fault caused by accessing
141 // other 'singletons' after those singletons have been deleted. Instead we
142 // atempt to delete all TLS at RunManagerMTWorker destructor. If that fails for
143 // some reason, it is better to leak than cause a crash.
144 // thread_local RunManagerMTWorker::TLSData* RunManagerMTWorker::m_tls{nullptr};
145 
147  : m_generator(iConfig.getParameter<edm::ParameterSet>("Generator")),
148  m_InToken(iC.consumes<edm::HepMCProduct>(
149  iConfig.getParameter<edm::ParameterSet>("Generator").getParameter<edm::InputTag>("HepMCProductLabel"))),
150  m_theLHCTlinkToken(
151  iC.consumes<edm::LHCTransportLinkContainer>(iConfig.getParameter<edm::InputTag>("theLHCTlinkTag"))),
152  m_nonBeam(iConfig.getParameter<bool>("NonBeamEvent")),
153  m_UseG4EventManager(iConfig.getParameter<bool>("UseG4EventManager")),
154  m_pUseMagneticField(iConfig.getParameter<bool>("UseMagneticField")),
155  m_LHCTransport(iConfig.getParameter<bool>("LHCTransport")),
156  m_thread_index{get_new_thread_index()},
157  m_pField(iConfig.getParameter<edm::ParameterSet>("MagneticField")),
158  m_pRunAction(iConfig.getParameter<edm::ParameterSet>("RunAction")),
159  m_pEventAction(iConfig.getParameter<edm::ParameterSet>("EventAction")),
160  m_pStackingAction(iConfig.getParameter<edm::ParameterSet>("StackingAction")),
161  m_pTrackingAction(iConfig.getParameter<edm::ParameterSet>("TrackingAction")),
162  m_pSteppingAction(iConfig.getParameter<edm::ParameterSet>("SteppingAction")),
163  m_pCustomUIsession(iConfig.getUntrackedParameter<edm::ParameterSet>("CustomUIsession")),
164  m_G4CommandsEndRun(iConfig.getParameter<std::vector<std::string>>("G4CommandsEndRun")),
165  m_p(iConfig) {
166  int thisID = getThreadIndex();
167  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker for the thread " << thisID;
168 
169  // sensitive detectors
170  std::vector<std::string> onlySDs = iConfig.getParameter<std::vector<std::string>>("OnlySDs");
171  m_sdMakers = sim::sensitiveDetectorMakers(m_p, iC, onlySDs);
172 
173  // TLS and watchers
174  initializeTLS();
175  if (m_hasWatchers) {
176  for (auto& watcher : m_tls->watchers) {
177  watcher->registerConsumes(iC);
178  }
179  }
180  if (m_LHCTransport) {
181  m_LHCToken = iC.consumes<edm::HepMCProduct>(edm::InputTag("LHCTransport"));
182  }
183  if (m_pUseMagneticField) {
184  m_MagField = iC.esConsumes<MagneticField, IdealMagneticFieldRecord, edm::Transition::BeginRun>();
185  }
186  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker is constructed for the thread " << thisID;
187  unsigned int k = 0;
188  for (std::unordered_map<std::string, std::unique_ptr<SensitiveDetectorMakerBase>>::const_iterator itr =
189  m_sdMakers.begin();
190  itr != m_sdMakers.end();
191  ++itr, ++k)
192  edm::LogVerbatim("SimG4CoreApplication") << "SD[" << k << "] " << itr->first;
193 }
194 
196  m_tls = nullptr;
197  delete m_UIsession;
198 }
199 
201  int id = getThreadIndex();
202  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::beginRun for the thread " << id;
203  for (auto& maker : m_sdMakers) {
204  maker.second->beginRun(es);
205  }
206  if (m_pUseMagneticField) {
208  }
209  if (m_hasWatchers) {
210  for (auto& watcher : m_tls->watchers) {
211  watcher->beginRun(es);
212  }
213  }
214  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::beginRun done for the thread " << id;
215 }
216 
218  int id = getThreadIndex();
219  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::endRun for the thread " << id;
220  terminateRun();
221 }
222 
224  if (nullptr != m_tls) {
225  return;
226  }
227 
228  m_tls = new TLSData();
229  m_tls->registry = std::make_unique<SimActivityRegistry>();
230 
231  edm::Service<SimActivityRegistry> otherRegistry;
232  //Look for an outside SimActivityRegistry
233  // this is used by the visualization code
234  int thisID = getThreadIndex();
235  if (otherRegistry) {
236  m_tls->registry->connect(*otherRegistry);
237  if (thisID > 0) {
238  throw cms::Exception("Configuration")
239  << "RunManagerMTWorker::initializeTLS : "
240  << "SimActivityRegistry service (i.e. visualization) is not supported for more than 1 thread. "
241  << " \n If this use case is needed, RunManagerMTWorker has to be updated.";
242  }
243  }
245 }
246 
249  return;
250 
251  G4Timer timer;
252  timer.Start();
253 
254  // I guess everything initialized here should be in thread_local storage
255  initializeTLS();
256 
257  int thisID = getThreadIndex();
258  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::initializeG4 in thread " << thisID << " is started";
259 
260  // Initialize per-thread output
261  G4Threading::G4SetThreadId(thisID);
262  G4UImanager::GetUIpointer()->SetUpForAThread(thisID);
263  const std::string& uitype = m_pCustomUIsession.getUntrackedParameter<std::string>("Type", "MessageLogger");
264  if (uitype == "MessageLogger") {
266  } else if (uitype == "MessageLoggerThreadPrefix") {
268  m_pCustomUIsession.getUntrackedParameter<std::string>("ThreadPrefix", ""), thisID);
269  } else if (uitype == "FilePerThread") {
270  m_UIsession =
272  } else {
273  throw cms::Exception("Configuration")
274  << "RunManagerMTWorker::initializeG4: Invalid value of CustomUIsession.Type '" << uitype
275  << "', valid are MessageLogger, MessageLoggerThreadPrefix, FilePerThread";
276  }
277  G4UImanager::GetUIpointer()->SetCoutDestination(m_UIsession);
278 
279  // Initialize worker part of shared resources (geometry, physics)
280  G4WorkerThread::BuildGeometryAndPhysicsVector();
281 
282  // Create worker run manager
283  m_tls->kernel.reset(G4WorkerRunManagerKernel::GetRunManagerKernel());
284  if (nullptr == m_tls->kernel) {
285  m_tls->kernel = std::make_unique<G4WorkerRunManagerKernel>();
286  }
287 
288  // Define G4 exception handler
289  double th = m_p.getParameter<double>("ThresholdForGeometryExceptions") * CLHEP::GeV;
290  bool tr = m_p.getParameter<bool>("TraceExceptions");
291  G4StateManager::GetStateManager()->SetExceptionHandler(new ExceptionHandler(th, tr));
292 
293  // Set the geometry for the worker, share from master
294  auto worldPV = runManagerMaster->world().GetWorldVolume();
295  m_tls->kernel->WorkerDefineWorldVolume(worldPV);
296  G4TransportationManager* tM = G4TransportationManager::GetTransportationManager();
297  tM->SetWorldForTracking(worldPV);
298 
299  // we need the track manager now
300  m_tls->trackManager = std::make_unique<SimTrackManager>();
301 
302  // setup the magnetic field
303  if (m_pUseMagneticField) {
304  const GlobalPoint g(0.f, 0.f, 0.f);
305 
306  sim::FieldBuilder fieldBuilder(m_pMagField, m_pField);
307 
308  CMSFieldManager* fieldManager = new CMSFieldManager();
309  tM->SetFieldManager(fieldManager);
310  fieldBuilder.build(fieldManager, tM->GetPropagatorInField());
311 
312  std::string fieldFile = m_p.getUntrackedParameter<std::string>("FileNameField", "");
313  if (!fieldFile.empty()) {
314  std::call_once(applyOnce, [this]() { m_dumpMF = true; });
315  if (m_dumpMF) {
316  edm::LogVerbatim("SimG4CoreApplication")
317  << "RunManagerMTWorker::InitializeG4: Dump magnetic field to file " << fieldFile;
318  DumpMagneticField(tM->GetFieldManager()->GetDetectorField(), fieldFile);
319  }
320  }
321  }
322 
323  // attach sensitive detector
324  auto sensDets = sim::attachSD(
325  m_sdMakers, es, runManagerMaster->catalog(), m_p, m_tls->trackManager.get(), *(m_tls->registry.get()));
326 
327  m_tls->sensTkDets.swap(sensDets.first);
328  m_tls->sensCaloDets.swap(sensDets.second);
329 
330  edm::LogVerbatim("SimG4CoreApplication")
331  << "RunManagerMTWorker::InitializeG4: Sensitive Detectors are built in thread " << thisID << " found "
332  << m_tls->sensTkDets.size() << " Tk type SD, and " << m_tls->sensCaloDets.size() << " Calo type SD";
333 
334  // Enable couple transportation
335  bool scorer = m_p.getParameter<bool>("UseCommandBaseScorer");
336  if (scorer) {
337  G4ScoringManager* scManager = G4ScoringManager::GetScoringManager();
338  scManager->SetVerboseLevel(1);
339  }
340 
341  // Set the physics list for the worker, share from master
342  PhysicsList* physicsList = runManagerMaster->physicsListForWorker();
343 
344  edm::LogVerbatim("SimG4CoreApplication")
345  << "RunManagerMTWorker::InitializeG4: start initialisation of PhysicsList for the thread " << thisID;
346 
347  // Geant4 UI commands in PreInit state
348  if (!runManagerMaster->G4Commands().empty()) {
349  G4cout << "RunManagerMTWorker::InitializeG4: Requested UI commands: " << G4endl;
350  for (const std::string& command : runManagerMaster->G4Commands()) {
351  G4cout << " " << command << G4endl;
352  G4UImanager::GetUIpointer()->ApplyCommand(command);
353  }
354  }
355  G4StateManager::GetStateManager()->SetNewState(G4State_Init);
356 
357  physicsList->InitializeWorker();
358  m_tls->kernel->SetPhysics(physicsList);
359  m_tls->kernel->InitializePhysics();
360 
361  if (!m_tls->kernel->RunInitialization()) {
362  throw cms::Exception("Configuration")
363  << "RunManagerMTWorker::InitializeG4: Geant4 kernel initialization failed in thread " << thisID;
364  }
365 
366  //tell all interesting parties that we are beginning the job
367  BeginOfJob aBeginOfJob(&es);
368  m_tls->registry->beginOfJobSignal_(&aBeginOfJob);
369 
370  G4int sv = m_p.getUntrackedParameter<int>("SteppingVerbosity", 0);
371  G4double elim = m_p.getUntrackedParameter<double>("StepVerboseThreshold", 0.1) * CLHEP::GeV;
372  std::vector<int> ve = m_p.getUntrackedParameter<std::vector<int>>("VerboseEvents");
373  std::vector<int> vn = m_p.getUntrackedParameter<std::vector<int>>("VertexNumber");
374  std::vector<int> vt = m_p.getUntrackedParameter<std::vector<int>>("VerboseTracks");
375 
376  if (sv > 0) {
377  m_sVerbose = std::make_unique<CMSSteppingVerbose>(sv, elim, ve, vn, vt);
378  }
379  if (!m_UseG4EventManager)
380  m_evtManager = std::make_unique<CMSSimEventManager>(m_p);
382 
383  G4StateManager::GetStateManager()->SetNewState(G4State_Idle);
384 
385  timer.Stop();
386  edm::LogVerbatim("SimG4CoreApplication")
387  << "RunManagerMTWorker::initializeG4 done for the thread " << thisID << " " << timer;
388  m_tls->threadInitialized = true;
389 }
390 
392  m_tls->runInterface = std::make_unique<SimRunInterface>(this, false);
393  m_tls->userRunAction = std::make_unique<RunAction>(m_pRunAction, m_tls->runInterface.get(), false);
394  m_tls->userRunAction->SetMaster(false);
395  Connect(m_tls->userRunAction.get());
396 
397  G4int ver = m_p.getParameter<int>("EventVerbose");
398  G4EventManager* eventManager = m_tls->kernel->GetEventManager();
399  eventManager->SetVerboseLevel(ver);
400 
401  auto userEventAction =
403  Connect(userEventAction);
404  if (m_UseG4EventManager) {
405  eventManager->SetUserAction(userEventAction);
406  } else {
407  m_evtManager->SetUserAction(userEventAction);
408  }
409 
410  auto userTrackingAction = new TrackingAction(m_tls->trackManager.get(), m_sVerbose.get(), m_pTrackingAction);
411  Connect(userTrackingAction);
412  if (m_UseG4EventManager) {
413  eventManager->SetUserAction(userTrackingAction);
414  } else {
415  m_evtManager->SetUserAction(userTrackingAction);
416  }
417 
418  auto userSteppingAction =
420  Connect(userSteppingAction);
421  if (m_UseG4EventManager) {
422  eventManager->SetUserAction(userSteppingAction);
423  } else {
424  m_evtManager->SetUserAction(userSteppingAction);
425  }
426 
427  auto userStackingAction = new StackingAction(userTrackingAction, m_pStackingAction, m_sVerbose.get());
428  if (m_UseG4EventManager) {
429  eventManager->SetUserAction(userStackingAction);
430  } else {
431  m_evtManager->SetUserAction(userStackingAction);
432  }
433 }
434 
436  runAction->m_beginOfRunSignal.connect(m_tls->registry->beginOfRunSignal_);
437  runAction->m_endOfRunSignal.connect(m_tls->registry->endOfRunSignal_);
438 }
439 
441  eventAction->m_beginOfEventSignal.connect(m_tls->registry->beginOfEventSignal_);
442  eventAction->m_endOfEventSignal.connect(m_tls->registry->endOfEventSignal_);
443 }
444 
446  trackingAction->m_beginOfTrackSignal.connect(m_tls->registry->beginOfTrackSignal_);
447  trackingAction->m_endOfTrackSignal.connect(m_tls->registry->endOfTrackSignal_);
448 }
449 
451  steppingAction->m_g4StepSignal.connect(m_tls->registry->g4StepSignal_);
452 }
453 
455  initializeTLS();
456  return m_tls->trackManager.get();
457 }
458 std::vector<SensitiveTkDetector*>& RunManagerMTWorker::sensTkDetectors() {
459  initializeTLS();
460  return m_tls->sensTkDets;
461 }
462 std::vector<SensitiveCaloDetector*>& RunManagerMTWorker::sensCaloDetectors() {
463  initializeTLS();
464  return m_tls->sensCaloDets;
465 }
466 std::vector<std::shared_ptr<SimProducer>>& RunManagerMTWorker::producers() {
467  initializeTLS();
468  return m_tls->producers;
469 }
470 
472  m_tls->currentRun = new G4Run();
473  G4StateManager::GetStateManager()->SetNewState(G4State_GeomClosed);
474  if (nullptr != m_tls->userRunAction) {
475  m_tls->userRunAction->BeginOfRunAction(m_tls->currentRun);
476  }
477  int id = getThreadIndex();
478  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::initializeRun done for thread " << id;
479 }
480 
482  int id = getThreadIndex();
483  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::terminateRun for thread " << id;
484  if (nullptr == m_tls || m_tls->runTerminated) {
485  return;
486  }
487 
488  // Geant4 UI commands after the run
489  if (!m_G4CommandsEndRun.empty()) {
490  std::call_once(applyOnceEnd, [this]() { m_endOfRun = true; });
491  if (m_endOfRun) {
492  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker: Requested end of run UI commands: ";
493  for (const std::string& command : m_G4CommandsEndRun) {
494  edm::LogVerbatim("SimG4CoreApplication") << " " << command;
495  G4UImanager::GetUIpointer()->ApplyCommand(command);
496  }
497  }
498  }
499  if (m_tls->userRunAction) {
500  m_tls->userRunAction->EndOfRunAction(m_tls->currentRun);
501  m_tls->userRunAction.reset();
502  }
503  m_tls->currentEvent.reset();
504  if (m_tls->kernel) {
505  m_tls->kernel->RunTermination();
506  }
507  m_tls->runTerminated = true;
508  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::terminateRun done for thread " << id;
509 }
510 
512  const edm::EventSetup& es,
513  RunManagerMT& runManagerMaster) {
514  // The initialization and begin/end run is a bit convoluted due to
515  // - Geant4 deals per-thread
516  // - OscarMTProducer deals per-stream
517  // and framework/TBB is free to schedule work in streams to the
518  // threads as it likes.
519  //
520  // We have to do the per-thread initialization, and per-thread
521  // per-run initialization here by ourselves.
522 
523  assert(m_tls != nullptr and m_tls->threadInitialized);
524  // Initialize run
525  if (inpevt.id().run() != m_tls->currentRunNumber) {
526  edm::LogVerbatim("SimG4CoreApplication")
527  << "RunManagerMTWorker::produce: RunID= " << inpevt.id().run() << " TLS RunID= " << m_tls->currentRunNumber;
528  if (m_tls->currentRunNumber != 0 && !m_tls->runTerminated) {
529  // If previous run in this thread was not terminated via endRun() call,
530  // terminate it now
531  terminateRun();
532  }
533  initializeRun();
534  m_tls->currentRunNumber = inpevt.id().run();
535  }
536  m_tls->runInterface->setRunManagerMTWorker(this); // For UserActions
537 
538  m_tls->currentEvent.reset(generateEvent(inpevt));
539 
540  m_simEvent.clear();
543  if (m_generator.genVertex() != nullptr) {
544  auto genVertex = m_generator.genVertex();
545  m_simEvent.collisionPoint(math::XYZTLorentzVectorD(genVertex->x() / CLHEP::cm,
546  genVertex->y() / CLHEP::cm,
547  genVertex->z() / CLHEP::cm,
548  genVertex->t() / CLHEP::second));
549  }
550  if (m_tls->currentEvent->GetNumberOfPrimaryVertex() == 0) {
551  throw cms::Exception("EventCorruption")
552  << "RunManagerMTWorker::produce: event " << inpevt.id().event() << " with no G4PrimaryVertices"
553  << " StreamID=" << inpevt.streamID() << " threadIndex=" << getThreadIndex();
554 
555  } else {
556  edm::LogVerbatim("SimG4CoreApplication")
557  << "RunManagerMTWorker::produce: start EventID=" << inpevt.id().event() << " StreamID=" << inpevt.streamID()
558  << " threadIndex=" << getThreadIndex() << " weight=" << m_simEvent.weight() << "; "
559  << m_tls->currentEvent->GetNumberOfPrimaryVertex() << " vertices for Geant4; generator produced "
560  << m_simEvent.nGenParts() << " particles.";
561 
562  if (m_UseG4EventManager) {
563  m_tls->kernel->GetEventManager()->ProcessOneEvent(m_tls->currentEvent.get());
564  } else {
565  m_evtManager->ProcessOneEvent(m_tls->currentEvent.get());
566  }
567  }
568 
569  //remove memory only needed during event processing
570  m_tls->currentEvent.reset();
571 
572  for (auto& sd : m_tls->sensCaloDets) {
573  sd->reset();
574  }
575  edm::LogVerbatim("SimG4CoreApplication") << "RunManagerMTWorker::produce: ended Event " << inpevt.id().event();
576  return &m_simEvent;
577 }
578 
580  if (m_tls->runTerminated) {
581  return;
582  }
583  G4Track* t = m_tls->kernel->GetEventManager()->GetTrackingManager()->GetTrack();
584  t->SetTrackStatus(fStopAndKill);
585 
586  // CMS-specific act
587  //
588  TrackingAction* uta = static_cast<TrackingAction*>(m_tls->kernel->GetEventManager()->GetUserTrackingAction());
590 
591  m_tls->currentEvent->SetEventAborted();
592  m_tls->kernel->GetEventManager()->GetStackManager()->clear();
593  m_tls->kernel->GetEventManager()->GetTrackingManager()->EventAborted();
594 }
595 
596 void RunManagerMTWorker::abortRun(bool softAbort) {
597  if (!softAbort) {
598  abortEvent();
599  }
600  m_tls->currentRun = nullptr;
601  terminateRun();
602 }
603 
605  m_tls->currentEvent.reset();
606 
607  // 64 bits event ID in CMSSW converted into Geant4 event ID
608  G4int evtid = (G4int)inpevt.id().event();
609  G4Event* evt = new G4Event(evtid);
610 
612  inpevt.getByToken(m_InToken, HepMCEvt);
613 
614  m_generator.setGenEvent(HepMCEvt->GetEvent());
615 
616  // required to reset the GenParticle Id for particles transported
617  // along the beam pipe
618  // to their original value for SimTrack creation
619  resetGenParticleId(inpevt);
620 
621  if (!m_nonBeam) {
622  m_generator.HepMC2G4(HepMCEvt->GetEvent(), evt);
623  if (m_LHCTransport) {
625  inpevt.getByToken(m_LHCToken, LHCMCEvt);
626  m_generator.nonCentralEvent2G4(LHCMCEvt->GetEvent(), evt);
627  }
628  } else {
629  m_generator.nonCentralEvent2G4(HepMCEvt->GetEvent(), evt);
630  }
631 
632  return evt;
633 }
634 
637  inpevt.getByToken(m_theLHCTlinkToken, theLHCTlink);
638  if (theLHCTlink.isValid()) {
639  m_tls->trackManager->setLHCTransportLink(theLHCTlink.product());
640  }
641 }
642 
643 void RunManagerMTWorker::DumpMagneticField(const G4Field* field, const std::string& file) const {
644  std::ofstream fout(file.c_str(), std::ios::out);
645  if (fout.fail()) {
646  edm::LogWarning("SimG4CoreApplication")
647  << "MTWorker::DumpMagneticField: error opening file <" << file << "> for magnetic field";
648  } else {
649  // CMS magnetic field volume
650  double rmax = 9000 * mm;
651  double zmax = 24000 * mm;
652 
653  double dr = 1 * cm;
654  double dz = 5 * cm;
655 
656  int nr = (int)(rmax / dr);
657  int nz = 2 * (int)(zmax / dz);
658 
659  double r = 0.0;
660  double z0 = -zmax;
661  double z;
662 
663  double phi = 0.0;
664  double cosf = cos(phi);
665  double sinf = sin(phi);
666 
667  double point[4] = {0.0, 0.0, 0.0, 0.0};
668  double bfield[3] = {0.0, 0.0, 0.0};
669 
670  fout << std::setprecision(6);
671  for (int i = 0; i <= nr; ++i) {
672  z = z0;
673  for (int j = 0; j <= nz; ++j) {
674  point[0] = r * cosf;
675  point[1] = r * sinf;
676  point[2] = z;
677  field->GetFieldValue(point, bfield);
678  fout << "R(mm)= " << r / mm << " phi(deg)= " << phi / degree << " Z(mm)= " << z / mm
679  << " Bz(tesla)= " << bfield[2] / tesla << " Br(tesla)= " << (bfield[0] * cosf + bfield[1] * sinf) / tesla
680  << " Bphi(tesla)= " << (bfield[0] * sinf - bfield[1] * cosf) / tesla << G4endl;
681  z += dz;
682  }
683  r += dr;
684  }
685 
686  fout.close();
687  }
688 }
void connect(Observer< const T *> *iObs)
does not take ownership of memory
Definition: Signaler.h:55
edm::ParameterSet m_pSteppingAction
Log< level::Info, true > LogVerbatim
virtual const HepMC::GenEvent * genEvent() const
Definition: Generator.h:30
std::vector< std::shared_ptr< SimWatcher > > watchers
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
CustomUIsession * m_UIsession
void nonCentralEvent2G4(const HepMC::GenEvent *g, G4Event *e)
Definition: Generator.cc:552
std::unique_ptr< G4Event > currentEvent
T const & getData(const ESGetToken< T, R > &iToken) const noexcept(false)
Definition: EventSetup.h:119
ROOT::Math::LorentzVector< ROOT::Math::PxPyPzE4D< double > > XYZTLorentzVectorD
Lorentz vector with cylindrical internal representation using pseudorapidity.
Definition: LorentzVector.h:14
unsigned int nGenParts() const
Definition: G4SimEvent.h:22
def create(alignables, pedeDump, additionalData, outputFile, config)
SimActivityRegistry::G4StepSignal m_g4StepSignal
SimTrackManager * GetSimTrackManager()
void HepMC2G4(const HepMC::GenEvent *g, G4Event *e)
Definition: Generator.cc:112
std::unique_ptr< SimRunInterface > runInterface
Sin< T >::type sin(const T &t)
Definition: Sin.h:22
std::unique_ptr< CMSSteppingVerbose > m_sVerbose
T const * product() const
Definition: Handle.h:70
SimActivityRegistry::EndOfRunSignal m_endOfRunSignal
Definition: RunAction.h:24
std::vector< SensitiveTkDetector * > sensTkDets
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:540
SimActivityRegistry::EndOfEventSignal m_endOfEventSignal
Definition: EventAction.h:38
G4VPhysicalVolume * GetWorldVolume() const
Definition: DDDWorld.h:24
virtual const math::XYZTLorentzVector * genVertex() const
Definition: Generator.h:31
assert(be >=bs)
void beginRun(const edm::EventSetup &)
edm::EDGetTokenT< edm::HepMCProduct > m_InToken
The Signals That Services Can Subscribe To This is based on ActivityRegistry and is current per Services can connect to the signals distributed by the ActivityRegistry in order to monitor the activity of the application Each possible callback has some defined which we here list in angle e g
Definition: Activities.doc:4
std::vector< std::string > m_G4CommandsEndRun
G4SimEvent * produce(const edm::Event &inpevt, const edm::EventSetup &es, RunManagerMT &runManagerMaster)
std::unique_ptr< G4RunManagerKernel > kernel
std::unique_ptr< CMSSimEventManager > m_evtManager
edm::EDGetTokenT< edm::HepMCProduct > m_LHCToken
T getUntrackedParameter(std::string const &, T const &) const
auto &__restrict__ ws
U second(std::pair< T, U > const &p)
static std::once_flag applyOnceEnd
void weight(float w)
Definition: G4SimEvent.h:25
std::unique_ptr< SimActivityRegistry > registry
edm::ParameterSet m_pEventAction
std::unique_ptr< SimTrackManager > trackManager
edm::ParameterSet m_pRunAction
std::vector< SensitiveCaloDetector * > sensCaloDets
std::unordered_map< std::string, std::unique_ptr< SensitiveDetectorMakerBase > > m_sdMakers
Cos< T >::type cos(const T &t)
Definition: Cos.h:22
std::vector< SensitiveTkDetector * > & sensTkDetectors()
void resetGenParticleId(const edm::Event &inpevt)
double f[11][100]
RunManagerMTWorker(const edm::ParameterSet &iConfig, edm::ConsumesCollector &&iC)
const SensitiveDetectorCatalog & catalog() const
Definition: RunManagerMT.h:72
std::unique_ptr< RunAction > userRunAction
edm::EventID id() const
Definition: EventBase.h:63
void hepEvent(const HepMC::GenEvent *r)
Definition: G4SimEvent.h:23
void setGenEvent(const HepMC::GenEvent *inpevt)
Definition: Generator.h:24
SimActivityRegistry::EndOfTrackSignal m_endOfTrackSignal
StreamID streamID() const
Definition: Event.h:98
std::vector< std::shared_ptr< SimProducer > > producers
void abortRun(bool softAbort=false)
const HepMC::GenEvent * GetEvent() const
Definition: HepMCProduct.h:37
void build(CMSFieldManager *fM, G4PropagatorInField *fP)
Definition: FieldBuilder.cc:32
std::pair< std::vector< SensitiveTkDetector * >, std::vector< SensitiveCaloDetector * > > attachSD(const std::unordered_map< std::string, std::unique_ptr< SensitiveDetectorMakerBase >> &, const edm::EventSetup &, const SensitiveDetectorCatalog &, edm::ParameterSet const &, const SimTrackManager *, SimActivityRegistry &reg)
void clear()
Definition: G4SimEvent.cc:23
const DDDWorld & world() const
Definition: RunManagerMT.h:70
static std::once_flag applyOnce
RunNumber_t run() const
Definition: EventID.h:38
std::vector< SensitiveCaloDetector * > & sensCaloDetectors()
edm::ParameterSet m_pTrackingAction
edm::ParameterSet m_pField
G4Event * generateEvent(const edm::Event &inpevt)
std::vector< std::shared_ptr< SimProducer > > & producers()
edm::EDGetTokenT< edm::LHCTransportLinkContainer > m_theLHCTlinkToken
bool isValid() const
Definition: HandleBase.h:70
list command
Definition: mps_check.py:25
const std::vector< std::string > & G4Commands() const
Definition: RunManagerMT.h:74
SimActivityRegistry::BeginOfRunSignal m_beginOfRunSignal
Definition: RunAction.h:23
HLT enums.
edm::ParameterSet m_pCustomUIsession
const MagneticField * m_pMagField
std::unordered_map< std::string, std::unique_ptr< SensitiveDetectorMakerBase > > sensitiveDetectorMakers(edm::ParameterSet const &, edm::ConsumesCollector, std::vector< std::string > const &chosenMakers)
std::vector< LHCTransportLink > LHCTransportLinkContainer
static void createWatchers(const edm::ParameterSet &iP, SimActivityRegistry &iReg, std::vector< std::shared_ptr< SimWatcher >> &oWatchers, std::vector< std::shared_ptr< SimProducer >> &oProds)
void PostUserTrackingAction(const G4Track *aTrack) override
unsigned int RunNumber_t
void initializeG4(RunManagerMT *runManagerMaster, const edm::EventSetup &es)
virtual const double eventWeight() const
Definition: Generator.h:32
#define get
Log< level::Warning, false > LogWarning
edm::ParameterSet m_p
void DumpMagneticField(const G4Field *, const std::string &) const
int getThreadIndex() const
edm::ESGetToken< MagneticField, IdealMagneticFieldRecord > m_MagField
void collisionPoint(const math::XYZTLorentzVectorD &v)
Definition: G4SimEvent.h:27
SimActivityRegistry::BeginOfEventSignal m_beginOfEventSignal
Definition: EventAction.h:37
*vegas h *****************************************************used in the default bin number in original ***version of VEGAS is ***a higher bin number might help to derive a more precise ***grade subtle point
Definition: invegas.h:5
EventNumber_t event() const
Definition: EventID.h:40
PhysicsList * physicsListForWorker() const
Definition: RunManagerMT.h:78
edm::ParameterSet m_pStackingAction
void Connect(RunAction *)
SimActivityRegistry::BeginOfTrackSignal m_beginOfTrackSignal