FairShip
Loading...
Searching...
No Matches
split_weight_uncertainties_rdf.py
Go to the documentation of this file.
1#!/usr/bin/env python
2# SPDX-License-Identifier: LGPL-3.0-or-later
3# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
4
5"""Momentum spectrum at a scoring plane with event-level uncertainties, using RDataFrame.
6
7RDataFrame version of split_weight_uncertainties.py, with the same options,
8table and output. The selection runs as compiled RDataFrame columns, and the
9C++ EventHistogram accumulates with one instance per processing slot, merged
10with Add() at the end. That makes it safe to run multithreaded (-j). The
11bootstrap replicas depend only on run and event number, so the result does not
12depend on the number of threads or the order of events.
13
14 python examples/split_weight_uncertainties_rdf.py -f out/*/pythia8_*.root -o spectrum.root -j 8
15"""
16
17import numpy as np
18import ROOT
19from event_histogram import generated_events
20from split_weight_uncertainties import log_edges, make_parser, print_table
21
22ROOT.gSystem.Load("libShipData")
23ROOT.gInterpreter.Declare(
24 """
25#include "EventHistogram.h"
26
27// EventHistogram is not thread safe, so every slot fills its own.
28void FillEventHistograms(ROOT::RDF::RNode df, std::vector<EventHistogram*>& slots) {
29 df.ForeachSlot(
30 [&slots](unsigned slot, const ROOT::RVecD& p, const ROOT::RVecD& w, ULong64_t key) {
31 for (std::size_t i = 0; i < p.size(); ++i) slots[slot]->Fill(p[i], w[i]);
32 slots[slot]->EndEvent(key);
33 },
34 {"p", "w", "key"});
35}
36"""
37)
38
39
40def complete_element_class(df, column):
41 """Expressions on the elements of a vector column need their full class, but
42 the dictionaries only forward declare it. Looking the class up from Python
43 makes Cling parse its header."""
44 vector_class = ROOT.TClass.GetClass(df.GetColumnType(column))
45 if vector_class is None:
46 raise RuntimeError(f"no dictionary for the type of column {column}")
47 getattr(ROOT, vector_class.GetCollectionProxy().GetValueClass().GetName())
48
49
50def main():
51 ap = make_parser(__doc__.splitlines()[0])
52 ap.add_argument("-j", "--threads", type=int, default=1, help="threads, 0 for all cores")
53 args = ap.parse_args()
54 if args.threads != 1:
55 ROOT.EnableImplicitMT(args.threads)
56 edges = log_edges(args.bins)
57
58 def per_point(expr, mask=""):
59 """expr for each point v of the scoring plane, as an RVec. The lambda has a
60 return statement, so RDataFrame takes the string as a function body."""
61 return f"return Map({args.branch}, [&](const auto& v) {{ return {expr}; }}){mask};"
62
63 df = ROOT.RDataFrame("cbmsim", args.files)
64 for column in (args.branch, "MCTrack"):
65 complete_element_class(df, column)
66 df = (
67 df.Define("sel", per_point(f"{args.pdg} == 0 || std::abs(v.PdgCode()) == {args.pdg}"))
68 .Define("p", per_point("std::hypot(v.GetPx(), v.GetPy(), v.GetPz())", "[sel]"))
69 .Define("w", per_point("MCTrack[v.GetTrackID()].GetWeight()", "[sel]"))
70 .Define("key", "EventHistogram::MakeEventKey(MCEventHeader.fRunId, MCEventHeader.fEventId)")
71 )
72
73 title = f"{args.branch};p (GeV/c);per event"
74 slots = [
75 ROOT.EventHistogram(args.name, title, len(edges) - 1, edges, True, args.replicas) for _ in range(df.GetNSlots())
76 ]
77 pointers = ROOT.std.vector("EventHistogram*")(slots)
78 ROOT.FillEventHistograms(ROOT.RDF.AsRNode(df), pointers) # pyrefly: ignore[missing-attribute] # declared above
79 h = slots[0]
80 for other in slots[1:]:
81 h.Add(other)
82
83 n_generated = 0
84 for name in args.files:
85 f = ROOT.TFile.Open(name)
86 n_generated += generated_events(f)
87 f.Close()
88 h.AddEmptyEvents(n_generated - h.GetNEvents())
89
90 result, naive = h.MakeResult(), h.MakeNaive()
91 errors, naive_errors = np.sqrt(result.variances()), np.sqrt(naive.variances())
92 print_table(args, n_generated, edges, result.values(), errors, naive_errors, h.MakeNeff().values())
93
94 out = ROOT.TFile(args.output, "RECREATE")
95 h.Write(out)
96 out.Close()
97 print(f"written to {args.output}")
98
99
100if __name__ == "__main__":
101 main()