FairShip
Loading...
Searching...
No Matches
make_time_window.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"""Construct realistic time windows by overlaying MC truth events.
6
7Reads simulation output from a single ROOT file, computes the expected
8number of interactions per time window, and produces merged events where
9multiple sub-events are overlaid with Poisson-distributed multiplicity
10and uniform time offsets.
11
12Statistical choices (may be refined later):
13- All events are treated with equal selection probability.
14- Per-event MC weights are used only via their sum to determine the
15 Poisson mean (lambda) for the number of interactions per window.
16- Events are consumed consecutively from the input file rather than
17 sampled randomly. This is valid because:
18 * All events are statistically independent.
19 * The event pool is large enough that sampling without replacement
20 is equivalent to sampling with replacement.
21 * Consecutive reading avoids random-access I/O and caching overhead.
22
23Physics assumptions:
24- Event weight (on the first muon track, |pdg| == 13) gives the expected
25 number of occurrences of that interaction per spill. Weights already
26 scale to one full spill.
27- Time window duration: 1 microsecond
28- Uniform distribution of interactions in time
29- Number of interactions per window: Poisson distributed
30"""
31
32import argparse
33import hashlib
34import json
35import logging
36import os
37import sys
38
39import numpy as np
40import ROOT
41import shipunit as u
42
43logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
44log = logging.getLogger(__name__)
45
46# Physics parameters
47SPILL_DURATION = 1.0 * u.second # 1 second in ns
48TIME_WINDOW = 1.0 * u.microsecond # 1 microsecond in ns
49
50
52 """Return list of branch names containing 'Point'."""
53 return [b.GetName() for b in tree.GetListOfBranches() if "Point" in b.GetName()]
54
55
56def get_point_class_name(chain, branch_name):
57 """Get the C++ element class name for a Point branch."""
58 branch = chain.GetBranch(branch_name)
59 if not branch:
60 return None
61 class_name = branch.GetClassName()
62 if class_name.startswith("vector<"):
63 return class_name[7:-1]
64 return class_name
65
66
67def generate_cpp(point_class_names):
68 """Generate C++ build_time_windows() that reads events sequentially."""
69 includes = '#include "ShipMCTrack.h"\n'
70 for class_name in sorted(set(point_class_names.values())):
71 includes += f'#include "{class_name}.h"\n'
72
73 # Input branch address setup
74 branch_addr_setup = ""
75 for branch_name, class_name in point_class_names.items():
76 branch_addr_setup += f" std::vector<{class_name}>* in_{branch_name} = nullptr;\n"
77 branch_addr_setup += f' chain.SetBranchAddress("{branch_name}", &in_{branch_name});\n'
78
79 # Output vector declarations and branches
80 out_decl = ""
81 for branch_name, class_name in point_class_names.items():
82 out_decl += f" std::vector<{class_name}> out_{branch_name};\n"
83 out_decl += f' out_tree.Branch("{branch_name}", &out_{branch_name});\n'
84
85 # Clear output vectors per window
86 out_clear = ""
87 for branch_name in point_class_names:
88 out_clear += f" out_{branch_name}.clear();\n"
89
90 # Merge points from current entry
91 merge_points = ""
92 for branch_name in point_class_names:
93 merge_points += f"""
94 for (const auto& pt : *in_{branch_name}) {{
95 auto p = pt;
96 p.SetTime(pt.GetTime() + t_offset);
97 p.SetTrackID(pt.GetTrackID() + track_offset);
98 out_{branch_name}.push_back(std::move(p));
99 }}
100 total_points += in_{branch_name}->size();"""
101
102 return f"""{includes}
103
104int build_time_windows(
105 TChain& chain,
106 const std::vector<int>& window_sizes,
107 const std::vector<double>& all_time_offsets,
108 const char* output_path
109) {{
110 int n_windows = static_cast<int>(window_sizes.size());
111 int n_entries = static_cast<int>(chain.GetEntries());
112
113 // Set up input branch addresses
114 std::vector<ShipMCTrack>* in_tracks = nullptr;
115 chain.SetBranchAddress("MCTrack", &in_tracks);
116{branch_addr_setup}
117
118 // Set up output file and trees
119 TFile out_file(output_path, "RECREATE");
120 TTree out_tree("cbmsim", "Time window overlay");
121
122 std::vector<ShipMCTrack> out_tracks;
123 out_tree.Branch("MCTrack", &out_tracks);
124{out_decl}
125
126 TTree meta_tree("timewindow_meta", "Time window metadata");
127 int n_overlaid = 0, n_total_tracks = 0, n_total_points = 0;
128 meta_tree.Branch("n_overlaid", &n_overlaid);
129 meta_tree.Branch("n_total_tracks", &n_total_tracks);
130 meta_tree.Branch("n_total_points", &n_total_points);
131
132 std::vector<double> sub_time_offsets_v;
133 std::vector<int> sub_n_tracks_v, sub_original_indices_v;
134 meta_tree.Branch("sub_time_offsets", &sub_time_offsets_v);
135 meta_tree.Branch("sub_n_tracks", &sub_n_tracks_v);
136 meta_tree.Branch("sub_original_indices", &sub_original_indices_v);
137
138 // Build time windows by reading events sequentially
139 int cursor = 0;
140 int offset = 0;
141 for (int w = 0; w < n_windows; ++w) {{
142 int n_sub = window_sizes[w];
143
144 out_tracks.clear();
145{out_clear}
146 sub_time_offsets_v.clear();
147 sub_n_tracks_v.clear();
148 sub_original_indices_v.clear();
149
150 int track_offset = 0;
151 int total_points = 0;
152
153 for (int k = 0; k < n_sub; ++k) {{
154 int evt_idx = cursor % n_entries;
155 chain.GetEntry(evt_idx);
156 double t_offset = all_time_offsets[offset + k];
157
158 int nt = static_cast<int>(in_tracks->size());
159
160 // Merge MCTracks with time offset and re-indexing
161 for (int i = 0; i < nt; ++i) {{
162 auto t = (*in_tracks)[i];
163 t.SetStartT((*in_tracks)[i].GetStartT() + t_offset);
164 if ((*in_tracks)[i].GetMotherId() >= 0)
165 t.SetMotherId((*in_tracks)[i].GetMotherId() + track_offset);
166 t.SetTrackID(i + track_offset);
167 t.SetEventID(k);
168 out_tracks.push_back(std::move(t));
169 }}
170
171 // Merge Point branches{merge_points}
172
173 sub_time_offsets_v.push_back(t_offset);
174 sub_n_tracks_v.push_back(nt);
175 sub_original_indices_v.push_back(evt_idx);
176
177 track_offset += nt;
178 ++cursor;
179 }}
180
181 n_overlaid = n_sub;
182 n_total_tracks = static_cast<int>(out_tracks.size());
183 n_total_points = total_points;
184
185 out_tree.Fill();
186 meta_tree.Fill();
187
188 offset += n_sub;
189
190 if ((w + 1) % 10 == 0 || w == 0 || w == n_windows - 1) {{
191 std::cout << "\\rBuilding windows: " << (w + 1) << "/" << n_windows
192 << " (" << (100 * (w + 1) / n_windows) << "%)" << std::flush;
193 }}
194 }}
195 std::cout << std::endl;
196
197 out_file.Write();
198 out_file.Close();
199
200 std::cout << "Output written to " << output_path << std::endl;
201 std::cout << " cbmsim tree: " << n_windows << " time window events" << std::endl;
202 std::cout << " timewindow_meta tree: per-window metadata" << std::endl;
203
204 return 0;
205}}
206"""
207
208
209def main():
210 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
211 parser.add_argument("input_file", help="Input ROOT file")
212 parser.add_argument(
213 "-n", "--n-windows", type=int, default=100, help="Number of time windows to generate (default: 100)"
214 )
215 parser.add_argument(
216 "-o", "--output", default="time_windows.root", help="Output ROOT file (default: time_windows.root)"
217 )
218 parser.add_argument("--seed", type=int, default=None, help="Random seed for reproducibility")
219 args = parser.parse_args()
220
221 if args.seed is not None:
222 np.random.seed(args.seed)
223
224 log.info("=== Time Window Event Overlay ===")
225 log.info(f"Time window: {TIME_WINDOW / u.microsecond:.1f} us")
226 log.info(f"Output: {args.output}")
227 log.info(f"Number of time windows: {args.n_windows}")
228
229 # Open input
230 chain = ROOT.TChain("cbmsim")
231 chain.Add(args.input_file)
232
233 n_events = chain.GetEntries()
234 if n_events == 0:
235 log.error("No events found in input file")
236 sys.exit(1)
237 log.info(f"Input events: {n_events}")
238
239 # Discover Point branches
240 chain.GetEntry(0)
241 point_branches = discover_point_branches(chain)
242 log.info(f"Point branches: {point_branches}")
243
244 point_class_names = {}
245 for branch_name in point_branches:
246 class_name = get_point_class_name(chain, branch_name)
247 if class_name:
248 point_class_names[branch_name] = class_name
249 log.info(f" {branch_name} -> {class_name}")
250 else:
251 raise RuntimeError(
252 f"Could not determine Point class for branch '{branch_name}' in chain 'cbmsim'. Cannot proceed."
253 )
254
255 # --- Determine total interactions per spill (= sum of event weights) ---
256 # The per-spill weight lives on the first muon track (|pdg| == 13) in
257 # each event. Sum over all events to get the total interaction rate
258 # per spill. Cache the result to avoid recomputing (~minutes for large files).
259 real_path = os.path.realpath(args.input_file)
260 stat = os.stat(real_path)
261 cache_meta = {"path": real_path, "size": stat.st_size, "mtime": stat.st_mtime}
262 sumw_cache = hashlib.md5(real_path.encode()).hexdigest() + ".sumw"
263
264 sum_weights = None
265 try:
266 with open(sumw_cache) as f:
267 cached = json.load(f)
268 if (
269 cached.get("path") == cache_meta["path"]
270 and cached.get("size") == cache_meta["size"]
271 and cached.get("mtime") == cache_meta["mtime"]
272 ):
273 sum_weights = cached["sum_weights"]
274 log.info(f"Sum of weights (cached): {sum_weights:.6g}")
275 else:
276 log.info("Cache stale (file metadata changed), recomputing...")
277 except (FileNotFoundError, ValueError, KeyError):
278 pass
279
280 if sum_weights is None:
281 log.info("Computing sum of weights (first muon per event)...")
282 weight_chain = ROOT.TChain("cbmsim")
283 weight_chain.Add(args.input_file)
284 weight_chain.SetBranchStatus("*", 0)
285 weight_chain.SetBranchStatus("MCTrack*", 1)
286 sum_weights = 0.0
287 for i in range(n_events):
288 weight_chain.GetEntry(i)
289 for track in weight_chain.MCTrack:
290 if abs(track.GetPdgCode()) == 13:
291 sum_weights += track.GetWeight()
292 break
293 if (i + 1) % 1000000 == 0:
294 log.info(f" {i + 1}/{n_events} events processed...")
295 with open(sumw_cache, "w") as f:
296 json.dump({**cache_meta, "sum_weights": sum_weights}, f)
297 log.info(f"Sum of weights: {sum_weights:.6g} (saved to {sumw_cache})")
298
299 if sum_weights <= 0:
300 log.error("Sum of weights is zero or negative")
301 sys.exit(1)
302
303 # Compute Poisson mean (lambda) for interactions per time window.
304 # sum_weights = total interactions per spill (weights scale to one spill).
305 # Fraction of spill in one time window gives the per-window expectation:
306 lam = sum_weights * (TIME_WINDOW / SPILL_DURATION)
307
308 log.info(f"Expected interactions per window (lambda): {lam:.4f}")
309
310 # --- Pre-generate window sizes and time offsets ---
311 window_sizes_np = np.random.poisson(lam, size=args.n_windows).astype(np.int32)
312 total_events_needed = int(window_sizes_np.sum())
313 log.info(f"Total events to consume: {total_events_needed}")
314
315 if total_events_needed > n_events:
316 log.warning(
317 f"Need {total_events_needed} events but only {n_events} available; "
318 f"will wrap around (events reused after full pass)."
319 )
320
321 # Uniform time offsets for each sub-event
322 time_offsets_np = np.random.uniform(0, TIME_WINDOW, size=total_events_needed)
323
324 # Convert to ROOT vectors for C++
325 window_sizes_vec = ROOT.std.vector("int")(window_sizes_np.tolist())
326 time_offsets_vec = ROOT.std.vector("double")(time_offsets_np.tolist())
327
328 # --- Generate C++, compile, and run ---
329 log.info("Compiling generated C++ code...")
330 cpp_code = generate_cpp(point_class_names)
331 if not ROOT.gInterpreter.Declare(cpp_code):
332 log.error("Failed to compile generated C++ code")
333 log.error("Generated code:\n" + cpp_code)
334 sys.exit(1)
335
336 log.info("Building time windows...")
337 ROOT.build_time_windows(chain, window_sizes_vec, time_offsets_vec, args.output)
338 log.info("Done.")
339
340
341if __name__ == "__main__":
342 main()
get_point_class_name(chain, branch_name)
generate_cpp(point_class_names)