Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • yizhouh/Moore
  • ipolyako/Moore
  • qhan/Moore
  • allightb/Moore
  • gpietrzy/Moore
  • smaccoli/Moore
  • rmatev/Moore
  • bldelane/Moore
  • egranado/Moore
  • peilian/Moore
  • rcurrie/Moore
  • mstahl/Moore
  • jonrob/Moore
  • raaij/Moore
  • lhcb/Moore
15 results
Select Git revision
Show changes
Commits on Source (113)
Showing
with 2826 additions and 23 deletions
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
from Moore import options, run_reconstruction
from Moore.config import Reconstruction
from RecoConf.hlt1_tracking import require_gec, make_hlt1_tracks, make_VeloKalman_fitted_tracks, make_pvs
from RecoConf.mc_checking import monitor_IPresolution
from Configurables import ApplicationMgr
from Configurables import NTupleSvc
def hlt1_reco_IPresolution():
hlt1_tracks = make_hlt1_tracks()
fitted_tracks = make_VeloKalman_fitted_tracks(hlt1_tracks)
inputPVs = make_pvs()
pr_checker = monitor_IPresolution(fitted_tracks["v1"], inputPVs,
hlt1_tracks["Velo"]["v1"])
return Reconstruction('IPresolution', [pr_checker], [require_gec()])
run_reconstruction(options, hlt1_reco_IPresolution)
NTupleSvc().Output += [
"FILE1 DATAFILE='Hlt1ForwardTracking_IPresolution.root' TYPE='ROOT' OPT='NEW'"
]
ApplicationMgr().ExtSvc += [NTupleSvc()]
ApplicationMgr().HistogramPersistency = "ROOT"
......@@ -13,3 +13,5 @@ from RecoConf.standalone import standalone_hlt1_reco
with standalone_hlt1_reco.bind(do_mc_checking=True):
run_reconstruction(options, standalone_hlt1_reco)
options.histo_file = "MCMatching_baseline_MiniBias.root"
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
from Moore import options, run_reconstruction
from Moore.config import Reconstruction
from PyConf.application import configure_input, configure
from PyConf.control_flow import CompositeNode, NodeLogic
from RecoConf.hlt1_tracking import (require_gec, make_hlt1_tracks,
make_VeloClusterTrackingSIMD_hits)
from RecoConf.mc_checking import monitor_tracking_efficiency, make_links_tracks_mcparticles, make_links_lhcbids_mcparticles_tracking_system
from RecoConf.mc_checking_categories import get_mc_categories, get_hit_type_mask
from RecoConf.hlt1_muonid import make_fitted_tracks_with_muon_id
from Hlt1Conf.algorithms import Filter
from Functors import ISMUON
from PyConf.Algorithms import (
LHCb__Converters__Track__v1__fromV2TrackV1Track as
trackV1FromV2TrackV1Track,
LHCb__Converters__Track__v2__fromPrFittedForwardTrackWithMuonID as
trackV2FromPrFittedForwardTrackWithMuonID)
def hlt1_reco_muonid_efficiency():
# get the fitted tracks with muon ID
tracks_with_muon_id = make_fitted_tracks_with_muon_id()
# appliy selection to tracks to select only tracks which are isMuon
full_sel = ISMUON
track_filter = Filter(tracks_with_muon_id,
full_sel)['PrFittedForwardWithMuonID']
# convert result to v1 (which is what the PrChecker needs)
velo_hits = make_VeloClusterTrackingSIMD_hits()
v2_tracks = trackV2FromPrFittedForwardTrackWithMuonID(
FittedTracks=track_filter, VeloHits=velo_hits)
v1_tracks = trackV1FromV2TrackV1Track(InputTracksName=v2_tracks, )
# make links to lhcb id for mc matching
links_to_lhcbids = make_links_lhcbids_mcparticles_tracking_system()
# make links between tracks and mcparticles for mc matching
links_to_tracks_muon_id = make_links_tracks_mcparticles(
InputTracks={"v1": v1_tracks.OutputTracksName},
LinksToLHCbIDs=links_to_lhcbids)
# build the PrChecker algorihm for muon_id track
pr_checker_for_muon_id = monitor_tracking_efficiency(
TrackType="MuonMatch",
InputTracks={"v1": v1_tracks.OutputTracksName},
#InputTracks={"v1": v1_tracks.OutputTracksName},
LinksToTracks=links_to_tracks_muon_id,
LinksToLHCbIDs=links_to_lhcbids,
MCCategories=get_mc_categories("MuonMatch"),
HitTypesToCheck=get_hit_type_mask("BestLong"),
)
# build the PrChecker algorihm for forward track
forward_tracks = make_hlt1_tracks()['Forward']
links_to_forward_tracks = make_links_tracks_mcparticles(
InputTracks=forward_tracks, LinksToLHCbIDs=links_to_lhcbids)
pr_checker_for_forward_track = monitor_tracking_efficiency(
TrackType="Forward",
InputTracks=forward_tracks,
LinksToTracks=links_to_forward_tracks,
LinksToLHCbIDs=links_to_lhcbids,
MCCategories=get_mc_categories("MuonMatch"),
HitTypesToCheck=get_hit_type_mask("BestLong"),
)
return Reconstruction(
'muonideff', [pr_checker_for_forward_track, pr_checker_for_muon_id],
[require_gec()])
options.histo_file = "PrChecker_MuonID_MiniBias.root"
run_reconstruction(options, hlt1_reco_muonid_efficiency)
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
from Moore import options, run_reconstruction
from Moore.config import Reconstruction
from RecoConf.hlt1_tracking import require_gec, make_hlt1_tracks, make_VeloKalman_fitted_tracks, make_pvs
from RecoConf.mc_checking import get_pv_checkers, get_track_checkers
from Configurables import ApplicationMgr
from Configurables import NTupleSvc
def hlt1_reco_pvchecker():
hlt1_tracks = make_hlt1_tracks()
pvs = make_pvs()
data = [pvs]
data += get_pv_checkers(pvs, hlt1_tracks["Velo"], produce_ntuple=True)
return Reconstruction('PVperformance', data, [require_gec()])
run_reconstruction(options, hlt1_reco_pvchecker)
NTupleSvc().Output += [
"FILE1 DATAFILE='Hlt1_PVperformance.root' TYPE='ROOT' OPT='NEW'"
]
ApplicationMgr().ExtSvc += [NTupleSvc()]
ApplicationMgr().HistogramPersistency = "ROOT"
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
from Moore import options, run_reconstruction
from Moore.config import Reconstruction
from RecoConf.hlt1_tracking import require_gec, make_hlt1_tracks
from RecoConf.mc_checking import monitor_track_resolution
from PyConf.application import make_data_with_FetchDataFromFile
def hlt1_reco_trackresolution():
track_type = "Forward"
tracks = make_hlt1_tracks()[track_type]
pr_checker = monitor_track_resolution(tracks)
#return CompositeNode(
# name='hlt1_trackRes',
# children=pr_checker,
# combineLogic=NodeLogic.NONLAZY_OR,
# forceOrder=False)
return Reconstruction(
'track_resolution',
[make_data_with_FetchDataFromFile("/Event/MC/TrackInfo"), pr_checker],
[require_gec()])
options.histo_file = "Hlt1ForwardTrackingResolution.root"
run_reconstruction(options, hlt1_reco_trackresolution)
###############################################################################
# (c) Copyright 2020 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
fpga_clustering = False
......@@ -12,6 +12,19 @@ import logging
from PyConf import configurable
from PyConf.application import default_raw_event
from .fpga_clustering import fpga_clustering
from Gaudi.Configuration import DEBUG
from Configurables import (
VoidFilter,
PrGECFilter,
PrStoreUTHit,
PrStorePrUTHits,
PatPV3DFuture,
PrForwardTracking,
)
from PyConf.Algorithms import (
MakeSelection__Track_v1 as TrackV1Selection,
MakeSelection__Track_v2 as TrackV2Selection,
......@@ -27,7 +40,11 @@ from PyConf.Algorithms import (
TracksFitConverter,
VPClus,
VPClusFull,
VPRetinaSPmixer,
VPRetinaClusterCreator,
VPRetinaFullClustering,
VeloClusterTrackingSIMD,
VeloRetinaClusterTrackingSIMD,
TrackBeamLineVertexFinderSoA,
PrVeloUT,
SciFiTrackForwardingStoreHit,
......@@ -114,6 +131,22 @@ def make_VeloClusterTrackingSIMD_hits(make_raw=default_raw_event):
return VeloClusterTrackingSIMD(RawEventLocation=make_raw()).HitsLocation
@configurable
def make_VeloRetinaClusterTrackingSIMD_hits(make_raw=default_raw_event):
"""Makes velo hits with VeloRetinaClusterTrackingSIMD
Args:
make_raw (DataHandle): RawEventLocation for VeloRetinaClusterTrackingSIMD, defaults to `default_raw_event <PyConf.application.default_raw_event>`.
Returns:
DataHandle: VeloClusterTrackingSIMD's HitsLocation.
"""
cluster = make_RetinaCluster(make_raw)
raw_cluster = cluster["raw"]
return VeloRetinaClusterTrackingSIMD(
RawEventLocation=raw_cluster).HitsLocation
def make_VPClus_location_and_offsets(make_raw=default_raw_event):
"""Makes velo clusters with VPClus
......@@ -136,7 +169,11 @@ def make_VPClus_hits():
@configurable
def make_velo_full_clusters(make_raw=default_raw_event):
return VPClusFull(RawEventLocation=make_raw()).ClusterLocation
mixed_SP = VPRetinaSPmixer(RawEventLocation=make_raw())
return VPRetinaFullClustering(
RawEventLocation=mixed_SP.RawEventLocationMixed
).ClusterLocation if fpga_clustering else VPClusFull(
RawEventLocation=make_raw()).ClusterLocation
@configurable
......@@ -163,6 +200,48 @@ def make_VeloClusterTrackingSIMD_tracks(make_raw=default_raw_event):
}
@configurable
def make_RetinaCluster(make_raw=default_raw_event):
"""Makes velo clusters with VPRetinaClusterCreator.
Args:
make_raw (DataHandle): RawEventLocation for VPRetinaClusterCreator, defaults to `default_raw_event <PyConf.application.default_raw_event>`.
Returns:
"""
mixed_SP = VPRetinaSPmixer(RawEventLocation=make_raw())
clustering = VPRetinaClusterCreator(
RawEventLocation=mixed_SP.RawEventLocationMixed)
raw_retina_cluster = clustering.RetinaClusterLocation
return {"raw": raw_retina_cluster}
@configurable
def make_VeloRetinaClusterTrackingSIMD_tracks(make_cluster=make_RetinaCluster):
"""Makes velo tracks with VeloRetinaClusterTrackingSIMD.
Args:
make_raw (DataHandle): RawEventLocation for VeloClusterTrackingSIMD, defaults to `default_raw_event <PyConf.application.default_raw_event>`.
Returns:
A dict mapping forward-, backward-going and v2 velo tracks to ``'Pr'``, ``'Pr::backward'`` and ``'v2'`` respectively.
"""
cluster = make_cluster()
raw_cluster = cluster["raw"]
tracking = VeloRetinaClusterTrackingSIMD(RawEventLocation=raw_cluster)
forward_going_tracks = tracking.TracksLocation
backward_going_tracks = tracking.TracksBackwardLocation
v2_tracks = TracksVPMergerConverter(
TracksForwardLocation=forward_going_tracks,
TracksBackwardLocation=backward_going_tracks,
HitsLocation=tracking.HitsLocation).OutputTracksLocation
return {
"Pr": forward_going_tracks,
"Pr::backward": backward_going_tracks,
"v2": v2_tracks
}
@configurable
def all_velo_track_types(make_velo_tracks=make_VeloClusterTrackingSIMD_tracks):
"""Helper function to get all types of velo tracks.
......@@ -185,6 +264,29 @@ def all_velo_track_types(make_velo_tracks=make_VeloClusterTrackingSIMD_tracks):
}
@configurable
def all_velo_retina_track_types(
make_velo_tracks=make_VeloRetinaClusterTrackingSIMD_tracks):
"""Helper function to get all types of velo tracks.
Args:
make_velo_tracks (DataHandle): velo tracking algorithm, defaults to `make_VeloRetinaClusterTrackingSIMD_tracks`.
Returns:
A dict mapping forward-, backward-going, v1 and v2 velo tracks to ``'Pr'``, ``'Pr::backward'``, ``'v1'`` and ``'v2'`` respectively.
"""
velo_tracks = make_velo_tracks()
velo_tracks_v2 = velo_tracks["v2"]
velo_tracks_v1 = FromV2TrackV1Track(
InputTracksName=velo_tracks_v2).OutputTracksName
return {
"Pr": velo_tracks["Pr"],
"Pr::backward": velo_tracks["Pr::backward"],
"v2": velo_tracks_v2,
"v1": velo_tracks_v1
}
def make_TrackBeamLineVertexFinderSoA_pvs(velo_tracks):
"""Makes primary vertices from velo tracks using TrackBeamLineVertexFinderSoA.
......@@ -240,7 +342,8 @@ def make_pvs():
Returns:
DataHandle: primary vertices
"""
return make_reco_pvs(all_velo_track_types())
return make_reco_pvs(all_velo_retina_track_types(
) if fpga_clustering else all_velo_track_types())
def require_pvs(pvs):
......@@ -486,7 +589,8 @@ def make_hlt1_tracks():
Returns:
A dict mapping all types of velo, upstream and HLT1 forward tracks to ``'Velo'``, ``'Upstream'`` and ``'Forward'`` respectively.
"""
velo_tracks = all_velo_track_types()
velo_tracks = all_velo_retina_track_types(
) if fpga_clustering else all_velo_track_types()
velo_ut_tracks = all_upstream_track_types(velo_tracks)
forward_tracks = all_hlt1_forward_track_types(velo_ut_tracks)
return {
......@@ -497,8 +601,10 @@ def make_hlt1_tracks():
@configurable
def make_VeloKalman_fitted_tracks(tracks,
make_hits=make_VeloClusterTrackingSIMD_hits):
def make_VeloKalman_fitted_tracks(
tracks,
make_hits=make_VeloRetinaClusterTrackingSIMD_hits
if fpga_clustering else make_VeloClusterTrackingSIMD_hits):
"""Fits tracks with VeloKalman.
Args:
......
......@@ -13,27 +13,27 @@ from __future__ import absolute_import, division, print_function
In this file, algorithms needed to run the MC reconstruction checking (PrTrackChecker) are defined.
'''
from PyConf.tonic import (configurable)
from PyConf.dataflow import DataHandle
from PyConf.components import Tool
from PyConf.application import default_raw_event
from PyConf.application import make_data_with_FetchDataFromFile
from PyConf.Algorithms import (
VPFullCluster2MCParticleLinker,
PrLHCbID2MCParticle,
PrLHCbID2MCParticleVPUTFTMU,
PrTrackAssociator,
PrTrackChecker,
PrUTHitChecker,
)
VPFullCluster2MCParticleLinker, PrLHCbID2MCParticle,
PrLHCbID2MCParticleVPUTFTMU, PrTrackAssociator, PrTrackChecker,
PrUTHitChecker, PrimaryVertexChecker, VPFullCluster2MCParticleLinker,
TrackListRefiner, TrackResChecker, TrackIPResolutionCheckerNT,
DataPacking__Unpack_LHCb__MCVPHitPacker_)
from PyConf.Algorithms import LHCb__Converters__RecVertex__v2__fromVectorLHCbRecVertices as FromVectorLHCbRecVertices
from PyConf.Tools import LoKi__Hybrid__MCTool
from PyConf.Tools import LoKi__Hybrid__TrackSelector as LoKiTrackSelector
from RecoConf.hlt1_tracking import (
make_PrStoreUTHit_hits,
make_FTRawBankDecoder_clusters,
make_velo_full_clusters,
)
from RecoConf.hlt1_tracking import (make_PrStoreUTHit_hits,
make_FTRawBankDecoder_clusters,
make_velo_full_clusters)
from Hlt2Conf.data_from_file import mc_unpackers
......@@ -47,7 +47,6 @@ def get_item(x, key):
TODO: This helper function can be replaces once Moore!63 has been addressed.
"""
from PyConf.dataflow import DataHandle
if isinstance(x, DataHandle): return x
return x[key]
......@@ -111,7 +110,7 @@ def monitor_tracking_efficiency(
LinksToLHCbIDs,
MCCategories,
HitTypesToCheck,
WriteHistos=1,
WriteHistos=2,
):
""" Setup tracking efficiency checker
......@@ -265,10 +264,66 @@ def get_best_tracks_checkers(
return efficiency_checkers
@configurable
def get_pv_checkers(
pvs,
tracks,
produce_ntuple=False,
make_links_lhcbids_mcparticles=make_links_lhcbids_mcparticles_tracking_system
):
assert isinstance(
pvs, DataHandle), "Please provide reconstructed primary verticies"
links_to_lhcbids = make_links_lhcbids_mcparticles()
links_to_tracks = make_links_tracks_mcparticles(
InputTracks=tracks, LinksToLHCbIDs=links_to_lhcbids)
pv_checkers = []
pvchecker = PrimaryVertexChecker(
produceNtuple=produce_ntuple,
inputVerticesName=pvs,
inputTracksName=tracks["v1"],
MCVertexInput=mc_unpackers()["MCVertices"],
MCParticleInput=mc_unpackers()["MCParticles"],
MCHeaderLocation=make_data_with_FetchDataFromFile("/Event/MC/Header"),
MCPropertyInput=make_data_with_FetchDataFromFile(
"/Event/MC/TrackInfo"))
pv_checkers.append(pvchecker)
return pv_checkers
def make_track_filter(InputTracks, code):
from PyConf.Algorithms import TrackListRefiner
from PyConf.Tools import LoKi__Hybrid__TrackSelector as LoKiTrackSelector
selector = LoKiTrackSelector(Code=code, StatPrint=True)
filtered_tracks = TrackListRefiner(
inputLocation=InputTracks["v1"], Selector=selector).outputLocation
return filtered_tracks
def monitor_track_resolution(InputTracks):
links_to_lhcbids = make_links_lhcbids_mcparticles_tracking_system()
links_to_tracks = make_links_tracks_mcparticles(
InputTracks["v1"], LinksToLHCbIDs=links_to_lhcbids)
res_checker = TrackResChecker(
TracksInContainer=InputTracks["v1"],
MCParticleInContainer=mc_unpackers()["MCParticles"],
LinkerInTable=links_to_tracks)
return res_checker
def monitor_IPresolution(InputTracks, InputPVs, VeloTracks):
vertexConverter = FromVectorLHCbRecVertices(
InputVerticesName=InputPVs,
InputTracksName=VeloTracks).OutputVerticesName
links_to_lhcbids = make_links_lhcbids_mcparticles_tracking_system()
links_to_tracks = make_links_tracks_mcparticles(
InputTracks, LinksToLHCbIDs=links_to_lhcbids)
IPres_checker = TrackIPResolutionCheckerNT(
TrackContainer=InputTracks,
MCParticleInput=mc_unpackers()["MCParticles"],
MCHeaderLocation=make_data_with_FetchDataFromFile("/Event/MC/Header"),
LinkerLocation=links_to_tracks,
PVContainer=vertexConverter,
NTupleLUN="FILE1")
return IPres_checker
......@@ -20,7 +20,9 @@ from RecoConf.hlt1_muonmatch import make_tracks_with_muonmatch_ipcut
from .hlt1_muonid import make_muon_id, make_tracks_with_muon_id
from .hlt2_tracking import make_hlt2_tracks, make_TrackBestTrackCreator_tracks
from .calorimeter_reconstruction import make_calo
from .mc_checking import get_track_checkers, get_best_tracks_checkers
from .mc_checking import (get_track_checkers, get_best_tracks_checkers,
get_pv_checkers, monitor_IPresolution,
monitor_track_resolution)
from .reco_objects_from_file import reconstruction
from PyConf.application import default_raw_event
from .rich_reconstruction import make_rich_pids, make_rich_pixels, default_rich_reco_options
......@@ -33,6 +35,8 @@ from PyConf.Algorithms import Rich__Future__Rec__TrackFilter as TrackFilter
from GaudiKernel.SystemOfUnits import MeV, mm
from Moore.config import Reconstruction
from .fpga_clustering import fpga_clustering
def reco_prefilters():
return [require_gec()]
......@@ -62,8 +66,16 @@ def standalone_hlt1_reco(do_mc_checking=False):
"Forward": hlt1_tracks["Forward"],
}
data += get_track_checkers(types_and_locations_for_checkers)
data += [monitor_track_resolution(hlt1_tracks["Forward"])]
data += [
monitor_IPresolution(fitted_tracks["v1"], pvs,
hlt1_tracks["Velo"]["v1"])
]
data += get_pv_checkers(pvs, hlt1_tracks["Velo"], produce_ntuple=True)
return Reconstruction('hlt1_reco', data, reco_prefilters())
return Reconstruction(
'hlt1_{}reco'.format('fpga_clustering_' if fpga_clustering else ''),
data, reco_prefilters())
def standalone_hlt1_reco_velo_only():
......
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
#!/usr/bin/python
# Script for accessing histograms of reconstructible and
# reconstructed tracks for different tracking categories
# created by hlt1_reco_baseline_with_mcchecking
#
# The efficency is calculated usig TGraphAsymmErrors
# and Bayesian error bars
#
# author: Dorothea vom Bruch (dorothea.vom.bruch@cern.ch)
# date: 10/2018
# updated by Peilian Li
#
import os, sys
import argparse
import ROOT
from ROOT import TMultiGraph, TMath, TAxis, TH1, TLatex, TGaxis, TROOT, TSystem, TCanvas, TFile, TTree, TObject
from ROOT import kDashed, kRed, kGreen, kBlue, kBlack, kAzure, kGray, kOrange, kMagenta, kCyan, kTRUE, kFALSE, gPad
from ROOT import gROOT, gStyle, TStyle, TPaveText
from ROOT import ROOT, vector, TGraphAsymmErrors
import logging
import subprocess
def getEfficiencyHistoNames():
return ["eta", "p", "pt", "phi", "nPV"]
def getTrackers():
return ["Velo", "Upstream", "Forward"]
def getOriginFolders():
basedict = {"Velo": {}, "Upstream": {}, "Forward": {}}
basedict["Velo"]["folder"] = "VeloTrackChecker/"
basedict["Upstream"]["folder"] = "UpstreamTrackChecker/"
basedict["Forward"]["folder"] = "ForwardTrackChecker/"
return basedict
def get_colors():
return [kBlack, kAzure, kOrange, kMagenta + 2, kGreen + 3, kCyan + 2]
def get_markers():
return [20, 24, 21, 22, 23, 25]
def get_fillstyles():
return [3004, 3003, 3325, 3144, 3244, 3444]
def getGhostHistoNames():
return ["eta", "nPV", "pt", "p"]
def argument_parser():
parser = argparse.ArgumentParser(description="location of the tuple file")
parser.add_argument(
'--filename',
type=str,
default='MCMatching_MiniBias.root',
nargs='+',
help='input files, including path')
parser.add_argument(
'--outfile',
type=str,
default='efficiency_plots.root',
help='output file')
parser.add_argument(
'--label', nargs='+', default="EffChecker", help='label for files')
parser.add_argument(
'--plotstyle',
default=os.getcwd(),
help='location of LHCb utils plot style file')
parser.add_argument(
'--dist',
default=False,
action='store_true',
help='draw histogram of all files')
parser.add_argument(
'--plotelec',
default=False,
action='store_true',
help='draw eff of electron on the same canvas')
parser.add_argument(
'--savepdf',
default=False,
action='store_true',
help='save plots in pdf format')
return parser
def get_files(tf, filename, label):
for i, f in enumerate(filename):
tf[label[i]] = TFile(f, "read")
return tf
def get_eff(eff, hist, tf, histoName, label, var):
eff = {}
hist = {}
for i, lab in enumerate(label):
numeratorName = histoName + "_reconstructed"
numerator = tf[lab].Get(numeratorName)
denominatorName = histoName + "_reconstructible"
denominator = tf[lab].Get(denominatorName)
if numerator.GetEntries() == 0 or denominator.GetEntries() == 0:
continue
numerator.Sumw2()
denominator.Sumw2()
eff[lab] = TGraphAsymmErrors()
eff[lab].SetName(lab)
eff[lab].Divide(numerator, denominator, "cl=0.683 b(1,1) mode")
eff[lab].SetTitle(lab + "not elec.")
if (histoName.find('strange') != -1):
eff[lab].SetTitle(lab + " from stranges")
if (histoName.find('electron') != -1):
eff[lab].SetTitle(lab + " electron")
hist[lab] = denominator.Clone()
hist[lab].SetName("h_numerator_notElectrons")
hist[lab].SetTitle(var + " histo. not elec.")
if (histoName.find('strange') != -1):
hist[lab].SetTitle(var + " histo. stranges")
if (histoName.find('electron') != -1):
hist[lab].SetTitle(var + " histo. electron")
if var == "p":
eff[lab].GetXaxis().SetRangeUser(0, 50000)
hist[lab].GetXaxis().SetRangeUser(0, 50000)
if var == "pt":
eff[lab].GetXaxis().SetRangeUser(0, 5000)
hist[lab].GetXaxis().SetRangeUser(0, 5000)
return eff, hist
def PrCheckerEfficiency(filename, outfile, label, plotstyle, dist, plotelec,
savepdf):
sys.path.append(os.path.abspath(plotstyle))
from utils.LHCbStyle import setLHCbStyle, set_style
from utils.ConfigHistos import (efficiencyHistoDict, ghostHistoDict,
categoriesDict, getCuts)
from utils.Legend import place_legend
setLHCbStyle()
markers = get_markers()
colors = get_colors()
styles = get_fillstyles()
tf = {}
tf = get_files(tf, filename, label)
outputfile = TFile(outfile, "recreate")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.05)
efficiencyHistoDict = efficiencyHistoDict()
efficiencyHistos = getEfficiencyHistoNames()
ghostHistos = getGhostHistoNames()
ghostHistoDict = ghostHistoDict()
categories = categoriesDict()
cuts = getCuts()
trackers = getTrackers()
folders = getOriginFolders()
for tracker in trackers:
outputfile.cd()
trackerDir = outputfile.mkdir(tracker)
trackerDir.cd()
for cut in cuts[tracker]:
cutDir = trackerDir.mkdir(cut)
cutDir.cd()
folder = folders[tracker]["folder"]
print(folder)
histoBaseName = "Track/" + folder + tracker + "/" + cut + "_"
# calculate efficiency
for histo in efficiencyHistos:
canvastitle = "efficiency_" + histo + ", " + categories[
tracker][cut]["title"]
# get efficiency for not electrons category
histoName = histoBaseName + "" + efficiencyHistoDict[histo][
"variable"]
print("not electrons: " + histoName)
eff = {}
hist_den = {}
eff, hist_den = get_eff(eff, hist_den, tf, histoName, label,
histo)
name = "efficiency_" + histo
canvas = TCanvas(name, canvastitle)
mg = TMultiGraph()
for i, lab in enumerate(label):
mg.Add(eff[lab])
set_style(eff[lab], colors[i], markers[i], styles[i])
mg.Draw("AP")
mg.GetYaxis().SetRangeUser(0, 1.05)
xtitle = efficiencyHistoDict[histo]["xTitle"]
mg.GetXaxis().SetTitle(xtitle)
mg.GetYaxis().SetTitle("Efficiency")
if dist:
for i, lab in enumerate(label):
rightmax = 1.05 * hist_den[lab].GetMaximum()
scale = gPad.GetUymax() / rightmax
hist_den[lab].Scale(scale)
if i == 0:
set_style(hist_den[lab], kGray, markers[i],
styles[i])
else:
set_style(hist_den[lab], colors[i] - 10,
markers[i], styles[i])
hist_den[lab].Draw("hist SAME")
else:
rightmax = 0.95 * hist_den[label[0]].GetMaximum()
scale = gPad.GetUymax() / rightmax
set_style(hist_den[label[0]], kBlue - 10, markers[i],
styles[i])
hist_den[label[0]].Scale(scale)
hist_den[label[0]].Draw("hist SAME")
canvas.PlaceLegend()
cutName = categories[tracker][cut]["title"]
latex.DrawLatex(0.7, 0.85, "LHCb simultaion")
latex.DrawLatex(0.35, 0.3, cutName)
canvasName = tracker + "_" + cut + "_" + histo + ".pdf"
if savepdf:
canvas.SaveAs(canvasName)
canvas.SetRightMargin(0.05)
canvas.Write()
# get efficiency for electrons category
if categories[tracker][cut]["plotElectrons"]:
histoNameElec = "Track/" + folder + tracker + "/" + categories[
tracker][cut]["Electrons"]
histoName = histoNameElec + "_" + efficiencyHistoDict[
histo]["variable"]
print("electrons: " + histoName)
eff_elec = {}
hist_elec = {}
eff_elec, hist_elec = get_eff(eff_elec, hist_elec, tf,
histoName, label, histo)
#draw efficiency of electron
canvas_elec = TCanvas(name + "_elec",
canvastitle + "_elec")
mg_elec = TMultiGraph()
for i, lab in enumerate(label):
mg_elec.Add(eff_elec[lab])
set_style(eff_elec[lab], colors[i], markers[i],
styles[i])
set_style(hist_elec[lab], colors[i] - 10, markers[i],
styles[i])
mg_elec.Draw("AP")
mg_elec.GetYaxis().SetRangeUser(0, 1.05)
mg_elec.GetXaxis().SetTitle(xtitle)
mg_elec.GetYaxis().SetTitle("Efficiency")
if dist:
for lab in label:
rightmax = 1.05 * hist_elec[lab].GetMaximum()
scale = gPad.GetUymax() / rightmax
hist_elec[lab].Scale(scale)
hist_elec[lab].Draw("hist SAME")
else:
rightmax = 1.05 * hist_elec[label[0]].GetMaximum()
scale = gPad.GetUymax() / rightmax
hist_elec[label[0]].Scale(scale)
hist_elec[label[0]].Draw("hist SAME")
set_style(hist_elec[label[0]], kBlue - 10, markers[i],
styles[i])
canvas_elec.PlaceLegend()
latex.DrawLatex(0.7, 0.85, "LHCb simultaion")
latex.DrawLatex(0.35, 0.3, cutName)
canvasName_elec = tracker + "_" + cut + "_" + histo + "_elec.pdf"
if savepdf:
canvas_elec.SaveAs(canvasName_elec)
canvas_elec.SetRightMargin(0.05)
canvas_elec.Write()
#draw them both
if plotelec:
canvas_com = TCanvas(name + "_combine",
title + "_combine")
i = 0
mg_comb = TMultiGraph()
for lab in label:
mg_comb.Add(eff[lab])
mg_comb.Add(eff_elec[lab])
set_style(eff[lab], colors[i], markers[i],
styles[i])
set_style(eff_elec[lab], colors[i + 1],
markers[i + 1], styles[i])
set_style(hist_den[lab], colors[i] - 10,
markers[i], styles[i])
set_style(hist_elec[lab], colors[i + 1] - 10,
markers[i + 1], styles[i])
rightmax = 1.05 * hist_den[lab].GetMaximum()
scale = gPad.GetUymax() / rightmax
hist_den[lab].Scale(scale)
rightmax_elec = 1.05 * hist_elec[lab].GetMaximum()
scale_elec = gPad.GetUymax() / rightmax_elec
hist_elec[lab].Scale(scale_elec)
i = i + 2
mg_comb.Draw("ap")
mg_comb.GetYaxis().SetRangeUser(0, 1.05)
rightmax = 1.05 * hist_den[label[0]].GetMaximum()
mg_comb.GetXaxis().SetTitle(xtitle)
mg_comb.GetYaxis().SetTitle("Efficiency")
mg_comb.GetYaxis().SetRangeUser(0, 1.05)
mg_comb.SetTitle(tracker + " " + cut)
for lab in label:
hist_lab[lab].Draw("hist SAME")
hist_elec[lab].Draw("hist SAME")
canvas_com.PlaceLegend()
latex.DrawLatex(0.7, 0.85, "LHCb simultaion")
latex.DrawLatex(0.35, 0.3, cutName)
canvas_com.SetRightMargin(0.05)
canvas_com.Write()
# calculate ghost rate
if tracker == "Forward":
histoBaseName = "Track/" + folder + tracker + "/"
for histo in ghostHistos:
trackerDir.cd()
title = "ghost rate vs " + histo
canvas = TCanvas(title, title)
gPad.SetTicks()
numeratorName = histoBaseName + ghostHistoDict[histo][
"variable"] + "_Ghosts"
denominatorName = histoBaseName + ghostHistoDict[histo][
"variable"] + "_Total"
print("ghost histo: " + histoBaseName + " " + numeratorName +
" " + denominatorName)
ghost = {}
mg = TMultiGraph()
for i, lab in enumerate(label):
numerator = tf[lab].Get(numeratorName)
denominator = tf[lab].Get(denominatorName)
numerator.Sumw2()
denominator.Sumw2()
ghost[lab] = TGraphAsymmErrors()
ghost[lab].SetName(lab)
ghost[lab].Divide(numerator, denominator,
"cl=0.683 b(1,1) mode")
set_style(ghost[lab], colors[i], markers[i], styles[i])
mg.Add(ghost[lab])
xtitle = ghostHistoDict[histo]["xTitle"]
mg.GetXaxis().SetTitle(xtitle)
mg.GetYaxis().SetTitle("ghost rate")
mg.Draw("ap")
canvas.PlaceLegend()
if savepdf:
canvas.SaveAs("ghost_rate_" + histo + ".pdf")
canvas.Write()
outputfile.Write()
outputfile.Close()
if __name__ == '__main__':
parser = argument_parser()
args = parser.parse_args()
PrCheckerEfficiency(**vars(args))
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
'''
Script for accessing tuples of IP resolution checker to obtain the values of mean and width of IP resolution
as well as a check of the IP error distribution and efficiencies in different chi2 cut.
The resolution is fitted by a Gaussian function
author: Peilian Li(peilian.li@cern.ch)
date: 01/2020
'''
import os, sys
import argparse
import ROOT
from ROOT import TMultiGraph, TMath, TAxis, TH1, TLatex, TGaxis, TROOT, TSystem, TCanvas, TFile, TTree, TObject
from ROOT import kDashed, kRed, kGreen, kBlue, kCyan, kMagenta, kBlack, kOrange, kAzure, kTRUE, kFALSE, gPad, TH1F, TH2F, TF1
from ROOT import gDirectory, gROOT, gStyle, TStyle, TPaveText, TString
from ROOT import ROOT, vector, TGraphAsymmErrors
def get_colors():
return [kBlack, kBlue, kOrange, kMagenta + 2, kGreen + 3, kCyan + 2]
def get_markers():
return [20, 24, 21, 22, 23, 25]
def get_fillstyles():
return [3004, 3003, 3325, 3144, 3244, 3444]
def get_files(tf, filename, label):
for i, f in enumerate(filename):
tf[label[i]] = TFile(f, "read")
return tf
def get_trees(tr, tf, label):
for lab in label:
tr[lab] = tf[lab].Get("TrackIPResolutionCheckerNT/tracks")
return tr
def argument_parser():
parser = argparse.ArgumentParser(description="location of the tuple file")
parser.add_argument(
'--filename',
nargs='+',
default=[],
help='input tuple files, including path')
parser.add_argument(
'--label',
nargs='+',
default=["IPchecker"],
help='label of input files')
parser.add_argument(
'--outfile',
default='IPresolution_plots.root',
help='output file name ')
parser.add_argument(
'--savepdf',
default=False,
action='store_true',
help='save plots in pdf format')
parser.add_argument(
'--plotstyle',
default=os.getcwd(),
help='location of LHCb utils plot style file')
return parser
def get_resolution(resx, resy, tr, label):
resIPx = {}
resIPy = {}
resIPx_1 = {}
resIPy_1 = {}
markers = get_markers()
colors = get_colors()
styles = get_fillstyles()
cutAcc = "trueeta<5 && trueeta>2 && typeofprefix==0"
print("Velo track from PV in acceptance: " + cutAcc)
for i, lab in enumerate(label):
### typeofprefix==0 for track from PV and matched with MC
resIPx[lab] = TH2F("resIPx_" + lab, "IPx:1/pt", 20, 0, 2, 100, -300,
300)
resIPy[lab] = TH2F("resIPy_" + lab, "IPy:1/pt", 20, 0, 2, 100, -300,
300)
resIPx[lab].SetMarkerStyle(1)
resIPy[lab].SetMarkerStyle(1)
varx = "recIPx*1000:1.0/truept"
vary = "recIPy*1000:1.0/truept"
print("IPx var: " + varx + " " + " IPy var: " + vary)
tr[lab].Draw(varx + ">>resIPx_" + lab, cutAcc)
tr[lab].Draw(vary + ">>resIPy_" + lab, cutAcc)
resIPx[lab].FitSlicesY()
resIPy[lab].FitSlicesY()
resx[lab] = gDirectory.Get("resIPx_" + lab + "_2")
resy[lab] = gDirectory.Get("resIPy_" + lab + "_2")
resIPx_1[lab] = gDirectory.Get("resIPx_" + lab + "_1")
resIPy_1[lab] = gDirectory.Get("resIPy_" + lab + "_1")
for i in range(1, 20):
print(
lab + ": in 1/pT region: (" +
format(resIPx_1[lab].GetBinLowEdge(i), '.2f') + ", " + format(
resIPx_1[lab].GetBinLowEdge(i) +
resIPx_1[lab].GetBinWidth(i), '.2f') + ") [c/GeV]" +
" ---- " + "resIPx for mean : " +
format(resIPx_1[lab].GetBinContent(i), '.2f') +
"[\mum] width : " + format(resx[lab].GetBinContent(i), '.2f') +
"[\mum] ---- " + "resIPy for mean : " +
format(resIPy_1[lab].GetBinContent(i), '.2f') +
"[\mum] width : " + format(resy[lab].GetBinContent(i), '.2f') +
"[\mum]")
return resx, resy
def PrCheckerIPresolution(filename, label, outfile, savepdf, plotstyle):
sys.path.append(os.path.abspath(plotstyle))
from utils.LHCbStyle import setLHCbStyle, set_style
setLHCbStyle()
from utils.Legend import place_legend
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.05)
markers = get_markers()
colors = get_colors()
styles = get_fillstyles()
tf = {}
tr = {}
tf = get_files(tf, filename, label)
tr = get_trees(tr, tf, label)
outputfile = TFile(outfile, "recreate")
outputfile.cd()
gr_resx = {}
gr_resy = {}
gr_resx, gr_resy = get_resolution(gr_resx, gr_resy, tr, label)
canvas1 = TCanvas("resIPx_pT", "resIPx v.s. 1/pT")
canvas2 = TCanvas("resIPy_pT", "resIPy v.s. 1/pT")
canvas = TCanvas("IPChi2", "IPChi2")
canvas.SetLogy()
canvas1.cd()
latex.DrawLatex(0.7, 0.85, "LHCb simultaion")
polx = {}
Par0x = {}
Par1x = {}
Funcx = {}
gr_resx[label[0]].GetYaxis().SetTitle("#sigma_{IPx} [#mum]")
gr_resx[label[0]].GetXaxis().SetTitle("1/p_{T} [c/GeV]")
gr_resx[label[0]].SetTitle("#sigma(IP_{x}):1/p_{T}")
for idx, lab in enumerate(label):
set_style(gr_resx[lab], colors[idx], markers[idx], 0)
if idx == 0:
gr_resx[lab].Draw("E1 p1")
else:
gr_resx[lab].Draw("E1 p1 same")
polx[lab] = TF1("polx_" + lab, "pol1", 0, 3)
polx[lab].SetLineColor(colors[idx])
print(lab + ": Fit to Resolution of IPx v.s. 1/pT:")
gr_resx[lab].Fit("polx_" + lab, "R")
Par0x[lab] = format(polx[lab].GetParameter(0), '.2f')
Par1x[lab] = format(polx[lab].GetParameter(1), '.2f')
Funcx[lab] = lab + ": " + Par0x[lab] + "+" + Par1x[lab] + "/p_{T}"
gr_resx[lab].SetTitle(Funcx[lab])
#canvas1.PlaceLegend()
place_legend(
canvas1, 0.5, 0.2, 0.85, 0.45, header="LHCb simulation", option="lep")
canvas1.SetRightMargin(0.05)
canvas1.Write()
if savepdf:
canvas1.SaveAs("resIPx_pt.pdf")
canvas2.cd()
latex.DrawLatex(0.7, 0.85, "LHCb simultaion")
poly = {}
Par0y = {}
Par1y = {}
Funcy = {}
gr_resy[label[0]].GetYaxis().SetTitle("#sigma_{IPy} [#mum]")
gr_resy[label[0]].GetXaxis().SetTitle("1/p_{T} [c/GeV]")
gr_resy[label[0]].SetTitle("#sigma(IP_{y}):1/p_{T}")
for idx, lab in enumerate(label):
set_style(gr_resy[lab], colors[idx], markers[idx], 0)
if idx == 0:
gr_resy[lab].Draw("E1 p1")
else:
gr_resy[lab].Draw("E1 p1 same")
poly[lab] = TF1("poly_" + lab, "pol1", 0, 3)
poly[lab].SetLineColor(colors[idx])
print(lab + ": Fit to Resolution of IPy v.s. 1/pT:")
gr_resy[lab].Fit("poly_" + lab, "R")
Par0y[lab] = format(poly[lab].GetParameter(0), '.2f')
Par1y[lab] = format(poly[lab].GetParameter(1), '.2f')
Funcy[lab] = lab + ": " + Par0y[lab] + "+" + Par1y[lab] + "/p_{T}"
gr_resy[lab].SetTitle(Funcy[lab])
#canvas2.PlaceLegend()
place_legend(
canvas2, 0.5, 0.2, 0.85, 0.45, header="LHCb simulation", option="lep")
canvas2.SetRightMargin(0.05)
canvas2.Write()
if savepdf:
canvas2.SaveAs("resIPy_pt.pdf")
#### rec IP chi2 distribution
recIPChi2 = {}
var = "recIPChi2"
cutAcc = "trueeta<5 && trueeta>2 && typeofprefix==0"
for i, lab in enumerate(label):
recIPChi2[lab] = TH1F("recIPChi2_" + lab, lab, 100, 0, 200)
tr[lab].Draw(var + ">>recIPChi2_" + lab, cutAcc)
recIPChi2[lab].SetLineColor(colors[i])
canvas.cd()
latex.DrawLatex(0.7, 0.85, "LHCb simultaion")
recIPChi2[label[0]].Draw()
recIPChi2[label[0]].SetXTitle("#chi^{2}_{IP}")
recIPChi2[label[0]].SetYTitle("N_{tracks}")
for lab in label[1:]:
recIPChi2[lab].Draw("hist same")
place_legend(canvas, 0.5, 0.5, 0.8, 0.7, "", "lep")
canvas.SetRightMargin(0.05)
canvas.Write()
if savepdf:
canvas.SaveAs("recIPchi2.pdf")
for lab in label:
### print efficiency of different IPchi2 cut
Numerator = TH1F("Numerator", "Numerator", 100, 0, 200)
Denominator = TH1F("Denominator", "Denominator", 100, 0, 200)
tr[lab].Draw(var + ">>Denominator", cutAcc)
for cut in [100, 25, 16, 9, 4]:
cutChi2 = " && recIPChi2<" + format(cut)
cutNum = cutAcc + cutChi2
tr[lab].Draw(var + ">>Numerator", cutNum)
if Numerator.GetEntries() == 0 or Denominator.GetEntries() == 0:
continue
Eff = Numerator.GetEntries() / (Denominator.GetEntries() + 0.0)
print(lab + ": Efficiency of IPchi2<" + format(cut) + " : " +
format(Eff, '.2%'))
outputfile.Write()
outputfile.Close()
if __name__ == '__main__':
parser = argument_parser()
args = parser.parse_args()
PrCheckerIPresolution(**vars(args))
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
#!/usr/bin/python
# Script for accessing histograms of reconstructible and
# reconstructed tracks for different tracking categories
# created by hlt1_reco_baseline_with_mcchecking.py and
# hlt1_reco_baseline_and_Allen_with_mcchecking.py
#
# The efficency is calculated usig TGraphAsymmErrors
# and Bayesian error bars
#
# author: Dorothea vom Bruch (dorothea.vom.bruch@cern.ch)
# date: 10/2018
# updated by Peilian Li
#
import os, sys
import argparse
import ROOT
from ROOT import TMultiGraph, TMath, TAxis, TH1, TLatex, TGaxis, TROOT, TSystem, TCanvas, TFile, TTree, TObject
from ROOT import kDashed, kGray, kOrange, kMagenta, kRed, kGreen, kCyan, kBlue, kBlack, kAzure, kTRUE, kFALSE, gPad, TPad
from ROOT import gROOT, gStyle, TStyle, TPaveText, TH1F
from ROOT import ROOT, TH1D, TH1F, TGraphAsymmErrors
import logging
import subprocess
def getEfficiencyHistoNames():
return ["eta", "p", "pt", "phi", "nPV"]
def getOriginFolders():
basedict = {"Forward": {}, "MuonMatch": {}}
basedict["Forward"]["folder"] = "ForwardTrackChecker/"
basedict["MuonMatch"]["folder"] = "MuonMatchTrackChecker/"
return basedict
def get_colors():
return [kBlack, kAzure, kOrange, kMagenta + 2, kGreen + 3, kCyan + 2]
def get_markers():
return [20, 24, 21, 22, 23, 25]
def get_fillstyles():
return [3004, 3003, 3325, 3144, 3244, 3444]
def argument_parser():
parser = argparse.ArgumentParser(description="location of the tuple file")
parser.add_argument(
'--filename',
type=str,
default='PrChecker_MuonID_MiniBias.root',
nargs='+',
help='input files, including path')
parser.add_argument(
'--outfile',
type=str,
default='MuonIDefficiency_plots.root',
help='output file')
parser.add_argument(
'--label', nargs='+', default="EffChecker", help='label for files')
parser.add_argument(
'--plotstyle',
default=os.getcwd(),
help='location of LHCb utils plot style file')
parser.add_argument(
'--savepdf',
default=False,
action='store_true',
help='save plots in pdf format')
parser.add_argument(
'--printval',
default=False,
action='store_true',
help='print out the muon ID efficiency in momentum bins ')
return parser
def get_files(tf, filename, label):
for i, f in enumerate(filename):
tf[label[i]] = TFile(f, "read")
return tf
def get_eff(eff, hist, tf, histoName, histoName_Den, label, var, printval):
eff = {}
hist = {}
for i, lab in enumerate(label):
numeratorName = histoName + "_reconstructed"
numerator = tf[lab].Get(numeratorName)
denominatorName = histoName_Den + "_reconstructed"
denominator = tf[lab].Get(denominatorName)
if numerator.GetEntries() == 0 or denominator.GetEntries() == 0:
continue
numerator.Sumw2()
denominator.Sumw2()
eff[lab] = TGraphAsymmErrors()
eff[lab].SetName(lab)
eff[lab].Divide(numerator, denominator, "cl=0.683 b(1,1) mode")
eff[lab].SetTitle(lab + "not elec.")
if (histoName.find('strange') != -1):
eff[lab].SetTitle(lab + " from stranges")
if (histoName.find('electron') != -1):
eff[lab].SetTitle(lab + " electron")
hist[lab] = denominator.Clone()
hist[lab].SetName("h_numerator_notElectrons")
hist[lab].SetTitle(var + " histo. not elec.")
if (histoName.find('strange') != -1):
hist[lab].SetTitle(var + " histo. stranges")
if (histoName.find('electron') != -1):
hist[lab].SetTitle(var + " histo. electron")
if var == "p":
eff[lab].GetXaxis().SetRangeUser(0, 50000)
hist[lab].GetXaxis().SetRangeUser(0, 50000)
#print the muonID efficiency in each p bin
if var == "p" and printval:
for i in range(1, numerator.GetNbinsX()):
if denominator.GetBinContent(i) == 0:
continue
Eff = numerator.GetBinContent(i) / (
denominator.GetBinContent(i) + 0.0)
print(lab + ": Efficiency of muon ID in (" +
format(numerator.GetBinLowEdge(i), '.2f') + ", " +
format(
numerator.GetBinLowEdge(i) +
numerator.GetBinWidth(i), '.2f') + ") [GeV/c] : " +
format(Eff, '.2%'))
if var == "pt":
eff[lab].GetXaxis().SetRangeUser(0, 5000)
hist[lab].GetXaxis().SetRangeUser(0, 5000)
return eff, hist
def PrCheckerMuonIDEff(filename, outfile, label, plotstyle, savepdf, printval):
sys.path.append(os.path.abspath(plotstyle))
from utils.LHCbStyle import setLHCbStyle, set_style
from utils.ConfigHistos import (efficiencyHistoDict, categoriesDict,
getCuts)
from utils.Legend import place_legend
setLHCbStyle()
markers = get_markers()
colors = get_colors()
styles = get_fillstyles()
tf = {}
tf = get_files(tf, filename, label)
outputfile = TFile(outfile, "recreate")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.055)
efficiencyHistoDict = efficiencyHistoDict()
efficiencyHistos = getEfficiencyHistoNames()
categories = categoriesDict()
cuts = getCuts()
folders = getOriginFolders()
tracker = "MuonMatch"
outputfile.cd()
trackerDir = outputfile.mkdir(tracker)
trackerDir.cd()
for cut in cuts[tracker]:
cutDir = trackerDir.mkdir(cut)
cutDir.cd()
folder = folders[tracker]["folder"]
print(folder)
histoBaseName = "Track/" + folder + tracker + "/" + cut + "_"
histoBaseName_den = "Track/" + "ForwardTrackChecker/Forward/" + cut + "_"
# calculate efficiency
for histo in efficiencyHistos:
canvastitle = "efficiency vs. " + histo + ", " + categories[
tracker][cut]["title"]
name = "efficiency_" + histo + "_" + cut
# get efficiency for not electrons category
histoName = histoBaseName + "" + efficiencyHistoDict[histo][
"variable"]
histoName_den = histoBaseName_den + "" + efficiencyHistoDict[
histo]["variable"]
print("not electrons: " + histoName)
eff = {}
hist_den = {}
eff, hist_den = get_eff(eff, hist_den, tf, histoName,
histoName_den, label, histo, printval)
canvas = TCanvas(name, canvastitle)
mg = TMultiGraph()
for i, lab in enumerate(label):
mg.Add(eff[lab])
set_style(eff[lab], colors[i], markers[i], styles[i])
mg.Draw("AP")
mg.GetYaxis().SetRangeUser(0, 1.05)
xtitle = efficiencyHistoDict[histo]["xTitle"]
mg.GetXaxis().SetTitle(xtitle)
mg.GetYaxis().SetTitle("Muon ID Efficiency")
for i, lab in enumerate(label):
rightmax = 1.05 * hist_den[lab].GetMaximum()
scale = gPad.GetUymax() / rightmax
hist_den[lab].Scale(scale)
if i == 0:
set_style(hist_den[lab], kGray, markers[i], styles[i])
else:
set_style(hist_den[lab], colors[i] - 10, markers[i],
styles[i])
hist_den[lab].Draw("hist SAME")
canvas.PlaceLegend()
cutName = categories[tracker][cut]["title"]
latex.DrawLatex(0.35, 0.3, cutName)
latex.DrawLatex(0.7, 0.85, "LHCb simulation")
canvas.SetRightMargin(0.05)
canvas.Write()
canvasName = "MuonIDEff_" + cut + "_" + histo + ".pdf"
if savepdf:
canvas.SaveAs(canvasName)
canvas.SetRightMargin(0.05)
canvas.Write()
outputfile.Write()
outputfile.Close()
if __name__ == '__main__':
parser = argument_parser()
args = parser.parse_args()
PrCheckerMuonIDEff(**vars(args))
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
'''
Script for the plots of tracking resolution v.s. p and eta
The resolution is fitted by a Gaussian function
author: Peilian Li(peilian.li@cern.ch)
date: 01/2020
'''
import os, sys
import argparse
import ROOT
from ROOT import TMultiGraph, TMath, TAxis, TH2F, TH2, TH1, TLatex, TGaxis, TROOT, TSystem, TCanvas, TFile, TTree, TObject
from ROOT import kDashed, kOrange, kGray, kMagenta, kCyan, kRed, kGreen, kBlue, kBlack, kAzure, kTRUE, kFALSE, gPad, TH1, TH2, TF1
from ROOT import gROOT, gDirectory, gStyle, TStyle, TPaveText, TString
from ROOT import ROOT, vector, TGraphAsymmErrors
from collections import defaultdict
def get_colors():
return [kBlack, kBlue, kOrange, kMagenta + 2, kGreen + 3, kCyan + 2]
def get_markers():
return [20, 24, 21, 22, 23, 25]
def get_fillstyles():
return [3004, 3003, 3325, 3144, 3244, 3444]
def get_files(tf, filename, label):
for i, f in enumerate(filename):
tf[label[i]] = TFile(f, "read")
return tf
def argument_parser():
parser = argparse.ArgumentParser(
description="location of the histogram file")
parser.add_argument(
'--filename', nargs='+', default=[], help='name of input files')
parser.add_argument(
'--label',
nargs='+',
default=["TrackRes"],
help='name of input tuple files')
parser.add_argument(
'--outfile',
type=str,
default='TrackResolution_plots.root',
help='name of output files')
parser.add_argument(
'--savepdf',
default=False,
action='store_true',
help='save plots in pdf format')
parser.add_argument(
'--plotstyle',
default=os.getcwd(),
help='location of LHCb utils plot style file')
return parser
def PrCheckerTrackResolution(filename, label, outfile, savepdf, plotstyle):
sys.path.append(os.path.abspath(plotstyle))
from utils.LHCbStyle import setLHCbStyle, set_style
from utils.Legend import place_legend
setLHCbStyle()
markers = get_markers()
colors = get_colors()
styles = get_fillstyles()
tf = {}
tf = get_files(tf, filename, label)
outputfile = TFile(outfile, "recreate")
outputfile.cd()
hdp_p = {}
hdp_eta = {}
hres_p = {}
hres_eta = {}
hmom = {}
heta = {}
canvas1 = TCanvas("res_p", "res v.s. p")
canvas1.cd()
for idx, lab in enumerate(label):
hdp_p[lab] = tf[lab].Get(
"Track/TrackResChecker/ALL/vertex/dpoverp_vs_p")
hdp_p[lab].SetName("dpoverp_p_" + lab)
hmom[lab] = hdp_p[lab].ProjectionX()
hmom[lab].SetTitle("p histo. " + lab)
hdp_p[lab].FitSlicesY()
hres_p[lab] = gDirectory.Get("dpoverp_p_" + lab + "_2")
hres_p[lab].GetYaxis().SetTitle("dp/p [%]")
hres_p[lab].GetXaxis().SetTitle("p [GeV/c]")
hres_p[lab].GetYaxis().SetRangeUser(0, 1.2)
hres_p[lab].SetTitle("Res. " + lab)
set_style(hres_p[lab], colors[idx], markers[idx], 0)
if idx == 0:
hres_p[lab].Draw("E1 p1")
set_style(hmom[lab], kGray, markers[idx], styles[idx])
else:
hres_p[lab].Draw("E1 p1 same")
set_style(hmom[lab], colors[idx] - 10, markers[idx], styles[idx])
hmom[lab].Scale(gPad.GetUymax() / hmom[lab].GetMaximum())
hmom[lab].Draw("hist same")
for i in range(1, hres_p[lab].GetNbinsX()):
hres_p[lab].SetBinContent(i, hres_p[lab].GetBinContent(i) * 100)
print(lab + ": Track resolution (dp/p) in p region: (" +
format(hres_p[lab].GetBinLowEdge(i), '.2f') + ", " + format(
hres_p[lab].GetBinLowEdge(i) +
hres_p[lab].GetBinWidth(i), '.2f') + ") [GeV/c]" +
" --- " + format(hres_p[lab].GetBinContent(i), '.2f') + "%")
print("-----------------------------------------------------")
canvas1.PlaceLegend()
canvas1.SetRightMargin(0.05)
canvas1.Write()
if savepdf:
canvas1.SaveAs("trackres_p.pdf")
print("=====================================================")
canvas2 = TCanvas("res_eta", "res v.s. eta")
canvas2.cd()
for idx, lab in enumerate(label):
hdp_eta[lab] = tf[lab].Get(
"Track/TrackResChecker/ALL/vertex/dpoverp_vs_eta")
hdp_eta[lab].SetName("dpoverp_eta_" + lab)
hdp_eta[lab].FitSlicesY()
heta[lab] = hdp_eta[lab].ProjectionX()
heta[lab].SetTitle("#eta histo. " + lab)
hres_eta[lab] = gDirectory.Get("dpoverp_eta_" + lab + "_2")
hres_eta[lab].GetYaxis().SetTitle("dp/p [%]")
hres_eta[lab].GetXaxis().SetTitle("#eta")
hres_eta[lab].GetYaxis().SetRangeUser(0, 1.2)
hres_eta[lab].SetTitle("Res. " + lab)
set_style(hres_eta[lab], colors[idx], markers[idx], 0)
if idx == 0:
hres_eta[lab].Draw("E1 p1")
set_style(heta[lab], kGray, markers[idx], styles[idx])
else:
hres_eta[lab].Draw("E1 p1 same")
set_style(heta[lab], colors[idx] - 10, markers[idx], styles[idx])
heta[lab].Scale(gPad.GetUymax() / heta[lab].GetMaximum())
heta[lab].Draw("hist same")
for i in range(1, hres_eta[lab].GetNbinsX()):
hres_eta[lab].SetBinContent(i,
hres_eta[lab].GetBinContent(i) * 100)
print(lab + ": Track resolution (dp/p) in eta region: (" +
format(hres_eta[lab].GetBinLowEdge(i), '.2f') + ", " +
format(
hres_eta[lab].GetBinLowEdge(i) +
hres_eta[lab].GetBinWidth(i), '.2f') + ")" + " --- " +
format(hres_eta[lab].GetBinContent(i), '.2f') + "%")
canvas2.PlaceLegend()
canvas2.SetRightMargin(0.05)
canvas2.Write()
if savepdf:
canvas2.SaveAs("trackres_eta.pdf")
outputfile.Write()
outputfile.Close()
if __name__ == '__main__':
parser = argument_parser()
args = parser.parse_args()
PrCheckerTrackResolution(**vars(args))
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
#!/usr/bin/python
# The script for plotting PV efficinecy as the function
# of various distributions: nTracks, z, r.
# As input the NTuple created by hlt1_reco_pvchecker.py
# is needed.
#
# The efficency is calculated usig TGraphAsymmErrors
# and Bayesian error bars
#
# author: Agnieszka Dziurda (agnieszka.dziurda@cern.ch)
# date: 02/2020
#
# Example of usage:
# ../../../run python PrimaryVertexCheckerEfficiency.py
# --file file1.root file2.root --label name1 name2 --dist
#
import os, sys
import argparse
import ROOT
from ROOT import TFile, TTree
from ROOT import kRed, kBlue, kOrange, kMagenta, kGreen, kCyan, kGray
from ROOT import gROOT, TLegend
parser = argparse.ArgumentParser()
parser.add_argument(
'--file', dest='fileName', default="", nargs='+', help='filename to plot')
parser.add_argument(
'--label', dest='label', default="", nargs='+', help='labels for files')
parser.add_argument(
'--tree',
dest='treeName',
default="",
nargs='+',
help='tree name to plot',
)
parser.add_argument(
'--smog',
dest='smog',
default=False,
action='store_true',
help='set true for SMOG')
parser.add_argument(
'--multi',
dest='multi',
default=False,
action='store_true',
help='add multiplicity plots')
parser.add_argument(
'--dist',
dest='dist',
default=False,
action='store_true',
help='plot distributions in the canvas')
parser.add_argument(
'--prefix',
dest='prefix',
default="pv_eff",
help='prefix for the plot name',
)
parser.add_argument(
'--dir',
dest='directory',
default=os.getcwd(),
help='tree name to plot',
)
def get_categories(multi, smog):
cut = {}
cut["all"] = {"cut": ""}
cut["isolated"] = {"cut": "&&isol==1"}
if not smog:
cut["close"] = {"cut": "&&isol==0"}
if multi:
cut["1st"] = {"cut": "&&multimc==1"}
cut["2nd"] = {"cut": "&&multimc==2"}
cut["3rd"] = {"cut": "&&multimc==3"}
cut["4th"] = {"cut": "&&multimc==4"}
cut["5th"] = {"cut": "&&multimc==5"}
return cut
def get_colors():
return [kRed, kBlue, kOrange, kMagenta + 2, kGreen + 3, kCyan + 2]
def get_markers():
return [21, 20, 22, 23, 24, 25, 26]
def get_labels(number_of_files):
label = []
for i in range(0, number_of_files):
label.append("PV Checker {number}".format(number=str(i + 1)))
return label
if __name__ == '__main__':
args = parser.parse_args()
path = args.directory + "/utils/"
sys.path.append(os.path.abspath(path))
gROOT.SetBatch()
from pvutils import get_default_tree_name
from pvutils import get_files, get_trees, get_eff, plot_eff
from pvutils import set_legend
markers = get_markers()
colors = get_colors()
label = args.label
if args.label == "":
label = get_labels(len(args.fileName))
tr = {}
tf = {}
tf = get_files(tf, label, args.fileName)
tr = get_trees(tf, tr, label, args.treeName, True)
eff_tr = {}
eff_z = {}
eff_r = {}
hist_tr = {}
hist_z = {}
hist_r = {}
cat = get_categories(args.multi, args.smog)
eff_tr, hist_tr = get_eff(eff_tr, hist_tr, tr, "nrectrmc", colors, markers,
args.smog, cat, label)
eff_z, hist_z = get_eff(eff_z, hist_z, tr, "zMC", colors, markers,
args.smog, cat, label)
eff_r, hist_r = get_eff(eff_r, hist_r, tr, "rMC", colors, markers,
args.smog, cat, label)
if args.dist:
legend = TLegend(0.15, 0.82, 0.88, 0.98)
else:
legend = TLegend(0.15, 0.86, 0.88, 0.98)
legend = set_legend(legend, label, eff_tr, hist_tr, args.dist)
plot_eff(eff_tr, hist_tr, args.prefix, "ntracks", cat, label, legend,
args.dist)
plot_eff(eff_z, hist_z, args.prefix, "z", cat, label, legend, args.dist)
plot_eff(eff_r, hist_r, args.prefix, "r", cat, label, legend, args.dist)
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
#!/usr/bin/python
# The script for plotting PV efficinecy as the function
# of various distributions: nTracks, z, r.
# As input the NTuple created by hlt1_reco_pvchecker.py
# is needed.
#
# The efficency is calculated usig TGraphAsymmErrors
# and Bayesian error bars
#
# author: Agnieszka Dziurda (agnieszka.dziurda@cern.ch)
# date: 02/2020
#
# Example of usage:
# ../../../run python PrimaryVertexCheckerPull.py
# --file file1.root file2.root --label name1 name2
#
import os, sys
import argparse
import ROOT
from ROOT import TFile, TTree
from ROOT import kRed, kBlue, kOrange, kMagenta, kGreen, kCyan, kGray, kYellow
from ROOT import gROOT, TLegend
parser = argparse.ArgumentParser()
parser.add_argument(
'--file', dest='fileName', default="", nargs='+', help='filename to plot')
parser.add_argument(
'--label', dest='label', default="", nargs='+', help='labels for files')
parser.add_argument(
'--tree',
dest='treeName',
default="",
nargs='+',
help='tree name to plot',
)
parser.add_argument(
'--smog',
dest='smog',
default=False,
action='store_true',
help='set true for SMOG')
parser.add_argument(
'--multi',
dest='multi',
default=False,
action='store_true',
help='add multiplicity plots')
parser.add_argument(
'--dist',
dest='dist',
default=False,
action='store_true',
help='plot distributions in the canvas')
parser.add_argument(
'--prefix',
dest='prefix',
default="pv_pull",
help='prefix for the plot name',
)
parser.add_argument(
'--dir',
dest='directory',
default=os.getcwd(),
help='tree name to plot',
)
def get_categories(multi, smog):
cut = {}
cut["all"] = {"cut": ""}
cut["isolated"] = {"cut": "&&isol==1"}
if not smog:
cut["close"] = {"cut": "&&isol==0"}
if multi:
cut["1st"] = {"cut": "&&multimc==1"}
cut["2nd"] = {"cut": "&&multimc==2"}
cut["3rd"] = {"cut": "&&multimc==3"}
cut["4th"] = {"cut": "&&multimc==4"}
cut["5th"] = {"cut": "&&multimc==5"}
return cut
def get_colors():
return [kRed, kBlue, kOrange, kMagenta, kGreen, kCyan]
def get_markers():
return [21, 20, 22, 23, 24, 25, 26]
def get_labels(number_of_files):
label = []
for i in range(0, number_of_files):
label.append("PV Checker {number}".format(number=str(i + 1)))
return label
if __name__ == '__main__':
args = parser.parse_args()
path = args.directory + "/utils/"
sys.path.append(os.path.abspath(path))
gROOT.SetBatch()
from pvutils import get_default_tree_name
from pvutils import get_files, get_trees
from pvutils import set_legend, get_global, plot_comparison
markers = get_markers()
colors = get_colors()
cat = get_categories(args.multi, args.smog)
label = args.label
if args.label == "":
label = get_labels(len(args.fileName))
tr = {}
tf = {}
tf = get_files(tf, label, args.fileName)
tr = get_trees(tf, tr, label, args.treeName, True)
hist_x = {}
hist_y = {}
hist_z = {}
norm = True #to-do
hist_x = get_global(hist_x, tr, "pullx", "#Delta x / #sigma_{x}",
"Candidates Normalized", colors, markers, cat, label)
hist_y = get_global(hist_y, tr, "pully", "#Delta y / #sigma_{y}",
"Candidates Normalized", colors, markers, cat, label)
hist_z = get_global(hist_z, tr, "pullz", "#Delta z / #sigma_{z}",
"Candidates Normalized", colors, markers, cat, label)
plot_comparison(hist_x, args.prefix, "pullx", cat, label, colors, norm)
plot_comparison(hist_y, args.prefix, "pully", cat, label, colors, norm)
plot_comparison(hist_z, args.prefix, "pullz", cat, label, colors, norm)
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
#!/usr/bin/python
# The script for plotting PV efficinecy as the function
# of various distributions: nTracks, z, r.
# As input the NTuple created by hlt1_reco_pvchecker.py
# is needed.
#
# The efficency is calculated usig TGraphAsymmErrors
# and Bayesian error bars
#
# author: Agnieszka Dziurda (agnieszka.dziurda@cern.ch)
# date: 02/2020
#
# Example of usage:
# ../../../run python PrimaryVertexCheckerResolution.py
# --file file1.root file2.root --label name1 name2
#
import os, sys
import argparse
import ROOT
from ROOT import TFile, TTree
from ROOT import kRed, kBlue, kOrange, kMagenta, kGreen, kCyan, kGray, kYellow
from ROOT import gROOT, TLegend
parser = argparse.ArgumentParser()
parser.add_argument(
'--file', dest='fileName', default="", nargs='+', help='filename to plot')
parser.add_argument(
'--label', dest='label', default="", nargs='+', help='labels for files')
parser.add_argument(
'--tree',
dest='treeName',
default="",
nargs='+',
help='tree name to plot',
)
parser.add_argument(
'--smog',
dest='smog',
default=False,
action='store_true',
help='set true for SMOG')
parser.add_argument(
'--multi',
dest='multi',
default=False,
action='store_true',
help='add multiplicity plots')
parser.add_argument(
'--dist',
dest='dist',
default=False,
action='store_true',
help='plot distributions in the canvas')
parser.add_argument(
'--prefix',
dest='prefix',
default="pv_resol",
help='prefix for the plot name',
)
parser.add_argument(
'--dir',
dest='directory',
default=os.getcwd(),
help='tree name to plot',
)
def get_categories(multi, smog):
cut = {}
cut["all"] = {"cut": ""}
cut["isolated"] = {"cut": "&&isol==1"}
if not smog:
cut["close"] = {"cut": "&&isol==0"}
if multi:
cut["1st"] = {"cut": "&&multimc==1"}
cut["2nd"] = {"cut": "&&multimc==2"}
cut["3rd"] = {"cut": "&&multimc==3"}
cut["4th"] = {"cut": "&&multimc==4"}
cut["5th"] = {"cut": "&&multimc==5"}
return cut
def get_colors():
return [kRed, kBlue, kOrange, kMagenta, kGreen, kCyan]
def get_markers():
return [21, 20, 22, 23, 24, 25, 26]
def get_labels(number_of_files):
label = []
for i in range(0, number_of_files):
label.append("PV Checker {number}".format(number=str(i + 1)))
return label
if __name__ == '__main__':
args = parser.parse_args()
path = args.directory + "/utils/"
sys.path.append(os.path.abspath(path))
gROOT.SetBatch()
from pvutils import get_default_tree_name
from pvutils import get_files, get_trees
from pvutils import set_legend, get_global, plot_comparison
markers = get_markers()
colors = get_colors()
cat = get_categories(args.multi, args.smog)
label = args.label
if args.label == "":
label = get_labels(len(args.fileName))
tr = {}
tf = {}
tf = get_files(tf, label, args.fileName)
tr = get_trees(tf, tr, label, args.treeName, True)
hist_x = {}
hist_y = {}
hist_z = {}
norm = True
hist_x = get_global(hist_x, tr, "dx", "#Delta x [mm]",
"Candidates Normalized", colors, markers, cat, label)
hist_y = get_global(hist_y, tr, "dy", "#Delta y [mm]",
"Candidates Normalized", colors, markers, cat, label)
hist_z = get_global(hist_z, tr, "dz", "#Delta z [mm]",
"Candidates Normalized", colors, markers, cat, label)
plot_comparison(hist_x, args.prefix, "dx", cat, label, colors, norm)
plot_comparison(hist_y, args.prefix, "dy", cat, label, colors, norm)
plot_comparison(hist_z, args.prefix, "dz", cat, label, colors, norm)
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
from collections import defaultdict
def efficiencyHistoDict():
basedict = {
"eta": {},
"p": {},
"pt": {},
"phi": {},
"nPV": {},
"docaz": {}
}
basedict["eta"]["xTitle"] = "#eta"
basedict["eta"]["variable"] = "Eta"
basedict["p"]["xTitle"] = "p [MeV]"
basedict["p"]["variable"] = "P"
basedict["pt"]["xTitle"] = "p_{T} [MeV]"
basedict["pt"]["variable"] = "Pt"
basedict["phi"]["xTitle"] = "#phi [rad]"
basedict["phi"]["variable"] = "Phi"
basedict["nPV"]["xTitle"] = "# of PVs"
basedict["nPV"]["variable"] = "nPV"
basedict["docaz"]["xTitle"] = "docaz (mm)"
basedict["docaz"]["variable"] = "docaz"
return basedict
def ghostHistoDict():
basedict = {"eta": {}, "nPV": {}, "pt": {}, "p": {}}
basedict["eta"]["xTitle"] = "#eta"
basedict["eta"]["variable"] = "Eta"
basedict["nPV"]["xTitle"] = "# of PVs"
basedict["nPV"]["variable"] = "nPV"
basedict["pt"]["xTitle"] = "p_{T} [MeV]"
basedict["pt"]["variable"] = "Pt"
basedict["p"]["xTitle"] = "p [MeV]"
basedict["p"]["variable"] = "P"
return basedict
def getCuts():
basedict = {"Velo": {}, "Upstream": {}, "Forward": {}, "MuonMatch": {}}
basedict["Velo"] = [
"01_velo",
"02_long",
"03_long_P>5GeV",
"04_long_strange",
"05_long_strange_P>5GeV",
"06_long_fromB",
"07_long_fromB_P>5GeV",
"11_long_fromB_P>3GeV_Pt>0.5GeV",
"12_UT_long_fromB_P>3GeV_Pt>0.5GeV",
#"11_long_fromD_P>3GeV_Pt>0.5GeV", "11_long_strange_P>3GeV_Pt>0.5GeV",
#"06_long_fromD"
]
basedict["Upstream"] = [
"01_velo",
"02_velo+UT",
"03_velo+UT_P>5GeV",
"07_long",
"08_long_P>5GeV",
"09_long_fromB",
"10_long_fromB_P>5GeV",
"14_long_fromB_P>3GeV_Pt>0.5GeV",
"15_UT_long_fromB_P>3GeV_Pt>0.5GeV",
#"09_long_fromD", "14_long_fromD_P>3GeV_Pt>0.5GeV",
#"14_long_strange_P>3GeV_Pt>0.5GeV"
]
basedict["Forward"] = [
"01_long", "02_long_P>5GeV", "03_long_strange",
"04_long_strange_P>5GeV", "05_long_fromB", "06_long_fromB_P>5GeV",
"10_long_fromB_P>3GeV_Pt>0.5GeV", "11_UT_long_fromB_P>3GeV_Pt>0.5GeV",
"05_long_fromD", "10_long_fromD_P>3GeV_Pt>0.5GeV",
"10_long_strange_P>3GeV_Pt>0.5GeV"
]
basedict["MuonMatch"] = [
#"02_long_muon_P>3GeV_Pt>0.5GeV", "04_long_pion_P>3GeV_Pt>0.5GeV",
#"03_long_muon_from_strange_P>3GeV_Pt>0.5GeV",
"01_long",
"02_long_muon",
"03_long_muon_from_strange",
"04_long_pion"
]
return basedict
def categoriesDict():
basedict = defaultdict(lambda: defaultdict(dict))
basedict["MuonMatch"]["01_long"][
"title"] = "Long, forward track, 2 <#eta< 5"
basedict["MuonMatch"]["02_long_muon"][
"title"] = "Long, #mu, forward track, 2 <#eta< 5"
basedict["MuonMatch"]["02_long_muon_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, #mu, forward track, p>3GeV, pt>0.5GeV, 2 <#eta< 5"
basedict["MuonMatch"]["03_long_muoon_from_strange"][
"title"] = "Long, #mu from strange, forward track, 2 <#eta< 5"
basedict["MuonMatch"]["03_long_muon_from_strange_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, #mu from strange, forward track, p>3GeV, pt>0.5GeV, 2 <#eta< 5"
basedict["MuonMatch"]["04_long_pion"][
"title"] = "Long, #pi, forward track, 2 <#eta< 5"
basedict["MuonMatch"]["04_long_pion_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, #pi, forward track, p>3GeV, pt>0.5GeV, 2 <#eta< 5"
basedict["Velo"]["01_velo"]["title"] = "Velo, 2 <#eta< 5"
basedict["Velo"]["02_long"]["title"] = "Long, 2 <#eta< 5"
basedict["Velo"]["03_long_P>5GeV"]["title"] = "Long, p>5GeV, 2<#eta< 5"
basedict["Velo"]["04_long_strange"][
"title"] = "Long, from Strange, 2 <#eta < 5"
basedict["Velo"]["05_long_strange_P>5GeV"][
"title"] = "Long, from Strange, p>5GeV, 2 <#eta < 5"
basedict["Velo"]["06_long_fromB"]["title"] = "Long from B, 2<#eta<5"
basedict["Velo"]["06_long_fromD"]["title"] = "Long from D, 2<#eta<5"
basedict["Velo"]["07_long_fromB_P>5GeV"][
"title"] = "Long from B, p>5GeV, 2<#eta<5"
basedict["Velo"]["11_long_fromB_P>3GeV_Pt>0.5GeV"][
"title"] = "Long from B, p>3GeV, pt>0.5GeV, 2<#eta<5"
basedict["Velo"]["11_long_fromD_P>3GeV_Pt>0.5GeV"][
"title"] = "Long from D, p>3GeV, pt>0.5GeV, 2<#eta<5"
basedict["Velo"]["11_long_strange_P>3GeV_Pt>0.5GeV"][
"title"] = "Long from strange, p>3GeV, pt>0.5GeV, 2<#eta<5"
basedict["Velo"]["12_UT_long_fromB_P>3GeV_Pt>0.5GeV"][
"title"] = "UT Long, from B, p>3GeV, pt>0.5GeV, 2<#eta<5"
basedict["Velo"]["01_velo"]["plotElectrons"] = False
basedict["Velo"]["02_long"]["plotElectrons"] = True
basedict["Velo"]["03_long_P>5GeV"]["plotElectrons"] = False
basedict["Velo"]["04_long_strange"]["plotElectrons"] = False
basedict["Velo"]["05_long_strange_P>5GeV"]["plotElectrons"] = False
basedict["Velo"]["06_long_fromB"]["plotElectrons"] = True
basedict["Velo"]["06_long_fromD"]["plotElectrons"] = False
basedict["Velo"]["07_long_fromB_P>5GeV"]["plotElectrons"] = True
#basedict["Velo"]["11_long_fromB_P>3GeV_Pt>0.5GeV"]["plotElectrons"] = True
basedict["Velo"]["11_long_fromB_P>3GeV_Pt>0.5GeV"]["plotElectrons"] = False
basedict["Velo"]["11_long_fromD_P>3GeV_Pt>0.5GeV"]["plotElectrons"] = False
basedict["Velo"]["11_long_strange_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Velo"]["12_UT_long_fromB_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Velo"]["02_long"]["Electrons"] = "08_long_electrons"
basedict["Velo"]["06_long_fromB"]["Electrons"] = "09_long_fromB_electrons"
basedict["Velo"]["07_long_fromB_P>5GeV"][
"Electrons"] = "10_long_fromB_electrons_P>5GeV"
basedict["Velo"]["11_long_fromB_P>3GeV_Pt>0.5GeV"][
"Electrons"] = "11_long_fromB_electrons_P>3GeV_Pt>0.5GeV"
basedict["Upstream"]["01_velo"]["title"] = "Velo, 2 <#eta < 5"
basedict["Upstream"]["02_velo+UT"]["title"] = "VeloUT, 2 <#eta < 5"
basedict["Upstream"]["03_velo+UT_P>5GeV"][
"title"] = "VeloUT, p>5GeV, 2 <#eta < 5"
basedict["Upstream"]["07_long"]["title"] = "Long, 2 <#eta < 5"
basedict["Upstream"]["08_long_P>5GeV"][
"title"] = "Long, p>5GeV, 2 <#eta < 5"
basedict["Upstream"]["09_long_fromB"]["title"] = "Long from B, 2 <#eta < 5"
basedict["Upstream"]["09_long_fromD"]["title"] = "Long from D, 2 <#eta < 5"
basedict["Upstream"]["10_long_fromB_P>5GeV"][
"title"] = "Long from B, p>5GeV, 2 <#eta < 5"
basedict["Upstream"]["14_long_fromB_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, from B, p>3GeV, pt>0.5GeV"
basedict["Upstream"]["14_long_fromD_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, from D, p>3GeV, pt>0.5GeV"
basedict["Upstream"]["14_long_strange_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, from strange, p>3GeV, pt>0.5GeV"
basedict["Upstream"]["15_UT_long_fromB_P>3GeV_Pt>0.5GeV"][
"title"] = "Long, from B, p>3GeV, pt>0.5GeV"
basedict["Upstream"]["01_velo"]["plotElectrons"] = False
basedict["Upstream"]["02_velo+UT"]["plotElectrons"] = False
basedict["Upstream"]["03_velo+UT_P>5GeV"]["plotElectrons"] = False
basedict["Upstream"]["07_long"]["plotElectrons"] = True
basedict["Upstream"]["08_long_P>5GeV"]["plotElectrons"] = False
basedict["Upstream"]["09_long_fromB"]["plotElectrons"] = True
basedict["Upstream"]["09_long_fromD"]["plotElectrons"] = False
basedict["Upstream"]["10_long_fromB_P>5GeV"]["plotElectrons"] = True
#basedict["Upstream"]["14_long_fromB_P>3GeV_Pt>0.5GeV"]["plotElectrons"] = True
basedict["Upstream"]["14_long_fromB_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Upstream"]["14_long_fromD_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Upstream"]["14_long_strange_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Upstream"]["15_UT_long_fromB_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Upstream"]["07_long"]["Electrons"] = "11_long_electrons"
basedict["Upstream"]["09_long_fromB"][
"Electrons"] = "12_long_fromB_electrons"
basedict["Upstream"]["10_long_fromB_P>5GeV"][
"Electrons"] = "13_long_fromB_electrons_P>5GeV"
basedict["Upstream"]["14_long_fromB_P>3GeV_Pt>0.5GeV"][
"Electrons"] = "14_long_fromB_electrons_P>3GeV_Pt>0.5GeV"
basedict["Forward"]["01_long"]["title"] = "Long, 2 <#eta < 5"
basedict["Forward"]["02_long_P>5GeV"][
"title"] = "Long, p>5GeV, 2 <#eta < 5"
basedict["Forward"]["03_long_strange"][
"title"] = "Long, from strange, 2 <#eta < 5"
basedict["Forward"]["04_long_strange_P>5GeV"][
"title"] = "Long, from strange, p>5GeV, 2 <#eta < 5"
basedict["Forward"]["05_long_fromB"]["title"] = "Long from B, 2 <#eta < 5"
basedict["Forward"]["05_long_fromD"]["title"] = "Long from D, 2 <#eta < 5"
basedict["Forward"]["06_long_fromB_P>5GeV"][
"title"] = "Long from B, p>5GeV 2 <#eta < 5"
basedict["Forward"]["10_long_fromB_P>3GeV_Pt>0.5GeV"][
"title"] = "Long from B, p>3GeV, pt>0.5GeV, 2 <#eta < 5"
basedict["Forward"]["10_long_fromD_P>3GeV_Pt>0.5GeV"][
"title"] = "Long from D, p>3GeV, pt>0.5GeV, 2 <#eta < 5"
basedict["Forward"]["10_long_strange_P>3GeV_Pt>0.5GeV"][
"title"] = "Long from strange, p>3GeV, pt>0.5GeV, 2 <#eta < 5"
basedict["Forward"]["11_UT_long_fromB_P>3GeV_Pt>0.5GeV"][
"title"] = "UT Long from B, p>3GeV, pt>0.5GeV, 2 <#eta < 5"
basedict["Forward"]["01_long"]["plotElectrons"] = True
basedict["Forward"]["02_long_P>5GeV"]["plotElectrons"] = False
basedict["Forward"]["03_long_strange"]["plotElectrons"] = False
basedict["Forward"]["04_long_strange_P>5GeV"]["plotElectrons"] = False
basedict["Forward"]["05_long_fromB"]["plotElectrons"] = True
basedict["Forward"]["05_long_fromD"]["plotElectrons"] = False
basedict["Forward"]["06_long_fromB_P>5GeV"]["plotElectrons"] = True
#basedict["Forward"]["10_long_fromB_P>3GeV_Pt>0.5GeV"]["plotElectrons"] = True
basedict["Forward"]["10_long_fromB_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Forward"]["10_long_fromD_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Forward"]["10_long_strange_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Forward"]["11_UT_long_fromB_P>3GeV_Pt>0.5GeV"][
"plotElectrons"] = False
basedict["Forward"]["01_long"]["Electrons"] = "07_long_electrons"
basedict["Forward"]["05_long_fromB"][
"Electrons"] = "08_long_fromB_electrons"
basedict["Forward"]["06_long_fromB_P>5GeV"][
"Electrons"] = "09_long_fromB_electrons_P>5GeV"
basedict["Forward"]["10_long_fromB_P>3GeV_Pt>0.5GeV"][
"Electrons"] = "10_long_fromB_electrons_P>3GeV_Pt>0.5GeV"
return basedict
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
from ROOT import gStyle
from ROOT import gROOT, TH1, TH1F, TH1D
from ROOT import TStyle
def set_style(graph, color, marker, style):
graph.SetLineColor(color)
graph.SetMarkerColor(color)
graph.SetMarkerSize(1.0)
graph.SetMarkerStyle(marker)
graph.GetYaxis().SetTitleOffset(0.85)
if type(graph) == TH1F or type(graph) == TH1 or type(graph) == TH1D:
graph.SetFillColor(color)
graph.SetFillStyle(style)
graph.SetLineWidth(2)
graph.SetStats(False)
graph.GetYaxis().SetTitleOffset(1.0)
graph.GetYaxis().SetTitleSize(0.06)
graph.GetYaxis().SetLabelSize(0.06)
graph.GetXaxis().SetTitleSize(0.06)
graph.GetXaxis().SetLabelSize(0.06)
graph.GetXaxis().SetTitleFont(132)
graph.GetXaxis().SetLabelFont(132)
graph.GetYaxis().SetTitleFont(132)
graph.GetYaxis().SetLabelFont(132)
return graph
def setLHCbStyle():
global lhcbStyle
lhcbFont = 132
lhcbTSize = 0.06
lhcbWidth = 2
lhcbStyle = TStyle("lhcbStyle", "LHCb plots style")
lhcbStyle.SetFillColor(1)
lhcbStyle.SetFillStyle(1001) # solid
lhcbStyle.SetFrameFillColor(0)
lhcbStyle.SetFrameBorderMode(0)
lhcbStyle.SetPadBorderMode(0)
lhcbStyle.SetPadColor(0)
lhcbStyle.SetCanvasBorderMode(0)
lhcbStyle.SetCanvasColor(0)
lhcbStyle.SetStatColor(0)
lhcbStyle.SetLegendBorderSize(0)
lhcbStyle.SetLegendFont(132)
# use large fonts
lhcbStyle.SetTextFont(lhcbFont)
lhcbStyle.SetTitleFont(lhcbFont)
lhcbStyle.SetTextSize(lhcbTSize)
lhcbStyle.SetLabelFont(lhcbFont, "x")
lhcbStyle.SetLabelFont(lhcbFont, "y")
lhcbStyle.SetLabelFont(lhcbFont, "z")
lhcbStyle.SetLabelSize(lhcbTSize, "x")
lhcbStyle.SetLabelSize(lhcbTSize, "y")
lhcbStyle.SetLabelSize(lhcbTSize, "z")
lhcbStyle.SetTitleFont(lhcbFont)
lhcbStyle.SetTitleFont(lhcbFont, "x")
lhcbStyle.SetTitleFont(lhcbFont, "y")
lhcbStyle.SetTitleFont(lhcbFont, "z")
lhcbStyle.SetTitleSize(1.2 * lhcbTSize, "x")
lhcbStyle.SetTitleSize(1.2 * lhcbTSize, "y")
lhcbStyle.SetTitleSize(1.2 * lhcbTSize, "z")
# set the paper & margin sizes
lhcbStyle.SetPaperSize(20, 26)
lhcbStyle.SetPadTopMargin(0.05)
lhcbStyle.SetPadRightMargin(0.05) # increase for colz plots
lhcbStyle.SetPadBottomMargin(0.16)
lhcbStyle.SetPadLeftMargin(0.14)
# use medium bold lines and thick markers
lhcbStyle.SetLineWidth(lhcbWidth)
lhcbStyle.SetFrameLineWidth(lhcbWidth)
lhcbStyle.SetHistLineWidth(lhcbWidth)
lhcbStyle.SetFuncWidth(lhcbWidth)
lhcbStyle.SetGridWidth(lhcbWidth)
lhcbStyle.SetLineStyleString(2, "[12 12]")
# postscript dashes
lhcbStyle.SetMarkerStyle(20)
lhcbStyle.SetMarkerSize(1.0)
# label offsets
lhcbStyle.SetLabelOffset(0.010, "X")
lhcbStyle.SetLabelOffset(0.010, "Y")
# by default, do not display histogram decorations:
lhcbStyle.SetOptStat(0)
#lhcbStyle.SetOptStat("emr") # show only nent -e , mean - m , rms -r
# full opts at http:#root.cern.ch/root/html/TStyle.html#TStyle:SetOptStat
lhcbStyle.SetStatFormat("6.3g") # specified as c printf options
lhcbStyle.SetOptTitle(0)
lhcbStyle.SetOptFit(0)
#lhcbStyle.SetOptFit(1011) # order is probability, Chi2, errors, parameters
#titles
lhcbStyle.SetTitleOffset(0.95, "X")
lhcbStyle.SetTitleOffset(0.85, "Y")
lhcbStyle.SetTitleOffset(1.2, "Z")
lhcbStyle.SetTitleFillColor(0)
lhcbStyle.SetTitleStyle(0)
lhcbStyle.SetTitleBorderSize(0)
lhcbStyle.SetTitleFont(lhcbFont, "title")
lhcbStyle.SetTitleX(0.0)
lhcbStyle.SetTitleY(1.0)
lhcbStyle.SetTitleW(1.0)
lhcbStyle.SetTitleH(0.05)
# look of the statistics box:
lhcbStyle.SetStatBorderSize(0)
lhcbStyle.SetStatFont(lhcbFont)
lhcbStyle.SetStatFontSize(0.05)
lhcbStyle.SetStatX(0.9)
lhcbStyle.SetStatY(0.9)
lhcbStyle.SetStatW(0.25)
lhcbStyle.SetStatH(0.15)
# put tick marks on top and RHS of plots
lhcbStyle.SetPadTickX(1)
lhcbStyle.SetPadTickY(1)
# histogram divisions: only 5 in x to avoid label overlaps
lhcbStyle.SetNdivisions(505, "x")
lhcbStyle.SetNdivisions(510, "y")
gROOT.SetStyle("lhcbStyle")
return
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
import ROOT
import itertools
from ROOT import gStyle
# Some convenience function to easily iterate over the parts of the collections
# Needed if importing this script from another script in case TMultiGraphs are used
#ROOT.SetMemoryPolicy(ROOT.kMemoryStrict)
# Start a bit right of the Yaxis and above the Xaxis to not overlap with the ticks
start, stop = 0.28, 0.52
x_width, y_width = 0.4, 0.2
PLACES = [
(start, stop - y_width, start + x_width, stop), # top left opt
(start, start, start + x_width, start + y_width), # bottom left opt
(stop - x_width, stop - y_width, stop, stop), # top right opt
(stop - x_width, start, stop, start + y_width), # bottom right opt
(stop - x_width, 0.5 - y_width / 2, stop, 0.5 + y_width / 2), # right
(start, 0.5 - y_width / 2, start + x_width, 0.5 + y_width / 2)
] # left
# Needed if importing this script from another script in case TMultiGraphs are used
#ROOT.SetMemoryPolicy(ROOT.kMemoryStrict)
def transform_to_user(canvas, x1, y1, x2, y2):
"""
Transforms from Pad coordinates to User coordinates.
This can probably be replaced by using the built-in conversion commands.
"""
xstart = canvas.GetX1()
xlength = canvas.GetX2() - xstart
xlow = xlength * x1 + xstart
xhigh = xlength * x2 + xstart
if canvas.GetLogx():
xlow = 10**xlow
xhigh = 10**xhigh
ystart = canvas.GetY1()
ylength = canvas.GetY2() - ystart
ylow = ylength * y1 + ystart
yhigh = ylength * y2 + ystart
if canvas.GetLogy():
ylow = 10**ylow
yhigh = 10**yhigh
return xlow, ylow, xhigh, yhigh
def overlap_h(hist, x1, y1, x2, y2):
xlow = hist.FindFixBin(x1)
xhigh = hist.FindFixBin(x2)
for i in range(xlow, xhigh + 1):
val = hist.GetBinContent(i)
# Values
if y1 <= val <= y2:
return True
# Errors
if val + hist.GetBinErrorUp(i) > y1 and val - hist.GetBinErrorLow(
i) < y2:
return True
return False
def overlap_rect(rect1, rect2):
"""Do the two rectangles overlap?"""
if rect1[0] > rect2[2] or rect1[2] < rect2[0]:
return False
if rect1[1] > rect2[3] or rect1[3] < rect2[1]:
return False
return True
def overlap_g(graph, x1, y1, x2, y2):
x_values = list(graph.GetX())
y_values = list(graph.GetY())
x_err = list(graph.GetEX()) or [0] * len(x_values)
y_err = list(graph.GetEY()) or [0] * len(y_values)
for x, ex, y, ey in zip(x_values, x_err, y_values, y_err):
# Could maybe be less conservative
if overlap_rect((x1, y1, x2, y2), (x - ex, y - ey, x + ex, y + ey)):
# print "Overlap with graph", graph.GetName(), "at point", (x, y)
return True
return False
def place_legend(canvas,
x1=None,
y1=None,
x2=None,
y2=None,
header="",
option="LPF"):
gStyle.SetFillStyle(0)
gStyle.SetTextSize(0.06)
# If position is specified, use that
if all(x is not None for x in (x1, x2, y1, y2)):
return canvas.BuildLegend(x1, y1, x2, y2, header, option)
# Make sure all objects are correctly registered
canvas.Update()
# Build a list of objects to check for overlaps
objects = []
for x in canvas.GetListOfPrimitives():
if isinstance(x, ROOT.TH1) or isinstance(x, ROOT.TGraph):
objects.append(x)
elif isinstance(x, ROOT.THStack) or isinstance(x, ROOT.TMultiGraph):
objects.extend(x)
for place in PLACES:
place_user = canvas.PadtoU(*place)
# Make sure there are no overlaps
if any(obj.Overlap(*place_user) for obj in objects):
continue
return canvas.BuildLegend(place[0], place[1], place[2], place[3],
header, option)
# As a fallback, use the default values, taken from TCanvas::BuildLegend
return canvas.BuildLegend(0.4, 0.37, 0.88, 0.68, header, option)
# Monkey patch ROOT objects to make it all work
ROOT.THStack.__iter__ = lambda self: iter(self.GetHists())
ROOT.TMultiGraph.__iter__ = lambda self: iter(self.GetListOfGraphs())
ROOT.TH1.Overlap = overlap_h
ROOT.TGraph.Overlap = overlap_g
ROOT.TPad.PadtoU = transform_to_user
ROOT.TPad.PlaceLegend = place_legend
###############################################################################
# (c) Copyright 2019 CERN for the benefit of the LHCb Collaboration #
# #
# This software is distributed under the terms of the GNU General Public #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING". #
# #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization #
# or submit itself to any jurisdiction. #
###############################################################################
# The utils for processing output of the PrimaryVertexChecker output
#
# author: Agnieszka Dziurda (agnieszka.dziurda@cern.ch)
# date: 02/2020
#
from ROOT import TFile, TTree, TH1F, gDirectory, TGraphAsymmErrors
from ROOT import TCanvas
from ROOT import TGraphErrors, TLegend
from ROOT import gPad, kGray, TLatex
def get_default_tree_name(is_checker):
if is_checker:
return "PrimaryVertexChecker/101"
else:
return "VertexCompare/102"
def get_files(tf, label, files):
i = 0
for f in files:
tf[label[i]] = TFile(f)
i += 1
return tf
def get_trees(tf, tr, label, trees, is_checker):
i = 0
for lab in label:
if len(tf) == len(trees):
tr[lab] = tf[lab].Get(trees[i])
else:
tr[lab] = tf[lab].Get(get_default_tree_name(is_checker))
i += 1
return tr
def set_style(graph, color, marker, xaxis, yaxis, title):
graph.SetTitle("")
graph.SetLineColor(color)
graph.SetMarkerColor(color)
graph.SetMarkerSize(1.3)
graph.SetMarkerStyle(marker)
graph.GetYaxis().SetTitleOffset(0.85)
if type(graph) == TH1F:
graph.SetFillColor(color)
graph.SetLineWidth(4)
graph.SetStats(False)
graph.GetYaxis().SetTitleOffset(1.1)
graph.GetYaxis().SetTitleSize(0.06)
graph.GetYaxis().SetLabelSize(0.06)
graph.GetXaxis().SetTitleSize(0.06)
graph.GetXaxis().SetLabelSize(0.06)
graph.GetXaxis().SetTitleFont(132)
graph.GetXaxis().SetLabelFont(132)
graph.GetYaxis().SetTitleFont(132)
graph.GetYaxis().SetLabelFont(132)
if title != "":
graph.SetTitle(title)
if xaxis != "":
graph.GetXaxis().SetTitle(xaxis)
if yaxis != "":
graph.GetYaxis().SetTitle(yaxis)
def get_range(dependence, smog):
if dependence == "zMC":
if smog:
return "(100,-500,200)"
else:
return "(50,-200,200)"
elif dependence == "rMC":
return "(50,0.0,0.2)"
elif (dependence == "dx" or dependence == "dy"):
return "(50,-0.10,0.10)"
elif dependence == "dz":
return "(50,-0.5,0.5)"
elif "err" in dependence or "pull" in dependence:
return "(50,-3.5,3.5)"
else:
return "(66,4,70)"
def get_x_axis(dependence):
if dependence == "zMC":
return "z [mm]"
elif dependence == "rMC":
return "radial distance [mm]"
else:
return "number of tracks in Primary Vertex"
def get_eff(eff, hist, trees, dependence, colors, markers, smog, categories,
label):
hist_range = get_range(dependence, smog)
for cat in categories:
eff[cat] = {}
hist[cat] = {}
i = 0
for lab in label:
var_den = '{dependence}>>hist{code}_{dep}_{cat}_{lab}{hist_range}'.format(
dependence=dependence,
code="den",
dep=dependence,
cat=cat,
lab=lab,
hist_range=hist_range)
var_nom = '{dependence}>>hist{code}_{dep}_{cat}_{lab}{hist_range}'.format(
dependence=dependence,
code="nom",
dep=dependence,
cat=cat,
lab=lab,
hist_range=hist_range)
cut_den = 'nrectrmc>=4 {cuts}'.format(cuts=categories[cat]["cut"])
cut_nom = cut_den + ' && reco == 1'
trees[lab].Draw(var_nom, cut_nom)
trees[lab].Draw(var_den, cut_den)
h_nom = gDirectory.Get('hist{code}_{dep}_{cat}_{lab}'.format(
code="nom", dep=dependence, cat=cat, lab=lab))
h_den = gDirectory.Get('hist{code}_{dep}_{cat}_{lab}'.format(
code="den", dep=dependence, cat=cat, lab=lab))
g_eff = TGraphAsymmErrors()
g_eff.Divide(h_nom, h_den, "cl=0.683 b(1,1) mode")
set_style(h_nom, colors[i] - 8, markers[i], get_x_axis(dependence),
"Efficiency", "")
set_style(h_den, kGray, markers[i], get_x_axis(dependence),
"Efficiency", "")
hist[cat][lab] = {}
hist[cat][lab]["nom"] = h_nom
hist[cat][lab]["den"] = h_den
set_style(g_eff, colors[i], markers[i], get_x_axis(dependence),
"Efficiency", "")
eff[cat][lab] = g_eff
i += 1
return eff, hist
def set_legend(legend, label, gr, hist, dist):
legend.SetTextSize(0.04)
legend.SetTextFont(12)
legend.SetFillColor(4000)
legend.SetShadowColor(0)
legend.SetBorderSize(0)
legend.SetTextFont(132)
legend.SetNColumns(2)
#legend.SetHeader("LHCb Preliminary");
for lab in label:
legend.AddEntry(gr["all"][lab], "Efficiency {lab}".format(lab=lab),
"lep")
if dist:
legend.AddEntry(hist["all"][label[0]]["den"], "Distribution MC", "f")
for lab in label:
legend.AddEntry(hist["all"][lab]["nom"],
"Distribution {lab}".format(lab=lab), "f")
return legend
def plot_eff(eff, hist, prefix, dependence, categories, label, legend, dist):
for cat in categories:
can = TCanvas('canvas_{depen}_{cat}'.format(depen=dependence, cat=cat),
"cR", 1200, 800)
can.SetBottomMargin(0.15)
can.SetLeftMargin(0.12)
can.SetTopMargin(0.15)
if dist:
can.SetTopMargin(0.20)
can.SetRightMargin(0.05)
can.cd()
eff[cat][label[0]].GetYaxis().SetRangeUser(0.0, 1.1)
eff[cat][label[0]].Draw("AP")
for lab in label:
eff[cat][lab].Draw("SAME P")
if dist:
histmax_den = 1.1 * hist[cat][label[0]]["den"].GetMaximum()
scale = gPad.GetUymax() / histmax_den
hist[cat][label[0]]["den"].Scale(scale * 0.75)
hist[cat][label[0]]["den"].Draw("hist SAME")
for lab in label:
histmax_nom = 1.1 * hist[cat][lab]["nom"].GetMaximum()
scale = gPad.GetUymax() / histmax_nom
hist[cat][lab]["nom"].Scale(scale * 0.75)
hist[cat][lab]["nom"].Draw("SAME")
eff[cat][lab].Draw("SAME P")
legend.Draw("SAME")
saveName = '{prefix}_{dependence}_{cat}.pdf'.format(
prefix=prefix, dependence=dependence, cat=cat)
can.SaveAs(saveName)
def transfer_dependence(dep):
if dep == "pullx":
return "dx/errx"
elif dep == "pully":
return "dy/erry"
elif dep == "pullz":
return "dz/errz"
else:
return dep
def get_global(hist, trees, dependence, x_axis, y_axis, colors, markers,
categories, label):
hist_range = get_range(dependence, False)
dep = transfer_dependence(dependence)
for cat in categories:
hist[cat] = {}
i = 0
for lab in label:
var = '{dependence}>>hist_{dep}_{cat}_{lab}{hist_range}'.format(
dependence=dep,
dep=dependence,
cat=cat,
lab=lab,
hist_range=hist_range)
cut = 'nrectrmc>=4 && reco == 1 {cuts}'.format(
cuts=categories[cat]["cut"])
trees[lab].Draw(var, cut)
h = gDirectory.Get('hist_{dep}_{cat}_{lab}'.format(
dep=dependence, cat=cat, lab=lab))
if i == 0:
col = colors[i] - 10
else:
col = colors[i]
set_style(h, col, markers[i], x_axis, y_axis, "")
hist[cat][lab] = h
i += 1
return hist
def get_text_cor():
return {"x": [0.17, 0.65, 0.17, 0.65], "y": [0.92, 0.92, 0.75, 0.75]}
def set_text(text, color, x, y, lab, mean, mean_err, rms, rms_err, scale,
units):
s = 1.0
if scale:
s = 1000.0
u = ""
if units:
u = "[#mu m]"
text.SetNDC()
text.SetTextFont(132)
text.SetTextColor(color)
text.DrawLatex(x, y * 1.0, lab)
text.DrawLatex(
x, y * 0.95, "#mu = {0:0.2f} #pm {1:0.2f} {unit}".format(
mean * 1000.0, mean_err * 1000.0, unit=u))
text.DrawLatex(
x, y * 0.90, "#sigma = {0:0.2f} #pm {1:0.2f} {unit}".format(
rms * s, rms_err * s, unit=u))
return text
def plot_comparison(hist, prefix, dependence, categories, label, colors, norm):
for cat in categories:
can = TCanvas('canvas_{depen}_{cat}'.format(depen=dependence, cat=cat),
"cR", 1200, 800)
can.SetBottomMargin(0.15)
can.SetLeftMargin(0.15)
can.SetTopMargin(0.20)
can.SetRightMargin(0.05)
can.cd()
cor = get_text_cor()
hist[cat][label[0]].GetYaxis().SetRangeUser(
0.0, hist[cat][label[0]].GetMaximum() * 1.1)
scale = True
units = True
if "pull" in dependence:
scale = False
units = False
if norm:
hist[cat][label[0]].DrawNormalized("hist")
hist_max = hist[cat][label[0]].GetMaximum()
i = 0
for lab in label:
hist[cat][lab].DrawNormalized("SAME PE")
text = TLatex()
text = set_text(text, colors[i], cor["x"][i], cor["y"][i], lab,
hist[cat][lab].GetMean(),
hist[cat][lab].GetMeanError(),
hist[cat][lab].GetRMS(),
hist[cat][lab].GetRMSError(), scale, units)
i += 1
else:
hist[cat][label[0]].Draw("hist")
for lab in label:
hist[cat][lab].Draw("SAME PE")
can.Update()
saveName = '{prefix}_{dependence}_{cat}.pdf'.format(
prefix=prefix, dependence=dependence, cat=cat)
can.SaveAs(saveName)