6 #include <TParameter.h>
7 #include <unordered_map>
8 #include "gallery/ValidHandle.h"
9 #include "gallery/Handle.h"
10 #include "canvas/Utilities/InputTag.h"
11 #include "canvas/Persistency/Provenance/SubRunAuxiliary.h"
12 #include "nusimdata/SimulationBase/MCFlux.h"
13 #include "nusimdata/SimulationBase/MCTruth.h"
14 #include "nusimdata/SimulationBase/MCNeutrino.h"
15 #include "nusimdata/SimulationBase/GTruth.h"
17 #include "canvas/Persistency/Common/FindManyP.h"
20 #include "fhiclcpp/ParameterSet.h"
21 #include "fhiclcpp/ParameterSetID.h"
22 #include "fhiclcpp/make_ParameterSet.h"
23 #include "fhiclcpp/ParameterSetRegistry.h"
25 #include "cetlib/sqlite/query_result.h"
26 #include "cetlib/sqlite/select.h"
28 #include "canvas/Persistency/Provenance/ParameterSetBlob.h"
29 #include "canvas/Persistency/Provenance/ParameterSetMap.h"
30 #include "art_root_io/RootDB/SQLite3Wrapper.h"
31 #include "art_root_io/RootDB/tkeyvfs.h"
52 : fEventIndex(0), fOutputFilename(
"output.root"), fProviderManager(NULL) {}
94 fTruthTag = { config->get<std::string>(
"MCTruthTag",
"generator") };
96 fFluxTag = { config->get<std::string>(
"MCFluxTag",
"generator") };
97 fMCTrackTag = { config->get<std::string>(
"MCTrackTag",
"mcreco") };
98 fMCShowerTag = { config->get<std::string>(
"MCShowerTag",
"mcreco") };
99 fMCParticleTag = { config->get<std::string>(
"MCParticleTag",
"largeant") };
100 fOutputFilename = config->get<std::string>(
"OutputFile",
"output.root");
103 fWriteTree = config->get<
bool>(
"WriteTree",
true);
108 if (config->has_key(
"MCWeightTags")) {
109 if (config->is_key_to_atom(
"MCWeightTags")) {
110 std::string weight_tag = config->get<std::string>(
"MCWeightTags");
111 fWeightTags = { { weight_tag } };
113 else if (config->is_key_to_sequence(
"MCWeightTags")) {
114 std::vector<std::string> weight_tags = \
115 config->get<std::vector<std::string> >(
"MCWeightTags");
116 for (
size_t i=0; i<weight_tags.size(); i++) {
117 fWeightTags.emplace_back(weight_tags[i]);
126 fGeneratorProcess =
"GenieGen";
127 fFluxTag = {
"generator" };
129 fMCTrackTag = {
"mcreco" };
130 fMCShowerTag = {
"mcreco" };
131 fMCParticleTag = {
"largeant" };
137 if (std::find(exps.begin(), exps.end(),
fExperimentID) != exps.end()) {
146 double XMin = std::min_element(iTPC, tend, [](
auto &lhs,
auto &rhs) {
return lhs.MinX() < rhs.MinX(); })->MinX();
147 double YMin = std::min_element(iTPC, tend, [](
auto &lhs,
auto &rhs) {
return lhs.MinY() < rhs.MinY(); })->MinY();
148 double ZMin = std::min_element(iTPC, tend, [](
auto &lhs,
auto &rhs) {
return lhs.MinZ() < rhs.MinZ(); })->MinZ();
150 double XMax = std::max_element(iTPC, tend, [](
auto &lhs,
auto &rhs) {
return lhs.MaxX() < rhs.MaxX(); })->MaxX();
151 double YMax = std::max_element(iTPC, tend, [](
auto &lhs,
auto &rhs) {
return lhs.MaxY() < rhs.MaxY(); })->MaxY();
152 double ZMax = std::max_element(iTPC, tend, [](
auto &lhs,
auto &rhs) {
return lhs.MaxZ() < rhs.MaxZ(); })->MaxZ();
160 <<
"Unknown experiment, no ProviderManager is available."
167 fTree =
new TTree(
"sbnana",
"SBN Analysis Tree");
169 fTree->Branch(
"events", &
fEvent);
172 fRecoTree =
new TTree(
"sbnreco",
"SBN Reco Event Tree");
177 fSubRunTree =
new TTree(
"sbnsubrun",
"SBN Analysis Subrun Tree");
183 fFileMetaTree =
new TTree(
"sbnfilemeta",
"SBN Analysis File Metadata Tree");
197 static TFile *last_tfile = NULL;
199 TFile *this_file = ev.getTFile();
201 if (this_file != last_tfile) {
205 TTree* srtree = (TTree*) ev.getTFile()->Get(
"SubRuns");
207 art::SubRunAuxiliary* sraux =
new art::SubRunAuxiliary;
208 srtree->SetBranchAddress(
"SubRunAuxiliary", &sraux);
210 for (
long i=0; i<srtree->GetEntries(); i++) {
213 int runid = sraux->run();
214 int subrunid = sraux->subRun();
216 std::string totpot_str =
"sumdata::POTSummary_generator__" + fGeneratorProcess +
".obj.totpot";
217 std::string totgoodpot_str =
"sumdata::POTSummary_generator__" + fGeneratorProcess +
".obj.totgoodpot";
218 std::string totspills_str =
"sumdata::POTSummary_generator__" + fGeneratorProcess +
".obj.totspills";
219 std::string goodspills_str =
"sumdata::POTSummary_generator__" + fGeneratorProcess +
".obj.goodspills";
221 TLeaf* potLeaf = srtree->GetLeaf(totpot_str.c_str());
222 float pot = potLeaf ? potLeaf->GetValue() : -1;
223 TLeaf* goodpotLeaf = srtree->GetLeaf(totgoodpot_str.c_str());
224 float goodpot = goodpotLeaf ? goodpotLeaf->GetValue() : -1;
225 TLeaf* spillsLeaf = srtree->GetLeaf(totspills_str.c_str());
226 int spills = spillsLeaf ? spillsLeaf->GetValue() : -1;
227 TLeaf* goodspillsLeaf = srtree->GetLeaf(goodspills_str.c_str());
228 int goodspills = goodspillsLeaf ? goodspillsLeaf->GetValue() : -1;
230 std::cout <<
"Subrun " << runid <<
"/" << subrunid <<
" added "
231 <<
"(good POT = " << goodpot <<
")"
233 *
fSubRun = { runid, subrunid, pot, goodpot, spills, goodspills };
238 last_tfile = ev.getTFile();
243 static TFile *last_tfile = NULL;
245 TFile *this_file = ev.getTFile();
247 if (this_file != last_tfile) {
248 unsigned n_gen_event = 0;
249 unsigned n_event = 0;
252 art::SQLite3Wrapper
sqliteDB(this_file,
"RootFileDB", SQLITE_OPEN_READONLY);
255 fhicl::ParameterSetRegistry::importFrom(db);
256 fhicl::ParameterSetRegistry::stageIn();
260 std::unordered_map<fhicl::ParameterSetID, fhicl::ParameterSet, fhicl::detail::HashParameterSetID> registry;
261 using namespace cet::sqlite;
262 query_result<std::string, std::string> entriesToStageIn;
263 entriesToStageIn << select(
"*").from(db,
"ParameterSets");
265 cet::transform_all(entriesToStageIn,
266 std::inserter(registry,
std::begin(registry)),
267 [](
auto const&
row) {
268 auto const& [idString, psBlob] =
row;
269 fhicl::ParameterSet pset;
270 fhicl::make_ParameterSet(psBlob, pset);
271 return std::make_pair(fhicl::ParameterSetID{idString}, pset);
274 for (
auto const& pr: registry) {
275 const fhicl::ParameterSet pset = pr.second;
276 if (pset.has_key(
"source") && pset.has_key(
"source.maxEvents") && pset.has_key(
"source.module_type")) {
277 int max_events = pset.get<
int>(
"source.maxEvents");
278 std::string
module_type = pset.get<std::string>(
"source.module_type");
280 if (module_type ==
"EmptyEvent") {
281 n_gen_event += max_events;
282 std::cout <<
"FILEMETA: " << max_events << std::endl;
286 n_event = ev.numberOfEventsInFile();
287 std::cout <<
"FILEMETA nevent: " << n_event << std::endl;
288 std::cout <<
"FILEMETA ngenevent: " << n_gen_event << std::endl;
293 last_tfile = ev.getTFile();
301 fTree->Write(
"sbnana", TObject::kOverwrite);
304 fRecoTree->Write(
"sbnreco", TObject::kOverwrite);
306 fSubRunTree->Write(
"sbnsubrun", TObject::kOverwrite);
319 const simb::MCParticle &genie_part,
320 const simb::MCTruth &mctruth,
321 const std::vector<art::Ptr<simb::MCParticle>> &g4_mcparticles,
322 const std::vector<const sim::GeneratedParticleInfo *> infos) {
324 const simb::MCParticle *ret = NULL;
325 for (
int iparticle = 0; iparticle < g4_mcparticles.size(); iparticle++) {
326 if (infos[iparticle]->hasGeneratedParticleIndex() &&
327 infos[iparticle]->generatedParticleIndex() < mctruth.NParticles() &&
328 mctruth.GetParticle(infos[iparticle]->generatedParticleIndex()).TrackId() == genie_part.TrackId() &&
329 g4_mcparticles[iparticle]->Process() ==
"primary" ) {
336 const simb::MCParticle& matched_genie_particle = mctruth.GetParticle(infos[iparticle]->generatedParticleIndex());
337 if ((matched_genie_particle.Position().Vect() - g4_mcparticles[iparticle]->Position().Vect()).Mag() < 1
e-4 &&
338 matched_genie_particle.PdgCode() == g4_mcparticles[iparticle]->PdgCode()) {
342 ret = g4_mcparticles[iparticle].get();
355 gallery::Handle<std::vector<simb::MCTruth>> mctruths_handle;
356 bool mctruth_is_valid = ev.getByLabel(
fTruthTag, mctruths_handle);
358 gallery::Handle<std::vector<simb::MCParticle> > mcparticle_list;
360 bool mcparticles_is_valid = mcparticle_list.isValid();
362 gallery::Handle<std::vector<simb::GTruth> > gtruths_handle;
363 ev.getByLabel(
fTruthTag, gtruths_handle);
364 bool genie_truth_is_valid = gtruths_handle.isValid();
367 std::vector<gallery::Handle<std::vector<evwgh::MCEventWeight> > > wghs;
371 gallery::Handle<std::vector<evwgh::MCEventWeight> > this_wgh;
372 bool hasWeights = ev.getByLabel(weightTag, this_wgh);
374 if (hasWeights && mctruth_is_valid) {
375 assert(this_wgh->size() == mctruths_handle->size());
378 wghs.push_back(this_wgh);
383 gallery::Handle<std::vector<simb::MCFlux> > mcflux_handle;
384 bool flux_is_valid = ev.getByLabel(fFluxTag, mcflux_handle);
386 if (flux_is_valid && mctruth_is_valid) {
387 assert(mctruths_handle->size() == mcflux_handle->size());
396 auto const& evaux = ev.eventAuxiliary();
402 if (mctruth_is_valid) {
404 art::FindManyP<simb::MCParticle, sim::GeneratedParticleInfo> truth_to_particles(mctruths_handle, ev,
fMCParticleTag);
405 unsigned n_truth = mctruths_handle->size();
406 for (
size_t i=0; i<n_truth; i++) {
409 interaction.
index = i;
411 auto const& mctruth = mctruths_handle->at(i);
415 if (!mctruth.NeutrinoSet())
continue;
428 for (
auto const& wgh : wghs) {
429 for (
const std::pair<std::string, std::vector<double> >& this_wgh : wgh->at(i).fWeight) {
431 if (interaction.
weights.count(this_wgh.first) == 0) {
434 std::vector<float>(this_wgh.second.begin(), this_wgh.second.end())
439 interaction.
weights.at(this_wgh.first).insert(
440 interaction.
weights.at(this_wgh.first).end(),
441 this_wgh.second.begin(),
442 this_wgh.second.end());
448 if (mcflux_handle.isValid()) {
449 const simb::MCFlux& flux = mcflux_handle->at(i);
453 TVector3(flux.fvx, flux.fvy, flux.fvz);
458 TLorentzVector q_labframe;
461 std::vector<art::Ptr<simb::MCParticle>> this_mcparticle_list;
462 std::vector<const sim::GeneratedParticleInfo *> this_mcparticle_assns;
463 if (mcparticles_is_valid) {
464 this_mcparticle_list = truth_to_particles.at(i);
465 this_mcparticle_assns = truth_to_particles.data(i);
468 if (mctruth.NeutrinoSet()) {
470 const simb::MCNeutrino&
nu = mctruth.GetNeutrino();
485 const simb::MCParticle& lepton = nu.Lepton();
486 interaction.
lepton.
pdg = lepton.PdgCode();
487 interaction.
lepton.
energy = lepton.Momentum(0).Energy();
489 interaction.
lepton.
start = lepton.Position(0).Vect();
494 const simb::MCParticle* lepton_traj =
Genie2G4MCParticle(lepton, mctruth, this_mcparticle_list, this_mcparticle_assns);
497 if (lepton_traj != NULL) {
506 interaction.
lepton.
end = lepton_traj->EndPosition().Vect();
515 q_labframe = nu.Nu().EndMomentum() - lepton.Momentum(0);
532 for (
int iparticle=0; iparticle<mctruth.NParticles(); iparticle++) {
533 const simb::MCParticle& particle = mctruth.GetParticle(iparticle);
535 if (particle.Process() !=
"primary") {
538 fsp.
pdg = particle.PdgCode();
539 fsp.
energy = particle.Momentum(0).Energy();
540 fsp.
momentum = particle.Momentum(0).Vect();
541 fsp.
start = particle.Position(0).Vect();
543 fsp.
is_primary = (particle.Process() ==
"primary");
548 const simb::MCParticle *traj =
Genie2G4MCParticle(particle, mctruth, this_mcparticle_list, this_mcparticle_assns);
563 if (genie_truth_is_valid) {
564 auto const& gtruth = gtruths_handle->at(i);
565 TLorentzVector q_nucframe(q_labframe);
568 const TLorentzVector& nucP4 = gtruth.fHitNucP4;
569 TVector3 nuc_boost(nucP4.BoostVector());
570 q_nucframe.Boost(nuc_boost);
TVector3 momentum
Neutrino three-momentum.
TTree * fSubRunTree
Subrun output tree.
Metadata metadata
Event metadata.
double MCParticleLength(const simb::MCParticle &particle)
TVector3 momentum
Three-momentum.
TParameter< int > * fExperimentParameter
Saves value of experiment enum.
void SetupServices(gallery::Event &ev)
Encapsulate the construction of a single cyostat.
Final state particle information.
art::InputTag fTruthTag
art tag for MCTruth information
FinalStateParticle lepton
The primary final state lepton.
int parentDecayMode
Parent hadron/muon decay mode.
TTree * fTree
The output ROOT tree.
std::vector< event::RecoInteraction > * fReco
Reco interaction list.
TFile * fOutputFile
The output ROOT file.
Neutrino neutrino
The neutrino.
Contains data associated to particles from detector simulation.
std::vector< geo::BoxBoundedGeo > fActiveVolumes
List of active volumes in configured detector.
TVector3 start
Start position in detector coords [cm].
int parentPDG
Parent hadron/muon PDG.
std::vector< art::InputTag > fWeightTags
art tag(s) for MCEventWeight information
bool iscc
CC (true) or NC/interference (false)
float length
Total length of the energy depositions [cm].
The reconstructed event data definition.
size_t ntruth
Size of truth.
const geo::GeometryCore * GetGeometryProvider() const
event::Event * fEvent
The standard output event data structure.
TPC_iterator begin_TPC() const
Returns an iterator pointing to the first TPC in the detector.
Access the description of auxiliary detector geometry.
event::RecoEvent * fRecoEvent
The standard output reco event data structure.
int status_code
Status code returned by GENIE (see GenieStatus enum)
float modq_lab
|q|, lab frame
TVector3 end
End position in detector coords (may be outside of AV) [cm].
auto vector(Vector const &v)
Returns a manipulator which will print the specified array.
Access the description of detector geometry.
Interface to LArSoft services.
void UpdateSubRuns(gallery::Event &ev)
virtual void Initialize(char *config=NULL)
std::string fProviderConfig
A custom provider config fcl file.
unsigned long fEventIndex
An incrementing index.
bool fWriteTree
Enable writing of the main tree.
int targetPDG
PDG code of struck target.
SubRun * fSubRun
Standard output subrun structure.
bool is_primary
Whether the process producing the particle was "primary".
virtual void EventCleanup()
double MCParticleContainedLength(const simb::MCParticle &particle, const std::vector< geo::BoxBoundedGeo > &active_volumes)
Experiment fExperimentID
Experiment identifier.
art::InputTag fFluxTag
art tag for MCFlux information
FileMeta * fFileMeta
standard output file metadata structure
std::vector< RecoInteraction > reco
Reconstructed interactions.
back track the reconstruction to the simulation
art::InputTag fMCShowerTag
art tag for MCShower
The standard subrun data definition.
float inelasticityY
Inelasticity y.
float w
Hadronic invariant mass W.
virtual void FillRecoTree()
Metadata metadata
Event metadata.
size_t index
Index in the MCTruth.
float baseline
Distance from decay to interaction.
Experiment experiment
Experiment identifier.
void BuildEventTree(gallery::Event &ev)
The standard event data definition.
auto begin(FixedBins< T, C > const &) noexcept
IteratorBox< cryostat_iterator,&GeometryCore::begin_cryostat,&GeometryCore::end_cryostat > IterateCryostats() const
Enables ranged-for loops on all cryostats of the detector.
size_t nfinalstate
Size of finalstate.
fhicl::ParameterSet * LoadConfig(char *configfile)
const simb::MCParticle * Genie2G4MCParticle(const simb::MCParticle &genie_part, const simb::MCTruth &mctruth, const std::vector< art::Ptr< simb::MCParticle >> &g4_mcparticles, const std::vector< const sim::GeneratedParticleInfo * > infos)
float q0
q0, struck nucleon rest frame
float modq
|q|, struck nucleon rest frame
std::string fGeneratorProcess
process_name of process used to run genie. Used to extract subrun/POT information ...
BEGIN_PROLOG triggeremu_data_config_icarus settings PMTADCthresholds sequence::icarus_stage0_multiTPC_TPC physics sequence::icarus_stage0_EastHits_TPC physics sequence::icarus_stage0_WestHits_TPC physics producers purityana0 module_type
std::vector< FinalStateParticle > finalstate
Other final state particles.
float q0_lab
q0, lab frame
double ECCQE(const TVector3 &l_momentum, double l_energy, double energy_distortion, double angle_distortion)
float energy
Neutrino energy (GeV)
TTree * fRecoTree
The output reco ROOT tree.
TVector3 position
Neutrino interaction position.
static std::vector< Experiment > GetValidExperiments()
ProviderManager * fProviderManager
Interface for provider access.
bool fWriteRecoTree
Enable writing of the reco tree.
art::InputTag fMCParticleTag
art tag for MCParticle
std::string fOutputFilename
The output filename.
TTree * fFileMetaTree
File metadata output tree.
void SetupServices(gallery::Event &ev)
int pdg
PDG code of probe neutrino.
height to which particles are projected pnfs larsoft persistent physics cosmics Fermilab CORSIKA standard He_showers_ * db
Forward iterator browsing all geometry elements in the detector.
art::InputTag fMCTrackTag
art tag for MCTrack
int initpdg
Initial PDG code of probe neutrino.
All truth information associated with one neutrino interaction.
BEGIN_PROLOG could also be cout
static const int kUnfilled
Value for unfilled variables.
int genie_intcode
Interaction mode (as for LArSoft MCNeutrino::Mode() )
TPC_iterator end_TPC() const
Returns an iterator pointing after the last TPC in the detector.
Encapsulate the construction of a single detector plane.
void UpdateFileMeta(gallery::Event &ev)
virtual void Setup(char *config=NULL)
TVector3 parentDecayVtx
Parent hadron/muon decay vertex.
bool isnc
same as LArSoft "ccnc" - 0=CC, 1=NC
std::map< std::string, std::vector< float > > weights
std::vector< Interaction > truth
All truth interactions.