def __init__(self, file_out, inputfilename="", params_gain=PARAMS_GAIN(), params_det=PARAMS_DET(), params_discharge=PARAMS_PD(), debug=False): self.ADCPKPOS_SECTOR_AVG = 0. #Average of the fitted cluster ADC PkPos in defined (ieta,iphi) sector self.ADCPKPOS_SECTOR_STDDEV = 0. #Std. Dev. of the fitted cluster ADC PkPos in defined (ieta,iphi) sector self.ANA_UNI_GRANULARITY = 32 self.AVGCLUSTSIZE_SECTOR_AVG = 0. #Average of Average Cluster Size distributions in defined (ieta,iphi) sector self.AVGCLUSTSIZE_SECTOR_STDDEV = 0. #Std. Dev. of Average Cluster Size distributions in defined (ieta,iphi) sector self.DEBUG = debug self.DETECTOR = params_det self.DET_IMON_QC5_RESP_UNI = params_det.DET_IMON_QC5_RESP_UNI self.DET_IMON_POINTS = [] self.FILE_IN = [] if len(inputfilename) > 0: self.FILE_IN = TFile(str(inputfilename), "READ", "", 1) self.FILE_OUT = file_out self.GAIN_CALCULATOR = params_gain self.GAIN_LAMBDA = 1. self.GAIN_LAMBDA_ERR = 0. self.GAIN_AVG_POINTS = [] #Average Gain over the entire detector self.GAIN_STDDEV_POINTS = [ ] #Std. Dev of Gain over the entire detector self.GAIN_MAX_POINTS = [] #Max Gain over the entire detector self.GAIN_MIN_POINTS = [] #Min Gain over the entire detector self.G2D_MAP_ABS_RESP_UNI = TGraph2D( ) #Absolute Response Uniformity Map self.G2D_MAP_AVG_CLUST_SIZE_ORIG = TGraph2D( ) #Absolute Avg Cluster Size Map self.G2D_MAP_AVG_CLUST_SIZE_NORM = TGraph2D( ) #Normalized " " self.G2D_MAP_GAIN_ORIG = TGraph2D() #Effective Gain Map self.PD_CALCULATOR = params_discharge self.PD_AVG_POINTS = [] #Avg P_D over entire detector self.PD_STDDEV_POINTS = [] #Std. Dev of P_D over entire detector self.PD_MAX_POINTS = [] #Max P_D over the entire detector self.PD_MIN_POINTS = [] #Min P_D over the entire detector return
def makePlot(s): if (type(s) == TH1D): s.SetStats(0) x = RooRealVar("x", "x", 0, 3) l = RooArgList(x) dh = RooDataHist("dh", "dh", l, s) frame = x.frame() dh.plotOn(frame) #frame.SetTitle(name) #frame.GetXaxis().SetTitle(s.GetXaxis().GetTitle()) frame.GetYaxis().SetTitle(s.GetYaxis().GetTitle()) # frame.GetYaxis().SetTopMargin(0.15) #frame.Draw(draw) return frame elif (type(s) == TH2D): s.SetStats(0) x = RooRealVar("x", "x", 0, 3) y = RooRealVar("y", "y", 0, 3) l = RooArgList(x, y) dh = RooDataHist("dh", "dh", l, s) t = TGraph2D(s) s.SetMarkerSize(1.0) s.SetMarkerStyle(1) #t.GetXaxis().SetTitle(s.GetXaxis().GetTitle()) return s elif (type(s) == TGraph2D): s.SetMarkerSize(1.0) s.SetMarkerStyle(1) return s
def plot(self, gD01, gDbar01, repeat=False): N = gD01.GetN() xD01 = gD01.GetX() yD01 = gD01.GetY() zD01 = gD01.GetZ() xDbar01 = gDbar01.GetX() yDbar01 = gDbar01.GetY() zDbar01 = gDbar01.GetZ() gr1 = TGraph2D(N) gr1.SetName("delta" + self.obj) for i in range(N): x1 = xD01[i] y1 = yD01[i] if self.obj=="gAbs": z1 = gDbar01.Interpolate(y1,x1) / zD01[i] * 100 else: z1 = gDbar01.Interpolate(y1, x1) - zD01[i] * 100 if (z1 < 0): z1 += 2 * pi #z1 *= 1/(2*pi) #z1 = zDbar01[i] - gD01.Interpolate(y1,x1) gr1.SetPoint(i, x1, y1, z1) xD1 = gr1.GetX() yD1 = gr1.GetY() zD1 = gr1.GetZ() #set_palette() theta = 89.9 phi=0.1 c1 = TCanvas("c1", "c1", 4000, 4000) gPad.SetLeftMargin(0.1) c1.cd() titles = { "gArg":"#delta_{D}", "gAbs": "|A_{#bar{D}^{0}}|/|A_{D^{0}}|" } title = titles[self.obj] if (repeat): title = "#Delta" + title gr1.SetTitle("%s ; m^{2}_{K_{S}^{0} #pi^{+}} ; m^{2}_{K_{S}^{0} #pi^{-}}" % (title)) gr1.GetXaxis().SetLabelOffset(15) gr1.GetYaxis().SetLabelOffset(15) gr1.GetZaxis().SetLabelOffset(15) gr1.SetMargin(0.02) gr1.Draw(self.draw2D) gPad.SetTheta(theta) gPad.SetPhi(phi) gPad.SetLeftMargin(0.15) gStyle.SetPalette(55) gPad.Update() c1.SaveAs("%s/Delta_%s.%s" % (self.output, self.obj, self.imgtype)) return gr1
def seed3dfitSVD(name,r1,r2,r3,r4,dodraw): g = TGraph2D() g.SetMarkerSize(3) g.SetMarkerStyle(20) g.SetMarkerColor(ROOT.kRed) g.SetLineColor(ROOT.kRed) g.SetPoint(0,r1[2],r1[1],r1[0]) g.SetPoint(1,r2[2],r2[1],r2[0]) g.SetPoint(2,r3[2],r3[1],r3[0]) g.SetPoint(3,r4[2],r4[1],r4[0]) g.GetXaxis().SetRangeUser(290,340) g.GetYaxis().SetRangeUser(-0.8,+0.8) g.GetZaxis().SetRangeUser( 0 if(isel(r1[0])) else xPsideL, xEsideR if(isel(r1[0])) else 0 ) x = np.array([r1[0],r2[0],r3[0],r4[0]]) y = np.array([r1[1],r2[1],r3[1],r4[1]]) z = np.array([r1[2],r2[2],r3[2],r4[2]]) data = np.concatenate((x[:, np.newaxis], y[:, np.newaxis], z[:, np.newaxis]), axis=1) # Calculate the mean of the points, i.e. the 'center' of the cloud datamean = data.mean(axis=0) # Do an SVD on the mean-centered data (Singular Value Decomposition) uu, dd, vv = np.linalg.svd(data - datamean) # Now vv[0] contains the first principal component, i.e. the direction # vector of the 'best fit' line in the least squares sense. # Now generate some points along this best fit line, for plotting. # I use -7, 7 since the spread of the data is roughly 14 # and we want it to have mean 0 (like the points we did # the svd on). Also, it's a straight line, so we only need 2 points. # linepts = vv[0] * np.mgrid[-7:7:2j][:, np.newaxis] linepts = vv[0] * np.mgrid[-50:50:2j][:, np.newaxis] # shift by the mean to get the line in the right place linepts += datamean if(dodraw): lfit = TPolyLine3D() for point in linepts: lfit.SetNextPoint(point[2],point[1],point[0]) lfit.SetLineColor(ROOT.kBlue) cnv = TCanvas("","",2000,2000) view = TView.CreateView(1) xviewmin = 0 if(isel(r1[0])) else xPsideL xviewmax = xEsideR if(isel(r1[0])) else 0 view.SetRange(290,-0.8, xviewmin , 340,+0.8,xviewmax) view.ShowAxis() g.Draw("p0") lfit.Draw("smae") cnv.SaveAs(name) return linepts, dd ## dd is a 1D array of the data singular values
def seed3dfit(name,r1,r2,r3,r4,dodraw): g = TGraph2D() g.SetMarkerSize(3) g.SetMarkerStyle(20) g.SetMarkerColor(ROOT.kRed) g.SetLineColor(ROOT.kRed) g.SetPoint(0,r1[2],r1[1],r1[0]) g.SetPoint(1,r2[2],r2[1],r2[0]) g.SetPoint(2,r3[2],r3[1],r3[0]) g.SetPoint(3,r4[2],r4[1],r4[0]) g.GetXaxis().SetRangeUser(290,340) g.GetYaxis().SetRangeUser(-0.8,+0.8) g.GetZaxis().SetRangeUser(0 if(isel(r1[0])) else xPsideL, xEsideR if(isel(r1[0])) else 0 ) x = np.array([r1[0],r2[0],r3[0],r4[0]]) y = np.array([r1[1],r2[1],r3[1],r4[1]]) z = np.array([r1[2],r2[2],r3[2],r4[2]]) # this will find the slope and x-intercept of a plane # parallel to the y-axis that best fits the data A_xz = np.vstack((x, np.ones(len(x)))).T # m_xz, c_xz = np.linalg.lstsq(A_xz, z,rcond=None)[0] result_xz = np.linalg.lstsq(A_xz, z,rcond=None) m_xz, c_xz = result_xz[0] residuals_xz = result_xz[1] # again for a plane parallel to the x-axis A_yz = np.vstack((y, np.ones(len(y)))).T # m_yz, c_yz = np.linalg.lstsq(A_yz, z,rcond=None)[0] result_yz = np.linalg.lstsq(A_yz, z,rcond=None) m_yz, c_yz = result_yz[0] residuals_yz = result_yz[1] if(dodraw): zz = np.array([300,310,320,330]) xx,yy = line3d(zz, m_xz,c_xz,m_yz,c_yz) lfit = TPolyLine3D() for i in range(4): lfit.SetNextPoint(zz[i],yy[i],xx[i]) lfit.SetLineColor(ROOT.kBlue) cnv = TCanvas("","",2000,2000) view = TView.CreateView(1) xviewmin = 0 if(isel(r1[0])) else xPsideL xviewmax = xEsideR if(isel(r1[0])) else 0 view.SetRange(290,-0.8, xviewmin , 340,+0.8,xviewmax) view.ShowAxis() g.Draw("p0") lfit.Draw("smae") cnv.SaveAs(name) return residuals_xz,residuals_yz
def MakeGraph(self, title, suffix): self.legend_title = title.replace('.root', '').replace('-', '_') self.suffix = suffix if title.find('DY') != -1: title = 'Drell-Yan events' elif title.find('TT') != -1: title = r't\bar{t} events' else: mH_value = re.findall(r'\d+', title)[2] mA_value = re.findall(r'\d+', title)[3] title = 'Signal events with M_{H} = %s GeV and M_{A} = %s GeV' % ( mH_value, mA_value) # Normalize # if self.normalize: self.Z += self.nevents * self.norm title += ' [Normalized]' self.legend_title += '_norm' # Divide by total entries # self.Z /= self.nevents # Divide by N self.Z *= 2 # Because -2 log L # check for invalids (nan of inf) might be coming from log10 # invalid_entries = np.logical_or(np.isinf(self.Z), np.isnan(self.Z)) max_Z = np.amax(self.Z[np.invert(invalid_entries)]) min_Z = np.amin(self.Z[np.invert(invalid_entries)]) self.Z[invalid_entries] = 0 # removes non physical points # Generate graph # graph = TGraph2D(self.N) print('Generating TGraph2D') manager = enlighten.get_manager() pbar = manager.counter(total=self.N, desc='Progress', unit='Point') for i in range(self.N): graph.SetPoint(i, self.mA[i], self.mH[i], self.Z[i]) pbar.update() manager.stop() #graph = copy.deepcopy(TGraph2D(self.N,self.mA,self.mH,self.Z)) graph.SetTitle( 'Log-Likelihood : %s;M_{A} [GeV]; M_{H} [GeV]; -2log L' % (title)) graph.SetMaximum(max_Z) graph.SetMinimum(min_Z) graph.SetNpx(1000) graph.SetNpy(1000) # Save graph # self.graph = graph self._saveGraph()
def initialR(b, d): tR = [ TH1D("X", ";x pos;", 100, 0, 10), TH1D("Y", ";y pos;", 100, 0, 10), TH1D("Z", ";z pos;", 100, 0, 10) ] tg2d = TGraph2D() c = 0 o = 0 for i in b.R(): if (c == d): for j in i: #print j x = j[0] y = j[1] z = j[2] tR[0].Fill(x) tR[1].Fill(y) tR[2].Fill(z) tg2d.SetPoint(o, x, y, z) o += 1 #print "(%f,%f,%f)" % (x,y,z) c += 1 tR[0].GetXaxis().SetTitle("X pos @ t = %d" % d) tR[1].GetXaxis().SetTitle("Y pos @ t = %d" % d) tR[2].GetXaxis().SetTitle("Z pos @ t = %d" % d) for y in xrange(3): tR[y].GetYaxis().SetTitle("Count") tR[y].GetYaxis().CenterTitle() tR[y].GetXaxis().CenterTitle() tg2d.GetXaxis().SetTitle("X") tg2d.GetYaxis().SetTitle("Y") tg2d.GetZaxis().SetTitle("Z") tg2d.GetXaxis().CenterTitle() tg2d.GetYaxis().CenterTitle() tg2d.GetZaxis().CenterTitle() return [tR, tg2d]
def _doProfile2d( solver, ipar1=0, type1="u", ipar2=1, type2= "m" ): from ConstrainedFit import clsq from ROOT import TGraph2D, TMarker, gPad from array import array global tg2d, hist, te1, te2, te3, tm par1= clsq.createClsqPar( ipar1, type1, solver ) par2= clsq.createClsqPar( ipar2, type2, solver ) parval1, parerr1, name1= _getUMParErrName( par1 ) parval2, parerr2, name2= _getUMParErrName( par2 ) print( "\nChi^2 profile plot " + name1 + " - " + name2 + ":" ) corr= solver.getCorrMatrix() icorr1= ipar1 icorr2= ipar2 if type1 == "u" or type2 == "u": nmpar= len(solver.getMpars()) if type1 == "u": icorr1= nmpar + ipar1 if type2 == "u": icorr2= nmpar + ipar2 rho= corr[icorr1,icorr2] te1= _makeEllipse( parval1, parval2, parerr1, parerr2, rho ) te2= _makeEllipse( parval1, parval2, 2.0*parerr1, 2.0*parerr2, rho ) te3= _makeEllipse( parval1, parval2, 3.0*parerr1, 3.0*parerr2, rho ) ca= clsq.clsqAnalysis( solver ) points= ca.profile2d( par1, par2 ) npoints= len(points) tg2d= TGraph2D( npoints ) for i in range( npoints ): point= points[i] tg2d.SetPoint( i, point[0], point[1], point[2] ) hist= tg2d.GetHistogram() contourlevels= array( "d", [ 1.0, 4.0, 9.0 ] ) hist.SetContour( 3, contourlevels ) hist.GetXaxis().SetTitle( name1 ) hist.GetYaxis().SetTitle( name2 ) hist.SetTitle( "Triangle fit "+name2+" vs "+name1 ) hist.Draw( "cont1" ) tm= TMarker( parval1, parval2, 20 ) tm.Draw( "s" ) te1.Draw( "s" ) te2.Draw( "s" ) te3.Draw( "s" ) gPad.Print( "triangle_errorellipse.png" ) return
def Plot(self): self.CheckError() if self.dataCorrect == True: c1 = TCanvas("c1", "a template of 1d graphics output", 200, 10, 1024, 768) gr = TGraph2D() gr.SetTitle(self.chartName) for index, item in enumerate(self.dataX): gr.SetPoint(index, item, self.dataY[index], self.dataZ[index]) gr.GetXaxis().SetTitle(self.axisXName) gr.GetYaxis().SetTitle(self.axisYName) gr.GetZaxis().SetTitle(self.axisZName) gr.Draw("surf1") c1.SaveAs("2D.C") print "2d finished" else: print "data Error nothing to do"
def plotDataROOT(self, name='plotDataROOT', ztitle='Z', zmin=None, zmax=None): self.canvasData = TCanvas("canvasData", "canvasData", 0, 0, 300, 300) gStyle.SetOptStat(0) minX, maxX, minY, maxY, minZ, maxZ = self.autoRange(zmin, zmax) X, Y, Z = self.getXYZpoints() n = X.shape[0] self.graphData = TGraph2D(name, ztitle, n, X, Y, Z) self.graphData.SetMaximum(maxZ) self.graphData.SetMinimum(minZ) gStyle.SetHistTopMargin(0) self.graphData.Draw("zpcol") return self.graphData
def ZoomHist(graph, bins, xmin, xmax, ymin, ymax): x = np.linspace(xmin, xmax, bins) y = np.linspace(ymin, ymax, bins) X, Y = np.meshgrid(x, y) X = X.ravel() Y = Y.ravel() valid = np.logical_and(np.greater_equal(Y, X), np.greater_equal(Y, 125)) X = X[valid] Y = Y[valid] N = X.shape[0] new_graph = TGraph2D(N) manager = enlighten.get_manager() pbar = manager.counter(total=N, desc='Progress', unit='Point') for i in range(N): content = graph.Interpolate(X[i], Y[i]) if content != 0 or Y[i] > 125: new_graph.SetPoint(i, X[i], Y[i], content) pbar.update() new_graph.SetTitle(graph.GetTitle()) return copy.deepcopy(new_graph)
def ExtrapolateGraph(graph, points): print('Extrapolation') new_graph = TGraph2D(N_plane) # Extrapolation # from scipy.optimize import curve_fit def func(x, a, b, c, x0, y0, e1, e2): z = (a * (x[0] - x0)**2 + b * (x[1] - y0)**2 + c * (x[0] - x0) * (x[1] - y0)) * np.exp(-x[0] / e1 - x[1] / e2) return z.ravel() initial_guess = (-4e-6, -5e-7, 9e-6, 500, 800, 400, 700) popt, pcov = curve_fit(func, (points[:, 0], points[:, 1]), points[:, 2], p0=initial_guess) print(popt) manager = enlighten.get_manager() pbar = manager.counter(total=N_plane, desc='Progress', unit='Point') for i in range(N_plane): pbar.update() m_A = mA_plane[i] m_H = mH_plane[i] if m_A >= m_H: #or m_H<=mh :#or m_H-m_A<mZ: new_graph.SetPoint(i, m_A, m_H, 0) continue Z = func((m_A, m_H), *popt) # Truncation # if m_H > 1000: Z = func((m_A, 1000), *popt) if Z <= 0.02: Z = 0.02 if Z <= 0.07 and m_H > 400: Z = 0.07 new_graph.SetPoint(i, m_A, m_H, Z) manager.stop() return new_graph
def test_fill_graph(): n_samples = 1000 data2D = RNG.randn(n_samples, 2) data3D = RNG.randn(n_samples, 3) graph = TGraph() rnp.fill_graph(graph, data2D) graph2d = TGraph2D() rnp.fill_graph(graph2d, data3D) # array not 2-d for g in (graph, graph2d): assert_raises(ValueError, rnp.fill_graph, g, RNG.randn(10)) # length of second axis does not match dimensionality of histogram for g in (graph, graph2d): assert_raises(ValueError, rnp.fill_graph, g, RNG.randn(10, 4)) # wrong type h = list() a = RNG.randn(10) assert_raises(TypeError, rnp.fill_graph, h, a)
def test_fill_graph(): np.random.seed(0) data2D = np.random.randn(1E6, 2) data3D = np.random.randn(1E4, 3) graph = TGraph() rnp.fill_graph(graph, data2D) graph2d = TGraph2D() rnp.fill_graph(graph2d, data3D) # array not 2-d for g in (graph, graph2d): assert_raises(ValueError, rnp.fill_graph, g, np.random.randn(1E4)) # length of second axis does not match dimensionality of histogram for g in (graph, graph2d): assert_raises(ValueError, rnp.fill_graph, g, np.random.randn(1E4, 4)) # wrong type h = list() a = np.random.randn(100) assert_raises(TypeError, rnp.fill_graph, h, a)
def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) for i in range(len(sys.argv)): if string.count(sys.argv[i],'defoDump') > 0: print 'Opening file number ' + str(i) + ' ' + sys.argv[i] file = open(sys.argv[i]) canvas1.cd() canvas1.Clear() nPointsX = 0 grX = TGraph2D() for line in file: values = [] tokenizedLine = line.split(' ',99) remove_values_from_list(tokenizedLine, ' ') remove_values_from_list(tokenizedLine, '') for token in tokenizedLine: values.append(token) nPointsX += 1 grX.SetPoint(nPointsX, float(values[2]), float(values[3]), float(values[6]) )
def seed2dfit(name,r1,r2,r3,r4,dodraw): gxyz = TGraph2D() gxyz.SetMarkerSize(1) gxyz.SetMarkerStyle(24) gxyz.SetMarkerColor(ROOT.kBlack) gxyz.SetPoint(0,r1[2],r1[1],r1[0]) gxyz.SetPoint(1,r2[2],r2[1],r2[0]) gxyz.SetPoint(2,r3[2],r3[1],r3[0]) gxyz.SetPoint(3,r4[2],r4[1],r4[0]) gxyz.GetXaxis().SetRangeUser(290,340) gxyz.GetYaxis().SetRangeUser(-0.8,+0.8) gxyz.GetZaxis().SetRangeUser( 0 if(isel(r1[0])) else xPsideL, xEsideR if(isel(r1[0])) else 0 ) gxz = TGraph() gxz.SetMarkerSize(1) gxz.SetMarkerStyle(24) gxz.SetMarkerColor(ROOT.kBlack) gxz.SetPoint(0,r1[2],r1[0]) gxz.SetPoint(1,r2[2],r2[0]) gxz.SetPoint(2,r3[2],r3[0]) gxz.SetPoint(3,r4[2],r4[0]) gxz.GetXaxis().SetRangeUser(290,340) if(isel(r1[0])): gxz.GetYaxis().SetRangeUser(0,xEsideR) else: gxz.GetYaxis().SetRangeUser(xPsideL,0) gyz = TGraph() gyz.SetMarkerSize(1) gyz.SetMarkerStyle(24) gyz.SetMarkerColor(ROOT.kBlack) gyz.SetLineColor(ROOT.kRed) gyz.SetPoint(0,r1[2],r1[1]) gyz.SetPoint(1,r2[2],r2[1]) gyz.SetPoint(2,r3[2],r3[1]) gyz.SetPoint(3,r4[2],r4[1]) gyz.GetXaxis().SetRangeUser(290,340) gyz.GetYaxis().SetRangeUser(-0.8,+0.8) fxz = TF1("fxz","pol1",300,330) fitr_xz = gxz.Fit(fxz,"Q") fitf_xz = gxz.FindObject("fxz") fyz = TF1("fyz","pol1",300,330) fitr_yz = gyz.Fit(fyz,"Q") fitf_yz = gyz.FindObject("fyz") if(dodraw): lfit = TPolyLine3D() for z in [300,310,320,330]: x = fitf_xz.Eval(z) y = fitf_yz.Eval(z) lfit.SetNextPoint(z,y,x) lfit.SetLineColor(ROOT.kBlue) cnv = TCanvas("","",1500,500) cnv.Divide(3,1) cnv.cd(1) view = TView.CreateView(1) xviewmin = 0 if(isel(r1[0])) else xPsideL xviewmax = xEsideR if(isel(r1[0])) else 0 view.SetRange(290,-0.8, xviewmin , 340,+0.8,xviewmax) view.ShowAxis() gxyz.Draw("p0") lfit.Draw("smae") cnv.cd(2) gxz.Draw() cnv.cd(3) gyz.Draw() cnv.SaveAs(name) chi2_xz = fitf_xz.GetChisquare()/fitf_xz.GetNDF() chi2_yz = fitf_yz.GetChisquare()/fitf_yz.GetNDF() prob_xz = fitf_xz.GetProb() prob_yz = fitf_yz.GetProb() return chi2_xz,prob_xz,chi2_yz,prob_yz
def makePlot2D(filepath,foutname,medcfg,chicfg,offshell=True): xsecs = fcncXsecs # FIXME limits = parseLimitFiles2D(filepath,None) gs = {} for g in ['exp','expup','expdown','obs','obsup','obsdown']: gs[g] = TGraph2D() iP=0 hgrid = TH2D('grid','grid',medcfg[0],medcfg[1],medcfg[2],chicfg[0],chicfg[1],chicfg[2]) for p in limits: mMed = p[0]; mChi = p[1] ''' if mMed<0.5*medcfg[1] or mMed>1.2*medcfg[2]: continue if mChi<0.5*chicfg[1] or mChi>1.2*chicfg[2]: continue ''' l = limits[p] if l.obs==0 or l.cent==0: print mMed,mChi continue hgrid.Fill(mMed,mChi) gs['exp'].SetPoint(iP,mMed,mChi,l.cent) gs['expup'].SetPoint(iP,mMed,mChi,l.up1) gs['expdown'].SetPoint(iP,mMed,mChi,l.down1) gs['obs'].SetPoint(iP,mMed,mChi,l.obs) gs['obsup'].SetPoint(iP,mMed,mChi,l.obs/(1-XSECUNCERT)) gs['obsdown'].SetPoint(iP,mMed,mChi,l.obs/(1+XSECUNCERT)) iP += 1 hs = {} for h in ['exp','expup','expdown','obs','obsup','obsdown']: hs[h] = TH2D(h,h,medcfg[0],medcfg[1],medcfg[2],chicfg[0],chicfg[1],chicfg[2]) # hs[h].SetStats(0); hs[h].SetTitle('') for iX in xrange(0,medcfg[0]): for iY in xrange(0,chicfg[0]): x = medcfg[1] + (medcfg[2]-medcfg[1])*iX/medcfg[0] y = chicfg[1] + (chicfg[2]-chicfg[1])*iY/chicfg[0] if not(offshell) and 2*y>x: continue val = gs[h].Interpolate(x,y) val = max(0.01,min(100,val)) hs[h].SetBinContent(iX+1,iY+1,val) # if h=='obs': # print iX+1,iY+1,x,y,gs[h].Interpolate(x,y) ''' zaxis = hs['obs'].GetZaxis() nbins = zaxis.GetNbins() print nbins zaxis.SetBinLabel(1,'<10^{-2}') zaxis.SetBinLabel(nbins,'>10') ''' hs['obsclone'] = hs['obs'].Clone() # clone it so we can draw with different settings for h in ['exp','expup','expdown','obsclone','obsup','obsdown']: hs[h].SetContour(2) hs[h].SetContourLevel(1,1) for iX in xrange(1,medcfg[0]+1): for iY in xrange(1,chicfg[0]+1): if hs[h].GetBinContent(iX,iY)<=0: hs[h].SetBinContent(iX,iY,100) canvas = ROOT.TCanvas("canvas", "canvas", 1000, 800) canvas.SetLogz() frame = canvas.DrawFrame(medcfg[1],chicfg[1],medcfg[2],chicfg[2],"") frame.GetYaxis().CenterTitle(); frame.GetYaxis().SetTitle("m_{#chi} [GeV]"); frame.GetXaxis().SetTitle("m_{V} [GeV]"); frame.GetXaxis().SetTitleOffset(1.15); frame.GetYaxis().SetTitleOffset(1.15); root.gStyle.SetLabelSize(0.035,"X"); root.gStyle.SetLabelSize(0.035,"Y"); root.gStyle.SetLabelSize(0.035,"Z"); frame.Draw() ##Color palette ncontours = 999; #root.TColor.InitializeColors(); #stops = [ 0.0000, 0.1250, 0.2500, 0.3750, 0.5000, 0.6250, 0.7500, 0.8750, 1.0000] stops = [ 0.0000, 0.10, 0.200, 0.30, 0.4000, 0.50, 0.7500, 0.8750, 1.0000] red = [ 243./255., 243./255., 240./255., 240./255., 241./255., 239./255., 186./255., 151./255., 129./255.] green = [ 0./255., 46./255., 99./255., 149./255., 194./255., 220./255., 183./255., 166./255., 147./255.] blue = [ 6./255., 8./255., 36./255., 91./255., 169./255., 235./255., 246./255., 240./255., 233./255.] stopsArray = array('d',stops) redArray = array('d',red) greenArray = array('d',green) blueArray = array('d',blue) root.TColor.CreateGradientColorTable(9, stopsArray, redArray, greenArray, blueArray, ncontours); root.gStyle.SetNumberContours(ncontours); hs['obs'].SetMinimum(0.01) hs['obs'].SetMaximum(100.) hs['obs'].Draw("COLZ SAME") hs['obsclone'].SetLineStyle(1) hs['obsclone'].SetLineWidth(3) hs['obsclone'].SetLineColor(2) hs['obsclone'].Draw('CONT3 SAME') ctemp = root.TCanvas() hs['obsclone'].Draw('contlist') ctemp.Update() objs = root.gROOT.GetListOfSpecials().FindObject('contours') saveobs = (objs.At(0)).First() canvas.cd() hs['obsup'].SetLineStyle(2) hs['obsup'].SetLineWidth(2) hs['obsup'].SetLineColor(2) hs['obsup'].Draw('CONT3 SAME') hs['obsdown'].SetLineStyle(2) hs['obsdown'].SetLineWidth(2) hs['obsdown'].SetLineColor(2) hs['obsdown'].Draw('CONT3 SAME') hs['exp'].SetLineStyle(1) hs['exp'].SetLineWidth(3) hs['exp'].SetLineColor(1) hs['exp'].Draw('CONT3 SAME') hs['expup'].SetLineStyle(2) hs['expup'].SetLineWidth(2) hs['expup'].SetLineColor(1) hs['expup'].Draw('CONT3 SAME') hs['expdown'].SetLineStyle(2) hs['expdown'].SetLineWidth(2) hs['expdown'].SetLineColor(1) hs['expdown'].Draw('CONT3 SAME') if drawLegend: leg = root.TLegend(0.16,0.62,0.55,0.88);#,NULL,"brNDC"); leg.SetHeader('a_{FC} = b_{FC} = 0.25, g_{DM} = 1') leg.AddEntry(hs['exp'],"Median Expected 95% CL","L"); leg.AddEntry(hs['expup'],"Exp. #pm 1 std. dev. (exp)","L"); leg.AddEntry(hs['obsclone'],"Observed 95% CL","L"); leg.AddEntry(hs['obsup'],"Obs. #pm 1 std. dev. (theory)","L"); leg.SetFillColor(0); leg.SetBorderSize(0) leg.Draw("SAME"); # hgrid.Draw('same') tex = root.TLatex(); tex.SetNDC(); tex.SetTextFont(42); tex.SetLineWidth(2); tex.SetTextSize(0.040); tex.Draw(); tex.DrawLatex(0.62,0.94,"12.9 fb^{-1} (13 TeV)"); tex2 = root.TLatex(); tex2.SetNDC(); tex2.SetTextFont(42); tex2.SetLineWidth(2); tex2.SetTextSize(0.04); tex2.SetTextAngle(270); tex2.DrawLatex(0.965,0.93,"Observed #sigma_{95% CL}/#sigma_{theory}"); texCMS = root.TLatex(0.12,0.94,"#bf{CMS}"); texCMS.SetNDC(); texCMS.SetTextFont(42); texCMS.SetLineWidth(2); texCMS.SetTextSize(0.05); texCMS.Draw(); texPrelim = root.TLatex(0.2,0.94,"#it{Preliminary}"); texPrelim.SetNDC(); texPrelim.SetTextFont(42); texPrelim.SetLineWidth(2); texPrelim.SetTextSize(0.04); texPrelim.Draw(); root.gPad.SetRightMargin(0.15); root.gPad.SetTopMargin(0.07); root.gPad.SetBottomMargin(0.15); root.gPad.RedrawAxis(); root.gPad.Modified(); root.gPad.Update(); canvas.SaveAs(foutname+'.png') canvas.SaveAs(foutname+'.pdf') fsave = root.TFile(foutname+'.root','RECREATE') fsave.WriteTObject(hs['obs'],'hobserved') fsave.WriteTObject(gs['obs'],'gobserved') fsave.WriteTObject(hs['exp'],'hexp') fsave.WriteTObject(gs['exp'],'gexp') fsave.WriteTObject(saveobs,'observed') fsave.Close()
gr68.SetLineStyle(1) gr68.SetLineColor(1) gr68.SetFillStyle(1001) gr68.SetFillColor(82) ##### gr95 = contourPlot(tree95, 0.049, 1.0, bestfit) gr95.SetLineWidth(2) gr95.SetLineStyle(7) gr95.SetLineColor(1) gr95.SetFillStyle(1001) gr95.SetFillColor(89) else : #gr68 = TGraph() #gr68 = tree68 #bestfit = BestFit(tfBF) graph = TGraph2D(th2) xbinsize = 0.05; ybinsize = 0.05 graph.SetNpx( int((graph.GetXmax() - graph.GetXmin())/xbinsize) ) graph.SetNpy( int((graph.GetYmax() - graph.GetYmin())/ybinsize) ) kk = graph.GetHistogram() canv = TCanvas("canv", "canv", 600, 600) canv.SetBottomMargin(0.10) canv.SetLeftMargin(0.08) canv.SetRightMargin(0.12) if fromGrid : graph.Draw('colz') #c.SaveAs('plot.pdf') gr68 = graph.GetContourList(2.3/2)
def RootifyCrossBR(self): for processname in self.processnames: outfilename_cross = self.crosssecfolder+'/Crosssections_%s%s.root' % (processname, self.tag) cross_module = importlib.import_module('crosssections.ChiPsi.Crosssections_%s' % (processname)) crosssections = cross_module.crosssection if self.submit: outfile = TFile(outfilename_cross, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_cross)) print green('--> Now at sample %s' % (processname)) for lamb in self.lambdas: if not lamb in crosssections: continue print green(' --> Now at lambda: %s' % (get_lambdastring(lamb))) xsecs_per_mref = crosssections[lamb] graph2d = TGraph2D() npoints2d=0 set_points ={} all_combinations = get_all_combinations(preferred_configurations=preferred_configurations) for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = False for mref in xsecs_per_mref: xsecs = xsecs_per_mref[mref] final_xsecs = [] mdeps = array('d') sigmas = array('d') tot_los = array('d') tot_his = array('d') mdeps_lo = array('d') mdeps_hi = array('d') for tuple in xsecs: mdep, sigma, q_lo, q_hi, pdf = tuple tot_lo = XsecTotErr(sigma, q_lo, pdf) tot_hi = XsecTotErr(sigma, q_hi, pdf) final_xsecs.append((mdep, sigma, tot_lo, tot_hi)) mdeps.append(mdep) sigmas.append(sigma) tot_los.append(tot_lo) tot_his.append(tot_hi) mdeps_lo.append(0.) mdeps_hi.append(0.) if 'LQLQ' in processname or 'LQTChannel' in processname: graph2d.SetPoint(npoints2d, mdep, mref, sigma) set_points[mdep][mref] = True elif 'PsiPsi' in processname: graph2d.SetPoint(npoints2d, mref, mdep, sigma) set_points[mref][mdep] = True else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') npoints2d += 1 # make TGraph out of it graph = TGraphAsymmErrors(len(mdeps), mdeps, sigmas, mdeps_lo, mdeps_hi, tot_los, tot_his) xaxistitle = 'M_{LQ} [GeV]' if ('LQLQ' in processname or 'LQTChannel' in processname) else 'M_{#chi_{1}} [GeV]' graph.GetXaxis().SetTitle('M_{LQ} [GeV]') graph.GetYaxis().SetTitle('#sigma [pb]') graphname = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphname += '_MC1%i' % (mref) elif 'PsiPsi' in processname: graphname += '_MLQ%i' % (mref) else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') graphname += '_L%s' % (get_lambdastring(lamb)) graph.SetName(graphname) # print 'graphname: %s' % (graphname) graphtitle = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphtitle += ', M_{#chi_{1}} = %i GeV' % (mref) elif 'PsiPsi' in processname: graphtitle += ', M_{LQ} = %i GeV' % (mref) graphtitle += ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.')) # print 'graphtitle: %s' % (graphtitle) graph.SetTitle(graphtitle) if self.submit: outfile.cd() graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: if not set_points[mlq][mch]: graph2d.SetPoint(npoints2d, mlq, mch, 0.) npoints2d += 1 graph2d.SetName(processname + '_L%s' % (get_lambdastring(lamb))) graph2d.GetXaxis().SetTitle('M_{LQ} [GeV]') graph2d.GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') graph2d.GetZaxis().SetTitle('#sigma [pb]') graph2d.SetTitle(processname + ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.'))) if self.submit: graph2d.Write() else: print yellow(' --> Would have written 2d-graph to outfile') if self.submit: outfile.Close() # also rootify BRs if we are looking at the LQLQ process without decays (just for fun, could also be any other LQLQ process) if processname == 'LQLQ': outfilename_br = self.crosssecfolder+'/Branchingratios_%s%s.root' % (processname, self.tag) if self.submit: outfile = TFile(outfilename_br, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_br)) br_module = importlib.import_module('crosssections.ChiPsi.Branchingratios_%s' % (processname)) allbrs = br_module.branchingratio for lamb in allbrs.keys(): brs = allbrs[lamb] brs2d = {} npoints2d = {} set_points ={} for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = {} for decaymode in decaymode_dict.keys(): set_points[mlq][mch][decaymode] = False decaymodes_present = [] for mlq in sorted(brs): mchs_per_decaymode = {} brs_per_decaymode = {} for mch in sorted(brs[mlq]): for decaymode in brs[mlq][mch]: if not decaymode in decaymodes_present: decaymodes_present.append(decaymode) if not decaymode in mchs_per_decaymode.keys(): mchs_per_decaymode[decaymode] = array('d') if not decaymode in brs_per_decaymode.keys(): brs_per_decaymode[decaymode] = array('d') # if not decaymode in set_points[mlq][mch].keys(): # # print mlq, mch, decaymode # set_points[mlq][mch][decaymode] = False if not decaymode in brs2d.keys(): graphname2d = processname + ('_L%s_%i_%i' % (get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) # print graphname2d npoints2d[decaymode] = 0 brs2d[decaymode] = TGraph2D() brs2d[decaymode].SetName(graphname2d) brs2d[decaymode].GetXaxis().SetTitle('M_{LQ} [GeV]') brs2d[decaymode].GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') brs2d[decaymode].GetZaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) brs2d[decaymode].SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) mchs_per_decaymode[decaymode].append(mch) brs_per_decaymode[decaymode].append(brs[mlq][mch][decaymode][0]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, brs[mlq][mch][decaymode][0]) set_points[mlq][mch][decaymode] = True npoints2d[decaymode] += 1 for decaymode in mchs_per_decaymode.keys(): graph = TGraph(len(mchs_per_decaymode[decaymode]), mchs_per_decaymode[decaymode], brs_per_decaymode[decaymode]) graphname = processname + ('_MLQ%i_L%s_%i_%i' % (mlq, get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) graph.SetName(graphname) graph.GetXaxis().SetTitle('M_{#chi_{1}} [GeV]') graph.GetYaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) graph.SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) if self.submit: graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: for decaymode in set_points[mlq][mch]: if not set_points[mlq][mch][decaymode] and decaymode in decaymodes_present: # print decaymode # print brs2d.keys() # print npoints2d.keys() # print 'Setting BR for MLQ=%i, MCH=%i, decay=(%i, %i) to 0' % (mlq, mch, decaymode[0], decaymode[1]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, 0) npoints2d[decaymode] += 1 if self.submit: for decaymode in brs2d: brs2d[decaymode].Write() else: print yellow(' --> Would have written 2d-graphs to outfile') outfile.Close()
ScinPlot = TH2F("Scin_" + str(phi), "Scin_" + str(phi), int(100), float(np.mean(theta_S) - 0.05), float(np.mean(theta_S) + 0.05), int(100), float(np.mean(phi_S) - 0.05), float(np.mean(phi_S) + 0.05)) CherPlot = TH2F("Cher_" + str(phi), "Cher_" + str(phi), int(100), float(np.mean(theta_S) - 0.05), float(np.mean(theta_S) + 0.05), int(100), float(np.mean(phi_S) - 0.05), float(np.mean(phi_S) + 0.05)) n = len(theta_S) array_theta_S = np.array(theta_S, 'd') array_phi_S = np.array(phi_S, 'd') array_E_s = np.array(E_s, 'd') ScinGraph = TGraph2D(n, array_theta_S, array_phi_S, array_E_s) ScinGraph.SetName("ScinGraph_" + str(phi)) n = len(theta_C) array_theta_C = np.array(theta_C, 'd') array_phi_C = np.array(phi_C, 'd') array_E_c = np.array(E_c, 'd') CherGraph = TGraph2D(n, array_theta_C, array_phi_C, array_E_c) CherGraph.SetName("CherGraph_" + str(phi)) MeanTheta = 0. MeanPhi = 0. sumtheta = 0. sumphi = 0. MeanThetaC = 0. MeanPhiC = 0.
def makePlot2D(filepath, foutname, medcfg, chicfg, offshell=False): limits = parseLimitFiles2D(filepath) gs = {} for g in ['exp', 'expup', 'expdown', 'obs', 'obsup', 'obsdown']: gs[g] = TGraph2D() iP = 0 hgrid = TH2D('grid', 'grid', medcfg[0], medcfg[1], medcfg[2], chicfg[0], chicfg[1], chicfg[2]) for p in limits: mMed = p[0] mChi = p[1] ''' if mMed<0.5*medcfg[1] or mMed>1.2*medcfg[2]: continue if mChi<0.5*chicfg[1] or mChi>1.2*chicfg[2]: continue ''' l = limits[p] if l.obs == 0 or l.cent == 0: print mMed, mChi continue hgrid.Fill(mMed, mChi) gs['exp'].SetPoint(iP, mMed, mChi, l.cent) gs['expup'].SetPoint(iP, mMed, mChi, l.up1) gs['expdown'].SetPoint(iP, mMed, mChi, l.down1) iP += 1 hs = {} for h in ['exp', 'expup', 'expdown']: hs[h] = TH2D(h, h, medcfg[0], medcfg[1], medcfg[2], chicfg[0], chicfg[1], chicfg[2]) # hs[h].SetStats(0); hs[h].SetTitle('') for iX in xrange(0, medcfg[0]): for iY in xrange(0, chicfg[0]): x = medcfg[1] + (medcfg[2] - medcfg[1]) * iX / medcfg[0] y = chicfg[1] + (chicfg[2] - chicfg[1]) * iY / chicfg[0] if not (offshell) and 2 * y > x: val = 9999 else: val = gs[h].Interpolate(x, y) if val == 0: val = 9999 val = max(0.01, min(100, val)) hs[h].SetBinContent(iX + 1, iY + 1, val) # if h=='obs': # print iX+1,iY+1,x,y,gs[h].Interpolate(x,y) ''' zaxis = hs['obs'].GetZaxis() nbins = zaxis.GetNbins() print nbins zaxis.SetBinLabel(1,'<10^{-2}') zaxis.SetBinLabel(nbins,'>10') ''' hs['expclone'] = hs['exp'].Clone() for h in ['expup', 'expdown', 'expclone']: hs[h].SetContour(2) hs[h].SetContourLevel(1, 1) for iX in xrange(1, medcfg[0] + 1): for iY in xrange(1, chicfg[0] + 1): if hs[h].GetBinContent(iX, iY) <= 0: hs[h].SetBinContent(iX, iY, 100) canvas = ROOT.TCanvas("canvas", "canvas", 1000, 800) canvas.SetLogz() frame = canvas.DrawFrame(medcfg[1], chicfg[1], medcfg[2], chicfg[2], "") frame.GetYaxis().CenterTitle() frame.GetYaxis().SetTitle("m_{#chi} [GeV]") frame.GetXaxis().SetTitle("m_{V} [GeV]") frame.GetXaxis().SetTitleOffset(1.15) frame.GetYaxis().SetTitleOffset(1.15) root.gStyle.SetLabelSize(0.035, "X") root.gStyle.SetLabelSize(0.035, "Y") root.gStyle.SetLabelSize(0.035, "Z") frame.Draw() hs['exp'].SetMinimum(0.01) hs['exp'].SetMaximum(100.) hs['exp'].Draw("COLZ SAME") hs['expclone'].SetLineStyle(1) hs['expclone'].SetLineWidth(3) hs['expclone'].SetLineColor(1) hs['expclone'].Draw('CONT3 SAME') ctemp = root.TCanvas() hs['expclone'].Draw('contlist') ctemp.Update() objs = root.gROOT.GetListOfSpecials().FindObject('contours') canvas.cd() hs['expup'].SetLineStyle(2) hs['expup'].SetLineWidth(2) hs['expup'].SetLineColor(1) hs['expup'].Draw('CONT3 SAME') hs['expdown'].SetLineStyle(2) hs['expdown'].SetLineWidth(2) hs['expdown'].SetLineColor(1) hs['expdown'].Draw('CONT3 SAME') if drawLegend: leg = root.TLegend(0.16, 0.62, 0.57, 0.88) #,NULL,"brNDC"); leg.SetHeader('g_{q}^{V} = 0.25, g_{DM}^{V} = 1') leg.AddEntry(hs['expclone'], "Median Expected 95% CL", "L") leg.AddEntry(hs['expup'], "Exp. #pm 1 std. dev. (exp)", "L") leg.SetFillColor(0) leg.SetBorderSize(0) leg.Draw("SAME") # hgrid.Draw('same') tex = root.TLatex() tex.SetNDC() tex.SetTextFont(42) tex.SetLineWidth(2) tex.SetTextSize(0.040) tex.Draw() tex.DrawLatex(0.62, 0.94, "36.3 fb^{-1} (13 TeV)") tex2 = root.TLatex() tex2.SetNDC() tex2.SetTextFont(42) tex2.SetLineWidth(2) tex2.SetTextSize(0.04) tex2.SetTextAngle(270) tex2.DrawLatex(0.965, 0.93, "Expected #sigma_{95% CL}/#sigma_{theory}") texCMS = root.TLatex(0.12, 0.94, "#bf{CMS}") texCMS.SetNDC() texCMS.SetTextFont(42) texCMS.SetLineWidth(2) texCMS.SetTextSize(0.05) texCMS.Draw() texPrelim = root.TLatex(0.2, 0.94, "#it{Preliminary}") texPrelim.SetNDC() texPrelim.SetTextFont(42) texPrelim.SetLineWidth(2) texPrelim.SetTextSize(0.04) texPrelim.Draw() root.gPad.SetRightMargin(0.15) root.gPad.SetTopMargin(0.07) root.gPad.SetBottomMargin(0.15) root.gPad.RedrawAxis() root.gPad.Modified() root.gPad.Update() canvas.SaveAs(foutname + '.png') canvas.SaveAs(foutname + '.pdf') fsave = root.TFile(foutname + '.root', 'RECREATE') fsave.WriteTObject(hs['exp'], 'hexp') fsave.WriteTObject(gs['exp'], 'gexp') fsave.Close()
def makePlot2D(filepath, foutname, medcfg, gqcfg, header): limits = parseLimitFiles2D(filepath) gs = {} for g in ['exp', 'expup', 'expdown', 'obs', 'obsup', 'obsdown']: gs[g] = TGraph2D() iP = 0 hgrid = TH2D('grid', 'grid', medcfg[0], medcfg[1], medcfg[2], gqcfg[0], gqcfg[1], gqcfg[2]) for p in limits: l = p.limit if l.obs == 0 or l.cent == 0: print l.mMed, l.gQ continue hgrid.Fill(l.mMed, l.gQ) gs['exp'].SetPoint(iP, l.mMed, l.gQ, l.cent) gs['expup'].SetPoint(iP, l.mMed, l.gQ, l.up1) gs['expdown'].SetPoint(iP, l.mMed, l.gQ, l.down1) gs['obs'].SetPoint(iP, l.mMed, l.gQ, l.obs) gs['obsup'].SetPoint(iP, l.mMed, l.gQ, l.obs / (1 - XSECUNCERT)) gs['obsdown'].SetPoint(iP, l.mMed, l.gQ, l.obs / (1 + XSECUNCERT)) iP += 1 hs = {} for h in ['exp', 'expup', 'expdown', 'obs', 'obsup', 'obsdown']: hs[h] = TH2D(h, h, medcfg[0], medcfg[1], medcfg[2], gqcfg[0], gqcfg[1], gqcfg[2]) # hs[h].SetStats(0); hs[h].SetTitle('') for iX in xrange(0, medcfg[0]): for iY in xrange(0, gqcfg[0]): x = medcfg[1] + (medcfg[2] - medcfg[1]) * iX / medcfg[0] y = gqcfg[1] + (gqcfg[2] - gqcfg[1]) * iY / gqcfg[0] val = gs[h].Interpolate(x, y) if val == 0: val = 9999 val = max(0.01, min(100, val)) hs[h].SetBinContent(iX + 1, iY + 1, val) # if h=='obs': # print iX+1,iY+1,x,y,gs[h].Interpolate(x,y) ''' zaxis = hs['obs'].GetZaxis() nbins = zaxis.GetNbins() print nbins zaxis.SetBinLabel(1,'<10^{-2}') zaxis.SetBinLabel(nbins,'>10') ''' hs['obsclone'] = hs['obs'].Clone( ) # clone it so we can draw with different settings for h in ['exp', 'expup', 'expdown', 'obsclone', 'obsup', 'obsdown']: hs[h].SetContour(2) hs[h].SetContourLevel(1, 1) for iX in xrange(1, medcfg[0] + 1): for iY in xrange(1, gqcfg[0] + 1): if hs[h].GetBinContent(iX, iY) <= 0: hs[h].SetBinContent(iX, iY, 100) global iC canvas = ROOT.TCanvas("canvas%i" % iC, '', 1000, 800) canvas.SetLogz() iC += 1 frame = canvas.DrawFrame(medcfg[1], gqcfg[1], medcfg[2], gqcfg[2], "") frame.GetYaxis().CenterTitle() frame.GetYaxis().SetTitle(gqcfg[3]) frame.GetXaxis().SetTitle("m_{V} [TeV]") frame.GetXaxis().SetTitleOffset(1.15) frame.GetYaxis().SetTitleOffset(1.15) frame.Draw() hs['obs'].SetMinimum(0.01) hs['obs'].SetMaximum(100.) hs['obs'].Draw("COLZ SAME") hs['obsclone'].SetLineStyle(1) hs['obsclone'].SetLineWidth(3) hs['obsclone'].SetLineColor(2) hs['obsclone'].Draw('CONT3 SAME') ctemp = root.TCanvas() hs['obsclone'].Draw('contlist') ctemp.Update() objs = root.gROOT.GetListOfSpecials().FindObject('contours') saveobs = (objs.At(0)).First() canvas.cd() hs['obsup'].SetLineStyle(2) hs['obsup'].SetLineWidth(1) hs['obsup'].SetLineColor(2) hs['obsup'].Draw('CONT3 SAME') hs['obsdown'].SetLineStyle(2) hs['obsdown'].SetLineWidth(1) hs['obsdown'].SetLineColor(2) hs['obsdown'].Draw('CONT3 SAME') hs['exp'].SetLineStyle(1) hs['exp'].SetLineWidth(3) hs['exp'].SetLineColor(1) hs['exp'].Draw('CONT3 SAME') hs['expup'].SetLineStyle(2) hs['expup'].SetLineWidth(1) hs['expup'].SetLineColor(1) hs['expup'].Draw('CONT3 SAME') hs['expdown'].SetLineStyle(2) hs['expdown'].SetLineWidth(1) hs['expdown'].SetLineColor(1) hs['expdown'].Draw('CONT3 SAME') if drawLegend: leg = root.TLegend(0.16, 0.62, 0.57, 0.88) #,NULL,"brNDC"); leg.SetHeader(header) leg.AddEntry(hs['exp'], "Median Expected 95% CL", "L") leg.AddEntry(hs['expup'], "Exp. #pm 1 std. dev. (exp)", "L") leg.AddEntry(hs['obsclone'], "Observed 95% CL", "L") leg.AddEntry(hs['obsup'], "Obs. #pm 1 std. dev. (theory)", "L") leg.SetFillColor(0) leg.SetBorderSize(0) leg.Draw("SAME") # hgrid.Draw('same') tex = root.TLatex() tex.SetNDC() tex.SetTextFont(42) tex.SetLineWidth(2) tex.SetTextSize(0.040) tex.Draw() tex.DrawLatex(0.6, 0.94, "35.8 fb^{-1} (13 TeV)") tex2 = root.TLatex() tex2.SetNDC() tex2.SetTextFont(42) tex2.SetLineWidth(2) tex2.SetTextSize(0.04) tex2.SetTextAngle(270) tex2.DrawLatex(0.965, 0.93, "Expected #sigma_{95% CL}/#sigma_{theory}") texCMS = root.TLatex(0.12, 0.94, "#bf{CMS}") texCMS.SetNDC() texCMS.SetTextFont(42) texCMS.SetLineWidth(2) texCMS.SetTextSize(0.05) texCMS.Draw() # texPrelim = root.TLatex(0.2,0.94,"#it{Preliminary}"); # texPrelim.SetNDC(); # texPrelim.SetTextFont(42); # texPrelim.SetLineWidth(2); # texPrelim.SetTextSize(0.04); texPrelim.Draw(); root.gPad.SetRightMargin(0.15) root.gPad.SetTopMargin(0.07) root.gPad.SetBottomMargin(0.15) root.gPad.RedrawAxis() root.gPad.Modified() root.gPad.Update() canvas.SaveAs(foutname + '.png') canvas.SaveAs(foutname + '.pdf') fsave = root.TFile(foutname + '.root', 'RECREATE') fsave.WriteTObject(hs['exp'], 'hexp') fsave.WriteTObject(gs['exp'], 'gexp') fsave.Close()
0.97514, 0.97068, 0.94650, 0.90751, 0.95916, 0.93991, 0.96377, 0.98120, 0.99205, 0.97595, 0.92522, 0.97245, 0.99472, 0.99782, 0.99816 ]) AUC_DNN = np.array([ 0.90729, 0.90475, 0.90596, 0.87725, 0.93349, 0.90674, 0.85802, 0.97674, 0.97644, 0.97210, 0.94923, 0.90743, 0.96152, 0.93995, 0.96559, 0.98142, 0.99210, 0.97635, 0.92650, 0.97343, 0.99470, 0.99726, 0.99729 ]) #mH = np.array([200,200,250,250,300,300,300,500,500,500,500,500,650,800,800,800,800,800,1000,1000,1000]) #mA = np.array([50,100,50,100,50,100,200,50,100,200,300,400,50,50,100,200,400,700,50,200,500]) #AUC_MEM = np.array([0.90107,0.89736,0.90640,0.87296,0.92959,0.90424,0.85102,0.97537,0.97514,0.97068,0.94650,0.90751,0.95916,0.93991,0.96377,0.98120,0.99205,0.97595,0.92522,0.97245,0.99472]) #AUC_DNN = np.array([0.90729,0.90475,0.90596,0.87725,0.93349,0.90674,0.85802,0.97674,0.97644,0.97210,0.94923,0.90743,0.96152,0.93995,0.96559,0.98142,0.99210,0.97635,0.92650,0.97343,0.99470]) N = mA.shape[0] graph_DNN = TGraph2D(N) graph_MEM = TGraph2D(N) for i in range(0, N): graph_MEM.SetPoint(i, mA[i], mH[i], AUC_MEM[i]) graph_DNN.SetPoint(i, mA[i], mH[i], AUC_DNN[i]) graph_MEM.SetNpx(500) graph_MEM.SetNpy(500) graph_DNN.SetNpx(500) graph_DNN.SetNpy(500) canvas = TCanvas('c1', 'c1', 1800, 700) canvas.Divide(2, 1, 0.005) canvas.cd(1) gPad.SetRightMargin(0.2)
def makePlot2D(filepath,foutname,medcfg,chicfg,header='',offshell=False): limits = parseLimitFiles2D(filepath) gs = {} for g in ['exp','expup','expdown','obs','obsup','obsdown']: gs[g] = TGraph2D() iP=0 hgrid = TH2D('grid','grid',medcfg[0],medcfg[1],medcfg[2],chicfg[0],chicfg[1],chicfg[2]) for p in limits: mMed = p[0]; mChi = p[1] l = limits[p] if l.obs==0 or l.cent==0: print mMed,mChi continue hgrid.Fill(mMed,mChi,100) gs['exp'].SetPoint(iP,mMed,mChi,l.cent) gs['expup'].SetPoint(iP,mMed,mChi,l.up1) gs['expdown'].SetPoint(iP,mMed,mChi,l.down1) gs['obs'].SetPoint(iP,mMed,mChi,l.obs) gs['obsup'].SetPoint(iP,mMed,mChi,l.obs/(1-XSECUNCERT)) gs['obsdown'].SetPoint(iP,mMed,mChi,l.obs/(1+XSECUNCERT)) iP += 1 hs = {} for h in ['exp','expup','expdown','obs','obsup','obsdown']: hs[h] = TH2D(h,h,medcfg[0],medcfg[1],medcfg[2],chicfg[0],chicfg[1],chicfg[2]) # hs[h].SetStats(0); hs[h].SetTitle('') for iX in xrange(0,medcfg[0]): for iY in xrange(0,chicfg[0]): x = medcfg[1] + (medcfg[2]-medcfg[1])*iX/medcfg[0] y = chicfg[1] + (chicfg[2]-chicfg[1])*iY/chicfg[0] if not(offshell) and 2*y>x: val = 9999 else: val = gs[h].Interpolate(x,y) if val == 0: val = 9999 val = max(0.01,min(100,val)) hs[h].SetBinContent(iX+1,iY+1,val) hs['obsclone'] = hs['obs'].Clone() # clone it so we can draw with different settings for h in ['exp','expup','expdown','obsclone','obsup','obsdown']: hs[h].SetContour(2) hs[h].SetContourLevel(1,1) for iX in xrange(1,medcfg[0]+1): for iY in xrange(1,chicfg[0]+1): if hs[h].GetBinContent(iX,iY)<=0: hs[h].SetBinContent(iX,iY,100) global iC canvas = ROOT.TCanvas("canvas%i"%iC, '', 1000, 800) canvas.SetLogz() iC+=1 frame = canvas.DrawFrame(medcfg[1],chicfg[1],medcfg[2],chicfg[2],"") frame.GetYaxis().CenterTitle(); #frame.GetYaxis().SetTitle("m_{A} [TeV]"); if options.thdm: frame.GetYaxis().SetTitle("m_{A} (TeV/c^{2})"); if options.zpb: frame.GetYaxis().SetTitle("m_{#chi} (TeV/c^{2})"); frame.GetXaxis().SetTitle("m_{Z'} (TeV/c^{2})"); frame.GetXaxis().SetTitleOffset(1.15); frame.GetYaxis().SetTitleOffset(1.15); # frame.GetXaxis().SetNdivisions(5) frame.Draw() htest = hs['exp'] obs_color = root.kOrange hs['obs'].SetMinimum(0.01) hs['obs'].SetMaximum(100.) hs['obs'].Draw("COLZ SAME") hs['obsclone'].SetLineStyle(1) hs['obsclone'].SetLineWidth(3) hs['obsclone'].SetLineColor(obs_color) hs['obsclone'].Draw('CONT3 SAME') ctemp = root.TCanvas() hs['obsclone'].Draw('contlist') ctemp.Update() objs = root.gROOT.GetListOfSpecials().FindObject('contours') saveobs = root.TGraph((objs.At(0)).First()) canvas.cd() root.gStyle.SetLineStyleString(11, '40 80') conts = {} hs['obsup'].SetLineStyle(3) hs['obsup'].SetLineWidth(2) hs['obsup'].SetLineColor(obs_color) conts['obsup'] = get_contours(hs['obsup'], canvas)[0] conts['obsup'].Draw('L SAME') # hs['obsup'].Draw('CONT3 SAME') hs['obsdown'].SetLineStyle(3) hs['obsdown'].SetLineWidth(2) hs['obsdown'].SetLineColor(obs_color) conts['obsdown'] = get_contours(hs['obsdown'], canvas)[0] conts['obsdown'].Draw('L SAME') #hs['obsdown'].Draw('CONT3 SAME') hs['exp'].SetLineStyle(1) hs['exp'].SetLineWidth(3) hs['exp'].SetLineColor(1) hs['exp'].Draw('CONT3 SAME') conts['exp'] = get_contours(hs['exp'], canvas)[0] conts['obsclone'] = get_contours(hs['obsclone'], canvas)[0] hs['expup'].SetLineStyle(3) hs['expup'].SetLineWidth(2) hs['expup'].SetLineColor(1) conts['expup'] = get_contours(hs['expup'], canvas)[0] conts['expup'].Draw('L SAME') #hs['expup'].Draw('CONT3 SAME') hs['expdown'].SetLineStyle(3) hs['expdown'].SetLineWidth(2) hs['expdown'].SetLineColor(1) conts['expdown'] = get_contours(hs['expdown'], canvas)[0] conts['expdown'].Draw('L SAME') #hs['expdown'].Draw('CONT3 SAME') graphroot = TFile("limitGraphs2HDMComboTanBeta.root","RECREATE") graphroot.cd() h_exp = conts['exp'] h_exp.SetName("expected_curve") h_exp.Write() #conts['exp'].Write() conts['expup'].Write() conts['expdown'].Write() #conts['obsclone'].Write() h_obs = conts['obsclone'] h_obs.SetName("observed_curve") h_obs.Write() conts['obsup'].Write() conts['obsdown'].Write() if drawLegend: leg = root.TLegend(0.13,0.75,0.39,0.9);#,NULL,"brNDC"); leg.SetHeader(header) leg.AddEntry(hs['exp'],"Median expected 95% CL","L"); leg.AddEntry(hs['expup'],"Exp. #pm 1 #sigma_{experiment}","L"); leg.AddEntry(hs['obsclone'],"Observed 95% CL","L"); leg.AddEntry(hs['obsup'],"Obs. #pm 1 #sigma_{theory}","L"); leg.SetFillColor(0); leg.SetBorderSize(0) leg.Draw("SAME"); tex = root.TLatex(); tex.SetNDC(); tex.SetTextFont(42); tex.SetLineWidth(2); tex.SetTextSize(0.040); tex.Draw(); tex.DrawLatex(0.65,0.94,"35.9 fb^{-1} (13 TeV)"); coupling = root.TLatex(); coupling.SetNDC(); coupling.SetTextFont(42); coupling.SetLineWidth(2); coupling.SetTextSize(0.025); coupling.SetTextColor(0); coupling.Draw(); if options.thdm: coupling.DrawLatex(0.15,0.70,"g_{Z'} = 0.8, g_{#chi} = 1"); coupling.DrawLatex(0.15,0.65,"m_{#chi} = 100 GeV, tan#beta = 1"); if options.zpb: coupling.DrawLatex(0.15,0.70,"g_{q} = 0.25, g_{#chi} = 1"); tex2 = root.TLatex(); tex2.SetNDC(); tex2.SetTextFont(42); tex2.SetLineWidth(2); tex2.SetTextSize(0.04); tex2.SetTextAngle(90); tex2.SetTextAlign(33) tex2.DrawLatex(0.965,0.93,"Observed #sigma_{95% CL}/#sigma_{theory}"); texCMS = root.TLatex(0.12,0.94,"#bf{CMS}"); texCMS.SetNDC(); texCMS.SetTextFont(42); texCMS.SetLineWidth(2); texCMS.SetTextSize(0.05); texCMS.Draw(); root.gPad.SetRightMargin(0.15); root.gPad.SetTopMargin(0.07); root.gPad.SetBottomMargin(0.15); root.gPad.RedrawAxis(); root.gPad.Modified(); root.gPad.Update(); canvas.SaveAs(foutname+'.png') canvas.SaveAs(foutname+'.pdf') texPrelim = root.TLatex(0.2,0.94,""); texPrelim.SetNDC(); texPrelim.SetTextFont(42); texPrelim.SetLineWidth(2); texPrelim.SetTextSize(0.05); texPrelim.Draw(); canvas.SaveAs(foutname+'_prelim.png') canvas.SaveAs(foutname+'_prelim.pdf') canvas.SetGrid() hgrid.Draw('BOX') hs['obsup'].Draw('CONT3 SAME') hs['obsdown'].Draw('CONT3 SAME') hs['exp'].Draw('CONT3 SAME') hs['expup'].Draw('CONT3 SAME') hs['expdown'].Draw('CONT3 SAME') canvas.SaveAs(foutname+'_grid.png') canvas.SaveAs(foutname+'_grid.pdf') fsave = root.TFile(foutname+'.root','RECREATE') fsave.WriteTObject(hs['obs'],'hobserved') fsave.WriteTObject(gs['obs'],'gobserved') fsave.WriteTObject(hs['exp'],'hexp') fsave.WriteTObject(gs['exp'],'gexp') fsave.WriteTObject(saveobs,'observed') fsave.Close()
def makeAndStorePlot(self, inputfilename, iSkip=2, strObsName="MPV", outputfilename="AnaSuiteClustQOutput.root", strFileOpt="RECREATE"): #Load the data from an input text file clustChargeData = np.loadtxt(inputfilename, skiprows=iSkip) #Splice the clustChargeData into HVORGAIN & CLUSTSIZE self.ARRAY_HVORGAIN = clustChargeData[:,0] self.ARRAY_CLUSTSIZE= clustChargeData[:,1] #Print the shape if requested if self.DEBUG: print "Shape of clustChargeData = {0}".format(clustChargeData.shape) print "Shape of self.ARRAY_HVORGAIN = {0}".format(self.ARRAY_HVORGAIN.shape) print "Shape of self.ARRAY_CLUSTSIZE = {0}".format(self.ARRAY_CLUSTSIZE.shape) #Reparameterize in terms of Gain? strIndepVarName = "VDrift" if self.TRANSFORM2GAIN: strIndepVarName = "EffGain" #array_X = self.GAIN_CALCULATOR.calcGain(array_X) self.ARRAY_HVORGAIN = self.GAIN_CALCULATOR.calcGain(self.ARRAY_HVORGAIN) #Transform input observable name to uppercase strObsName = strObsName.upper() #Initialize the correct TGraph2D g2D_ClustQ_Obs = TGraph2D(len(clustChargeData)) g2D_ClustQ_Obs.SetTitle("") if strObsName == self.STROBSNAME_MPV: #self.G2D_CLUSTQ_MPV.Set( len(clustChargeData) ) #self.G2D_CLUSTQ_MPV.SetName("g2D_ClusterChargeMPV_StripSize_vs_" + strIndepVarName) #self.G2D_CLUSTQ_MPV.SetTitle("") g2D_ClustQ_Obs.SetName("g2D_ClusterChargeMPV_StripSize_vs_{0}".format(strIndepVarName)) self.ARRAY_CLUSTQ_MPV = clustChargeData[:,2] elif strObsName == self.STROBSNAME_MEAN: #self.G2D_CLUSTQ_MEAN.Set( len(clustChargeData) ) #self.G2D_CLUSTQ_MEAN.SetName("g2D_ClusterChargeMean_StripSize_vs_" + strIndepVarName) #self.G2D_CLUSTQ_MEAN.SetTitle("") g2D_ClustQ_Obs.SetName("g2D_ClusterChargeMean_StripSize_vs_{0}".format(strIndepVarName)) self.ARRAY_CLUSTQ_MEAN = clustChargeData[:,2] elif strObsName == self.STROBSNAME_SIGMA: #self.G2D_CLUSTQ_SIGMA.Set( len(clustChargeData) ) #self.G2D_CLUSTQ_SIGMA.SetName("g2D_ClusterChargeSigma_StripSize_vs_" + strIndepVarName) #self.G2D_CLUSTQ_SIGMA.SetTitle("") g2D_ClustQ_Obs.SetName("g2D_ClusterChargeSigma_StripSize_vs_{0}".format(strIndepVarName)) self.ARRAY_CLUSTQ_SIGMA = clustChargeData[:,2] else: print "Input Observable Name: {0}".format(strObsName) print "Was not recognized, please cross-check and re-run" print "Exiting" return #Set the points for i in range(0, len(clustChargeData)): if strObsName == self.STROBSNAME_MPV: #self.G2D_CLUSTQ_MPV.SetPoint(i, self.ARRAY_HVORGAIN[i], self.ARRAY_CLUSTSIZE[i], self.ARRAY_CLUSTQ_MPV[i]) g2D_ClustQ_Obs.SetPoint(i, self.ARRAY_HVORGAIN[i], self.ARRAY_CLUSTSIZE[i], self.ARRAY_CLUSTQ_MPV[i]) elif strObsName == self.STROBSNAME_MEAN: #self.G2D_CLUSTQ_MEAN.SetPoint(i, self.ARRAY_HVORGAIN[i], self.ARRAY_CLUSTSIZE[i], self.ARRAY_CLUSTQ_MEAN[i]) g2D_ClustQ_Obs.SetPoint(i, self.ARRAY_HVORGAIN[i], self.ARRAY_CLUSTSIZE[i], self.ARRAY_CLUSTQ_MEAN[i]) elif strObsName == self.STROBSNAME_SIGMA: #self.G2D_CLUSTQ_SIGMA.SetPoint(i, self.ARRAY_HVORGAIN[i], self.ARRAY_CLUSTSIZE[i], self.ARRAY_CLUSTQ_SIGMA[i]) g2D_ClustQ_Obs.SetPoint(i, self.ARRAY_HVORGAIN[i], self.ARRAY_CLUSTSIZE[i], self.ARRAY_CLUSTQ_SIGMA[i]) #Reshape the arrays for later analysis self.ARRAY_HVORGAIN = np.unique(self.ARRAY_HVORGAIN) self.ARRAY_CLUSTSIZE = np.unique(self.ARRAY_CLUSTSIZE) if strObsName == self.STROBSNAME_MPV: self.ARRAY_CLUSTQ_MPV = np.reshape(self.ARRAY_CLUSTQ_MPV,(len(self.ARRAY_HVORGAIN),len(self.ARRAY_CLUSTSIZE)),order='F') elif strObsName == self.STROBSNAME_MEAN: self.ARRAY_CLUSTQ_MEAN = np.reshape(self.ARRAY_CLUSTQ_MEAN,(len(self.ARRAY_HVORGAIN),len(self.ARRAY_CLUSTSIZE)),order='F') elif strObsName == self.STROBSNAME_SIGMA: self.ARRAY_CLUSTQ_SIGMA = np.reshape(self.ARRAY_CLUSTQ_SIGMA,(len(self.ARRAY_HVORGAIN),len(self.ARRAY_CLUSTSIZE)),order='F') #Store the Plot #outputFile = TFile(outputfilename,strFileOpt,"",1) #dir_Out = [] #if strFileOpt == "UPDATE": #dir_Out = outputFile.GetDirectory("ClusterChargeData") #else: #dir_Out = outputFile.mkdir("ClusterChargeData") dir_Out = self.FILE_OUT.mkdir("ClusterChargeData") dir_Out.cd() g2D_ClustQ_Obs.Write() outputFile.Close() return
print "Could not find a valid value for par %s in filename: %s !" % ( par, file) return val ROOT.gStyle.SetPalette(1) par1 = options.par1 par2 = options.par2 par1Latex = options.par1Latex par2Latex = options.par2Latex limits = { '-2s': [TGraph2D(), 0], '-1s': [TGraph2D(), 1], 'mean': [TGraph2D(), 2], '+1s': [TGraph2D(), 3], '+2s': [TGraph2D(), 4], 'obs': [TGraph2D(), 5] } n = 0 for file in glob(options.input): if '.root' not in file: print "Skipped non-root file: %s" % file continue par1val = extractParValue(par1, file) par2val = extractParValue(par2, file)
def analyzeMeshes(self, dictOfMeshes, doCull=False, cullCut=0.90): """ analyzeMeshes takes a dictionary with meshes as input, and fits it to the references output dictionary includes a deepcopy of the input meshes note: this fits to zDiff = dictOfMeshes - interpolation of self.meshDict ie. the sign is defined as (other guy) - (me) """ # deepcopy the meshes! no longer adjusts in place dictOfMeshesCopy = {} for key in list(dictOfMeshes.keys()): theMesh = copy.deepcopy(dictOfMeshes[key]) dictOfMeshesCopy[key] = theMesh # then we analyze the Zernike polynomials by comparing them to stored references # analyzeDonuts returns a dictionary containing deltas and rotation angles for focus, astigmatism and coma # as well as the hexapod adjustments # it also makes a Canvas of plots for study dictOfResults = {} # loop over keys, fitting References for key in list(dictOfMeshesCopy.keys()): # some special cases resultsKeyName = "%sResultDict" % (key.replace("Mesh", "")) meshName = key if key == "z4Mesh": print("Python 3 debugging: %r" % self.meshDict) dictOfResults[resultsKeyName] = self.fitToRefMesh( self.meshDict[meshName], dictOfMeshesCopy[meshName], self.zangleconv) elif key == "rzeroMesh": dictOfResults[resultsKeyName] = self.analyzeRzero( dictOfMeshesCopy["rzeroMesh"], dictOfMeshesCopy["chi2Mesh"], dictOfMeshesCopy["neleMesh"]) elif key == "chi2Mesh": continue elif key == "neleMesh": continue else: # check that meshDict has the appropriate mesh if meshName in self.meshDict: dictOfResults[resultsKeyName] = self.fitToRefMesh( self.meshDict[meshName], dictOfMeshesCopy[meshName]) # if we want to cull, cull and refit! # use the fitted weight to cull - culltype="fit" if doCull: # this will take the wgt's from the fit and take their product # for each point, and cull at a product of cullCut self.cullAllMeshes(dictOfMeshesCopy, cullCut=cullCut) for key in list(dictOfMeshesCopy.keys()): # some special cases resultsKeyName = "%sResultDict" % (key.replace("Mesh", "")) meshName = key if key == "z4Mesh": dictOfResults[resultsKeyName] = self.fitToRefMesh( self.meshDict[meshName], dictOfMeshesCopy[meshName], self.zangleconv) elif key == "rzeroMesh": dictOfResults[resultsKeyName] = self.analyzeRzero( dictOfMeshesCopy["rzeroMesh"], dictOfMeshesCopy["chi2Mesh"], dictOfMeshesCopy["neleMesh"]) elif key == "chi2Mesh": continue elif key == "neleMesh": continue else: # check that meshDict has the appropriate mesh if meshName in self.meshDict: dictOfResults[resultsKeyName] = self.fitToRefMesh( self.meshDict[meshName], dictOfMeshesCopy[meshName]) # analyze this data and extract the hexapod coefficients donutDict = self.calcHexapod(dictOfResults) if len(donutDict) == 0: goodCalc = False else: goodCalc = True # add the individual fit results here too for key in list(dictOfResults.keys()): donutDict[key] = dictOfResults[key] # and add the meshes too for key in list(dictOfMeshesCopy.keys()): donutDict[key] = dictOfMeshesCopy[key] # cmr add X and Y coords keylist = list(dictOfResults.keys()) key0 = keylist[0] dict0 = dictOfResults[key0] donutDict['deltaArrayX'] = dict0['deltaArrayX'] donutDict['deltaArrayY'] = dict0['deltaArrayY'] # make a Canvas of plots for this image # plot Histogram of Difference before fit, after fit, and after fit vs. X,Y position if self.paramDict["histFlag"] and "deltaArrayBefore" in dictOfResults[ "z4ResultDict"] and goodCalc: # setup plots gStyle.SetStatH(0.32) gStyle.SetStatW(0.4) gStyle.SetOptStat(1111111) gStyle.SetMarkerStyle(20) gStyle.SetMarkerSize(0.5) gStyle.SetPalette(1) gROOT.ForceStyle() # loop over results, making plots for each nplots = 0 plotDict = {} for key in list(dictOfResults.keys()): theResultDict = dictOfResults[key] keyId = key.replace("ResultDict", "") # special cases if keyId == "z4": nWavesBefore = 200.0 nWavesAfter = 200.0 else: nWavesBefore = 2.0 nWavesAfter = 0.2 if keyId != "rzero": nplots = nplots + 1 hBefore = hfillhist(key + "Before", "Delta " + key + ", Before Fit", theResultDict["deltaArrayBefore"], 200, -nWavesBefore, nWavesBefore) hAfter = hfillhist(key + "zAfter", "Delta " + key + ", After Fit", theResultDict["deltaArrayAfter"], 200, -nWavesAfter, nWavesAfter) hBefore2D = TGraph2D( key + "Before2D", "Delta " + key + ", Before Fit, vs. Position;X[mm];Y[mm]", theResultDict["deltaArrayBefore"].shape[0], theResultDict["deltaArrayX"], theResultDict["deltaArrayY"], theResultDict["deltaArrayBefore"]) hAfter2D = TGraph2D( key + "After2D", "Delta " + key + ", After Fit, vs. Position;X[mm];Y[mm]", theResultDict["deltaArrayAfter"].shape[0], theResultDict["deltaArrayX"], theResultDict["deltaArrayY"], theResultDict["deltaArrayAfter"]) plotList = [hBefore, hAfter, hBefore2D, hAfter2D] plotDict[keyId] = plotList # the Canvas # unique name for our canvas # might be that # gROOT.SetBatch(kTRUE) # will prevent the Canvas from appearing, but will still get made in output pickle tstr = "canvas" + str(time.time()) canvas = TCanvas(tstr, tstr, 300 * nplots, 1000) canvas.Divide(nplots, 4) # plot em jZ = 0 for iZ in range(4, 15 + 1): key = "z%d" % (iZ) if key in plotDict: jZ = jZ + 1 plotList = plotDict[key] icanvas = jZ + 0 * nplots canvas.cd(icanvas) plotList[0].Draw() icanvas = jZ + 1 * nplots canvas.cd(icanvas) plotList[1].Draw() icanvas = jZ + 2 * nplots canvas.cd(icanvas) plotList[2].Draw("zcolpcol") icanvas = jZ + 3 * nplots canvas.cd(icanvas) plotList[3].Draw("zcolpcol") # set it so that python doesn't own these ROOT object for key in list(plotDict.keys()): for plot in plotDict[key]: SetOwnership(plot, False) # save canvas in the output Dictionary donutDict["canvas"] = canvas # all done return donutDict
for plane in otherplanes: branches[plane[0]][0] = float( randint(0, 11)) scores.append(reader.EvaluateMVA(ML)) MLscore = sum(scores) / float(len(scores)) plane_y.append(float(strip1)) plane_x.append(float(strip2)) MLscores.append(MLscore) ########## Make canvases, draw plots, and save them c = TCanvas( sample[0] + "_" + planey[1] + "vs" + planex[1] + "vs" + ML, sample[0] + "_" + planey[1] + "vs" + planex[1] + "vs" + ML) gr = TGraph2D(len(MLscores), plane_x, plane_y, MLscores) gr.SetName(sample[1] + " " + planey[1] + " vs " + planex[1] + " vs " + ML + " score") gr.Draw("COLZ") c.Update() gr.SetTitle(sample[1] + " " + planey[1] + " vs " + planex[1] + " vs " + ML + " score") gr.GetXaxis().SetTitle(planex[1]) gr.GetYaxis().SetTitle(planey[1]) gr.GetZaxis().SetTitle(ML + " score") gr.GetZaxis().SetTitleOffset(1.2) d_out.cd() c.Write() c.SaveAs(folder + "/%s.pdf" % (c.GetName()))
def calcGainMapHV(self, strDetName, hvPt): #Create the new TGraph2D - Gain g2D_Map_Gain_hvPt = TGraph2D( self.G2D_MAP_GAIN_ORIG.GetN() ) #g2D_Map_Gain_hvPt.SetName( "g2D_" + strDetName + "_EffGain_AllEta_" + str(int(hvPt)) ) g2D_Map_Gain_hvPt.SetName( "g2D_{0}_EffGain_AllEta_{1}".format(strDetName, int(hvPt)) ) #Create the new TGraph2D - Discharge Probability g2D_Map_PD_hvPt = TGraph2D( self.G2D_MAP_GAIN_ORIG.GetN() ) #g2D_Map_PD_hvPt.SetName( "g2D_" + strDetName + "_PD_AllEta_" + str(int(hvPt)) ) g2D_Map_PD_hvPt.SetName( "g2D_{0}_PD_AllEta_{1}".format(strDetName, int(hvPt)) ) #Get the arrays that make the response uniformity map array_fPx = self.G2D_MAP_GAIN_ORIG.GetX() array_fPy = self.G2D_MAP_GAIN_ORIG.GetY() array_fPz = self.G2D_MAP_GAIN_ORIG.GetZ() #Calculate alpha alpha = self.calcAlpha(hvPt) #Loop Over all Points of self.G2D_MAP_ABS_RESP_UNI array_Gain_Vals = np.zeros(self.G2D_MAP_ABS_RESP_UNI.GetN()) array_PD_Vals = np.zeros(self.G2D_MAP_ABS_RESP_UNI.GetN()) for i in range(0, self.G2D_MAP_ABS_RESP_UNI.GetN() ): #Set the i^th point in self.G2D_MAP_GAIN_ORIG array_Gain_Vals[i] = array_fPz[i] * alpha array_PD_Vals[i] = self.PD_CALCULATOR.calcPD(array_fPz[i] * alpha) g2D_Map_Gain_hvPt.SetPoint(i, array_fPx[i], array_fPy[i], array_fPz[i] * alpha) g2D_Map_PD_hvPt.SetPoint(i, array_fPx[i], array_fPy[i], self.PD_CALCULATOR.calcPD(array_fPz[i] * alpha) ) #Store Average, Std. Dev., Max, & Min Gain array_Gain_Vals = rejectOutliers(array_Gain_Vals) self.DET_IMON_POINTS.append(hvPt) self.GAIN_AVG_POINTS.append(np.mean(array_Gain_Vals) ) self.GAIN_STDDEV_POINTS.append(np.std(array_Gain_Vals) ) self.GAIN_MAX_POINTS.append(np.max(array_Gain_Vals) ) self.GAIN_MIN_POINTS.append(np.min(array_Gain_Vals) ) #Store Average, Std. Dev., Max & Min P_D array_PD_Vals = rejectOutliers(array_PD_Vals) self.PD_AVG_POINTS.append(np.mean(array_PD_Vals) ) self.PD_STDDEV_POINTS.append(np.std(array_PD_Vals) ) self.PD_MAX_POINTS.append(np.max(array_PD_Vals) ) self.PD_MIN_POINTS.append(np.min(array_PD_Vals) ) #Draw the effective gain map #canv_Gain_Map_hvPt = TCanvas("canv_" + strDetName + "_EffGain_AllEta_" + str(int(hvPt)),"Gain Map - hvPt = " + str(hvPt),600,600) canv_Gain_Map_hvPt = TCanvas("canv_{0}_EffGain_AllEta_{1}".format(strDetName, int(hvPt)),"Gain Map - hvPt = {0}".format(hvPt),600,600) canv_Gain_Map_hvPt.cd() canv_Gain_Map_hvPt.cd().SetLogz(1) g2D_Map_Gain_hvPt.Draw("TRI2Z") #Draw the discharge probability map #canv_PD_Map_hvPt = TCanvas("canv_" + strDetName + "_PD_AllEta_" + str(int(hvPt)),"Discharge Probability Map - hvPt = " + str(hvPt),600,600) canv_PD_Map_hvPt = TCanvas("canv_{0}_PD_AllEta_{1}".format(strDetName,int(hvPt)),"Discharge Probability Map - hvPt = {0}".format(hvPt),600,600) canv_PD_Map_hvPt.cd() canv_PD_Map_hvPt.cd().SetLogz(1) g2D_Map_PD_hvPt.Draw("TRI2Z") #Write the effective gain map to the output file #dir_hvPt = self.FILE_OUT.mkdir( "GainMap_HVPt" + str(int(hvPt)) ) dir_hvPt = self.FILE_OUT.mkdir( "GainMap_HVPt{0}".format(int(hvPt)) ) dir_hvPt.cd() canv_Gain_Map_hvPt.Write() g2D_Map_Gain_hvPt.Write() canv_PD_Map_hvPt.Write() g2D_Map_PD_hvPt.Write() return g2D_Map_Gain_hvPt
args = parser.parse_args() N = args.nEvents name = args.name draw = args.draw opt = args.opt out = args.output print(N) print(name[1:]) print(opt) title = "" if (name == "gArg" or name == "gAbs"): title = name[ 1:] + "(A(m^{2}_{K_{S}^{0}#pi^{+}},m^{2}_{K_{S}^{0}#pi^{-}})); m^{2}_{K_{S}^{0}#pi^{+}}(GeV); m^{2}_{K_{S}^{0}#pi^{-}} (GeV)" os.system("Generator --nEvents %i --Output %s.root %s.opt" % (N, opt, opt)) f = TFile.Open("%s.root" % (opt)) s = f.Get(name) c = TCanvas("c_%s" % (name), name, 1000, 1000) c.cd() gStyle.SetPalette(55) if (type(s) == TH2D): s = TGraph2D(s) s.SetMargin(0.1) print(type(s)) s.SetTitle(title) s.Draw(draw) c.SaveAs("%s.png" % (out))