Skip to content

Commit 020840b

Browse files
authored
Refactor plotting script and improve event sorting (#12)
* fixed plotting_script * Refactor W+ to W- ratio calculation and improve error handling in MassReader; sort passing events in getPassingEvents function * fixed bugs * API consistency
1 parent d796de7 commit 020840b

3 files changed

Lines changed: 28 additions & 12 deletions

File tree

scripts/plotting_script.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from __future__ import annotations
22

33
import argparse
4-
from glob import glob
54
from collections import defaultdict
5+
from datetime import datetime
6+
from glob import glob
67

78
import matplotlib.pyplot as plt
89
import mplhep as hep # type: ignore
@@ -11,10 +12,10 @@
1112
def parser_setup() -> argparse.ArgumentParser:
1213
parser = argparse.ArgumentParser(prog="plotting_script.py", description="Plotting script")
1314
parser.add_argument("--input", "-i", type=str, help="Input Folder; defaults to './'", default="./")
14-
parser.add_argument("--output", "-o", type=str, help="Output file with extension; defaults to './output.png'", default="./output.png")
15+
parser.add_argument("--output", "-o", type=str, help="Output file with extension; defaults to './*current date*.png'", default=None)
1516
parser.add_argument(
16-
"--channel", "-c", type=str, nargs="*", choices=["Higgs", "W", "Z", "all"], default=["Higgs", "Z"],
17-
help="Channel to plot; default plots all channels.",
17+
"--channel", "-c", type=str, nargs="*", choices=["Higgs", "W", "Z", "all"], default=None,
18+
help="Channel(s) to plot; defaults to Higgs and Z channels.",
1819
)
1920
parser.add_argument("--min", "-m", type=float, default=10.0, help="minimum value for the histogram; default is 10.0")
2021
parser.add_argument("--unstack", "-u", action='store_true', default=False, help="Unstack the histograms; default is stacked")
@@ -23,8 +24,13 @@ def parser_setup() -> argparse.ArgumentParser:
2324
return parser
2425

2526

26-
def get_files_by_channel(channel: str, input_folder: str) -> dict[str, list[str]]:
27-
channels = ["Higgs", "W", "Z"] if channel == "all" else [channel]
27+
def get_files_by_channel(channel: str | list[str] | None, input_folder: str) -> dict[str, list[str]]:
28+
if not channel:
29+
channels = ["Higgs", "Z"]
30+
elif channel == "all":
31+
channels = ["Higgs", "W", "Z"]
32+
else:
33+
channels = channel if isinstance(channel, list) else [channel]
2834
if "W" in channels:
2935
channels.extend(["Wp", "Wm"])
3036
channels.remove("W")
@@ -89,16 +95,18 @@ def _read_file(self, file: str) -> list[float]:
8995
def w_ratio(self):
9096
""" Calculates the ratio of W+ to W- events.
9197
"""
92-
wp = self.data["Wp"]
93-
wm = self.data["Wm"]
98+
wp = len(self.data["Wp"])
99+
wm = len(self.data["Wm"])
94100

95101
print(40 * "*")
96102
print("***\tCalculating W+ to W- ratio...")
97-
if len(wm) == 0:
103+
if wm == 0:
98104
print("!!!\tNo W- events found. Skipping W+ to W- ratio calculation.")
99105
else:
100-
print(f"***\tFound: {len(wp)} W+ events and {len(wm)} W- events.")
101-
print(f"***\tW+ to W- ratio: {len(wp) / len(wm)}")
106+
w_ratio = wp / wm
107+
w_error = np.sqrt(w_ratio / wm * (1 + w_ratio))
108+
print(f"***\tFound: {wp} W+ events and {wm} W- events.")
109+
print(f"***\tW+ to W- ratio: {w_ratio} ± {w_error} (stat)")
102110
print(40 * "*")
103111

104112
def items(self) -> tuple[list[str], list[list[float]]]:
@@ -151,6 +159,8 @@ def plot_masses(reader: MassReader, unstack: bool, output: str, **kwargs):
151159
def main():
152160
parser = parser_setup()
153161
args = parser.parse_args()
162+
if args.output is None:
163+
args.output = f"./{datetime.now().strftime('%d%m%Y')}.png"
154164
files = get_files_by_channel(args.channel, args.input)
155165
if not files:
156166
raise Exception(f"No files found for channel '{args.channel}' in folder '{args.input}'")

ts/setup.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,12 @@ function initSelectionFields() {
624624
if (["TrackerMuons", "GsfElectrons", "Photons", "maxMETs"].includes(key)) {
625625
createCheckboxContainer(cont);
626626
}
627+
if (key === "pt") {
628+
cont.onFinishChange(function (this: SelectionFieldController, value: number) {
629+
if (value < 0) this.setValue(0);
630+
ispy.subfoldersReduced.Controllers.find((c) => c.property === "min_pt")?.setValue(value);
631+
});
632+
}
627633
});
628634

629635
// add all controllers to the reduced subfolders for convenience

ts/uhh_selection.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ function getPassingEvents(): string[] {
188188
}
189189
}
190190

191-
return passing_events;
191+
return passing_events.sort((a, b) => Number(a) - Number(b));
192192
}
193193

194194
/**

0 commit comments

Comments
 (0)