コード例 #1
0
ファイル: pfobjects.py プロジェクト: f-thiele/heppy
class Blob(object):
    def __init__(self, cluster):
        self.cluster = cluster
        pos = cluster.position
        radius = cluster.size()
        thetaphiradius = cluster.angular_size()
        # print radius
        color = 1
        if cluster.particle:
            if cluster.particle.pdgid() == 22 or cluster.particle.pdgid() == 11:
                color = 2
            else:
                color = 4
        max_energy = cluster.__class__.max_energy
        self.contour_xy = TEllipse(pos.X(), pos.Y(), radius)
        self.contour_yz = TEllipse(pos.Z(), pos.Y(), radius)   
        self.contour_xz = TEllipse(pos.Z(), pos.X(), radius)
        self.contour_thetaphi = TEllipse(math.pi/2. - pos.Theta(), pos.Phi(),
                                         thetaphiradius)
        contours = [self.contour_xy, self.contour_yz, self.contour_xz,
                    self.contour_thetaphi]
        iradius = radius * cluster.energy / max_energy
        ithetaphiradius = thetaphiradius * cluster.energy / max_energy
        self.inner_xy = TEllipse(pos.X(), pos.Y(), iradius)
        self.inner_yz = TEllipse(pos.Z(), pos.Y(), iradius)   
        self.inner_xz = TEllipse(pos.Z(), pos.X(), iradius)
        self.inner_thetaphi = TEllipse(math.pi/2. - pos.Theta(), pos.Phi(),
                                       ithetaphiradius)
        inners = [self.inner_xy, self.inner_yz, self.inner_xz,
                  self.inner_thetaphi]
        for contour in contours:
            contour.SetLineColor(color)
            contour.SetFillStyle(0)
        for inner in inners: 
            inner.SetFillColor(color)
            inner.SetFillStyle(3002)
            
    def draw(self, projection, opt=''):
        if projection == 'xy':
            self.contour_xy.Draw(opt+"psame")
            self.inner_xy.Draw(opt+"psame")
        elif projection == 'yz':
            self.contour_yz.Draw(opt+"psame")
            self.inner_yz.Draw(opt+"psame")
        elif projection == 'xz':
            self.contour_xz.Draw(opt+"psame")            
            self.inner_xz.Draw(opt+"psame")
        elif projection == 'ECAL_thetaphi':
            if self.cluster.layer == 'ecal_in':
                self.contour_thetaphi.Draw(opt+"psame")            
                self.inner_thetaphi.Draw(opt+"psame")
        elif projection == 'HCAL_thetaphi':
            if self.cluster.layer == 'hcal_in':
                self.contour_thetaphi.Draw(opt+"psame")            
                self.inner_thetaphi.Draw(opt+"psame")            
        else:
            raise ValueError('implement drawing for projection ' + projection )
コード例 #2
0
ファイル: geotools.py プロジェクト: dcarogancia/heppy_fcc
        xp = -xp
    xm = math.sqrt(r2**2 - ym**2)
    if abs((xm - x1)**2 + (ym - y1)**2 - r1**2) > 1e-9:
        xm = -xm
    if switchxy:
        xm, ym = ym, xm
        xp, yp = yp, xp
    return xm, ym, xp, yp


if __name__ == '__main__':

    from ROOT import TEllipse, TH2F, TCanvas, TMarker

    can = TCanvas("can", "", 600, 600)
    suph = TH2F("suph", "", 10, -5, 5, 10, -5, 5)
    suph.Draw()
    x1, y1, r1, r2 = 0., 1.8, 1., 2.
    results = circle_intersection(x1, y1, r1, r2)
    c1 = TEllipse(x1, y1, r1)
    c1.Draw('same')
    c2 = TEllipse(0., 0., r2)
    c2.Draw('same')
    c1.SetFillStyle(0)
    c2.SetFillStyle(0)
    mm = TMarker(results[0], results[1], 8)
    mp = TMarker(results[2], results[3], 21)
    mm.Draw('same')
    mp.Draw('same')
    can.Update()
class CovarianceMatrix2DContourPlot(object):
    """2D confidence interval contour plot.

    This is a base class to plot, given a 2D fit result, the contour region (that
    is an ellipse in the gaussian likelihood approximation) relative to a given
    confidence level, on the two dimensional space parameters.

    TODO: extend the class to plot more than one covariance_matrix!
    TODO: raise exceptions in the init code instead of printing some erros message!
    TODO: would a name like PlotFitResult be nicer?
    """

    def __init__(self, name, fit_parameters, covariance_matrix, args = dict(sigma = 1)):
        """Constructor with the fit output.

        Provide the constructor with the following objects:
        - name: identificative name for ROOT objects
        - fit_parameters: numpy array (shape 1,2) containing the two paramters of the fit
        - covariance_matrix: numpy array (shape 2,2) containing the covariance matrix of the fit
        - args: dictionary to specify the type of plot you want:
        It can be:
        - dict(sigma = 1)
        - dict(probability = 0.68)
        """
        self.name = name
        self.fit_parameters = fit_parameters
        self.covariance_matrix = covariance_matrix
        self.args = args

        if len(self.args) != 1:
            print "args length different than 1"
            return

        if 'sigma' in self.args:
            self.sigma = self.args['sigma']
            self.ellipse_dimension = self.sigma
        elif 'probability' in self.args:
            self.probability = self.args['probability']
            if self.probability > 1 or self.probability < 0:
                print "probability must be between 0 and 1!"
                return
            self.ellipse_dimension = np.sqrt(-2 * np.log(1 - self.probability))
        else:
            print "neither 'sigma' nor 'probability' in args"
            return

    def DefineEllipse(self):
        self.second_derivative_matrix = np.linalg.inv(self.covariance_matrix)

        self.eigenvals, self.eigenvecs = np.linalg.eig(self.second_derivative_matrix)
        self.lambd = np.sqrt(self.eigenvals)
        self.angle = np.rad2deg(np.arctan(self.eigenvecs[1,0]/self.eigenvecs[0,0]))

        self.ellipse = TEllipse(self.fit_parameters[0, 0],
                                self.fit_parameters[0, 1],
                                self.ellipse_dimension/self.lambd[0],
                                self.ellipse_dimension/self.lambd[1],
                                0.,
                                360.,
                                self.angle)
        self.ellipse.SetFillStyle(0)
        self.ellipse.SetLineColor(2)
        self.ellipse.SetLineWidth(4)

        self.graph_axis_range = max(self.ellipse_dimension/self.lambd[0], self.ellipse_dimension/self.lambd[1])

    def PrepareDraw(self, title = '', legend_title = '', xtitle = '', ytitle = ''):
        self.title = title
        self.legend_title = legend_title
        self.xtitle = xtitle
        self.ytitle = ytitle

        self.x_axis = np.array([-self.graph_axis_range * 2.1,
                                self.graph_axis_range * 2.1,
                                self.fit_parameters[0, 0],
                                self.fit_parameters[0, 0],
                                self.fit_parameters[0, 0],
                                self.fit_parameters[0, 0]])
        self.y_axis = np.array([self.fit_parameters[0, 1],
                                self.fit_parameters[0, 1],
                                self.fit_parameters[0, 1],
                                -self.graph_axis_range * 2.1,
                                self.fit_parameters[0, 1],
                                self.graph_axis_range * 2.1])
        self.graph_axis = TGraph(6, self.x_axis, self.y_axis)
        self.graph_axis.SetNameTitle("axis_" + self.name, self.title)
        self.graph_axis.GetXaxis().SetTitle(xtitle)
        self.graph_axis.GetYaxis().SetTitle(ytitle)
        self.graph_axis.GetXaxis().SetRangeUser(self.fit_parameters[0, 0] - self.graph_axis_range * 2.,
                                          self.fit_parameters[0, 0] + self.graph_axis_range * 2.)

        self.graph_axis.GetYaxis().SetRangeUser(self.fit_parameters[0, 1] - self.graph_axis_range * 2.,
                                          self.fit_parameters[0, 1] + self.graph_axis_range * 2.)

        self.ellipse.SetFillStyle(3001)
        self.ellipse.SetFillColor(2)
        self.ellipse.SetLineColor(2)
        self.ellipse.SetLineWidth(4)

        self.legend = TLegend(0.7407705, 0.6983945, 0.9911717, 0.928899)
        key, value = self.args.items()[0]
        if key == 'sigma':
            aux_legend_string = self.legend_title + " " + str(value) + ' #sigma'
        else:
            aux_legend_string = self.legend_title + " C.L. " + str(int(100 * value)) + '%'
        self.legend.AddEntry(self.ellipse, aux_legend_string, "f")

    def Draw(self):
        TopMassStyle()

        self.canvas = TCanvas("canvas_" + self.name, self.title, 800, 600)
        self.canvas.cd()
        self.canvas.SetGrid()

        self.graph_axis.Draw("AP")
        self.ellipse.Draw("same")
        self.legend.Draw("same")
コード例 #4
0
    def MakePlots(self):
        if not hasattr(self, "Numerator") or not hasattr(self, "Denominator"):
            print "Either Numerator or Denominator has not been defined. Not finding hot spots..."
            return

        circles = []
        for spots in self._hotSpotsList:
            circle = TEllipse(float(spots[0]), float(spots[1]), 0.06)
            circle.SetLineColor(2)
            circle.SetLineWidth(1)
            circle.SetFillStyle(0)
            circles.append(circle)

        LumiText = str.format('{0:.1f}',
                              self._luminosityInInvFb) + " fb^{-1} (13 TeV)"

        pasLumiLatex = TLatex()
        pasLumiLatex.SetNDC()
        pasLumiLatex.SetTextAngle(0)
        pasLumiLatex.SetTextFont(42)
        pasLumiLatex.SetTextAlign(32)
        pasLumiLatex.SetTextSize(0.04)

        pasCMSLatex = TLatex()
        pasCMSLatex.SetNDC()
        pasCMSLatex.SetTextAngle(0)
        pasCMSLatex.SetTextFont(62)
        pasCMSLatex.SetTextAlign(12)
        pasCMSLatex.SetTextSize(0.04)

        pasPrelimLatex = TLatex()
        pasPrelimLatex.SetNDC()
        pasPrelimLatex.SetTextAngle(0)
        pasPrelimLatex.SetTextFont(62)
        pasPrelimLatex.SetTextAlign(12)
        pasPrelimLatex.SetTextSize(0.04)

        self.Denominator["histogram"].Draw('colz')
        pasLumiLatex.DrawLatex(0.96, 0.93, LumiText)
        pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary")
        self._canvas.SaveAs('fiducialMapCalc_beforeVeto_' +
                            self.Denominator["sample"] + '.pdf')

        self.Numerator["histogram"].Draw('colz')
        pasLumiLatex.DrawLatex(0.96, 0.93, LumiText)
        pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary")
        self._canvas.SaveAs('fiducialMapCalc_afterVeto_' +
                            self.Numerator["sample"] + '.pdf')

        self._canvas.SetLogz(False)
        self.Numerator["histogram"].Divide(self.Denominator["histogram"])
        self.Numerator["histogram"].Draw('colz')

        if 'SingleEle' in self.Numerator["sample"]:
            self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 0.5)
        elif 'SingleMu' in self.Numerator["sample"]:
            self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 0.05)
        self.Numerator["histogram"].GetZaxis().SetLabelSize(0.025)

        for circle in circles:
            circle.Draw("same")

        pasLumiLatex.DrawLatex(0.96, 0.93, LumiText)
        pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary")
        self._canvas.SaveAs('fiducialMapCalc_efficiency_' +
                            self.Numerator["sample"] + '.pdf')

        for xbin in range(1,
                          self.Numerator["histogram"].GetXaxis().GetNbins()):
            for ybin in range(
                    1, self.Numerator["histogram"].GetYaxis().GetNbins()):

                thisInefficiency = self.Numerator["histogram"].GetBinContent(
                    xbin, ybin)
                if thisInefficiency == 0:
                    continue

                valueInSigma = (thisInefficiency - self._meanInefficiency
                                ) / self._stdDevInefficiency
                if valueInSigma < 0:
                    valueInSigma = 0

                self.Numerator["histogram"].SetBinContent(
                    xbin, ybin, valueInSigma)

        self._canvas.SetLogz(False)
        self.Numerator["histogram"].GetZaxis().SetLabelSize(0.04)
        self.Numerator["histogram"].Draw('colz')

        if 'SingleEle' in self.Numerator["sample"]:
            if '2017' in self.Numerator["sample"]:
                self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 7)
            self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 12)
        elif 'SingleMu' in self.Numerator["sample"]:
            self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 23)
        self.Numerator["histogram"].GetZaxis().SetLabelSize(0.025)

        for circle in circles:
            circle.Draw("same")

        pasLumiLatex.DrawLatex(0.96, 0.93, LumiText)
        pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary")
        self._canvas.SaveAs('fiducialMapCalc_efficiencyInSigma_' +
                            self.Numerator["sample"] + '.pdf')
class CovarianceMatrix2DContourPlot(object):
    """

    TODO: extend the class to plot more than one covariance_matrix!
    TODO: raise exceptions in the init code instead of printing some erros message!
    """
    def __init__(self, name, mean, covariance_matrix, args=dict(sigma=1)):
        """ """
        self.name = name
        self.mean = mean
        self.covariance_matrix = covariance_matrix
        self.args = args

        if len(self.args) != 1:
            print "args length different than 1"
            return

        if 'sigma' in self.args:
            self.sigma = self.args['sigma']
            self.k = self.sigma
        elif 'probability' in self.args:
            self.probability = self.args['probability']
            if self.probability > 1 or self.probability < 0:
                print "probability must be between 0 and 1!"
                return
            self.k = np.sqrt(-2 * np.log(1 - self.probability))
        else:
            print "neither 'sigma' nor 'probability' in args"
            return

        self.second_derivative_matrix = np.linalg.inv(self.covariance_matrix)

        self.eigenvals, self.eigenvecs = np.linalg.eig(
            self.second_derivative_matrix)
        self.lambd = np.sqrt(self.eigenvals)
        self.angle = np.rad2deg(
            np.arctan(self.eigenvecs[1, 0] / self.eigenvecs[0, 0]))

        self.ellipse = TEllipse(self.mean[0], self.mean[1],
                                self.k / self.lambd[0], self.k / self.lambd[1],
                                0., 360., self.angle)
        self.ellipse.SetFillStyle(0)
        self.ellipse.SetLineColor(2)
        self.ellipse.SetLineWidth(4)

        self.scale = max(self.k / self.lambd[0], self.k / self.lambd[1])

    def Draw(self):

        self.canvas = TCanvas("canvas_" + self.name, self.name, 800, 600)

        self.x_axis = np.array(
            [-self.scale * 2.1, self.scale * 2.1, 0., 0., 0., 0.])
        self.y_axis = np.array(
            [0., 0., 0., -self.scale * 2.1, 0., self.scale * 2.1])
        self.axis = TGraph(6, x, y)
        self.axis.SetNameTitle("axis_" + self.name, self.name)

        self.ellipse.SetFillStyle(3001)
        self.ellipse.SetFillColor(2)
        self.ellipse.SetLineColor(2)
        self.ellipse.SetLineWidth(4)

        self.legend = TLegend(0.7407705, 0.6983945, 0.9911717, 0.928899)
        self.legend.AddEntry(self.ellipse, "FCC-ee 1 #sigma ", "f")

        self.canvas.cd()
        self.canvas.SetGrid()

        self.axis.Draw("AP")
        self.ellipse.Draw("same")
        self.legend.Draw("same")

    def LoadExternalPoints(self):

        external_points = TGraph()
        external_points.SetNameTitle()

        with open(fileName) as f:
            for i, line in enumerate(f):
                data = line.split()
                external_points.SetPoint(i, data[0], data[1])

        external_points.GetXaxis().SetLimits(-6, 6)
        external_points.GetYaxis().SetRangeUser(-6, 10)
        external_points.GetXaxis().SetTitle("#Delta g_{L} / g_{L} (%)")
        external_points.GetYaxis().SetTitle("#Delta g_{R} / g_{R} (%)")
        external_points.SetTitle(
            "Expected relative precision on the Zt_{L}t_{L} and Zt_{R}t_{R} couplings at FCC-ee"
        )
        external_points.SetMarkerSize(0.4)
        external_points.SetMarkerStyle(20)

        self.legend.AddEntry(external_points, "4DCHM f #leq 1.5 TeV", "p")
コード例 #6
0
ファイル: pfobjects.py プロジェクト: efilmer/heppyold
class Blob(object):
    ''' Blob is used to plot clusters on an event diagram
    '''
    def __init__(self, cluster, grey=False):
        ''' cluster = a cluster object
            grey = True/False an option to plot the cluster all in grey
                   used for comparing reconstructed and simulated particles
            '''
        self.cluster = cluster
        pos = cluster.position
        radius = cluster.size()
        thetaphiradius = cluster.angular_size()
        #color is for the circle showing the cluster resolution
        color = 7
        #innercolor is for the the shaded energy scaled cluster sie
        innercolor = 1

        if cluster.particle:
            if cluster.particle.pdgid() == 22 or cluster.particle.pdgid(
            ) == 11:
                color = 2
            else:
                color = 4
        if grey:  #option that can be used to compare reconstructed and simulated
            #if set the blob will be in grey
            color = 17  #grey!
            innercolor = 17
        if color == 1:
            pass
        max_energy = cluster.__class__.max_energy
        self.contour_xy = TEllipse(pos.X(), pos.Y(), radius)
        self.contour_yz = TEllipse(pos.Z(), pos.Y(), radius)
        self.contour_xz = TEllipse(pos.Z(), pos.X(), radius)
        self.contour_thetaphi = TEllipse(math.pi / 2. - pos.Theta(), pos.Phi(),
                                         thetaphiradius)
        contours = [
            self.contour_xy, self.contour_yz, self.contour_xz,
            self.contour_thetaphi
        ]
        iradius = radius * cluster.energy / max_energy
        ithetaphiradius = thetaphiradius * cluster.energy / max_energy
        self.inner_xy = TEllipse(pos.X(), pos.Y(), iradius)
        self.inner_yz = TEllipse(pos.Z(), pos.Y(), iradius)
        self.inner_xz = TEllipse(pos.Z(), pos.X(), iradius)
        self.inner_thetaphi = TEllipse(math.pi / 2. - pos.Theta(), pos.Phi(),
                                       ithetaphiradius)
        inners = [
            self.inner_xy, self.inner_yz, self.inner_xz, self.inner_thetaphi
        ]
        for contour in contours:
            contour.SetLineColor(color)
            contour.SetFillStyle(0)
        for inner in inners:
            inner.SetLineColor(innercolor)
            inner.SetFillColor(color)
            inner.SetFillStyle(3002)

    def draw(self, projection, opt=''):
        if projection == 'xy':
            self.contour_xy.Draw(opt + "psame")
            self.inner_xy.Draw(opt + "psame")
        elif projection == 'yz':
            self.contour_yz.Draw(opt + "psame")
            self.inner_yz.Draw(opt + "psame")
        elif projection == 'xz':
            self.contour_xz.Draw(opt + "psame")
            self.inner_xz.Draw(opt + "psame")
        elif projection == 'ECAL_thetaphi':
            if self.cluster.layer == 'ecal_in':
                self.contour_thetaphi.Draw(opt + "psame")
                self.inner_thetaphi.Draw(opt + "psame")
        elif projection == 'HCAL_thetaphi':
            if self.cluster.layer == 'hcal_in':
                self.contour_thetaphi.Draw(opt + "psame")
                self.inner_thetaphi.Draw(opt + "psame")
        else:
            raise ValueError('implement drawing for projection ' + projection)
コード例 #7
0
ファイル: ModelGraph.py プロジェクト: suatdonertas/Memoire
    # Print Ellipse #
    test_isin = np.isin(gen_ellipse, mHmA[c, :])
    test_isin = np.logical_and(test_isin[:, 0], test_isin[:, 1])
    test_check = False
    for idx, val in enumerate(test_isin):
        if val == True:
            test_check = True
    #test_check = False # Don't want the ellipses now
    if test_check == True:
        x, y, a, b, theta = getEllipseConf(mHmA[c, 1], mHmA[c, 0],
                                           ellipse_conf)
        t = theta * 57.29  # radians -> Degrees
        ell = TEllipse(x, y, rho * math.sqrt(a), rho * math.sqrt(b), 0, 360, t)
        ell.SetFillStyle(0)
        ell.SetLineWidth(2)
        ell.Draw("same")
    else:
        print('Not an ellipse configuration')

    #c1.Modified()
    #c1.Update()

    #c1.Print(path+filename,'Title:mH_%0.f_mA_%0.f'%(mHmA[c,0],mHmA[c,1]))
    c1.Print(path + filename + '_' + str(c) + '.jpg')
    c1.Clear()

#c1.Print(path+filename+']')
#if gROOT.IsBatch():
#c1.Print(path+filename+'++')

#input('Press enter to end')