7#include <Pythia8/Pythia.h>
10#include <TTreeReader.h>
11#include <TTreeReaderValue.h>
20#include "FairLogger.h"
32template <
typename Histogram>
33Histogram* WithFlowBins(TDirectory* dir,
const char* name,
const char* title,
34 int bins,
double low,
double high) {
35 const double width = (high - low) / bins;
37 new Histogram(name, title, bins + 2, low - width, high + width);
38 histogram->SetDirectory(dir);
42template <
typename Histogram>
43Histogram* WithFlowBins(TDirectory* dir,
const char* name,
const char* title,
44 int nx,
double xmin,
double xmax,
int ny,
double ymin,
46 const double dx = (xmax - xmin) / nx, dy = (ymax - ymin) /
ny;
47 auto* histogram =
new Histogram(name, title, nx + 2, xmin - dx, xmax + dx,
48 ny + 2, ymin - dy, ymax + dy);
49 histogram->SetDirectory(dir);
53double VisibleFlowValue(
const TAxis* axis,
double value) {
54 if (value < axis->GetBinLowEdge(2))
return axis->GetBinCenter(1);
55 if (value >= axis->GetBinLowEdge(axis->GetNbins()))
56 return axis->GetBinCenter(axis->GetNbins());
60void FillWithFlow(TH1* histogram,
double value) {
61 if (!histogram)
return;
62 histogram->Fill(VisibleFlowValue(histogram->GetXaxis(), value));
65void FillWithFlow(TH2* histogram,
double x,
double y) {
66 if (!histogram)
return;
67 histogram->Fill(VisibleFlowValue(histogram->GetXaxis(), x),
68 VisibleFlowValue(histogram->GetYaxis(), y));
72 const int pid = std::abs(particle.
pid);
73 return pid == 12 ||
pid == 14 ||
pid == 16;
76bool InsideXY(
const TVector3& hit,
const std::array<double, 4>& bounds) {
77 return hit.X() >= bounds[0] && hit.X() <= bounds[1] && hit.Y() >= bounds[2] &&
81bool PassesChargedMomentumCut(
const DISparticle& particle) {
82 return std::sqrt(particle.
px * particle.
px + particle.
py * particle.
py +
83 particle.
pz * particle.
pz) > 1.;
86constexpr std::array<double, 5> kMomentumEdges = {2., 20., 50., 100., 400.};
87constexpr std::array<double, 6> kPtEdges = {0., 1., 2., 3., 5., 10.};
89int KinematicBin(
double value,
const double* edges,
unsigned bins) {
90 if (!std::isfinite(value) || value < edges[0] || value > edges[bins])
92 for (
unsigned bin = 0; bin < bins; ++bin)
93 if (value < edges[bin + 1] || bin + 1 == bins)
return bin;
103 fLogger = FairLogger::GetLogger();
106 fPDG = TDatabasePDG::Instance();
110 unsigned xbins,
double ymin,
111 double ymax,
unsigned ybins,
112 double zmin,
double zmax,
114 const auto symmetricAboutZero = [](
double low,
double high) {
115 return std::abs(low + high) <=
116 1.e-12 * std::max({1., std::abs(low), std::abs(high)});
118 if (!std::isfinite(xmin) || !std::isfinite(xmax) || !std::isfinite(ymin) ||
119 !std::isfinite(ymax) || !std::isfinite(zmin) || !std::isfinite(zmax) ||
120 xmin >= xmax || ymin >= ymax || zmin >= zmax || xbins == 0 ||
121 ybins == 0 || zbins == 0 || xbins % 2 == 0 || ybins % 2 == 0 ||
122 !symmetricAboutZero(xmin, xmax) || !symmetricAboutZero(ymin, ymax))
123 throw std::invalid_argument(
124 "Filter-efficiency x/y axes must be symmetric about zero with an odd "
125 "positive number of bins; all axis bounds must increase");
134 const TString& label) {
139 h.dis_vxz = WithFlowBins<TH2D>(
140 dir, Form(
"vertex_x_vs_z_%s", label.Data()),
141 Form(
"DIS vertex x vs z - %s;z [cm];x [cm]", mat.Data()), 3300, 2700.,
142 9000., 600, -300., 300.);
143 h.dis_vyz = WithFlowBins<TH2D>(
144 dir, Form(
"vertex_y_vs_z_%s", label.Data()),
145 Form(
"DIS vertex y vs z - %s;z [cm];y [cm]", mat.Data()), 3300, 2700.,
146 9000., 600, -300., 300.);
147 h.dis_vxy = WithFlowBins<TH2D>(
148 dir, Form(
"vertex_y_vs_x_%s", label.Data()),
149 Form(
"DIS vertex y vs x - %s;x [cm];y [cm]", mat.Data()), 600, -300.,
150 300., 600, -300., 300.);
152 h.dis_vr = WithFlowBins<TH1D>(
153 dir, Form(
"vertex_r_%s", label.Data()),
154 Form(
"DIS vertex radius - %s;r [cm];Events", mat.Data()), 600, 0.,
156 h.dis_vz = WithFlowBins<TH1D>(
157 dir, Form(
"vertex_z_%s", label.Data()),
158 Form(
"DIS vertex z - %s;z [cm];Events", mat.Data()), 3300, 2700., 9000.);
160 h.dis_pdg = WithFlowBins<TH1I>(
161 dir, Form(
"daughter_pdg_%s", label.Data()),
162 Form(
"PDG code of DIS daughters - %s;PDG code;Particles", mat.Data()),
163 12001, -6000.5, 6000.5);
164 h.dis_pdgGrouped = WithFlowBins<TH1I>(
165 dir, Form(
"daughter_pdg_grouped_%s", label.Data()),
166 Form(
"DIS daughter species - %s;Species;Particles", mat.Data()), 11, 0.5,
168 const char* labels[] = {
"e^{+}",
"e^{-}",
"#mu^{+}",
"#mu^{-}",
169 "#gamma",
"#nu/#bar{#nu}",
"#pi^{#pm}",
"h^{#pm}",
170 "#pi^{0}",
"h^{0}",
"other"};
171 for (
int bin = 1; bin <= 11; ++bin)
172 h.dis_pdgGrouped->GetXaxis()->SetBinLabel(bin + 1, labels[bin - 1]);
174 h.dis_n = WithFlowBins<TH1I>(
175 dir, Form(
"n_daughters_%s", label.Data()),
176 Form(
"Number of DIS daughters - %s;multiplicity;Event", mat.Data()), 50,
179 h.dis_nCharged = WithFlowBins<TH1I>(
180 dir, Form(
"n_daughters_charged_%s", label.Data()),
181 Form(
"Number of charged DIS daughters - %s;charged multiplicity;Event",
184 h.dis_nChargedCandidates = WithFlowBins<TH1I>(
185 dir, Form(
"n_charged_candidates_%s", label.Data()),
187 "Number of charged filter candidates - %s;charged multiplicity;Event",
190 h.dis_eNeutralTD = WithFlowBins<TH1D>(
191 dir, Form(
"neutral_candidate_energy_TD_%s", label.Data()),
192 Form(
"Visible neutral candidate energy reaching timing detector - "
193 "%s;energy [GeV];Event",
197 h.dis_pChargedFrac = WithFlowBins<TH1D>(
198 dir, Form(
"pfrac_charged_%s", label.Data()),
199 Form(
"Charged fraction - %s;p(charged)/p(all);Event", mat.Data()), 101,
202 h.dis_pMuFrac = WithFlowBins<TH1D>(
203 dir, Form(
"pfrac_mu_%s", label.Data()),
204 Form(
"p fraction of outgoing mu - %s;p(mu)/p(all);Event", mat.Data()),
207 h.mu_p = WithFlowBins<TH1D>(
208 dir, Form(
"muon_p_%s", label.Data()),
209 Form(
"muon momentum - %s;p_{#mu,in} [GeV]; Input mu events",
213 h.mu_pt = WithFlowBins<TH1D>(
214 dir, Form(
"muon_pt_%s", label.Data()),
215 Form(
"muon p_{T} - %s;p_{T,#mu,in} [GeV];Input mu events", mat.Data()),
217 h.mu_ppt = WithFlowBins<TH2D>(dir, Form(
"muon_pt_vs_p_%s", label.Data()),
218 Form(
"muon p_{T} vs p - %s;p_{#mu,in} [GeV]; "
219 "p_{T,#mu,in} [GeV];Input mu events",
221 400, 0, 400, 100, 0., 10.);
223 h.mu_ndis = WithFlowBins<TH1I>(
224 dir, Form(
"muon_n_dis_%s", label.Data()),
225 Form(
"Number of DIS events - %s;DIS multiplicity;Input mu events",
229 h.mu_wdis = WithFlowBins<TH1D>(
230 dir, Form(
"muon_vtx_weight_%s", label.Data()),
231 Form(
"DIS vertex weight - %s;wDIS;Input mu events", mat.Data()), 100,
242 for (
unsigned ipt = 0; ipt <
kPtBins; ++ipt)
245 Form(
"p%u_pt%u_%s", ip, ipt,
MatTypeStr[imat].Data());
246 const TString title = Form(
247 "DIS filter efficiency, %.0f #leq p < %.0f GeV, "
248 "%.0f #leq p_{T} < %.0f GeV - %s",
249 kMomentumEdges[ip], kMomentumEdges[ip + 1], kPtEdges[ipt],
251 const TString axTitles =
";x_{#mu,start} [cm];y_{#mu,start} [cm]";
254 all =
new TH2D(Form(
"filter_efficiency_all_%s", tag.Data()),
257 passed =
new TH2D(Form(
"filter_efficiency_passed_%s", tag.Data()),
260 all->SetDirectory(dir);
262 passed->SetDirectory(dir);
276 Form(
"filter_efficiency_z_all_%s_x%u_y%u", tag.Data(), ix, iy),
277 title + Form(
";z_{DIS} [cm];Weighted DIS events"),
279 passedZ =
new TH1D(Form(
"filter_efficiency_z_passed_%s_x%u_y%u",
283 allZ->SetDirectory(dir);
285 passedZ->SetDirectory(dir);
293 double momentum,
double pt,
294 double x,
double y,
double z,
295 double weight,
bool passed) {
297 const int ip = KinematicBin(momentum, kMomentumEdges.data(),
kMomentumBins);
298 const int ipt = KinematicBin(pt, kPtEdges.data(),
kPtBins);
299 if (ip < 0 || ipt < 0)
return;
302 all->Fill(x, y, weight);
303 if (passed) accepted->Fill(x, y, weight);
305 const int ix = all->GetXaxis()->FindFixBin(x) - 1;
306 const int iy = all->GetYaxis()->FindFixBin(y) - 1;
316 if (aEvts < -1 || aStart < 0)
317 throw std::invalid_argument(
"Invalid event range");
332 std::vector<std::string> fileNames = {fileName};
337 const int startEvent) {
338 if (startEvent < 0)
return kFALSE;
340 if (fileNames.empty()) {
341 LOG(error) <<
"MuDISFilter: no input files provided. "
342 <<
"Check the -f/--inputFile argument or input file glob.";
345 for (
const auto& fileName : fileNames) {
346 if (fileName.empty()) {
347 LOG(error) <<
"MuDISFilter: received an empty input file name. "
348 <<
"Check the -f/--inputFile argument.";
353 for (
const auto& name : fileNames) {
354 std::unique_ptr<TFile> file(TFile::Open(name.c_str(),
"READ"));
355 TTree* tree =
nullptr;
356 if (file && !file->IsZombie()) file->GetObject(
"MuonDIS", tree);
358 LOG(error) <<
"MuDISFilter: missing MuonDIS tree in " << name;
362 if (!check.
Setup(tree))
return kFALSE;
363 tree->ResetBranchAddresses();
368 ftree =
new TChain(
"MuonDIS");
369 for (
const auto& name : fileNames) {
370 if (!
ftree->Add(name.c_str()))
return kFALSE;
372 Long64_t treeEvts =
ftree->GetEntries();
373 LOG(info) <<
"Reading " << treeEvts <<
" entries.";
377 LOG(error) <<
"MuDISFilter: failed to bind one or more required branches";
380 LOG(info) <<
"MuDISFilter: Initialization successful.";
387 const std::string& output) {
388 std::vector<std::string> fileNames = {input};
393 const std::string& output) {
395 throw std::runtime_error(
396 "Filter options 1 and 2 require detector acceptance");
398 throw std::runtime_error(
399 "Configure detector acceptance with geometry and field map first");
404 throw std::runtime_error(
"MuDISFilter: failed to initialize input files");
410 TChain vertices(
"MuonDIS");
411 for (
const auto& name : input) vertices.Add(name.c_str());
412 TTreeReader reader(&vertices);
413 std::vector<std::unique_ptr<TTreeReaderValue<std::vector<double>>>> vz;
414 for (
unsigned imat = 0; imat < nMats; ++imat)
415 vz.emplace_back(
new TTreeReaderValue<std::vector<double>>(
419 :
ftree->GetEntries();
420 double minimum = std::numeric_limits<double>::infinity(),
425 Long64_t scanned = 0;
426 while (reader.Next()) {
428 for (
unsigned imat = 0; imat < nMats; ++imat) {
429 const auto* values = vz[imat]->Get();
430 if (!values || vz[imat]->GetSetupStatus() < 0 ||
431 vz[imat]->GetReadStatus() !=
432 TTreeReaderValue<std::vector<double>>::kReadSuccess) {
436 for (
double z : *values) {
437 if (!std::isfinite(z)) {
441 minimum = std::min(minimum, z);
442 if (
MatTypeStr[imat] ==
"MS") msMinimum = std::min(msMinimum, z);
446 valid = valid && scanned == end -
fstartEvt;
448 if (valid && std::isfinite(minimum)) {
449 const double detectorMinimum =
454 minimum = std::min(minimum, detectorMinimum);
455 LOG(info) <<
"Muon shield field bounds: input MS minimum z = "
456 << msMinimum <<
" cm; conservative scan minimum z = " << minimum
461 fPropagator->SetMuonShieldMinZ(-std::numeric_limits<double>::infinity());
464 <<
"Vertex range scan failed; using full muon shield field bounds";
470 const auto closeOutput = [
this](TFile* file) {
473 for (
auto& hist :
hist_all) hist = {};
477 std::unique_ptr<TFile,
decltype(closeOutput)> outfile(
478 TFile::Open(output.c_str(),
"CREATE"), closeOutput);
479 if (!outfile || outfile->IsZombie()) {
480 throw std::runtime_error(
"MuDISFilter: cannot create output file " +
485 for (
unsigned imat = 0; imat < nMats; ++imat) {
486 TDirectory* dir = outfile->mkdir(
MatTypeStr[imat].Data());
495 "MuonDIS",
"Muon information, DIS products and soft interaction tracks");
498 Long64_t n =
ftree->GetEntries();
499 LOG(info) <<
" * input tree with " << n <<
" entries" << std::endl;
504 if (outfile->Write() <= 0 || outfile->TestBit(TFile::kWriteError))
505 throw std::runtime_error(
"MuDISFilter: failed to write output file");
513 for (
unsigned i = 0; i < nMats; ++i)
foutEv.br[i].initEvent(0);
517 return Charge(particle) != 0.;
521 const auto* pdg =
fPDG->GetParticle(particle.
pid);
523 if (!pdg && std::abs(particle.
pid) >= 1000000000)
524 return ((std::abs(particle.
pid) / 10000) % 1000) *
525 (particle.
pid > 0 ? 1. : -1.);
526 return pdg ? pdg->Charge() / 3. : 0.;
530 switch (particle.
pid) {
554 const auto* pdg =
fPDG->GetParticle(particle.
pid);
556 const TString particleClass = pdg->ParticleClass();
557 if (particleClass ==
"Meson" || particleClass ==
"Baryon")
558 return pdg->Charge() != 0. ? 8 : 10;
566 const std::array<const char*, 5> names = {
"Tr1",
"Tr2",
"Tr3",
"Tr4",
568 std::array<double, 5> planes;
569 std::array<std::array<double, 4>, 5> bounds;
570 for (
unsigned i = 0; i < names.size(); ++i) {
571 planes[i] = propagator.
GetPlaneZ(names[i]);
576 }
else if (option == 2) {
578 const double end = propagator.
GetVolumeZRange(
"TimingDetector").second;
580 throw std::runtime_error(
581 "Timing detector end must be downstream of the Tr1 front");
588 throw std::invalid_argument(
"Filter option must be 0, 1 or 2");
603 1 + (
static_cast<unsigned>(
fPythiaDecayer->rndm.getState().seed) - 1) %
606 if (!
fPythiaDecayer->readString(
"Random:seed = " + std::to_string(seed)))
607 throw std::invalid_argument(
"MuDISFilter: invalid Pythia8 decay seed");
608 constexpr std::array<int, 10> decayIds = {211, 321, 130, 310, 3112,
609 3122, 3222, 3312, 3322, 3334};
610 for (
int id : decayIds) {
611 if (!
fPythiaDecayer->readString(std::to_string(
id) +
":mayDecay = on"))
612 throw std::runtime_error(
613 "MuDISFilter: cannot enable Pythia8 decay for PDG " +
617 throw std::runtime_error(
618 "MuDISFilter: failed to initialize the Pythia8 decayer");
619 LOG(info) <<
"MuDISFilter: Pythia8 decay seed = "
637 const std::vector<DISparticle>& daughters,
const TVector3& vertex)
const {
639 std::vector<FilterCandidate> candidates;
640 candidates.reserve(daughters.size());
641 for (
const auto& particle : daughters)
642 candidates.push_back({particle, vertex});
646 throw std::runtime_error(
"MuDISFilter: Pythia decays require Tr1 geometry");
648 std::vector<FilterCandidate> candidates;
649 const double tr1Zmm = 10. *
fTr1Z;
650 const auto addParticle = [&candidates](
const Pythia8::Particle& particle) {
652 daughter.
pid = particle.id();
653 daughter.
px = particle.px();
654 daughter.
py = particle.py();
655 daughter.
pz = particle.pz();
656 daughter.
E = particle.e();
657 candidates.push_back(
658 {daughter, TVector3(particle.xProd() / 10., particle.yProd() / 10.,
659 particle.zProd() / 10.)});
661 for (
const auto& daughter : daughters) {
663 const double momentum2 = daughter.px * daughter.px +
664 daughter.py * daughter.py +
665 daughter.pz * daughter.pz;
666 const double mass2 = daughter.E * daughter.E - momentum2;
667 if (mass2 < -1.e-8) {
668 candidates.push_back({daughter, vertex});
672 daughter.pid, 1, 0, 0, daughter.px, daughter.py, daughter.pz,
673 daughter.E, std::sqrt(std::max(0., mass2)));
674 fPythiaDecayer->event[root].vProd(10. * vertex.X(), 10. * vertex.Y(),
675 10. * vertex.Z(), 0.);
681 std::function<void(
int)> decay = [&](
int index) {
683 if ((tr1Zmm - particle.zProd()) * particle.pz() <= 0.) {
684 addParticle(particle);
709 return (z - candidate.vertex.Z()) * candidate.particle.pz >= 0.;
714 const auto& particle = candidate.particle;
722 double charge,
double z,
723 const std::array<double, 4>& bounds)
const {
725 const auto& particle = candidate.particle;
726 TVector3 hit, momentum;
728 charge, candidate.vertex,
729 TVector3(particle.px, particle.py, particle.pz), z, hit,
731 InsideXY(hit, bounds);
735 double charge)
const {
736 const auto& particle = candidate.particle;
737 const auto& vertex = candidate.vertex;
738 TVector3 position = vertex, momentum(particle.px, particle.py, particle.pz);
739 std::array<unsigned, 5> order = {0, 1, 2, 3, 4};
740 std::sort(order.begin(), order.end(),
741 [
this, &particle](
unsigned a,
unsigned b) {
742 return particle.pz >= 0. ? fStationZ[a] < fStationZ[b]
743 : fStationZ[a] > fStationZ[b];
745 bool firstPair =
false, secondPair =
false, TD =
false;
746 for (
unsigned station : order) {
748 TVector3 hit, nextMomentum;
749 if (!
fPropagator->Extrapolate(charge, position, momentum,
753 momentum = nextMomentum;
754 if (!InsideXY(hit,
fStationXY[station]))
continue;
757 else if (station < 4)
761 if (firstPair && secondPair && TD)
return true;
767 const auto& particle = candidate.particle;
772 Charge(particle), candidate.vertex,
773 TVector3(particle.px, particle.py, particle.pz), minimum, maximum);
777 const std::vector<FilterCandidate>& candidates,
unsigned minimum)
const {
778 if (minimum == 0)
return true;
779 if (candidates.size() < minimum)
return false;
781 unsigned remaining = 0, accepted = 0;
782 std::vector<double> charges;
783 charges.reserve(candidates.size());
784 for (
const auto& candidate : candidates) {
786 charges.push_back(charge);
787 if (charge != 0.) ++remaining;
789 for (std::size_t i = 0; i < candidates.size(); ++i) {
790 if (accepted + remaining < minimum)
return false;
791 if (charges[i] == 0.)
continue;
798 {-200., 200., -300., 300.});
801 if (++accepted >= minimum)
return true;
807 TGeoManager* geometry,
double z,
810 throw std::invalid_argument(
"Detector acceptance requires a field map");
811 auto propagator = std::make_unique<MagneticTrackPropagator>(field, geometry,
813 if (muonShieldField) {
814 const auto range = propagator->GetMuonShieldZRange();
816 <<
"MuDISFilter: muon shield geometry z range [" << range.first <<
", "
818 <<
"] cm; propagating with shield map including nonzero fringe fields";
820 const double planeZ = std::isnan(z) ? propagator->GetPlaneZ() : z;
821 if (!std::isfinite(planeZ))
822 throw std::invalid_argument(
"Detector z must be finite");
823 fTr1Z = propagator->GetPlaneZ(
"Tr1");
827 }
catch (
const std::runtime_error&) {
838 throw std::runtime_error(
839 "Detector acceptance requires the DIS vertex; use "
840 "PassFilter(daughters, vertex)");
845 const TVector3& vertex)
const {
851 const std::vector<FilterCandidate>& candidates)
const {
853 throw std::runtime_error(
854 "Filter options 1 and 2 require detector acceptance");
856 throw std::runtime_error(
857 "Configure detector acceptance with geometry and field map first");
859 return std::any_of(candidates.begin(), candidates.end(),
861 return HitsDetectorVolume(candidate);
877 const std::vector<DISparticle>& daughters,
878 const std::vector<FilterCandidate>& candidates,
880 unsigned charged = 0;
881 double totalP = 0., chargedP = 0., muonP = 0.;
882 for (
const auto& p : daughters) {
884 for (
auto* target : {&h, filtered}) {
885 if (!target)
continue;
886 FillWithFlow(target->dis_pdg, p.pid);
887 FillWithFlow(target->dis_pdgGrouped, category);
889 const double momentum = std::sqrt(p.px * p.px + p.py * p.py + p.pz * p.pz);
893 chargedP += momentum;
895 if (std::abs(p.pid) == 13) muonP += momentum;
897 unsigned chargedCandidates = 0;
898 double neutralTDEnergy = 0.;
899 for (
const auto& candidate : candidates) {
902 }
else if (!IsNeutrino(candidate.particle) &&
904 neutralTDEnergy += candidate.particle.E;
907 for (
auto* target : {&h, filtered}) {
908 if (!target)
continue;
909 FillWithFlow(target->dis_vxz, br.DISvz->at(idis), br.DISvx->at(idis));
910 FillWithFlow(target->dis_vyz, br.DISvz->at(idis), br.DISvy->at(idis));
911 FillWithFlow(target->dis_vxy, br.DISvx->at(idis), br.DISvy->at(idis));
912 FillWithFlow(target->dis_vr,
913 std::hypot(br.DISvx->at(idis), br.DISvy->at(idis)));
914 FillWithFlow(target->dis_vz, br.DISvz->at(idis));
915 FillWithFlow(target->dis_n, daughters.size());
916 FillWithFlow(target->dis_nCharged, charged);
917 FillWithFlow(target->dis_nChargedCandidates, chargedCandidates);
918 FillWithFlow(target->dis_eNeutralTD, neutralTDEnergy);
920 FillWithFlow(target->dis_pChargedFrac, chargedP / totalP);
921 FillWithFlow(target->dis_pMuFrac, muonP / totalP);
928 throw std::runtime_error(
"Initialize input and output first");
929 if (
fstartEvt < 0)
throw std::invalid_argument(
"Negative start event");
932 :
ftree->GetEntries();
933 Long64_t selected = 0, skipped = 0;
934 Long64_t selectedDIS[nMats] = {};
935 double weightedDIS[nMats] = {};
936 Long64_t processedDIS[nMats] = {};
937 double weightedProcessedDIS[nMats] = {};
938 double weightedMuons[nMats] = {}, weightedSelectedMuons[nMats] = {};
939 for (Long64_t event =
fstartEvt;
event < end; ++event) {
941 LOG(info) <<
"MuDISFilter: processing entry " << event;
942 if (!
finEv.PrepareEntry(
ftree, event) ||
ftree->GetEntry(event) <= 0 ||
950 for (
const auto& br :
finEv.br) {
957 LOG(error) <<
"MuDISFilter: malformed entry " <<
event <<
"; skipping";
962 const auto& muon =
finEv.mcTrks->at(0);
963 const double muonP = muon.GetP(), muonPt = muon.GetPt();
965 for (
unsigned imat = 0; imat < nMats; ++imat) {
966 const auto& in =
finEv.br[imat];
967 auto& out =
foutEv.br[imat];
969 out.nDISevtsGenerated = in.nDISevtsGenerated;
970 out.pPythia = in.pPythia;
971 std::size_t offset = 0;
972 for (
int idis = 0; idis < in.nDISevts; ++idis) {
973 const auto endOffset = offset + in.nDISdau->at(idis);
974 std::vector<DISparticle> daughters(
975 in.DISparticles->begin() + offset,
976 in.DISparticles->begin() + endOffset);
978 const TVector3 vertex(in.DISvx->at(idis), in.DISvy->at(idis),
980 std::vector<FilterCandidate> candidates;
982 candidates.reserve(daughters.size());
983 for (
const auto& daughter : daughters)
984 candidates.push_back({daughter, vertex});
988 bool identical = candidates.size() == daughters.size();
989 for (std::size_t i = 0; identical && i < daughters.size(); ++i) {
990 const auto& original = daughters[i];
991 const auto& candidate = candidates[i];
992 identical = candidate.particle.pid == original.pid &&
993 candidate.particle.px == original.px &&
994 candidate.particle.py == original.py &&
995 candidate.particle.pz == original.pz &&
996 candidate.particle.E == original.E &&
997 candidate.vertex.Z() == vertex.Z();
1000 std::ostringstream original;
1001 for (
const auto& daughter : daughters) original <<
' ' << daughter;
1003 << idis <<
" at z=" << vertex.Z()
1004 <<
" cm original daughters:" << original.str();
1005 std::ostringstream
final;
1006 for (
const auto& candidate : candidates) {
1007 const auto& daughter = candidate.particle;
1008 final <<
" [" << daughter.pid <<
',' << daughter.px <<
','
1009 << daughter.py <<
',' << daughter.pz <<
',' << daughter.E
1010 <<
"; vz=" << candidate.vertex.Z() <<
']';
1013 << idis <<
" final stable daughters:" <<
final.str();
1015 const bool accepted =
1020 muon.GetStartY(), vertex.Z(), in.wDIS,
1022 if (!accepted)
continue;
1024 out.DISxsec.push_back(in.DISxsec->at(idis));
1025 out.DIStarget.push_back(in.DIStarget->at(idis));
1026 out.DISvx.push_back(in.DISvx->at(idis));
1027 out.DISvy.push_back(in.DISvy->at(idis));
1028 out.DISvz.push_back(in.DISvz->at(idis));
1029 out.DISvt.push_back(in.DISvt->at(idis));
1030 out.nDISdau.push_back(daughters.size());
1031 out.DISparticles.insert(out.DISparticles.end(), daughters.begin(),
1035 auto fillMuon = [muonP, muonPt, &in](
Histograms& h,
int count) {
1036 FillWithFlow(h.mu_p, muonP);
1037 FillWithFlow(h.mu_pt, muonPt);
1038 FillWithFlow(h.mu_ppt, muonP, muonPt);
1039 FillWithFlow(h.mu_ndis, count);
1040 FillWithFlow(h.mu_wdis, in.wDIS);
1042 fillMuon(
hist_all[imat], in.nDISevts);
1043 if (out.nDISevts > 0) fillMuon(
hist_filt[imat], out.nDISevts);
1044 selectedDIS[imat] += out.nDISevts;
1045 if (out.nDISevts > 0) weightedDIS[imat] += out.nDISevts * in.wDIS;
1046 processedDIS[imat] += in.nDISevts;
1047 if (in.nDISevts > 0) weightedProcessedDIS[imat] += in.nDISevts * in.wDIS;
1048 weightedMuons[imat] += in.wDIS;
1049 if (out.nDISevts > 0) weightedSelectedMuons[imat] += in.wDIS;
1060 throw std::runtime_error(
"Failed writing MuonDIS entry");
1064 LOG(info) <<
"MuDISFilter: saved " << selected <<
" muon entries; skipped "
1065 << skipped <<
" unreadable or malformed entries.";
1066 for (
unsigned imat = 0; imat < nMats; ++imat) {
1067 LOG(info) <<
"MuDISFilter: selected DIS events in "
1068 <<
MatTypeStr[imat].Data() <<
": raw = " << selectedDIS[imat]
1069 <<
", weighted = " << weightedDIS[imat];
1071 new TH1D(
"filter_counts",
"Filter counts;Sample;Count", 8, 0., 8.);
1072 counts->SetDirectory(
1074 const char* labels[] = {
"muons_processed_raw",
"muons_processed_weighted",
1075 "muons_selected_raw",
"muons_selected_weighted",
1076 "dis_processed_raw",
"dis_processed_weighted",
1077 "dis_selected_raw",
"dis_selected_weighted"};
1078 const double values[] = {
1079 hist_all[imat].mu_ppt->GetEntries(), weightedMuons[imat],
1080 hist_filt[imat].mu_ppt->GetEntries(), weightedSelectedMuons[imat],
1081 static_cast<double>(processedDIS[imat]), weightedProcessedDIS[imat],
1082 static_cast<double>(selectedDIS[imat]), weightedDIS[imat]};
1083 for (
int bin = 1; bin <= 8; ++bin) {
1084 counts->GetXaxis()->SetBinLabel(bin, labels[bin - 1]);
1085 counts->SetBinContent(bin, values[bin - 1]);
double GetPlaneZ(const char *volumeName="Tr1") const
std::pair< double, double > GetVolumeZRange(const char *volumeName) const
std::array< double, 4 > GetVolumeExitFaceXY(const char *volumeName) const
void SetFilterEfficiencyBinning(double xmin, double xmax, unsigned xbins, double ymin, double ymax, unsigned ybins, double zmin, double zmax, unsigned zbins)
int DaughterCategory(const DISparticle &particle) const
double ChargedCandidateCharge(const FilterCandidate &candidate) const
ShipMuDIS::MuonInBranches finEv
std::unique_ptr< MagneticTrackPropagator > fPropagator
Runtime decayer.
ShipMuDIS::MuonBranches foutEv
std::vector< FilterCandidate > DecayDaughters(const std::vector< DISparticle > &daughters, const TVector3 &vertex) const
std::unique_ptr< Pythia8::Pythia > fPythiaDecayer
TChain * ftree
User-supplied runtime predicate.
bool HitsDetectorVolume(const FilterCandidate &candidate) const
void SetUsePythiaDecays(bool enabled)
Bool_t InitFile(const char *, int)
std::array< double, 4 > fTimingDetectorXY
int fnEvts
don't make it persistent, magic ROOT command
Filter fFilter
Runtime transport.
Histograms BookHistograms(TDirectory *dir, const TString &mat, const TString &label="")
bool IsCharged(const DISparticle &particle) const
std::array< double, 4 > fEfficiencyXYBounds
bool HitsTrackingAndTD(const FilterCandidate &candidate, double charge) const
Histograms hist_filt[ShipMuDIS::nMats]
void FillDIS(Histograms &h, const ShipMuDIS::MuonDISInBranches &br, int idis, const std::vector< DISparticle > &daughters, const std::vector< FilterCandidate > &candidates, Histograms *filtered)
std::array< double, 5 > fStationZ
std::pair< double, double > fDetectorVolumeZ
Tr1, Tr2, Tr3, Tr4, TD plane.
static constexpr unsigned kMomentumBins
void SetDetectorAcceptance(ShipBFieldMap *field, TGeoManager *geometry, double z=std::numeric_limits< double >::quiet_NaN(), ShipBFieldMap *muonShieldField=nullptr)
static constexpr unsigned kPtBins
void SetPythiaDecaySeed(unsigned seed)
bool IsForwardToPlane(const FilterCandidate &candidate, double z) const
bool PassCandidates(const std::vector< FilterCandidate > &candidates) const
bool PassChargedCandidates(const std::vector< FilterCandidate > &candidates, unsigned minimum) const
Bool_t InitFiles(const std::vector< std::string > &, int)
void FillFilterEfficiencyHistograms(unsigned material, double momentum, double pt, double x, double y, double z, double weight, bool passed)
double Charge(const DISparticle &particle) const
std::array< double, 2 > fEfficiencyZBounds
unsigned fEfficiencyZBins
void init(const int &aEvts, const int &aStart)
Histograms hist_all[ShipMuDIS::nMats]
unsigned fMinChargedDaughters
void process_file(const std::string &input, const std::string &output)
void ConfigureFilterGeometry(unsigned option, const MagneticTrackPropagator &propagator)
unsigned fEfficiencyYBins
void SetFilterOption(unsigned option)
static constexpr unsigned kEfficiencyMaterials
bool fUseDetectorAcceptance
unsigned fEfficiencyXBins
bool HitsDetectorPlane(const FilterCandidate &candidate, double charge, double z, const std::array< double, 4 > &bounds) const
bool IncludesParticle(const DISparticle &particle) const
bool HitsTimingDetector(const FilterCandidate &candidate) const
void BookFilterEfficiencyHistograms(TDirectory *dir)
unsigned fPythiaDecaySeed
FilterEfficiencyHistograms fFilterEfficiency
bool PassFilter(const std::vector< DISparticle > &daughters) const
void InitialisePythiaDecayer()
std::array< std::array< double, 4 >, 5 > fStationXY
Class that defines a (3d) magnetic field map (distances in cm, fields in tesla).
const std::array< TString, nMats > MatTypeStr