From 1e66adddd5f3af1b4b53400726b490370788b9d0 Mon Sep 17 00:00:00 2001
From: Wouter Deconinck <wdconinc@gmail.com>
Date: Thu, 5 Aug 2021 16:22:27 -0500
Subject: [PATCH] B0 track reconstruction benchmark

---
 .gitlab-ci.yml                                |   2 +-
 benchmarks/B0/config.yml                      |   6 +
 benchmarks/B0/far_forward_protons.sh          | 127 ++++++++++
 .../B0/options/B0_tracker_reconstruction.py   | 103 ++++++++
 .../B0/scripts/gen_far_forward_protons.cxx    |  83 ++++++
 .../B0/scripts/hits_far_forward_protons.cxx   | 190 ++++++++++++++
 .../B0/scripts/rec_far_forward_protons.cxx    | 237 ++++++++++++++++++
 7 files changed, 747 insertions(+), 1 deletion(-)
 create mode 100644 benchmarks/B0/config.yml
 create mode 100644 benchmarks/B0/far_forward_protons.sh
 create mode 100644 benchmarks/B0/options/B0_tracker_reconstruction.py
 create mode 100644 benchmarks/B0/scripts/gen_far_forward_protons.cxx
 create mode 100644 benchmarks/B0/scripts/hits_far_forward_protons.cxx
 create mode 100644 benchmarks/B0/scripts/rec_far_forward_protons.cxx

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 4489f61e..dd4be7dd 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -68,7 +68,7 @@ include:
   - local: 'benchmarks/imaging_ecal/config.yml'
   - local: 'benchmarks/imaging_shower_ML/config.yml'
   - local: 'benchmarks/full/config.yml'
-
+  - local: 'benchmarks/B0/config.yml'
 
 final_report:
   stage: finish
diff --git a/benchmarks/B0/config.yml b/benchmarks/B0/config.yml
new file mode 100644
index 00000000..d5444920
--- /dev/null
+++ b/benchmarks/B0/config.yml
@@ -0,0 +1,6 @@
+B0_far_forward_protons:
+  extends: .rec_benchmark
+  stage: run
+  timeout: 24 hours
+  script:
+    - bash benchmarks/B0/far_forward_protons.sh
diff --git a/benchmarks/B0/far_forward_protons.sh b/benchmarks/B0/far_forward_protons.sh
new file mode 100644
index 00000000..16f77c00
--- /dev/null
+++ b/benchmarks/B0/far_forward_protons.sh
@@ -0,0 +1,127 @@
+#!/bin/bash
+
+function print_the_help {
+  echo "USAGE: ${0} [--rec-only]  "
+  echo "  OPTIONS: "
+  echo "            --rec-only   only run gaudi reconstruction part"
+  exit 
+}
+
+REC_ONLY=
+ANALYSIS_ONLY=
+
+POSITIONAL=()
+while [[ $# -gt 0 ]]
+do
+  key="$1"
+
+  case $key in
+    -h|--help)
+      shift # past argument
+      print_the_help
+      ;;
+    --rec-only)
+      REC_ONLY=1
+      shift # past value
+      ;;
+    --ana-only)
+      ANALYSIS_ONLY=1
+      shift # past value
+      ;;
+    *)    # unknown option
+      #POSITIONAL+=("$1") # save it in an array for later
+      echo "unknown option $1"
+      print_the_help
+      shift # past argument
+      ;;
+  esac
+done
+set -- "${POSITIONAL[@]}" # restore positional parameters
+
+
+print_env.sh
+
+## To run the reconstruction, we need the following global variables:
+## - JUGGLER_INSTALL_PREFIX:   Install prefix for Juggler (simu/recon)
+## - JUGGLER_DETECTOR:         the detector package we want to use for this benchmark
+## - JUGGLER_DETECTOR_VERSION: the detector package we want to use for this benchmark
+## - DETECTOR_PATH:            full path to the detector definitions
+##
+## You can ready options/env.sh for more in-depth explanations of the variables
+## and how they can be controlled.
+export DETECTOR_PATH=${DETECTOR_PATH}
+
+if [[ ! -n  "${JUGGLER_N_EVENTS}" ]] ; then 
+  export JUGGLER_N_EVENTS=100
+fi
+
+
+export JUGGLER_FILE_NAME_TAG="far_forward_protons"
+export JUGGLER_GEN_FILE="${JUGGLER_FILE_NAME_TAG}.hepmc"
+
+export JUGGLER_SIM_FILE="sim_${JUGGLER_FILE_NAME_TAG}.root"
+export JUGGLER_REC_FILE="rec_${JUGGLER_FILE_NAME_TAG}.root"
+
+echo "JUGGLER_N_EVENTS = ${JUGGLER_N_EVENTS}"
+echo "JUGGLER_DETECTOR = ${JUGGLER_DETECTOR}"
+
+
+if [[ -z "${REC_ONLY}" && -z "${ANALYSIS_ONLY}" ]] ;
+then
+
+  ## generate the input events
+  root -b -q "benchmarks/B0/scripts/gen_far_forward_protons.cxx(${JUGGLER_N_EVENTS}, \"${JUGGLER_FILE_NAME_TAG}.hepmc\")"
+  if [[ "$?" -ne "0" ]] ; then
+    echo "ERROR running script"
+    exit 1
+  fi
+
+  echo "Running geant4 simulation"
+  ## run geant4 simulations
+  npsim --runType batch \
+    --part.minimalKineticEnergy 1000*GeV  \
+    -v WARNING \
+    --numberOfEvents ${JUGGLER_N_EVENTS} \
+    --compactFile ${DETECTOR_PATH}/${JUGGLER_DETECTOR}.xml \
+    --inputFiles  ${JUGGLER_FILE_NAME_TAG}.hepmc \
+    --outputFile  ${JUGGLER_SIM_FILE}
+  if [[ "$?" -ne "0" ]] ; then
+    echo "ERROR running script"
+    exit 1
+  fi
+fi
+
+rootls -t ${JUGGLER_SIM_FILE}
+
+if [[ -z "${ANALYSIS_ONLY}" ]] ;
+then
+  # Need to figure out how to pass file name to juggler from the commandline
+  xenv -x ${JUGGLER_INSTALL_PREFIX}/Juggler.xenv gaudirun.py benchmarks/B0/options/B0_tracker_reconstruction.py
+  if [[ "$?" -ne "0" ]] ; then
+    echo "ERROR running juggler"
+    exit 1
+  fi
+fi
+
+mkdir -p results/B0
+
+root -b -q "benchmarks/B0/scripts/rec_far_forward_protons.cxx(\"${JUGGLER_REC_FILE}\")"
+if [[ "$?" -ne "0" ]] ; then
+  echo "ERROR running root script"
+  exit 1
+fi
+
+root -b -q "benchmarks/B0/scripts/hits_far_forward_protons.cxx(\"${JUGGLER_SIM_FILE}\")"
+if [[ "$?" -ne "0" ]] ; then
+  echo "ERROR running root script"
+  exit 1
+fi
+
+root_filesize=$(stat --format=%s "${JUGGLER_REC_FILE}")
+if [[ "${JUGGLER_N_EVENTS}" -lt "500" ]] ; then 
+  # file must be less than 10 MB to upload
+  if [[ "${root_filesize}" -lt "10000000" ]] ; then 
+    cp ${JUGGLER_REC_FILE} results/.
+  fi
+fi
+
diff --git a/benchmarks/B0/options/B0_tracker_reconstruction.py b/benchmarks/B0/options/B0_tracker_reconstruction.py
new file mode 100644
index 00000000..5db97e3b
--- /dev/null
+++ b/benchmarks/B0/options/B0_tracker_reconstruction.py
@@ -0,0 +1,103 @@
+from Gaudi.Configuration import *
+
+from Configurables import ApplicationMgr, EICDataSvc, PodioOutput, GeoSvc
+from GaudiKernel.SystemOfUnits import MeV, GeV, mm, cm, mrad
+
+detector_name = str(os.environ.get("JUGGLER_DETECTOR", "athena"))
+detector_path = str(os.environ.get("DETECTOR_PATH", "."))
+compact_path = str(os.environ.get("JUGGLER_COMPACT_PATH", "{}.xml".format(os.path.join(detector_path, detector_name))))
+
+# todo add checks
+input_sims = [f.strip() for f in str.split(os.environ["JUGGLER_SIM_FILE"], ",") if f.strip()]
+output_rec = str(os.environ["JUGGLER_REC_FILE"])
+n_events = int(os.environ["JUGGLER_N_EVENTS"])
+
+geo_service = GeoSvc("GeoSvc", detectors=[compact_path], OutputLevel=WARNING)
+podioevent = EICDataSvc("EventDataSvc", inputs=input_sims, OutputLevel=WARNING)
+
+from Configurables import PodioInput
+from Configurables import Jug__Digi__UFSDTrackerDigi as TrackerDigi
+from Configurables import Jug__Reco__TrackerHitReconstruction as TrackerReco
+
+from Configurables import Jug__Reco__TrackerSourceLinker as TrackerSourceLinker
+from Configurables import Jug__Reco__TrackerSourcesLinker as TrackerSourcesLinker
+#from Configurables import Jug__Reco__TrackingHitsSourceLinker as TrackingHitsSourceLinker
+from Configurables import Jug__Reco__TrackParamTruthInit as TrackParamTruthInit
+
+from Configurables import Jug__Reco__TrackFindingAlgorithm as TrackFindingAlgorithm
+from Configurables import Jug__Reco__ParticlesFromTrackFit as ParticlesFromTrackFit
+from Configurables import Jug__Base__InputCopier_dd4pod__Geant4ParticleCollection_dd4pod__Geant4ParticleCollection_ as MCCopier
+
+
+sim_colls = [
+    "mcparticles",
+    "B0TrackerHits"
+]
+podin = PodioInput("PodioReader", collections=sim_colls)
+podout = PodioOutput("out", filename=output_rec)
+
+## copiers to get around input --> output copy bug. Note the "2" appended to the output collection.
+mccopier = MCCopier("MCCopier",
+        inputCollection="mcparticles",
+        outputCollection="mcparticles2")
+
+trk_b0_digi = TrackerDigi("trk_b0_digi",
+        inputHitCollection="B0TrackerHits",
+        outputHitCollection="B0TrackerRawHits",
+        timeResolution=8)
+
+trk_b0_reco = TrackerReco("trk_b_reco",
+        inputHitCollection = trk_b0_digi.outputHitCollection,
+        outputHitCollection="B0TrackerRecHits")
+
+sourcelinker = TrackerSourcesLinker("trk_srcslnkr",
+        inputHitCollections=["B0TrackerRecHits"],
+        outputSourceLinks="B0TrackerSourceLinks",
+        outputMeasurements="B0TrackerMeasurements",
+        OutputLevel=INFO)
+
+## Track param init
+truth_trk_init = TrackParamTruthInit("truth_trk_init",
+        inputMCParticles="mcparticles",
+        outputInitialTrackParameters="InitTrackParams",
+        OutputLevel=INFO)
+
+# Tracking algorithms
+trk_find_alg = TrackFindingAlgorithm("trk_find_alg",
+        inputSourceLinks = sourcelinker.outputSourceLinks,
+        inputMeasurements = sourcelinker.outputMeasurements,
+        inputInitialTrackParameters= truth_trk_init.outputInitialTrackParameters,
+        outputTrajectories="trajectories",
+        OutputLevel=INFO)
+
+parts_from_fit = ParticlesFromTrackFit("parts_from_fit",
+        inputTrajectories=trk_find_alg.outputTrajectories,
+        outputParticles="ReconstructedParticles",
+        outputTrackParameters="outputTrackParameters",
+        OutputLevel=INFO)
+
+podout.outputCommands = [
+    "keep *",
+    "drop InitTrackParams",
+    "drop trajectories",
+    "drop outputSourceLinks",
+    "drop outputInitialTrackParameters",
+    "drop mcparticles",
+]
+
+ApplicationMgr(
+    TopAlg = [podin, mccopier,
+              trk_b0_digi,
+              trk_b0_reco,
+              sourcelinker,
+              truth_trk_init,
+              trk_find_alg,
+              parts_from_fit,
+              podout
+              ],
+    EvtSel = 'NONE',
+    EvtMax   = n_events,
+    ExtSvc = [podioevent, geo_service],
+    OutputLevel=WARNING
+ )
+
diff --git a/benchmarks/B0/scripts/gen_far_forward_protons.cxx b/benchmarks/B0/scripts/gen_far_forward_protons.cxx
new file mode 100644
index 00000000..33d5f2e4
--- /dev/null
+++ b/benchmarks/B0/scripts/gen_far_forward_protons.cxx
@@ -0,0 +1,83 @@
+#include "HepMC3/GenEvent.h"
+#include "HepMC3/ReaderAscii.h"
+#include "HepMC3/WriterAscii.h"
+#include "HepMC3/Print.h"
+
+#include <iostream>
+#include<random>
+#include<cmath>
+#include <math.h>
+#include <TMath.h>
+
+using namespace HepMC3;
+
+/** Generate protons in the far forward region.
+ *  This is for testing detectors in the B0 tracker.
+ */
+void gen_far_forward_protons(int n_events = 100, 
+                     const char* out_fname = "far_forward_protons.hepmc")
+{
+  double cos_theta_min = std::cos(0.3*(M_PI/180.0));
+  double cos_theta_max = std::cos(2.0*(M_PI/180.0));
+
+  WriterAscii hepmc_output(out_fname);
+  int events_parsed = 0;
+  GenEvent evt(Units::GEV, Units::MM);
+
+  // Random number generator
+  TRandom *r1 = new TRandom();
+
+  for (events_parsed = 0; events_parsed < n_events; events_parsed++) {
+    // FourVector(px,py,pz,e,pdgid,status)
+    // type 4 is beam
+    // pdgid 11 - proton
+    // pdgid 111 - pi0
+    // pdgid 2212 - proton
+    GenParticlePtr p1 =
+        std::make_shared<GenParticle>(FourVector(0.0, 0.0, 10.0, 10.0), 11, 4);
+    GenParticlePtr p2 = std::make_shared<GenParticle>(
+        FourVector(0.0, 0.0, 0.0, 0.938), 2212, 4);
+
+    // Define momentum
+    Double_t p     = r1->Uniform(1.0, 10.0);
+    Double_t phi   = r1->Uniform(0.0, 2.0 * M_PI);
+    Double_t costh = r1->Uniform(cos_theta_min, cos_theta_max);
+    Double_t th    = std::acos(costh);
+    Double_t px    = p * std::cos(phi) * std::sin(th);
+    Double_t py    = p * std::sin(phi) * std::sin(th);
+    Double_t pz    = p * std::cos(th);
+    // Generates random vectors, uniformly distributed over the surface of a
+    // sphere of given radius, in this case momentum.
+    // r1->Sphere(px, py, pz, p);
+
+    //std::cout << std::sqrt(px*px + py*py + pz*pz) - p << " is zero? \n";
+
+    // type 1 is final state
+    // pdgid 11 - proton 0.510 MeV/c^2
+    GenParticlePtr p3 = std::make_shared<GenParticle>(
+        FourVector(
+            px, py, pz,
+            sqrt(p*p + (0.000511 * 0.000511))),
+        11, 1);
+
+    GenVertexPtr v1 = std::make_shared<GenVertex>();
+    v1->add_particle_in(p1);
+    v1->add_particle_in(p2);
+
+    v1->add_particle_out(p3);
+    evt.add_vertex(v1);
+
+    if (events_parsed == 0) {
+      std::cout << "First event: " << std::endl;
+      Print::listing(evt);
+    }
+
+    hepmc_output.write_event(evt);
+    if (events_parsed % 10000 == 0) {
+      std::cout << "Event: " << events_parsed << std::endl;
+    }
+    evt.clear();
+  }
+  hepmc_output.close();
+  std::cout << "Events parsed and written: " << events_parsed << std::endl;
+}
diff --git a/benchmarks/B0/scripts/hits_far_forward_protons.cxx b/benchmarks/B0/scripts/hits_far_forward_protons.cxx
new file mode 100644
index 00000000..aa877e88
--- /dev/null
+++ b/benchmarks/B0/scripts/hits_far_forward_protons.cxx
@@ -0,0 +1,190 @@
+#include "ROOT/RDataFrame.hxx"
+#include "TCanvas.h"
+#include "TLegend.h"
+#include "TH1D.h"
+#include "TProfile.h"
+
+#include <iostream>
+
+R__LOAD_LIBRARY(libeicd.so)
+R__LOAD_LIBRARY(libDD4pod.so)
+#include "dd4pod/TrackerHitCollection.h"
+#include "dd4pod/TrackerHitData.h"
+#include "dd4pod/Geant4ParticleCollection.h"
+#include "eicd/TrackParametersCollection.h"
+#include "eicd/ClusterCollection.h"
+#include "eicd/ClusterData.h"
+#include "eicd/TrackerHitCollection.h"
+
+using ROOT::RDataFrame;
+using namespace ROOT::VecOps;
+
+auto p_track = [](std::vector<eic::TrackParametersData> const& in) {
+  std::vector<double> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+    result.push_back(std::abs(1.0/(in[i].qOverP)));
+  }
+  return result;
+};
+
+
+std::vector<float> pt (std::vector<dd4pod::Geant4ParticleData> const& in){
+  std::vector<float> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+    result.push_back(std::sqrt(in[i].psx * in[i].psx + in[i].psy * in[i].psy));
+  }
+  return result;
+}
+
+auto momentum = [](std::vector<ROOT::Math::PxPyPzMVector> const& in) {
+  std::vector<double> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+   result.push_back(in[i].E());
+  }
+  return result;
+};
+auto theta = [](std::vector<ROOT::Math::PxPyPzMVector> const& in) {
+  std::vector<double> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+   result.push_back(in[i].Theta()*180/M_PI);
+  }
+  return result;
+};
+auto fourvec = [](ROOT::VecOps::RVec<dd4pod::Geant4ParticleData> const& in) {
+  std::vector<ROOT::Math::PxPyPzMVector> result;
+  ROOT::Math::PxPyPzMVector lv;
+  for (size_t i = 0; i < in.size(); ++i) {
+    lv.SetCoordinates(in[i].psx, in[i].psy, in[i].psz, in[i].mass);
+    result.push_back(lv);
+  }
+  return result;
+};
+
+auto delta_p = [](const std::vector<double>& tracks, const std::vector<double>& thrown) {
+  std::vector<double> res;
+  for (const auto& p1 : thrown) {
+    for (const auto& p2 : tracks) {
+      res.push_back(p1 - p2);
+    }
+  }
+  return res;
+};
+
+auto delta_p_over_p = [](const std::vector<double>& tracks, const std::vector<double>& thrown) {
+  std::vector<double> res;
+  for (const auto& p1 : thrown) {
+    for (const auto& p2 : tracks) {
+      res.push_back((p1 - p2)/p1);
+    }
+  }
+  return res;
+};
+
+int hits_far_forward_protons(const char* fname = "sim_far_forward_protons.root")
+{
+
+  ROOT::EnableImplicitMT();
+  ROOT::RDataFrame df("events", fname);
+
+  auto df0 = df.Define("isThrown", "mcparticles.genStatus == 1")
+                 .Define("thrownParticles", "mcparticles[isThrown]")
+                 .Define("thrownP", fourvec, {"thrownParticles"})
+                 .Define("p_thrown", momentum, {"thrownP"})
+                 .Define("theta_thrown", theta, {"thrownP"})
+                 .Define("theta0", "theta_thrown[0]")
+                 //.Define("nTracks", "outputTrackParameters.size()")
+                 //.Define("p_track", p_track, {"outputTrackParameters"})
+                 //.Define("p_track1", p_track, {"outputTrackParameters1"})
+                 //.Define("p_track2", p_track, {"outputTrackParameters2"})
+                 //.Define("delta_p0",delta_p, {"p_track", "p_thrown"})
+                 //.Define("delta_p1",delta_p, {"p_track1", "p_thrown"})
+                 ////.Define("delta_p2",delta_p, {"p_track2", "p_thrown"})
+                 //.Define("delta_p_over_p0",delta_p_over_p, {"p_track", "p_thrown"})
+                 //.Define("delta_p_over_p1",delta_p_over_p, {"p_track1", "p_thrown"})
+                 //.Define("delta_p_over_p2",delta_p_over_p, {"p_track2", "p_thrown"})
+                 //.Define("N_VtxBarrelHits",[](std::vector<eic::TrackerHitData> hits) { return hits.size();},{"VertexBarrelRecHits"})
+                 .Define("N_BarrelHits", [](std::vector<dd4pod::TrackerHitData> hits) { return hits.size();}, {"TrackerBarrelHits"})
+                 .Define("N_EndcapHits", [](std::vector<dd4pod::TrackerHitData> hits) { return hits.size();}, {"TrackerEndcapHits"})
+                 ;
+
+  auto hBarrel_x_vs_y = df0.Histo2D({"hBarrel_x_vs_y", "; x ; y ",   100, -900, 900,100, -900, 900 }, "TrackerBarrelHits.position.x", "TrackerBarrelHits.position.y");
+
+  auto hBarrel_N_vs_theta = df0.Histo1D({"hBarrel_N_vs_theta", "; #theta [deg.]",   20, 0, 180 }, "theta0", "N_BarrelHits");
+  auto hEndcap_N_vs_theta = df0.Histo1D({"hEndcap_N_vs_theta", "; #theta [deg.]",   20, 0, 180 }, "theta0", "N_EndcapHits");
+  //auto hVtxBarrel_N_vs_theta = df0.Histo1D({"hVtxBarrel_N_vs_theta", "; #theta [deg.]", 20, 0, 180 }, "theta0", "N_VtxBarrelHits");
+
+  auto hBarrel_Nhits  = df0.Histo1D({"hBarrel_Nhits", "; #theta [deg.]",   20, 0, 20 }, "N_BarrelHits");
+  auto hEndcap_Nhits  = df0.Histo1D({"hEndcap_Nhits", "; #theta [deg.]",   20, 0, 20 }, "N_EndcapHits");
+  //auto hVtxBarrel_Nhits = df0.Histo1D({"hVtxBarrel_Nhits", "; #theta [deg.]", 20, 0, 20 },  "N_VtxBarrelHits");
+
+  auto hBarrel_Ntheta = df0.Histo1D({"hBarrel_Ntheta", "; #theta [deg.]",   20, 0, 180 }, "theta0");
+  auto hEndcap_Ntheta = df0.Histo1D({"hEndcap_Ntheta", "; #theta [deg.]",   20, 0, 180 }, "theta0");
+  //auto hVtxBarrel_Ntheta = df0.Histo1D({"hVtxBarrel_Ntheta", "; #theta [deg.]", 20, 0, 180 }, "theta0");
+
+  auto c = new TCanvas();
+  auto hs = new THStack("n_hits","; #theta  ");
+  auto h1 = (TH1D*) hBarrel_N_vs_theta->Clone();
+  auto h2 = (TH1D*) hBarrel_Ntheta->Clone();
+  h1->Divide(h2);
+  hs->Add(h1);
+  h1 = (TH1D*) hEndcap_N_vs_theta->Clone();
+  h2 = (TH1D*) hEndcap_Ntheta->Clone();
+  h1->Divide(h2);
+  h1->SetLineColor(2);
+  hs->Add(h1);
+  //h1 = (TH1D*) hVtxBarrel_vs_theta->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  hs->Draw("nostack, hist");
+  c->BuildLegend();
+  c->SaveAs("results/B0/hits_far_forward_protons_n_hits_vs_theta.png");
+  c->SaveAs("results/B0/hits_far_forward_protons_n_hits_vs_theta.pdf");
+
+  c  = new TCanvas();
+  hs = new THStack("theta","; #theta  ");
+  h1 = (TH1D*) hBarrel_N_vs_theta->Clone();
+  h2 = (TH1D*) hBarrel_Ntheta->Clone();
+  //h1->Divide(h2);
+  hs->Add(h2);
+  h1 = (TH1D*) hEndcap_N_vs_theta->Clone();
+  h2 = (TH1D*) hEndcap_Ntheta->Clone();
+  //h1->Divide(h2);
+  h1->SetLineColor(2);
+  h2->SetLineColor(2);
+  hs->Add(h2);
+  //h1 = (TH1D*) hVtxBarrel_vs_theta->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  hs->Draw("nostack hist");
+  c->BuildLegend();
+  c->SaveAs("results/B0/hits_far_forward_protons_theta.png");
+  c->SaveAs("results/B0/hits_far_forward_protons_theta.pdf");
+
+  c  = new TCanvas();
+  hs = new THStack("hits","; hits  ");
+  h1 = (TH1D*) hBarrel_Nhits->Clone();
+  hs->Add(h1);
+  h1 = (TH1D*) hEndcap_Nhits->Clone();
+  h1->SetLineColor(2);
+  h2->SetLineColor(2);
+  hs->Add(h2);
+  //h1 = (TH1D*) hVtxBarrel_Nhits->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  //hs->Draw("nostack hist");
+  c->BuildLegend();
+  c->SaveAs("results/B0/hits_far_forward_protons_nhits.png");
+  c->SaveAs("results/B0/hits_far_forward_protons_nhits.pdf");
+
+  c = new TCanvas();
+  hBarrel_x_vs_y->DrawCopy("colz");
+  c->SaveAs("results/B0/hits_far_forward_protons_xy.png");
+  c->SaveAs("results/B0/hits_far_forward_protons_xy.pdf");
+  return 0;
+}
diff --git a/benchmarks/B0/scripts/rec_far_forward_protons.cxx b/benchmarks/B0/scripts/rec_far_forward_protons.cxx
new file mode 100644
index 00000000..4cd5d321
--- /dev/null
+++ b/benchmarks/B0/scripts/rec_far_forward_protons.cxx
@@ -0,0 +1,237 @@
+#include "ROOT/RDataFrame.hxx"
+#include "TCanvas.h"
+#include "TLegend.h"
+#include "TH1D.h"
+#include "TProfile.h"
+
+#include <iostream>
+
+R__LOAD_LIBRARY(libeicd.so)
+R__LOAD_LIBRARY(libDD4pod.so)
+#include "dd4pod/Geant4ParticleCollection.h"
+#include "eicd/TrackParametersCollection.h"
+#include "eicd/ClusterCollection.h"
+#include "eicd/ClusterData.h"
+#include "eicd/TrackerHitCollection.h"
+
+using ROOT::RDataFrame;
+using namespace ROOT::VecOps;
+
+auto p_track = [](std::vector<eic::TrackParametersData> const& in) {
+  std::vector<double> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+    result.push_back(std::abs(1.0/(in[i].qOverP)));
+  }
+  return result;
+};
+
+
+std::vector<float> pt (std::vector<dd4pod::Geant4ParticleData> const& in){
+  std::vector<float> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+    result.push_back(std::sqrt(in[i].psx * in[i].psx + in[i].psy * in[i].psy));
+  }
+  return result;
+}
+
+auto momentum = [](std::vector<ROOT::Math::PxPyPzMVector> const& in) {
+  std::vector<double> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+   result.push_back(in[i].P());
+  }
+  return result;
+};
+auto theta = [](std::vector<ROOT::Math::PxPyPzMVector> const& in) {
+  std::vector<double> result;
+  for (size_t i = 0; i < in.size(); ++i) {
+   result.push_back(in[i].Theta()*180/M_PI);
+  }
+  return result;
+};
+auto fourvec = [](ROOT::VecOps::RVec<dd4pod::Geant4ParticleData> const& in) {
+  std::vector<ROOT::Math::PxPyPzMVector> result;
+  ROOT::Math::PxPyPzMVector lv;
+  for (size_t i = 0; i < in.size(); ++i) {
+    lv.SetCoordinates(in[i].psx, in[i].psy, in[i].psz, in[i].mass);
+    result.push_back(lv);
+  }
+  return result;
+};
+
+auto delta_p = [](const std::vector<double>& tracks, const std::vector<double>& thrown) {
+  std::vector<double> res;
+  for (const auto& p1 : thrown) {
+    for (const auto& p2 : tracks) {
+      res.push_back(p1 - p2);
+    }
+  }
+  return res;
+};
+
+auto delta_p_over_p = [](const std::vector<double>& tracks, const std::vector<double>& thrown) {
+  std::vector<double> res;
+  for (const auto& p1 : thrown) {
+    for (const auto& p2 : tracks) {
+      res.push_back((p1 - p2)/p1);
+    }
+  }
+  return res;
+};
+
+int rec_far_forward_protons(const char* fname = "topside/rec_far_forward_protons.root")
+{
+
+  ROOT::EnableImplicitMT();
+  ROOT::RDataFrame df("events", fname);
+
+  auto df0 = df.Define("isThrown", "mcparticles2.genStatus == 1")
+                 .Define("thrownParticles", "mcparticles2[isThrown]")
+                 .Define("thrownP", fourvec, {"thrownParticles"})
+                 .Define("p_thrown", momentum, {"thrownP"})
+                 .Define("theta_thrown", theta, {"thrownP"})
+                 .Define("theta0", "theta_thrown[0]")
+                 .Define("nTracks", "outputTrackParameters.size()")
+                 .Define("p_track", p_track, {"outputTrackParameters"})
+                 //.Define("p_track1", p_track, {"outputTrackParameters1"})
+                 //.Define("p_track2", p_track, {"outputTrackParameters2"})
+                 .Define("delta_p0",delta_p, {"p_track", "p_thrown"})
+                 //.Define("delta_p1",delta_p, {"p_track1", "p_thrown"})
+                 //.Define("delta_p2",delta_p, {"p_track2", "p_thrown"})
+                 .Define("delta_p_over_p0",delta_p_over_p, {"p_track", "p_thrown"})
+                 //.Define("delta_p_over_p1",delta_p_over_p, {"p_track1", "p_thrown"})
+                 //.Define("delta_p_over_p2",delta_p_over_p, {"p_track2", "p_thrown"})
+                 //.Define("N_VtxBarrelHits",[](std::vector<eic::TrackerHitData> hits) { return hits.size();},{"VertexBarrelRecHits"})
+                 .Define("N_B0TrackerHits", [](std::vector<eic::TrackerHitData> hits) { return hits.size();}, {"B0TrackerRecHits"})
+                 ;
+
+  auto h_nTracks = df0.Histo1D({"h_nTracks", "; N tracks ", 10, 0, 10}, "nTracks");
+  auto h_pTracks = df0.Histo1D({"h_pTracks", "; GeV/c ", 100, 0, 10}, "p_track");
+
+  auto h_delta_p0  = df0.Histo1D({"h_delta_p0", "Truth Track Init; GeV/c ",  100, -10, 10}, "delta_p0");
+  //auto h_delta_p1 = df0.Histo1D({"h_delta_p1", "Ecal Cluster Init; GeV/c ", 100, -10, 10}, "delta_p1");
+  //auto h_delta_p2 = df0.Histo1D({"h_delta_p2", "Ecal Cluster, innner vtx hit Init; GeV/c ", 100, -10, 10}, "delta_p2");
+
+  auto h_delta_p0_over_p = df0.Histo1D({"h_delta_p0_over_p",  "Truth Track Init; delta p/p ",  100, -0.1, 0.1}, "delta_p_over_p0");
+  //auto h_delta_p1_over_p = df0.Histo1D({"h_delta_p1_over_p", "Ecal Cluster Init; delta p/p ", 100, -0.1, 0.1}, "delta_p_over_p1");
+  //auto h_delta_p2_over_p = df0.Histo1D({"h_delta_p2_over_p", "Ecal Cluster, innner vtx hit Init; delta p/p ", 100, -0.1, 0.1}, "delta_p_over_p2");
+
+  auto hB0Tracker_N_vs_theta = df0.Histo1D({"hB0Tracker_N_vs_theta", "; #theta [deg.]",   20, 0, 180 }, "theta0", "N_B0TrackerHits");
+  //auto hSiEndcap_N_vs_theta = df0.Histo1D({"hSiEndcap_N_vs_theta", "; #theta [deg.]",   20, 0, 180 }, "theta0", "N_SiEndcapHits");
+  //auto hVtxBarrel_N_vs_theta = df0.Histo1D({"hVtxBarrel_N_vs_theta", "; #theta [deg.]", 20, 0, 180 }, "theta0", "N_VtxBarrelHits");
+
+  auto hB0Tracker_Nhits  = df0.Histo1D({"hB0Tracker_Nhits", "; #theta [deg.]",   20, 0, 20 }, "N_B0TrackerHits");
+  //auto hSiEndcap_Nhits  = df0.Histo1D({"hSiEndcap_Nhits", "; #theta [deg.]",   20, 0, 20 }, "N_SiEndcapHits");
+  //auto hVtxBarrel_Nhits = df0.Histo1D({"hVtxBarrel_Nhits", "; #theta [deg.]", 20, 0, 20 },  "N_VtxBarrelHits");
+
+  auto hB0Tracker_Ntheta = df0.Histo1D({"hB0Tracker_Ntheta", "; #theta [deg.]",   20, 0, 180 }, "theta0");
+  //auto hSiEndcap_Ntheta = df0.Histo1D({"hSiEndcap_Ntheta", "; #theta [deg.]",   20, 0, 180 }, "theta0");
+  //auto hVtxBarrel_Ntheta = df0.Histo1D({"hVtxBarrel_Ntheta", "; #theta [deg.]", 20, 0, 180 }, "theta0");
+
+  auto c = new TCanvas();
+
+  h_nTracks->DrawCopy();
+  c->SaveAs("results/B0/rec_far_forward_protons_nTracks.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_nTracks.pdf");
+
+  h_pTracks->DrawCopy();
+  c->SaveAs("results/B0/rec_far_forward_protons_pTracks.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_pTracks.pdf");
+
+  c = new TCanvas();
+  THStack * hs = new THStack("hs_delta_p","; GeV/c ");
+  TH1D* h1 = (TH1D*) h_delta_p0->Clone();
+  hs->Add(h1);
+  //h1 = (TH1D*) h_delta_p1->Clone();
+  //h1->SetLineColor(2);
+  //hs->Add(h1);
+  //h1 = (TH1D*) h_delta_p2->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  hs->Draw("nostack");
+  c->BuildLegend();
+  c->SaveAs("results/B0/rec_far_forward_protons_delta_p.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_delta_p.pdf");
+
+  c  = new TCanvas();
+  hs = new THStack("hs_delta_p_over_p","; delta p/p ");
+  h1 = (TH1D*) h_delta_p0_over_p->Clone();
+  hs->Add(h1);
+  //h1 = (TH1D*) h_delta_p1_over_p->Clone();
+  //h1->SetLineColor(2);
+  //hs->Add(h1);
+  //h1 = (TH1D*) h_delta_p2_over_p->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  hs->Draw("nostack");
+  c->BuildLegend();
+  c->SaveAs("results/B0/rec_far_forward_protons_delta_p_over_p.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_delta_p_over_p.pdf");
+
+  c  = new TCanvas();
+  hs = new THStack("n_hits","; #theta  ");
+  h1 = (TH1D*) hB0Tracker_N_vs_theta->Clone();
+  auto h2 = (TH1D*) hB0Tracker_Ntheta->Clone();
+  h1->Divide(h2);
+  hs->Add(h1);
+  //h1 = (TH1D*) hSiEndcap_N_vs_theta->Clone();
+  //h2 = (TH1D*) hSiEndcap_Ntheta->Clone();
+  //h1->Divide(h2);
+  //h1->SetLineColor(2);
+  //hs->Add(h1);
+  //h1 = (TH1D*) hVtxBarrel_vs_theta->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  hs->Draw("nostack, hist");
+  c->BuildLegend();
+  c->SaveAs("results/B0/rec_far_forward_protons_n_hits_vs_theta.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_n_hits_vs_theta.pdf");
+
+  c  = new TCanvas();
+  hs = new THStack("theta","; #theta  ");
+  h1 = (TH1D*) hB0Tracker_N_vs_theta->Clone();
+  h2 = (TH1D*) hB0Tracker_Ntheta->Clone();
+  //h1->Divide(h2);
+  hs->Add(h2);
+  //h1 = (TH1D*) hSiEndcap_N_vs_theta->Clone();
+  //h2 = (TH1D*) hSiEndcap_Ntheta->Clone();
+  //h1->Divide(h2);
+  //h1->SetLineColor(2);
+  //h2->SetLineColor(2);
+  //hs->Add(h2);
+  //h1 = (TH1D*) hVtxBarrel_vs_theta->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  hs->Draw("nostack hist");
+  c->BuildLegend();
+  c->SaveAs("results/B0/rec_far_forward_protons_theta.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_theta.pdf");
+
+  c  = new TCanvas();
+  hs = new THStack("hits","; hits  ");
+  h1 = (TH1D*) hB0Tracker_Nhits->Clone();
+  hs->Add(h1);
+  //h1 = (TH1D*) hSiEndcap_Nhits->Clone();
+  //h1->SetLineColor(2);
+  //h2->SetLineColor(2);
+  //hs->Add(h2);
+  //h1 = (TH1D*) hVtxBarrel_Nhits->Clone();
+  //h1->SetLineColor(4);
+  //h1->SetFillStyle(3001);
+  //h1->SetFillColor(4);
+  //hs->Add(h1);
+  //hs->Draw("nostack hist");
+  c->BuildLegend();
+  c->SaveAs("results/B0/rec_far_forward_protons_nhits.png");
+  c->SaveAs("results/B0/rec_far_forward_protons_nhits.pdf");
+
+
+  return 0;
+}
-- 
GitLab