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
7import sys
8
9import ROOT
10
11
12def histograms_identical(hist1: ROOT.TH1, hist2: ROOT.TH1) -> bool:
13 """Return True if two histograms have identical binning, contents and errors.
14
15 ``TH1`` does not override ``TObject::IsEqual`` (which compares addresses), so
16 a content-based comparison is required. ``GetNcells`` covers the under- and
17 overflow bins and works for 1/2/3-D histograms alike.
18 """
19 ncells = hist1.GetNcells() # type: ignore[attr-defined]
20 if ncells != hist2.GetNcells(): # type: ignore[attr-defined]
21 return False
22 for i in range(ncells):
23 if hist1.GetBinContent(i) != hist2.GetBinContent(i):
24 return False
25 if hist1.GetBinError(i) != hist2.GetBinError(i):
26 return False
27 return True
28
29
30def compare_histograms(
31 hist1: ROOT.TH1, hist2: ROOT.TH1, use_ks_test: bool = False, significance_threshold: float = 0.05
32) -> bool:
33 """Compare two histograms for equality or statistical compatibility."""
34 name = hist1.GetName()
35
36 if not histograms_identical(hist1, hist2):
37 print(f"Histograms '{name}' are different in terms of bin contents or errors.")
38
39 if use_ks_test:
40 p_value = hist1.KolmogorovTest(hist2)
41 print(f"KS p-value: {p_value}")
42 if p_value >= significance_threshold:
43 print(f"Histograms '{name}' are statistically compatible (p >= {significance_threshold}).")
44 return True
45 print(f"Histograms '{name}' are statistically different (p < {significance_threshold}).")
46 return False
47 return False
48
49 print(f"Histograms '{name}' are equal.")
50 return True
51
52
53def main(file1_path: str, file2_path: str, use_ks_test: bool, significance_threshold: float) -> bool:
54 """Compare histograms in two ROOT files.
55
56 Returns True if every histogram is present in both files and identical,
57 False otherwise (so the caller can propagate a non-zero exit status).
58 """
59 file1 = ROOT.TFile.Open(file1_path)
60 file2 = ROOT.TFile.Open(file2_path)
61 all_match = True
62
63 histograms1 = {}
64 for key in file1.GetListOfKeys():
65 cls = ROOT.TClass.GetClass(key.GetClassName())
66 if cls and cls.InheritsFrom("TH1"):
67 histograms1[key.GetName()] = file1.Get(key.GetName())
68
69 histograms2 = {}
70 for key in file2.GetListOfKeys():
71 cls = ROOT.TClass.GetClass(key.GetClassName())
72 if cls and cls.InheritsFrom("TH1"):
73 histograms2[key.GetName()] = file2.Get(key.GetName())
74
75 for hist_name in histograms1:
76 if hist_name in histograms2:
77 if not compare_histograms(
78 histograms1[hist_name], histograms2[hist_name], use_ks_test, significance_threshold
79 ):
80 all_match = False
81 else:
82 print(f"Histogram '{hist_name}' not found in file2.")
83 all_match = False
84
85 for hist_name in histograms2:
86 if hist_name not in histograms1:
87 print(f"Histogram '{hist_name}' not found in file1.")
88 all_match = False
89
90 return all_match
91
92
93if __name__ == "__main__":
94 parser = argparse.ArgumentParser(description="Compare histograms in two ROOT files.")
95 parser.add_argument("file1", help="Path to the first ROOT file.")
96 parser.add_argument("file2", help="Path to the second ROOT file.")
97 parser.add_argument(
98 "--ks",
99 action="store_true",
100 help="Use Kolmogorov-Smirnov test for statistical comparison.",
101 )
102 parser.add_argument(
103 "--threshold",
104 type=float,
105 default=0.05,
106 help="Significance threshold for the KS test (default: 0.05).",
107 )
108
109 args = parser.parse_args()
110
111 sys.exit(0 if main(args.file1, args.file2, args.ks, args.threshold) else 1)
bool histograms_identical(ROOT.TH1 hist1, ROOT.TH1 hist2)