Example #1
0
def generate_initial_params(data_bg_mul2, data_bg_mul8, seed=5):

    # fit to the data distributions

    bg_params = Parameters()
    bg_params.add_many(
        ('alpha', -1.80808e+01, True, 1e-20, 20, None, None),
        ('beta', -8.21174e-02, True, -10, -1e-20, None, None),
        ('gamma', 8.06289e-01, True, 1e-20, 10, None, None)
    )

    bg_model = Model(bg_pdf, bg_params)
    bg_fitter = NLLFitter(bg_model)
    bg_result = bg_fitter.fit(data_bg_mul2, calculate_corr=False)

    n_bg = len(data_bg_mul8)

    gRandom.SetSeed(seed)

    # Set up bg sampling
    bg_pdf_ROOT = functools.partial(bg_pdf, doROOT=True)
    tf1_bg_pdf = TF1("tf1_bg_pdf", bg_pdf_ROOT, 2800, 13000, 3)
    tf1_bg_pdf.SetParameters(*bg_result.x)
    mc_bg = [tf1_bg_pdf.GetRandom() for i in range(n_bg)]

    be_bg = bayesian_blocks(mc_bg, p0=0.02)
    be_bg[-1] += 0.1
    be_bg = np.append(be_bg, [13000])
    be_bg[0] = 2800
    # print be_bg
    # hist(data_bg_mul8, bins=be_bg, scale='binwidth')
    # plt.show()

    return bg_result, n_bg, be_bg
Example #2
0
def generate_initial_params(data_bg_mul2, data_bg_mul8, seed=5):

    # fit to the data distributions
    bg_model = ff.Model(bg_pdf, ['alpha', 'beta', 'gamma'])
    bg_model.set_bounds([(1e-20, 20), (-10, -1e-20), (1e-20, 10)])
    bg_fitter = ff.NLLFitter(bg_model, data_bg_mul2)
    bg_result = bg_fitter.fit([-1.80808e+01, -8.21174e-02, 8.06289e-01])
    n_bg = len(data_bg_mul8)

    gRandom.SetSeed(seed)

    # Set up bg sampling
    bg_pdf_ROOT = functools.partial(bg_pdf, doROOT=True)
    tf1_bg_pdf = TF1("tf1_bg_pdf", bg_pdf_ROOT, 2800, 13000, 3)
    tf1_bg_pdf.SetParameters(*bg_result.x)
    mc_bg = [tf1_bg_pdf.GetRandom() for i in range(n_bg)]

    be_bg = bayesian_blocks(mc_bg, p0=0.02)
    be_bg[-1] += 0.1
    be_bg = np.append(be_bg, [13000])
    be_bg[0] = 2800
    # print be_bg
    # hist(data_bg_mul8, bins=be_bg, scale='binwidth')
    # plt.show()

    return bg_result, n_bg, be_bg
Example #3
0
def createhists(procs,binning,nevts):
  """Prepare histograms for simulated data-MC comparison."""
  
  # BINNING
  if len(binning)==3: # constant binning
    nbins, xmin, xmax = binning
  elif len(binning)==1: # variable binning
    nbins = len(binning[0])-1
    binning = (nbins,array('d',list(binning[0])))
  else:
    raise IOError("Wrong binning: %s"%(binning))
  
  # EXPECTED: PSEUDO MC
  exphists = [ ]
  tothist   = None
  gRandom.SetSeed(1777)
  for hname, htitle, scale, generator, args in procs:
    hist = TH1D(hname,htitle,*binning)
    hist.Sumw2()
    for j in xrange(nevts):
      hist.Fill(generator(*args))
    hist.Scale(scale)
    hist.SetFillColor(coldict.get(hname,kWhite))
    exphists.append(hist)
    if tothist:
      tothist.Add(hist)
    else:
      tothist = hist.Clone('total')
  
  # OBSERVED: PSEUDO DATA
  datahist = TH1D('data','Observed',*binning)
  datahist.SetBinErrorOption(TH1D.kPoisson)
  if LOG.verbosity>=1:
    print ">>> createhists: Creating pseudo data:"
    TAB = LOG.table("%5s [%5s, %5s]      %-14s   %-20s",
                    "%5d [%5s, %5s] %8.1f +- %5.1f %8d +%5.1f -%5.1f")
    TAB.printheader('bin','xlow','xup','exp','data')
  for ibin in xrange(0,nbins+2):
    exp    = tothist.GetBinContent(ibin)
    xlow   = hist.GetXaxis().GetBinLowEdge(ibin)
    xup    = hist.GetXaxis().GetBinUpEdge(ibin)
    experr = tothist.GetBinError(ibin)
    #if ibin==int(0.3*nbins): # add a large deviation to test points falling off ratio plot
    #  exp *= 0.5
    #elif ibin==int(0.8*nbins): # add a large deviation to test points falling off ratio plot
    #  exp *= 1.51
    data   = int(gRandom.Poisson(exp))
    datahist.SetBinContent(ibin,data)
    if LOG.verbosity>=1:
      TAB.printrow(ibin,xlow,xup,exp,experr,data,datahist.GetBinErrorUp(ibin),datahist.GetBinErrorLow(ibin))
  
  return datahist, exphists
Example #4
0
def createhists(nhist=3):
  nbins    = 50
  xmin     = 0
  xmax     = 100
  nevts    = 10000
  rrange   = 0.5
  hists    = [ ]
  gRandom.SetSeed(1777)
  for i in xrange(1,nhist+1):
    mu     = 48+i
    sigma  = 10
    hname  = "hist%d"%(i)
    htitle = "#mu = %s, #sigma = %s"%(mu,sigma)
    hist   = TH1D(hname,hname,nbins,xmin,xmax)
    for j in xrange(nevts):
      hist.Fill(gRandom.Gaus(mu,sigma))
    hists.append(hist)
  return hists
Example #5
0
    def __init__(self, parse):

        #energy of electron beam, GeV
        self.Ee = parse.getfloat("main", "Ee")
        #proton beam, GeV
        self.Ep = parse.getfloat("main", "Ep")

        print("Ee =", self.Ee, "GeV")
        print("Ep =", self.Ep, "GeV")

        #minimal photon energy, GeV
        self.emin = parse.getfloat("main", "emin")
        print("emin =", self.emin)

        #electron and proton mass
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()
        self.mp = TDatabasePDG.Instance().GetParticle(2212).Mass()
        self.mep = self.me * self.mp

        #CMS energy squared, GeV^2
        self.s = 2 * self.Ee * self.Ep + self.me**2 + self.mp**2
        self.s += 2 * TMath.Sqrt(self.Ee**2 -
                                 self.me**2) * TMath.Sqrt(self.Ep**2 -
                                                          self.mp**2)
        print("s =", self.s, "GeV^2")

        #normalization,  4 alpha r_e^2
        self.ar2 = 4 * 7.297 * 2.818 * 2.818 * 1e-2  # m barn

        #parametrizations for dSigma/dy and dSigma/dtheta
        gRandom.SetSeed(5572323)
        self.eq1par = self.eq1(self)
        self.dSigDy = TF1("dSigDy", self.eq1par, self.emin / self.Ee, 1)
        tmax = 1.5e-3  #maximal photon angle
        self.eq3par = self.eq3(self)
        self.dSigDtheta = TF1("dSigDtheta", self.eq3par, 0, tmax)

        #uniform generator for azimuthal angles
        self.rand = TRandom3()
        self.rand.SetSeed(5572323)

        print("H1 parametrization initialized")
        print("Total cross section: " +
              str(self.dSigDy.Integral(self.emin / self.Ee, 1)) + " mb")
Example #6
0
    def __init__(self, parse):

        #electron beam, GeV
        self.Ee = parse.getfloat("main", "Ee")
        #proton beam, GeV
        self.Ep = parse.getfloat("main", "Ep")

        print("Ee =", self.Ee, "GeV")
        print("Ep =", self.Ep, "GeV")

        #minimal photon energy, GeV
        self.emin = parse.getfloat("main", "emin")
        print("emin =", self.emin)

        #maximal photon angle
        self.tmax = 1.5e-3
        if parse.has_option("main", "tmax"):
            self.tmax = parse.getfloat("main", "tmax")

        #electron and proton mass
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()
        self.mp = TDatabasePDG.Instance().GetParticle(2212).Mass()
        self.mep = self.me * self.mp

        #normalization,  4 alpha r_e^2
        self.ar2 = 4*7.297*2.818*2.818*1e-2 # m barn

        #parametrizations for dSigma/dE_gamma and dSigma/dtheta
        gRandom.SetSeed(5572323)
        self.eq1par = self.eq1(self)
        self.dSigDe = TF1("dSigDe", self.eq1par, self.emin, self.Ee)

        self.theta_const = 1e-11 # constant term in theta formula
        self.eq2par = self.eq2(self)
        self.dSigDtheta = TF1("dSigDtheta", self.eq2par, 0, self.tmax)

        #uniform generator for azimuthal angles
        self.rand = TRandom3()
        self.rand.SetSeed(5572323)

        print("ZEUS parametrization initialized")
        print("Total cross section: "+str(self.dSigDe.Integral(self.emin, self.Ee))+" mb")
Example #7
0
    hfile.Close()
hfile = TFile('hsimple.root', 'RECREATE', 'Demo ROOT file with histograms')

# Create some histograms, a profile histogram and an ntuple
hpx = TH1F('hpx', 'This is the px distribution', 100, -4, 4)
hpxpy = TH2F('hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4)
hprof = TProfile('hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20)
ntuple = TNtuple('ntuple', 'Demo ntuple', 'px:py:pz:random:i')

# Set canvas/frame attributes.
hpx.SetFillColor(48)

gBenchmark.Start('hsimple')

# Initialize random number generator.
gRandom.SetSeed()
gauss, rndm = gRandom.Gaus, gRandom.Rndm

# For speed, bind and cache the Fill member functions,
histos = ['hpx', 'hpxpy', 'hprof', 'ntuple']
for name in histos:
    exec '%sFill = %s.Fill' % (name, name)

# Fill histograms randomly.
kUPDATE = 1000
for i in xrange(25000):
    # Generate random values.
    px = gauss()
    py = gauss()
    pz = px * px + py * py
    random = rndm(1)
Example #8
0
            be_10GeV[i + 1])
        true_sig_bc_10GeV.append(true_sig * n_sig)

    signif_nll_fit_hist = []
    signif_nll_constrained_hist = []
    signif_nll_true_hist = []
    signif_nll_true_fit_hist = []
    signif_bb_true_hist = []
    signif_bb_shape_hist = []
    signif_1GeV_true_hist = []
    signif_2GeV_true_hist = []
    signif_5GeV_true_hist = []
    signif_10GeV_true_hist = []

    # Do a bunch of toys
    gRandom.SetSeed(20)

    for i in tqdm_notebook(list(range(1000))):
        mc_bg, mc_sig = generate_toy_data(tf1_bg_pdf, tf1_sig_pdf, n_bg, n_sig)
        mc_bg_sig = mc_bg + mc_sig

        q0_nll_fit = generate_q0_via_nll_unbinned(mc_bg_sig)
        signif_nll_fit_hist.append(np.sqrt(q0_nll_fit))

        q0_nll_constrained = generate_q0_via_nll_unbinned_constrained(
            mc_bg, mc_bg_sig, bg_result.x)
        signif_nll_constrained_hist.append(np.sqrt(q0_nll_constrained))

        q0_nll_true = generate_q0_via_nll_unbinned(
            mc_bg_sig,
            bg_params=[-0.957, 0.399, -0.126],
Example #9
0
    be_100GeV = np.linspace(2800, 13000, 103)
    be_200GeV = np.linspace(2800, 13000, 52)
    be_400GeV = np.linspace(2800, 13000, 26)
    be_1000GeV = np.linspace(2800, 13000, 11)
    be_2000GeV = np.linspace(2800, 13000, 6)

    true_bg_bc_bb = get_true_bin_content(be_bg, bg_pdf, bg_result.x)
    true_bg_bc_50GeV = get_true_bin_content(be_50GeV, bg_pdf, bg_result.x)
    true_bg_bc_100GeV = get_true_bin_content(be_100GeV, bg_pdf, bg_result.x)
    true_bg_bc_200GeV = get_true_bin_content(be_200GeV, bg_pdf, bg_result.x)
    true_bg_bc_400GeV = get_true_bin_content(be_400GeV, bg_pdf, bg_result.x)
    true_bg_bc_1000GeV = get_true_bin_content(be_1000GeV, bg_pdf, bg_result.x)
    true_bg_bc_2000GeV = get_true_bin_content(be_2000GeV, bg_pdf, bg_result.x)

    # Do a bunch of toys
    gRandom.SetSeed(seed)

    bg_sig_model = ff.Model(bg_sig_pdf,
                            ['C', 'mu', 'sigma', 'alpha', 'beta', 'gamma'])
    # sig_params = [(4000, 800), (5000, 1000), (6000, 1200), (7000, 1400)]
    # sig_params = [(4750, 970), (5350, 1070), (6000, 1200), (6600, 1300),
    #               (7150, 1440), (7800, 1500), (8380, 1660)]
    sig_params = [(5350, 1070), (6000, 1200), (6600, 1300), (7150, 1440),
                  (7800, 1500), (8380, 1660)]
    # sig_params = [(7150, 1440)]

    unbinned_A_mle = [[] for i in range(len(sig_params))]
    binned_A_mle = [[] for i in range(len(sig_params))]
    binned_A_hybrid_mle = [[] for i in range(len(sig_params))]
    binned_A_50_mle = [[] for i in range(len(sig_params))]
    binned_A_100_mle = [[] for i in range(len(sig_params))]
Example #10
0
    def __init__(self, parse, tree):

        #electron and proton energy, GeV
        self.Ee = parse.getfloat("main", "Ee")
        self.Ep = parse.getfloat("main", "Ep")

        print("Ee, GeV =", self.Ee)
        print("Ep, GeV =", self.Ep)

        #A and Z of the nucleus
        self.A = 1
        self.Z = 1
        if parse.has_option("main", "A"):
            self.A = parse.getint("main", "A")
        if parse.has_option("main", "Z"):
            self.Z = parse.getint("main", "Z")
        print("A:", self.A)
        print("Z:", self.Z)

        #minimal photon energy, GeV
        self.emin = parse.getfloat("main", "emin")
        print("emin, GeV =", self.emin)

        #alpha r_e^2
        self.ar2 = 7.297 * 2.818 * 2.818 * 1e-2  # m barn

        #electron and nucleus mass
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()
        self.mp = TDatabasePDG.Instance().GetParticle(2212).Mass()
        self.mn = self.A * self.mp

        #nucleus beam vector
        nvec = TLorentzVector()
        pz_a = TMath.Sqrt(self.Ep**2 - self.mp**2) * self.Z
        en_a = TMath.Sqrt(pz_a**2 + self.mn**2)
        nvec.SetPxPyPzE(0, 0, pz_a, en_a)
        print("Nucleus beam gamma:", nvec.Gamma())

        #boost vector of nucleus beam
        self.nbvec = nvec.BoostVector()

        #electron beam vector
        evec = TLorentzVector()
        evec.SetPxPyPzE(0, 0, -TMath.Sqrt(self.Ee**2 - self.me**2), self.Ee)
        print("Electron beam gamma:", evec.Gamma())

        #electron beam energy in nucleus beam rest frame
        evec.Boost(-self.nbvec.x(), -self.nbvec.y(), -self.nbvec.z())
        self.Ee_n = evec.E()

        print("Ee_n, GeV:", self.Ee_n)

        #minimal photon energy in nucleus rest frame
        eminv = TLorentzVector()
        eminv.SetPxPyPzE(0, 0, -self.emin, self.emin)
        eminv.Boost(-self.nbvec.x(), -self.nbvec.y(), -self.nbvec.z())
        emin_n = eminv.E()
        print("emin_n, GeV:", emin_n)

        #maximal delta in nucleus frame
        dmax_n = 100.
        if parse.has_option("main", "dmax_n"):
            dmax_n = parse.getfloat("main", "dmax_n")

        print("dmax_n:", dmax_n)

        #cross section formula
        self.eqpar = self.eq(self)
        self.dSigDwDt = TF2("dSigDwDt", self.eqpar, emin_n, self.Ee_n, 0,
                            dmax_n)
        self.dSigDwDt.SetNpx(2000)
        self.dSigDwDt.SetNpy(2000)
        gRandom.SetSeed(5572323)

        #total integrated cross section over all delta (to 1e5)
        dSigInt = TF2("dSigInt", self.eqpar, emin_n, self.Ee_n, 0, 1e5)
        sigma_tot = dSigInt.Integral(emin_n, self.Ee_n, 0, 1e5)

        print("Total cross section, mb:", sigma_tot)

        #uniform generator for azimuthal angles
        self.rand = TRandom3()
        self.rand.SetSeed(5572323)

        #tree output from the generator
        tlist = ["true_phot_w", "true_phot_delta", "true_phot_theta_n"]
        tlist += ["true_phot_theta", "true_phot_phi", "true_phot_E"]
        tlist += ["true_el_theta", "true_el_phi", "true_el_E"]
        self.tree_out = self.set_tree(tree, tlist)

        print("Lifshitz_93p16 parametrization initialized")
Example #11
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')
Example #12
0
#   Authors: H. Jung,
#            A. Bermudez Martinez, L.I. Estevez Banos, J. Lidrych, M. Mendizabal Morentin,
#            S. Taheri Monfared, P. L.S. Connor, Q. Wang, H. Yang, R. Zlebcik
#
# Define function which we want to integrate

from ROOT import gRandom
from math import sqrt


def g0(z):
    return 3 * z * z


# initialise random number generator:
gRandom.SetSeed(32767)

# Calculate the sum and sum2 of the function values at the random points
xg0 = xg00 = 0
npoints = 1000000
for n in range(npoints):
    x0 = gRandom.Uniform()
    f = g0(x0)
    xg0 += f
    xg00 += f**2

# Calculate average and average to the squared values

avg = xg0 / npoints
avg2 = xg00 / npoints
        legendLinearPlot[iPt].SetNColumns(3)
        if cutSetCfg['linearplot']['uncbands']:
            fNfdNpromptUpper.append([])
            fNfdNpromptLower.append([])

    # apply smearing to raw yields
    if doRawYieldsSmearing:
        listRawYield.reverse()
        listRawYieldSmeared = []
        listBkg.reverse()
        listDelta = []
        listDeltaSmeared = []
        listDeltaBkg = []
        listDeltaSmearedBkg = []
        if cutSetCfg['minimisation']['setseed']:
            gRandom.SetSeed(10)
        for iRawYeld, _ in enumerate(listRawYield):
            if iRawYeld == 0:
                listDelta.append(0.)
                listDeltaBkg.append(0.)
            else:
                listDelta.append(listRawYield[iRawYeld] -
                                 listRawYield[iRawYeld - 1])
                listDeltaBkg.append(listBkg[iRawYeld] - listBkg[iRawYeld - 1])
            listDeltaSmeared.append(
                gRandom.PoissonD(listDelta[iRawYeld] + listDeltaBkg[iRawYeld]))
            if cutSetCfg['minimisation']['correlated']:
                if iRawYeld == 0:
                    listRawYieldSmeared.append(
                        gRandom.PoissonD(listRawYield[iRawYeld] +
                                         listBkg[iRawYeld]) -
from ROOT import TCanvas, TFile, TProfile, TNtuple, TH1F, TH2F from ROOT import gROOT, gBenchmark, gRandom, gSystem, Double
# Create a new canvas, and customize it.
c1 = TCanvas( 'c1', 'Dynamic Filling Example', 200, 10, 700, 500 ) c1.SetFillColor( 42 ) c1.GetFrame().SetFillColor( 21 ) 
c1.GetFrame().SetBorderSize( 6 ) c1.GetFrame().SetBorderMode( -1 )
# Create a new ROOT binary machine independent file. Note that this file may contain any kind of ROOT objects, histograms, 
# pictures, graphics objects, detector geometries, tracks, events, etc.. This file is now becoming the current directory.
hfile = gROOT.FindObject( 'py-hsimple.root' ) if hfile:
   hfile.Close() hfile = TFile( 'py-hsimple.root', 'RECREATE', 'Demo ROOT file with histograms' )
# Create some histograms, a profile histogram and an ntuple
hpx = TH1F( 'hpx', 'This is the px distribution', 100, -4, 4 ) hpxpy = TH2F( 'hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4 ) hprof = 
TProfile( 'hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20 ) ntuple = TNtuple( 'ntuple', 'Demo ntuple', 'px:py:pz:random:i' )
# Set canvas/frame attributes.
hpx.SetFillColor( 48 ) gBenchmark.Start( 'hsimple' )
# Initialize random number generator.
gRandom.SetSeed() rannor, rndm = gRandom.Rannor, gRandom.Rndm
# For speed, bind and cache the Fill member functions,
histos = [ 'hpx', 'hpxpy', 'hprof', 'ntuple' ] for name in histos:
   exec('%sFill = %s.Fill' % (name,name))
# Fill histograms randomly.
px, py = Double(), Double() kUPDATE = 1000 for i in range( 25000 ):
 # Generate random values.
   rannor( px, py )
   pz = px*px + py*py
   random = rndm(1)
 # Fill histograms.
   hpx.Fill( px )
   hpxpy.Fill( px, py )
   hprof.Fill( px, pz )
   ntuple.Fill( px, py, pz, random, i )
 # Update display every kUPDATE events.
   if i and i%kUPDATE == 0:
                  dest='seed',
                  type='int',
                  default=0,
                  help='random seed for generating toys.')
parser.add_option('-m',
                  '--mode',
                  default="HWWconfig",
                  dest='modeConfig',
                  help='which config to select from WjjFitterConfigs')
(opts, args) = parser.parse_args()

import generateToyWpJ
from ROOT import gRandom

startingFile = 'TempInitFile.txt'
cpCmd = ['cp', '-v', opts.startingFile, startingFile]
optCmd = [
    'python', 'newOptimize.py', '-b', '-j',
    str(opts.Nj), '-p',
    str(opts.P), '-m', opts.modeConfig, '--init', startingFile, '--dir',
    opts.mcdir
]

print ' '.join(cpCmd)
subprocess.call(cpCmd)
if opts.seed > 0:
    gRandom.SetSeed(opts.seed)
generateToyWpJ.generate(opts.mcdir, opts.Nj, opts.modeConfig)
print ' '.join(optCmd)
subprocess.call(optCmd)
Example #16
0
neutrino_global_normalisation = 0.
for neutrino_name in neutrino_names_list:
    neutrino_spectra_dict[neutrino_name] = TH2D(
        neutrino_spectra_file.Get(neutrino_name))
    neutrino_type_threshold[
        neutrino_name] = neutrino_global_normalisation + neutrino_spectra_dict[
            neutrino_name].GetSum()
    neutrino_global_normalisation += neutrino_spectra_dict[
        neutrino_name].GetSum()

print(toolbox.warning, "Opening file containing PREM function :",
      parameters["PREM_file"])
PREM_file = TFile.Open(parameters["PREM_file"], "READ")
PREM_TF1 = TF1(PREM_file.Get("PREM_TF1"))

gRandom.SetSeed(
    parameters["PRNG_seed"])  # set the generator seed for TH2D.GetRandom2

variables_names_list = list()

# saved variables
variables_names_list.append("PDG_code")  # sampled by the norm of each spectrum
variables_names_list.append("E_nu")  # sampled by the spectrum

variables_names_list.append(
    "R_Earth_emitted")  # determined by neutrino_altitude and earth radius
variables_names_list.append("R_SK_emitted")  # computed

variables_names_list.append("cos_theta_SK")  # sampled by the spectrum
variables_names_list.append("cos_theta_Earth")  # computed

variables_names_list.append("phi")  # sampled