-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_features.py
More file actions
235 lines (176 loc) · 6.56 KB
/
plot_features.py
File metadata and controls
235 lines (176 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import sys
import glob
import json
import argparse
import numpy as np
import awkward
import uproot
import logging
import ROOT
ROOT.gROOT.SetBatch()
import tdrstyle
tdrstyle.setTDRStyle()
from utilities import python_mkdir
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser(description='Convert')
parser.add_argument('rootDir', type=str,
help='Directory of input root files')
parser.add_argument('convertDir', type=str,
help='Output directory')
parser.add_argument('--electron', action='store_true',
help='Add electron as truth')
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, stream=sys.stderr, format='%(asctime)s.%(msecs)03d %(levelname)s %(name)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
inDir = args.rootDir
outDir = args.convertDir
plotDir = outDir+'/features'
doElectron = args.electron
if os.path.exists(plotDir):
print(plotDir, 'already exists')
sys.exit(0)
os.makedirs(plotDir, exist_ok=True)
fnames = glob.glob('{}/*.root'.format(inDir))
treename = 'deepMuonTree/DeepMuonTree'
with open('{}/means.json'.format(outDir)) as f:
means_result = json.load(f)
with open('{}/branches.txt'.format(outDir)) as f:
branches = [line.strip() for line in f.readlines()]
means = means_result['means']
stds = means_result['stds']
linear = means_result['linear']
loglinear = means_result['loglinear']
gen_branches = [
'muon_gen_sim_pdgId',
]
truths = ['muon','pion','electron']
colors = {
'muon': ROOT.kRed,
'pion': ROOT.kBlack,
'electron': ROOT.kBlue,
}
def plot_input(savename,arrays,**kwargs):
binning = kwargs.pop('binning',[])
if not binning:
full = np.concatenate(list(arrays.values()))
xmin = full.min()
xmax = full.max()
nbins = 100
binning = [100,xmin,xmax]
hists = {}
canvas = ROOT.TCanvas('c','c',800,800)
canvas.SetTopMargin(0.12)
legend = ROOT.TLegend(0.2,0.88,0.8,0.98)
legend.SetNColumns(3)
legend.SetTextFont(42)
legend.SetBorderSize(0)
legend.SetFillColor(0)
for t,truth in enumerate(truths):
array = arrays[truth]
hists[truth] = ROOT.TH1F('{}_{}'.format(savename.replace('/','_'),truth),'',*binning)
nphist, edges = np.histogram(array,binning[0],binning[1:])
for i in range(binning[0]):
hists[truth].SetBinContent(i+1,nphist[i])
hists[truth].Scale(1./hists[truth].Integral())
hists[truth].SetLineColor(colors[truth])
hists[truth].SetLineWidth(2)
if t==0:
hists[truth].Draw('hist')
hists[truth].GetXaxis().SetTitle(savename.split('/')[-1])
hists[truth].GetYaxis().SetTitle('Unit normalized')
else:
hists[truth].Draw('hist same')
legend.AddEntry(hists[truth],truth,'l')
legend.Draw()
canvas.Print(savename+'.png')
# first plot the inputs
for arrays in uproot.iterate(fnames,treename,branches+gen_branches,namedecode="utf-8",entrysteps=1000000):
print(arrays.keys())
muon = (abs(arrays['muon_gen_sim_pdgId'])==13)
pion = (abs(arrays['muon_gen_sim_pdgId'])==211)
electron = (abs(arrays['muon_gen_sim_pdgId'])==11)
for key in arrays:
if key in gen_branches: continue
toPlot = {}
toPlot['muon'] = arrays[key][muon]
toPlot['pion'] = arrays[key][pion]
toPlot['electron'] = arrays[key][electron]
for truth in toPlot:
if isinstance(toPlot[truth],awkward.JaggedArray):
toPlot[truth] = toPlot[truth].flatten()
savename = '{}/input_{}'.format(plotDir,key)
plot_input(savename,toPlot)
break
# now plot the outputs
nx = 2
if doElectron:
truths = ['pion','muon','electron']
else:
truths = ['pion','muon']
fnames = {truth: sorted([f for f in glob.glob('{}/output_{}*.x0.npy'.format(outDir,truth)) if 'validation' not in f]) for truth in truths}
X = {}
Y = {}
W = {}
for truth in truths:
Xs = [[np.load(fname.replace('.x0.npy','.x{}.npy'.format(i))) for i in range(nx)] for fname in fnames[truth]]
Ys = [np.load(fname.replace('.x0.npy','.y.npy')) for fname in fnames[truth]]
Ws = [np.load(fname.replace('.x0.npy','.w.npy')) for fname in fnames[truth]]
Ws = [np.reshape(w,(w.shape[0],1)) for w in Ws]
X[truth] = [np.vstack([Xs[j][i] for j in range(len(Xs))]) for i in range(nx)]
Y[truth] = np.vstack(Ys)
W[truth] = np.vstack(Ws)
def plot_output(savename,arrays,**kwargs):
binning = kwargs.pop('binning',[])
weights = kwargs.pop('weights',{})
if not binning:
full = np.concatenate(list(arrays.values()))
xmin = full.min()
xmax = full.max()
nbins = 100
binning = [100,xmin,xmax]
hists = {}
canvas = ROOT.TCanvas('c','c',800,800)
canvas.SetTopMargin(0.12)
legend = ROOT.TLegend(0.2,0.88,0.8,0.98)
legend.SetNColumns(3)
legend.SetTextFont(42)
legend.SetBorderSize(0)
legend.SetFillColor(0)
for t,truth in enumerate(truths):
array = arrays[truth]
hists[truth] = ROOT.TH1F('{}_{}'.format(savename.replace('/','_'),truth),'',*binning)
if weights:
nphist, edges = np.histogram(array,binning[0],binning[1:],weights=np.squeeze(weights[truth]))
else:
nphist, edges = np.histogram(array,binning[0],binning[1:])
for i in range(binning[0]):
hists[truth].SetBinContent(i+1,nphist[i])
hists[truth].Scale(1./hists[truth].Integral())
hists[truth].SetLineColor(colors[truth])
hists[truth].SetLineWidth(2)
if t==0:
hists[truth].Draw('hist')
hists[truth].GetXaxis().SetTitle(savename.split('/')[-1])
hists[truth].GetYaxis().SetTitle('Unit normalized')
else:
hists[truth].Draw('hist same')
legend.AddEntry(hists[truth],truth,'l')
legend.Draw()
canvas.Print(savename+'.png')
for i,branch in enumerate(branches):
toPlot = {}
weight = {}
for t,truth in enumerate(truths):
shapes = [X[truth][j].shape for j in range(nx)]
toPlot[truth] = X[truth][0][:,i] if i<shapes[0][1] else X[truth][1][:,i-shapes[0][1],:]
weight[truth] = W[truth]
if i>=shapes[0][1]:
newweight = np.ones_like(toPlot[truth]) * weight[truth]
weight[truth] = newweight.flatten()
toPlot[truth] = toPlot[truth].flatten()
savename = '{}/output_{}'.format(plotDir,branch)
plot_output(savename,toPlot)
savename = '{}/output_weighted_{}'.format(plotDir,branch)
plot_output(savename,toPlot,weights=weight)