Skip to content

Commit d0d4d9c

Browse files
committed
Add lambda decay analysis
1 parent 29aa2c8 commit d0d4d9c

1 file changed

Lines changed: 325 additions & 0 deletions

File tree

Lines changed: 325 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,325 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Script: lambda_decay.py
4+
5+
MC truth analysis for Lambda particles and their decays from mcpart_lambda CSV files.
6+
Plots kinematic distributions (momentum, pT) and decay vertex locations.
7+
8+
Usage:
9+
python lambda_decay.py -o output_dir -b 10x100 file1.csv file2.csv
10+
python lambda_decay.py -o plots data/*.mcpart_lambda.csv
11+
12+
Dependencies:
13+
pip install pandas numpy matplotlib hist mplhep
14+
"""
15+
16+
import pandas as pd
17+
import numpy as np
18+
import matplotlib
19+
matplotlib.use('Agg')
20+
import matplotlib.pyplot as plt
21+
from matplotlib.colors import LogNorm
22+
import hist
23+
from hist import Hist
24+
from hist.axis import Regular as Axis
25+
26+
import argparse
27+
from pathlib import Path
28+
import warnings
29+
warnings.filterwarnings('ignore')
30+
31+
# Optional: Use HEP styling
32+
try:
33+
import mplhep as hep
34+
plt.style.use(hep.style.ROOT)
35+
except ImportError:
36+
print("Note: mplhep not installed, using default matplotlib style")
37+
38+
39+
###############################################################################
40+
# Histogram Definitions
41+
###############################################################################
42+
43+
def create_histograms():
44+
"""Create all histograms with explicit explicit names and predefined binning."""
45+
hists = {}
46+
47+
# --- Lambda Kinematics ---
48+
hists['hist_lam_p'] = Hist(Axis(100, 0.0, 50.0, name="p", label=r"True $\Lambda$ $|\vec{p}|$ [GeV/c]"))
49+
hists['hist_lam_pt'] = Hist(Axis(100, 0.0, 5.0, name="pt", label=r"True $\Lambda$ $p_T$ [GeV/c]"))
50+
hists['hist_lam_pz'] = Hist(Axis(120, -10.0, 50.0, name="pz", label=r"True $\Lambda$ $p_z$ [GeV/c]"))
51+
hists['hist_lam_eta'] = Hist(Axis(100, -6.0, 6.0, name="eta", label=r"True $\Lambda$ $\eta$"))
52+
53+
# --- Lambda Decay Vertices ---
54+
# epz = End Point Z, decay_r = sqrt(epx^2 + epy^2)
55+
hists['hist_lam_decay_z'] = Hist(Axis(150, -5000.0, 40000.0, name="decay_z", label=r"$\Lambda$ Decay $z$ [mm]"))
56+
hists['hist_lam_decay_r'] = Hist(Axis(100, 0.0, 2000.0, name="decay_r", label=r"$\Lambda$ Decay $r$ [mm]"))
57+
58+
# 2D Decay Vertex Map
59+
hists['hist_lam_decay_rz_2d'] = Hist(
60+
Axis(150, -5000.0, 40000.0, name="decay_z", label=r"$\Lambda$ Decay $z$ [mm]"),
61+
Axis(100, 0.0, 2000.0, name="decay_r", label=r"$\Lambda$ Decay $r$ [mm]")
62+
)
63+
64+
# --- Daughter Kinematics (Proton & Pion from p + pi- decay) ---
65+
hists['hist_prot_p'] = Hist(Axis(100, 0.0, 50.0, name="p", label=r"True Proton $|\vec{p}|$ [GeV/c]"))
66+
hists['hist_pimin_p'] = Hist(Axis(100, 0.0, 20.0, name="p", label=r"True $\pi^-$ $|\vec{p}|$ [GeV/c]"))
67+
68+
return hists
69+
70+
71+
###############################################################################
72+
# Data Loading
73+
###############################################################################
74+
75+
def concat_csvs_with_unique_events(files):
76+
"""Load and concatenate CSV files with globally unique event IDs."""
77+
dfs = []
78+
offset = 0
79+
80+
for file in files:
81+
print(f" Reading: {file}")
82+
if str(file).endswith('.zip'):
83+
df = pd.read_csv(file, compression='zip')
84+
else:
85+
df = pd.read_csv(file)
86+
87+
df['event'] = df['event'] + offset
88+
offset = df['event'].max() + 1
89+
dfs.append(df)
90+
91+
return pd.concat(dfs, ignore_index=True)
92+
93+
94+
###############################################################################
95+
# Derived Quantities
96+
###############################################################################
97+
98+
def add_derived_columns(df):
99+
"""Compute total momentum, transverse momentum, and spatial coordinates."""
100+
101+
# Lambda kinematics
102+
df['lam_p'] = np.sqrt(df['lam_px']**2 + df['lam_py']**2 + df['lam_pz']**2)
103+
df['lam_pt'] = np.sqrt(df['lam_px']**2 + df['lam_py']**2)
104+
df['lam_eta'] = np.where(
105+
df['lam_pt'] > 0,
106+
np.arctanh(df['lam_pz'] / df['lam_p']),
107+
np.nan
108+
)
109+
110+
# Lambda decay spatial properties
111+
# epx, epy, epz are the end points of the Lambda track (decay point)
112+
df['lam_decay_r'] = np.sqrt(df['lam_epx']**2 + df['lam_epy']**2)
113+
df['lam_decay_z'] = df['lam_epz']
114+
115+
# Flags for decays
116+
# lam_nd is number of daughters. If > 0, it decayed inside the simulated world.
117+
df['has_decay'] = df['lam_nd'] > 0
118+
df['is_ppi_decay'] = df['prot_id'].notna() & df['pimin_id'].notna()
119+
df['is_npi0_decay'] = df['neut_id'].notna() & df['pizero_id'].notna()
120+
121+
# Proton kinematics (if it exists)
122+
df['prot_p'] = np.sqrt(df['prot_px']**2 + df['prot_py']**2 + df['prot_pz']**2)
123+
df['prot_pt'] = np.sqrt(df['prot_px']**2 + df['prot_py']**2)
124+
125+
# Pion- kinematics (if it exists)
126+
df['pimin_p'] = np.sqrt(df['pimin_px']**2 + df['pimin_py']**2 + df['pimin_pz']**2)
127+
df['pimin_pt'] = np.sqrt(df['pimin_px']**2 + df['pimin_py']**2)
128+
129+
return df
130+
131+
132+
###############################################################################
133+
# Fill Histograms
134+
###############################################################################
135+
136+
def fill_histograms(hists, df):
137+
"""Explicitly fill histograms using dataframe series to avoid obfuscation."""
138+
print("\nFilling histograms...")
139+
140+
# 1. Lambda Kinematics (All primary lambdas)
141+
valid_lam_p = df.dropna(subset=['lam_p', 'lam_pt', 'lam_pz', 'lam_eta'])
142+
if not valid_lam_p.empty:
143+
hists['hist_lam_p'].fill(valid_lam_p['lam_p'].values)
144+
hists['hist_lam_pt'].fill(valid_lam_p['lam_pt'].values)
145+
hists['hist_lam_pz'].fill(valid_lam_p['lam_pz'].values)
146+
hists['hist_lam_eta'].fill(valid_lam_p['lam_eta'].values)
147+
print(f" Filled Lambda kinematics: {len(valid_lam_p)} entries")
148+
149+
# 2. Lambda Decay Vertices (Only for lambdas that actually decayed)
150+
decayed_lam = df[df['has_decay']].dropna(subset=['lam_decay_r', 'lam_decay_z'])
151+
if not decayed_lam.empty:
152+
hists['hist_lam_decay_r'].fill(decayed_lam['lam_decay_r'].values)
153+
hists['hist_lam_decay_z'].fill(decayed_lam['lam_decay_z'].values)
154+
hists['hist_lam_decay_rz_2d'].fill(decayed_lam['lam_decay_z'].values, decayed_lam['lam_decay_r'].values)
155+
print(f" Filled Decay Vertices: {len(decayed_lam)} entries")
156+
157+
# 3. Daughter Kinematics (Proton from p pi- decay)
158+
valid_prot = df[df['is_ppi_decay']].dropna(subset=['prot_p'])
159+
if not valid_prot.empty:
160+
hists['hist_prot_p'].fill(valid_prot['prot_p'].values)
161+
print(f" Filled Proton kinematics: {len(valid_prot)} entries")
162+
163+
# 4. Daughter Kinematics (Pion from p pi- decay)
164+
valid_pimin = df[df['is_ppi_decay']].dropna(subset=['pimin_p'])
165+
if not valid_pimin.empty:
166+
hists['hist_pimin_p'].fill(valid_pimin['pimin_p'].values)
167+
print(f" Filled Pion kinematics: {len(valid_pimin)} entries")
168+
169+
170+
###############################################################################
171+
# Plotting Helpers
172+
###############################################################################
173+
174+
def _stats_text(values, edges):
175+
"""Return a stats-box string for a filled 1D histogram."""
176+
total = values.sum()
177+
if total == 0:
178+
return ""
179+
centers = (edges[:-1] + edges[1:]) / 2
180+
mean = np.average(centers, weights=values)
181+
std = np.sqrt(np.average((centers - mean)**2, weights=values))
182+
return f"Entries: {int(total)}\nMean: {mean:.4f}\nStd: {std:.4f}"
183+
184+
185+
def plot_single_1d(h, path):
186+
"""Save a single 1-D histogram to *path*."""
187+
fig, ax = plt.subplots(figsize=(10, 6))
188+
h.plot1d(ax=ax, linewidth=2, color="#4878d0")
189+
190+
stats = _stats_text(h.values(), h.axes[0].edges)
191+
if stats:
192+
ax.text(0.95, 0.95, stats, transform=ax.transAxes,
193+
verticalalignment='top', horizontalalignment='right',
194+
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8),
195+
fontsize=11)
196+
197+
ax.set_xlabel(h.axes[0].label or h.axes[0].name)
198+
ax.set_ylabel("Counts")
199+
ax.set_title(f"{h.axes[0].name} Distribution")
200+
ax.grid(True, alpha=0.3)
201+
202+
plt.tight_layout()
203+
plt.savefig(path, dpi=150, bbox_inches='tight')
204+
plt.close()
205+
print(f" Saved: {path}")
206+
207+
208+
def plot_single_2d(h, path):
209+
"""Save a 2-D histogram to *path*."""
210+
fig, ax = plt.subplots(figsize=(10, 6))
211+
212+
# Plot using a log scale for better visibility of vertex distributions
213+
w, x, y = h.to_numpy()
214+
mesh = ax.pcolormesh(x, y, w.T, norm=LogNorm(), cmap='viridis')
215+
fig.colorbar(mesh, ax=ax, label='Counts')
216+
217+
ax.set_xlabel(h.axes[0].label or h.axes[0].name)
218+
ax.set_ylabel(h.axes[1].label or h.axes[1].name)
219+
ax.set_title(f"2D Distribution: {h.axes[1].name} vs {h.axes[0].name}")
220+
221+
plt.tight_layout()
222+
plt.savefig(path, dpi=150, bbox_inches='tight')
223+
plt.close()
224+
print(f" Saved: {path}")
225+
226+
227+
###############################################################################
228+
# Event Counts Bar Chart
229+
###############################################################################
230+
231+
def plot_decay_channels(df, path):
232+
"""Bar chart: total lambdas, decayed, p pi-, n pi0 channels."""
233+
n_total = len(df)
234+
n_decayed = int(df['has_decay'].sum())
235+
n_ppi = int(df['is_ppi_decay'].sum())
236+
n_npi0 = int(df['is_npi0_decay'].sum())
237+
n_other = n_decayed - (n_ppi + n_npi0)
238+
239+
categories = ["Total Lambda", "Decayed", "p + pi-", "n + pi0", "Other Decays"]
240+
counts = [n_total, n_decayed, n_ppi, n_npi0, n_other]
241+
colors = ["#4878d0", "#6acc64", "#ee854a", "#d65f5f", "#956cb4"]
242+
243+
fig, ax = plt.subplots(figsize=(10, 6))
244+
bars = ax.bar(categories, counts, color=colors, edgecolor='black', linewidth=1.0)
245+
246+
for bar in bars:
247+
height = bar.get_height()
248+
pct = 100.0 * height / n_total if n_total > 0 else 0
249+
label = f"{int(height)}\n({pct:.1f}%)"
250+
ax.text(bar.get_x() + bar.get_width() / 2, height,
251+
label, ha='center', va='bottom', fontsize=11)
252+
253+
ax.set_ylabel("Count")
254+
ax.set_title(r"MC Truth $\Lambda$ Decay Channels")
255+
ax.grid(axis='y', alpha=0.3)
256+
257+
# Extend Y axis slightly to fit the text labels
258+
ax.set_ylim(0, max(counts) * 1.15)
259+
260+
plt.tight_layout()
261+
plt.savefig(path, dpi=150, bbox_inches='tight')
262+
plt.close()
263+
print(f" Saved: {path}")
264+
265+
266+
###############################################################################
267+
# Main Analysis
268+
###############################################################################
269+
270+
def main():
271+
parser = argparse.ArgumentParser(description="MC Truth Lambda analysis using mcpart_lambda CSV files")
272+
parser.add_argument('-o', '--output', type=str, default='mcpart_lambda_plots', help='Directory for output plots')
273+
parser.add_argument('-b', '--beam', type=str, default=None, help='Beam configuration (e.g. 10x100)')
274+
parser.add_argument('-e', '--events', type=int, default=None, help='Max number of events to process')
275+
parser.add_argument('files', nargs='+', help='Input mcpart_lambda CSV files')
276+
args = parser.parse_args()
277+
278+
output_dir = Path(args.output)
279+
output_dir.mkdir(parents=True, exist_ok=True)
280+
281+
print(f"{'=' * 70}")
282+
print(f"MC Truth Lambda Analysis")
283+
if args.beam:
284+
print(f"Beam: {args.beam}")
285+
print(f"{'=' * 70}")
286+
287+
# --- Load data ---
288+
print("\nLoading CSV files...")
289+
df = concat_csvs_with_unique_events([Path(f) for f in args.files])
290+
291+
if args.events is not None:
292+
print(f"Limiting to {args.events} events")
293+
df = df.head(args.events)
294+
295+
print(f"Total events processed: {len(df)}")
296+
297+
# --- Derived columns ---
298+
df = add_derived_columns(df)
299+
300+
# --- Create & fill histograms ---
301+
hists = create_histograms()
302+
fill_histograms(hists, df)
303+
304+
# --- Plotting ---
305+
print("\nCreating plots...")
306+
for name, h in hists.items():
307+
if h.sum() > 0:
308+
if isinstance(h.axes, tuple) and len(h.axes) == 2:
309+
plot_single_2d(h, output_dir / f"{name}.png")
310+
else:
311+
plot_single_1d(h, output_dir / f"{name}.png")
312+
313+
# --- Decay channel summary chart ---
314+
print("\nCreating decay channel summary chart...")
315+
plot_decay_channels(df, output_dir / "decay_channels.png")
316+
317+
# --- Summary ---
318+
print("\n" + "=" * 70)
319+
print("Analysis Complete!")
320+
print(f"Output plots saved in: {output_dir}")
321+
print("=" * 70)
322+
323+
324+
if __name__ == "__main__":
325+
main()

0 commit comments

Comments
 (0)