Beispiel #1
0
def splitting():
    epsilon = 0.1
    #error ~ C / sqrt(Nevents)
    #z = epsilon + (1 - 2*epsilon) *Rand()
    #weightz = as2pi* 6 (1./z + 1./(1.-z))
    #return

    as2pi = 0.1/2./pi

    #		here we calculate  the splitting variable z for 1/z and  1/(1-z)
    #		use Pgg=6./z 
    # + 6./(1.-z))  // z -> 1-z

    g0 = 6.*as2pi * log((1.-epsilon)/epsilon)
    g1 = 6.*as2pi * log((1.-epsilon)/epsilon)
    gtot = g0 + g1 

    zmin = epsilon
    zmax = 1.-epsilon

    r1 = gRandom.Uniform()
    r2 = gRandom.Uniform()

    z = zmin * (zmax/zmin)**r2
    if r1 > g0/gtot:
        z = 1. - z
    weightz = 1.
    return z
Beispiel #2
0
def fncomposition(a, b, a1, a2, b1, b2):
    while (True):
        nr = gRandom.Uniform(0,1)
        nk = gRandom.Uniform(0,1)
        if nk < a1:
            return inv1(nr, b1)
        else:
            return inv2(nr, b2)
Beispiel #3
0
def suda(t1, t2):
    # Generate randomly q2
    q2 = t1 * pow(t2 / t1, gRandom.Uniform())
    # we generate here z1 = 1-z,
    # because we have a pole in the splitting functions \sim 1/(1-z)
    # Generate randomly z1
    z1min, z1max = 0.01, 0.99
    z1 = z1min * pow(z1max / z1min, gRandom.Uniform())

    z = 1. - z1
    q = sqrt(q2)
    integrand = alphaS(q) / 2 / pi * Splitting(z) / q2
    weight = q2 * log(t2 / t1) * z1 * log(z1max / z1min)
    return integrand * weight
Beispiel #4
0
 def fill(sample,tree,nevts): # help function to fill trees
   for i in xrange(nevts):
     genmatch_2[0] = 5 if gRandom.Uniform(1.)<getgenerator('genmatch_2',sample) else 0
     m_vis[0]      = getgenerator('m_vis',sample)(genmatch_2[0])
     pt_1[0]       = getgenerator('pt_1', sample)()
     pt_2[0]       = getgenerator('pt_2', sample)()
     if m_vis[0]<0 or pt_1[0]<0 or pt_2[0]<0: continue
     if pt_1[0]<pt_1[0]:
       pt_1[0], pt_2[0] = pt_2[0], pt_1[0]
     dm_2[0]   = getgenerator('dm_2', sample)(gRandom.Uniform(1.))
     eta_1[0]  = getgenerator('eta_1', sample)()
     eta_2[0]  = getgenerator('eta_2', sample)()
     njets[0]  = getgenerator('njets', sample)()
     weight[0] = getgenerator('weight',sample)() if sample!='Data' else 1.0
     tree.Fill()
Beispiel #5
0
def writeTree():
    print ">>> Writing a tree."

    # make new root file with new tree
    file = TFile("tree.root", 'recreate')
    tree = TTree("tree_name", "tree title")

    # create 1 dimensional float arrays as fill variables, in this way the float array serves
    # as a pointer which can be passed to the branch
    n = array('d', [0])
    u = array('d', [0])

    # using numpy instead of array class (note python's float datatype corresponds to C++ doubles):
    #n = numpy.zeros(1, dtype=float)
    #u = numpy.zeros(1, dtype=float)

    # create the branches and assign the fill-variables to them as doubles (D)
    tree.Branch("normal", n, 'normal/D')
    tree.Branch("uniform", u, 'uniform/D')

    # create some random numbers, assign them into the fill variables and call Fill()
    for i in xrange(10000):
        n[0] = gRandom.Gaus()
        u[0] = gRandom.Uniform()
        tree.Fill()

    # write the tree into the output file and close the file
    file.Write()
    file.Close()
Beispiel #6
0
def getpdf(q2):
    xmin = 0.00001
    xmax = 0.999
    x = xmin * (xmax/xmin)**gRandom.Uniform()
    weightx = x*log(xmax/xmin) 
    # this is for the simple case            
    pdf = 3.*pow((1-x),5)/x

    kx, ky = gauss2D(0.7)
    pVec = TLorentzVector()
    pVec.SetXYZM(kx, ky, x*Eb, 0.)
    return pVec, weightx * pdf
Beispiel #7
0
def splitting():
    epsilon = 0.1

    as2pi = 0.1/2./pi

    #	here we calculate  the splitting variable z for 1/z and  1/(1-z)
    #	use Pgg=6(1/z + 1/(1-z))  // for large z we use z -> 1-z

    g0 = 6.*as2pi * log((1.-epsilon)/epsilon)
    g1 = 6.*as2pi * log((1.-epsilon)/epsilon)
    gtot = g0 + g1 

    zmin = epsilon
    zmax = 1.-epsilon

    r1 = gRandom.Uniform()
    r2 = gRandom.Uniform()

    z = zmin * (zmax/zmin)**r2
    if r1 > g0/gtot:
        z = 1. - z
    weightz = 1.
    return z
Beispiel #8
0
def get_starting_pdf(q2):
    xmin = 0.0001
    xmax = 0.999
    # get x value according to g(x)\sim 1/x            
    x = xmin * (xmax/xmin)**gRandom.Uniform()
    weightx = x*log(xmax/xmin) 
    # use: xg(x) = 3 (1-x)**5
    pdf = 3.*pow((1-x),5)/x

    # now generate instrinsic kt according to a gauss distribution  
    kx, ky = gauss2D(0.7)
    pVec = TLorentzVector()
    pVec.SetXYZM(kx, ky, x*Eb, 0.)
    return pVec, weightx * pdf
def makeTTree():
    """Create ROOT TTree filled with a Gaussian distribution in x
       and a uniform distribution in y"""

    tree = TTree("tree", "tree")
    px = array('d', [0])
    py = array('d', [0])
    tree.Branch("px", px, "px/D")
    tree.Branch("py", py, "py/D")
    for i in range(500):
        px[0] = gRandom.Gaus(0, 3)
        py[0] = gRandom.Uniform() * 30 - 15
        tree.Fill()
    return tree
Beispiel #10
0
def sudakov(t0):
    #   here we calculate  from the sudakov form factor the next t > t0
    epsilon = 0.1
    as2pi = 0.1/(2.*pi)
    Ca = 3.
    # for Pgg use fact = 2*Ca
    fac = 2.*Ca 
    # use fixed alphas and only the 1/(1-z) term of the splitting fct

    r1 = gRandom.Uniform()
    Pint=log((1.-epsilon)/epsilon) # for 1/(1-z) splitting fct 
    t2 = -log(r1)/fac/as2pi/Pint
    t2 = t0 * exp(t2)
    assert(t2 >= t0)
    return t2
Beispiel #11
0
def createdummyroot(fname, nevts=10000):
    print ">>> Creating dummy ROOT file %r..." % (fname)
    file = TFile(fname, 'RECREATE')
    tree = TTree('tree', 'tree')
    hist = TH1F('hist', 'hist', 50, -2, 2)
    pt = array('d', [0])
    phi = array('d', [0])
    tree.Branch("pt", pt, 'normal/D')
    tree.Branch("phi", phi, 'uniform/D')
    for i in xrange(nevts):
        pt[0] = gRandom.Landau(40, 20)
        phi[0] = gRandom.Uniform(-1.57, 1.57)
        hist.Fill(gRandom.Landau(0, 1))
        tree.Fill()
    file.Write()
    file.Close()
    return fname
Beispiel #12
0
def evolve_pdf(q20, q2, p0):
    x = p0.Pz()/Eb
    kx = p0.Px()
    ky = p0.Py()
    weightx = 1.
    t1 = q20
    tcut = q2
    while t1 < tcut:
        # here we do now the evolution
        # first we generate t
        t0 = t1
        t1 = sudakov(t0) 
        
        # now we generate z
        z = splitting()
        #   since the sudakov involves only the 1/(1-z) part 
        #   of the splitting fct, we need to weight each branching
        #   by the ratio of the integral of the full and 
        #   approximate splitting fct

        ratio_splitting = 2 # for using Pgg

        if  t1 < tcut:
            x = x*z
            weightx = weightx *ratio_splitting
            # 
            # use here the angular ordering condition: sqrt(t1) = qt/(1-z) 
            # and apply this also to the propagator gluons
            #
            phi = 2*pi*gRandom.Uniform()
            kx +=  sqrt(t1)*cos(phi)*(1.-z)
            ky +=  sqrt(t1)*sin(phi)*(1.-z)                     
            #   kx += sqrt(t1)*cos(phi)
            #   ky += sqrt(t1)*sin(phi)                     
    k = TLorentzVector()
    k.SetXYZM(kx, ky, x*Eb, 0.)
    return k, weightx
Beispiel #13
0
def makesamples(nevts=10000,**kwargs):
  """Create pseudo MC and data tree for quick and reproducible testing of Plotter tools."""
  
  outdir  = kwargs.get('outdir',  'plots' )
  channel = kwargs.get('channel', 'mutau' )
  samples = kwargs.get('sample',  ['Data','ZTT','WJ','QCD','TT'])
  scales  = kwargs.get('scales',  None    )
  samples = unwraplistargs(samples)
  
  scaledict = { # relative contribtions to pseudo data
    'ZTT': 1.00,
    'WJ':  0.40,
    'QCD': 0.25,
    'TT':  0.15,
    'DYJets':  1.0,
    'DY1Jets': 0.5,
    'DY2Jets': 0.3,
    'DY3Jets': 0.2,
    'DY4Jets': 0.1,
  }
  if scales:
    scaledict.update(scales)
  scaledict.pop('Data',None)
  vardict = { # uncorrelated pseudo distributions for variables
    'm_vis': {
      '*':   lambda gm: gRandom.Gaus( 72, 9) if gm==5 else gRandom.Gaus( 91, 2), # default
      'ZTT': lambda gm: gRandom.Gaus( 72, 9),
      'WJ':  lambda gm: gRandom.Gaus( 65,28),
      'QCD': lambda gm: gRandom.Gaus( 80,44),
      'TT':  lambda gm: gRandom.Gaus(110,70),
    },
    'genmatch_2': { # chance that genmatch_2==5 (real tau)
      '*':   0.9, # default
      'ZTT': 1.0,
      'WJ':  0.5,
      'QCD': 0.5,
      'TT':  0.8,
    },
    'pt_1': {
      '*':   lambda: gRandom.Landau(30,2), # default
      'QCD': lambda: gRandom.Landau(30,5),
      'TT':  lambda: gRandom.Landau(40,6),
    },
    'pt_2': {
      '*':   lambda: gRandom.Landau(24,2), # default
      'WJ':  lambda: gRandom.Landau(24,2),
      'QCD': lambda: gRandom.Landau(24,5),
      'TT':  lambda: gRandom.Landau(30,6),
    },
    'eta_1': {
      '*': lambda: gRandom.Uniform(-2.5,2.5), # default
    },
    'eta_2': {
      '*': lambda: gRandom.Uniform(-2.5,2.5), # default
    },
    'dm_2': {
      '*':   lambda r: 0 if r<0.4 else 1 if r<0.6 else 10 if r<0.9 else 11, # default
    },
    'njets': {
      '*':   lambda: gRandom.Poisson(0.2,), # default
      'ZTT': lambda: gRandom.Poisson(0.2,),
      'WJ':  lambda: gRandom.Poisson(1.2,),
      'QCD': lambda: gRandom.Poisson(2.0,),
      'TT':  lambda: gRandom.Poisson(2.5,),
      'DYJets':  lambda: gRandom.Poisson(0.2,),
      'DY1Jets': lambda: 1,
      'DY2Jets': lambda: 2,
      'DY3Jets': lambda: 3,
      'DY4Jets': lambda: 4,
    },
    'NUP': {
      '*':   lambda: gRandom.Poisson(0.2,), # default
      'ZTT': lambda: gRandom.Poisson(0.2,),
      'WJ':  lambda: gRandom.Poisson(1.2,),
      'QCD': lambda: gRandom.Poisson(2.0,),
      'TT':  lambda: gRandom.Poisson(2.5,),
      'DYJets':  lambda: gRandom.Poisson(0.2,),
      'DY1Jets': lambda: 1,
      'DY2Jets': lambda: 2,
      'DY3Jets': lambda: 3,
      'DY4Jets': lambda: 4,
    },
    'weight': {
      '*':   lambda: gRandom.Gaus(1.0,0.10), # default
      'ZTT': lambda: gRandom.Gaus(1.0,0.10),
      'WJ':  lambda: gRandom.Gaus(1.0,0.10),
      'QCD': lambda: gRandom.Gaus(1.0,0.05),
      'TT':  lambda: gRandom.Gaus(1.0,0.08),
    },
  }
  
  # PREPARE TREES
  ensuredir(outdir)
  filedict   = { }
  histdict   = { }
  m_vis      = np.zeros(1,dtype='f')
  pt_1       = np.zeros(1,dtype='f')
  pt_2       = np.zeros(1,dtype='f')
  dm_2       = np.zeros(1,dtype='f')
  eta_1      = np.zeros(1,dtype='f')
  eta_2      = np.zeros(1,dtype='f')
  njets      = np.zeros(1,dtype='i')
  genmatch_2 = np.zeros(1,dtype='i') # genmatch_2: 5 = real tau; 0 = fake tau
  NUP        = np.zeros(1,dtype='i') # number of LHE-level partons for jet stitching
  weight     = np.zeros(1,dtype='f')
  def makesample(sample): # help function to create file with tree
    fname = "%s/%s_%s.root"%(outdir,sample,channel)
    file  = TFile(fname,'RECREATE')
    hist  = TH1D('cutflow','cutflow',20,0,20)
    tree  = TTree('tree','tree')
    tree.Branch('m_vis',      m_vis,      'm_vis/F')
    tree.Branch('pt_1',       pt_1,       'pt_1/F')
    tree.Branch('pt_2',       pt_2,       'pt_2/F')
    tree.Branch('dm_2',       dm_2,       'dm_2/I')
    tree.Branch('eta_1',      eta_1,      'eta_1/F')
    tree.Branch('eta_2',      eta_2,      'eta_2/F')
    tree.Branch('njets',      njets,      'njets/I')
    tree.Branch('genmatch_2', genmatch_2, 'genmatch_2/I')
    tree.Branch('NUP',        NUP,        'NUP/I')
    tree.Branch('weight',     weight,     'weight/F')
    tree.SetDirectory(file)
    hist.SetDirectory(file)
    hist.SetBinContent( 1,1)
    hist.SetBinContent(17,1)
    histdict[sample] = hist
    filedict[sample] = (file,tree)
  for sample in scaledict:
    makesample(sample)
  makesample('Data')
  
  def getgenerator(var,sample): # get random generator from dictionary
    if sample in vardict[var]: return vardict[var][sample]
    else: return vardict[var]['*']
  def fill(sample,tree,nevts): # help function to fill trees
    for i in xrange(nevts):
      genmatch_2[0] = 5 if gRandom.Uniform(1.)<getgenerator('genmatch_2',sample) else 0
      m_vis[0]      = getgenerator('m_vis',sample)(genmatch_2[0])
      pt_1[0]       = getgenerator('pt_1', sample)()
      pt_2[0]       = getgenerator('pt_2', sample)()
      if m_vis[0]<0 or pt_1[0]<0 or pt_2[0]<0: continue
      if pt_1[0]<pt_1[0]:
        pt_1[0], pt_2[0] = pt_2[0], pt_1[0]
      dm_2[0]   = getgenerator('dm_2', sample)(gRandom.Uniform(1.))
      eta_1[0]  = getgenerator('eta_1', sample)()
      eta_2[0]  = getgenerator('eta_2', sample)()
      njets[0]  = getgenerator('njets', sample)()
      weight[0] = getgenerator('weight',sample)() if sample!='Data' else 1.0
      tree.Fill()
  
  # PSEUDO MC
  print ">>> Generating pseudo MC..."
  #time0 = time.time()
  for sample in samples:
    if sample=='Data': continue
    #print ">>>   %r"%(sample)
    file, tree = filedict[sample]
    file.cd()
    fill(sample,tree,nevts)
    histdict[sample].Write()
    tree.Write()
  #print ">>>   %.1f seconds"%(time.time()-time0)
  
  # PSEUDO DATA
  if 'Data' in samples:
    print ">>> Generating pseudo data..."
    file, tree = filedict['Data']
    file.cd()
    #time0 = time.time()
    for sample in samples:
      if sample=='Data': continue
      prob = scaledict.get(sample,1.0)
      ndevts = int(prob*nevts) # relative contribtion to pseudo data
      fill(sample,tree,ndevts)
    histdict[sample].Write()
    tree.Write()
    #print ">>>   %.1f seconds"%(time.time()-time0)
  
  return filedict
Beispiel #14
0
        def CreateRandomPeaksConfig(xmin, xmax, ymin, ymax, bkg=120, peak_height=0.5, npeaks=NPeaks):
            '''
            Creates the input parameters for SignalShape, which describes the peak distribution in the
            Signal distribution
            :param xmin: window parameter
            :param xmax: window parameter
            :param ymin: window parameter
            :param ymax: window parameter
            :param bkg: background of signal response
            :param peak_height: height of one peak in % of bkg, if bkg==0: the peaks heights are set to 1
            :param npeaks: number of peaks in window - if none it picks random between 0 and 15
            :return: array containing the parameters
            '''
            if npeaks == None:
                npeaks = int(round(gRandom.Uniform(0, 15)))

            if self.MCAttributes['SpecialDistribution'] in ["Central", "central"]:
                npeaks = 1
                dxy = 0.02
                parameters = np.zeros(7)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                parameters[3] = gRandom.Uniform(center_x - dxy, center_x + dxy)
                parameters[4] = gRandom.Uniform(center_y - dxy, center_y + dxy)
                parameters[5] = gRandom.Uniform(self.MCAttributes['PeakSigmaX_min'], self.MCAttributes['PeakSigmaX_max'])
                parameters[6] = gRandom.Uniform(self.MCAttributes['PeakSigmaY_min'], self.MCAttributes['PeakSigmaY_max'])
            elif self.MCAttributes['SpecialDistribution'] in ["4Peaks", "4peaks", "L", "3Peaks"]:
                npeaks = 4
                dxy = 0.02
                parameters = np.zeros(3 + 4 * npeaks)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                # peaks:
                peaknr = 0
                for x in [center_x - 0.07, center_x + 0.07]:
                    for y in [center_y - 0.07, center_y + 0.07]:
                        parameters[3 + 4 * peaknr] = gRandom.Uniform(x - dxy, x + dxy)
                        parameters[4 + 4 * peaknr] = gRandom.Uniform(y - dxy, y + dxy)
                        parameters[5 + 4 * peaknr] = gRandom.Uniform(self.MCAttributes['PeakSigmaX_min'], self.MCAttributes['PeakSigmaX_max'])
                        parameters[6 + 4 * peaknr] = gRandom.Uniform(self.MCAttributes['PeakSigmaY_min'], self.MCAttributes['PeakSigmaY_max'])
                        peaknr += 1
                if self.MCAttributes['SpecialDistribution'] in ["L", "3Peaks"]:
                    npeaks = 3
                    parameters[0] = npeaks
                    parameters = parameters[:3 + 4 * npeaks]
            elif self.MCAttributes['SpecialDistribution'] in ["Testpattern", "testpattern", "Test", "test"]:
                npeaks = 8
                Center_x = gRandom.Uniform(center_x - 0.01, center_x + 0.01)
                Center_y = gRandom.Uniform(center_y - 0.01, center_y + 0.01)
                parameters = np.zeros(3 + 4 * npeaks)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                parameters[3] = Center_x - 0.1
                parameters[4] = Center_y + 0.08
                parameters[5] = 0.02
                parameters[6] = 0.02
                parameters[7] = Center_x - 0.04
                parameters[8] = Center_y + 0.08
                parameters[9] = 0.02
                parameters[10] = 0.02
                parameters[11] = Center_x - 0.1
                parameters[12] = Center_y
                parameters[13] = 0.025
                parameters[14] = 0.025
                parameters[15] = Center_x
                parameters[16] = Center_y
                parameters[17] = 0.02
                parameters[18] = 0.02
                parameters[19] = Center_x + 0.1
                parameters[20] = Center_y
                parameters[21] = 0.03
                parameters[22] = 0.03
                parameters[23] = Center_x - 0.04
                parameters[24] = Center_y - 0.06
                parameters[25] = 0.015
                parameters[26] = 0.015
                parameters[27] = Center_x - 0.12
                parameters[28] = Center_y - 0.12
                parameters[29] = 0.03
                parameters[30] = 0.03
                parameters[31] = Center_x + 0.08
                parameters[32] = Center_y - 0.12
                parameters[33] = 0.04
                parameters[34] = 0.04
            else:
                parameters = np.zeros(3 + 4 * npeaks)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                for i in range(npeaks):
                    parameters[3 + 4 * i] = gRandom.Uniform(xmin, xmax)
                    parameters[4 + 4 * i] = gRandom.Uniform(ymin, ymax)
                    parameters[5 + 4 * i] = gRandom.Uniform(0.02, 0.07)
                    parameters[6 + 4 * i] = gRandom.Uniform(0.02, 0.07)
            self.MCAttributes['NPeaks'] = npeaks
            return parameters
Beispiel #15
0
def gauss2D(sigma):
    kT = sigma * sqrt(-2 * log(gRandom.Uniform()))
    phi = 2 * pi * gRandom.Uniform()
    kx = kT * cos(phi)
    ky = kT * sin(phi)
    return kx, ky
Beispiel #16
0
def writeTree()
  print gDirectory.GetName()
  print gDirectory.ls()
  file = TFile("treeParticles.root", 'recreate')
  tree = TTree("tree_name", "tree title")
  
  nevts = 100
  Nmax = 10
  nParticles = array( 'i', [ 0 ] )
  pt = array( 'd', Nmax*[ 0. ] )
  tree.Branch( 'nParticles', nParticles, 'nParticles/I' )
  tree.Branch( 'pt', pt, 'pt[nParticles]/D' )
  
  for i in xrange(nevts):
    nParticles[0] = int(gRandom.Uniform()*10)
    for j in range(nParticles[0]):
       pt[j] = gRandom.Gaus(20,2)
    tree.Fill()
  
  tree.Draw("pt[0] >> h(100,0,10)")
  hist = gDirectory.Get("h")
  print gDirectory.GetName()
  print gDirectory.ls()
  print hist
  print type(hist)
  
  file.Write()
  file.Close()
  
Beispiel #17
0
def fonneuman(a, b):
    fmax = ff(1)
    while True:
        mu = gRandom.Uniform(0, fmax)
        r = gRandom.Uniform(a, b)
        if mu<=ff(r): return r
Beispiel #18
0
#     name: python2
#     display_name: Python 2
# ---

# # Demonstration of hit & miss method
# Import what is needed

from ROOT import gRandom
from math import sqrt

# Loop over random points in the 2D space

nhit = 0
npoints = 2000000
for n in range(npoints):
    x, y = gRandom.Uniform(), gRandom.Uniform()
    #accept if y < x
    if y < x:
        nhit += 1

# Calculate the integral

Int = float(nhit) / npoints

# And error using binomial formula

sigma2 = (1. - Int) / nhit
error = sqrt(sigma2) * Int

# Show the results
Beispiel #19
0
# Define the beam energy of the protons

Eb = 6500
xmin = 1e-5
xmax = pdf.xMax

# Define the number of points to be generated

npoints = 1000000

# Generate npoints of "events"

s1 = s2 = 0
for n in range(npoints):
    #Importance sampling in x1 and x2
    x1 = xmin * (xmax / xmin)**gRandom.Uniform()
    x2 = xmin * (xmax / xmin)**gRandom.Uniform()
    wgt = log(xmax / xmin)**2 * x1 * x2

    #mass and eta of DY
    m = 2 * Eb * sqrt(x1 * x2)
    eta = 1. / 2 * log(x1 / x2)
    #Accepted mass range
    if m < 40 or m > 60:
        continue

    #to simplify calculation
    def q(id, x):
        return pdf.xfxQ(id, x, m) / x

    def qq(id):
Beispiel #20
0
serial = 1000

arr = numpy.zeros(quantity)

integral = 0 
err = 0
cur = 0
cur_err = 0

for i in range (1, quantity + 1):
    if (i%serial == 0):
        err = numpy.sqrt((numpy.mean(arr[:i]**2)-numpy.mean(arr[:i])**2)/i) # sqrt from dispersion
        cur_err = numpy.sqrt((numpy.mean(arr[i-serial:i]**2)-numpy.mean(arr[i-serial:i])**2)/serial) # sqrt from dispersion for all
        print('Serial: %d, integral: %f, error: %f, cur_int/serial: %f, cur_error: %f' % (i, integral/i, err, cur/serial, cur_err))
        cur = 0
    x = gRandom.Uniform(ax, bx)
    y = gRandom.Uniform(ay, by)
    model = (bx-ax)*(by-ay)*F([x, y], 0)
    integral += model
    cur += model
    arr[i-1] = F([x, y], 0)*((bx-ax)*(by-ay)) # average method
    
def g1(x, y): return (numpy.exp(x[0] + (x[1])**2)/x[1] - (2 + x[1] * numpy.sqrt(x[0]))/x[1])
def g2(x, y): return 2*x[1]

def F2(x, y): return g1(x, y) + g2(x, y)

# def F2(x, y): return (numpy.exp(x[0] + (x[1])**2))/(1 + (x[1])*numpy.sqrt(x[0])/2) - 2 * x[1]

h3 = TH2F('h1', 'histogram tytle1', 100, 0, 0.5, 100, 1, 3);
for i in range(100):
Beispiel #21
0
from math import sqrt

# Define histograms with sum of random numbers

points = [1, 2, 3, 6, 12, 20, 40]
histos = {}
for p in points:
    histos[p] = TH1D(str(p), str(p), 100, -6, 6)

# Fill the histograms with random numbers

for n in range(100000):
    for p in points:
        x = 0.
        for n2 in range(p):
            x += gRandom.Uniform()
        histos[p].Fill((x - p / 2.) / sqrt(p / 12.))

# Plot Histograms separately

c = []
for p in points[:3]:
    c.append(TCanvas())
    histos[p].SetLineColor(p + 1)
    histos[p].Draw("hist e")
    c[-1].Draw()

# Plot histograms together

c.append(TCanvas())
for p in points:
Beispiel #22
0
    def Simulate(self, save=None, draw=None):
        '''

        :param save: if True: saves the root file as well as the true signal distribution
        :param draw: if True draws the signal distribution
        :param ask:
        :return:
        '''

        # Settings:
        MPV = self.MCAttributes['Landau_MPV_bkg']  # background for Landau MPV distribution
        sigma = self.MCAttributes['Landau_Sigma']  # Landau scaling sigma
        NPeaks = self.MCAttributes['NPeaks']
        MCRunPath = self.MCAttributes['MCRunPath'].format(self.RunNumber)
        xmin = self.diamond.Position['xmin'] + 0.01
        xmax = self.diamond.Position['xmax'] - 0.01
        ymin = self.diamond.Position['ymin'] + 0.01
        ymax = self.diamond.Position['ymax'] - 0.01
        center_x = (xmax + xmin) / 2.
        center_y = (ymax + ymin) / 2.
        if draw != None:
            assert (type(draw) == t.BooleanType), "draw has to be boolean type"
            self.MCAttributes['DrawRealDistribution'] = draw
        if save != None:
            assert (type(save) == t.BooleanType), "save argument has to be of type boolean"
            self.MCAttributes['Save'] = save

        def ManualHitDistribution(x, par):
            '''
            Probability density function for hit distribution based on
            6 2d gaussian in a rectangular pattern. The PDF is NOT
            normalized to 1
            :param x: array, x[0]: x position, x[1]: y position
            :param par: parameter array;
            :return:
            '''
            result = 0.1  # bkg
            norm = 1.
            sigma = 0.04
            for i in range(len(par) / 2):
                result += norm * TMath.Gaus(x[0], par[2 * i], sigma) * TMath.Gaus(x[1], par[2 * i + 1], sigma)
            return result

        def CreateRandomPeaksConfig(xmin, xmax, ymin, ymax, bkg=120, peak_height=0.5, npeaks=NPeaks):
            '''
            Creates the input parameters for SignalShape, which describes the peak distribution in the
            Signal distribution
            :param xmin: window parameter
            :param xmax: window parameter
            :param ymin: window parameter
            :param ymax: window parameter
            :param bkg: background of signal response
            :param peak_height: height of one peak in % of bkg, if bkg==0: the peaks heights are set to 1
            :param npeaks: number of peaks in window - if none it picks random between 0 and 15
            :return: array containing the parameters
            '''
            if npeaks == None:
                npeaks = int(round(gRandom.Uniform(0, 15)))

            if self.MCAttributes['SpecialDistribution'] in ["Central", "central"]:
                npeaks = 1
                dxy = 0.02
                parameters = np.zeros(7)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                parameters[3] = gRandom.Uniform(center_x - dxy, center_x + dxy)
                parameters[4] = gRandom.Uniform(center_y - dxy, center_y + dxy)
                parameters[5] = gRandom.Uniform(self.MCAttributes['PeakSigmaX_min'], self.MCAttributes['PeakSigmaX_max'])
                parameters[6] = gRandom.Uniform(self.MCAttributes['PeakSigmaY_min'], self.MCAttributes['PeakSigmaY_max'])
            elif self.MCAttributes['SpecialDistribution'] in ["4Peaks", "4peaks", "L", "3Peaks"]:
                npeaks = 4
                dxy = 0.02
                parameters = np.zeros(3 + 4 * npeaks)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                # peaks:
                peaknr = 0
                for x in [center_x - 0.07, center_x + 0.07]:
                    for y in [center_y - 0.07, center_y + 0.07]:
                        parameters[3 + 4 * peaknr] = gRandom.Uniform(x - dxy, x + dxy)
                        parameters[4 + 4 * peaknr] = gRandom.Uniform(y - dxy, y + dxy)
                        parameters[5 + 4 * peaknr] = gRandom.Uniform(self.MCAttributes['PeakSigmaX_min'], self.MCAttributes['PeakSigmaX_max'])
                        parameters[6 + 4 * peaknr] = gRandom.Uniform(self.MCAttributes['PeakSigmaY_min'], self.MCAttributes['PeakSigmaY_max'])
                        peaknr += 1
                if self.MCAttributes['SpecialDistribution'] in ["L", "3Peaks"]:
                    npeaks = 3
                    parameters[0] = npeaks
                    parameters = parameters[:3 + 4 * npeaks]
            elif self.MCAttributes['SpecialDistribution'] in ["Testpattern", "testpattern", "Test", "test"]:
                npeaks = 8
                Center_x = gRandom.Uniform(center_x - 0.01, center_x + 0.01)
                Center_y = gRandom.Uniform(center_y - 0.01, center_y + 0.01)
                parameters = np.zeros(3 + 4 * npeaks)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                parameters[3] = Center_x - 0.1
                parameters[4] = Center_y + 0.08
                parameters[5] = 0.02
                parameters[6] = 0.02
                parameters[7] = Center_x - 0.04
                parameters[8] = Center_y + 0.08
                parameters[9] = 0.02
                parameters[10] = 0.02
                parameters[11] = Center_x - 0.1
                parameters[12] = Center_y
                parameters[13] = 0.025
                parameters[14] = 0.025
                parameters[15] = Center_x
                parameters[16] = Center_y
                parameters[17] = 0.02
                parameters[18] = 0.02
                parameters[19] = Center_x + 0.1
                parameters[20] = Center_y
                parameters[21] = 0.03
                parameters[22] = 0.03
                parameters[23] = Center_x - 0.04
                parameters[24] = Center_y - 0.06
                parameters[25] = 0.015
                parameters[26] = 0.015
                parameters[27] = Center_x - 0.12
                parameters[28] = Center_y - 0.12
                parameters[29] = 0.03
                parameters[30] = 0.03
                parameters[31] = Center_x + 0.08
                parameters[32] = Center_y - 0.12
                parameters[33] = 0.04
                parameters[34] = 0.04
            else:
                parameters = np.zeros(3 + 4 * npeaks)
                parameters[0] = npeaks
                parameters[1] = bkg
                parameters[2] = peak_height
                for i in range(npeaks):
                    parameters[3 + 4 * i] = gRandom.Uniform(xmin, xmax)
                    parameters[4 + 4 * i] = gRandom.Uniform(ymin, ymax)
                    parameters[5 + 4 * i] = gRandom.Uniform(0.02, 0.07)
                    parameters[6 + 4 * i] = gRandom.Uniform(0.02, 0.07)
            self.MCAttributes['NPeaks'] = npeaks
            return parameters

        def SignalShape(x, par):
            '''

            :param x:   x[0]: x position
                        x[1]: y position
            :param par: par[0]: number of peaks
                        par[1]: mean bkg signal
                        par[2]: peak height in percent of bkg
                        par[3]: peak1 x position
                        par[4]: peak1 y position
                        par[5]: peak1 sigma in x
                        par[6]: peak1 sigma in y
                        ...
                        par[3+4*n]: peakn x position
                        par[4+4*n]: peakn y position
                        par[5+4*n]: peakn sigma in x
                        par[6+4*n]: peakn sigma in y
            :return:
            '''
            norm = par[1] * par[2]
            result = par[1]
            if par[1] == 0:
                norm = 1
            for i in range(int(par[0])):
                result += norm * TMath.Gaus(x[0], par[3 + 4 * i], par[5 + 4 * i]) * TMath.Gaus(x[1], par[4 + 4 * i], par[6 + 4 * i])
            return result

        # Set seed for random number generator:
        today = datetime.today()
        seed = int((today - datetime(today.year, today.month, today.day, 0, 0, 0, 0)).total_seconds() % 1800 * 1e6)
        gRandom.SetSeed(seed)

        # create track_info ROOT file
        if not os.path.exists(MCRunPath):
            os.makedirs(MCRunPath)
        if self.MCAttributes['Save']:
            file = TFile(MCRunPath + 'track_info.root', 'RECREATE')
        self.track_info = TTree('track_info', 'MC track_info')
        track_x = array('f', [0])
        track_y = array('f', [0])
        integral50 = array('f', [0])
        calibflag = array('i', [0])
        calib_offset = array('i', [0])
        time_stamp = array('f', [0])
        self.track_info.Branch('track_x', track_x, 'track_x/F')
        self.track_info.Branch('track_y', track_y, 'track_y/F')
        self.track_info.Branch('integral50', integral50, 'integral50/F')
        self.track_info.Branch('calibflag', calibflag, 'calibflag/I')
        self.track_info.Branch('calib_offset', calib_offset, 'calib_offset/I')
        self.track_info.Branch('time_stamp', time_stamp, 'time_stamp/F')

        # Create Manual Hit Distribution:
        if self.MCAttributes['HitDistributionMode'] == 'Manual':
            dx = 0.08
            dy = 0.07
            f_lateral = TF2('f_lateral', ManualHitDistribution, xmin, xmax, ymin, ymax, 12)
            f_lateral.SetNpx(80)
            f_lateral.SetNpy(80)
            # 6 gaus centers:
            par = np.array([center_x - dx / 2.,  # x1
                            center_y + dy,  # y1
                            center_x + dx / 2.,  # x2
                            center_y + dy,  # y2
                            center_x + dx / 2.,  # x3
                            center_y,  # y3
                            center_x - dx / 2.,  # x4
                            center_y,  # y4
                            center_x - dx / 2.,  # x5
                            center_y - dy,  # y5
                            center_x + dx / 2.,  # x6
                            center_y - dy  # y6
                            ])
            f_lateral.SetParameters(par)
        a = Double()
        b = Double()

        # Generate Signal Distribution:
        if self.MCAttributes['SignalMode'] == 'Landau':
            self.SignalParameters = CreateRandomPeaksConfig(xmin, xmax, ymin, ymax, peak_height=self.MCAttributes['PeakHeight'], bkg=MPV)
        else:
            self.SignalParameters = CreateRandomPeaksConfig(xmin, xmax, ymin, ymax, peak_height=self.MCAttributes['PeakHeight'], bkg=100)
        f_signal = TF2('f_signal', SignalShape, xmin, xmax, ymin, ymax, len(self.SignalParameters))
        f_signal.SetNpx(40)  # Resolution
        f_signal.SetNpy(40)
        f_signal.SetParameters(self.SignalParameters)
        if self.MCAttributes['DrawRealDistribution']:
            canvas = TCanvas('canvas', 'canvas')
            canvas.cd()
            gStyle.SetPalette(55)  # a Rain Bow palette == used.
            gStyle.SetNumberContours(8)
            f_signal.Draw('surf1')
            gPad.Print(MCRunPath + 'RealSignalDistribution.png')
            if self.ShowAndWait:
                answer = input('for data creation, type `yes`: ')
            else:
                answer = 'yes'
        else:
            answer = 'yes'

        # Set the Hit distribution for Manual or Import
        if self.MCAttributes['HitDistributionMode'] == 'Manual':
            HitsTemplate = f_lateral
        elif self.MCAttributes['HitDistributionMode'] == 'Import':
            HitsTemplate = self.counthisto

        mc_start_timestamp = 42.  # arbitrary timestamp for the first MC event
        MCEventDeltaTime = 30. * 60. / 300000.  # 1800s/300000Hits = 0.006s/Hit
        tmp_time = mc_start_timestamp
        # Generate Toy Data:
        if answer == 'yes':
            if self.verbose:
                self.ShowMCConfig()
            self.verbose_print('Creating Toy Data with {0} Hits'.format(self.NumberOfHits))
            integral50_max = self.MCAttributes['integral50_max']  # Maximum of Signal response allowed (data: 500 ?)
            i = 0
            j = 0
            while i < self.NumberOfHits and j < 2 * self.NumberOfHits:
                # Get x and y
                if self.MCAttributes['HitDistributionMode'] == 'Uniform':
                    track_x[0] = gRandom.Uniform(xmin, xmax)
                    track_y[0] = gRandom.Uniform(ymin, ymax)
                else:
                    HitsTemplate.GetRandom2(a, b)
                    track_x[0] = gRandom.Gaus(a, self.MCAttributes['TrackResolution'])  # 0.002 = 20mu track resolution (first guess)
                    track_y[0] = gRandom.Gaus(b, self.MCAttributes['TrackResolution'])

                # Get Signal at x and y
                if self.MCAttributes['SignalMode'] == 'Landau':
                    integral50[0] = gRandom.Landau(f_signal(track_x[0], track_y[0]), sigma)
                else:
                    integral50[0] = gRandom.Gaus(f_signal(track_x[0], track_y[0]), 0.6 * f_signal(track_x[0], track_y[0]) - 33)

                # check if found values fulfill requirements
                if xmin < track_x[0] < xmax and ymin < track_y[0] < ymax and integral50[0] < integral50_max:
                    tmp_time += MCEventDeltaTime
                    time_stamp[0] = tmp_time
                    self.track_info.Fill()
                    self.Data['track_x'].append(track_x[0])
                    self.Data['track_y'].append(track_y[0])
                    self.Data['integral50'].append(integral50[0])
                    i += 1
                j += 1
            if not j < 2 * self.NumberOfHits:  # if too many times requirements were not fulfilled
                assert (False), "Bad MC Parameters"

            # Save root file and true Signal Shape:
            if self.MCAttributes['Save']:
                file.Write()
                f_signal.SaveAs(MCRunPath + 'RealSignalDistribution.root')
                self.verbose_print(MCRunPath + 'track_info.root has been written')
                self.TrackingPadAnalysis['ROOTFile'] = MCRunPath + 'track_info.root'

            # Print Settings of created data:
            if self.verbose:
                print("\nToydata containing {:.0f} peaks generated.".format(self.SignalParameters[0]))
                if self.MCAttributes['SignalMode'] == 'Landau':
                    for i in range(int(self.SignalParameters[0])):
                        x = self.SignalParameters[3 + 4 * i]
                        y = self.SignalParameters[4 + 4 * i]
                        print("Peak {0:.0f} at position: ({1:.3f}/{2:.3f}) with Laundau Response MPV: {3:.2f} Sigma: {4:.1f}".format(i + 1, x, y, f_signal(x, y), sigma))
                else:
                    integral50[0] = gRandom.Gaus(f_signal(track_x[0], track_y[0]), 0.6 * f_signal(track_x[0], track_y[0]) - 33)
                    for i in range(int(self.SignalParameters[0])):
                        x = self.SignalParameters[3 + 4 * i]
                        y = self.SignalParameters[4 + 4 * i]
                        print("Peak {0:.0f} at position: ({1:.3f}/{2:.3f}) with Gaussian Response Mean: {3:.2f} Sigma: {4:.1f}".format(i + 1, x, y, f_signal(x, y), 0.6 * f_signal(x, y) - 33))

            self.DataIsMade = True
            self.verbose_print('Monte Carlo Toy Data created.\n')
#myRandom = TRandom3
#myRandom = gRandom.TRandom
# Initialize random number generator.
gRandom.SetSeed()
ranlux = TRandom3

for n in range(npoints):
    # fill the 2 random numbers into a scatter plot to compare the correlation
    xC = randCon()
    yC = randCon()
    hConguent.Fill(xC, yC)

    # next use the ranlux generator and compare also the 2 random numbers

    xRL = gRandom.Uniform()
    yRL = gRandom.Uniform()
    #xRL = ranlux
    #yRL = ranlux
    hRANLUX.Fill(xRL, yRL)

# Plotting the results

c = TCanvas()
hConguent.Draw()
c.Draw()

d = TCanvas()
hRANLUX.Draw()
d.Draw()
Beispiel #24
0
# Define the number of points to be generated

npoints = 1200000

# Generate npoints of "events"

lnM2min = log((mH-dmH)**2)
lnM2max = log((mH+dmH)**2)
yMin = -dy
yMax = +dy

s1 = s2 = 0
for n in range(npoints):
    #Linear sampling in lnM2 and rapidiyt y
    lnM2 = lnM2min + (lnM2max - lnM2min)*gRandom.Uniform()
    y    = yMin    + (yMax    -    yMin)*gRandom.Uniform()
    m = exp(0.5*lnM2)

    #Get x1 and x2
    x1 = m/(2*Eb) * exp(+y)
    x2 = m/(2*Eb) * exp(-y)

    #if outside of the physical phase space
    if x1 > 1 or x2 > 1:
        continue

    #Weight from linear sampling
    wgt = (lnM2max - lnM2min)*(yMax - yMin)
    
    #gluon PDF
Beispiel #25
0
# Define function which we want to integrate

def g0(z):
    return (1 - z)**5 / z

# The lower limit of the integration, the upper is 1

xmin = 1e-4

# Generate npoints randomly with importance sampling

npoints = 1000000
xg0 = xg00 = 0
for n1 in range(npoints):
    #here do the calculation with importance sampling
    x0 = xmin**gRandom.Uniform()
    weight = x0*log(1/xmin)
    # here do the calculation using linear sampling
    # x0 = xmin+(1-xmin)*gRandom.Uniform()
    # weight = 1-xmin
    f  = g0(x0) 
    ff = weight*f
    xg0  +=  ff
    xg00 +=  ff**2

# Calculate the MC integral

xg0  /= npoints
xg00 /= npoints
sigma2 = xg00 - xg0*xg0
error  = sqrt(sigma2/npoints)
Beispiel #26
0
def get_random_color():
    r, g, b = [gRandom.Uniform(0, 1) for _ in range(3)]
    return ROOT.TColor.GetColor(r, g, b)