CMS 3D CMS Logo

trackingPlots.py
Go to the documentation of this file.
1 import os
2 import copy
3 import collections
4 
5 import ROOT
6 ROOT.gROOT.SetBatch(True)
7 ROOT.PyConfig.IgnoreCommandLineOptions = True
8 
9 from plotting import Subtract, FakeDuplicate, CutEfficiency, Transform, AggregateBins, ROC, Plot, PlotEmpty, PlotGroup, PlotOnSideGroup, PlotFolder, Plotter
10 from html import PlotPurpose
11 import plotting
12 import validation
13 import html
14 
15 ########################################
16 #
17 # Per track collection plots
18 #
19 ########################################
20 
21 _maxEff = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.8, 1.025, 1.2, 1.5, 2]
22 _maxFake = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.8, 1.025]
23 
24 #_minMaxResol = [1e-5, 2e-5, 5e-5, 1e-4, 2e-4, 5e-4, 1e-3, 2e-3, 5e-3, 1e-2, 2e-2, 5e-2, 0.1, 0.2, 0.5, 1]
25 _minMaxResol = [1e-5, 4e-5, 1e-4, 4e-4, 1e-3, 4e-3, 1e-2, 4e-2, 0.1, 0.4, 1]
26 _minMaxN = [5e-1, 5, 5e1, 5e2, 5e3, 5e4, 5e5, 5e6, 5e7, 5e8, 5e9]
27 
28 _minHits = [0, 5, 10]
29 _maxHits = [5, 10, 20, 40, 60, 80]
30 _minLayers = [0, 5, 10]
31 _maxLayers = [5, 10, 25]
32 _maxPixelLayers = 8
33 _min3DLayers = [0, 5, 10]
34 _max3DLayers = [5, 10, 20]
35 _minZ = [-60, -40, -20, -10, -5]
36 _maxZ = [5, 10, 20, 40, 60]
37 _minPU = [0, 10, 20, 50, 100, 150]
38 _maxPU = [20, 50, 65, 80, 100, 150, 200, 250]
39 _minMaxTracks = [0, 200, 500, 1000, 1500, 2000]
40 _minMaxMVA = [-1.025, -0.5, 0, 0.5, 1.025]
41 
43  return ([-x for x in ma], ma)
44 
45 (_minResidualPhi, _maxResidualPhi) = _minMaxResidual([1e-4, 2e-4]) # rad
46 (_minResidualCotTheta, _maxResidualCotTheta) = _minMaxResidual([1e-4, 2e-4])
47 (_minResidualDxy, _maxResidualDxy) = _minMaxResidual([10, 20, 50, 100]) # um
48 (_minResidualDz, _maxResidualDz) = (_minResidualDxy, _maxResidualDxy)
49 (_minResidualPt, _maxResidualPt) = _minMaxResidual([1, 1.5, 2, 5]) # %
50 
51 
52 _legendDy_1row = 0.46
53 _legendDy_2rows = -0.025
54 _legendDy_2rows_3cols = -0.17
55 _legendDy_4rows = 0.09
56 
57 # Ok, because of the way the "reference release" histograms are
58 # stored, this histogram is not accessible for the summary plots. To
59 # be fixed later with (large) reorganization of how things work.
60 #_trackingNumberOfEventsHistogram = "DQMData/Run 1/Tracking/Run summary/Track/general_trackingParticleRecoAsssociation/tracks"
61 
62 _trackingIterationOrderHistogram = "DQMData/Run 1/Tracking/Run summary/TrackBuilding/num_reco_coll"
63 
64 def _makeEffFakeDupPlots(postfix, quantity, unit="", common={}, effopts={}, fakeopts={}):
65  p = postfix
66  q = quantity
67  xq = q
68  if unit != "":
69  xq += " (" + unit + ")"
70 
71  effargs = dict(xtitle="TP "+xq , ytitle="efficiency vs "+q , ymax=_maxEff)
72  fakeargs = dict(xtitle="track "+xq, ytitle="fake+duplicates rate vs "+q, ymax=_maxFake)
73  effargs.update(common)
74  fakeargs.update(common)
75  effargs.update(effopts)
76  fakeargs.update(fakeopts)
77 
78  return [
79  Plot("effic_vs_"+p, **effargs),
80  Plot(FakeDuplicate("fakeduprate_vs_"+p, assoc="num_assoc(recoToSim)_"+p, dup="num_duplicate_"+p, reco="num_reco_"+p, title="fake+duplicates vs "+q), **fakeargs)
81  ]
82 
83 def _makeFakeDupPileupPlots(postfix, quantity, unit="", xquantity="", xtitle=None, common={}):
84  p = postfix
85  q = quantity
86  if xtitle is None:
87  if xquantity != "":
88  xq = xquantity
89  else:
90  xq = q
91  if unit != "":
92  xq += " (" + unit + ")"
93  xtitle="track "+xq
94 
95  return [
96  Plot("fakerate_vs_"+p , xtitle=xtitle, ytitle="fakerate vs "+q , ymax=_maxFake, **common),
97  Plot("duplicatesRate_"+p, xtitle=xtitle, ytitle="duplicates rate vs "+q, ymax=_maxFake, **common),
98  Plot("pileuprate_"+p , xtitle=xtitle, ytitle="pileup rate vs "+q , ymax=_maxFake, **common),
99  ]
100 
101 def _makeFakeDist(postfix):
102  return Subtract("num_fake_"+postfix, "num_reco_"+postfix, "num_assoc(recoToSim)_"+postfix)
103 
104 def _makeDistPlots(postfix, quantity, common={}):
105  p = postfix
106  q = quantity
107 
108  args = dict(xtitle="track "+q, ylog=True, ymin=_minMaxN, ymax=_minMaxN)
109  args.update(common)
110 
111  return [
112  Plot("num_reco_"+p , ytitle="tracks", **args),
113  Plot("num_assoc(recoToSim)_"+p, ytitle="true tracks", **args),
114  Plot(_makeFakeDist(p), ytitle="fake tracks", **args),
115  Plot("num_duplicate_"+p , ytitle="duplicate tracks", **args),
116  ]
117 
118 def _makeDistSimPlots(postfix, quantity, common={}):
119  p = postfix
120  q = quantity
121 
122  args = dict(xtitle="TP "+q, ylog=True, ymin=_minMaxN, ymax=_minMaxN)
123  args.update(common)
124 
125  return [
126  Plot("num_simul_"+p , ytitle="TrackingParticles", **args),
127  Plot("num_assoc(simToReco)_"+p, ytitle="Reconstructed TPs", **args),
128  ]
129 
130 def _makeMVAPlots(num, hp=False):
131  pfix = "_hp" if hp else ""
132  pfix2 = "Hp" if hp else ""
133 
134  xtitle = "MVA%d output"%num
135  xtitlecut = "Cut on MVA%d output"%num
136  args = dict(xtitle=xtitle, ylog=True, ymin=_minMaxN, ymax=_minMaxN)
137 
138  argsroc = dict(
139  xtitle="Efficiency (excl. trk eff)", ytitle="Fake rate",
140  xmax=_maxEff, ymax=_maxFake,
141  drawStyle="EP",
142  )
143  argsroc2 = dict(
144  ztitle="Cut on MVA%d"%num,
145  xtitleoffset=5, ytitleoffset=6.5, ztitleoffset=4,
146  adjustMarginRight=0.12
147  )
148  argsroc2.update(argsroc)
149  argsroc2["drawStyle"] = "pcolz"
150 
151  argsprofile = dict(ymin=_minMaxMVA, ymax=_minMaxMVA)
152 
153  true_cuteff = CutEfficiency("trueeff_vs_mva%dcut%s"%(num,pfix), "num_assoc(recoToSim)_mva%dcut%s"%(num,pfix))
154  fake_cuteff = CutEfficiency("fakeeff_vs_mva%dcut%s"%(num,pfix), Subtract("num_fake_mva%dcut%s"%(num,pfix), "num_reco_mva%dcut%s"%(num,pfix), "num_assoc(recoToSim)_mva%dcut%s"%(num,pfix)))
155 
156  return [
157  PlotGroup("mva%d%s"%(num,pfix2), [
158  Plot("num_assoc(recoToSim)_mva%d%s"%(num,pfix), ytitle="true tracks", **args),
159  Plot(Subtract("num_fake_mva%d%s"%(num,pfix), "num_reco_mva%d%s"%(num,pfix), "num_assoc(recoToSim)_mva%d%s"%(num,pfix)), ytitle="fake tracks", **args),
160  Plot("effic_vs_mva%dcut%s"%(num,pfix), xtitle=xtitlecut, ytitle="Efficiency (excl. trk eff)", ymax=_maxEff),
161  #
162  Plot("fakerate_vs_mva%dcut%s"%(num,pfix), xtitle=xtitlecut, ytitle="Fake rate", ymax=_maxFake),
163  Plot(ROC("effic_vs_fake_mva%d%s"%(num,pfix), "effic_vs_mva%dcut%s"%(num,pfix), "fakerate_vs_mva%dcut%s"%(num,pfix)), **argsroc),
164  Plot(ROC("effic_vs_fake_mva%d%s"%(num,pfix), "effic_vs_mva%dcut%s"%(num,pfix), "fakerate_vs_mva%dcut%s"%(num,pfix), zaxis=True), **argsroc2),
165  # Same signal efficiency, background efficiency, and ROC definitions as in TMVA
166  Plot(true_cuteff, xtitle=xtitlecut, ytitle="True track selection efficiency", ymax=_maxEff),
167  Plot(fake_cuteff, xtitle=xtitlecut, ytitle="Fake track selection efficiency", ymax=_maxEff),
168  Plot(ROC("true_eff_vs_fake_rej_mva%d%s"%(num,pfix), true_cuteff, Transform("fake_rej_mva%d%s"%(num,pfix), fake_cuteff, lambda x: 1-x)), xtitle="True track selection efficiency", ytitle="Fake track rejection", xmax=_maxEff, ymax=_maxEff),
169  ], ncols=3, legendDy=_legendDy_1row),
170  PlotGroup("mva%d%sPtEta"%(num,pfix2), [
171  Plot("mva_assoc(recoToSim)_mva%d%s_pT"%(num,pfix), xtitle="Track p_{T} (GeV)", ytitle=xtitle+" for true tracks", xlog=True, **argsprofile),
172  Plot("mva_fake_mva%d%s_pT"%(num,pfix), xtitle="Track p_{T} (GeV)", ytitle=xtitle+" for fake tracks", xlog=True, **argsprofile),
173  Plot("mva_assoc(recoToSim)_mva%d%s_eta"%(num,pfix), xtitle="Track #eta", ytitle=xtitle+" for true tracks", **argsprofile),
174  Plot("mva_fake_mva%d%s_eta"%(num,pfix), xtitle="Track #eta", ytitle=xtitle+" for fake tracks", **argsprofile),
175  ], legendDy=_legendDy_2rows)
176  ]
177 
178 _effandfakePtEtaPhi = PlotGroup("effandfakePtEtaPhi", [
179  Plot("efficPt", title="Efficiency vs p_{T}", xtitle="TP p_{T} (GeV)", ytitle="efficiency vs p_{T}", xlog=True, ymax=_maxEff),
180  Plot(FakeDuplicate("fakeduprate_vs_pT", assoc="num_assoc(recoToSim)_pT", dup="num_duplicate_pT", reco="num_reco_pT", title="fake+duplicates vs p_{T}"),
181  xtitle="track p_{T} (GeV)", ytitle="fake+duplicates rate vs p_{T}", ymax=_maxFake, xlog=True),
182  Plot("effic", xtitle="TP #eta", ytitle="efficiency vs #eta", title="", ymax=_maxEff),
183  Plot(FakeDuplicate("fakeduprate_vs_eta", assoc="num_assoc(recoToSim)_eta", dup="num_duplicate_eta", reco="num_reco_eta", title=""),
184  xtitle="track #eta", ytitle="fake+duplicates rate vs #eta", ymax=_maxFake),
185 ] +
186  _makeEffFakeDupPlots("phi", "#phi")
187 )
188 
189 _effandfakeDxyDzBS = PlotGroup("effandfakeDxyDzBS",
190  _makeEffFakeDupPlots("dxy" , "dxy" , "cm") +
191  _makeEffFakeDupPlots("dz" , "dz" , "cm"),
192  legendDy=_legendDy_2rows
193 )
194 _effandfakeDxyDzPV = PlotGroup("effandfakeDxyDzPV",
195  _makeEffFakeDupPlots("dxypv" , "dxy(PV)", "cm") +
196  _makeEffFakeDupPlots("dxypv_zoomed", "dxy(PV)", "cm") +
197  _makeEffFakeDupPlots("dzpv" , "dz(PV)" , "cm") +
198  _makeEffFakeDupPlots("dzpv_zoomed" , "dz(PV)" , "cm"),
199  legendDy=_legendDy_4rows
200 )
201 _effandfakeHitsLayers = PlotGroup("effandfakeHitsLayers",
202  _makeEffFakeDupPlots("hit" , "hits" , common=dict(xmin=_minHits , xmax=_maxHits)) +
203  _makeEffFakeDupPlots("layer" , "layers" , common=dict(xmin=_minLayers , xmax=_maxLayers)) +
204  _makeEffFakeDupPlots("pixellayer", "pixel layers", common=dict( xmax=_maxPixelLayers)) +
205  _makeEffFakeDupPlots("3Dlayer" , "3D layers" , common=dict(xmin=_min3DLayers, xmax=_max3DLayers)),
206  legendDy=_legendDy_4rows
207 )
208 _common = {"ymin": 0, "ymax": _maxEff}
209 _effandfakePos = PlotGroup("effandfakePos",
210  _makeEffFakeDupPlots("vertpos", "vert r", "cm", fakeopts=dict(xtitle="track ref. point r (cm)", ytitle="fake+duplicates vs. r"), common=dict(xlog=True)) +
211  _makeEffFakeDupPlots("zpos" , "vert z", "cm", fakeopts=dict(xtitle="track ref. point z (cm)", ytitle="fake+duplicates vs. z")) +
212  _makeEffFakeDupPlots("simpvz" , "Sim. PV z", "cm", common=dict(xtitle="Sim. PV z (cm)", xmin=_minZ, xmax=_maxZ))
213 )
214 _effandfakeDeltaRPU = PlotGroup("effandfakeDeltaRPU",
215  _makeEffFakeDupPlots("dr" , "#DeltaR", effopts=dict(xtitle="TP min #DeltaR"), fakeopts=dict(xtitle="track min #DeltaR"), common=dict(xlog=True)) +
216  _makeEffFakeDupPlots("pu" , "PU" , common=dict(xtitle="Pileup", xmin=_minPU, xmax=_maxPU)),
217  legendDy=_legendDy_2rows
218 )
219 
220 
221 _algos_common = dict(removeEmptyBins=True, xbinlabelsize=10, xbinlabeloption="d")
222 _duplicateAlgo = PlotOnSideGroup("duplicateAlgo", Plot("duplicates_oriAlgo_vs_oriAlgo", drawStyle="COLZ", adjustMarginLeft=0.1, adjustMarginRight=0.1, **_algos_common))
223 
224 _dupandfakePtEtaPhi = PlotGroup("dupandfakePtEtaPhi", [
225  Plot("fakeratePt", xtitle="track p_{T} (GeV)", ytitle="fakerate vs p_{T}", xlog=True, ymax=_maxFake),
226  Plot("duplicatesRate_Pt", xtitle="track p_{T} (GeV)", ytitle="duplicates rate vs p_{T}", ymax=_maxFake, xlog=True),
227  Plot("pileuprate_Pt", xtitle="track p_{T} (GeV)", ytitle="pileup rate vs p_{T}", ymax=_maxFake, xlog=True),
228  Plot("fakerate", xtitle="track #eta", ytitle="fakerate vs #eta", title="", ymax=_maxFake),
229  Plot("duplicatesRate", xtitle="track #eta", ytitle="duplicates rate vs #eta", title="", ymax=_maxFake),
230  Plot("pileuprate", xtitle="track #eta", ytitle="pileup rate vs #eta", title="", ymax=_maxFake),
231 ] + _makeFakeDupPileupPlots("phi", "#phi"),
232  ncols=3
233 )
234 _dupandfakeDxyDzBS = PlotGroup("dupandfakeDxyDzBS",
235  _makeFakeDupPileupPlots("dxy" , "dxy" , "cm") +
236  _makeFakeDupPileupPlots("dz" , "dz" , "cm"),
237  ncols=3, legendDy=_legendDy_2rows_3cols
238 )
239 _dupandfakeDxyDzPV = PlotGroup("dupandfakeDxyDzPV",
240  _makeFakeDupPileupPlots("dxypv" , "dxy(PV)", "cm") +
241  _makeFakeDupPileupPlots("dxypv_zoomed", "dxy(PV)", "cm") +
242  _makeFakeDupPileupPlots("dzpv" , "dz(PV)" , "cm") +
243  _makeFakeDupPileupPlots("dzpv_zoomed" , "dz(PV)" , "cm"),
244  ncols=3, legendDy=_legendDy_4rows
245 )
246 _dupandfakeHitsLayers = PlotGroup("dupandfakeHitsLayers",
247  _makeFakeDupPileupPlots("hit" , "hits" , common=dict(xmin=_minHits , xmax=_maxHits)) +
248  _makeFakeDupPileupPlots("layer" , "layers" , common=dict(xmin=_minLayers , xmax=_maxLayers)) +
249  _makeFakeDupPileupPlots("pixellayer", "pixel layers", common=dict( xmax=_maxPixelLayers)) +
250  _makeFakeDupPileupPlots("3Dlayer" , "3D layers" , common=dict(xmin=_min3DLayers, xmax=_max3DLayers)),
251  ncols=3, legendDy=_legendDy_4rows
252 )
253 _dupandfakePos = PlotGroup("dupandfakePos",
254  _makeFakeDupPileupPlots("vertpos", "r", "cm", xquantity="ref. point r (cm)", common=dict(xlog=True)) +
255  _makeFakeDupPileupPlots("zpos" , "z", "cm", xquantity="ref. point z (cm)") +
256  _makeFakeDupPileupPlots("simpvz" , "Sim. PV z", xtitle="Sim. PV z (cm)", common=dict(xmin=_minZ, xmax=_maxZ)),
257  ncols=3,
258 )
259 _dupandfakeDeltaRPU = PlotGroup("dupandfakeDeltaRPU",
260  _makeFakeDupPileupPlots("dr" , "#DeltaR", xquantity="min #DeltaR", common=dict(xlog=True)) +
261  _makeFakeDupPileupPlots("pu" , "PU" , xtitle="Pileup", common=dict(xmin=_minPU, xmax=_maxPU)),
262  ncols=3, legendDy=_legendDy_2rows_3cols
263 )
264 _seedingLayerSet_common = dict(removeEmptyBins=True, xbinlabelsize=8, xbinlabeloption="d", adjustMarginRight=0.1)
265 _dupandfakeSeedingPlots = _makeFakeDupPileupPlots("seedingLayerSet", "seeding layers", xtitle="", common=_seedingLayerSet_common)
266 _dupandfakeChi2Seeding = PlotGroup("dupandfakeChi2Seeding",
267  _makeFakeDupPileupPlots("chi2", "#chi^{2}") +
268  _dupandfakeSeedingPlots,
269  ncols=3, legendDy=_legendDy_2rows_3cols
270 )
271 
272 _common = {
273  "ytitle": "Fake+pileup rate",
274  "ymax": _maxFake,
275  "drawStyle": "EP",
276 }
277 _common2 = {}
278 _common2.update(_common)
279 _common2["drawStyle"] = "pcolz"
280 _common2["ztitleoffset"] = 1.5
281 _common2["xtitleoffset"] = 7
282 _common2["ytitleoffset"] = 10
283 _common2["ztitleoffset"] = 6
284 _pvassociation1 = PlotGroup("pvassociation1", [
285  Plot(ROC("effic_vs_fakepileup_dzpvcut", "effic_vs_dzpvcut", FakeDuplicate("fakepileup_vs_dzpvcut", assoc="num_assoc(recoToSim)_dzpvcut", reco="num_reco_dzpvcut", dup="num_pileup_dzpvcut")),
286  xtitle="Efficiency vs. cut on dz(PV)", **_common),
287  Plot(ROC("effic_vs_fakepileup2_dzpvcut", "effic_vs_dzpvcut", FakeDuplicate("fakepileup_vs_dzpvcut", assoc="num_assoc(recoToSim)_dzpvcut", reco="num_reco_dzpvcut", dup="num_pileup_dzpvcut"), zaxis=True),
288  xtitle="Efficiency", ztitle="Cut on dz(PV)", **_common2),
289  #
290  Plot(ROC("effic_vs_fakepileup_dzpvsigcut", "effic_vs_dzpvsigcut", FakeDuplicate("fakepileup_vs_dzpvsigcut", assoc="num_assoc(recoToSim)_dzpvsigcut", reco="num_reco_dzpvsigcut", dup="num_pileup_dzpvsigcut")),
291  xtitle="Efficiency vs. cut on dz(PV)/dzError", **_common),
292  Plot(ROC("effic_vs_fakepileup2_dzpvsigcut", "effic_vs_dzpvsigcut", FakeDuplicate("fakepileup_vs_dzpvsigcut", assoc="num_assoc(recoToSim)_dzpvsigcut", reco="num_reco_dzpvsigcut", dup="num_pileup_dzpvsigcut"), zaxis=True),
293  xtitle="Efficiency", ztitle="Cut on dz(PV)/dzError", **_common2),
294 
295  Plot(ROC("effic_vs_fakepileup_dzpvcut_pt", "effic_vs_dzpvcut_pt", FakeDuplicate("fakepileup_vs_dzpvcut_pt", assoc="num_assoc(recoToSim)_dzpvcut_pt", reco="num_reco_dzpvcut_pt", dup="num_pileup_dzpvcut_pt")),
296  xtitle="Efficiency (p_{T} weighted) vs. cut on dz(PV)", **_common),
297  Plot(ROC("effic_vs_fakepileup2_dzpvcut_pt", "effic_vs_dzpvcut_pt", FakeDuplicate("fakepileup_vs_dzpvcut_pt", assoc="num_assoc(recoToSim)_dzpvcut_pt", reco="num_reco_dzpvcut_pt", dup="num_pileup_dzpvcut_pt"), zaxis=True),
298  xtitle="Efficiency (p_{T} weighted)", ztitle="Cut on dz(PV)", **_common2),
299  #
300  Plot(ROC("effic_vs_fakepileup_dzpvsigcut_pt", "effic_vs_dzpvsigcut_pt", FakeDuplicate("fakepileup_vs_dzpvsigcut_pt", assoc="num_assoc(recoToSim)_dzpvsigcut_pt", reco="num_reco_dzpvsigcut_pt", dup="num_pileup_dzpvsigcut_pt")),
301  xtitle="Efficiency (p_{T} weighted) vs. cut on dz(PV)/dzError", **_common),
302  Plot(ROC("effic_vs_fakepileup2_dzpvsigcut_pt", "effic_vs_dzpvsigcut_pt", FakeDuplicate("fakepileup_vs_dzpvsigcut_pt", assoc="num_assoc(recoToSim)_dzpvsigcut_pt", reco="num_reco_dzpvsigcut_pt", dup="num_pileup_dzpvsigcut_pt"), zaxis=True),
303  xtitle="Efficiency (p_{T} weighted)", ztitle="Cut on dz(PV)/dzError", **_common2),
304 ], onlyForPileup=True,
305  legendDy=_legendDy_4rows
306 )
307 _pvassociation2 = PlotGroup("pvassociation2", [
308  Plot("effic_vs_dzpvcut", xtitle="Cut on dz(PV) (cm)", ytitle="Efficiency vs. cut on dz(PV)", ymax=_maxEff),
309  Plot("effic_vs_dzpvcut2", xtitle="Cut on dz(PV) (cm)", ytitle="Efficiency (excl. trk eff)", ymax=_maxEff),
310  Plot("fakerate_vs_dzpvcut", xtitle="Cut on dz(PV) (cm)", ytitle="Fake rate vs. cut on dz(PV)", ymax=_maxFake),
311  Plot("pileuprate_dzpvcut", xtitle="Cut on dz(PV) (cm)", ytitle="Pileup rate vs. cut on dz(PV)", ymax=_maxFake),
312  #
313  Plot("effic_vs_dzpvsigcut", xtitle="Cut on dz(PV)/dzError", ytitle="Efficiency vs. cut on dz(PV)/dzError", ymax=_maxEff),
314  Plot("effic_vs_dzpvsigcut2", xtitle="Cut on dz(PV)/dzError", ytitle="Efficiency (excl. trk eff)", ymax=_maxEff),
315  Plot("fakerate_vs_dzpvsigcut", xtitle="Cut on dz(PV)/dzError", ytitle="Fake rate vs. cut on dz(PV)/dzError", ymax=_maxFake),
316  Plot("pileuprate_dzpvsigcut", xtitle="Cut on dz(PV)/dzError", ytitle="Pileup rate vs. cut on dz(PV)/dzError", ymax=_maxFake),
317 ], onlyForPileup=True,
318  legendDy=_legendDy_4rows
319 )
320 _pvassociation3 = PlotGroup("pvassociation3", [
321  Plot("effic_vs_dzpvcut_pt", xtitle="Cut on dz(PV) (cm)", ytitle="Efficiency (p_{T} weighted)", ymax=_maxEff),
322  Plot("effic_vs_dzpvcut2_pt", xtitle="Cut on dz(PV) (cm)", ytitle="Efficiency (p_{T} weighted, excl. trk eff)", ymax=_maxEff),
323  Plot("fakerate_vs_dzpvcut_pt", xtitle="Cut on dz(PV) (cm)", ytitle="Fake rate (p_{T} weighted)", ymax=_maxFake),
324  Plot("pileuprate_dzpvcut_pt", xtitle="Cut on dz(PV) (cm)", ytitle="Pileup rate (p_{T} weighted)", ymax=_maxFake),
325  #
326  Plot("effic_vs_dzpvsigcut_pt", xtitle="Cut on dz(PV)/dzError", ytitle="Efficiency (p_{T} weighted)", ymax=_maxEff),
327  Plot("effic_vs_dzpvsigcut2_pt", xtitle="Cut on dz(PV)/dzError", ytitle="Efficiency (p_{T} weighted, excl. trk eff)", ymax=_maxEff),
328  Plot("fakerate_vs_dzpvsigcut_pt", xtitle="Cut on dz(PV)/dzError", ytitle="Fake rate (p_{T} weighted)", ymax=_maxFake),
329  Plot("pileuprate_dzpvsigcut_pt", xtitle="Cut on dz(PV)/dzError", ytitle="Pileup rate (p_{T} weighted)", ymax=_maxFake),
330 ], onlyForPileup=True,
331  legendDy=_legendDy_4rows
332 )
333 
334 
335 # These don't exist in FastSim
336 _common = {"normalizeToUnitArea": True, "stat": True, "drawStyle": "hist"}
337 _dedx = PlotGroup("dedx", [
338  Plot("h_dedx_estim1", xtitle="dE/dx, harm2", **_common),
339  Plot("h_dedx_estim2", xtitle="dE/dx, trunc40", **_common),
340  Plot("h_dedx_nom1", xtitle="dE/dx number of measurements", title="", **_common),
341  Plot("h_dedx_sat1", xtitle="dE/dx number of measurements with saturation", title="", **_common),
342  ],
343  legendDy=_legendDy_2rows
344 )
345 
346 _chargemisid = PlotGroup("chargemisid", [
347  Plot("chargeMisIdRate", xtitle="#eta", ytitle="charge mis-id rate vs #eta", ymax=0.05),
348  Plot("chargeMisIdRate_Pt", xtitle="p_{T}", ytitle="charge mis-id rate vs p_{T}", xmax=300, ymax=0.1, xlog=True),
349  Plot("chargeMisIdRate_hit", xtitle="hits", ytitle="charge mis-id rate vs hits", title=""),
350  Plot("chargeMisIdRate_phi", xtitle="#phi", ytitle="charge mis-id rate vs #phi", title="", ymax=0.01),
351  Plot("chargeMisIdRate_dxy", xtitle="dxy", ytitle="charge mis-id rate vs dxy", ymax=0.1),
352  Plot("chargeMisIdRate_dz", xtitle="dz", ytitle="charge mis-id rate vs dz", ymax=0.1)
353 ])
354 _common = {"stat": True, "normalizeToUnitArea": True, "ylog": True, "ymin": 1e-6, "drawStyle": "hist"}
355 _hitsAndPt = PlotGroup("hitsAndPt", [
356  Plot("missing_inner_layers", xmin=_minLayers, xmax=_maxLayers, ymax=1, **_common),
357  Plot("missing_outer_layers", xmin=_minLayers, xmax=_maxLayers, ymax=1, **_common),
358  Plot("hits_eta", xtitle="track #eta", ytitle="<hits> vs #eta", ymin=_minHits, ymax=_maxHits, statyadjust=[0,0,-0.15],
359  fallback={"name": "nhits_vs_eta", "profileX": True}),
360  Plot("hits", stat=True, xtitle="track hits", xmin=_minHits, xmax=_maxHits, ylog=True, ymin=[5e-1, 5, 5e1, 5e2, 5e3], drawStyle="hist"),
361  Plot("num_simul_pT", xtitle="TP p_{T}", xlog=True, ymax=[1e-1, 2e-1, 5e-1, 1], **_common),
362  Plot("num_reco_pT", xtitle="track p_{T}", xlog=True, ymax=[1e-1, 2e-1, 5e-1, 1], **_common)
363 ])
364 _tuning = PlotGroup("tuning", [
365  Plot("chi2", stat=True, normalizeToUnitArea=True, ylog=True, ymin=1e-6, ymax=[0.1, 0.2, 0.5, 1.0001], drawStyle="hist", xtitle="#chi^{2}", ratioUncertainty=False),
366  Plot("chi2_prob", stat=True, normalizeToUnitArea=True, drawStyle="hist", xtitle="Prob(#chi^{2})"),
367  Plot("chi2mean", title="", xtitle="#eta", ytitle="< #chi^{2} / ndf >", ymin=[0, 0.5], ymax=[2, 2.5, 3, 5],
368  fallback={"name": "chi2_vs_eta", "profileX": True}),
369  Plot("ptres_vs_eta_Mean", scale=100, title="", xtitle="TP #eta (PCA to beamline)", ytitle="< #delta p_{T} / p_{T} > (%)", ymin=_minResidualPt, ymax=_maxResidualPt)
370 ])
371 _common = {"stat": True, "fit": True, "normalizeToUnitArea": True, "drawStyle": "hist", "drawCommand": "", "xmin": -10, "xmax": 10, "ylog": True, "ymin": 5e-5, "ymax": [0.01, 0.05, 0.1, 0.2, 0.5, 0.8, 1.025], "ratioUncertainty": False}
372 _pulls = PlotGroup("pulls", [
373  Plot("pullPt", **_common),
374  Plot("pullQoverp", **_common),
375  Plot("pullPhi", **_common),
376  Plot("pullTheta", **_common),
377  Plot("pullDxy", **_common),
378  Plot("pullDz", **_common),
379 ],
380  legendDx=0.1, legendDw=-0.1, legendDh=-0.015
381 )
382 _common = {"title": "", "ylog": True, "xtitle": "TP #eta (PCA to beamline)", "ymin": _minMaxResol, "ymax": _minMaxResol}
383 _resolutionsEta = PlotGroup("resolutionsEta", [
384  Plot("phires_vs_eta_Sigma", ytitle="#sigma(#delta #phi) (rad)", **_common),
385  Plot("cotThetares_vs_eta_Sigma", ytitle="#sigma(#delta cot(#theta))", **_common),
386  Plot("dxyres_vs_eta_Sigma", ytitle="#sigma(#delta d_{xy}) (cm)", **_common),
387  Plot("dzres_vs_eta_Sigma", ytitle="#sigma(#delta d_{z}) (cm)", **_common),
388  Plot("ptres_vs_eta_Sigma", ytitle="#sigma(#delta p_{T}/p_{T})", **_common),
389 ])
390 _common = {"title": "", "ylog": True, "xlog": True, "xtitle": "TP p_{T} (PCA to beamline)", "xmin": 0.1, "xmax": 1000, "ymin": _minMaxResol, "ymax": _minMaxResol}
391 _resolutionsPt = PlotGroup("resolutionsPt", [
392  Plot("phires_vs_pt_Sigma", ytitle="#sigma(#delta #phi) (rad)", **_common),
393  Plot("cotThetares_vs_pt_Sigma", ytitle="#sigma(#delta cot(#theta))", **_common),
394  Plot("dxyres_vs_pt_Sigma", ytitle="#sigma(#delta d_{xy}) (cm)", **_common),
395  Plot("dzres_vs_pt_Sigma", ytitle="#sigma(#delta d_{z}) (cm)", **_common),
396  Plot("ptres_vs_pt_Sigma", ytitle="#sigma(#delta p_{T}/p_{T})", **_common),
397 ])
398 
399 ## Extended set of plots
400 _extDistPtEtaPhi = PlotGroup("distPtEtaPhi",
401  _makeDistPlots("pT", "p_{T} (GeV)", common=dict(xlog=True)) +
402  _makeDistPlots("eta", "#eta") +
403  _makeDistPlots("phi", "#phi"),
404  ncols=4)
405 _extDistDxyDzBS = PlotGroup("distDxyDzBS",
406  _makeDistPlots("dxy" , "dxy (cm)") +
407  _makeDistPlots("dz" , "dz (cm)"),
408  ncols=4, legendDy=_legendDy_2rows)
409 _extDistDxyDzPV = PlotGroup("distDxyDzPV",
410  _makeDistPlots("dxypv" , "dxy(PV) (cm)") +
411  _makeDistPlots("dxypv_zoomed", "dxy(PV) (cm)") +
412  _makeDistPlots("dzpv" , "dz(PV) (cm)") +
413  _makeDistPlots("dzpv_zoomed" , "dz(PV) (cm)"),
414  ncols=4, legendDy=_legendDy_4rows)
415 _extDistHitsLayers = PlotGroup("distHitsLayers",
416  _makeDistPlots("hit" , "hits" , common=dict(xmin=_minHits , xmax=_maxHits)) +
417  _makeDistPlots("layer" , "layers" , common=dict(xmin=_minLayers , xmax=_maxLayers)) +
418  _makeDistPlots("pixellayer", "pixel layers", common=dict( xmax=_maxPixelLayers)) +
419  _makeDistPlots("3Dlayer" , "3D layers" , common=dict(xmin=_min3DLayers, xmax=_max3DLayers)),
420  ncols=4, legendDy=_legendDy_4rows,
421 )
422 _extDistPosDeltaR = PlotGroup("distPosDeltaR",
423  _makeDistPlots("vertpos", "ref. point r (cm)", common=dict(xlog=True)) +
424  _makeDistPlots("zpos" , "ref. point z (cm)") +
425  _makeDistPlots("simpvz" , "Sim. PV z (cm)", common=dict(xmin=_minZ, xmax=_maxZ)) +
426  _makeDistPlots("dr" , "min #DeltaR", common=dict(xlog=True)),
427  ncols=4, legendDy=_legendDy_4rows,
428 )
429 _extDistSeedingPlots = _makeDistPlots("seedingLayerSet", "seeding layers", common=dict(xtitle="", **_seedingLayerSet_common))
430 _extDistChi2Seeding = PlotGroup("distChi2Seeding",
431  _makeDistPlots("chi2", "#chi^{2}") +
432  _extDistSeedingPlots,
433  ncols=4, legendDy=_legendDy_2rows_3cols
434 )
435 _common = dict(title="", xtitle="TP #eta (PCA to beamline)")
436 _extResidualEta = PlotGroup("residualEta", [
437  Plot("phires_vs_eta_Mean", ytitle="< #delta #phi > (rad)", ymin=_minResidualPhi, ymax=_maxResidualPhi, **_common),
438  Plot("cotThetares_vs_eta_Mean", ytitle="< #delta cot(#theta) >", ymin=_minResidualCotTheta, ymax=_maxResidualCotTheta, **_common),
439  Plot("dxyres_vs_eta_Mean", ytitle="< #delta d_{xy} > (#mum)", scale=10000, ymin=_minResidualDxy, ymax=_maxResidualDxy, **_common),
440  Plot("dzres_vs_eta_Mean", ytitle="< #delta d_{z} > (#mum)", scale=10000, ymin=_minResidualDz, ymax=_maxResidualDz, **_common),
441  Plot("ptres_vs_eta_Mean", ytitle="< #delta p_{T}/p_{T} > (%)", scale=100, ymin=_minResidualPt, ymax=_maxResidualPt, **_common), # same as in tuning, but to be complete
442 ])
443 _common = dict(title="", xlog=True, xtitle="TP p_{T} (PCA to beamline)", xmin=0.1, xmax=1000)
444 _extResidualPt = PlotGroup("residualPt", [
445  Plot("phires_vs_pt_Mean", ytitle="< #delta #phi > (rad)", ymin=_minResidualPhi, ymax=_maxResidualPhi, **_common),
446  Plot("cotThetares_vs_pt_Mean", ytitle="< #delta cot(#theta > )", ymin=_minResidualCotTheta, ymax=_maxResidualCotTheta, **_common),
447  Plot("dxyres_vs_pt_Mean", ytitle="< #delta d_{xy} > (#mum)", scale=10000, ymin=_minResidualDxy, ymax=_maxResidualDxy, **_common),
448  Plot("dzres_vs_pt_Mean", ytitle="< #delta d_{z} > (#mum)", scale=10000, ymin=_minResidualDz, ymax=_maxResidualDz, **_common),
449  Plot("ptres_vs_pt_Mean", ytitle="< #delta p_{T}/p_{T} > (%)", scale=100, ymin=_minResidualPt, ymax=_maxResidualPt, **_common), # same as in tuning, but to be complete
450 ])
451 _common = dict(title="", ytitle="Selected tracks/TrackingParticles", ymax=_maxEff)
452 _extNrecVsNsim = PlotGroup("nrecVsNsim", [
453  Plot("nrec_vs_nsim", title="", xtitle="TrackingParticles", ytitle="Tracks", profileX=True, xmin=_minMaxTracks, xmax=_minMaxTracks, ymin=_minMaxTracks, ymax=_minMaxTracks),
454  Plot("nrecPerNsim_vs_pu", xtitle="Pileup", xmin=_minPU, xmax=_maxPU, **_common),
455  Plot("nrecPerNsimPt", xtitle="p_{T} (GeV)", xlog=True, **_common),
456  Plot("nrecPerNsim", xtitle="#eta", **_common)
457 ], legendDy=_legendDy_2rows)
458 _extHitsLayers = PlotGroup("hitsLayers", [
459  Plot("PXLhits_vs_eta", xtitle="#eta", ytitle="<pixel hits>"),
460  Plot("PXLlayersWithMeas_vs_eta", xtitle="#eta", ytitle="<pixel layers>"),
461  Plot("STRIPhits_vs_eta", xtitle="#eta", ytitle="<strip hits>"),
462  Plot("STRIPlayersWithMeas_vs_eta", xtitle="#eta", ytitle="<strip layers>"),
463 ], legendDy=_legendDy_2rows)
464 
465 
466 ## Extended set of plots also for simulation
467 _extDistSimPtEtaPhi = PlotGroup("distsimPtEtaPhi",
468  _makeDistSimPlots("pT", "p_{T} (GeV)", common=dict(xlog=True)) +
469  _makeDistSimPlots("eta", "#eta") +
470  _makeDistSimPlots("phi", "#phi"),
471  ncols=2)
472 _extDistSimDxyDzBS = PlotGroup("distsimDxyDzBS",
473  _makeDistSimPlots("dxy" , "dxy (cm)") +
474  _makeDistSimPlots("dz" , "dz (cm)"),
475  ncols=2, legendDy=_legendDy_2rows)
476 _extDistSimDxyDzPV = PlotGroup("distsimDxyDzPV",
477  _makeDistSimPlots("dxypv" , "dxy(PV) (cm)") +
478  _makeDistSimPlots("dxypv_zoomed", "dxy(PV) (cm)") +
479  _makeDistSimPlots("dzpv" , "dz(PV) (cm)") +
480  _makeDistSimPlots("dzpv_zoomed" , "dz(PV) (cm)"),
481  ncols=2, legendDy=_legendDy_4rows)
482 _extDistSimHitsLayers = PlotGroup("distsimHitsLayers",
483  _makeDistSimPlots("hit" , "hits" , common=dict(xmin=_minHits , xmax=_maxHits)) +
484  _makeDistSimPlots("layer" , "layers" , common=dict(xmin=_minLayers , xmax=_maxLayers)) +
485  _makeDistSimPlots("pixellayer", "pixel layers", common=dict( xmax=_maxPixelLayers)) +
486  _makeDistSimPlots("3Dlayer" , "3D layers" , common=dict(xmin=_min3DLayers, xmax=_max3DLayers)),
487  ncols=2, legendDy=_legendDy_4rows,
488 )
489 _extDistSimPosDeltaR = PlotGroup("distsimPosDeltaR",
490  _makeDistSimPlots("vertpos", "vert r (cm)", common=dict(xlog=True)) +
491  _makeDistSimPlots("zpos" , "vert z (cm)") +
492  _makeDistSimPlots("simpvz" , "Sim. PV z (cm)", common=dict(xmin=_minZ, xmax=_maxZ)) +
493  _makeDistSimPlots("dr" , "min #DeltaR", common=dict(xlog=True)),
494  ncols=2, legendDy=_legendDy_4rows,
495 )
496 
497 ########################################
498 #
499 # Summary plots
500 #
501 ########################################
502 
503 _possibleTrackingNonIterationColls = [
504  'ak4PFJets',
505  'btvLike',
506 ]
507 _possibleTrackingColls = [
508  'initialStepPreSplitting',
509  'initialStep',
510  'highPtTripletStep', # phase1
511  'detachedQuadStep', # phase1
512  'detachedTripletStep',
513  'lowPtQuadStep', # phase1
514  'lowPtTripletStep',
515  'pixelPairStepA', # seeds
516  'pixelPairStepB', # seeds
517  'pixelPairStepC', # seeds
518  'pixelPairStep',
519  'mixedTripletStepA', # seeds
520  'mixedTripletStepB', # seeds
521  'mixedTripletStep',
522  'pixelLessStep',
523  'tobTecStepPair', # seeds
524  'tobTecStepTripl', # seeds
525  'tobTecStep',
526  'jetCoreRegionalStep',
527  'muonSeededStepInOut',
528  'muonSeededStepOutIn',
529  'duplicateMerge',
530 ] + _possibleTrackingNonIterationColls
531 _possibleTrackingCollsOld = {
532  "Zero" : "iter0",
533  "First" : "iter1",
534  "Second": "iter2",
535  "Third" : "iter3",
536  "Fourth": "iter4",
537  "Fifth" : "iter5",
538  "Sixth" : "iter6",
539  "Seventh": "iter7",
540  "Ninth" : "iter9",
541  "Tenth" : "iter10",
542 }
543 
545  ret = subfolder.replace("trackingParticleRecoAsssociation", "AssociatorByHitsRecoDenom")
546  for (old, new) in [("InitialStep", "Zero"),
547  ("HighPtTripletStep", "First"),
548  ("LowPtQuadStep", "Second"),
549  ("LowPtTripletStep", "Third"),
550  ("DetachedQuadStep", "Fourth"),
551  ("PixelPairStep", "Fifth"),
552  ("MuonSeededStepInOut", "Ninth"),
553  ("MuonSeededStepOutIn", "Tenth")]:
554  ret = ret.replace(old, new)
555  if ret == subfolder:
556  return None
557  return ret
559  for (old, new) in [("initialStep", "iter0"),
560  ("highPtTripletStep", "iter1"),
561  ("lowPtQuadStep", "iter2"),
562  ("lowPtTripletStep", "iter3"),
563  ("detachedQuadStep", "iter4"),
564  ("pixelPairStep", "iter5"),
565  ("muonSeededStepInOut", "iter9"),
566  ("muonSeededStepOutIn", "iter10")]:
567  path = path.replace(old, new)
568  return path
569 
571  return subfolder.replace("trackingParticleRecoAsssociation", "trackingParticleRecoAsssociationSignal")
573  return subfolder.replace("quickAssociatorByHits", "quickAssociatorByHitsConversion")
574 
575 # Additional "quality" flags than highPurity. In a separate list to
576 # allow customization.
577 _additionalTrackQualities = [
578  "Pt09",
579  "ByOriginalAlgo",
580  "ByAlgoMask"
581 ]
583  if "Hp" in collName:
584  quality = "highPurity"
585  else:
586  quality = ""
587  collNameNoQuality = collName.replace("Hp", "")
588  for qual in _additionalTrackQualities:
589  if qual in collName:
590  quality += qual
591  collNameNoQuality = collNameNoQuality.replace(qual, "")
592 
593  collNameNoQuality = collNameNoQuality.replace("Tracks", "", 1) # make summary naming consistent with iteration folders
594  collNameLow = collNameNoQuality.lower().replace("frompv2", "").replace("frompv", "").replace("frompvalltp", "").replace("alltp", "")
595 
596  if collNameLow.find("seed") == 0:
597  collNameLow = collNameLow[4:]
598  if collNameLow == "initialstepseedspresplitting":
599  collNameLow = "initialsteppresplittingseeds"
600  elif collNameLow == "muonseededseedsinout":
601  collNameLow = "muonseededstepinoutseeds"
602  elif collNameLow == "muonseededseedsoutin":
603  collNameLow = "muonseededstepoutinseeds"
604 
605  i_seeds = collNameLow.index("seeds")
606  quality = collNameLow[i_seeds:]+quality
607 
608  collNameLow = collNameLow[:i_seeds]
609 
610  algo = None
611  prefixes = ["cutsreco", "cutsrecofrompv", "cutsrecofrompv2", "cutsrecofrompvalltp"]
612  if collNameLow in ["general", "generalfrompv"]+prefixes:
613  algo = "ootb"
614  else:
615  def testColl(coll):
616  for pfx in prefixes:
617  if coll == collNameLow.replace(pfx, ""):
618  return True
619  return False
620 
621  for coll in _possibleTrackingColls:
622  if testColl(coll.lower()):
623  algo = coll
624  break
625  # next try "old style"
626  if algo is None:
627  for coll, name in _possibleTrackingCollsOld.iteritems():
628  if testColl(coll.lower()):
629  algo = name
630  break
631 
632  # fallback
633  if algo is None:
634  algo = collNameNoQuality
635 
636  # fix for track collection naming convention
637  if algo == "muonSeededInOut":
638  algo = "muonSeededStepInOut"
639  if algo == "muonSeededOutIn":
640  algo = "muonSeededStepOutIn"
641 
642  return (algo, quality)
643 
644 def _collhelper(name):
645  return (name, [name])
646 _collLabelMap = collections.OrderedDict(map(_collhelper, ["generalTracks"]+_possibleTrackingColls))
647 _collLabelMapHp = collections.OrderedDict(map(_collhelper, ["generalTracks"]+filter(lambda n: "Step" in n, _possibleTrackingColls)))
648 def _summaryBinRename(binLabel, highPurity, byOriginalAlgo, byAlgoMask, ptCut, seeds):
649  (algo, quality) = _mapCollectionToAlgoQuality(binLabel)
650  if algo == "ootb":
651  algo = "generalTracks"
652  ret = None
653 
654  if byOriginalAlgo:
655  if algo != "generalTracks" and "ByOriginalAlgo" not in quality: # keep generalTracks bin as well
656  return None
657  quality = quality.replace("ByOriginalAlgo", "")
658  if byAlgoMask:
659  if algo != "generalTracks" and "ByAlgoMask" not in quality: # keep generalTracks bin as well
660  return None
661  quality = quality.replace("ByAlgoMask", "")
662  if ptCut:
663  if "Pt09" not in quality:
664  return None
665  quality = quality.replace("Pt09", "")
666 
667  if highPurity:
668  if quality == "highPurity":
669  ret = algo
670  elif seeds:
671  i_seeds = quality.find("seeds")
672  if i_seeds == 0:
673  ret = algo
674  seedSubColl = quality[i_seeds+5:]
675  if seedSubColl != "":
676  ret += seedSubColl[0].upper() + seedSubColl[1:]
677  else:
678  if quality == "":
679  ret = algo
680 
681  return ret
682 
683 def _constructSummary(mapping=None, highPurity=False, byOriginalAlgo=False, byAlgoMask=False, ptCut=False, seeds=False, midfix=""):
684  _common = {"drawStyle": "EP", "xbinlabelsize": 10, "xbinlabeloption": "d"}
685  _commonN = dict(ylog=True, ymin=_minMaxN, ymax=_minMaxN,
686  normalizeToNumberOfEvents=True,
687  )
688  _commonN.update(_common)
689  _commonAB = dict(mapping=mapping,
690  renameBin=lambda bl: _summaryBinRename(bl, highPurity, byOriginalAlgo, byAlgoMask, ptCut, seeds),
691  ignoreMissingBins=True,
692  originalOrder=True,
693  )
694  if byOriginalAlgo or byAlgoMask:
695  _commonAB["minExistingBins"] = 2
696  prefix = "summary"+midfix
697 
698  h_eff = "effic_vs_coll"
699  h_fakerate = "fakerate_vs_coll"
700  h_duplicaterate = "duplicatesRate_coll"
701  h_pileuprate = "pileuprate_coll"
702 
703  h_reco = "num_reco_coll"
704  h_true = "num_assoc(recoToSim)_coll"
705  h_fake = Subtract("num_fake_coll_orig", "num_reco_coll", "num_assoc(recoToSim)_coll")
706  h_duplicate = "num_duplicate_coll"
707  h_pileup = "num_pileup_coll"
708  if mapping is not None:
709  h_eff = AggregateBins("efficiency", h_eff, **_commonAB)
710  h_fakerate = AggregateBins("fakerate", h_fakerate, **_commonAB)
711  h_duplicaterate = AggregateBins("duplicatesRate", h_duplicaterate, **_commonAB)
712  h_pileuprate = AggregateBins("pileuprate", h_pileuprate, **_commonAB)
713 
714  h_reco = AggregateBins("num_reco_coll", h_reco, **_commonAB)
715  h_true = AggregateBins("num_true_coll", h_true, **_commonAB)
716  h_fake = AggregateBins("num_fake_coll", h_fake, **_commonAB)
717  h_duplicate = AggregateBins("num_duplicate_coll", h_duplicate, **_commonAB)
718  h_pileup = AggregateBins("num_pileup_coll", h_pileup, **_commonAB)
719 
720  summary = PlotGroup(prefix, [
721  Plot(h_eff, title="Efficiency vs collection", ytitle="Efficiency", ymin=1e-3, ymax=1, ylog=True, **_common),
722  Plot(h_fakerate, title="Fakerate vs collection", ytitle="Fake rate", ymax=_maxFake, **_common),
723  #
724  Plot(h_duplicaterate, title="Duplicates rate vs collection", ytitle="Duplicates rate", ymax=_maxFake, **_common),
725  Plot(h_pileuprate, title="Pileup rate vs collection", ytitle="Pileup rate", ymax=_maxFake, **_common),
726  ],
727  legendDy=_legendDy_2rows
728  )
729  summaryN = PlotGroup(prefix+"_ntracks", [
730  # FIXME
731  #Plot(h_reco, ytitle="Tracks/event", title="Number of tracks/event vs collection", **_commonN),
732  #Plot(h_true, ytitle="True tracks/event", title="Number of true tracks/event vs collection", **_commonN),
733  #Plot(h_fake, ytitle="Fake tracks/event", title="Number of fake tracks/event vs collection", **_commonN),
734  #Plot(h_duplicate, ytitle="Duplicate tracks/event", title="Number of duplicate tracks/event vs collection", **_commonN),
735  #Plot(h_pileup, ytitle="Pileup tracks/event", title="Number of pileup tracks/event vs collection", **_commonN),
736  Plot(h_reco, ytitle="Tracks", title="Number of tracks vs collection", **_commonN),
737  Plot(h_true, ytitle="True tracks", title="Number of true tracks vs collection", **_commonN),
738  Plot(h_fake, ytitle="Fake tracks", title="Number of fake tracks vs collection", **_commonN),
739  Plot(h_duplicate, ytitle="Duplicate tracks", title="Number of duplicate tracks vs collection", **_commonN),
740  Plot(h_pileup, ytitle="Pileup tracks", title="Number of pileup tracks vs collection", **_commonN),
741  ])
742 
743  return (summary, summaryN)
744 
745 (_summaryRaw, _summaryRawN) = _constructSummary(midfix="Raw")
746 (_summary, _summaryN) = _constructSummary(_collLabelMap)
747 (_summaryHp, _summaryNHp) = _constructSummary(_collLabelMapHp, highPurity=True)
748 (_summaryByOriginalAlgo, _summaryByOriginalAlgoN) = _constructSummary(_collLabelMapHp, byOriginalAlgo=True, midfix="ByOriginalAlgo")
749 (_summaryByOriginalAlgoHp, _summaryByOriginalAlgoNHp) = _constructSummary(_collLabelMapHp, byOriginalAlgo=True, midfix="ByOriginalAlgo", highPurity=True)
750 (_summaryByAlgoMask, _summaryByAlgoMaskN) = _constructSummary(_collLabelMapHp, byAlgoMask=True, midfix="ByAlgoMask")
751 (_summaryByAlgoMaskHp, _summaryByAlgoMaskNHp) = _constructSummary(_collLabelMapHp, byAlgoMask=True, midfix="ByAlgoMask", highPurity=True)
752 (_summaryPt09, _summaryPt09N) = _constructSummary(_collLabelMap, ptCut=True, midfix="Pt09")
753 (_summaryPt09Hp, _summaryPt09NHp) = _constructSummary(_collLabelMap, ptCut=True, midfix="Pt09", highPurity=True)
754 (_summarySeeds, _summarySeedsN) = _constructSummary(_collLabelMapHp, seeds=True)
755 
756 ########################################
757 #
758 # PackedCandidate plots
759 #
760 ########################################
761 
762 _common = {"normalizeToUnitArea": True, "ylog": True, "ymin": [1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2], "ymax": [1e-2, 1e-1, 1.1]}
763 _commonStatus = {}
764 _commonStatus.update(_common)
765 _commonStatus.update({"xbinlabelsize": 10, "xbinlabeloption": "d", "drawStyle": "hist", "adjustMarginRight": 0.08})
766 _commonLabelSize = {}
767 _commonLabelSize.update(_common)
768 _commonLabelSize.update({"xlabelsize": 17})
769 
770 _packedCandidateFlow = PlotGroup("flow", [
771  Plot("selectionFlow", xbinlabelsize=10, xbinlabeloption="d", adjustMarginRight=0.1, drawStyle="hist", ylog=True, ymin=[0.9, 9, 9e1, 9e2, 9e3, 9e4, 9e5, 9e6, 9e7]),
772  Plot("diffCharge", xtitle="Charge", **_common),
773  Plot("diffIsHighPurity", xtitle="High purity status", **_common),
774  Plot("diffNdof", xtitle="ndof", **_common),
775  Plot("diffNormalizedChi2", xtitle="#chi^{2}/ndof", **_common),
776 ])
777 
778 _packedCandidateHitsHitPattern = PlotGroup("hitsHitPattern", [
779  Plot("diffHitPatternNumberOfValidHits", xtitle="Valid hits (via HitPattern)", **_common),
780  Plot("diffHitPatternNumberOfValidPixelHits", xtitle="Valid pixel hits (via HitPattern)", **_common),
781  Plot("diffHitPatternHasValidHitInFirstPixelBarrel", xtitle="Has valid hit in BPix1 layer (via HitPattern)", **_common),
782  Plot("diffHitPatternNumberOfLostPixelHits", xtitle="Lost pixel hits (via HitPattern)", **_common),
783 ],
784  legendDy=_legendDy_2rows
785 )
786 _packedCandidateHits = PlotGroup("hits", [
787  Plot("diffNumberOfHits", xtitle="Hits", **_common),
788  Plot("diffNumberOfPixelHits", xtitle="Pixel hits", **_common),
789  Plot("diffLostInnerHits", xtitle="Lost inner hits", **_common),
790  Plot("numberHitsOverMax", xtitle="Number of overflown hits", **_common),
791  Plot("numberPixelHitsOverMax", xtitle="Number of overflown pixel hits", **_common),
792  Plot("numberStripHitsOverMax", xtitle="Number of overflown strip hits", **_common),
793 ],
794  ncols=3, legendDy=_legendDy_2rows_3cols
795 )
796 
797 _packedCandidateLayers = PlotGroup("layers", [
798  PlotEmpty(),
799  Plot("diffNumberOfPixelLayers", xtitle="Pixel layers", **_common),
800  Plot("diffNumberOfStripLayers", xtitle="Strip layers", **_common),
801  #
802  Plot("diffHitPatternTrackerLayersWithMeasurement", xtitle="Layers (via HitPattern)", **_common),
803  Plot("diffHitPatternPixelLayersWithMeasurement", xtitle="Pixel layers (via HitPattern)", **_common),
804  Plot("diffHitPatternStripLayersWithMeasurement", xtitle="Strip layers (via HitPattern)", **_common),
805  #
806  Plot("numberLayersOverMax", xtitle="Number of overflown layers", **_common),
807  Plot("numberPixelLayersOverMax", xtitle="Number of overflown pixel layers", **_common),
808  Plot("numberStripLayersOverMax", xtitle="Number of overflown strip layers", **_common),
809 ],
810  ncols=3
811 )
812 
813 
814 _packedCandidateImpactParameter1 = PlotGroup("impactParameter1", [
815  Plot("diffDxyAssocPV", xtitle="dxy(assocPV)", adjustMarginRight=0.02, **_commonLabelSize),
816  Plot("diffDxyAssocPVStatus", **_commonStatus),
817  Plot("diffDxyAssocPVUnderOverFlowSign", xtitle="dxy(assocPV)", **_common),
818  Plot("diffDzAssocPV", xtitle="dz(assocPV)", adjustMarginRight=0.02, **_commonLabelSize),
819  Plot("diffDzAssocPVStatus", **_commonStatus),
820  Plot("diffDzAssocPVUnderOverFlowSign", xtitle="dz(assocPV)", **_common),
821  Plot("diffDxyError", xtitle="dxyError()", adjustMarginRight=0.02, **_commonLabelSize),
822  Plot("diffDszError", xtitle="dszError()", adjustMarginRight=0.02, **_commonLabelSize),
823  Plot("diffDzError", xtitle="dzError()", adjustMarginRight=0.02, **_commonLabelSize),
824 
825 ],
826  ncols=3
827 )
828 
829 _packedCandidateImpactParameter2 = PlotGroup("impactParameter2", [
830  Plot("diffDxyPV", xtitle="dxy(PV) via PC", **_commonLabelSize),
831  Plot("diffDzPV", xtitle="dz(PV) via PC", **_commonLabelSize),
832  Plot("diffTrackDxyAssocPV", xtitle="dxy(PV) via PC::bestTrack()", **_commonLabelSize),
833  Plot("diffTrackDzAssocPV", xtitle="dz(PV) via PC::bestTrack()", **_commonLabelSize),
834  Plot("diffTrackDxyError", xtitle="dxyError() via PC::bestTrack()", adjustMarginRight=0.02, **_commonLabelSize),
835  Plot("diffTrackDzError", xtitle="dzError() via PC::bestTrack()", **_commonLabelSize),
836 ])
837 
838 _packedCandidateCovarianceMatrix1 = PlotGroup("covarianceMatrix1", [
839  Plot("diffCovQoverpQoverp", xtitle="cov(qoverp, qoverp)", **_commonLabelSize),
840  Plot("diffCovQoverpQoverpStatus", **_commonStatus),
841  Plot("diffCovQoverpQoverpUnderOverFlowSign", xtitle="cov(qoverp, qoverp)", **_common),
842  Plot("diffCovLambdaLambda", xtitle="cov(lambda, lambda)", **_commonLabelSize),
843  Plot("diffCovLambdaLambdaStatus", **_commonStatus),
844  Plot("diffCovLambdaLambdaUnderOverFlowSign", xtitle="cov(lambda, lambda)", **_common),
845  Plot("diffCovLambdaDsz", xtitle="cov(lambda, dsz)", **_commonLabelSize),
846  Plot("diffCovLambdaDszStatus", **_commonStatus),
847  Plot("diffCovLambdaDszUnderOverFlowSign", xtitle="cov(lambda, dsz)", **_common),
848  Plot("diffCovPhiPhi", xtitle="cov(phi, phi)", **_commonLabelSize),
849  Plot("diffCovPhiPhiStatus", **_commonStatus),
850  Plot("diffCovPhiPhiUnderOverFlowSign", xtitle="cov(phi, phi)", **_common),
851 ],
852  ncols=3, legendDy=_legendDy_4rows
853 )
854 _packedCandidateCovarianceMatrix2 = PlotGroup("covarianceMatrix2", [
855  Plot("diffCovPhiDxy", xtitle="cov(phi, dxy)", **_commonLabelSize),
856  Plot("diffCovPhiDxyStatus", **_commonStatus),
857  Plot("diffCovPhiDxyUnderOverFlowSign", xtitle="cov(phi, dxy)", **_common),
858  Plot("diffCovDxyDxy", xtitle="cov(dxy, dxy)", adjustMarginRight=0.02, **_commonLabelSize),
859  Plot("diffCovDxyDxyStatus", **_commonStatus),
860  Plot("diffCovDxyDxyUnderOverFlowSign", xtitle="cov(dxy, dxy)", **_common),
861  Plot("diffCovDxyDsz", xtitle="cov(dxy, dsz)", adjustMarginRight=0.02, **_commonLabelSize),
862  Plot("diffCovDxyDszStatus", **_commonStatus),
863  Plot("diffCovDxyDszUnderOverFlowSign", xtitle="cov(dxy, dsz)", **_common),
864  Plot("diffCovDszDsz", xtitle="cov(dsz, dsz)", adjustMarginRight=0.02, **_commonLabelSize),
865  Plot("diffCovDszDszStatus", **_commonStatus),
866  Plot("diffCovDszDszUnderOverFlowSign", xtitle="cov(dsz, dsz)", **_common),
867 ],
868  ncols=3, legendDy=_legendDy_4rows
869 )
870 
871 _common["xlabelsize"] = 16
872 _packedCandidateVertex = PlotGroup("vertex", [
873  Plot("diffVx", xtitle="Reference point x", **_common),
874  Plot("diffVy", xtitle="Reference point y", **_common),
875  Plot("diffVz", xtitle="Reference point z", **_common),
876 ],
877  legendDy=_legendDy_2rows
878 )
879 
880 _common["adjustMarginRight"] = 0.05
881 _packedCandidateKinematics = PlotGroup("kinematics", [
882  Plot("diffPt", xtitle="p_{T}", **_common),
883  Plot("diffPtError", xtitle="p_{T} error", **_common),
884  Plot("diffEta", xtitle="#eta", **_common),
885  Plot("diffEtaError", xtitle="#eta error", **_common),
886  Plot("diffPhi", xtitle="#phi", **_common),
887 ])
888 
890  def __init__(self, *args, **kwargs):
891  self._fallbackRefFiles = kwargs.pop("fallbackRefFiles", [])
892  PlotFolder.__init__(self, *args, **kwargs)
893 
894  def translateSubFolder(self, dqmSubFolderName):
895  spl = dqmSubFolderName.split("_")
896  if len(spl) != 2:
897  return None
898  collName = spl[0]
899  return _mapCollectionToAlgoQuality(collName)
900 
901  def iterSelectionName(self, plotFolderName, translatedDqmSubFolder):
902  (algoOrig, quality) = translatedDqmSubFolder
903 
904  for fallback in [lambda n: n]+self._fallbackRefFiles:
905  algo = fallback(algoOrig)
906 
907  ret = ""
908  if plotFolderName != "":
909  ret += "_"+plotFolderName
910  if quality != "":
911  ret += "_"+quality
912  if not (algo == "ootb" and quality != ""):
913  ret += "_"+algo
914  yield ret
915 
916  def limitSubFolder(self, limitOnlyTo, translatedDqmSubFolder):
917  """Return True if this subfolder should be processed
918 
919  Arguments:
920  limitOnlyTo -- Function '(algo, quality) -> bool'
921  translatedDqmSubFolder -- Return value of translateSubFolder
922  """
923  (algo, quality) = translatedDqmSubFolder
924  return limitOnlyTo(algo, quality)
925 
926  # track-specific hack
927  def isAlgoIterative(self, algo):
928  return algo not in _possibleTrackingNonIterationColls
929 
931  class GeneralTracks: pass
932  class GeneralTracksPt09: pass
933  class HighPurity: pass
934  class HighPurityPt09: pass
935  class BTVLike: pass
936  class AK4PFJets: pass
937  class Pixel: pass
938 
939  def __init__(self, section, collection=GeneralTracks):
940  self._collection = collection
942  self._page = "summary"
943  self._section = section
944 
945  def getPurpose(self):
946  return self._purpose
947 
948  def getPage(self):
949  return self._page
950 
951  def getSection(self, dqmSubFolder):
952  return self._section
953 
954  def create(self, tdirectory):
955  def _getAlgoQuality(data, algo, quality):
956  for label, value in data.iteritems():
957  (a, q) = _mapCollectionToAlgoQuality(label)
958  if a == algo and q == quality:
959  return value[0] # value is (value, uncertainty) tuple
960  return None
961  def _getN(hname):
962  h = tdirectory.Get(hname)
963  if not h:
964  return None
967  return _getAlgoQuality(data, "ootb", "")
969  return _getAlgoQuality(data, "ootb", "Pt09")
971  return _getAlgoQuality(data, "ootb", "highPurity")
973  return _getAlgoQuality(data, "ootb", "highPurityPt09")
975  return _getAlgoQuality(data, "btvLike", "")
977  return _getAlgoQuality(data, "ak4PFJets", "")
979  return _getAlgoQuality(data, "pixel", "")
980  else:
981  raise Exception("Collection not recognized, %s" % str(self._collection))
982  def _formatOrNone(num, func):
983  if num is None:
984  return None
985  return func(num)
986 
987  n_tps = _formatOrNone(_getN("num_simul_coll"), int)
988  n_m_tps = _formatOrNone(_getN("num_assoc(simToReco)_coll"), int)
989 
990  n_tracks = _formatOrNone(_getN("num_reco_coll"), int)
991  n_true = _formatOrNone(_getN("num_assoc(recoToSim)_coll"), int)
992  if n_tracks is not None and n_true is not None:
993  n_fake = n_tracks-n_true
994  else:
995  n_fake = None
996  n_pileup = _formatOrNone(_getN("num_pileup_coll"), int)
997  n_duplicate = _formatOrNone(_getN("num_duplicate_coll"), int)
998 
999  eff = _formatOrNone(_getN("effic_vs_coll"), lambda n: "%.4f" % n)
1000  eff_nopt = _formatOrNone(_getN("effic_vs_coll_allPt"), lambda n: "%.4f" % n)
1001  fake = _formatOrNone(_getN("fakerate_vs_coll"), lambda n: "%.4f" % n)
1002  duplicate = _formatOrNone(_getN("duplicatesRate_coll"), lambda n: "%.4f" % n)
1003 
1004  ret = [eff, n_tps, n_m_tps,
1005  eff_nopt, fake, duplicate,
1006  n_tracks, n_true, n_fake, n_pileup, n_duplicate]
1007  if ret.count(None) == len(ret):
1008  return None
1009  return ret
1010 
1011  def headers(self):
1012  return [
1013  "Efficiency",
1014  "Number of TrackingParticles (after cuts)",
1015  "Number of matched TrackingParticles",
1016  "Efficiency (w/o pT cut)",
1017  "Fake rate",
1018  "Duplicate rate",
1019  "Number of tracks",
1020  "Number of true tracks",
1021  "Number of fake tracks",
1022  "Number of pileup tracks",
1023  "Number of duplicate tracks"
1024  ]
1025 
1026 # Provide a "PlotGroup" interface, but provide a html page
1028  def __init__(self, fileName, plots, titles, isRate, **kwargs):
1029  self._plots = plots
1030  self._titles = titles
1031  self._fileName = fileName
1032  self._format = "%.4g" if isRate else "%d"
1033 
1034  if len(plots) != len(titles):
1035  raise Exception("Number of plots (%d) has to be the same as number of titles (%d)" % (len(plots), len(titles)))
1036 
1037  def _set(attr, default):
1038  setattr(self, "_"+attr, kwargs.get(attr, default))
1039 
1040  _set("onlyForPileup", False)
1041 
1042  def onlyForPileup(self):
1043  """Return True if the PlotGroup is intended only for pileup samples"""
1044  return self._onlyForPileup
1045 
1046  def create(self, tdirectoryNEvents, requireAllHistograms=False):
1047  # [plot][histo]
1048  for plot in self._plots:
1049  plot.create(tdirectoryNEvents, requireAllHistograms)
1050 
1051  def draw(self, legendLabels, prefix=None, directory="", *args, **kwargs):
1052  # Do not make the table if it would be empty
1053  onlyEmptyPlots = True
1054  for plot in self._plots:
1055  if not plot.isEmpty():
1056  onlyEmptyPlots = False
1057  break
1058  if onlyEmptyPlots:
1059  return []
1060 
1061  haveShortLabels = False
1062  legendLabels = legendLabels[:]
1063  if max(map(len, legendLabels)) > 20:
1064  haveShortLabels = True
1065  labels_short = [str(chr(ord('A')+i)) for i in xrange(len(legendLabels))]
1066  for i, ls in enumerate(labels_short):
1067  legendLabels[i] = "%s: %s" % (ls, legendLabels[i])
1068  else:
1069  labels_short = legendLabels
1070 
1071  content = [
1072  '<html>',
1073  ' <body>',
1074  ' <table border="1">',
1075  ' <tr>',
1076  ]
1077 
1078 
1079  histos_linear = []
1080  histos_index = []
1081  labels = []
1082  for plot, title in zip(self._plots, self._titles):
1083  h_tmp = []
1084  l_tmp = []
1085  for h, l in zip(plot._histograms, labels_short):
1086  if h is not None:
1087  h_tmp.append(len(histos_linear))
1088  histos_linear.append(h)
1089  l_tmp.append(l)
1090 
1091  if len(h_tmp) > 0:
1092  histos_index.append(h_tmp)
1093  labels.append(l_tmp)
1094  content.extend([
1095  ' <td></td>',
1096  ' <td colspan="%d">%s</td>' % (len(h_tmp), title),
1097  ])
1098 
1099  if len(histos_linear) == 0:
1100  return []
1101 
1102  content.extend([
1103  ' </tr>',
1104  ' <tr>',
1105  ])
1106 
1107  xbinlabels = plotting._mergeBinLabelsX(histos_linear)
1108  histos_linear = plotting._th1IncludeOnlyBins(histos_linear, xbinlabels)
1109  if len(histos_linear) == 0:
1110  return []
1111  (histos_linear_new, xbinlabels) = plotting._th1RemoveEmptyBins(histos_linear, xbinlabels)
1112  # in practice either all histograms are returned, or none, but let's add a check anyway
1113  if len(histos_linear_new) > 0 and len(histos_linear_new) != len(histos_linear):
1114  raise Exception("This should never happen. len(histos_linear_new) %d != len(histos_linear) %d" % (len(histos_linear_new), len(histos_linear)))
1115  histos_linear = histos_linear_new
1116  if len(histos_linear) == 0:
1117  return []
1118 
1119  data = [ [h.GetBinContent(i) for i in xrange(1, h.GetNbinsX()+1)] for h in histos_linear]
1120  table = html.Table(["dummy"]*len(histos_linear), xbinlabels, data, None, None, None)
1121  data = table.tableAsRowColumn()
1122 
1123  for labs in labels:
1124  content.append(' <td></td>')
1125  content.extend([' <td>%s</td>' % lab for lab in labs])
1126  content.extend([
1127  ' </tr>',
1128  ])
1129 
1130  for irow, row in enumerate(data):
1131  content.extend([
1132  ' <tr>',
1133  ' <td>%s</td>' % table.rowHeaders()[irow]
1134  ])
1135 
1136  for hindices in histos_index:
1137  for hindex in hindices:
1138  item = row[hindex]
1139  formatted = self._format%item if item is not None else ""
1140  content.append(' <td align="right">%s</td>' % formatted)
1141  content.append(' <td></td>')
1142  del content[-1]
1143  content.append(' </tr>')
1144 
1145  content.append(' </table>')
1146  if haveShortLabels:
1147  for lab in legendLabels:
1148  content.append(' %s<br/>' % lab)
1149 
1150  content.extend([
1151  ' </body>',
1152  '<html>'
1153  ])
1154 
1155  name = self._fileName
1156  if prefix is not None:
1157  name = prefix+name
1158  name += ".html"
1159  name = os.path.join(directory, name)
1160 
1161  with open(name, "w") as f:
1162  for line in content:
1163  f.write(line)
1164  f.write("\n")
1165  return [name]
1166 
1167 _dupandfakeSeedingTable = TrackingSeedingLayerTable("dupandfakeSeeding", [p.clone() for p in _dupandfakeSeedingPlots],
1168  ["Fake rate", "Duplicate rate", "Pileup rate"], isRate=True)
1169 _extDistSeedingTable = TrackingSeedingLayerTable("distSeeding", [p.clone() for p in _extDistSeedingPlots],
1170  ["All tracks", "True tracks", "Fake tracks", "Duplicate tracks"], isRate=False)
1171 
1172 def _trackingFolders(lastDirName="Track"):
1173  return [
1174  "DQMData/Run 1/Tracking/Run summary/"+lastDirName,
1175  "DQMData/Tracking/"+lastDirName,
1176  "DQMData/Run 1/RecoTrackV/Run summary/"+lastDirName,
1177  "DQMData/RecoTrackV/"+lastDirName,
1178  ]
1179 
1180 _simBasedPlots = [
1181  _effandfakePtEtaPhi,
1182  _effandfakeDxyDzBS,
1183  _effandfakeDxyDzPV,
1184  _effandfakeHitsLayers,
1185  _effandfakePos,
1186  _effandfakeDeltaRPU,
1187  _duplicateAlgo,
1188 ]
1189 _recoBasedPlots = [
1190  _dupandfakePtEtaPhi,
1191  _dupandfakeDxyDzBS,
1192  _dupandfakeDxyDzPV,
1193  _dupandfakeHitsLayers,
1194  _dupandfakePos,
1195  _dupandfakeDeltaRPU,
1196  _dupandfakeChi2Seeding,
1197  _dupandfakeSeedingTable,
1198  _pvassociation1,
1199  _pvassociation2,
1200  _pvassociation3,
1201  _dedx,
1202 # _chargemisid,
1203  _hitsAndPt,
1204  _pulls,
1205  _resolutionsEta,
1206  _resolutionsPt,
1207  _tuning,
1208 ]
1209 _seedingBuildingPlots = _simBasedPlots + [
1210  _dupandfakePtEtaPhi,
1211  _dupandfakeDxyDzBS,
1212  _dupandfakeDxyDzPV,
1213  _dupandfakeHitsLayers,
1214  _dupandfakePos,
1215  _dupandfakeDeltaRPU,
1216  _dupandfakeChi2Seeding,
1217  _dupandfakeSeedingTable,
1218  _hitsAndPt,
1219 ] + _makeMVAPlots(1) \
1220  + _makeMVAPlots(2) \
1221  + _makeMVAPlots(2, hp=True) \
1222  + _makeMVAPlots(3) \
1223  + _makeMVAPlots(3, hp=True)
1224 # add more if needed
1225 _extendedPlots = [
1226  _extDistPtEtaPhi,
1227  _extDistDxyDzBS,
1228  _extDistDxyDzPV,
1229  _extDistHitsLayers,
1230  _extDistPosDeltaR,
1231  _extDistChi2Seeding,
1232  _extDistSeedingTable,
1233  _extResidualEta,
1234  _extResidualPt,
1235  _extNrecVsNsim,
1236  _extHitsLayers,
1237  _extDistSimPtEtaPhi,
1238  _extDistSimDxyDzBS,
1239  _extDistSimDxyDzPV,
1240  _extDistSimHitsLayers,
1241  _extDistSimPosDeltaR,
1242 ]
1243 _summaryPlots = [
1244  _summary,
1245  _summaryN,
1246  _summaryByOriginalAlgo,
1247  _summaryByOriginalAlgoN,
1248  _summaryByAlgoMask,
1249  _summaryByAlgoMaskN,
1250  _summaryPt09,
1251  _summaryPt09N,
1252 ]
1253 _summaryPlotsHp = [
1254  _summaryHp,
1255  _summaryNHp,
1256  _summaryByOriginalAlgoHp,
1257  _summaryByOriginalAlgoNHp,
1258  _summaryByAlgoMaskHp,
1259  _summaryByAlgoMaskNHp,
1260  _summaryPt09Hp,
1261  _summaryPt09NHp,
1262 ]
1263 _summaryPlotsSeeds = [
1264  _summarySeeds,
1265  _summarySeedsN,
1266 ]
1267 _packedCandidatePlots = [
1268  _packedCandidateFlow,
1269  _packedCandidateKinematics,
1270  _packedCandidateVertex,
1271  _packedCandidateImpactParameter1,
1272  _packedCandidateImpactParameter2,
1273  _packedCandidateCovarianceMatrix1,
1274  _packedCandidateCovarianceMatrix2,
1275  _packedCandidateHits,
1276  _packedCandidateHitsHitPattern,
1277  _packedCandidateLayers,
1278 ]
1279 plotter = Plotter()
1280 plotterExt = Plotter()
1281 def _appendTrackingPlots(lastDirName, name, algoPlots, onlyForPileup=False, onlyForElectron=False, onlyForConversion=False, onlyForBHadron=False, seeding=False, rawSummary=False, highPuritySummary=True):
1282  folders = _trackingFolders(lastDirName)
1283  # to keep backward compatibility, this set of plots has empty name
1284  limiters = dict(onlyForPileup=onlyForPileup, onlyForElectron=onlyForElectron, onlyForConversion=onlyForConversion, onlyForBHadron=onlyForBHadron)
1285  commonForTPF = dict(purpose=PlotPurpose.TrackingIteration, fallbackRefFiles=[
1286  _trackingRefFileFallbackSLHC_Phase1PU140
1287  ], **limiters)
1288  common = dict(fallbackDqmSubFolders=[
1289  _trackingSubFoldersFallbackSLHC_Phase1PU140,
1290  _trackingSubFoldersFallbackFromPV, _trackingSubFoldersFallbackConversion])
1291  plotter.append(name, folders, TrackingPlotFolder(*algoPlots, **commonForTPF), **common)
1292  plotterExt.append(name, folders, TrackingPlotFolder(*_extendedPlots, **commonForTPF), **common)
1293 
1294  summaryName = ""
1295  if name != "":
1296  summaryName += name+"_"
1297  summaryName += "summary"
1298  summaryPlots = []
1299  if rawSummary:
1300  summaryPlots.extend([_summaryRaw, _summaryRawN])
1301  summaryPlots.extend(_summaryPlots)
1302 
1303  common = dict(loopSubFolders=False, purpose=PlotPurpose.TrackingSummary, page="summary",
1304  #numberOfEventsHistogram=_trackingNumberOfEventsHistogram, # FIXME
1305  **limiters)
1306  plotter.append(summaryName, folders,
1307  PlotFolder(*summaryPlots, section=name, **common))
1308  if highPuritySummary:
1309  plotter.append(summaryName+"_highPurity", folders,
1310  PlotFolder(*_summaryPlotsHp, section=name+"_highPurity" if name != "" else "highPurity", **common),
1311  fallbackNames=[summaryName]) # backward compatibility for release validation, the HP plots used to be in the same directory with all-track plots
1312  if seeding:
1313  plotter.append(summaryName+"_seeds", folders,
1314  PlotFolder(*_summaryPlotsSeeds, section=name+"_seeds", **common))
1315 
1316  plotter.appendTable(summaryName, folders, TrackingSummaryTable(section=name))
1317  plotter.appendTable(summaryName, folders, TrackingSummaryTable(section=name+"Pt09", collection=TrackingSummaryTable.GeneralTracksPt09))
1318  if highPuritySummary:
1319  sectionName = name+"_highPurity" if name != "" else "highPurity"
1320  plotter.appendTable(summaryName+"_highPurity", folders, TrackingSummaryTable(section=sectionName, collection=TrackingSummaryTable.HighPurity))
1321  plotter.appendTable(summaryName+"_highPurity", folders, TrackingSummaryTable(section=sectionName+"Pt09", collection=TrackingSummaryTable.HighPurityPt09))
1322  if name == "":
1323  plotter.appendTable(summaryName, folders, TrackingSummaryTable(section="btvLike", collection=TrackingSummaryTable.BTVLike))
1324  plotter.appendTable(summaryName, folders, TrackingSummaryTable(section="ak4PFJets", collection=TrackingSummaryTable.AK4PFJets))
1325 _appendTrackingPlots("Track", "", _simBasedPlots+_recoBasedPlots)
1326 _appendTrackingPlots("TrackTPPtLess09", "tpPtLess09", _simBasedPlots)
1327 _appendTrackingPlots("TrackAllTPEffic", "allTPEffic", _simBasedPlots, onlyForPileup=True)
1328 _appendTrackingPlots("TrackFromPV", "fromPV", _simBasedPlots+_recoBasedPlots, onlyForPileup=True)
1329 _appendTrackingPlots("TrackFromPVAllTP", "fromPVAllTP", _simBasedPlots+_recoBasedPlots, onlyForPileup=True)
1330 _appendTrackingPlots("TrackFromPVAllTP2", "fromPVAllTP2", _simBasedPlots+_recoBasedPlots, onlyForPileup=True)
1331 _appendTrackingPlots("TrackSeeding", "seeding", _seedingBuildingPlots, seeding=True)
1332 _appendTrackingPlots("TrackBuilding", "building", _seedingBuildingPlots)
1333 _appendTrackingPlots("TrackConversion", "conversion", _simBasedPlots+_recoBasedPlots, onlyForConversion=True, rawSummary=True, highPuritySummary=False)
1334 _appendTrackingPlots("TrackGsf", "gsf", _simBasedPlots+_recoBasedPlots, onlyForElectron=True, rawSummary=True, highPuritySummary=False)
1335 _appendTrackingPlots("TrackBHadron", "bhadron", _simBasedPlots+_recoBasedPlots, onlyForBHadron=True)
1336 # Pixel tracks
1337 _common = dict(purpose=PlotPurpose.Pixel, page="pixel")
1338 plotter.append("pixelTrack", _trackingFolders("PixelTrack"), TrackingPlotFolder(*(_simBasedPlots+_recoBasedPlots), **_common))
1339 plotterExt.append("pixelTrack", _trackingFolders("PixelTrack"), TrackingPlotFolder(*_extendedPlots, **_common))
1340 plotter.append("pixelTrack_summary", _trackingFolders("PixelTrack"), PlotFolder(_summaryRaw, _summaryRawN, loopSubFolders=False, purpose=PlotPurpose.TrackingSummary, page="summary", section="pixel"))
1341 plotter.appendTable("pixelTrack_summary", _trackingFolders("PixelTrack"), TrackingSummaryTable(section="pixel", collection=TrackingSummaryTable.Pixel))
1342 
1343 
1344 # MiniAOD
1345 plotter.append("packedCandidate", _trackingFolders("PackedCandidate"),
1346  PlotFolder(*_packedCandidatePlots, loopSubFolders=False,
1347  purpose=PlotPurpose.MiniAOD, page="miniaod", section="PackedCandidate"))
1348 plotter.append("packedCandidateLostTracks", _trackingFolders("PackedCandidate/lostTracks"),
1349  PlotFolder(*_packedCandidatePlots, loopSubFolders=False,
1350  purpose=PlotPurpose.MiniAOD, page="miniaod", section="PackedCandidate (lostTracks)"))
1351 
1352 # HLT
1353 _hltFolder = [
1354  "DQMData/Run 1/HLT/Run summary/Tracking/ValidationWRTtp",
1355 ]
1356 plotterHLT = Plotter()
1357 plotterHLTExt = Plotter()
1358 _common = dict(purpose=PlotPurpose.HLT, page="hlt")
1359 plotterHLT.append("hlt", _hltFolder, TrackingPlotFolder(*(_simBasedPlots+_recoBasedPlots), **_common))
1360 plotterHLTExt.append("hlt", _hltFolder, TrackingPlotFolder(*_extendedPlots, **_common))
1361 
1362 # Timing
1364  def __init__(self, name, clusterMasking=None, seeding=None, building=None, fit=None, selection=None, other=[]):
1365  self._name = name
1366 
1367  def _set(param, name, modules):
1368  if param is not None:
1369  setattr(self, name, param)
1370  else:
1371  setattr(self, name, modules)
1372 
1373  _set(clusterMasking, "_clusterMasking", [self._name+"Clusters"])
1374  # it's fine to include e.g. quadruplets here also for pair
1375  # steps, as non-existing modules are just ignored
1376  _set(seeding, "_seeding", [self._name+"SeedingLayers", self._name+"TrackingRegions", self._name+"HitDoublets", self._name+"HitTriplets", self._name+"HitQuadruplets", self._name+"Seeds"])
1377  _set(building, "_building", [self._name+"TrackCandidates"])
1378  _set(fit, "_fit", [self._name+"Tracks"])
1379  _set(selection, "_selection", [self._name])
1380  self._other = other
1381 
1382  def name(self):
1383  return self._name
1384 
1385  def all(self):
1386  return self._clusterMasking+self._seeding+self._building+self._fit+self._selection+self._other
1387 
1388  def clusterMasking(self):
1389  return self._clusterMasking
1390 
1391  def seeding(self):
1392  return self._seeding
1393 
1394  def building(self):
1395  return self._building
1396 
1397  def fit(self):
1398  return self._fit
1399 
1400  def selection(self):
1401  return self._selection
1402 
1403  def other(self):
1404  return self._other
1405 
1406  def modules(self):
1407  return [("ClusterMask", self.clusterMasking()),
1408  ("Seeding", self.seeding()),
1409  ("Building", self.building()),
1410  ("Fit", self.fit()),
1411  ("Selection", self.selection()),
1412  ("Other", self.other())]
1413 
1414 
1415 _iterations = [
1416  Iteration("initialStepPreSplitting", clusterMasking=[],
1417  seeding=["initialStepSeedLayersPreSplitting",
1418  "initialStepTrackingRegionsPreSplitting",
1419  "initialStepHitDoubletsPreSplitting",
1420  "initialStepHitTripletsPreSplitting",
1421  "initialStepHitQuadrupletsPreSplitting",
1422  "initialStepSeedsPreSplitting"],
1423  building=["initialStepTrackCandidatesPreSplitting"],
1424  fit=["initialStepTracksPreSplitting"],
1425  other=["firstStepPrimaryVerticesPreSplitting",
1426  "initialStepTrackRefsForJetsPreSplitting",
1427  "caloTowerForTrkPreSplitting",
1428  "ak4CaloJetsForTrkPreSplitting",
1429  "jetsForCoreTrackingPreSplitting",
1430  "siPixelClusters",
1431  "siPixelRecHits",
1432  "MeasurementTrackerEvent",
1433  "siPixelClusterShapeCache"]),
1434  Iteration("initialStep", clusterMasking=[],
1435  selection=["initialStepClassifier1",
1436  "initialStepClassifier2",
1437  "initialStepClassifier3",
1438  "initialStep",
1439  "initialStepSelector"],
1440  other=["firstStepPrimaryVerticesUnsorted",
1441  "initialStepTrackRefsForJets",
1442  "caloTowerForTrk",
1443  "ak4CaloJetsForTrk",
1444  "firstStepPrimaryVertices"]),
1445  Iteration("highPtTripletStep",
1446  selection=["highPtTripletStepClassifier1",
1447  "highPtTripletStepClassifier2",
1448  "highPtTripletStepClassifier3",
1449  "highPtTripletStep",
1450  "highPtTripletStepSelector"]),
1451  Iteration("detachedQuadStep",
1452  selection=["detachedQuadStepClassifier1",
1453  "detachedQuadStepClassifier2",
1454  "detachedQuadStep",
1455  "detachedQuadStepSelector"]),
1456  Iteration("detachedTripletStep",
1457  selection=["detachedTripletStepClassifier1",
1458  "detachedTripletStepClassifier2",
1459  "detachedTripletStep",
1460  "detachedTripletStepSelector"]),
1461  Iteration("lowPtQuadStep",
1462  selection=["lowPtQuadStepClassifier1",
1463  "lowPtQuadStepClassifier2",
1464  "lowPtQuadStep",
1465  "lowPtQuadStepSelector"]),
1466  Iteration("lowPtTripletStep",
1467  selection=["lowPtTripletStepClassifier1",
1468  "lowPtTripletStepClassifier2",
1469  "lowPtTripletStep",
1470  "lowPtTripletStepSelector"]),
1471  Iteration("pixelPairStep",
1472  seeding=["pixelPairStepSeedLayers",
1473  "pixelPairStepSeedLayersB",
1474  "pixelPairStepSeedLayersC",
1475  "pixelPairStepTrackingRegions",
1476  "pixelPairStepTrackingRegionsB",
1477  "pixelPairStepTrackingRegionsC",
1478  "pixelPairStepTrackingRegionsSeedLayersB",
1479  "pixelPairStepHitDoublets",
1480  "pixelPairStepHitDoubletsB",
1481  "pixelPairStepHitDoubletsC",
1482  "pixelPairStepSeedsA",
1483  "pixelPairStepSeedsB",
1484  "pixelPairStepSeedsC",
1485  "pixelPairStepSeeds",],
1486  selection=["pixelPairStep",
1487  "pixelPairStepSelector"]),
1488  Iteration("mixedTripletStep",
1489  seeding=["mixedTripletStepSeedLayersA",
1490  "mixedTripletStepSeedLayersB",
1491  "mixedTripletStepTrackingRegionsA",
1492  "mixedTripletStepTrackingRegionsB",
1493  "mixedTripletStepHitDoubletsA",
1494  "mixedTripletStepHitDoubletsB",
1495  "mixedTripletStepHitTripletsA",
1496  "mixedTripletStepHitTripletsB",
1497  "mixedTripletStepSeedsA",
1498  "mixedTripletStepSeedsB",
1499  "mixedTripletStepSeeds"],
1500  selection=["mixedTripletStepClassifier1",
1501  "mixedTripletStepClassifier2",
1502  "mixedTripletStep",
1503  "mixedTripletStepSelector"]),
1504  Iteration("pixelLessStep",
1505  selection=["pixelLessStepClassifier1",
1506  "pixelLessStepClassifier2",
1507  "pixelLessStep",
1508  "pixelLessStepSelector"]),
1509  Iteration("tobTecStep",
1510  seeding=["tobTecStepSeedLayersTripl",
1511  "tobTecStepSeedLayersPair",
1512  "tobTecStepTrackingRegionsTripl",
1513  "tobTecStepTrackingRegionsPair",
1514  "tobTecStepHitDoubletsTripl",
1515  "tobTecStepHitDoubletsPair",
1516  "tobTecStepHitTripletsTripl",
1517  "tobTecStepSeedsTripl",
1518  "tobTecStepSeedsPair",
1519  "tobTecStepSeeds"],
1520  selection=["tobTecStepClassifier1",
1521  "tobTecStepClassifier2",
1522  "tobTecStep",
1523  "tobTecStepSelector"]),
1524  Iteration("jetCoreRegionalStep",
1525  clusterMasking=[],
1526  other=["jetsForCoreTracking",
1527  "firstStepGoodPrimaryVertices",
1528  ]),
1529  Iteration("muonSeededSteps",
1530  clusterMasking=[],
1531  seeding=["muonSeededSeedsInOut",
1532  "muonSeededSeedsOutIn"],
1533  building=["muonSeededTrackCandidatesInOut",
1534  "muonSeededTrackCandidatesOutIn"],
1535  fit=["muonSeededTracksInOut",
1536  "muonSeededTracksOutIn"],
1537  selection=["muonSeededTracksInOutClassifier",
1538  "muonSeededTracksInOutSelector",
1539  "muonSeededTracksOutIntClassifier",
1540  "muonSeededTracksOutIntSelector"],
1541 # other=["earlyMuons"]
1542  ),
1543  Iteration("duplicateMerge",
1544  clusterMasking=[], seeding=[],
1545  building=["duplicateTrackCandidates"],
1546  fit=["mergedDuplicateTracks"],
1547  selection=["duplicateTrackClassifier"]),
1548  Iteration("generalTracks",
1549  clusterMasking=[], seeding=[], building=[], fit=[], selection=[],
1550  other=["preDuplicateMergingGeneralTracks",
1551  "generalTracks"]),
1552  Iteration("ConvStep",
1553  clusterMasking=["convClusters"],
1554  seeding=["convLayerPairs",
1555  "photonConvTrajSeedFromSingleLeg"],
1556  building=["convTrackCandidates"],
1557  fit=["convStepTracks"],
1558  selection=["convStepSelector"]),
1559  Iteration("Other", clusterMasking=[], seeding=[], building=[], fit=[], selection=[],
1560  other=["trackerClusterCheckPreSplitting",
1561  "trackerClusterCheck"]),
1562 ]
1563 
1564 def _iterModuleMap(includeConvStep=True, onlyConvStep=False):
1565  iterations = _iterations
1566  if not includeConvStep:
1567  iterations = filter(lambda i: i.name() != "ConvStep", iterations)
1568  if onlyConvStep:
1569  iterations = filter(lambda i: i.name() == "ConvStep", iterations)
1570  return collections.OrderedDict([(i.name(), i.all()) for i in iterations])
1572  def getProp(prop):
1573  ret = []
1574  for i in _iterations:
1575  if i.name() == "ConvStep":
1576  continue
1577  ret.extend(getattr(i, prop)())
1578  return ret
1579 
1580  return collections.OrderedDict([
1581  ("ClusterMask", getProp("clusterMasking")),
1582  ("Seeding", getProp("seeding")),
1583  ("Building", getProp("building")),
1584  ("Fitting", getProp("fit")),
1585  ("Selection", getProp("selection")),
1586  ("Other", getProp("other"))
1587  ])
1588 
1590  def __init__(self, name, timeHisto):
1591  self._name = name
1592  self._timeHisto = timeHisto
1593  self._eventsHisto = "path time_real"
1594  self._cache = {}
1595 
1596  def __str__(self):
1597  return self._name
1598 
1599  def _create(self, tdirectory):
1600  timeTh1 = plotting._getOrCreateObject(tdirectory, self._timeHisto)
1601  if timeTh1 is None:
1602  return None
1603 
1604  eventsTh1 = plotting._getOrCreateObject(tdirectory, self._eventsHisto)
1605  if eventsTh1 is None:
1606  return None
1607  nevents = eventsTh1.GetEntries()
1608  if nevents == 0:
1609  return None
1610 
1611  ret = timeTh1.Clone(self._name)
1612  xaxis = ret.GetXaxis()
1613  for i in xrange(1, ret.GetNbinsX()+1):
1614  ret.SetBinContent(i, ret.GetBinContent(i)/nevents)
1615  ret.SetBinError(i, ret.GetBinError(i)/nevents)
1616  xaxis.SetBinLabel(i, xaxis.GetBinLabel(i).replace(" (unscheduled)", ""))
1617  return ret
1618 
1619  def create(self, tdirectory):
1620  path = tdirectory.GetPath()
1621  if path not in self._cache:
1622  self._cache[path] = self._create(tdirectory)
1623  return self._cache[path]
1624 
1626  def __init__(self, name, timeHisto, selectedTracks=False):
1627  self._name = name
1628  self._timeHisto = timeHisto
1629  self._selectedTracks = selectedTracks
1630 
1631  def __str__(self):
1632  return self._name
1633 
1634  def _getDirectory(self, tfile):
1635  for dirName in _trackingFolders():
1636  tdir = tfile.Get(dirName)
1637  if tdir != None:
1638  return tdir
1639  return None
1640 
1641  def create(self, tdirectory):
1642  timeTh1 = plotting._getOrCreateObject(tdirectory, self._timeHisto)
1643  if timeTh1 is None:
1644  return None
1645 
1646  # this is bit of a hack, but as long as it is needed only
1647  # here, I won't invest in better solution
1648  tfile = tdirectory.GetFile()
1649  trkDir = self._getDirectory(tfile)
1650  if trkDir is None:
1651  return None
1652 
1653  iterMap = copy.copy(_collLabelMapHp)
1654  del iterMap["generalTracks"]
1655  del iterMap["jetCoreRegionalStep"] # this is expensive per track on purpose
1656  if self._selectedTracks:
1657  renameBin = lambda bl: _summaryBinRename(bl, highPurity=True, byOriginalAlgo=False, byAlgoMask=True, ptCut=False, seeds=False)
1658  else:
1659  renameBin = lambda bl: _summaryBinRename(bl, highPurity=False, byOriginalAlgo=False, byAlgoMask=False, ptCut=False, seeds=False)
1660  recoAB = AggregateBins("tmp", "num_reco_coll", mapping=iterMap,ignoreMissingBins=True, renameBin=renameBin)
1661  h_reco_per_iter = recoAB.create(trkDir)
1662  if h_reco_per_iter is None:
1663  return None
1664  values = {}
1665  for i in xrange(1, h_reco_per_iter.GetNbinsX()+1):
1666  values[h_reco_per_iter.GetXaxis().GetBinLabel(i)] = h_reco_per_iter.GetBinContent(i)
1667 
1668 
1669  result = []
1670  for i in xrange(1, timeTh1.GetNbinsX()+1):
1671  iterName = timeTh1.GetXaxis().GetBinLabel(i)
1672  if iterName in values:
1673  ntrk = values[iterName]
1674  result.append( (iterName,
1675  timeTh1.GetBinContent(i)/ntrk if ntrk > 0 else 0,
1676  timeTh1.GetBinError(i)/ntrk if ntrk > 0 else 0) )
1677 
1678  if len(result) == 0:
1679  return None
1680 
1681  res = ROOT.TH1F(self._name, self._name, len(result), 0, len(result))
1682  for i, (label, value, error) in enumerate(result):
1683  res.GetXaxis().SetBinLabel(i+1, label)
1684  res.SetBinContent(i+1, value)
1685  res.SetBinError(i+1, error)
1686 
1687  return res
1688 
1690  def __init__(self):
1691  self._cache = {}
1692 
1693  def _findOrder(self, f):
1694  h = f.Get(_trackingIterationOrderHistogram)
1695  if not h:
1696  return None
1697  xaxis = h.GetXaxis()
1698  def _edit(s):
1699  # remove "Tracks" from the track producer name to get the iteration name
1700  # muonSeeded iterations do not have "Step" in the producer name, so add it here
1701  return s.replace("Tracks", "").replace("muonSeeded", "muonSeededStep")
1702  return [_edit(xaxis.GetBinLabel(i)) for i in xrange(1, h.GetNbinsX()+1)]
1703 
1704  def __call__(self, tdirectory, labels):
1705  ret = range(0, len(labels))
1706  f = tdirectory.GetFile()
1707  if not f:
1708  return ret
1709 
1710  if not f.GetName() in self._cache:
1711  r = self._findOrder(f)
1712  if r is None:
1713  return ret
1714  self._cache[f.GetName()] = r
1715  order = self._cache[f.GetName()]
1716 
1717  # O(N^2) I know, but we're talking about O(10) elements...
1718  orderIndices = []
1719  for l in order:
1720  try:
1721  orderIndices.append(labels.index(l))
1722  except ValueError:
1723  pass
1724  ret = []
1725  for i, l in enumerate(labels):
1726  if l in order:
1727  try:
1728  found = orderIndices.index(i)
1729  if found == 0:
1730  ret.append(i)
1731  else:
1732  ret.append(orderIndices[0])
1733  except ValueError:
1734  ret.append(orderIndices[0])
1735  orderIndices.pop(0)
1736  else:
1737  ret.append(i)
1738  return ret
1739 
1740 _time_per_event_cpu = TimePerEventPlot("timePerEvent", "module_time_thread_total")
1741 _time_per_event_real = TimePerEventPlot("timePerEvent", "module_time_real_total")
1742 
1744  def __init__(self):
1746  self._page = "timing"
1747  self._section = "timing"
1748 
1749  def getPurpose(self):
1750  return self._purpose
1751 
1752  def getPage(self):
1753  return self._page
1754 
1755  def getSection(self, dqmSubFolder):
1756  return self._section
1757 
1758  def _getValues(self, tdirectory, histo):
1759  h = tdirectory.Get(histo)
1760  totalReco = None
1761  if h:
1762  totalReco = "%.1f" % h.Integral()
1763 
1764  creator = AggregateBins("iteration", histo, _iterModuleMap(includeConvStep=False), ignoreMissingBins=True)
1765  h = creator.create(tdirectory)
1766  totalTracking = None
1767  if h:
1768  totalTracking = "%.1f" % h.Integral()
1769 
1770  creator = AggregateBins("iteration", histo, _iterModuleMap(onlyConvStep=True), ignoreMissingBins=True)
1771  h = creator.create(tdirectory)
1772  totalConvStep = None
1773  if h:
1774  totalConvStep = "%.1f" % h.Integral()
1775 
1776  return [
1777  totalReco,
1778  totalTracking,
1779  totalConvStep,
1780  ]
1781 
1782  def create(self, tdirectory):
1783  cpuValues = self._getValues(tdirectory, _time_per_event_cpu)
1784  realValues = self._getValues(tdirectory, _time_per_event_real)
1785 
1786  return cpuValues + realValues
1787 
1788  def headers(self):
1789  return [
1790  "Average reco CPU time / event (ms)",
1791  "Average tracking (w/o convStep) CPU time / event (ms)",
1792  "Average convStep CPU time / event (ms)",
1793  "Average reco real time / event (ms)",
1794  "Average tracking (w/o convStep) real time / event (ms)",
1795  "Average convStep real time / event (ms)",
1796  ]
1797 
1798 _common = {
1799  "drawStyle": "P",
1800  "xbinlabelsize": 10,
1801  "xbinlabeloption": "d"
1802 }
1803 
1804 _iteration_reorder = TrackingIterationOrder()
1805 _time_per_iter_cpu = AggregateBins("iteration", _time_per_event_cpu, _iterModuleMap(), ignoreMissingBins=True, reorder=_iteration_reorder)
1806 _time_per_iter_real = AggregateBins("iteration", _time_per_event_real, _iterModuleMap(), ignoreMissingBins=True, reorder=_iteration_reorder)
1807 
1808 _timing_summaryCPU = PlotGroup("summaryCPU", [
1809  Plot(_time_per_iter_cpu,
1810  ytitle="Average CPU time (ms)", title="Average CPU time / event", legendDx=-0.4, **_common),
1811  Plot(AggregateBins("iteration_fraction", _time_per_event_cpu, _iterModuleMap(), ignoreMissingBins=True, reorder=_iteration_reorder),
1812  ytitle="Fraction", title="", normalizeToUnitArea=True, **_common),
1813  #
1814  Plot(AggregateBins("step", _time_per_event_cpu, _stepModuleMap(), ignoreMissingBins=True),
1815  ytitle="Average CPU time (ms)", title="Average CPU time / event", **_common),
1816  Plot(AggregateBins("step_fraction", _time_per_event_cpu, _stepModuleMap(), ignoreMissingBins=True),
1817  ytitle="Fraction", title="", normalizeToUnitArea=True, **_common),
1818  #
1819  Plot(TimePerTrackPlot("iteration_track", _time_per_iter_cpu, selectedTracks=False),
1820  ytitle="Average CPU time / built track (ms)", title="Average CPU time / built track", **_common),
1821  Plot(TimePerTrackPlot("iteration_trackhp", _time_per_iter_cpu, selectedTracks=True),
1822  ytitle="Average CPU time / selected track (ms)", title="Average CPU time / selected HP track by algoMask", **_common),
1823  ],
1824 )
1825 _timing_summaryReal = PlotGroup("summaryReal", [
1826  Plot(_time_per_iter_real,
1827  ytitle="Average real time (ms)", title="Average real time / event", legendDx=-0.4, **_common),
1828  Plot(AggregateBins("iteration_fraction", _time_per_event_real, _iterModuleMap(), ignoreMissingBins=True, reorder=_iteration_reorder),
1829  ytitle="Fraction", title="", normalizeToUnitArea=True, **_common),
1830  #
1831  Plot(AggregateBins("step", _time_per_event_real, _stepModuleMap(), ignoreMissingBins=True),
1832  ytitle="Average real time (ms)", title="Average real time / event", **_common),
1833  Plot(AggregateBins("step_fraction", _time_per_event_real, _stepModuleMap(), ignoreMissingBins=True),
1834  ytitle="Fraction", title="", normalizeToUnitArea=True, **_common),
1835  #
1836  Plot(TimePerTrackPlot("iteration_track", _time_per_iter_real, selectedTracks=False),
1837  ytitle="Average real time / built track (ms)", title="Average real time / built track", **_common),
1838  Plot(TimePerTrackPlot("iteration_trackhp", _time_per_iter_real, selectedTracks=True),
1839  ytitle="Average real time / selected track (ms)", title="Average real time / selected HP track by algoMask", **_common),
1840  ],
1841 )
1842 
1843 _timing_iterationsCPU = PlotGroup("iterationsCPU", [
1844  Plot(AggregateBins(i.name(), _time_per_event_cpu, collections.OrderedDict(i.modules()), ignoreMissingBins=True),
1845  ytitle="Average CPU time (ms)", title=i.name(), **_common)
1846  for i in _iterations
1847 ],
1848  ncols=4, legend=False
1849 )
1850 _timing_iterationsReal = PlotGroup("iterationsReal", [
1851  Plot(AggregateBins(i.name(), _time_per_event_real, collections.OrderedDict(i.modules()), ignoreMissingBins=True),
1852  ytitle="Average real time (ms)", title=i.name(), **_common)
1853  for i in _iterations
1854 ],
1855  ncols=4, legend=False
1856 )
1857 
1858 # TODO: to be updated to new FastTimerService format later
1859 #_pixelTiming = PlotGroup("pixelTiming", [
1860 # Plot(AggregateBins("pixel", "reconstruction_step_module_average", {"pixelTracks": ["pixelTracks"]}), ytitle="Average processing time [ms]", title="Average processing time / event", drawStyle="HIST")
1861 #])
1862 
1863 _timeFolders = [
1864 # "DQMData/Run 1/DQM/Run summary/TimerService/process RECO paths/path reconstruction_step",
1865  "DQMData/Run 1/DQM/Run summary/TimerService/process RECO paths/path prevalidation_step", # because of unscheduled, it's actually prevalidation_step that has all the tracking modules?
1866 ]
1867 timePlotter = Plotter()
1868 timePlotter.append("timing", _timeFolders, PlotFolder(
1869  _timing_summaryCPU,
1870  _timing_iterationsCPU,
1871  _timing_summaryReal,
1872  _timing_iterationsReal,
1873  # _pixelTiming,
1874  loopSubFolders=False, purpose=PlotPurpose.Timing, page="timing"
1875 ))
1876 timePlotter.appendTable("timing", _timeFolders, TrackingTimingTable())
1877 
1878 _common = {"stat": True, "normalizeToUnitArea": True, "drawStyle": "hist"}
1879 _tplifetime = PlotGroup("tplifetime", [
1880  Plot("TPlip", xtitle="TP lip", **_common),
1881  Plot("TPtip", xtitle="TP tip", **_common),
1882 ])
1883 
1884 tpPlotter = Plotter()
1885 tpPlotter.append("tp", [
1886  "DQMData/Run 1/Tracking/Run summary/TrackingMCTruth/TrackingParticle",
1887  "DQMData/Tracking/TrackingMCTruth/TrackingParticle",
1888 ], PlotFolder(
1889  _tplifetime,
1890 ))
1891 
1892 
def iterSelectionName(self, plotFolderName, translatedDqmSubFolder)
def getSection(self, dqmSubFolder)
def _makeFakeDist(postfix)
def _makeFakeDupPileupPlots(postfix, quantity, unit="", xquantity="", xtitle=None, common={})
def __init__(self, name, timeHisto)
def _getOrCreateObject(tdirectory, nameOrCreator)
Definition: plotting.py:54
def _iterModuleMap(includeConvStep=True, onlyConvStep=False)
def replace(string, replacements)
def _makeDistSimPlots(postfix, quantity, common={})
def getSection(self, dqmSubFolder)
def create(self, tdirectory)
def _summaryBinRename(binLabel, highPurity, byOriginalAlgo, byAlgoMask, ptCut, seeds)
def translateSubFolder(self, dqmSubFolderName)
def _collhelper(name)
def _mapCollectionToAlgoQuality(collName)
def __init__(self, section, collection=GeneralTracks)
def __init__(self, args, kwargs)
def _minMaxResidual(ma)
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
def create(self, tdirectoryNEvents, requireAllHistograms=False)
def _trackingSubFoldersFallbackConversion(subfolder)
def __call__(self, tdirectory, labels)
def _appendTrackingPlots(lastDirName, name, algoPlots, onlyForPileup=False, onlyForElectron=False, onlyForConversion=False, onlyForBHadron=False, seeding=False, rawSummary=False, highPuritySummary=True)
def _trackingSubFoldersFallbackSLHC_Phase1PU140(subfolder)
def limitSubFolder(self, limitOnlyTo, translatedDqmSubFolder)
def __init__(self, name, timeHisto, selectedTracks=False)
def _makeMVAPlots(num, hp=False)
def _trackingRefFileFallbackSLHC_Phase1PU140(path)
def _th1RemoveEmptyBins(histos, xbinlabels)
Definition: plotting.py:603
def _constructSummary(mapping=None, highPurity=False, byOriginalAlgo=False, byAlgoMask=False, ptCut=False, seeds=False, midfix="")
def _trackingSubFoldersFallbackFromPV(subfolder)
def _makeDistPlots(postfix, quantity, common={})
def __init__(self, fileName, plots, titles, isRate, kwargs)
def _create(self, tdirectory)
def create(self, tdirectory)
def _trackingFolders(lastDirName="Track")
def __init__(self, name, clusterMasking=None, seeding=None, building=None, fit=None, selection=None, other=[])
def _makeEffFakeDupPlots(postfix, quantity, unit="", common={}, effopts={}, fakeopts={})
def _th1ToOrderedDict(th1, renameBin=None)
Definition: plotting.py:97
def draw(self, legendLabels, prefix=None, directory="", args, kwargs)
def _mergeBinLabelsX(histos)
Definition: plotting.py:703
def _th1IncludeOnlyBins(histos, xbinlabels)
Definition: plotting.py:740
def _getValues(self, tdirectory, histo)