FairShip
Loading...
Searching...
No Matches
compare_histograms.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4"""Compare histograms for exact or statistical equality."""
5
6import argparse
7
8import ROOT
9
10
11def compare_histograms(
12 hist1: ROOT.TH1, hist2: ROOT.TH1, use_ks_test: bool = False, significance_threshold: float = 0.05
13) -> bool:
14 """Compare two histograms for equality or statistical compatibility."""
15 name = hist1.GetName()
16
17 if not hist1.IsEqual(hist2):
18 print(f"Histograms '{name}' are different in terms of bin contents or errors.")
19
20 if use_ks_test:
21 p_value = hist1.KolmogorovTest(hist2)
22 print(f"KS p-value: {p_value}")
23 if p_value < significance_threshold:
24 print(f"Histograms '{name}' are statistically different (p < {significance_threshold}).")
25 else:
26 print(f"Histograms '{name}' are statistically compatible (p >= {significance_threshold}).")
27 return False
28
29 print(f"Histograms '{name}' are equal.")
30 return True
31
32
33def main(file1_path: str, file2_path: str, use_ks_test: bool, significance_threshold: float) -> None:
34 """Compare histograms in two ROOT files."""
35 file1 = ROOT.TFile.Open(file1_path)
36 file2 = ROOT.TFile.Open(file2_path)
37
38 histograms1 = {}
39 for key in file1.GetListOfKeys():
40 if ROOT.TClass.GetClass(key.GetClassName()).InheritsFrom("TH1"):
41 histograms1[key.GetName()] = file1.Get(key.GetName())
42
43 histograms2 = {}
44 for key in file2.GetListOfKeys():
45 if ROOT.TClass.GetClass(key.GetClassName()).InheritsFrom("TH1"):
46 histograms2[key.GetName()] = file2.Get(key.GetName())
47
48 for hist_name in histograms1:
49 if hist_name in histograms2:
50 compare_histograms(histograms1[hist_name], histograms2[hist_name], use_ks_test, significance_threshold)
51 else:
52 print(f"Histogram '{hist_name}' not found in file2.")
53
54 for hist_name in histograms2:
55 if hist_name not in histograms1:
56 print(f"Histogram '{hist_name}' not found in file1.")
57
58
59if __name__ == "__main__":
60 parser = argparse.ArgumentParser(description="Compare histograms in two ROOT files.")
61 parser.add_argument("file1", help="Path to the first ROOT file.")
62 parser.add_argument("file2", help="Path to the second ROOT file.")
63 parser.add_argument(
64 "--ks",
65 action="store_true",
66 help="Use Kolmogorov-Smirnov test for statistical comparison.",
67 )
68 parser.add_argument(
69 "--threshold",
70 type=float,
71 default=0.05,
72 help="Significance threshold for the KS test (default: 0.05).",
73 )
74
75 args = parser.parse_args()
76
77 main(args.file1, args.file2, args.ks, args.threshold)
None main(str file1_path, str file2_path, bool use_ks_test, float significance_threshold)