示例#1
0
def bookHist(h,
             key=None,
             title='',
             nbinsx=100,
             xmin=0,
             xmax=1,
             nbinsy=0,
             ymin=0,
             ymax=1,
             nbinsz=0,
             zmin=0,
             zmax=1):
    if key == None:
        print('missing key')
        return
    rkey = str(
        key)  # in case somebody wants to use integers, or floats as keys
    if key in h: h[key].Reset()
    elif nbinsz > 0:
        h[key] = TH3D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax,
                      nbinsz, zmin, zmax)
    elif nbinsy > 0:
        h[key] = TH2D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax)
    else:
        h[key] = TH1D(rkey, title, nbinsx, xmin, xmax)
    h[key].SetDirectory(gROOT)
示例#2
0
def bookHist(h,
             key=None,
             title='',
             nbinsx=100,
             xmin=0,
             xmax=0,
             nbinsy=0,
             ymin=0,
             ymax=0,
             nbinsz=0,
             zmin=0,
             zmax=0):
    if key == None:
        print 'missing key'
        return
    rkey = str(
        key)  # in case somebody wants to use integers, or floats as keys
    if h.has_key(key): h[key].Reset()
    elif hasattr(nbinsx, 'itemsize'):
        if xmin == 0:
            h[key] = TH1D(rkey, title, len(nbinsx) - 1, nbinsx)
        else:
            h[key] = TH2D(rkey, title,
                          len(nbinsx) - 1, nbinsx, xmin, xmax, nbinsy)
    elif nbinsz > 0:
        h[key] = TH3D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax,
                      nbinsz, zmin, zmax)
    elif nbinsy > 0:
        h[key] = TH2D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax)
    else:
        h[key] = TH1D(rkey, title, nbinsx, xmin, xmax)
    h[key].SetDirectory(gROOT)
示例#3
0
def prepare_TH3D(name, xbin, xmin, xmax, ybin, ymin, ymax, zbin, zmin, zmax):

    #bins along x, y and z
    nx, xmax = get_nbins(xbin, xmin, xmax)
    ny, ymax = get_nbins(ybin, ymin, ymax)
    nz, zmax = get_nbins(zbin, zmin, zmax)

    hx = TH3D(name, name, nx, xmin, xmax, ny, ymin, ymax, nz, zmin, zmax)

    return hx
示例#4
0
文件: test.py 项目: cdeil/root_numpy
    def test_fill_array(self):
        a = TH1D('th1d', 'test', 1000, -5, 5)
        fill_array(a, np.random.randn(1E6))
        assert (a.Integral() > 0)

        b = TH2D('th2d', 'test', 100, -5, 5, 100, -5, 5)
        fill_array(b, np.random.randn(1E6, 2))
        assert (b.Integral() > 0)

        c = TH3D('th3d', 'test', 10, -5, 5, 10, -5, 5, 10, -5, 5)
        fill_array(c, np.random.randn(1E4, 3))
        assert (c.Integral() > 0)
示例#5
0
def test_random_sample():
    funcs = [
        TF1("f1", "TMath::DiLog(x)"),
        TF2("f2", "sin(x)*sin(y)/(x*y)"),
        TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)"),
    ]
    hists = [
        TH1D("h1", "h1", 10, -3, 3),
        TH2D("h2", "h2", 10, -3, 3, 10, -3, 3),
        TH3D("h3", "h3", 10, -3, 3, 10, -3, 3, 10, -3, 3),
    ]
    for i, hist in enumerate(hists):
        hist.FillRandom(funcs[i].GetName())
    for obj in funcs + hists:
        yield check_random_sample, obj
示例#6
0
def make_hist(name, mins=0, maxs=100, titles=None, bins=None, dim=1, des=None):
    """
    Make a named ROOT histogram. 
    
    Mins, maxs and bins can be supplied either as a single number to be 
    used for all axis, an indexable object (indexes: 0,1,2). If not supplied
    the defaults of 0, 100 and min-max (of that axis) will be used.
    
    If not supplied the number of bins per axis will be the difference 
    between the minimum and maximum (or 10 if the difference is less than 1)
    
    Titles will be set if supplied and are assumed be in the order (x,y,z)
    """
    dim = int(dim)
    if dim not in (1, 2, 3):
        raise ROOTException("dim must between 1 & 3")

    description = des if des else name

    # make the argument list
    args = [
        name,
        description,
    ]
    for d in range(dim):
        t_min = mins if not hasattr(mins, '__len__') else mins[d]
        t_max = maxs if not hasattr(maxs, '__len__') else maxs[d]
        if hasattr(bins, '__len__'):
            t_bin = bins[d]
        elif bins:
            t_bin = bins
        else:
            t_bin = int(t_max - t_min) if int(t_max - t_min) > 1 else 1
        if (t_min > t_max): raise ROOTException("min > max!")
        args += [t_bin, t_min, t_max]

    if dim == 1:
        res = TH1D(*args)
    elif dim == 2:
        res = TH2D(*args)
    elif dim == 3:
        res = TH3D(*args)
    # Checking titles exists stops len raising an error if it doesn't
    if titles and len(titles) >= 1: res.GetXaxis().SetTitle(titles[0])
    if titles and len(titles) >= 2: res.GetYaxis().SetTitle(titles[1])
    if titles and len(titles) >= 3: res.GetZaxis().SetTitle(titles[2])

    return res
示例#7
0
def test_fill_hist():
    np.random.seed(0)
    data1D = np.random.randn(1E6)
    w1D = np.empty(1E6)
    w1D.fill(2.)
    data2D = np.random.randn(1E6, 2)
    data3D = np.random.randn(1E4, 3)

    a = TH1D('th1d', 'test', 1000, -5, 5)
    rnp.fill_hist(a, data1D)
    # one element lies beyond hist range; that's why it's not 1e6
    assert_almost_equal(a.Integral(), 999999.0)

    a_w = TH1D('th1dw', 'test', 1000, -5, 5)
    rnp.fill_hist(a_w, data1D, w1D)
    assert_almost_equal(a_w.Integral(), 999999.0 * 2)

    b = TH2D('th2d', 'test', 100, -5, 5, 100, -5, 5)
    rnp.fill_hist(b, data2D)
    assert_almost_equal(b.Integral(), 999999.0)

    c = TH3D('th3d', 'test', 10, -5, 5, 10, -5, 5, 10, -5, 5)
    rnp.fill_hist(c, data3D)
    assert_almost_equal(c.Integral(), 10000.0)

    # array and weights lengths do not match
    assert_raises(ValueError, rnp.fill_hist, c, data3D, np.ones(10))

    # weights is not 1D
    assert_raises(ValueError, rnp.fill_hist, c, data3D,
        np.ones((data3D.shape[0], 1)))

    # array not 2-d when filling 2D/3D histogram
    for h in (b, c):
        assert_raises(ValueError, rnp.fill_hist, h, np.random.randn(1E4))

    # length of second axis does not match dimensionality of histogram
    for h in (a, b, c):
        assert_raises(ValueError, rnp.fill_hist, h, np.random.randn(1E4, 4))

    # wrong type
    h = list()
    a = np.random.randn(100)
    assert_raises(TypeError, rnp.fill_hist, h, a)
示例#8
0
def test_fill_hist():
    n_samples = 1000
    data1D = RNG.randn(n_samples)
    w1D = np.empty(n_samples)
    w1D.fill(2.)
    data2D = RNG.randn(n_samples, 2)
    data3D = RNG.randn(n_samples, 3)

    a = TH1D('th1d', 'test', 100, -5, 5)
    rnp.fill_hist(a, data1D)
    assert_almost_equal(a.Integral(), n_samples)

    a_w = TH1D('th1dw', 'test', 100, -5, 5)
    rnp.fill_hist(a_w, data1D, w1D)
    assert_almost_equal(a_w.Integral(), n_samples * 2)

    b = TH2D('th2d', 'test', 100, -5, 5, 100, -5, 5)
    rnp.fill_hist(b, data2D)
    assert_almost_equal(b.Integral(), n_samples)

    c = TH3D('th3d', 'test', 10, -5, 5, 10, -5, 5, 10, -5, 5)
    rnp.fill_hist(c, data3D)
    assert_almost_equal(c.Integral(), n_samples)

    # array and weights lengths do not match
    assert_raises(ValueError, rnp.fill_hist, c, data3D, np.ones(10))

    # weights is not 1D
    assert_raises(ValueError, rnp.fill_hist, c, data3D,
                  np.ones((data3D.shape[0], 1)))

    # array not 2-d when filling 2D/3D histogram
    for h in (b, c):
        assert_raises(ValueError, rnp.fill_hist, h, RNG.randn(10))

    # length of second axis does not match dimensionality of histogram
    for h in (a, b, c):
        assert_raises(ValueError, rnp.fill_hist, h, RNG.randn(10, 4))

    # wrong type
    h = list()
    a = RNG.randn(10)
    assert_raises(TypeError, rnp.fill_hist, h, a)
def calculate_efficiency(
    reconstructed: ROOT.TH3D,
    generated: ROOT.TH3D,
    eta_cut: float = None,
    pt_range: typing.List[float] = None,
):
    """Calculated the efficiency as function of the feature in axis.

    Args:
        reconstructed: histogram with the reconstructed information.
        generated: histogram with the generated information.
        eta_cut: applies the selection |n| < eta_cut to the efficiency
        pt_range: selects only particles with pt_range[0] < pt < pt_range[1]

    Returns:
        efficiency: a TGraph with the efficiencies
    """

    epsilon = 0.0001

    if eta_cut is not None:
        generated.GetYaxis().SetRangeUser(-1.0 * eta_cut + epsilon,
                                          eta_cut - epsilon)
        reconstructed.GetYaxis().SetRangeUser(-1.0 * eta_cut + epsilon,
                                              eta_cut - epsilon)

    if pt_range is not None:
        if len(pt_range) != 2:
            raise ValueError(
                "You should pass exactly two values to the transverse momentum"
                "range (pt_range).")

        generated.GetXaxis().SetRangeUser(pt_range[0] + epsilon,
                                          pt_range[1] - epsilon)
        reconstructed.GetXaxis().SetRangeUser(pt_range[0] + epsilon,
                                              pt_range[1] - epsilon)

    generated_1d = generated.Project3D("x")
    reconstructed_1d = reconstructed.Project3D("x")

    # efficiency = ROOT.TEfficiency(reconstructed_1d, generated_1d)
    efficiency = reconstructed_1d.Clone("Efficiency")
    efficiency.Divide(generated_1d)

    return efficiency
示例#10
0
    def init_create(self, cf):

        #create the 'j' and 'k' components at a given 'i'

        #bins in x, y and mlt
        nx, xmax = self.get_nbins(cf("xybin"), cf("xmin"), cf("xmax"))
        ny, ymax = self.get_nbins(cf("xybin"), cf("ymin"), cf("ymax"))
        nt, tmax = self.get_nbins(cf("tbin"), cf("tmin"), cf("tmax"))
        xmin = cf("xmin")
        ymin = cf("ymin")
        tmin = cf("tmin")

        #mlt in x and y at 'j' and 'k'
        self.hXYTjk = TH3D(self.namXYT, self.namXYT, nx, xmin, xmax, ny, ymin,
                           ymax, nt, tmin, tmax)

        #mean of mlt in x and y at 'j' and 'k'
        self.hTjk = TH2D(self.namT, self.namT, nx, xmin, xmax, ny, ymin, ymax)

        #underflow and overflow in x, y and mlt
        self.hX = TH1D("hX_" + self.namXYT, "hX", nx, xmin, xmax)
        self.hY = TH1D("hY_" + self.namXYT, "hY", ny, ymin, ymax)
        self.hT = TH1D("hT_" + self.namXYT, "hT", nt, tmin, tmax)
示例#11
0
 def getBestFitHistoList(self):
     #declare 3D histogram
     histoname = '%s_best_fit_3D_histo' % (self._name)
     self._best_fit_histo = TH3D(
         histoname,
         '%s channel best fit 3D histogram; c*; |x_{F}|; M [GeV]' %
         (self._name),
         len(self._best_fit_x_bins) - 1, self._best_fit_x_bins,
         len(self._best_fit_y_bins) - 1, self._best_fit_y_bins,
         len(self._best_fit_z_bins) - 1, self._best_fit_z_bins)
     #draw skimmed tree into this histogram
     cstar = array('f', [-1.0])
     self._skimmed_tree.SetBranchAddress('cstar', cstar)
     x_F = array('f', [-1.0])
     self._skimmed_tree.SetBranchAddress('x_F', x_F)
     M = array('f', [-1.0])
     self._skimmed_tree.SetBranchAddress('M', M)
     for i in range(self._skimmed_tree.GetEntries()):
         self._skimmed_tree.GetEntry(i)
         self._best_fit_histo.Fill(cstar[0], abs(x_F[0]), M[0])
     #return the histogram and its projections
     return self._best_fit_histo, self._best_fit_histo.ProjectionX(
     ), self._best_fit_histo.ProjectionY(
     ), self._best_fit_histo.ProjectionZ()
示例#12
0
# creating histograms
from ROOT import TH3D
from array import array

# variable width bins
hist3d = TH3D('3d', '3d', 3, array('d', [0, 3, 10, 100]), 5,
              array('d', [2.3, 4.2, 5.8, 10, 20, 25.5]), 2,
              array('d', [-100, 0, 20]))
# ROOT is missing some constructors... (the following will not work)
hist3d = TH3D('3d', '3d', 3, 0, 5, 5, array('d',
                                            [2.3, 4.2, 5.8, 10, 20, 25.5]), 2,
              array('d', [-100, 0, 20]))
示例#13
0
文件: test3d.py 项目: vpalladi/VYO
FileOutName = 'Out_R' + str(R) + '.root'
FileOutRoot = TFile(FileOutName, 'recreate')

# position and concentration matrixes
P = [[[[0., 0., 0.] for iz in range(Nz + 2)] for iy in range(Ny + 2)]
     for ix in range(Nx + 2)]
C = [[[C_contour for iz in range(Nz + 2)] for iy in range(Ny + 2)]
     for ix in range(Nx + 2)]

# graphs
gMassEvolution = TGraph()
gMassRelease = TGraph()

# generate the map at t0
Cmap_t0 = TH3D("Cmap_t0", "Cmap_t0", Nx + 2, (-Nx / 2 - 1) * dx + dx / 2,
               (Nx / 2 + 1) * dx + dx / 2, Ny + 2, (-Ny / 2 - 1) * dy + dy / 2,
               (Ny / 2 + 1) * dy + dy / 2, Nz + 2, (-Nz / 2 - 1) * dz + dz / 2,
               (Nz / 2 + 1) * dz + dz / 2)

Total_amount_solute = 0  # g

# define the matrix of pixels
MATRIX = [[[Cpixel(pixel_meanlife) for i in range(Nx + 2)]
           for i in range(Ny + 2)] for i in range(Nz + 2)]

hDegradation_time_distribution = TH1D('degradation_time_distribution',
                                      'degradation_time_distribution', 100, 0,
                                      pixel_meanlife * 4)

print " > Generating the map at t0"
for ix in range(0, Nx + 2):
    for iy in range(0, Ny + 2):
示例#14
0
    def __plot_3d(self):
        global unique_cnt
        uid = next(unique_cnt)
        header = self.__parser.get_header_info()
        hdata = self.__parser.get_histogram_data()
        name = header['H_NAME']
        name = name[1:]
        nrbins = header['RBINS']
        npbins = header['PBINS']
        nzbins = header['ZBINS']
        rl = header['RRAN'][0]
        ru = header['RRAN'][1]
        pl = header['PRAN'][0]
        pu = header['PRAN'][1]
        zl = header['ZRAN'][0]
        zu = header['ZRAN'][1]

        ## ------   TH2D::TH2D(const char* name, const char* title, int nbinsx, double xlow, double xup, int nbinsy, double ylow, double yup)
        self.__histo = TH3D("RPZ " + name, "RPZ " + name, int(nrbins),
                            float(rl), float(ru), int(npbins), float(pl),
                            float(pu), int(nzbins), float(zl), float(zu))
        self.__histo.SetXTitle("R [cm]")
        self.__histo.GetXaxis().CenterTitle(kTRUE)
        self.__histo.GetXaxis().SetTitleOffset(1.1)
        self.__histo.GetXaxis().SetTitleSize(0.04)
        self.__histo.GetXaxis().SetLabelSize(0.03)
        self.__histo.GetXaxis().SetTickLength(0.02)
        self.__histo.GetXaxis().SetNdivisions(20510)

        self.__histo.SetYTitle("P [rad]")
        self.__histo.GetYaxis().CenterTitle(kTRUE)
        self.__histo.GetYaxis().SetTitleOffset(1.2)
        self.__histo.GetYaxis().SetTitleSize(0.04)
        self.__histo.GetYaxis().SetLabelSize(0.03)
        self.__histo.GetYaxis().SetTickLength(0.02)
        self.__histo.GetYaxis().SetNdivisions(20510)
        #self.__histo.SetMinimum(1e-9);

        self.__histo.GetZaxis().SetTitle("Z [cm]")
        self.__histo.GetZaxis().CenterTitle(kTRUE)
        self.__histo.GetZaxis().SetTitleOffset(1.2)
        self.__histo.GetZaxis().SetTitleSize(0.04)
        self.__histo.GetZaxis().SetLabelSize(0.03)
        self.__histo.GetZaxis().SetTickLength(0.02)
        self.__histo.GetZaxis().SetNdivisions(20510)

        ResR = (header['RRAN'][1] - header['RRAN'][0]) / nrbins
        ResP = (pu - pl) / npbins
        ResZ = (zu - zl) / nzbins
        FirstR = header['RRAN'][0] + ResR / 2.
        FirstP = pl + ResP / 2.
        FirstZ = zl + ResZ / 2.
        N = nrbins * npbins * nzbins
        rPos = [None] * N
        pPos = [None] * N
        zPos = [None] * N
        # -> fill the histo now!
        if nzbins > 1:
            pos_cnt = 0
            for zentry in range(nzbins):
                zPos[zentry] = FirstZ + float(zentry) * ResZ
                for pentry in range(npbins):
                    pPos[pentry] = FirstP + float(pentry) * ResP
                    for rentry in range(nrbins):
                        data_point = hdata['DATA'][pos_cnt]
                        rPos[rentry] = FirstR + float(rentry) * ResR
                        self.__histo.SetBinContent(int(rentry), int(pentry),
                                                   int(zentry),
                                                   float(data_point))
                        pos_cnt += 1

        else:
            self.__histo = TH1F(name, name, int(nrbins), float(rl), float(ru))

            data_points = [0] * nrbins
            error_points = [0] * nrbins
            pos_cnt = 0
            for pentry in range(npbins):
                for rentry in range(nrbins):
                    data_points[rentry] += hdata['DATA'][pos_cnt]
                    error_points[rentry] += hdata['ERRORS'][pos_cnt]
                    pos_cnt += 1

            data_points[:] = [x / npbins for x in data_points]
            error_points[:] = [x / npbins for x in error_points]

            for indx, data_point in enumerate(data_points):
                self.__histo.SetBinContent(indx + 1, data_point)

            for indx, error_point in enumerate(hdata['ERRORS']):
                error_point *= self.__histo.GetBinContent(indx) * 0.01 / 2
                self.__histo.SetBinError(indx, error_point)

            min_val = min(hdata['DATA'])
            max_val = max(hdata['DATA'])
示例#15
0
 def makeTH3D(self, *args):
     """args need to be args for TH3D constructor."""
     self.append(TH3D(*args))
示例#16
0
def test_evaluate():
    # create functions and histograms
    f1 = TF1("f1", "x")
    f2 = TF2("f2", "x*y")
    f3 = TF3("f3", "x*y*z")
    h1 = TH1D("h1", "", 10, 0, 1)
    h1.FillRandom("f1")
    h2 = TH2D("h2", "", 10, 0, 1, 10, 0, 1)
    h2.FillRandom("f2")
    h3 = TH3D("h3", "", 10, 0, 1, 10, 0, 1, 10, 0, 1)
    h3.FillRandom("f3")
    # generate random arrays
    arr_1d = np.random.rand(5)
    arr_2d = np.random.rand(5, 2)
    arr_3d = np.random.rand(5, 3)
    arr_4d = np.random.rand(5, 4)
    # evaluate the functions
    assert_array_equal(rnp.evaluate(f1, arr_1d), map(f1.Eval, arr_1d))
    assert_array_equal(rnp.evaluate(f1.GetTitle(), arr_1d),
                       map(f1.Eval, arr_1d))
    assert_array_equal(rnp.evaluate(f2, arr_2d),
                       [f2.Eval(*x) for x in arr_2d])
    assert_array_equal(rnp.evaluate(f2.GetTitle(), arr_2d),
                       [f2.Eval(*x) for x in arr_2d])
    assert_array_equal(rnp.evaluate(f3, arr_3d),
                       [f3.Eval(*x) for x in arr_3d])
    assert_array_equal(rnp.evaluate(f3.GetTitle(), arr_3d),
                       [f3.Eval(*x) for x in arr_3d])
    # 4d formula
    f4 = TFormula('test', 'x*y+z*t')
    assert_array_equal(rnp.evaluate(f4, arr_4d),
                       [f4.Eval(*x) for x in arr_4d])
    # evaluate the histograms
    assert_array_equal(rnp.evaluate(h1, arr_1d),
                       [h1.GetBinContent(h1.FindBin(x)) for x in arr_1d])
    assert_array_equal(rnp.evaluate(h2, arr_2d),
                       [h2.GetBinContent(h2.FindBin(*x)) for x in arr_2d])
    assert_array_equal(rnp.evaluate(h3, arr_3d),
                       [h3.GetBinContent(h3.FindBin(*x)) for x in arr_3d])
    # create a graph
    g = TGraph(2)
    g.SetPoint(0, 0, 1)
    g.SetPoint(1, 1, 2)
    assert_array_equal(rnp.evaluate(g, [0, .5, 1]), [1, 1.5, 2])
    from ROOT import TSpline3
    s = TSpline3("spline", g)
    assert_array_equal(rnp.evaluate(s, [0, .5, 1]), map(s.Eval, [0, .5, 1]))
    # test exceptions
    assert_raises(TypeError, rnp.evaluate, object(), [1, 2, 3])
    assert_raises(ValueError, rnp.evaluate, h1, arr_2d)
    assert_raises(ValueError, rnp.evaluate, h2, arr_3d)
    assert_raises(ValueError, rnp.evaluate, h2, arr_1d)
    assert_raises(ValueError, rnp.evaluate, h3, arr_1d)
    assert_raises(ValueError, rnp.evaluate, h3, arr_2d)
    assert_raises(ValueError, rnp.evaluate, f1, arr_2d)
    assert_raises(ValueError, rnp.evaluate, f2, arr_3d)
    assert_raises(ValueError, rnp.evaluate, f2, arr_1d)
    assert_raises(ValueError, rnp.evaluate, f3, arr_1d)
    assert_raises(ValueError, rnp.evaluate, f3, arr_2d)
    assert_raises(ValueError, rnp.evaluate, g, arr_2d)
    assert_raises(ValueError, rnp.evaluate, s, arr_2d)
    assert_raises(ValueError, rnp.evaluate, "f", arr_1d)
    assert_raises(ValueError, rnp.evaluate, "x*y", arr_1d)
    assert_raises(ValueError, rnp.evaluate, "x", arr_2d)
    assert_raises(ValueError, rnp.evaluate, "x*y", arr_3d)
示例#17
0
    'hoMuonAnalyzer/etaPhi/etaP1PhiM1_', 'hoMuonAnalyzer/etaPhi/etaP2PhiM1_',
    'hoMuonAnalyzer/etaPhi/etaM2PhiM2_', 'hoMuonAnalyzer/etaPhi/etaM1PhiM2_',
    'hoMuonAnalyzer/etaPhi/etaP0PhiM2_', 'hoMuonAnalyzer/etaPhi/etaP1PhiM2_',
    'hoMuonAnalyzer/etaPhi/etaP2PhiM2_'
]

scenarioNameList = ['WithSingleMu', 'NoSingleMu', 'NoSingleMuAboveThr']

histoList = []
fitList = []
paveList = []
lowStatisticsList = []
boxList = []

h3D = TH3D("histMpvs",
           "MPV results;Relative i#eta;Relative i#phi;Rec. E / GeV", 7, -3.5,
           3.5, 7, -3.5, 3.5, 20, 0, 4)

for i, scenario in enumerate(scenarioNameList):
    canvasList.append(
        TCanvas("canvasLandau" + str(i), "Canvas Landau" + str(i), 900, 900))
    canvasList[-1].Divide(5, 5)
    for j, nameTrunk in enumerate(nameTrunkList):
        canvasList[i].cd(j + 1)
        localHist = file.Get(nameTrunk + scenario)
        if (localHist):
            localHist.GetXaxis().SetRangeUser(-.1, 5)
            histoList.append(localHist)
            localHist.Draw()
            localHist.SetStats(0)
            paveText = TPaveText(0.4, 0.6, 0.9, 0.9, 'NDC')
示例#18
0
                    -30, 300, 700, -165, 165)
numuVertexZX = TH2D("numuVertexZX", "#nu_{#mu};V_{z} [cm];V_{x} [cm]", 2600,
                    -30, 1200, 700, -30, 300)
numuVertexZY = TH2D("numuVertexZY", "#nu_{#mu};V_{z} [cm];V_{y} [cm]", 2600,
                    -30, 1200, 700, -165, 165)
numuVertexX = TH1D("numuVertexX", ";V_{x} [cm];Events", 70, -30, 300)
numuVertexY = TH1D("numuVertexY", ";V_{y} [cm];Events", 70, -165, 165)
numuVertexZ = TH1D("numuVertexZ", ";V_{z} [cm];Events", 200, -30, 1200)
nueVertexXY = TH2D("nueVertexXY", "#nu_{e};V_{x} [cm];V_{y} [cm]", 70, -30,
                   300, 70, -165, 165)
numuEnergyDistance = TH2D("numuEnergyDistance", ";Energy [GeV];d [cm]", 600, 0,
                          6, 500, 0, 80000)
numuCreationZ = TH1D("numuCreationZ", ";z [cm];Events", 1000, -140, 100000)

#numuVertex3D = TH3D("numuVertex3D", ";V_{x} [cm];V_{y} [cm];V_{z} [cm]", 100, -10, 260, 100, -145, 145, 300, -30, 1100)
numuVertex3D = TH3D("numuVertex3D", ";V_{x} [cm];V_{y} [cm];V_{z} [cm]", 50,
                    50, 60, 50, -105, -95, 300, -30, 1100)

numuVertexXY1 = TH2D("numuVertexXY1",
                     "#nu_{#mu}   z < 208 cm;V_{x} [cm];V_{y} [cm]", 70, -30,
                     300, 70, -165, 165)
numuVertexXY2 = TH2D("numuVertexXY2",
                     "#nu_{#mu}   208 < z < 416 cm;V_{x} [cm];V_{y} [cm]", 70,
                     -30, 300, 70, -165, 165)
numuVertexXY3 = TH2D("numuVertexXY3",
                     "#nu_{#mu}   416 < z < 624 cm;V_{x} [cm];V_{y} [cm]", 70,
                     -30, 300, 70, -165, 165)
numuVertexXY4 = TH2D("numuVertexXY4",
                     "#nu_{#mu}   624 < z < 832 cm;V_{x} [cm];V_{y} [cm]", 70,
                     -30, 300, 70, -165, 165)
numuVertexXY5 = TH2D("numuVertexXY5",
                     "#nu_{#mu}   z > 832 cm;V_{x} [cm];V_{y} [cm]", 70, -30,
def set_all_bin_contents(hist: ROOT.TH3D, value: float):
    for x in range(0, hist.GetNbinsX() + 2):
        for y in range(0, hist.GetNbinsY() + 2):
            for z in range(0, hist.GetNbinsZ() + 2):
                hist.SetBinContent(x, y, z, value)
示例#20
0
p0 = my_func.GetParameter(0)
p1 = my_func.GetParameter(1)
p2 = my_func.GetParameter(2)

# ---------------------------------------------------------------------------------------#
# fills a 3d histogram based off the spatial calibrations and then saves the 3dhist and
# 3 paramater values to calibration file (any empy bins are assigned a value of 1, saved as Cal_run_run_subrun_subrun
# to do: expand to 3 planes
# ---------------------------------------------------------------------------------------#

zbin, xbin, ybin = len(grid_zy[0]), len(grid_x), len(grid_zy)
xmin, xmax = X[0], X[xbin - 1]
zmin, zmax = zmesh[0][0], zmesh[0][zbin - 1]
ymin, ymax = ymesh[0][0], ymesh[ybin - 1][0]

hist3d = TH3D("Calibration", "Calibration", xbin, xmin, xmax, ybin, ymin, ymax,
              zbin, zmin, zmax)

for row in range(nrow):
    for col in range(ncol):
        for xrow in range(len(X)):
            zc = zmesh[row, col]
            yc = ymesh[row, col]
            xc = X[xrow]
            cal = localval_zy[row, col]
            cal2 = localval_x[xrow]
            Cal = cal * cal2
            if np.isfinite(Cal) == False:
                Cal = 1
            bin_num = hist3d.FindBin(xc, yc, zc)
            cur_val = hist3d.GetBinContent(bin_num)
            if cur_val == 0:
示例#21
0
#!/usr/bin/python
from ROOT import TH3D
import sys

data=[]
fl=open (sys.argv[1])
h=TH3D  ("hist", "Histogram",100,0.,3.,100,0,3., 100,0,3.)
for line in fl:
  h.Fill (
  float(line.split()[int(sys.argv[2])]),
  float(line.split()[int(sys.argv[3])]),
  float(line.split()[int(sys.argv[4])]))
h.Draw()
raw_input()
示例#22
0
def test_random_sample_h3():
    hist = TH3D("h3", "h3", 10, -3, 3, 10, -3, 3, 10, -3, 3)
    sample = rnp.random_sample(hist, 100)
    assert_equal(sample.shape, (100, 3))
示例#23
0
    def __plot_2d(self):
        global unique_cnt
        uid = next(unique_cnt)
        header = self.__parser.get_header_info()
        hdata = self.__parser.get_histogram_data()['DATA']
        name = header['H_NAME'] + ' ' + str(uid)
        name = name[1:]
        nxbins = header['XBINS']
        nybins = header['YBINS']
        nzbins = header['ZBINS']
        xl = header['XRAN'][0]
        xu = header['XRAN'][1]
        yl = header['YRAN'][0]
        yu = header['YRAN'][1]
        zl = header['ZRAN'][0]
        zu = header['ZRAN'][1]
        n_of_histo = nzbins

        self.__histo = TH3D("XYZ " + name, "XYZ " + name, int(nxbins),
                            float(xl), float(xu), int(nybins), float(yl),
                            float(yu), int(nzbins), float(zl), float(zu))
        self.__histo.SetXTitle("X [cm]")
        self.__histo.GetXaxis().CenterTitle(kTRUE)
        self.__histo.GetXaxis().SetTitleOffset(1.1)
        self.__histo.GetXaxis().SetTitleSize(0.04)
        self.__histo.GetXaxis().SetLabelSize(0.03)
        self.__histo.GetXaxis().SetTickLength(0.02)
        self.__histo.GetXaxis().SetNdivisions(20510)

        self.__histo.SetYTitle("Y [cm]")
        self.__histo.GetYaxis().CenterTitle(kTRUE)
        self.__histo.GetYaxis().SetTitleOffset(1.2)
        self.__histo.GetYaxis().SetTitleSize(0.04)
        self.__histo.GetYaxis().SetLabelSize(0.03)
        self.__histo.GetYaxis().SetTickLength(0.02)
        self.__histo.GetYaxis().SetNdivisions(20510)

        self.__histo.GetZaxis().SetTitle("Z [cm]")
        self.__histo.GetZaxis().CenterTitle(kTRUE)
        self.__histo.GetZaxis().SetTitleOffset(1.3)
        self.__histo.GetZaxis().SetTitleSize(0.04)
        self.__histo.GetZaxis().SetLabelSize(0.03)
        self.__histo.GetZaxis().SetTickLength(0.02)
        self.__histo.GetZaxis().SetNdivisions(20510)

        ResX = (xu - xl) / nxbins
        ResY = (yu - yl) / nybins
        ResZ = (zu - zl) / nzbins
        FirstX = xl + ResX / 2.
        FirstY = yl + ResY / 2.
        FirstZ = zl + ResZ / 2.
        N = nxbins * nybins * nzbins
        zPos = [None] * N
        xPos = [None] * N
        yPos = [None] * N
        # -> fill the histo now!
        pos_cnt = 0
        for zentry in range(nzbins):
            zPos[zentry] = FirstZ + float(zentry) * ResZ
            for yentry in range(nybins):
                yPos[yentry] = FirstY + float(yentry) * ResY
                for xentry in range(nxbins):
                    data_point = hdata[pos_cnt]
                    xPos[xentry] = FirstX + float(xentry) * ResX
                    self.__histo.Fill(float(xPos[xentry]), float(yPos[yentry]),
                                      float(zPos[zentry]), float(data_point))
                    self.__histo.SetFillColor(kRed)
                    pos_cnt += 1
示例#24
0
                               'Base Histogram for RooDataHist', nGridPar1Bins,
                               par1GridMin, par1GridMax, nGridPar2Bins,
                               par2GridMin, par2GridMax)
            newFormatInput = TH2D('bin_content_par1_par2_' + str(i),
                                  'bincontent', nGridPointsForNewF,
                                  par1GridMin, par1GridMax, nGridPointsForNewF,
                                  par2GridMin, par2GridMax)
        elif (model == "par1par2par3_TH3" or model == "par1par2par3_TF3"):
            theBaseData = TH3F('theBaseData_' + section + '_' + str(i),
                               'Base Histogram for RooDataHist', nGridPar1Bins,
                               par1GridMin, par1GridMax, nGridPar2Bins,
                               par2GridMin, par2GridMax, nGridPar3Bins,
                               par3GridMin, par3GridMax)
            newFormatInput = TH3D('bin_content_par1_par2_par3_' + str(i),
                                  'bincontent', nGridPointsForNewF,
                                  par1GridMin, par1GridMax, nGridPointsForNewF,
                                  par2GridMin, par2GridMax, nGridPointsForNewF,
                                  par3GridMin, par3GridMax)

        if i != len(bins) - 1:
            binMin = bins[i - 1]
            binMax = bins[i]

            if (model == "par1_TH1" or model == "par1_TF1"):
                sigObj.Draw(
                    par1Name + ' >> theBaseData_' + section + '_' + str(i),
                    #                            '('+weight.GetName()+'*'+str(efficiencies[i-1])+')'+'*('+cfg.get(section,'obsVar') + #
                    weight.GetName() + '*(' + cfg.get(section, 'obsVar') +  #
                    ' > ' + str(binMin) + ' && ' + cfg.get(section, 'obsVar') +
                    ' < ' + str(binMax) + ')',
                    'goff')
示例#25
0
def convert2tfrecords(args):

  nChannel=3
  h1 = TH3D('h1','h1',\
            args.nBinX,args.rangeXL,args.rangeXH,\
            args.nBinY,args.rangeYL,args.rangeYH,\
            args.nBinZ,args.rangeZL,args.rangeZH)
  h2 = TH3D('h2','h2',\
            args.nBinX,args.rangeXL,args.rangeXH,\
            args.nBinY,args.rangeYL,args.rangeYH,\
            args.nBinZ,args.rangeZL,args.rangeZH)
  h3 = TH3D('h3','h3',\
            args.nBinX,args.rangeXL,args.rangeXH,\
            args.nBinY,args.rangeYL,args.rangeYH,\
            args.nBinZ,args.rangeZL,args.rangeZH)
  chainCME0=TChain('AMPT')
  chainCME0.Add(args.input0)
  chainCME1=TChain('AMPT')
  chainCME1.Add(args.input1)
  totalNumber0=chainCME0.GetEntries()
  totalNumber1=chainCME1.GetEntries()
  
  with tf.io.TFRecordWriter(args.output) as record_writer:

    writeOutNumber=0
    for (event0,event1) in zip(chainCME0,chainCME1):
      for i in range(event0.mult):
        if(event0.ID[i]==211):
          h1.Fill(event0.Px[i],event0.Py[i],event0.Pz[i])
          continue
        if(event0.ID[i]==111):
          h2.Fill(event0.Px[i],event0.Py[i],event0.Pz[i])
          continue
        if(event0.ID[i]==-211):
          h3.Fill(event0.Px[i],event0.Py[i],event0.Pz[i])
          continue

      channel1=histogram3D2Matrix(h1,args.nBinZ,args.nBinY,args.nBinX)
      channel2=histogram3D2Matrix(h2,args.nBinZ,args.nBinY,args.nBinX)
      channel3=histogram3D2Matrix(h3,args.nBinZ,args.nBinY,args.nBinX)
      
      channel1=channel1[:,:,:,np.newaxis]
      channel2=channel2[:,:,:,np.newaxis]
      channel3=channel3[:,:,:,np.newaxis]
      event=np.hstack((channel1,channel2,channel3))
      event=event.reshape(args.nBinX*args.nBinY*args.nBinZ*nChannel)
      example=tf.train.Example(features=tf.train.Features(
        feature={
          'image': tf.train.Feature(float_list=tf.train.FloatList(value=event)),
          'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[0])),
          'nBinX': tf.train.Feature(int64_list=tf.train.Int64List(value=[args.nBinX])),
          'nBinY': tf.train.Feature(int64_list=tf.train.Int64List(value=[args.nBinY])),
          'nBinZ': tf.train.Feature(int64_list=tf.train.Int64List(value=[args.nBinZ])),
          'nChannel': tf.train.Feature(int64_list=tf.train.Int64List(value=[nChannel])),
        }))
      record_writer.write(example.SerializeToString())
      h1.Reset()
      h2.Reset()
      h3.Reset()

      for i in range(event1.mult):
        if(event1.ID[i]==211):
          h1.Fill(event1.Px[i],event1.Py[i],event1.Pz[i])
          continue
        if(event1.ID[i]==111):
          h2.Fill(event1.Px[i],event1.Py[i],event1.Pz[i])
          continue
        if(event1.ID[i]==-211):
          h3.Fill(event1.Px[i],event1.Py[i],event1.Pz[i])
          continue
        
      channel1=histogram3D2Matrix(h1,args.nBinZ,args.nBinY,args.nBinX)
      channel2=histogram3D2Matrix(h2,args.nBinZ,args.nBinY,args.nBinX)
      channel3=histogram3D2Matrix(h3,args.nBinZ,args.nBinY,args.nBinX)
      
      channel1=channel1[:,:,:,np.newaxis]
      channel2=channel2[:,:,:,np.newaxis]
      channel3=channel3[:,:,:,np.newaxis]
      event=np.hstack((channel1,channel2,channel3))
      event=event.reshape(args.nBinX*args.nBinY*args.nBinZ*nChannel)
      example=tf.train.Example(features=tf.train.Features(
        feature={
          'image': tf.train.Feature(float_list=tf.train.FloatList(value=event)),
          'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[1])),
          'nBinX': tf.train.Feature(int64_list=tf.train.Int64List(value=[args.nBinX])),
          'nBinY': tf.train.Feature(int64_list=tf.train.Int64List(value=[args.nBinY])),
          'nBinZ': tf.train.Feature(int64_list=tf.train.Int64List(value=[args.nBinZ])),
          'nChannel': tf.train.Feature(int64_list=tf.train.Int64List(value=[nChannel])),
        }))
      record_writer.write(example.SerializeToString())
      h1.Reset()
      h2.Reset()
      h3.Reset()
      writeOutNumber+=1
      print('{}\r'.format('   Tag0:%d, Tag1:%d, %d writen into %s' %(totalNumber0,totalNumber1,writeOutNumber,args.output)),end="",flush=True)