Ejemplo n.º 1
0
    def __init__(self):

        #interaction cross section, mb
        self.sigma_tot = 0.

        #instantaneous luminosity, cm^-2 sec^-1
        self.lumi_cmsec = 0.

        #number of bunches
        self.nbunch = 0.

        #electron beam energy, GeV
        self.Ee = 0.

        #coincidence selection
        self.emin = 1.  # GeV

        #collider circumference, speed of light, electron mass
        self.circ = 3834.  # m
        self.cspeed = 299792458.  # m sec^-1
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()  # GeV

        #input
        self.tree = TChain("DetectorTree")

        #geometry
        self.geo = None

        #output file name
        self.outfile = "hits_spect.root"
Ejemplo n.º 2
0
    def __init__(self,
                 funcName,
                 minMass,
                 maxMass,
                 numSigmaSideBands=0.,
                 peakMass=0.,
                 peakSigma=0.,
                 secPeakMass=0.,
                 secPeakSigma=0.):
        if funcName not in self.__implFunc:
            raise ValueError(f'Function \'{funcName}\' not implemented')
        self.funcName = funcName
        self.minMass = minMass
        self.maxMass = maxMass
        self.peakMass = peakMass
        self.peakDelta = peakSigma * numSigmaSideBands
        self.secPeakMass = secPeakMass
        self.secPeakDelta = secPeakSigma * numSigmaSideBands
        self.funcSBCallable = None
        self.funcFullCallable = None

        self.removePeak = False
        self.removeSecPeak = False
        if self.peakMass > 0. and self.peakDelta > 0.:
            self.removePeak = True
        if self.secPeakMass > 0. and self.secPeakDelta > 0.:
            self.removeSecPeak = True

        self.mPi = TDatabasePDG.Instance().GetParticle(211).Mass()
Ejemplo n.º 3
0
 def decayTree(self, genparticles):
   db = TDatabasePDG()
   theString = ""
   for part in genparticles:
     if part.M1==-1 and part.M2==-1:
       theString += part.printDecay(db, genparticles)
   return theString
Ejemplo n.º 4
0
    def __init__(self, parse, tree, hepmc_attrib):

        #minumum and maximum energy, GeV
        self.emin = parse.getfloat("main", "emin")
        self.emax = parse.getfloat("main", "emax")
        print("emin =", self.emin)
        print("emax =", self.emax)

        #pdg for generated particle, electron or photon
        self.pdg = 22
        if parse.has_option("main", "pdg"):
            self.pdg = parse.getint("main", "pdg")

        print("pdg =", self.pdg)

        #angular range, electrons for now
        self.theta_min = 0.
        self.theta_max = 0.

        #angles as mlt = -log_10(pi - theta)
        if parse.has_option("main", "mlt_min"):
            mlt_min = parse.getfloat("main", "mlt_min")
            mlt_max = parse.getfloat("main", "mlt_max")
            print("mlt_min =", mlt_min)
            print("mlt_max =", mlt_max)
            self.theta_min = TMath.Pi() - 10.**(-mlt_min)
            self.theta_max = TMath.Pi() - 10.**(-mlt_max)

        print("theta_min =", self.theta_min)
        print("theta_max =", self.theta_max)

        #generator functions for photons and electrons
        self.gen_func = {}
        self.gen_func[22] = self.gen_phot
        self.gen_func[11] = self.gen_el

        #test for pdg
        if self.gen_func.get(self.pdg) is None:
            print("Fatal: pdg", self.pdg, "is not supported")
            raise KeyError

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

        #electron mass
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()

        #set the output tree
        if self.pdg == 22:
            tnam = ["gen_E"]
        if self.pdg == 11:
            tnam = ["true_el_pT", "true_el_theta", "true_el_phi", "true_el_E"]
        self.out = self.make_tree(tree, tnam)

        #event attributes for hepmc
        self.hepmc_attrib = hepmc_attrib

        print("Uniform generator initialized")
Ejemplo n.º 5
0
    def __init__(self, filename, exclude_noise, save_plot, max_spill_count):
        self.filename = filename
        self.exclude_noise = exclude_noise
        self.save_plot = save_plot
        self.data_dir = os.path.dirname(self.filename)
        if not self.data_dir:
            self.data_dir = '.'
        self.file_basename = os.path.basename(self.filename)
        self.max_spill_count = max_spill_count

        self.pdg = TDatabasePDG()
        self.delta_x = 1.4  # mm
        self.delta_y = 8.6  # mm
        self.delta_z = 0.  # mm
        # self.delta_x = 1375.9  # mm
        # self.delta_y = -67.5  # mm
        # self.delta_z = -14617.4  # mm
        self.angle_rotation_y_axis = -0.349 * pi / 180.  # rad
Ejemplo n.º 6
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")
Ejemplo n.º 7
0
def get_scale(Ni):

    #scale for event rate in Hz per one simulated interaction
    #Ni is number of simulated interactions

    #interaction cross section, mb
    sigma_tot = 171.29  # 18x275
    #sigma_tot = 123.83 # 10x100
    #sigma_tot = 79.18 # 5x41

    #instantaneous luminosity, cm^-2 sec^-1
    lumi_cmsec = 1.54e33  # 18x275
    #lumi_cmsec = 4.48e33 # 10x100
    #lumi_cmsec = 0.44e33 # 5x41

    #number of bunches
    nbunch = 290  # 18x275
    #nbunch = 1160 # 10x100
    #nbunch = 1160 # 5x41

    #electron beam energy, GeV
    #Ee = 18. # GeV
    #Ee = 10. # GeV
    Ee = 5.  # GeV

    #collider circumference, speed of light, electron mass
    circ = 3834.  # m
    cspeed = 299792458.  # m sec^-1
    me = TDatabasePDG.Instance().GetParticle(11).Mass()  # GeV

    #beam velocity (units of c)
    beta = np.sqrt(Ee**2 - me**2) / Ee
    print("Beta:", beta)
    print("Orbit period (micro sec):", 1e6 * circ / (beta * cspeed))

    #bunch spacing, sec
    Tb = circ / (beta * cspeed * nbunch)
    print("Bunch spacing (micro sec):", 1e6 * Tb)
    print("Bunch frequency (MHz):", 1e-6 / Tb)

    #luminosity per bunch crossing, mb^-1
    Lb = lumi_cmsec * 1e-27 * Tb
    print("Luminosity per bunch crossing, mb^-1:", Lb)
    print("Mean number of interactions per bunch crossing:", sigma_tot * Lb)
    print("Probability for at least one interaction in bunch crossing:",
          (1. - np.e**(-sigma_tot * Lb)))

    scale = {}
    scale["lambda"] = sigma_tot * Lb
    scale["Tb"] = Tb  # sec

    #rate per one simulated interaction, Hz
    #return (1./Ni)*sigma_tot*1e-27*lumi_cmsec

    return scale
Ejemplo n.º 8
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")
Ejemplo n.º 9
0
    def __init__(self, en, pdg, zsign):
        #energy, pdg, sign of z-momentum

        particle.__init__(self, pdg)
        self.pdg = pdg
        #status code for beam particles
        self.stat = 201
        #set kinematics for beam particle
        m = TDatabasePDG.Instance().GetParticle(pdg).Mass()
        pz = zsign * sqrt(en**2 - m**2)
        self.vec.SetPxPyPzE(0, 0, pz, en)
Ejemplo n.º 10
0
    def get_s(self, Ee, Ep):

        #calculate the CMS squared s

        #proton mass
        mp = TDatabasePDG.Instance().GetParticle(2212).Mass()

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

        #print "sqrt(s):", TMath.Sqrt(s)

        return s
Ejemplo n.º 11
0
    def __init__(self, en, theta, phi):
        particle.__init__(self, 11)

        #transverse momentum
        m = TDatabasePDG.Instance().GetParticle(11).Mass()
        pt = sqrt(0.5 * (en**2 - m**2) * (1. - cos(2. * theta)))

        #pseudorapidity, rotate the theta for pz negative
        theta = pi - theta
        eta = -log(tan(theta / 2.))

        #set the electron Lorentz vector
        self.vec.SetPtEtaPhiE(pt, eta, phi, en)

        #status for the final particle
        self.stat = 1
Ejemplo n.º 12
0
def q2_calc_vec_from_kine(en, theta, phi):

    #create Lorentz vector from electron kinematics loaded from the tree

    #transverse momentum
    m = TDatabasePDG.Instance().GetParticle(11).Mass()
    pt = sqrt(0.5 * (en**2 - m**2) * (1. - cos(2. * theta)))

    #pseudorapidity
    eta = -log(tan(theta / 2.))

    #set the Lorentz vector
    vec = TLorentzVector()
    vec.SetPtEtaPhiE(pt, eta, phi, en)

    return vec
Ejemplo n.º 13
0
    def __init__(self, parse):

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

        #energy spread from input relative energy spread
        self.espread = None
        if parse.has_option("main", "espread"):
            sig_e = self.Ee * parse.getfloat("main", "espread")
            self.espread = TF1("espread", "gaus", -12 * sig_e, 12 * sig_e)
            self.espread.SetParameters(1, 0, sig_e)

        #electron mass
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()

        print("Electron beam initialized")
Ejemplo n.º 14
0
 def __init__(self, pdg):
     #particle Lorentz vector
     self.vec = TLorentzVector()
     #index in particle list
     self.idx = 0
     #status code
     self.stat = 0
     #pdg code
     self.pdg = pdg
     #particle database for pass and codes
     self.pdgdat = TDatabasePDG.Instance()
     #mass, GeV
     self.mass = self.pdgdat.GetParticle(self.pdg).Mass()
     #parent particle id
     self.parent_id = 0
     #vertex coordinates, mm
     self.vx = 0.
     self.vy = 0.
     self.vz = 0.
     #precision for momentum and energy
     self.pxyze_prec = 6
Ejemplo n.º 15
0
# result_1Bn_ecut_5.root  		1E9 with Ecut > 5 GeV
# result_0.1Bn_ecut_0.5.root         	1E8 with Ecut > 0.5 GeV
Yandex = False  # False
Yandex2 = False  # summer 2015 production, 10B, Ecut>10GeV, Mo/W/ target
Yandex3 = True  # spring 2016 production, 10B, Ecut>10GeV, Mo/W/ target, record start of track
afterHadronAbsorber = False
JPsi = False  # True
MoTarget = False
Tau = False

import ROOT, os
from array import array
from ROOT import TDatabasePDG, TMath, gDirectory
from rootUtils import *

pdg = TDatabasePDG()
mu = pdg.GetParticle(13)
Mmu = mu.Mass()
Mmu2 = Mmu * Mmu

if Yandex:
    stats = {5.: [1E9, 1E9], 0.5: [1E8]}
    files = {
        5.: [
            '$SHIPSOFT/data/result_1Bn_ecut_5.root',
            '$SHIPSOFT/data/result_1Bn_ecut_5-v02.root'
        ],
        0.5: ['$SHIPSOFT/data/result_0.1Bn_ecut_0.5.root']
    }
    fnew = 'pythia8_Geant4_total_Yandex.root'
if Yandex2:
Ejemplo n.º 16
0
def main():

    #input
    inp = TFile.Open("pC.root")
    tree = inp.Get("DetectorTree")

    #input generated particles
    gen_pdg = std.vector(int)()
    gen_en = std.vector(float)()
    tree.SetBranchAddress("gen_pdg", gen_pdg)
    tree.SetBranchAddress("gen_en", gen_en)

    #layer hits
    lay10_hit_edep = std.vector(float)()
    lay11_hit_edep = std.vector(float)()
    lay12_hit_edep = std.vector(float)()
    lay13_hit_edep = std.vector(float)()
    lay20_hit_edep = std.vector(float)()
    lay21_hit_edep = std.vector(float)()
    lay22_hit_edep = std.vector(float)()
    lay23_hit_edep = std.vector(float)()
    tree.SetBranchAddress("lay10_HitEdep", lay10_hit_edep)
    tree.SetBranchAddress("lay11_HitEdep", lay11_hit_edep)
    tree.SetBranchAddress("lay12_HitEdep", lay12_hit_edep)
    tree.SetBranchAddress("lay13_HitEdep", lay13_hit_edep)
    tree.SetBranchAddress("lay20_HitEdep", lay20_hit_edep)
    tree.SetBranchAddress("lay21_HitEdep", lay21_hit_edep)
    tree.SetBranchAddress("lay22_HitEdep", lay22_hit_edep)
    tree.SetBranchAddress("lay23_HitEdep", lay23_hit_edep)

    #output
    out = TFile("events.root", "recreate")
    otree = TTree("event", "event")
    ekin = c_float(0)
    lay10_edep = c_float(0)
    lay11_edep = c_float(0)
    lay12_edep = c_float(0)
    lay13_edep = c_float(0)
    lay20_edep = c_float(0)
    lay21_edep = c_float(0)
    lay22_edep = c_float(0)
    lay23_edep = c_float(0)
    otree.Branch("ekin", ekin, "ekin/F") # kinetic energy, MeV
    otree.Branch("lay10_edep", lay10_edep, "lay10_edep/F") # deposited energy, MeV
    otree.Branch("lay11_edep", lay11_edep, "lay11_edep/F")
    otree.Branch("lay12_edep", lay12_edep, "lay12_edep/F")
    otree.Branch("lay13_edep", lay13_edep, "lay13_edep/F")
    otree.Branch("lay20_edep", lay20_edep, "lay20_edep/F")
    otree.Branch("lay21_edep", lay21_edep, "lay21_edep/F")
    otree.Branch("lay22_edep", lay22_edep, "lay22_edep/F")
    otree.Branch("lay21_edep", lay23_edep, "lay23_edep/F")

    #number of events
    nev = tree.GetEntries()
    #nev = 100000

    #event loop
    for iev in range(nev):
        tree.GetEntry(iev)

        if iev%100000 == 0:
            print("Event: ", iev)

        #deposited energy, MeV
        lay10_edep.value = 0.
        lay11_edep.value = 0.
        lay12_edep.value = 0.
        lay13_edep.value = 0.
        lay20_edep.value = 0.
        lay21_edep.value = 0.
        lay22_edep.value = 0.
        lay23_edep.value = 0.

        #hit loops for layers
        nhit = 0
        nhit += get_edep_lay(lay10_hit_edep, lay10_edep)
        nhit += get_edep_lay(lay11_hit_edep, lay11_edep)
        nhit += get_edep_lay(lay12_hit_edep, lay12_edep)
        nhit += get_edep_lay(lay13_hit_edep, lay13_edep)
        nhit += get_edep_lay(lay20_hit_edep, lay20_edep)
        nhit += get_edep_lay(lay21_hit_edep, lay21_edep)
        nhit += get_edep_lay(lay22_hit_edep, lay22_edep)
        nhit += get_edep_lay(lay23_hit_edep, lay23_edep)

        #events with hits
        if nhit <= 0:
            continue

        #generated kinetic energy, MeV
        egen = gen_en.at(0)
        mass = TDatabasePDG.Instance().GetParticle(gen_pdg.at(0)).Mass()
        ekin.value = (egen-mass)*1e3 # MeV 

        #fill the output tree
        otree.Fill()

    #finish
    otree.Write()
    out.Close()
def comp_fit_pars(do_ratio=False, meson='Ds'): #pylint: disable-msg=too-many-statements,too-many-locals
    inputdir = '../../AnalysisNonPromptDpp2017/Dplus/outputs/rawyields'
    input_files = ['RawYieldsDplus_pp5TeV_prompt_central.root', 'RawYieldsDplus_pp5TeV_FD_central_freesigma.root']
    input_files_MC = ['RawYieldsDplusMC_pp5TeV_prompt_central.root', 'RawYieldsDplusMC_pp5TeV_FD_central.root']
    colors = [kOrange+7, kAzure+2, kRed+1, kAzure+4]
    markers = [kOpenCircle, kOpenSquare, kFullCircle, kFullSquare]
    legendnames = ['MC - prompt enhanced', 'MC - FD enhanced', 'data - prompt enhanced', 'data - FD enhanced']
    suffix = 'CompMCData'
    min_pt = 2.
    max_pt = 16.

    SetGlobalStyle(padleftmargin=0.18, padtopmargin=0.05, padbottommargin=0.14,
                   titleoffsety=1.6, titlesize=0.045, labelsize=0.04)
    hMean, hSigma = [], []
    input_files = input_files_MC + input_files

    if meson == 'Ds':
        massD = TDatabasePDG.Instance().GetParticle(431).Mass()
    elif meson == 'Dplus':
        massD = TDatabasePDG.Instance().GetParticle(411).Mass()

    lineMass = TLine(min_pt, massD, max_pt, massD)
    lineMass.SetLineWidth(2)
    lineMass.SetLineColor(kBlack)
    lineMass.SetLineStyle(9)

    legSigma = TLegend(0.2, 0.78, 0.8, 0.93)
    legSigma.SetFillStyle(0)
    legSigma.SetBorderSize(0)
    legSigma.SetTextSize(0.04)

    legMean = TLegend(0.4, 0.73, 0.7, 0.93)
    legMean.SetFillStyle(0)
    legMean.SetBorderSize(0)
    legMean.SetTextSize(0.04)
    legMean.AddEntry(lineMass, "PDG", 'l')

    for file_path, color, marker, legend_name in zip(input_files, colors, markers, legendnames):
        input_file = TFile(f'{inputdir}/{file_path}')
        histo_mean = input_file.Get('hRawYieldsMean')
        histo_sigma = input_file.Get('hRawYieldsSigma')
        histo_mean.SetDirectory(0)
        histo_sigma.SetDirectory(0)
        SetObjectStyle(histo_mean, linecolor=color, markercolor=color, markerstyle=marker)
        SetObjectStyle(histo_sigma, linecolor=color, markercolor=color, markerstyle=marker)
        legMean.AddEntry(histo_mean, legend_name, 'p')
        legSigma.AddEntry(histo_sigma, legend_name, 'p')
        hMean.append(histo_mean)
        hSigma.append(histo_sigma)

    if do_ratio:
        mean_num_list = list(hMean)
        mean_num_list.pop(0)
        mean_den_hist = hMean[0]
        mean_ratio_list = []
        for histo in mean_num_list:
            mean_ratio_list.append(ComputeRatioDiffBins(histo, mean_den_hist))
        cMeanRatio = TCanvas('cMeanRatio', '', 800, 800)
        cMeanRatio.DrawFrame(min_pt, 0.99, max_pt, 1.01, ';#it{p}_{T} (GeV/#it{c}); peak mean / peak mean MC')
        lineRatio = TLine(min_pt, 1., max_pt, 1.)
        lineRatio.SetLineWidth(2)
        lineRatio.SetLineColor(kBlack)
        lineRatio.SetLineStyle(9)
        legMeanRatio = TLegend(0.4, 0.73, 0.7, 0.93)
        legMeanRatio.SetFillStyle(0)
        legMeanRatio.SetBorderSize(0)
        legMeanRatio.SetTextSize(0.04)
        for hist, color, marker, legend_name in zip(mean_ratio_list, colors[1:],
                                                    markers[1:], legendnames[1:]):
            SetObjectStyle(hist, linecolor=color, markercolor=color, markerstyle=marker)
            hist.Draw('same')
            legMeanRatio.AddEntry(hist, legend_name, 'p')
        lineRatio.Draw()
        legMeanRatio.Draw()

        sigma_num_list = list(hSigma)
        sigma_num_list.pop(0)
        sigma_den_hist = hSigma[0]
        sigma_ratio_list = []
        for histo in sigma_num_list:
            sigma_ratio_list.append(ComputeRatioDiffBins(histo, sigma_den_hist))
        cSigmaRatio = TCanvas('cSigmaRatio', '', 800, 800)
        hFrameSigma = cSigmaRatio.DrawFrame(min_pt, 0.6, max_pt, 1.8,
                                            ';#it{p}_{T} (GeV/#it{c}); peak width / peak width MC')
        hFrameSigma.GetYaxis().SetDecimals()
        legSigmaRatio = TLegend(0.4, 0.73, 0.7, 0.93)
        legSigmaRatio.SetFillStyle(0)
        legSigmaRatio.SetBorderSize(0)
        legSigmaRatio.SetTextSize(0.04)
        for hist, color, marker, legend_name in zip(sigma_ratio_list, colors[1:],
                                                    markers[1:], legendnames[1:]):
            SetObjectStyle(hist, linecolor=color, markercolor=color, markerstyle=marker)
            hist.Draw('same')
            legSigmaRatio.AddEntry(hist, legend_name, 'p')
        lineRatio.Draw()
        legSigmaRatio.Draw()
        cMeanRatio.SaveAs(f'{inputdir}/MeanRatio_{suffix}.pdf')
        cSigmaRatio.SaveAs(f'{inputdir}/SigmaRatio_{suffix}.pdf')

    cMean = TCanvas('cMean', '', 800, 800)
    hFrameMean = cMean.DrawFrame(min_pt, massD*0.995, max_pt, massD*1.01,
                                 ';#it{p}_{T} (GeV/#it{c}); peak mean (GeV/#it{c}^{2})')
    hFrameMean.GetYaxis().SetDecimals()
    lineMass.Draw("same")
    for histo_mean in hMean:
        histo_mean.Draw('same')
    legMean.Draw()

    cSigma = TCanvas('cSigma', '', 800, 800)
    cSigma.DrawFrame(min_pt, 0., max_pt, 0.025, ';#it{p}_{T} (GeV/#it{c}); peak width (GeV/#it{c}^{2})')
    for histo_sigma in hSigma:
        histo_sigma.Draw('same')
    legSigma.Draw()

    cMean.SaveAs(f'{inputdir}/Mean_{suffix}.pdf')
    cSigma.SaveAs(f'{inputdir}/Sigma_{suffix}.pdf')
    input('Press enter to exit')
    def print_evt(event_filter=">= 0"):
        pdg_db = TDatabasePDG()
        ev_df = df.Filter(f"fIndexMcCollisions {event_filter}")
        npy = ev_df.AsNumpy()
        print()
        lastmother = 0
        for i, part_index in enumerate(npy["part_index"]):
            ev = npy["fIndexMcCollisions"][i]
            count("events", ev)
            if 0:
                m0 = npy["fMother0"][i]
                m1 = npy["fMother1"][i]
                d0 = npy["fDaughter0"][i]
                d1 = npy["fDaughter1"][i]
            else:
                m_arr = npy["fIndexArray_Mothers"][i]
                d_arr = npy["fIndexSlice_Daughters"][i]
                m_size = npy["fIndexArray_Mothers_size"][i]
                # print(m_size)
                # print("Mothers", m_arr)
                # print("Daughters", d_arr)

                if len(m_arr) == 0:
                    m0 = -1
                    m1 = -1
                else:
                    m0 = m_arr[0]
                    m1 = m_arr[int(m_size) - 1]
                d0 = d_arr[0]
                d1 = d_arr[1]
                # print(d_arr)
            pdg = npy["fPdgCode"][i]
            px = npy["fPx"][i]
            py = npy["fPy"][i]
            pz = npy["fPz"][i]
            eta = npy["eta"][i]
            is_ps = bool(npy["isPhysicalPrimary"][i])
            is_pt = bool(npy["isProducedByTransport"][i])
            process = npy["fStatusCode"][i]

            def getpname(pdg_code):
                p = pdg_db.GetParticle(int(pdg_code))
                if p:
                    p = p.GetName()
                else:
                    p = "Undef"
                return p

            part = getpname(pdg)
            summary_line = f"  ({part_index}) ev {ev} m0 {m0} m1 {m1}, d0 {d0} d1 {d1}, pdg {pdg} '{part}', physical primary {is_ps}, in transport {is_pt}, process {process}"
            if abs(pdg) not in [21, 2101, 2103, 2203, 1, 2, 3, 4, 5
                                ] and m0 > -1:
                if lastmother != m0 and count("mothers", m0):
                    raise ValueError("Duplicate mothers for ", summary_line)
            lastmother = m0
            if d1 > -1 and d0 > d1:
                if not continue_on_inconsistency:
                    raise ValueError("d0 > d1:", summary_line)
                else:
                    warning_msg("d0 > d1 for", part_index)

            def get_the_daughters():
                idaughters = []
                if d0 > -1 and d1 > -1:
                    for j in range(d0, d1 + 1):
                        entry = numpy.where(npy["part_index"] == j)[0]
                        if len(entry) > 1:
                            raise ValueError("Entry size is too high!")
                        if len(entry) == 0:
                            raise ValueError("Entry size is too low!")
                        entry = entry[0]
                        if 0:
                            d_m0 = npy["fMother0"][entry]
                            d_m1 = npy["fMother1"][entry]
                        else:
                            d_m0 = npy["fIndexArray_Mothers"][entry][0]
                            d_m1 = npy["fIndexArray_Mothers"][entry][
                                int(npy["fIndexArray_Mothers_size"][entry]) -
                                1]

                        if d_m0 != part_index and d_m1 != part_index:
                            if not continue_on_inconsistency:
                                raise ValueError("Daughter", j,
                                                 "has a different mother!",
                                                 "d_m0", d_m0, "d_m1", d_m1,
                                                 "w.r.t.", part_index)
                            else:
                                warning_msg("Daughter", j,
                                            "has a different mother!", "d_m0",
                                            d_m0, "d_m1", d_m1, "w.r.t.",
                                            part_index)
                        if d_m0 == d_m1 and 0:
                            raise ValueError("Daughter has same mother!", d_m0,
                                             d_m1)
                        idaughters.append(entry)
                if len(idaughters) == 0:
                    warning_msg("Found no daughters")
                    return idaughters
                # Checking that indices are increasing
                if sorted(idaughters) != idaughters:
                    raise ValueError("Daughters are not in order!")
                # Checking that indices have no holes
                if idaughters != [*range(idaughters[0], idaughters[-1] + 1)]:
                    raise ValueError("Daughters have hole in indices!",
                                     idaughters)
                return idaughters

            def daughters_pxpypz(daughters):
                d_px = 0
                d_py = 0
                d_pz = 0
                if len(daughters) == 0:
                    return None
                for j in daughters:
                    d_px += npy["fPx"][j]
                    d_py += npy["fPy"][j]
                    d_pz += npy["fPz"][j]
                return d_px, d_py, d_pz

            def daughters_pdg(daughters):
                d_pdgs = []
                for j in daughters:
                    d_pdgs.append(npy["fPdgCode"][j])
                return d_pdgs

            def check_momentum(daughters):
                d_p = daughters_pxpypz(daughters)
                if d_p is None:
                    return
                m_p = [px, py, pz]
                m_p_d = {0: "Px", 1: "Py", 2: "Pz"}
                momentum_format = "(px={:.5f}, py={:.5f}, pz={:.5f})"
                for j in enumerate(m_p):
                    if abs(j[1] - d_p[j[0]]) > 0.001:
                        e_msg = [
                            "Non-closure in", m_p_d[j[0]], "=",
                            momentum_format.format(*d_p)
                        ]
                        if not continue_on_inconsistency:
                            raise ValueError(*e_msg)
                        else:
                            warning_msg(*e_msg)
                            warning_msg("           mother =",
                                        momentum_format.format(*m_p))

            def is_decay_channel(desired_pdg_codes,
                                 daughters,
                                 fill_counter=True,
                                 min_prongs=0,
                                 max_prongs=10):
                d_pdgs = daughters_pdg(daughters)
                if len(daughters) >= min_prongs and len(
                        daughters) <= max_prongs:
                    print(pdg, part, "decaying in", len(d_pdgs), "particles")
                    for i, j in enumerate(d_pdgs):
                        if 0:
                            this_m0 = npy["fMother0"][daughters[i]]
                            this_m1 = npy["fMother1"][daughters[i]]
                        else:
                            this_m0 = npy["fIndexArray_Mothers"][
                                daughters[i]][0]
                            this_m1 = npy["fIndexArray_Mothers"][daughters[i]][
                                int(npy["fIndexArray_Mothers_size"][
                                    daughters[i]]) - 1]

                        print(" >", j, getpname(j), "index", daughters[i],
                              npy["part_index"][daughters[i]], "m0", this_m0,
                              "m1", this_m1, " -> physical primary",
                              npy["isPhysicalPrimary"][daughters[i]])
                if desired_pdg_codes is not None:
                    for i in desired_pdg_codes:
                        if i not in d_pdgs:
                            return False
                if fill_counter:
                    count(
                        f"{bcolors.BOKGREEN} {pdg} {part} {bcolors.ENDC} in {d_pdgs}",
                        part_index)
                return True

            extra = []
            if m0 < 0 and m1 < 0 and d0 < 1 and d1 < 0:
                extra.append("Sterile")
            if d1 < 0 and d1 != d0:
                extra.append(bcolors.BWARNING + "Problematic" + bcolors.ENDC)
            if pdg in pdg_of_interest:
                extra.append(", px={:.3f} py={:.2f} pz={:.2f}".format(
                    px, py, pz))
                extra.append(", eta={:.4f}".format(eta))
                extra.append(bcolors.BOKGREEN + "PDG of interest" +
                             bcolors.ENDC)
            extra = " ".join(extra)
            extra = extra.strip()

            count(part, part_index)
            if verbose or pdg in pdg_of_interest:
                print(summary_line, extra)
            if pdg in pdg_of_interest:
                daughters = get_the_daughters()
                check_momentum(daughters)
                is_decay_channel(None, daughters=daughters, fill_counter=True)
Ejemplo n.º 19
0
"""
This module contains names for the various PDG particle ID codes.
The names are the same as in EventKernel/PdtPdg.h.

This module also contains a dictionary pdgid_names mapping ID codes
back to printable strings, and a function pdgid_to_name to do this
conversion.  Similarly, root_names and pdgid_to_root_name translate to
strings with root markup.
"""
from __future__ import absolute_import

from ROOT import TDatabasePDG
from pkg_resources import resource_filename
import os

db = TDatabasePDG()
db.ReadPDGTable(resource_filename('rootpy', 'etc/pdg_table.txt'))


def GetParticle(id):
    return db.GetParticle(id)


# Table to translate from PDG IDs to printable strings.
pdgid_names = {}

# Table to translate from PDG IDs to strings with root markup.
root_names = {}


def id_to_name(id):
Ejemplo n.º 20
0
             ptBinsArr))
    SetObjectStyle(hRawYieldsSignalDiffSigma[iS],
                   color=kBlack,
                   markerstyle=kFullCircle)
    SetObjectStyle(hRawYieldsBkgDiffSigma[iS],
                   color=kBlack,
                   markerstyle=kFullCircle)
    SetObjectStyle(hRawYieldsSoverBDiffSigma[iS],
                   color=kBlack,
                   markerstyle=kFullCircle)
    SetObjectStyle(hRawYieldsSignifDiffSigma[iS],
                   color=kBlack,
                   markerstyle=kFullCircle)

# fit histos
massDplus = TDatabasePDG.Instance().GetParticle(411).Mass()
massDs = TDatabasePDG.Instance().GetParticle(431).Mass()
massLc = TDatabasePDG.Instance().GetParticle(4122).Mass()
massDstar = TDatabasePDG.Instance().GetParticle(
    413).Mass() - TDatabasePDG.Instance().GetParticle(421).Mass()
massD0 = TDatabasePDG.Instance().GetParticle(421).Mass()

if particleName == 'Dplus':
    massForFit = massDplus
elif particleName == 'Ds':
    massForFit = massDs
elif particleName == 'Dstar':
    massForFit = massDstar
elif particleName == 'D0':
    massForFit = massD0
else:
Ejemplo n.º 21
0
class EventGenerator:
    EVENT_TIME_DURATION = 50.e3  # ns, 50 us per event

    def __init__(self, filename, exclude_noise, save_plot, max_spill_count):
        self.filename = filename
        self.exclude_noise = exclude_noise
        self.save_plot = save_plot
        self.data_dir = os.path.dirname(self.filename)
        if not self.data_dir:
            self.data_dir = '.'
        self.file_basename = os.path.basename(self.filename)
        self.max_spill_count = max_spill_count

        self.pdg = TDatabasePDG()
        self.delta_x = 1.4  # mm
        self.delta_y = 8.6  # mm
        self.delta_z = 0.  # mm
        # self.delta_x = 1375.9  # mm
        # self.delta_y = -67.5  # mm
        # self.delta_z = -14617.4  # mm
        self.angle_rotation_y_axis = -0.349 * pi / 180.  # rad

    def rotate_y_axis(self, z, x):
        # angle > 0 if the coordinate system rotates counterclockwise
        # angle < 0 if the coordinate system rotates clockwise
        z_prime = cos(self.angle_rotation_y_axis) * z + sin(
            self.angle_rotation_y_axis) * x
        x_prime = -sin(self.angle_rotation_y_axis) * z + cos(
            self.angle_rotation_y_axis) * x
        return z_prime, x_prime

    def translate(self, x, y, z):
        return x + self.delta_x, y + self.delta_y, z + self.delta_z

    def run(self):
        particles = []
        particle_count = 0
        spill_count = 0

        f_beam = TFile(self.filename)
        spills = [key.GetName() for key in gDirectory.GetListOfKeys()]
        for spill in spills:
            spill_count += 1
            if self.max_spill_count and spill_count > self.max_spill_count:
                spill_count -= 1
                break
            print('spill = {}'.format(spill))

            for track in f_beam.Get(spill):
                particle_count += 1
                pass_all = track.TrackPresenttof_us and \
                    track.TrackPresentwire_chamber_1_detector and \
                    track.TrackPresentwire_chamber_2_detector and \
                    track.TrackPresentwire_chamber_3_detector and \
                    track.TrackPresentwire_chamber_4_detector and \
                    track.TrackPresentcherenkov and \
                    track.TrackPresenttof_ds and \
                    track.TrackPresentnova

                is_noise = not pass_all
                if self.exclude_noise and is_noise is True:
                    continue

                pdg_id = int(track.PDGidnova)
                x, y, z = self.translate(track.xnova, track.ynova,
                                         track.znova)  # mm
                # z, x = self.rotate_y_axis(z, x)
                t = track.tnova  # s

                px = track.Pxnova  # MeV
                py = track.Pynova  # MeV
                pz = track.Pznova  # MeV
                # pz, px = self.rotate_y_axis(pz, px)

                px /= 1000.  # GeV
                py /= 1000.  # GeV
                pz /= 1000.  # GeV
                x /= 10.  # cm
                y /= 10.  # cm
                z /= 10.  # cm
                t *= 1.e9  # ns

                mass = self.pdg.GetParticle(pdg_id).Mass()
                energy = (mass**2 + px**2 + py**2 + pz**2)**0.5
                particle = [
                    is_noise, 1, pdg_id, 0, 0, 0, 0, px, py, pz, energy, mass,
                    x, y, z, t
                ]

                particles.append(particle)
                particle_count += 1
                if particle_count % 1e6 == 0:
                    print('particle_count = {}'.format(particle_count))

        print('spill_count = {}'.format(spill_count))
        f_beam.Close()

        particles = sorted(particles, key=lambda p: p[-1])
        events = []
        event_end_time = 0.
        event_start_time = 0.
        event_particles = []
        for particle in particles:
            is_noise = particle[0]
            time = particle[-1]  # time
            if time > event_end_time:
                if event_particles:
                    events.append(event_particles)
                    event_particles = []
                if not is_noise:
                    particle[-1] = 0.
                    event_particles = [particle]
                    event_start_time = time
                    event_end_time = time + EventGenerator.EVENT_TIME_DURATION  # ns
            else:
                particle[-1] -= event_start_time
                event_particles.append(particle)
        if event_particles:
            events.append(event_particles)

        txt_filename = 'text_gen.{}{}.txt'.format(
            self.file_basename, '.exclude_noise' if self.exclude_noise else '')
        with open('{}/{}'.format(self.data_dir, txt_filename), 'w') as f_txt:
            for event in events:
                f_txt.write('0 {}\n'.format(len(event)))
                for particle in event:
                    f_txt.write(' '.join(map(str, particle[1:])) + '\n')

        if self.save_plot:
            self.make_plot(events)

    def make_plot(self, events):
        f_det = TFile(
            '{}/text_gen.{}{}.root'.format(
                self.data_dir, self.file_basename,
                '.exclude_noise' if self.exclude_noise else ''), 'RECREATE')
        multiple_particle_event_count = 0
        h_count = TH1D('h_count', 'h_count', 100, -0.5, 99.5)
        h_timing = TH1D('h_timing', 'h_timing', 5000, 0., 50.e3)  # ns
        h_xy = TH2D('h_xy', 'h_xy', 600, -150, 150, 600, -150, 150)  # cm
        h_z = TH1D('h_z', 'h_z', 500, -1, 1)  # cm
        for i, event in enumerate(events):
            h_count.Fill(len(event))
            if len(event) > 1:
                multiple_particle_event_count += 1

            for particle in event:
                h_timing.Fill(particle[-1])
                is_noise = particle[0]
                if is_noise:
                    continue
                x = particle[-4]
                y = particle[-3]
                z = particle[-2]
                h_xy.Fill(x, y)
                h_z.Fill(z)

        print('len(events) = {}'.format(len(events)))
        print('multiple_particle_event_count = {}'.format(
            multiple_particle_event_count))
        h_count.Write('h_particle_count_per_event')
        h_timing.Write('h_timing')
        h_xy.Write('h_xy')
        h_z.Write('h_z')
        f_det.Close()
Ejemplo n.º 22
0
parser.add_argument('outFileName', metavar='text', default='outFileName.root',
                    help='output root file name')
args = parser.parse_args()

#config with input file details
with open(args.cfgFileName, 'r') as ymlCfgFile:
    inputCfg = yaml.load(ymlCfgFile, yaml.FullLoader)
inFileNames = inputCfg['filename']
if not isinstance(inFileNames, list):
    inFileNames = [inFileNames]
isMC = inputCfg['isMC']

#define mass binning
meson = inputCfg['tree']['meson']
if meson == 'Ds':
    mD = TDatabasePDG.Instance().GetParticle(431).Mass()
elif meson == 'Dplus':
    mD = TDatabasePDG.Instance().GetParticle(411).Mass()
else:
    print('Error: only Dplus and Ds mesons supported. Exit!')
    exit()

#selections to be applied
with open(args.cutSetFileName, 'r') as ymlCutSetFile:
    cutSetCfg = yaml.load(ymlCutSetFile, yaml.FullLoader)
cutVars = cutSetCfg['cutvars']
selToApply = []
for iPt, _ in enumerate(cutVars['Pt']['min']):
    selToApply.append('')
    for iVar, varName in enumerate(cutVars):
        if varName == 'InvMass':
Ejemplo n.º 23
0
    def print_evt(event_filter=">= 0"):
        pdg_db = TDatabasePDG()
        ev_df = df.Filter(f"fMcCollisionsID {event_filter}")
        npy = ev_df.AsNumpy()
        print()
        lastmother = 0
        for i, part_index in enumerate(npy["part_index"]):
            ev = npy["fMcCollisionsID"][i]
            count("events", ev)
            m0 = npy["fMother0"][i]
            m1 = npy["fMother1"][i]
            d0 = npy["fDaughter0"][i]
            d1 = npy["fDaughter1"][i]
            pdg = npy["fPdgCode"][i]
            px = npy["fPx"][i]
            py = npy["fPy"][i]
            pz = npy["fPz"][i]

            def getpname(pdg_code):
                p = pdg_db.GetParticle(int(pdg_code))
                if p:
                    p = p.GetName()
                else:
                    p = "Undef"
                return p

            part = getpname(pdg)
            summary_line = f"  ({part_index}) ev {ev} m0 {m0} m1 {m1}, d0 {d0} d1 {d1}, pdg {pdg} '{part}'"
            if abs(pdg) not in [21, 2101, 2103, 2203, 1, 2, 3, 4, 5
                                ] and m0 > -1:
                if lastmother != m0 and count("mothers", m0):
                    raise ValueError("Duplicate mothers for ", summary_line)
            lastmother = m0
            if d1 > -1 and d0 > d1:
                raise ValueError("d0 < d1:", summary_line)

            def daughters():
                idaughters = []
                if d0 > -1 and d1 > -1:
                    for j in range(d0, d1 + 1):
                        entry = numpy.where(npy["part_index"] == j)[0]
                        if len(entry) > 1:
                            raise ValueError("Entry size is too high!")
                        if len(entry) == 0:
                            raise ValueError("Entry size is too low!")
                        entry = entry[0]
                        d_m0 = npy["fMother0"][entry]
                        d_m1 = npy["fMother1"][entry]
                        if d_m0 != part_index and d_m1 != part_index:
                            raise ValueError(
                                "Daughter has a different mother!", d_m0, d_m1,
                                "w.r.t.", part_index)
                        if d_m0 == d_m1:
                            raise ValueError("Daughter has same mother!", d_m0,
                                             d_m1)
                        idaughters.append(entry)
                # Checking that indices are increasing
                if sorted(idaughters) != idaughters:
                    raise ValueError("Daughters are not in order!")
                # Checking that indices have no holes
                if idaughters != [*range(idaughters[0], idaughters[-1] + 1)]:
                    raise ValueError("Daughters have hole in indices!",
                                     idaughters)
                return idaughters

            def daughters_pxpypz():
                d_px = 0
                d_py = 0
                d_pz = 0
                d = daughters()
                for j in d:
                    d_px += npy["fPx"][j]
                    d_py += npy["fPy"][j]
                    d_pz += npy["fPz"][j]
                return d_px, d_py, d_pz

            def daughters_pdg():
                d = daughters()
                d_pdgs = []
                for j in d:
                    d_pdgs.append(npy["fPdgCode"][j])
                return d_pdgs

            def check_momentum():
                d_p = daughters_pxpypz()
                m_p = [px, py, pz]
                for j in enumerate(m_p):
                    if (j[1] - d_p[j[0]]) > 0.001:
                        raise ValueError("Wrong P", j, "with", d_p)

            def is_decay_channel(desired_pdg_codes,
                                 fill_counter=True,
                                 min_prongs=0,
                                 max_prongs=10):
                d = daughters()
                d_pdgs = daughters_pdg()
                if len(d) >= min_prongs and len(d) <= max_prongs:
                    print(pdg, part, "decaying in")
                    for i, j in enumerate(d_pdgs):
                        print(" >", j, getpname(j), "index", d[i],
                              npy["part_index"][d[i]], "m0",
                              npy["fMother0"][d[i]], "m1",
                              npy["fMother1"][d[i]])
                if desired_pdg_codes is not None:
                    for i in desired_pdg_codes:
                        if i not in d_pdgs:
                            return False
                if fill_counter:
                    count(
                        f"{bcolors.BOKGREEN} {pdg} {part} {bcolors.ENDC} in {d_pdgs}",
                        part_index)
                return True

            extra = []
            if m0 < 0 and m1 < 0 and d0 < 1 and d1 < 0:
                extra.append("Sterile")
            if d1 <= d0 and d1 > -1:
                extra.append(bcolors.BWARNING + "Problematic" + bcolors.ENDC)
            if pdg in pdg_of_interest:
                extra.append(bcolors.BOKGREEN + "PDG of interest" +
                             bcolors.ENDC)
            extra = " ".join(extra)

            count(part, part_index)
            if verbose or pdg in pdg_of_interest:
                print(summary_line, extra)
            if pdg in pdg_of_interest:
                check_momentum()
                is_decay_channel(None, fill_counter=True)
Ejemplo n.º 24
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")
Ejemplo n.º 25
0
                   markerstyle=markersData[cut])
hEffPtIntMC = TH1F('hEffPtIntMC', ';|#Delta#it{M}(KK)| selection; efficiency',
                   21, 4.5, 25.5)
hEffPtIntData = TH1F('hEffPtIntData',
                     ';|#Delta#it{M}(KK)| selection; efficiency', 21, 4.5,
                     25.5)
SetObjectStyle(hEffPtIntMC,
               color=kRed + 1,
               fillstyle=0,
               markerstyle=kFullSquare)
SetObjectStyle(hEffPtIntData,
               color=kAzure + 4,
               fillstyle=0,
               markerstyle=kFullCircle)

massPhi = TDatabasePDG.Instance().GetParticle(333).Mass()
massK = TDatabasePDG.Instance().GetParticle(321).Mass()
widthPhi = TDatabasePDG.Instance().GetParticle(333).Width()

for iPt in range(nPtBinsMC):
    if iPt < nPtBinsMC - 1:
        ptMin = ptLims[iPt]
        ptMax = ptLims[iPt + 1]
    else:
        ptMin = ptLims[0]
        ptMax = ptLims[-1]

    # get massKK distributions in signal region
    massLowLimit = mean[iPt] - args.nSigma * sigma[iPt]
    massHighLimit = mean[iPt] + args.nSigma * sigma[iPt]
    binLow = hMassKKvsMassKKpiMC[iPt].GetXaxis().FindBin(massLowLimit * 1.0001)
Ejemplo n.º 26
0
import enum
from ROOT import TDatabasePDG

db = TDatabasePDG()
db.GetParticle(0)  # initialize list
all_particles = list(db.ParticleList())
data = {p.GetName(): p.PdgCode() for p in all_particles}
ParticleID = enum.IntEnum('ParticleID', data)


def main():
    for pid in ParticleID:
        print(
            f"{pid.__class__.__name__}({pid.value}) == {pid.__class__.__name__}['{pid.name}']"
        )


if __name__ == "__main__":
    main()
Ejemplo n.º 27
0
    def __init__(self, parse, tree, hepmc_attrib):

        print("Quasi-real configuration:")

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

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

        #boost vector pbvec of proton beam
        pbeam = TLorentzVector()
        pbeam.SetPxPyPzE(0, 0, TMath.Sqrt(self.Ep**2-mp**2), self.Ep)
        self.pbvec = pbeam.BoostVector()

        #electron beam energy Ee_p in proton beam rest frame
        ebeam = TLorentzVector()
        ebeam.SetPxPyPzE(0, 0, -TMath.Sqrt(self.Ee**2-self.me**2), self.Ee)
        ebeam.Boost(-self.pbvec.x(), -self.pbvec.y(), -self.pbvec.z()) # transform to proton beam frame
        self.Ee_p = ebeam.E()

        #center-of-mass squared s, GeV^2
        self.s = self.get_s(self.Ee, self.Ep)
        print("s =", self.s, "GeV^2")
        print("sqrt(s) =", TMath.Sqrt(self.s), "GeV")

        #range in x
        xmin = parse.getfloat("main", "xmin")
        xmax = parse.getfloat("main", "xmax")
        print("xmin =", xmin)
        print("xmax =", xmax)

        #range in u = log_10(x)
        umin = TMath.Log10(xmin)
        umax = TMath.Log10(xmax)
        print("umin =", umin)
        print("umax =", umax)

        #range in y
        ymin = parse.getfloat("main", "ymin")
        ymax = parse.getfloat("main", "ymax")

        #range in W
        wmin = -1.
        wmax = -1.
        if parse.has_option("main", "Wmin"):
            wmin = parse.getfloat("main", "Wmin")
            print("Wmin =", wmin)
        if parse.has_option("main", "Wmax"):
            wmax = parse.getfloat("main", "Wmax")
            print("Wmax =", wmax)

        #adjust range in y according to W
        if wmin > 0 and ymin < wmin**2/self.s:
            ymin = wmin**2/self.s
        if wmax > 0 and ymax > wmax**2/self.s:
            ymax = wmax**2/self.s

        print("ymin =", ymin)
        print("ymax =", ymax)

        #range in v = log_10(y)
        vmin = TMath.Log10(ymin)
        vmax = TMath.Log10(ymax)
        print("vmin =", vmin)
        print("vmax =", vmax)

        #range in Q2
        self.Q2min = parse.getfloat("main", "Q2min")
        self.Q2max = parse.getfloat("main", "Q2max")
        print("Q2min =", self.Q2min)
        print("Q2max =", self.Q2max)

        #constant term in the cross section
        self.const = TMath.Log(10)*TMath.Log(10)*(1./137)/(2.*math.pi)

        #cross section formula for d^2 sigma / dxdy, Eq. II.6
        #transformed as x -> u = log_10(x) and y -> v = log_10(y)
        self.eq_II6_uv_par = self.eq_II6_uv(self)
        self.eq = TF2("d2SigDuDvII6", self.eq_II6_uv_par, umin, umax, vmin, vmax)

        self.eq.SetNpx(1000)
        self.eq.SetNpy(1000)

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

        #generator event variables in output tree
        tnam = ["gen_u", "gen_v", "true_x", "true_y", "true_Q2", "true_W2"]
        tnam += ["true_el_Q2"]
        tnam += ["true_el_pT", "true_el_theta", "true_el_phi", "true_el_E"]

        #create the tree variables
        tcmd = "struct gen_out { Double_t "
        for i in tnam:
            tcmd += i + ", "
        tcmd = tcmd[:-2] + ";};"
        gROOT.ProcessLine( tcmd )
        self.out = rt.gen_out()

        #put zero to all variables
        for i in tnam:
            exec("self.out."+i+"=0")

        #set the variables in the tree
        if tree is not None:
            for i in tnam:
                tree.Branch(i, addressof(self.out, i), i+"/D")

        #event attributes for hepmc
        self.hepmc_attrib = hepmc_attrib

        #counters for all generated and selected events
        self.nall = 0
        self.nsel = 0

        #print generator statistics at the end
        atexit.register(self.show_stat)

        #total integrated cross section
        self.sigma_tot = self.eq.Integral(umin, umax, vmin, vmax)
        print("Total integrated cross section for a given x and y range:", self.sigma_tot, "mb")

        print("Quasi-real photoproduction initialized")
Ejemplo n.º 28
0
               markerstyle=kFullSquare)
SetObjectStyle(hRawYieldsSigmaRatioSecondFirstPeak,
               color=kRed,
               markerstyle=kFullSquare)
SetObjectStyle(hRawYieldsSoverBSecPeak, color=kRed, markerstyle=kFullSquare)
SetObjectStyle(hRawYieldsSignalSecPeak, color=kRed, markerstyle=kFullSquare)
SetObjectStyle(hRawYieldsBkgSecPeak, color=kRed, markerstyle=kFullSquare)
SetObjectStyle(hRawYieldsTrue, color=kRed, markerstyle=kFullSquare)
SetObjectStyle(hRawYieldsSecPeakTrue, color=kRed, markerstyle=kFullSquare)
SetObjectStyle(hRelDiffRawYieldsFitTrue, color=kRed, markerstyle=kFullSquare)
SetObjectStyle(hRelDiffRawYieldsSecPeakFitTrue,
               color=kRed,
               markerstyle=kFullSquare)

# fit histos
massDplus = TDatabasePDG.Instance().GetParticle(411).Mass()
massDs = TDatabasePDG.Instance().GetParticle(431).Mass()
massForFit = massDplus if fitConfig[cent]['Meson'] == 'Dplus' else massDs

cMass = TCanvas("cMass", "cMass", 1920, 1080)
DivideCanvas(cMass, nPtBins)
cResiduals = TCanvas("cResiduals", "cResiduals", 1920, 1080)
DivideCanvas(cResiduals, nPtBins)

massFitter = []
for iPt, (hM, ptMin, ptMax, reb, sgn, bkg, secPeak, massMin, massMax) in enumerate(zip(
        hMass, ptMins, ptMaxs, fitConfig[cent]['Rebin'], SgnFunc, BkgFunc, \
            inclSecPeak, fitConfig[cent]['MassMin'], fitConfig[cent]['MassMax'])):

    hMassForFit.append(TH1F())
    AliVertexingHFUtils.RebinHisto(hM, reb).Copy(
Ejemplo n.º 29
0
 1  2    3           4      5 6   7  8  9  10 11  12 13 14
ID  -  type       Part ID   - -  px py pz   -  -  vx vy vz
      1=active

"""
# all the not useful fields will be filled with 99

from ROOT import TGenPhaseSpace, TLorentzVector, TDatabasePDG, TMath, TVector3

import math
from random import random as rndm
from array import array
from random import gauss

dbpdg = TDatabasePDG()

# chose motherParticle
PDGmother = 3122
MotherMass = dbpdg.GetParticle(PDGmother).Mass()

# chose daughters
PDGs = [2212, -211]
DaughterMass = [dbpdg.GetParticle(i).Mass() for i in PDGs]

# Settings
# ========

NEVENTS = 50000
BeamPolarization = -1  # not useful
Ejemplo n.º 30
0
from ROOT import TLorentzVector, TDatabasePDG, TH1F, TH2F, TCanvas, TVector3
from math import *
import sys

with open(sys.argv[-1]) as fin:
    content = fin.readlines()

pdg = TDatabasePDG()

h0 = TH1F("m0", "", 200, 0, 3)
h1 = TH1F("m", "", 200, 0, 3)

h2t = TH2F("theta", "", 180, 0, 180, 90, 0, 180)
h2p = TH2F("phi", "", 180, -180, 180, 180, -180, 180)

i = 0
while i < len(content):

    line = content[i].strip().split()
    if len(line) == 10:
        g0line = content[i + 1].strip().split()
        g1line = content[i + 2].strip().split()
        g2line = content[i + 3].strip().split()

        g0d = [float(a) for a in g0line[6:9]]
        g1d = [float(a) for a in g1line[6:9]]
        g2d = [float(a) for a in g2line[6:9]]

        m0 = pdg.GetParticle(int(g0line[3])).Mass()
        m1 = pdg.GetParticle(int(g1line[3])).Mass()
        m2 = pdg.GetParticle(int(g2line[3])).Mass()