def setUp(self):
        # we only test symmetric bins for now
        self.n_bins_x = 6
        self.n_bins_y = 6
        # only entries in diagonals, p = 1, s = 1 for all bins
        self.best_case = Hist2D(self.n_bins_x, -3, 3, self.n_bins_y, 0, 6)
        for i in range(1, self.n_bins_x + 1):
            self.best_case.SetBinContent(i, i, random() * 1000)

        # random eclipse
        self.random_elipse = Hist2D(self.n_bins_x, -3, 3, self.n_bins_y, 0, 6)
        self.random_elipse.fill_array(
            np.random.multivariate_normal(mean=(0, 3),
                                          cov=[[1., 1.12], [1.12, 2.25]],
                                          size=(1000)))

        # this creates
        # [4, 0, 0, 0, 0, 1],
        # [0, 0, 0, 0, 1, 0],
        # [0, 0, 0, 1, 0, 0],
        # [0, 0, 1, 0, 0, 0],
        # [0, 1, 0, 0, 0, 0],
        # [1, 0, 0, 0, 0, 3],
        # this should result in a purity and stability value of 1 for all bins
        # except the first and last. The first bin should have p = 1/5 and
        # s = 1/4 and the last bin should have p = 1/4 and s = 1/5

        self.pre_calculated = Hist2D(self.n_bins_x, -3, 3, self.n_bins_y, 0, 6)
        for i in range(1, self.n_bins_x + 1):
            self.pre_calculated.SetBinContent(i, i, 1)
        self.pre_calculated.SetBinContent(1, self.n_bins_y, 4)
        self.pre_calculated.SetBinContent(self.n_bins_x, 1, 3)
 def setUp( self ):
     # create histograms
     self.h1 = Hist( 100, 0, 100, title = '1D' )
     self.h2 = Hist2D( 60, 40, 100, 60, 40, 100 )
     self.simple = Hist( 100, 0, 100, title = '1D' )
 
     # fill the histograms with our distributions
     map( self.h1.Fill, x1 )
     self.h2.fill_array( np.random.multivariate_normal( 
                                 mean = ( 50, 50 ),
                                 cov = np.arange( 4 ).reshape( 2, 2 ),
                                 size = ( int( 1E6 ), ) ) 
                     )
     self.bins = [40, 45, 50, 60, 65, 70, 75, 80, 100]
     # rebin them
     self.h2_rebinned = self.h2.rebinned( self.bins, axis = 0 )
     self.h2_rebinned = self.h2_rebinned.rebinned( self.bins, axis = 1 )
     self.h2_rebinned_2 = rebin_2d( self.h2, self.bins, self.bins )
     
     # we only test symmetric bins for now
     self.n_bins_x = 5
     self.n_bins_y = 5
     # only entries in diagonals, p = 1, s = 1 for all bins
     self.diagonals = Hist2D( self.n_bins_x, 0, 10, self.n_bins_y, 0, 10 )
     # this creates
     # [0, 0, 0, 0, 1],
     # [0, 0, 0, 1, 0],
     # [0, 0, 1, 0, 0],
     # [0, 1, 0, 0, 0],
     # [1, 0, 0, 0, 0]
     for i in range( 1, self.n_bins_x + 1 ):
         self.diagonals.SetBinContent( i, i, 1 )
     
     # the following should result in
     # [0, 0, 2],
     # [0, 2, 0],
     # [1, 0, 0]    
     self.bin_edges_nice = [0, 2, 6, 10]
     self.result_nice = [1, 2, 2]
     
     # the following should result in
     # [0, 0, 0, 2],
     # [0, 0, 2, 0]
     # [0, 1, 0, 0]
     # [0, 0, 0, 0]  
     self.bin_edges_out_of_bound = [-2, 0, 2, 6, 20]
     self.result_out_of_bound = [0, 1, 2, 2]
     # the following should result in
     # [0, 0, 2],
     # [0, 1, 0],
     # [2, 0, 0] 
     self.bin_edges_not_on_boundaries = [0, 3.5, 6, 20]
     self.result_not_on_boundaries = [2, 1, 2]
     
     for i in range(100):
         self.simple.Fill(i, 1)
示例#3
0
def test_power():
    h = Hist2D(10, 0, 1, 10, 0, 1)
    h.FillRandom(F2('x+y'))
    p = h.Clone()
    p /= h.Integral()
    pow(h, 2)
    h**2
    h**p
    assert_raises(ValueError, pow, h, Hist2D(20, 0, 1, 10, 0, 1))
    assert_raises(TypeError, pow, h, Hist(10, 0, 1))
    h **= 2
示例#4
0
def test_init():
    # constructor arguments are repetitions of #bins, left bound, right bound.
    h2d = Hist2D(10, 0, 1, 50, -40, 10, name='2d hist')
    h3d = Hist3D(3, -1, 4, 10, -1000, -200, 2, 0, 1, name='3d hist')

    # variable-width bins may be created by passing the bin edges directly:
    h1d_variable = Hist([1, 4, 10, 100])
    h2d_variable = Hist2D([2, 4, 7, 100, 200], [-100, -50, 0, 10, 20])
    h3d_variable = Hist3D([1, 3, 10], [20, 50, 100], [-10, -5, 10, 20])

    # variable-width and constant-width bins can be mixed:
    h2d_mixed = Hist2D([2, 10, 30], 10, 1, 5)
示例#5
0
def double_slope_relaxation_vs_pt(optimal_points_vs_ieta_low,
                                  optimal_points_vs_ieta_high,
                                  threshold_low,
                                  threshold_high,
                                  eff_min=0.4,
                                  max_et=110):
    points_vs_ieta_pt = Hist2D(
        np.array(optimal_points_vs_ieta_low.GetXaxis().GetXbins()), 200, 0.5,
        200.5)
    for bx in points_vs_ieta_pt.bins_range(0):
        eff_ref_low = optimal_points_vs_ieta_low[bx].value
        eff_ref_high = optimal_points_vs_ieta_high[bx].value
        for by in points_vs_ieta_pt.bins_range(1):
            et = points_vs_ieta_pt.GetYaxis().GetBinCenter(by)
            eff_high = (1. - eff_ref_high) / (max_et - threshold_high) * (
                et - threshold_high) + eff_ref_high
            eff_low = (eff_ref_high - eff_ref_low) / (
                threshold_high - threshold_low) * (et -
                                                   threshold_low) + eff_ref_low
            eff = eff_high
            if et < threshold_high:
                eff = eff_low
            eff = max(eff_min, min(1, eff))
            points_vs_ieta_pt[bx, by].value = eff
    return points_vs_ieta_pt
    def reweight_histogram_as_oliver(self, input_file, output_file):
        """
        This function will apply the same weightning procedure as described in Oliver thesis.
        :param input_file:
        :param output_file:
        :return:
        """
        input_file = os.path.join(self.input_directory, input_file)
        output_file = os.path.join(self.input_directory, output_file)

        f = r.TFile.Open(input_file, 'read')
        intuple = f.Get('pythia8-Geant4')
        out = r.TFile.Open(output_file, 'recreate')
        outtuple = intuple.CloneTree(0)
        h = Hist2D(100, 0, 350, 100, 0, 6)
        for muon in intuple:
            px = muon.px
            py = muon.py
            pz = muon.pz
            p = np.sqrt(px**2 + py**2 + pz**2)
            pt = np.sqrt(px**2 + py**2)
            b = int(p / 350. * 100) + 1, int(pt / 6. * 100) + 1
            if h[b].value < 100:
                h.Fill(p, pt)
                a = array('f', [y for x in muon.values() for y in x])
                outtuple.Fill(a)
        outtuple.Write()
        del outtuple
        intuple = out.Get('pythia8-Geant4')
        for muon in intuple:
            px = muon.px
            py = muon.py
            pz = muon.pz
            p = np.sqrt(px**2 + py**2 + pz**2)
            pt = np.sqrt(px**2 + py**2)
            b = int(p / 350. * 100) + 1, int(pt / 6. * 100) + 1
            a = array('f', [y for x in muon.values() for y in x])
            if h[b].value < 10:
                n = int(10 / h[b].value)
                for _ in range(n):
                    phi = r.gRandom.Uniform(0., 2.) * r.TMath.Pi()
                    px = pt * r.TMath.Cos(phi)
                    py = pt * r.TMath.Sin(phi)
                    a[1] = px
                    a[2] = py
                    intuple.Fill(a)
            a[1] = +pt
            a[2] = 0
            intuple.Fill(a)
            a[1] = -pt
            a[2] = 0
            intuple.Fill(a)
        # intuple.Write()
        # intuple.create_branches({'seed': 'F'})
        # for muon in intuple:
        #     # print muon.keys()
        #     a = array('f', [y for x in muon.values() for y in x])
        #     muon.seed = hash(sum(a))
        #     intuple.Fill()
        intuple.Write()
示例#7
0
def add_problematic(intuple, n=2000):
    # TODO why aren't these saved?
    h_added_problematic = Hist2D(100,
                                 0,
                                 maxp,
                                 100,
                                 0,
                                 maxpt,
                                 name='added_problematic')
    pt = 2.5
    for _ in range(n):
        p = r.gRandom.Uniform(150., maxp)
        pz = np.sqrt(p**2 - pt**2)
        phi = r.gRandom.Uniform(0., 2.) * r.TMath.Pi()
        px = pt * r.TMath.Cos(phi)
        py = pt * r.TMath.Sin(phi)
        intuple.Fill(
            array('f', [
                13., px, py, pz, 0, 0, -49.79, px, py, pz, 0, 0, -49.79, 0, 0,
                1, 0
            ]))
        intuple.Fill(
            array('f', [
                13., +pt, 0, pz, 0, 0, -49.79, +pt, 0, pz, 0, 0, -49.79, 0, 0,
                1, 0
            ]))
        intuple.Fill(
            array('f', [
                13., -pt, 0, pz, 0, 0, -49.79, -pt, 0, pz, 0, 0, -49.79, 0, 0,
                1, 0
            ]))
        h_added_problematic.Fill(p, pt)
        h_added_problematic.Fill(p, pt)
        h_added_problematic.Fill(p, pt)
    return intuple, h_added_problematic
def plot(x, y, sizes=None, marksize=1, filename=None, xlabel=None, ylabel=None):
	plt.plot(x, y, 'k.', ms=marksize)
	ax = plt.gca()
	if xlabel:
		ax.set_xlabel(xlabel, fontsize=12)
		ax.xaxis.set_label_coords(0.92,-0.06)
	if ylabel:
		ax.set_ylabel(ylabel, fontsize=12)
		ax.yaxis.set_label_coords(-0.06,0.86)
	if sizes:
		plt.axis(sizes)
	plt.tight_layout()
	if filename:
		plt.savefig(DIRECTORY + filename+".png")
		b = Hist2D(5000, sizes[0], sizes[1], 5000, sizes[2], sizes[3], name=filename, title=filename)
		b.fill_array(np.stack((x, y), axis=-1))
		b.GetXaxis().SetTitle(xlabel)
		b.GetYaxis().SetTitle(ylabel)
		with root_open(DIRECTORY +filename+".root", 'w') as f:
			b.Write()
			b.Draw()
				


	else:
		plt.show()
	plt.clf()
示例#9
0
    def plot_correlation(self):
        # Make correlations between estimators
        log.info("Correlating N_ch of each estimator")
        corr_dir = self.results_post.GetPath().split(":")[1] + '/correlations'
        try:
            self.f_out.mkdir(corr_dir, recurse=True)
        except:
            pass
        # Take ntuple from the first estimator and then add friends to this one
        nt0 = self.sums[0].FindObject("fEventTuple")
        nt0.SetAlias(self.sums[0].GetName(), "fEventTuple")

        # build ntuple
        for est_dir in self.sums[1:]:
            nt0.AddFriend(est_dir.FindObject("fEventTuple"), est_dir.GetName())
        for ref_est in self.considered_ests:
            for est_dir in self.sums:
                log.info("Correlating {0} with {1}".format(ref_est, est_dir.GetName()))
                corr_hist = Hist2D(400, 0, 400,
                                   400, 0, 400,
                                   name="corr_hist_{0}_vs_{1}".format(ref_est, est_dir.GetName()))
                # Lables are deliberatly swaped, see Projection below!
                corr_hist.title = ("Correlation N_{{ch}} in {0} and {1};N_{{ch}} {1};N_{{ch}} {0}"
                                   .format(ref_est, est_dir.GetName()))

                # this projects onto y:x, to make coding more adventurous
                nt0.Project(corr_hist.name, "{0}.nch:{1}.nch".format(ref_est, est_dir.GetName()),
                            "ev_weight")
                corr_hist.drawstyle = 'colz'
                self.f_out.cd(corr_dir)
                corr_hist.write()
示例#10
0
def test_overflow_underflow():
    h1d = Hist(10, 0, 1)
    h1d.Fill(-1)
    h1d.Fill(2)
    assert_equal(h1d.underflow(), 1)
    assert_equal(h1d.overflow(), 1)

    h2d = Hist2D(10, 0, 1, 10, 0, 1)
    h2d.Fill(-1, .5)
    h2d.Fill(2, .5)
    assert_equal(h2d.underflow()[h2d.axis(1).FindBin(.5)], 1)
    assert_equal(h2d.overflow()[h2d.axis(1).FindBin(.5)], 1)
    h2d.Fill(.5, -1)
    h2d.Fill(.5, 2)
    assert_equal(h2d.underflow(axis=1)[h2d.axis(0).FindBin(.5)], 1)
    assert_equal(h2d.overflow(axis=1)[h2d.axis(0).FindBin(.5)], 1)

    h3d = Hist3D(10, 0, 1, 10, 0, 1, 10, 0, 1)
    h3d.Fill(-1, .5, .5)
    h3d.Fill(2, .5, .5)
    assert_equal(h3d.underflow()[h3d.axis(1).FindBin(.5)][h3d.axis(2).FindBin(.5)], 1)
    assert_equal(h3d.overflow()[h3d.axis(1).FindBin(.5)][h3d.axis(2).FindBin(.5)], 1)
    h3d.Fill(.5, -1, .5)
    h3d.Fill(.5, 2, .5)
    assert_equal(h3d.underflow(axis=1)[h3d.axis(0).FindBin(.5)][h3d.axis(2).FindBin(.5)], 1)
    assert_equal(h3d.overflow(axis=1)[h3d.axis(0).FindBin(.5)][h3d.axis(2).FindBin(.5)], 1)
    h3d.Fill(.5, .5, -1)
    h3d.Fill(.5, .5, 2)
    assert_equal(h3d.underflow(axis=2)[h3d.axis(0).FindBin(.5)][h3d.axis(1).FindBin(.5)], 1)
    assert_equal(h3d.overflow(axis=2)[h3d.axis(0).FindBin(.5)][h3d.axis(1).FindBin(.5)], 1)
示例#11
0
    def th2(self,
            name_,
            xvalues,
            yvalues,
            bins,
            title="",
            xlabel="",
            ylabel="",
            cut=None,
            color=None,
            linecolor=None,
            markercolor=None,
            fillcolor=None,
            linewidth=None,
            linestyle=None,
            markersize=None,
            markerstyle=None,
            fillstyle=None):
        '''
            template type of function for TH2D, including all the overloaded
            construction function
        '''
        ## Create an unique name to prevent memory leak in ROOT
        if cut is not None:
            name = self.folderName + "_" + name_ + "___" + cut
            if cut not in self.cuts:
                self.cuts.add(cut)
        else:
            name = self.folderName + "_" + name_
        if name not in self.hist.keys():
            newtitle = title + ";" + xlabel + ";" + ylabel
            self.hist[name] = Hist2D(*bins, name=name, title=newtitle)
            self.setHistStyle(name, color, linecolor, markercolor, fillcolor,
                              linewidth, linestyle, markersize, markerstyle,
                              fillstyle)

        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fill Th2 ~~~~~
        x = None
        y = None
        if xvalues is None:
            pass
        elif isinstance(xvalues, awkward.JaggedArray):
            x = xvalues.flatten()
        elif isinstance(xvalues, np.ndarray):
            x = xvalues
        else:
            x = [xvalues]

        if yvalues is None:
            pass
        elif isinstance(yvalues, awkward.JaggedArray):
            y = yvalues.flatten()
        elif isinstance(yvalues, np.ndarray):
            y = yvalues
        else:
            y = [yvalues]
        self.hist[name].fill_array(np.vstack((x, y)).T)

        return self.hist[name]
示例#12
0
def test_draw():

    with root_open(FILE_PATHS[0]) as f:
        tree = f.tree

        tree.draw('a_x')
        tree.draw('a_x:a_y')
        tree.draw('a_x:TMath::Exp(a_y)')
        tree.draw('a_x:a_y:a_z')
        tree.draw('a_x:a_y:a_z:b_x')
        tree.draw('a_x:a_y:a_z:b_x:b_y', options='para')

        h1 = Hist(10, -1, 2, name='h1')
        h2 = Hist2D(10, -1, 2, 10, -1, 2)
        h3 = Hist3D(10, -1, 2, 10, -1, 2, 10, -1, 2)

        # dimensionality does not match
        assert_raises(TypeError, tree.draw, 'a_x:a_y', hist=h1)

        # name does not match
        assert_raises(ValueError, tree.draw, 'a_x>>+something', hist=h1)

        # hist is not a TH1
        assert_raises(TypeError, tree.draw, 'a_x:a_y', hist=ROOT.TGraph())

        # name does match and is fine (just redundant)
        tree.draw('a_x>>h1', hist=h1)
        assert_equal(h1.Integral() > 0, True)
        h1.Reset()
        tree.draw('a_x>>+h1', hist=h1)
        assert_equal(h1.Integral() > 0, True)
        h1.Reset()

        # both binning and hist are specified
        assert_raises(ValueError, tree.draw, 'a_x>>+h1(10, 0, 1)', hist=h1)

        tree.draw('a_x', hist=h1)
        assert_equal(h1.Integral() > 0, True)
        tree.draw('a_x:a_y', hist=h2)
        assert_equal(h2.Integral() > 0, True)
        tree.draw('a_x:a_y:a_z', hist=h3)
        assert_equal(h3.Integral() > 0, True)

        h3.Reset()
        tree.draw('a_x>0:a_y/2:a_z*2', hist=h3)
        assert_equal(h3.Integral() > 0, True)

        # create a histogram
        hist = tree.draw('a_x:a_y:a_z', create_hist=True)
        assert_equal(hist.Integral() > 0, True)

        hist = tree.draw('a_x:a_y:a_z>>new_hist_1')
        assert_equal(hist.Integral() > 0, True)
        assert_equal(hist.name, 'new_hist_1')

        # create_hist=True is redundant here
        hist = tree.draw('a_x:a_y:a_z>>new_hist_2', create_hist=True)
        assert_equal(hist.Integral() > 0, True)
        assert_equal(hist.name, 'new_hist_2')
示例#13
0
def draw_axes(params):
    '''Draw axes of the plot'''
    dummy_histo = Hist2D(1, params.xmin, params.xmax, 1, params.ymin,
                         params.ymax)
    dummy_histo.xaxis.SetTitle(params.xtitle)
    dummy_histo.yaxis.SetTitle(params.ytitle)
    dummy_histo.Draw()
    return dummy_histo
示例#14
0
def test_ravel():
    hist = Hist2D(3, 0, 1, 4, 0, 1)
    for i, bin in enumerate(hist.bins()):
        bin.value = i
        bin.error = i
    rhist = hist.ravel()
    assert_equal(list(rhist.y()), range(12))
    assert_equal(list(rhist.yerrh()), range(12))
def data_covariance_matrix(data):
    values = list(data)
    get_bin_error = data.GetBinError
    cov_matrix = Hist2D(len(values), -10, 10, len(values), -10, 10, type='D')
    for bin_i in range(len(values)):
        error = get_bin_error(bin_i + 1)
        cov_matrix.SetBinContent(bin_i + 1, bin_i + 1, error * error)
    return cov_matrix
示例#16
0
def test_contour():
    from rootpy.plotting import root2matplotlib as rplt
    import numpy as np
    a = Hist2D(100, -3, 3, 100, 0, 6)
    a.fill_array(
        np.random.multivariate_normal(mean=(0, 3),
                                      cov=np.arange(4).reshape(2, 2),
                                      size=(1000, )))
    rplt.contour(a)
示例#17
0
def test_contour():
    from rootpy.plotting import root2matplotlib as rplt
    import numpy as np
    a = Hist2D(100, -3, 3, 100, 0, 6)
    a.fill_array(
        np.random.multivariate_normal(mean=(0, 3),
                                      cov=[[1, .5], [.5, 1]],
                                      size=(1000, )))
    rplt.contour(a)
    def setUp( self ):
    	# create histograms
        # self.h1 = Hist2D( 15, 0, 15, 15, 0, 15 )
        # x_1 = [1, 3, 7, 7, 8, 1, 12, 7, 8, 6]
        # y_1 = [1, 7, 3, 7, 8, 12, 7, 12, 13, 11]
        self.h1 = Hist2D( 60, 40, 100, 60, 40, 100 )
        n_1 = 100000
        x_1 = 60 + 10 * np.random.randn( n_1 )
        y_1 = x_1 + np.random.randn( n_1 )
        z_1 = np.vstack( ( x_1, y_1 ) ).T
        self.h1.fill_array( z_1 )

        self.h1 = fix_overflow( self.h1 )

        self.histogram_information = [
                {'hist': self.h1,
                 'CoM': 7,
                 'channel':'test_1'},
                ]

        self.histograms = [info['hist'] for info in self.histogram_information]
        
        # requirements for new binning
        self.p_min, self.s_min, self.n_min = 0.5, 0.5, 1000

        self.bin_edges = []
        self.purities_GetBinContent = []
        self.stabilities_GetBinContent = []
        self.n_events_GetBinContent = []

        self.purities_Integral = []
        self.stabilities_Integral = []
        self.n_events_Integral = []

        first_hist = self.histograms[0]
        n_bins = first_hist.GetNbinsX()

        current_bin_start = 0
        current_bin_end = 0

        while current_bin_end < n_bins:
            current_bin_end, p, s, n_gen_and_reco = pick_bins.get_next_end( self.histograms, current_bin_start, current_bin_end, self.p_min, self.s_min, self.n_min )
            if not self.bin_edges:
                # if empty
                self.bin_edges.append( first_hist.GetXaxis().GetBinLowEdge( current_bin_start + 1 ) )
            self.bin_edges.append( first_hist.GetXaxis().GetBinLowEdge( current_bin_end ) + first_hist.GetXaxis().GetBinWidth( current_bin_end ) )
            self.purities_Integral.append(p)
            self.stabilities_Integral.append(s)
            self.n_events_Integral.append(n_gen_and_reco)
            current_bin_start = current_bin_end

        self.h1_rebinned = rebin_2d(self.h1, self.bin_edges, self.bin_edges)

        self.purities_GetBinContent = calculate_purities( self.h1_rebinned )
        self.stabilities_GetBinContent = calculate_stabilities( self.h1_rebinned )
        self.n_events_GetBinContent = [int( self.h1_rebinned.GetBinContent( i, i ) ) for i in range( 1, len( self.bin_edges ) )]
示例#19
0
def cap_bins(intuple, binmax=100):
    outtuple = intuple.CloneTree(0)
    h_all = Hist2D(100, 0, maxp, 100, 0, maxpt, name='all')
    h = Hist2D(100, 0, maxp, 100, 0, maxpt, name='cap')
    for muon in intuple:
        px = muon.opx
        py = muon.opy
        pz = muon.opz
        p = np.sqrt(px**2 + py**2 + pz**2)
        pt = np.sqrt(px**2 + py**2)
        assert p < maxp
        assert pt < maxpt
        b = int(p / maxp * 100) + 1, int(pt / maxpt * 100) + 1
        h_all.Fill(p, pt)
        if h[b].value < binmax:
            h.Fill(p, pt)
            a = array('f', [y for x in muon.values() for y in x])
            outtuple.Fill(a)
    return outtuple, h, h_all
示例#20
0
def test_bounds():
    h = Hist(10, 0, 1)
    assert_equal(h.bounds(), (0, 1))
    h = Hist2D(10, 0, 1, 10, 1, 2)
    assert_equal(h.bounds(axis=0), (0, 1))
    assert_equal(h.bounds(axis=1), (1, 2))
    h = Hist3D(10, 0, 1, 10, 1, 2, 10, 2, 3)
    assert_equal(h.bounds(axis=0), (0, 1))
    assert_equal(h.bounds(axis=1), (1, 2))
    assert_equal(h.bounds(axis=2), (2, 3))
示例#21
0
def test_quantiles():
    h3d = Hist3D(10, 0, 1, 10, 0, 1, 10, 0, 1)
    h3d.FillRandom('gaus')
    h3d.quantiles(2)
    h3d.quantiles(2, axis=1)
    h3d.quantiles([0, .5, 1], axis=2)

    h2d = Hist2D(100, 0, 1, 100, 0, 1)
    h2d.FillRandom(F2('x+y'))
    h2d.quantiles(4, axis=0)
    h2d.quantiles(4, axis=1)
示例#22
0
def test_compatibility():
    a = Hist(10, 0, 1)
    b = Hist(10, 0, 1)
    c = Hist(10, 1, 2)
    d = Hist2D(10, 0, 1, 10, 0, 1)

    assert_true(a.compatible(a))
    assert_true(a.compatible(b))
    assert_true(a.compatible(c))
    assert_false(a.compatible(c, check_edges=True))
    assert_false(a.compatible(d))
示例#23
0
def test_hist2d():
    from rootpy.plotting import root2matplotlib as rplt
    from matplotlib import pyplot
    import numpy as np
    if not hasattr(pyplot, 'hist2d'):
        raise SkipTest("matplotlib is too old")
    a = Hist2D(100, -3, 3, 100, 0, 6)
    a.fill_array(
        np.random.multivariate_normal(mean=(0, 3),
                                      cov=[[1, .5], [.5, 1]],
                                      size=(1000, )))
    rplt.hist2d(a)
示例#24
0
def make2DHist(h, **kwargs):
    if "xbins" in kwargs and "ybins" in kwargs:
        h2 = Hist2D(kwargs.get("xbins"), kwargs.get("ybins"))
    else:
        return
    nx = h.GetNbinsX()
    ny = h.GetNbinsY()
    for iy in range(ny):
        for ix in range(nx):
            ib = h.GetBin(ix, iy)
            h2.SetBinContent(ib, h.GetBinContent(ib))
    return h2
示例#25
0
def plot_hist2d(xvar_np,
                yvar_np,
                x_label,
                y_label,
                hist_bins,
                outputfile,
                logScale=False,
                isMC=False):
    hist = Hist2D(hist_bins['nbinx'],
                  hist_bins['xmin'],
                  hist_bins['xmax'],
                  hist_bins['nbiny'],
                  hist_bins['ymin'],
                  hist_bins['ymax'],
                  title='',
                  type='F')
    fill_hist(
        hist,
        np.vstack(
            (xvar_np[np.isfinite(xvar_np)], yvar_np[np.isfinite(yvar_np)])).T)

    ROOT.gStyle.SetPalette(ROOT.kDarkBodyRadiator)
    c = ROOT.TCanvas('c1', 'c1', 800, 600)
    pad = setup_pad()
    pad.SetLeftMargin(0.08)
    pad.SetRightMargin(0.11)
    pad.Draw()
    pad.cd()

    hist.SetContour(100)
    hist.GetYaxis().SetTitle(y_label)
    hist.GetXaxis().SetTitle(x_label)
    hist.SetTitleFont(42)
    hist.SetTitleSize(0.05)
    hist.GetYaxis().SetTitleOffset(0.9)
    hist.GetYaxis().SetTitleFont(42)
    hist.GetYaxis().SetTitleSize(0.04)
    hist.GetYaxis().SetLabelSize(0.04)
    hist.GetYaxis().SetLabelFont(42)
    hist.GetXaxis().SetTitleOffset(0.9)
    hist.GetXaxis().SetTitleFont(42)
    hist.GetXaxis().SetTitleSize(0.04)
    hist.GetXaxis().SetLabelSize(0.04)
    hist.GetXaxis().SetLabelFont(42)
    if logScale: ROOT.gPad.SetLogz(1)
    hist.Draw("colz")

    pad.cd()
    CMS_lumi(isMC)
    c.cd()
    c.Update()
    c.SaveAs(outputfile)
    c.Close()
示例#26
0
    def setUp(self):

        # create histograms
        self.h1 = Hist(60, 40, 100, title='1D')
        self.h2 = Hist2D(60, 40, 100, 100, 40, 140)

        # fill the histograms with our distributions
        map(self.h1.Fill, x1)
        self.h2.fill_array(
            np.random.multivariate_normal(mean=(100, 140),
                                          cov=np.arange(4).reshape(2, 2),
                                          size=(int(1E6), )))
示例#27
0
def test_efficiency():
    # 1D
    eff = Efficiency(Hist(10, 0, 1), Hist(10, 0, 1))
    eff.Fill(False, 0.1)
    eff.Fill(True, 0.8)
    assert_equal(len(eff), len(eff.total))
    if ROOT_VERSION >= ROOTVersion(53417):
        assert eff.graph
    assert eff.painted_graph
    assert_equal(len(list(eff.efficiencies())), 10)
    assert_equal(len(list(eff.efficiencies(overflow=True))), 12)
    assert_equal(len(list(eff.errors())), 10)
    assert_equal(len(list(eff.errors(overflow=True))), 12)
    # 2D
    eff = Efficiency(Hist2D(10, 0, 1, 10, 0, 1), Hist2D(10, 0, 1, 10, 0, 1))
    eff.Fill(False, 0.1)
    eff.Fill(True, 0.8)
    assert_equal(len(eff), len(eff.total))
    if ROOT_VERSION >= ROOTVersion(53417):
        assert eff.histogram
    assert eff.painted_histogram
示例#28
0
    def __init__(self, name, files):
        self.hists = {
            'pfPtRes' : Hist(41,-.3,.3),
            'tunePPtRes' : Hist(41,-.3,.3),
            'resCompare' : Hist(31,-.2,.2),
            'pfPtResUncor' : Hist(41,-.3,.3),
            'tunePPtResUncor' : Hist(41,-.3,.3),
            'resCompareUncor' : Hist(31,-.2,.2),
            'resCompareBothCor' : Hist(31,-.2,.2),
            }
        self.hists2D = {
            'pfPtResVsPt' : Hist2D(43,140.,1000.,41,-.15,.15),
            'tunePPtResVsPt' : Hist2D(43,140.,1000.,41,-.15,.15),
            'resCompareVsPt' : Hist2D(43,140.,1000.,21,-.1,.1),
            }

        if isinstance(files, str):
            self.files = files.split(',')
        else:
            self.files = files

        self.name = name
示例#29
0
 def getHistFromTree2d(self,
                       xbins,
                       xmin,
                       xmax,
                       xtitle,
                       ybins,
                       ymin,
                       ymax,
                       ytitle,
                       cut,
                       value,
                       tree,
                       weight=None):
     from rootpy.plotting import Hist, Hist2D
     self.clearHists()
     for f in self.files:
         try:
             _tree = self.files[f].Get(tree)
         except AttributeError as e:
             log_plotlib.warning("No %s in %s" % (tree, f))
             log_plotlib.warning(
                 "Will try without %s, and add an empty hist." % f)
             log_plotlib.warning(e)
             self.hists[f] = Hist(binns, xmin, xmax)
             continue
             #TH2F(const char* name, const char* title, Int_t nbinsx, const Float_t* xbins, Int_t nbinsy, const Float_t* ybins)
             #TH2F(const char* name, const char* title, Int_t nbinsx, Double_t xlow, Double_t xup, Int_t nbinsy, Double_t ylow, Double_t yup)
         self.hists[f] = Hist2D(xbins, xmin, xmax, ybins, ymin, ymax)
         self.hists[f].GetXaxis().SetTitle(xtitle)
         self.hists[f].GetXaxis().SetTitle(ytitle)
         try:
             #if weight is None:
             _tree.Draw(value, selection=cut, hist=self.hists[f])
         #else:
         #tmpFile=File("tmp.root", "recreate")
         #sel_tree=_tree.copy_tree(selection=cut)
         #print weight
         #sel_tree.Draw(value,selection=weight,hist=self.hists[f])
         except:
             log_plotlib.info("Perhaps try this one:")
             for i in _tree.glob("*"):
                 log_plotlib.info(i)
             raise RuntimeError("Will stop here!")
         self.hists[f].Scale(self._getWeight(f))
         self.hists[f].Sumw2()
     if self._joinList is not False:
         self.joinList(self._joinList)
     for hist in self.hists:
         if hist in self.style:
             self.hists[hist].decorate(**self.style[hist])
示例#30
0
def fill_up_bins(intuple, h, binmin=10):
    h_added_random = Hist2D(100, 0, maxp, 100, 0, maxpt, name='added_random')
    h_added_mirror = Hist2D(100, 0, maxp, 100, 0, maxpt, name='added_mirror')
    for muon in intuple:
        px = muon.opx
        py = muon.opy
        pz = muon.opz
        p = np.sqrt(px**2 + py**2 + pz**2)
        pt = np.sqrt(px**2 + py**2)
        b = int(p / maxp * 100) + 1, int(pt / maxpt * 100) + 1
        a = array('f', [y for x in muon.values() for y in x])
        if h[b].value < binmin:
            n = int(binmin / h[b].value)
            for _ in range(n):
                phi = r.gRandom.Uniform(0., 2.) * r.TMath.Pi()
                px = pt * r.TMath.Cos(phi)
                py = pt * r.TMath.Sin(phi)
                a[1] = px
                a[2] = py
                a[7] = px
                a[8] = py
                h_added_random.Fill(p, pt)
                intuple.Fill(a)
        a[1] = +pt
        a[2] = 0
        a[7] = +pt
        a[8] = 0
        intuple.Fill(a)
        h_added_mirror.Fill(p, pt)
        a[1] = -pt
        a[2] = 0
        a[7] = +pt
        a[8] = 0
        intuple.Fill(a)
        h_added_mirror.Fill(p, pt)
    return intuple, h_added_random, h_added_mirror