示例#1
0
    def get_hist(self, typ, wave1, wave2=None):
        """
		Creates a ROOT histogram for the gibten waves and type
		@param typ: Type of the histogram:
			intensity: Intensity of wave1 (No wave2 needed)
			real: Real part of the intereference of wave1 and wave2
			imag: Imaginary part of the intereference of wave1 and wave2
			phase: Complex phase of the intereference of wave1 and wave2
		@type typ: str
		@param wave1: Number of the first wave
		@type wave1: int
		@param wave2: Number of the second wave
		@type wave2: int
		@return: Chosen ROOT histogram		
		@rtype: Hist
		"""
        mmin, mmax, nbin = self.get_mmin_mmax_nbin()
        hist = Hist(nbin, mmin, mmax)
        for bin in self.bins:
            mass = bin.center()
            n_bin = hist.FindBin(mass)
            if typ == "intensity":
                hist.SetBinContent(n_bin, bin.intens[wave1])
                hist.SetBinError(n_bin, bin.errors_intens[wave1])
            elif typ == "real":
                hist.SetBinContent(n_bin, bin.re[wave1][wave2])
                hist.SetBinError(n_bin, bin.errors_re[wave1][wave2])
            elif typ == "imag":
                hist.SetBinContent(n_bin, bin.im[wave1][wave2])
                hist.SetBinError(n_bin, bin.errors_im[wave1][wave2])
            elif typ == "phase":
                hist.SetBinContent(n_bin, bin.phases[wave1][wave2] * 180. / pi)
                hist.SetBinError(n_bin,
                                 bin.errors_phase[wave1][wave2] * 180. / pi)
            else:
                raise KeyError  # Type not defined
        hist.SetTitle("mass-independent")
        hist.SetName("mass-independent")
        return hist
示例#2
0
map(h2.Fill, x2)

# normalize the histograms
h1 /= h1.Integral()
h2 /= h2.Integral()

# set visual attributes
h1.SetFillStyle("solid")
h1.SetFillColor("green")
h1.SetLineColor("green")

h2.SetFillStyle("solid")
h2.SetFillColor("red")
h2.SetLineColor("red")

# plot with ROOT
h1.GetXaxis().SetTitle('Smarts')
h1.GetYaxis().SetTitle('Probability')
h1.SetTitle("Histogram of IQ: #mu=100, #sigma=15")
h1.Draw("hist")
h2.Draw("same")

# plot with matplotlib
plt.figure()
rplt.hist(h1, alpha=0.75)
rplt.hist(h2, alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.show()
示例#3
0
 import matplotlib.pyplot as plt
 from matplotlib.ticker import AutoMinorLocator
 
 bins = array('d', [0, 25, 45, 70, 100, 1000])
 h_data = Hist(bins.tolist())
 h_data.SetBinContent(1, 2146)
 h_data.SetBinError(1, 145)
 h_data.SetBinContent(2, 3399)
 h_data.SetBinError(2, 254)
 h_data.SetBinContent(3, 3723)
 h_data.SetBinError(3, 69)
 h_data.SetBinContent(4, 2256)
 h_data.SetBinError(4, 53)
 h_data.SetBinContent(5, 1722)
 h_data.SetBinError(5, 91)
 h_data.SetTitle('input distribution')
 h_new = generate_toy_MC_from_distribution(h_data)
 h_new.SetTitle('toy MC')
 fig = plt.figure(figsize=(16, 10), dpi=100, facecolor='white')
 axes = plt.axes([0.15, 0.15, 0.8, 0.8])
 axes.xaxis.set_minor_locator(AutoMinorLocator())
 axes.yaxis.set_minor_locator(AutoMinorLocator())
 axes.tick_params(which='major', labelsize=15, length=8)
 axes.tick_params(which='minor', length=4)
 rplt.hist(h_new, axes=axes)
 rplt.errorbar(h_data, emptybins=False, axes=axes)
 plt.xlabel('Mass', position=(1., 0.), ha='right')
 plt.ylabel('Events', position=(0., 1.), va='top')
 plt.legend(numpoints=1)
 plt.savefig('toy_MC_test.png')
 print  list( h_data.y() )
# normalize the histograms
h1 /= h1.Integral()
h2 /= h2.Integral()

# set visual attributes
h1.SetFillStyle('solid')
h1.SetFillColor('green')
h1.SetLineColor('green')

h2.SetFillStyle('solid')
h2.SetFillColor('red')
h2.SetLineColor('red')

stack = HistStack()
stack.Add(h1)
stack.Add(h2)

# plot with ROOT
h1.SetTitle('Histogram of IQ: #mu=100, #sigma=15')
stack.Draw()
h1.GetXaxis().SetTitle('Smarts')
h1.GetYaxis().SetTitle('Probability')

# plot with matplotlib
rplt.histstack(stack, alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.show()
示例#5
0
def get_fit_histogram(chi2,typ,tbin,wave1, wave2 = None, mmin = .5, mmax = 2.5, nbin = 500,component = -1, parameters = None):
	"""
	Gets a single histogram from a chi2 object
	@param chi2: Chi2 from where the histogrm is built
	@type chi2: chi2
	@param typ: type of the histogram:
		intensity: Intensity for wave1
		amp_re: Real part of wave1
		amp_im: Imag part of wave1
		amp_phase: Phase of wave1
		real: Real part of the interference of wave1 and wave2
		imag: Imag part of the interference of wave1 and wave2
		phase: Phase of the interference of wave1 and wave2
	@type param: str
	@param wave1: Number of the first wave
	@type wave1: int
	@param wave2: Number of the first wave (only for interferences, ignored otherwise)
	@type wave2: int
	@param mmin: Minimum mass for the histogram
	@type mmin: float
	@param mmax: Maximum mass for the histogram
	@type mmax: float
	@param nbin: Number of bins for the histogram
	@type nbin: int
	@param component: Number of active component, all active if component == -1 (default)
	@type component: int
	@return Specified histogram
	@rtyp Hist
	"""
	nWaves = chi2.nWaves()
	nTbin= chi2.nTbin()
	perT = chi2.nBrCpl()
	nCpl = perT*nTbin


	hist = Hist(nbin,mmin,mmax)
	if typ.startswith("all_waves"):
		if not component == -1:
			raise ValueError # Not possible with specified component
		hist = []
		for i in range(nWaves):
			histLine = []
			for j in range(nWaves):
				histLine.append(Hist(nbin,mmin,mmax))
			hist.append(histLine)

	step = (mmax - mmin)/nbin
	if not parameters:
		parameters = chi2.fullParameters()
	print '-----------------------------------------------------'
	print '-----------------------------------------------------'
	print tbin,wave1,component
	print '-----------------------------------------------------'
	print parameters[:2*nTbin*perT]
	if not component == -1:
		params_to_keep = chi2.getFuncParameters(component)
		for i in range(2*nCpl):
			if not i in params_to_keep:
				parameters[i] = 0.
	print parameters[:2*nTbin*perT]
	for i in range(nTbin):
		if not i == tbin:
			for j in range(perT):
				parameters[2*(j+i*perT)  ] = 0. # Set eveything in the wrong tbin to zero, just to be shure
				parameters[2*(j+i*perT)+1] = 0.
	print '-----------------------------------------------------'
	print parameters[:2*nTbin*perT]

	for i in range(1,nbin+1):
		m = mmin+(i-.5)*step
		amps = chi2.Amplitudes(m,tbin, parameters)

		if typ == "intensity":
			hist.SetBinContent(i,abs(amps[wave1])**2)
		elif typ == "ampl_real":
			hist.SetBinContent(i,amps[wave1].real)
		elif typ == "ampl_imag":
			hist.SetBinContent(i,amps[wave1].imag)
		elif typ == "ampl_phase":
			hist.SetBinContent(i,math.atan2(amps[wave1].imag,amps[wave1].real)*180./math.pi)
		elif typ.startswith("all_waves"):
			for k in range(nWaves):
				for l in range(nWaves):
					interference = amps[k]*amps[l].conjugate()
					if typ.endswith("real"):
						hist[k][l].SetBinContent(i,interference.real)
					if typ.endswith("imag"):
						hist[k][l].SetBinContent(i,interference.imag)
					if typ.endswith("phase"):
						hist[k][l].SetBinConetnt(i,math.atan2(interference.imag,interference.real)*180./math.pi)
		else:
			interference = amps[wave1]*amps[wave2].conjugate()
			if typ =="real":
				hist.SetBinContent(i,interference.real)
			elif typ == "imag":
				hist.SetBinContent(i,interference.imag)
			elif typ == "phase":
				phase=math.atan2(interference.imag,interference.real)*180./math.pi
				hist.SetBinContent(i,phase)
	if component == -1:
		name = "mass-dependent"
	else:
		name = chi2.get_component_name(component)
	if not typ.startswith("all_waves"):
		hist.SetTitle(name)
		hist.SetName(name)	
	else:
		for i in range(nWaves):
			for j in range(nWaves):
				hist[i][j].SetTitle(name)
				hist[i][j].SetName(name)	
	return hist
示例#6
0
def makeComparisionPage(histodicts, fileNames, fileDescr, separateFiles):
    """
    Prepares a canvas comparing multiple histograms: plotting all in one pad and their ratios in the second
    """
    import rootpy
    from rootpy.plotting import Hist, Canvas, Legend
    import ROOT
    from ROOT import gPad
    log = logging.getLogger('pyroplot')
    cans = {}
    colors = [
        ROOT.kBlue, ROOT.kRed + 1, ROOT.kViolet - 1, ROOT.kOrange + 7,
        ROOT.kGreen - 7, ROOT.kOrange - 6, ROOT.kPink - 9, ROOT.kTeal - 6,
        ROOT.kBlue + 4, ROOT.kAzure + 2
    ]
    log.info("Drawing histograms ..")
    # prepare set of histograms to compare to the reference on (the first)
    # loop over the reference set of histos (sorted by key):
    for hidx, refname in enumerate(sorted(histodicts[0].keys())):
        # prepare canvas
        if separateFiles:
            log.debug("Creating new canvas with index %d." % (hidx))
            c = Canvas(600, 270)
            cans[refname] = c
            c.Divide(3, 1)
            c.cd(1)
        if not separateFiles and (hidx) % 4 == 0:
            log.debug("Creating new canvas with index %d." % (hidx / 3))
            # start a new canvas
            c = Canvas(600, 800)
            cans[refname] = c
            c.Divide(3, 4)
        # prepare histograms for drawing
        log.debug("Drawing histogram #" + str(hidx + 1) + " (" + refname +
                  ") on canvas #" + str(len(cans)))
        hists = []
        ratiohists = []
        hiter = iter(histodicts)
        # special treatment for tprofile: prepare the reference projection for the ratio
        if histodicts[0][refname].__class__.__name__ == "Profile":
            refProj = histodicts[0][refname].ProjectionX()
            refProj.SetName("reference_proj")
        for idx, h in enumerate(hiter):
            # make sure we have this histogram loaded:
            if not refname in h:
                continue
            # access the corresponding histogram of the other files at the same hidx as used for ref
            h[refname].color = colors[idx]
            h[refname].linestyle = idx
            hists.append(h[refname])
            # prepare ratio is this is not the first (i.e. reference) histogram
            if idx:
                # special treatment for TProfile:
                if h[refname].__class__.__name__ == "Profile":
                    myratio = Hist(h[refname].nbins(), h[refname].lowerbound(),
                                   h[refname].upperbound())  #dummy hist
                    myratioproj = h[refname].ProjectionX()
                    myratioproj.SetName("cmp_hist_proj" + str(idx))
                    try:
                        myratio.divide(myratioproj, refProj)
                    except rootpy.ROOTError, e:
                        log.error(
                            "Calculation of ratio for histogram %s caused ROOTError exception ('%s')"
                            % (h[refname].GetName(), e.msg))
                        break
                    myratio.color = colors[idx]
                else:
                    myratio = h[refname].clone(
                    )  # make sure that the ratio has the right type
                    try:
                        myratio.Divide(
                            h[refname],
                            histodicts[0][refname])  # divide by reference hist
                    except rootpy.ROOTError, e:
                        log.error(
                            "Calculation of ratio for histogram %s caused ROOTError exception ('%s')"
                            % (h[refname].GetName(), e.msg))
                        break
                myratio.yaxis.SetTitle("(h_{cmp} - h_{ref})/h_{ref}")
                myratio.SetTitle("ratio to reference")
                myratio.SetMaximum(2)
                myratio.SetMinimum(0)
                myratio.SetStats(0)
                ratiohists.append(myratio)