LArSoft  v07_13_02
Liquid Argon Software toolkit - http://larsoft.org/
AnalysisExample_module.cc
Go to the documentation of this file.
1 
47 // Always include headers defining everything you use. Starting from
48 // LArSoft and going up the software layers (nutools, art, etc.)
49 // ending with C++ is standard.
50 
51 // LArSoft includes
63 
64 // Framework includes
73 
74 // Utility libraries
76 #include "fhiclcpp/ParameterSet.h"
77 #include "fhiclcpp/types/Table.h"
78 #include "fhiclcpp/types/Atom.h"
79 #include "cetlib/pow.h" // cet::sum_of_squares()
80 
81 // ROOT includes. Note: To look up the properties of the ROOT classes,
82 // use the ROOT web site; e.g.,
83 // <https://root.cern.ch/doc/master/annotated.html>
84 #include "TH1.h"
85 #include "TH2.h"
86 #include "TTree.h"
87 #include "TLorentzVector.h"
88 #include "TVector3.h"
89 
90 // C++ includes
91 #include <map>
92 #include <vector>
93 #include <string>
94 #include <cmath>
95 
96 
97 namespace {
98 
99  // This is a local namespace (as opposed to the one below, which has
100  // the nested name lar::example::).
101  //
102  // The stuff you declare in an local namespace will not be
103  // visible beyond this file (more technically, this "translation
104  // unit", which is everything that gets included in the .cc file from
105  // now on). In this way, any functions you define in this namespace
106  // won't affect the environment of other modules.
107 
108  // We will define functions at the end, but we declare them here so
109  // that the module can freely use them.
110 
113  double DetectorDiagonal(geo::GeometryCore const& geom);
114 
118  bool TDCIDETimeCompare( const sim::TDCIDE&, const sim::TDCIDE& );
119 
120 } // local namespace
121 
122 
123 // It is good programming practice to put your code into a namespace,
124 // to make sure that no method or function you define will conflict
125 // with anything in any other module with the same name. Here we
126 // follow the LArSoft standard of declaring a main namespace of "lar"
127 // with a nested namespace of "example" because we're in the
128 // larexamples product. If an outside package wanted to call this
129 // module, it would have to use something like
130 // lar::example::AnalysisExample.
131 
132 namespace lar {
133 namespace example {
134 
135 
136  // BEGIN AnalysisExample group -----------------------------------------------
139  //-----------------------------------------------------------------------
140  //-----------------------------------------------------------------------
141  // class definition
183  {
184  public:
185 
186  // This structure describes the configuration parameters of the
187  // module. Any missing or unknown parameters will generate a
188  // configuration error.
189  //
190  // With an additional trick (see below) it allows configuration
191  // documentation to be displayed as a command-line option (see
192  // below).
193  //
194  // Note that, in this example, the Name() string (that is, the
195  // name you call a parameter in the FHiCL configuration file) and
196  // the data member name in the Config struct (that is, the name
197  // you access that parameter in your C++ code) match. This is not
198  // required, but it makes it easier to remember them.
199  //
200  // More details at:
201  // https://cdcvs.fnal.gov/redmine/projects/fhicl-cpp/wiki/Configuration_validation_and_fhiclcpp_types
202  //
203  struct Config {
204 
205  // Save some typing:
206  using Name = fhicl::Name;
208 
209  // One Atom for each parameter
211  Name("SimulationLabel"),
212  Comment("tag of the input data product with the detector simulation information")
213  };
214 
216  Name("HitLabel"),
217  Comment("tag of the input data product with reconstructed hits")
218  };
219 
221  Name("ClusterLabel"),
222  Comment("tag of the input data product with reconstructed clusters")
223  };
224 
226  Name("PDGcode"),
227  Comment("particle type (PDG ID) of the primary particle to be selected")
228  };
229 
231  Name("BinSize"),
232  Comment("dx [cm] used for the dE/dx calculation")
233  };
234 
235  }; // Config
236 
237  // If we define "Parameters" in this way, art will know to use the
238  // "Comment" items above for the module description. See what
239  // this command does:
240  //
241  // lar --print-description AnalysisExample
242  //
243  // The details of the art side of this trick are at:
244  //
245  // https://cdcvs.fnal.gov/redmine/projects/art/wiki/Configuration_validation_and_description
246  //
248 
249  // -------------------------------------------------------------------
250  // -------------------------------------------------------------------
251  // Standard constructor for an ART module with configuration validation;
252  // we don't need a special destructor here.
253 
255  explicit AnalysisExample(Parameters const& config);
256 
257  // The following methods have a standard meaning and a standard signature
258  // inherited from the framework (art::EDAnalyzer class).
259 
260  // - The "virtual" keyword is a reminder that the function we are
261  // dealing with is, in fact, virtual. You don't need to
262  // understand it now, but it's very important when you write a
263  // new algorithm.
264 
265  // - The "override" keyword, new in C++ 2011, is an important
266  // safety measure that ensures that the method we are going to
267  // write will override a matching method in the base class. For
268  // example, if we mistyped it as
269 
270  // virtual void beginJob() const;
271 
272  // (adding "const"), the compiler will be very happy with it,
273  // but art will not touch it, because art needs a "void
274  // beginJob()" (non-const) and it will find one in the base
275  // class (void art::EDAnalyzer::beginJob()) and will silently
276  // use that one instead. If you accidentally use:
277 
278  // virtual void beginJob() const override;
279 
280  // the compiler will immediately complain with us that this
281  // method is overriding nothing, hinting to some mistake (the
282  // spurious "const" in this case).
283 
284  // This method is called once, at the start of the job. In this
285  // example, it will define the histograms and n-tuples we'll
286  // write.
287  virtual void beginJob() override;
288 
289  // This method is called once, at the start of each run. It's a
290  // good place to read databases or files that may have
291  // run-dependent information.
292  virtual void beginRun(const art::Run& run) override;
293 
294  // The analysis routine, called once per event.
295  virtual void analyze (const art::Event& event) override;
296 
297  private:
298 
299  // The stuff below is the part you'll most likely have to change to
300  // go from this custom example to your own task.
301 
302  // The parameters we'll read from the .fcl file.
307  double fBinSize;
308 
309  // Pointers to the histograms we'll create.
310  TH1D* fPDGCodeHist;
313 
314  // The n-tuples we'll create.
317 
318  // The comment lines with the @ symbols define groups in doxygen.
321  int fEvent;
322  int fRun;
323  int fSubRun;
324 
328  int fSimPDG;
330 
331  // Arrays for 4-vectors: (x,y,z,t) and (Px,Py,Pz,E).
332  // Note: old-style C++ arrays are considered obsolete. However,
333  // to create simple n-tuples, we still need to use them.
334  double fStartXYZT[4];
335  double fEndXYZT[4];
336  double fStartPE[4];
337  double fEndPE[4];
338 
341 
343  std::vector<double> fSimdEdxBins;
345 
348  int fRecoPDG;
350 
353 
355  std::vector<double> fRecodEdxBins;
356 
358 
359  // Other variables that will be shared between different methods.
364 
365  }; // class AnalysisExample
366 
368  // END AnalysisExample group -------------------------------------------------
369 
370 
371  //-----------------------------------------------------------------------
372  //-----------------------------------------------------------------------
373  // class implementation
374 
375  //-----------------------------------------------------------------------
376  // Constructor
377  //
378  // Note that config is a Table<Config>, and to access the Config
379  // value we need to use an operator: "config()". In the same way,
380  // each element in Config is an Atom<Type>, so to access the type we
381  // again use the call operator, e.g. "SimulationLabel()".
382  //
384  : EDAnalyzer(config)
386  , fHitProducerLabel (config().HitLabel())
387  , fClusterProducerLabel (config().ClusterLabel())
388  , fSelectedPDG (config().PDGcode())
389  , fBinSize (config().BinSize())
390  {
391  // Get a pointer to the geometry service provider.
392  fGeometryService = lar::providerFrom<geo::Geometry>();
393  // The same for detector TDC clock services.
394  fTimeService = lar::providerFrom<detinfo::DetectorClocksService>();
395  // Access to detector properties.
396  const detinfo::DetectorProperties* detprop = lar::providerFrom<detinfo::DetectorPropertiesService>();
397  fTriggerOffset = detprop->TriggerOffset();
398 
399  // Since art 2.8, you can and should tell beforehand, here in the constructor,
400  // all the data the module is going to read ("consumes") or might read
401  // ("may_consume"). Diligence here will in the future help the framework
402  // execute modules in parallel, making sure the order is correct.
403  consumes<std::vector<simb::MCParticle>>(fSimulationProducerLabel);
404  consumes<std::vector<sim::SimChannel>>(fSimulationProducerLabel);
405  consumes<art::Assns<simb::MCTruth, simb::MCParticle>>(fSimulationProducerLabel);
406  consumes<std::vector<recob::Hit>>(fHitProducerLabel);
407  consumes<std::vector<recob::Cluster>>(fClusterProducerLabel);
408  consumes<art::Assns<recob::Cluster, recob::Hit>>(fHitProducerLabel);
409 
410  }
411 
412 
413  //-----------------------------------------------------------------------
415  {
416  // Get the detector length, to determine the maximum bin edge of one
417  // of the histograms.
418  const double detectorLength = DetectorDiagonal(*fGeometryService);
419 
420  // Access ART's TFileService, which will handle creating and writing
421  // histograms and n-tuples for us.
423 
424  // For TFileService, the arguments to 'make<whatever>' are the
425  // same as those passed to the 'whatever' constructor, provided
426  // 'whatever' is a ROOT class that TFileService recognizes.
427 
428  // Define the histograms. Putting semi-colons around the title
429  // causes it to be displayed as the x-axis label if the histogram
430  // is drawn (the format is "title;label on abscissae;label on ordinates").
431  fPDGCodeHist = tfs->make<TH1D>("pdgcodes",";PDG Code;", 5000, -2500, 2500);
432  fMomentumHist = tfs->make<TH1D>("mom", ";particle Momentum (GeV);", 100, 0., 10.);
433  fTrackLengthHist = tfs->make<TH1D>("length", ";particle track length (cm);", 200, 0, detectorLength);
434 
435  // Define our n-tuples, which are limited forms of ROOT
436  // TTrees. Start with the TTree itself.
437  fSimulationNtuple = tfs->make<TTree>("AnalysisExampleSimulation", "AnalysisExampleSimulation");
438  fReconstructionNtuple = tfs->make<TTree>("AnalysisExampleReconstruction","AnalysisExampleReconstruction");
439 
440  // Define the branches (columns) of our simulation n-tuple. To
441  // write a variable, we give the address of the variable to
442  // TTree::Branch.
443  fSimulationNtuple->Branch("Event", &fEvent, "Event/I");
444  fSimulationNtuple->Branch("SubRun", &fSubRun, "SubRun/I");
445  fSimulationNtuple->Branch("Run", &fRun, "Run/I");
446  fSimulationNtuple->Branch("TrackID", &fSimTrackID, "TrackID/I");
447  fSimulationNtuple->Branch("PDG", &fSimPDG, "PDG/I");
448  // When we write arrays, we give the address of the array to
449  // TTree::Branch; in C++ this is simply the array name.
450  fSimulationNtuple->Branch("StartXYZT", fStartXYZT, "StartXYZT[4]/D");
451  fSimulationNtuple->Branch("EndXYZT", fEndXYZT, "EndXYZT[4]/D");
452  fSimulationNtuple->Branch("StartPE", fStartPE, "StartPE[4]/D");
453  fSimulationNtuple->Branch("EndPE", fEndPE, "EndPE[4]/D");
454  // For a variable-length array: include the number of bins.
455  fSimulationNtuple->Branch("NdEdx", &fSimNdEdxBins, "NdEdx/I");
456  // ROOT branches can contain std::vector objects.
457  fSimulationNtuple->Branch("dEdx", &fSimdEdxBins);
458 
459  // A similar definition for the reconstruction n-tuple. Note that we
460  // use some of the same variables in both n-tuples.
461  fReconstructionNtuple->Branch("Event", &fEvent, "Event/I");
462  fReconstructionNtuple->Branch("SubRun", &fSubRun, "SubRun/I");
463  fReconstructionNtuple->Branch("Run", &fRun, "Run/I");
464  fReconstructionNtuple->Branch("TrackID", &fRecoTrackID, "TrackID/I");
465  fReconstructionNtuple->Branch("PDG", &fRecoPDG, "PDG/I");
466  fReconstructionNtuple->Branch("NdEdx", &fRecoNdEdxBins, "NdEdx/I");
467  fReconstructionNtuple->Branch("dEdx", &fRecodEdxBins);
468  }
469 
470  //-----------------------------------------------------------------------
471  // art expects this function to have a art::Run argument; C++
472  // expects us to use all the arguments we are given, or it will
473  // generate an "unused variable" warning. But we don't actually need
474  // nor use the art::Run object in this example. The trick to prevent
475  // that warning is to omit (or comment out) the name of the
476  // parameter.
477 
478  void AnalysisExample::beginRun(const art::Run& /*run*/)
479  {
480  // How to convert from number of electrons to GeV. The ultimate
481  // source of this conversion factor is
482  // ${LARCOREOBJ_INC}/larcoreobj/SimpleTypesAndConstants/PhysicalConstants.h.
483  // But sim::LArG4Parameters might in principle ask a database for it.
485  fElectronsToGeV = 1./larParameters->GeVToElectrons();
486  }
487 
488  //-----------------------------------------------------------------------
490  {
491  // Start by fetching some basic event information for our n-tuple.
492  fEvent = event.id().event();
493  fRun = event.run();
494  fSubRun = event.subRun();
495 
496  // This is the standard method of reading multiple objects
497  // associated with the same event; see
498  // <https://cdcvs.fnal.gov/redmine/projects/larsoft/wiki/Using_art_in_LArSoft>
499  // for more information.
500  //
501  // Define a "handle" to point to a vector of the objects.
503 
504  // Then tell the event to fill the vector with all the objects of
505  // that type produced by a particular producer.
506  //
507  // Note that if I don't test whether this is successful, and there
508  // aren't any simb::MCParticle objects, then the first time we
509  // access particleHandle, art will display a "ProductNotFound"
510  // exception message and, depending on art settings, it may skip
511  // all processing for the rest of this event (including any
512  // subsequent analysis steps) or stop the execution.
513  if (!event.getByLabel(fSimulationProducerLabel, particleHandle))
514  {
515  // If we have no MCParticles at all in an event, then we're in
516  // big trouble. Throw an exception to force this module to
517  // stop. Try to include enough information for the user to
518  // figure out what's going on. Note that when we throw a
519  // cet::exception, the run and event number will automatically
520  // be displayed.
521  //
522  // __LINE__ and __FILE__ are values computed by the compiler.
523 
524  throw cet::exception("AnalysisExample")
525  << " No simb::MCParticle objects in this event - "
526  << " Line " << __LINE__ << " in file " << __FILE__ << std::endl;
527  }
528 
529  // Get all the simulated channels for the event. These channels
530  // include the energy deposited for each simulated track.
531  //
532  // Here we use a different method to access objects:
533  // art::ValidHandle. Using this method, if there aren't any
534  // objects of the given type (sim::SimChannel in this case) in the
535  // input file for this art::Event, art will throw a
536  // ProductNotFound exception.
537  //
538  // The "auto" type means that the C++ compiler will determine the
539  // appropriate type for us, based on the return type of
540  // art::Event::getValidHandle<T>(). The "auto" keyword is a great
541  // timesaver, especially with frameworks like LArSoft which often
542  // have complicated data product structures.
543 
544  auto simChannelHandle =
545  event.getValidHandle<std::vector<sim::SimChannel>>(fSimulationProducerLabel);
546 
547  //
548  // Let's compute the variables for the simulation n-tuple first.
549  //
550 
551  // The MCParticle objects are not necessarily in any particular
552  // order. Since we may have to search the list of particles, let's
553  // put them into a map, a sorted container that will make
554  // searching fast and easy. To save both space and time, the map
555  // will not contain a copy of the MCParticle, but a pointer to it.
556  std::map< int, const simb::MCParticle* > particleMap;
557 
558  // This is a "range-based for loop" in the 2011 version of C++; do
559  // a web search on "c++ range based for loop" for more
560  // information. Here's how it breaks down:
561 
562  // - A range-based for loop operates on a container.
563  // "particleHandle" is not a container; it's a pointer to a
564  // container. If we want C++ to "see" a container, we have to
565  // dereference the pointer, like this: *particleHandle.
566 
567  // - The loop variable that is set to each object in the container
568  // is named "particle". As for the loop variable's type:
569 
570  // - To save a little bit of typing, and to make the code easier
571  // to maintain, we're going to let the C++ compiler deduce the
572  // type of what's in the container (simb::MCParticle objects
573  // in this case), so we use "auto".
574 
575  // - We do _not_ want to change the contents of the container,
576  // so we use the "const" keyword to make sure.
577 
578  // - We don't need to copy each object from the container into
579  // the variable "particle". It's sufficient to refer to the
580  // object by its address. So we use the reference operator "&"
581  // to tell the compiler to just copy the address, not the
582  // entire object.
583 
584  // It sounds complicated, but the end result is that we loop over
585  // the list of particles in the art::Event in the most efficient
586  // way possible.
587 
588  for ( auto const& particle : (*particleHandle) )
589  {
590  // For the methods you can call to get particle information,
591  // see ${NUSIMDATA_INC}/nusimdata/SimulationBase/MCParticle.h.
592  fSimTrackID = particle.TrackId();
593 
594  // Add the address of the MCParticle to the map, with the
595  // track ID as the key.
596  particleMap[fSimTrackID] = &particle;
597 
598  // Histogram the PDG code of every particle in the event.
599  fSimPDG = particle.PdgCode();
600  fPDGCodeHist->Fill( fSimPDG );
601 
602  // For this example, we want to fill the n-tuples and histograms
603  // only with information from the primary particles in the
604  // event, whose PDG codes match a value supplied in the .fcl file.
605  if ( particle.Process() != "primary" || fSimPDG != fSelectedPDG )
606  continue;
607 
608  // A particle has a trajectory, consisting of a set of
609  // 4-positions and 4-mommenta.
610  const size_t numberTrajectoryPoints = particle.NumberTrajectoryPoints();
611 
612  // For trajectories, as for vectors and arrays, the first
613  // point is #0, not #1.
614  const int last = numberTrajectoryPoints - 1;
615  const TLorentzVector& positionStart = particle.Position(0);
616  const TLorentzVector& positionEnd = particle.Position(last);
617  const TLorentzVector& momentumStart = particle.Momentum(0);
618  const TLorentzVector& momentumEnd = particle.Momentum(last);
619 
620  // Make a histogram of the starting momentum.
621  fMomentumHist->Fill( momentumStart.P() );
622 
623  // Fill arrays with the 4-values. (Don't be fooled by
624  // the name of the method; it just puts the numbers from
625  // the 4-vector into the array.)
626  positionStart.GetXYZT( fStartXYZT );
627  positionEnd.GetXYZT( fEndXYZT );
628  momentumStart.GetXYZT( fStartPE );
629  momentumEnd.GetXYZT( fEndPE );
630 
631  // Use a polar-coordinate view of the 4-vectors to
632  // get the track length.
633  const double trackLength = ( positionEnd - positionStart ).Rho();
634 
635  // Let's print some debug information in the job output to see
636  // that everything is fine. LOG_DEBUG() is a messagefacility
637  // macro that prints stuff when the message level is set to
638  // standard_debug in the .fcl file.
639  LOG_DEBUG("AnalysisExample")
640  << "Track length: " << trackLength << " cm";
641 
642  // Fill a histogram of the track length.
643  fTrackLengthHist->Fill( trackLength );
644 
645  LOG_DEBUG("AnalysisExample")
646  << "track ID=" << fSimTrackID
647  << " (PDG ID: " << fSimPDG << ") "
648  << trackLength << " cm long, momentum "
649  << momentumStart.P() << " GeV/c, has "
650  << numberTrajectoryPoints << " trajectory points";
651 
652  // Determine the number of dE/dx bins for the n-tuple.
653  fSimNdEdxBins = int( trackLength / fBinSize ) + 1;
654  // Initialize the vector of dE/dx bins to be empty.
655  fSimdEdxBins.clear();
656 
657  // To look at the energy deposited by this particle's track,
658  // we loop over the SimChannel objects in the event.
659  for ( auto const& channel : (*simChannelHandle) )
660  {
661  // Get the numeric ID associated with this channel. (The
662  // channel number is a 32-bit unsigned int, which normally
663  // requires a special data type. Let's use "auto" so we
664  // don't have to remember "raw::ChannelID_t".
665  auto const channelNumber = channel.Channel();
666 
667  // A little care: There is more than one plane that reacts
668  // to charge in the TPC. We only want to include the
669  // energy from the collection plane. Note:
670  // geo::kCollection is defined in
671  // ${LARCOREOBJ_INC}/larcoreobj/SimpleTypesAndConstants/geo_types.h
672  if ( fGeometryService->SignalType( channelNumber ) != geo::kCollection )
673  continue;
674 
675  // Each channel has a map inside it that connects a time
676  // slice to energy deposits in the detector. We'll use
677  // "auto", but it's worth noting that the full type of
678  // this map is
679  // std::map<unsigned short, std::vector<sim::IDE>>
680  auto const& timeSlices = channel.TDCIDEMap();
681 
682  // For every time slice in this channel:
683  for ( auto const& timeSlice : timeSlices )
684  {
685  // Each entry in a map is a pair<first,second>. For
686  // the timeSlices map, the 'first' is a time slice
687  // number. The 'second' is a vector of IDE objects.
688  auto const& energyDeposits = timeSlice.second;
689 
690  // Loop over the energy deposits. An "energy deposit"
691  // object is something that knows how much
692  // charge/energy was deposited in a small volume, by
693  // which particle, and where. The type of
694  // 'energyDeposit' will be sim::IDE, which is defined
695  // in
696  // ${LARDATAOBJ_INC}/lardataobj/Simulation/SimChannel.h.
697  for ( auto const& energyDeposit : energyDeposits )
698  {
699  // Check if the track that deposited the
700  // energy matches the track of the particle.
701  if ( energyDeposit.trackID != fSimTrackID ) continue;
702  // Get the (x,y,z) of the energy deposit.
703  TVector3 location( energyDeposit.x,
704  energyDeposit.y,
705  energyDeposit.z );
706 
707  // Distance from the start of the track.
708  const double distance = ( location - positionStart.Vect() ).Mag();
709 
710  // Into which bin of the dE/dx array do we add the energy?
711  const unsigned int bin = (unsigned int)( distance / fBinSize );
712 
713  // Is the dE/dx array big enough to include this bin?
714  if ( fSimdEdxBins.size() < bin+1 )
715  {
716  // Increase the array size to accomodate
717  // the new bin, padding it with zeros.
718  fSimdEdxBins.resize( bin+1 , 0. );
719  }
720 
721  // Add the energy deposit to that bin. (If you look at the
722  // definition of sim::IDE, you'll see that there's another
723  // way to get the energy. Are the two methods equivalent?
724  // Compare the results and see!)
725  fSimdEdxBins[bin] += energyDeposit.numElectrons * fElectronsToGeV;
726 
727  } // For each energy deposit
728  } // For each time slice
729  } // For each SimChannel
730 
731  // At this point we've filled in the values of all the
732  // variables and arrays we want to write to the n-tuple
733  // for this particle. The following command actually
734  // writes those values.
735  fSimulationNtuple->Fill();
736 
737  } // loop over all particles in the event.
738 
739  //
740  // Reconstruction n-tuple
741  //
742 
743  // All of the above is based on objects entirely produced by the
744  // simulation. Let's try to do something based on reconstructed
745  // objects. A Hit (see ${LARDATAOBJ_INC}/lardataobj/RecoBase/Hit.h)
746  // is a 2D object in a plane.
747 
748  // This code duplicates much of the code in the previous big
749  // simulation loop, and will produce the similar results. (It
750  // won't be identical, because of shaping and other factors; not
751  // every bit of charge in a channel ends up contributing to a
752  // hit.) The point is to show different methods of accessing
753  // information, not to produce profound physics results -- that
754  // part is up to you!
755 
756  // For the rest of this method, I'm going to assume you've read
757  // the comments in previous section; I won't repeat all the C++
758  // coding tricks and whatnot.
759 
760  // Start by reading the Hits. We don't use art::ValidHandle here
761  // because there might be no hits in the input; e.g., we ran the
762  // simulation but did not run the reconstruction steps yet. If
763  // there are no hits we may as well skip the rest of this module.
764 
766  if (!event.getByLabel(fHitProducerLabel, hitHandle)) return;
767 
768  // Our goal is to accumulate the dE/dx of any particles associated
769  // with the hits that match our criteria: primary particles with
770  // the PDG code from the .fcl file. I don't know how many such
771  // particles there will be in a given event. We'll use a map, with
772  // track ID as the key, to hold the vectors of dE/dx information.
773  std::map< int, std::vector<double> > dEdxMap;
774 
775  // For every Hit:
776  for ( auto const& hit : (*hitHandle) )
777  {
778  // The channel associated with this hit.
779  auto hitChannelNumber = hit.Channel();
780 
781  // We have a hit. For this example let's just focus on the
782  // hits in the collection plane.
783  if ( fGeometryService->SignalType( hitChannelNumber ) != geo::kCollection )
784  continue;
785 
786  LOG_DEBUG("AnalysisExample")
787  << "Hit in collection plane"
788  << std::endl;
789 
790  // In a few lines we're going to look for possible energy
791  // deposits that correspond to that hit. Determine a
792  // reasonable range of times that might correspond to those
793  // energy deposits.
794 
795  // In reconstruction, the channel waveforms are truncated. So
796  // we have to adjust the Hit TDC ticks to match those of the
797  // SimChannels, which were created during simulation.
798 
799  // Save a bit of typing, while still allowing for potential
800  // changes in the definitions of types in
801  // $LARDATAOBJ_DIR/source/lardataobj/Simulation/SimChannel.h
802 
803  typedef sim::SimChannel::StoredTDC_t TDC_t;
804  TDC_t start_tdc = fTimeService->TPCTick2TDC( hit.StartTick() );
805  TDC_t end_tdc = fTimeService->TPCTick2TDC( hit.EndTick() );
806  TDC_t hitStart_tdc = fTimeService->TPCTick2TDC( hit.PeakTime() - 3.*hit.SigmaPeakTime() );
807  TDC_t hitEnd_tdc = fTimeService->TPCTick2TDC( hit.PeakTime() + 3.*hit.SigmaPeakTime() );
808 
809  start_tdc = std::max(start_tdc, hitStart_tdc);
810  end_tdc = std::min(end_tdc, hitEnd_tdc );
811 
812  // In the simulation section, we started with particles to find
813  // channels with a matching track ID. Now we search in reverse:
814  // search the SimChannels for matching channel number, then look
815  // at the tracks inside the channel.
816 
817  for ( auto const& channel : (*simChannelHandle) )
818  {
819  auto simChannelNumber = channel.Channel();
820  if ( simChannelNumber != hitChannelNumber ) continue;
821 
822  LOG_DEBUG("AnalysisExample")
823  << "SimChannel number = " << simChannelNumber
824  << std::endl;
825 
826  // The time slices in this channel.
827  auto const& timeSlices = channel.TDCIDEMap();
828 
829  // We want to look over the range of time slices in this
830  // channel that correspond to the range of hit times.
831 
832  // To do this, we're going to use some fast STL search
833  // methods; STL algorithms are usually faster than the
834  // ones you might write yourself. The price for this speed
835  // is a bit of code complexity: in particular, we need to
836  // a custom comparison function, TDCIDETimeCompare, to
837  // define a "less-than" function for the searches.
838 
839  // For an introduction to STL algorithms, see
840  // <http://www.learncpp.com/cpp-tutorial/16-4-stl-algorithms-overview/>.
841  // For a list of available STL algorithms, see
842  // <http://en.cppreference.com/w/cpp/algorithm>
843 
844  // We have to create "dummy" time slices for the search.
845  sim::TDCIDE startTime;
846  sim::TDCIDE endTime;
847  startTime.first = start_tdc;
848  endTime.first = end_tdc;
849 
850  // Here are the fast searches:
851 
852  // Find a pointer to the first channel with time >= start_tdc.
853  auto const startPointer
854  = std::lower_bound( timeSlices.begin(), timeSlices.end(), startTime, TDCIDETimeCompare);
855 
856  // From that time slice, find the last channel with time < end_tdc.
857  auto const endPointer
858  = std::upper_bound( startPointer, timeSlices.end(), endTime, TDCIDETimeCompare);
859 
860  // Did we find anything? If not, skip.
861  if ( startPointer == timeSlices.end() || startPointer == endPointer ) continue;
862  LOG_DEBUG("AnalysisExample")
863  << "Time slice start = " << (*startPointer).first
864  << std::endl;
865 
866  // Loop over the channel times we found that match the hit
867  // times.
868  for ( auto slicePointer = startPointer; slicePointer != endPointer; slicePointer++)
869  {
870  auto const timeSlice = *slicePointer;
871  auto time = timeSlice.first;
872 
873  // How to debug a problem: Lots of print statements. There are
874  // debuggers such as gdb, but they can be tricky to use with
875  // shared libraries and don't work if you're using software
876  // that was compiled somewhere else (e.g., you're accessing
877  // LArSoft libraries via CVMFS).
878 
879  // The LOG_DEBUG statements below are left over from when I
880  // was trying to solve a problem about hit timing. I could
881  // have deleted them, but decided to leave them to demonsrate
882  // what a typical debugging process looks like.
883 
884  LOG_DEBUG("AnalysisExample")
885  << "Hit index = " << hit.LocalIndex()
886  << " channel number = " << hitChannelNumber
887  << " start TDC tick = " << hit.StartTick()
888  << " end TDC tick = " << hit.EndTick()
889  << " peak TDC tick = " << hit.PeakTime()
890  << " sigma peak time = " << hit.SigmaPeakTime()
891  << " adjusted start TDC tick = " << fTimeService->TPCTick2TDC(hit.StartTick())
892  << " adjusted end TDC tick = " << fTimeService->TPCTick2TDC(hit.EndTick())
893  << " adjusted peak TDC tick = " << fTimeService->TPCTick2TDC(hit.PeakTime())
894  << " adjusted start_tdc = " << start_tdc
895  << " adjusted end_tdc = " << end_tdc
896  << " time = " << time
897  << std::endl;
898 
899  // Loop over the energy deposits.
900  auto const& energyDeposits = timeSlice.second;
901  for ( auto const& energyDeposit : energyDeposits )
902  {
903  // Remember that map of MCParticles we created
904  // near the top of this method? Now we can use
905  // it. Search the map for the track ID associated
906  // with this energy deposit. Since a map is
907  // automatically sorted, we can use a fast binary
908  // search method, 'find()'.
909 
910  // By the way, the type of "search" is an iterator
911  // (to be specific, it's an
912  // std::map<int,simb::MCParticle*>::const_iterator,
913  // which makes you thankful for the "auto"
914  // keyword). If you're going to work with C++
915  // containers, you'll have to learn about
916  // iterators eventually; do a web search on "STL
917  // iterator" to get started.
918  auto search = particleMap.find( energyDeposit.trackID );
919 
920  // Did we find this track ID in the particle map?
921  // It's possible for the answer to be "no"; some
922  // particles are too low in kinetic energy to be
923  // written by the simulation (see
924  // ${LARSIM_DIR}/job/simulationservices.fcl,
925  // parameter ParticleKineticEnergyCut).
926  if ( search == particleMap.end() ) continue;
927 
928  // "search" points to a pair in the map: <track ID, MCParticle*>
929  int trackID = (*search).first;
930  const simb::MCParticle& particle = *((*search).second);
931 
932  // Is this a primary particle, with a PDG code that
933  // matches the user input?
934  if ( particle.Process() != "primary"
935  || particle.PdgCode() != fSelectedPDG )
936  continue;
937 
938  // Determine the dE/dx of this particle.
939  const TLorentzVector& positionStart = particle.Position(0);
940  TVector3 location( energyDeposit.x,
941  energyDeposit.y,
942  energyDeposit.z );
943  double distance = ( location - positionStart.Vect() ).Mag();
944  unsigned int bin = int( distance / fBinSize );
945  double energy = energyDeposit.numElectrons * fElectronsToGeV;
946 
947  // A feature of maps: if we refer to
948  // dEdxMap[trackID], and there's no such entry in
949  // the map yet, it will be automatically created
950  // with a zero-size vector. Test to see if the
951  // vector for this track ID is big enough.
952  //
953  // dEdxMap is a map, which is a slow container
954  // compared to a vector. If we are going to access
955  // the same element over and over, it is a good
956  // idea to find that element once, and then refer
957  // to that item directly. Since we don't care
958  // about the specific type of dEdxMap[trackID] (a
959  // vector, by the way), we can use "auto" to save
960  // some time. This must be a reference, since we
961  // want to change the original value in the map,
962  // and can't be constant.
963  auto& track_dEdX = dEdxMap[trackID];
964  if ( track_dEdX.size() < bin+1 )
965  {
966  // Increase the vector size, padding it with
967  // zeroes.
968  track_dEdX.resize( bin+1, 0 );
969  }
970 
971  // Add the energy to the dE/dx bins for this track.
972  track_dEdX[bin] += energy;
973 
974  } // loop over energy deposits
975  } // loop over time slices
976  } // for each SimChannel
977  } // for each Hit
978 
979  // We have a map of dE/dx vectors. Write each one of them to the
980  // reconstruction n-tuple.
981  for ( const auto& dEdxEntry : dEdxMap )
982  {
983  // Here, the map entries are <first,second>=<track ID, dE/dx vector>
984  fRecoTrackID = dEdxEntry.first;
985 
986  // This is an example of how we'd pick out the PDG code if
987  // there are multiple particle types or tracks in a single
988  // event allowed in the n-tuple.
989  fRecoPDG = particleMap[fRecoTrackID]->PdgCode();
990 
991  // Get the number of bins for this track.
992  const std::vector<double>& dEdx = dEdxEntry.second;
993  fRecoNdEdxBins = dEdx.size();
994 
995  // Copy this track's dE/dx information.
996  fRecodEdxBins = dEdx;
997 
998  // At this point, we've filled in all the reconstruction
999  // n-tuple's variables. Write it.
1000  fReconstructionNtuple->Fill();
1001  }
1002 
1003  // Think about the two big loops above, One starts from the
1004  // particles then looks at the channels; the other starts with the
1005  // hits and backtracks to the particles. What links the
1006  // information in simb::MCParticle and sim::SimChannel is the
1007  // track ID number assigned by the LArG4 simulation; what links
1008  // sim::SimChannel and recob::Hit is the channel ID.
1009 
1010  // In general, that is not how objects in the LArSoft
1011  // reconstruction chain are linked together. Most of them are
1012  // linked using associations and the art::Assns class:
1013  // <https://cdcvs.fnal.gov/redmine/projects/larsoft/wiki/Using_art_in_LArSoft#artAssns>
1014 
1015  // The web page may a bit difficult to understand (at least, it is
1016  // for me), so let's try to simplify things:
1017 
1018  // - If you're doing an analysis task, you don't have to worry
1019  // about creating art::Assns objects.
1020 
1021  // - You don't have to read the art:Assns objects on your
1022  // own. There are helper classes (FindXXX) which will do that for
1023  // you.
1024 
1025  // - There's only one helper you need: art::FindManyP. It will do
1026  // what you want with a minimum of fuss.
1027 
1028  // - Associations are symmetric. If you see an
1029  // art::Assns<ClassA,ClassB>, the helper classes will find all of
1030  // ClassA associated with ClassB or all of ClassB associated with
1031  // ClassA.
1032 
1033  // - To know what associations exist, you have to be a 'code
1034  // detective'. The important clue is to look for a 'produces' line
1035  // in the code that writes objects to an art::Event. For example,
1036  // in ${LARSIM_DIR}/source/larsim/LArG4/LArG4_module.cc, you'll see this
1037  // line:
1038 
1039  // produces< art::Assns<simb::MCTruth, simb::MCParticle> >();
1040 
1041  // That means a simulated event will have an association between
1042  // simb::MCTruth (the primary particle produced by the event
1043  // generator) and the simb::MCParticle objects (the secondary
1044  // particles produced in the detector simulation).
1045 
1046  // Let's try it. The following statement will find the
1047  // simb::MCTruth objects associated with the simb::MCParticle
1048  // objects in the event (referenced by particleHandle):
1049 
1050  const art::FindManyP<simb::MCTruth> findManyTruth(particleHandle, event, fSimulationProducerLabel);
1051 
1052  // Note that we still have to supply the module label of the step
1053  // that created the association. Also note that we did not have to
1054  // explicitly read in the simb::MCTruth objects from the
1055  // art::Event object 'event'; FindManyP did that for us.
1056 
1057  // Also note that at this point art::FindManyP has already found
1058  // all the simb::MCTruth associated with each of the particles in
1059  // particleHandle. This is a slow process, so in general you want
1060  // to do it only once. If we had a loop over the particles, we
1061  // would still do this outside that loop.
1062 
1063  // Now we can query the 'findManyTruth' object to access the
1064  // information. First, check that there wasn't some kind of error:
1065 
1066  if ( ! findManyTruth.isValid() )
1067  {
1068  mf::LogError("AnalysisExample")
1069  << "findManyTruth simb::MCTruth for simb::MCParticle failed!";
1070  }
1071 
1072  // I'm going to be lazy, and just look at the simb::MCTruth object
1073  // associated with the first simb::MCParticle we read in. (The
1074  // main reason I'm being lazy is that if I used the
1075  // single-particle generator in prodsingle.fcl, every particle in
1076  // the event is going to be associated with just the one primary
1077  // particle from the event generator.)
1078 
1079  size_t particle_index = 0; // look at first particle in
1080  // particleHandle's vector.
1081 
1082  // I'm using "auto" to save on typing. The result of
1083  // FindManyP::at() is a vector of pointers, in this case
1084  // simb::MCTruth*. In this case it will be a vector with just one
1085  // entry; I could have used art::FindOneP instead. (This will be a
1086  // vector of art::Ptr, which is a type of smart pointer; see
1087  // <https://cdcvs.fnal.gov/redmine/projects/larsoft/wiki/Using_art_in_LArSoft#artPtrltTgt-and-artPtrVectorltTgt>
1088  // To avoid unnecessary copying, and since art::FindManyP returns
1089  // a constant reference, use "auto const&".
1090 
1091  auto const& truth = findManyTruth.at( particle_index );
1092 
1093  // Make sure there's no problem.
1094  if ( truth.empty() )
1095  {
1096  mf::LogError("AnalysisExample")
1097  << "Particle ID=" << particleHandle->at( particle_index ).TrackId()
1098  << " has no primary!";
1099  }
1100 
1101  // Use the message facility to write output. I don't have to write
1102  // the event, run, or subrun numbers; the message facility takes
1103  // care of that automatically. I'm "going at warp speed" with the
1104  // vectors, pointers, and methods; see
1105  // ${NUSIMDATA_INC}/nusimdata/SimulationBase/MCTruth.h and
1106  // ${NUSIMDATA_INC}/nusimdata/SimulationBase/MCParticle.h for the
1107  // nested calls I'm using.
1108  mf::LogInfo("AnalysisExample")
1109  << "Particle ID=" << particleHandle->at( particle_index ).TrackId()
1110  << " primary PDG code=" << truth[0]->GetParticle(0).PdgCode();
1111 
1112  // Let's try a slightly more realistic example. Suppose I want to
1113  // read in the clusters, and learn what hits are associated with
1114  // them. Then I could backtrack from those hits to determine the
1115  // dE/dx of the particles in the clusters. (Don't worry; I won't
1116  // put you through the n-tuple creation procedure for a third
1117  // time.)
1118 
1119  // First, read in the clusters (if there are any).
1121  if (!event.getByLabel(fClusterProducerLabel, clusterHandle)) return;
1122 
1123  // Now use the associations to find which hits are associated with
1124  // which clusters. Note that this is not as trivial a query as the
1125  // one with MCTruth, since it's possible for a hit to be assigned
1126  // to more than one cluster.
1127 
1128  // We have to include fClusterProducerLabel, since that's the step
1129  // that created the art::Assns<recob::Hit,recob::Cluster> object;
1130  // look at the modules in ${LARRECO_DIR}/source/larreco/ClusterFinder/
1131  // and search for the 'produces' lines. (I did not know this before I
1132  // wrote these comments. I had to be a code detective and use UNIX
1133  // tools like 'grep' and 'find' to locate those routines.)
1134  const art::FindManyP<recob::Hit> findManyHits(clusterHandle, event, fClusterProducerLabel);
1135 
1136  if ( ! findManyHits.isValid() )
1137  {
1138  mf::LogError("AnalysisExample")
1139  << "findManyHits recob::Hit for recob::Cluster failed;"
1140  << " cluster label='" << fClusterProducerLabel << "'";
1141  }
1142 
1143  // Now we'll loop over the clusters to see the hits associated
1144  // with each one. Note that we're not using a range-based for
1145  // loop. That's because FindManyP::at() expects a number as an
1146  // argument, so we might as well go through the cluster objects
1147  // via numerical index instead.
1148  for ( size_t cluster_index = 0; cluster_index != clusterHandle->size(); cluster_index++ )
1149  {
1150  // In this case, FindManyP::at() will return a vector of
1151  // pointers to recob::Hit that corresponds to the
1152  // "cluster_index"-th cluster.
1153  auto const& hits = findManyHits.at( cluster_index );
1154 
1155  // We have a vector of pointers to the hits associated
1156  // with the cluster, but for this example I'm not going to
1157  // do anything fancy with them. I'll just print out how
1158  // many there are.
1159  mf::LogInfo("AnalysisExample")
1160  << "Cluster ID=" << clusterHandle->at( cluster_index ).ID()
1161  << " has " << hits.size() << " hits";
1162  }
1163 
1164  } // AnalysisExample::analyze()
1165 
1166 
1167  // This macro has to be defined for this module to be invoked from a
1168  // .fcl file; see AnalysisExample.fcl for more information.
1170 
1171 } // namespace example
1172 } // namespace lar
1173 
1174 
1175 // Back to our local namespace.
1176 namespace {
1177 
1178  // Define a local function to calculate the detector diagonal.
1179  double DetectorDiagonal(geo::GeometryCore const& geom) {
1180  const double length = geom.DetLength();
1181  const double width = 2. * geom.DetHalfWidth();
1182  const double height = 2. * geom.DetHalfHeight();
1183 
1184  return std::sqrt(cet::sum_of_squares(length, width, height));
1185  } // DetectorDiagonal()
1186 
1187  // Define a comparison function to use in std::upper_bound and
1188  // std::lower_bound searches above.
1189  bool TDCIDETimeCompare( const sim::TDCIDE& lhs, const sim::TDCIDE& rhs )
1190  {
1191  return lhs.first < rhs.first;
1192  }
1193 } // local namespace
1194 
Store parameters for running LArG4.
int fSimNdEdxBins
Number of dE/dx bins in a given track.
const TLorentzVector & Position(const int i=0) const
Definition: MCParticle.h:223
int PdgCode() const
Definition: MCParticle.h:216
TH1D * fPDGCodeHist
PDG code of all particles.
geo::Length_t DetHalfWidth(geo::TPCID const &tpcid) const
Returns the half width of the active volume of the specified TPC.
fhicl::Atom< art::InputTag > SimulationLabel
int fRecoTrackID
GEANT ID of the particle being processed.
std::pair< unsigned short, std::vector< sim::IDE > > TDCIDE
List of energy deposits at the same time (on this channel)
Definition: SimChannel.h:125
MaybeLogger_< ELseverityLevel::ELsev_info, false > LogInfo
Declaration of signal hit object.
art::InputTag fHitProducerLabel
The name of the producer that created hits.
double fEndXYZT[4]
(x,y,z,t) of the true end of the particle
geo::GeometryCore const * fGeometryService
pointer to Geometry provider
std::vector< double > fSimdEdxBins
The vector that will be used to accumulate dE/dx values as a function of range.
double fStartPE[4]
(Px,Py,Pz,E) at the true start of the particle
AnalysisExample(Parameters const &config)
Constructor: configures the module (see the Config structure above)
int fSimTrackID
GEANT ID of the particle being processed.
TTree * fReconstructionNtuple
tuple with reconstructed data
virtual void analyze(const art::Event &event) override
SigType_t SignalType(geo::PlaneID const &pid) const
Returns the type of signal on the channels of specified TPC plane.
MaybeLogger_< ELseverityLevel::ELsev_error, false > LogError
std::string Process() const
Definition: MCParticle.h:219
Particle class.
art::InputTag fSimulationProducerLabel
The name of the producer that tracked simulated particles through the detector.
Definition: Run.h:30
int fRecoNdEdxBins
Number of dE/dx bins in a given track.
Access the description of detector geometry.
Int_t max
Definition: plot.C:27
void hits()
Definition: readHits.C:15
geo::Length_t DetHalfHeight(geo::TPCID const &tpcid) const
Returns the half height of the active volume of the specified TPC.
#define DEFINE_ART_MODULE(klass)
Definition: ModuleMacros.h:42
virtual void beginRun(const art::Run &run) override
double fStartXYZT[4]
(x,y,z,t) of the true start of the particle
double energy
Definition: plottest35.C:25
std::vector< double > fRecodEdxBins
The vector that will be used to accumulate dE/dx values as a function of range.
geo::Length_t DetLength(geo::TPCID const &tpcid) const
Returns the length of the active volume of the specified TPC.
detinfo::DetectorClocks const * fTimeService
pointer to detector clock time service provider
art::InputTag fClusterProducerLabel
The name of the producer that created clusters.
EDAnalyzer(Table< Config > const &config)
Definition: EDAnalyzer.h:100
Description of geometry of one entire detector.
Declaration of cluster object.
float bin[41]
Definition: plottest35.C:14
int fRecoPDG
PDG ID of the particle being processed.
Definition of data types for geometry description.
Detector simulation of raw signals on wires.
Conversion of times between different formats and references.
int fSimPDG
PDG ID of the particle being processed.
int fRun
number of the run being processed
T * make(ARGS...args) const
virtual double TPCTick2TDC(double tick) const =0
Converts a TPC time tick into a electronics time tick.
TH1D * fMomentumHist
momentum [GeV] of all selected particles
LArSoft-specific namespace.
int fEvent
number of the event being processed
bool getByLabel(std::string const &label, std::string const &productInstanceName, Handle< PROD > &result) const
Definition: DataViewImpl.h:344
Int_t min
Definition: plot.C:26
object containing MC truth information necessary for making RawDigits and doing back tracking ...
#define LOG_DEBUG(id)
double fEndPE[4]
(Px,Py,Pz,E) at the true end of the particle
TTree * fSimulationNtuple
tuple with simulated data
double fElectronsToGeV
conversion factor
int fTriggerOffset
(units of ticks) time of expected neutrino event
double fBinSize
For dE/dx work: the value of dx.
double GeVToElectrons() const
art framework interface to geometry description
cet::coded_exception< error, detail::translate > exception
Definition: exception.h:33
TH1D * fTrackLengthHist
true length [cm] of all selected particles
Event finding and building.
int fSelectedPDG
PDG code of particle we&#39;ll focus on.
TDCIDE::first_type StoredTDC_t
Type for TDC tick used in the internal representation.
Definition: SimChannel.h:147
Signal from collection planes.
Definition: geo_types.h:93