Esempio n. 1
0
def get_alphavals(q2arr, pdfset, sq2=False):
    """ Generate an array of alphas(q) values from LHAPDF """
    lhapdf_pdf = lhapdf.mkPDF(pdfset)
    if sq2:
        return np.array([lhapdf_pdf.alphasQ2(iq) for iq in q2arr])
    else:
        return np.array([lhapdf_pdf.alphasQ(iq) for iq in q2arr])
Esempio n. 2
0
def benchmark(wdir, idxs, dirname, fmt='pdf'):
    import lhapdf

    X, Q2 = get_xQ2_grid(option=0)

    central = lhapdf.mkPDF(dirname, 0)

    for idx in idxs:

        nrows, ncols = 1, 1
        fig = py.figure(figsize=(ncols * 4, nrows * 3))
        ax = py.subplot(nrows, ncols, 1)

        tab = pd.read_excel('%s/sim/%d.xlsx' % (wdir, idx))
        for q2 in Q2:
            bin = tab.query('Q2==%f' % q2)
            X = bin.X.values
            interp = np.array([central.xfxQ2(idx, x, q2) for x in X])
            true = bin.value.values
            ax.plot(X, np.abs(interp - true) / true * 100)

        ax.text(0.1, 0.9, r'$%d$' % idx, transform=ax.transAxes)
        ax.set_ylabel(r'$\rm relative~error~(\%)$')
        ax.set_xlabel(r'$x$')
        ax.semilogy()
        ax.semilogx()

        checkdir('%s/gallery' % wdir)
        py.tight_layout()
        py.savefig('%s/gallery/benchmark-%s-%d.%s' % (wdir, dirname, idx, fmt))
Esempio n. 3
0
def genPDFs(filename, pdfset, Q, Nsets):
    f = open(filename, "w")
    f.write("%s\t %.1f\n" % (pdfset, Q))
    f.write("x\t x*uv\t dx*uv\t x*dv\t dx*dv\t x*(uv-dv)\t dx*(uv-dv)\n")
    pdfs = {}
    for i in range(Nsets):
        pdfs[i] = lhapdf.mkPDF(pdfset, i)
    X = 10**np.linspace(-4.0, 0.0, num=1000, endpoint=True)
    for x in X:
        xf = pdfs[0].xfxQ(2, x, Q) - pdfs[0].xfxQ(-2, x, Q) - pdfs[0].xfxQ(
            1, x, Q) + pdfs[0].xfxQ(-1, x, Q)
        xfu = pdfs[0].xfxQ(2, x, Q) - pdfs[0].xfxQ(-2, x, Q)
        xfd = pdfs[0].xfxQ(1, x, Q) - pdfs[0].xfxQ(-1, x, Q)
        xfall = []
        xfallu = []
        xfalld = []
        for i in range(Nsets):
            xfall.append((pdfs[i].xfxQ(2, x, Q) - pdfs[i].xfxQ(-2, x, Q)) -
                         (pdfs[i].xfxQ(1, x, Q) - pdfs[i].xfxQ(-1, x, Q)))
            xfallu.append(pdfs[i].xfxQ(2, x, Q) - pdfs[i].xfxQ(-2, x, Q))
            xfalld.append(pdfs[i].xfxQ(1, x, Q) - pdfs[i].xfxQ(-1, x, Q))
        dxf = np.std(np.array(xfall))
        dxfu = np.std(np.array(xfallu))
        dxfd = np.std(np.array(xfalld))
        f.write("%.3E\t%.3E\t%.3E\t%.3E\t%.3E\t%.3E\t%.3E\n" %
                (x, xfu, dxfu, xfd, dxfd, xf, dxf))
    f.close()
    return
Esempio n. 4
0
def get_pdfvals(xarr, qarr, pdfset):
    """ Get the pdf values from LHAPDF """
    lhapdf_pdf = lhapdf.mkPDF(pdfset)
    res = {}
    for x, q in zip(xarr, qarr):
        dict_update(res, lhapdf_pdf.xfxQ2(x, q))
    return res
Esempio n. 5
0
def getWeightedHistograms(filename, treename, nExp, pdfs):
    tree = readTree(filename, treename)
    nGen = tree.GetEntries()
    originalPdf = lhapdf.mkPDF("cteq6l1")

    out = {}
    binning = [100, 120, 160, 200, 270, 350]  # overflow ist last bin
    import array
    for name, pdfSet in pdfs.iteritems():
        for i in range(len(pdfSet)):
            out[name + "_%s" % i] = ROOT.TH1F(name + "_%s" % i, "",
                                              len(binning) - 1,
                                              array.array('d', binning))

    for event in tree:
        originalWeight = originalPdf.xfxQ(event.id1, event.x1,
                                          event.scale) * originalPdf.xfxQ(
                                              event.id2, event.x2, event.scale)
        for name, pdfSet in pdfs.iteritems():
            for i, pdf in enumerate(pdfSet):
                weight = pdf.xfxQ(event.id1, event.x1, event.scale) * pdf.xfxQ(
                    event.id2, event.x2, event.scale) / originalWeight
                out[name + "_%s" % i].Fill(event.met,
                                           event.weight * weight * nExp / nGen)
    return out
Esempio n. 6
0
def gen_statistical_uncertainties(wdir, dirname, iset, iF2, iFL, iF3, data,
                                  lum):
    """
    ATTENTION: sigtot is in 1/GeV^2
    lum must be in GeV^2
    """
    import lhapdf
    stf = lhapdf.mkPDF(dirname, iset)

    global par
    par = AUX()

    for bin in data:
        N = bin['sigtot'] * lum
        ps = (bin['xmax'] - bin['xmin']) * (bin['Q2max'] - bin['Q2min'])
        bin['<value>'] = N / ps / lum
        bin['stat_u'] = np.sqrt(N) / ps / lum

        bin['xmid'] = 0.5 * (bin['xmax'] + bin['xmin'])
        bin['Q2mid'] = 0.5 * (bin['Q2max'] + bin['Q2min'])
        x = bin['<x>']
        Q2 = bin['<Q2>']
        F2 = stf.xfxQ2(iF2, x, Q2)
        FL = stf.xfxQ2(iFL, x, Q2)
        F3 = 0
        rs = bin['rs']
        sign = bin['sign']
        bin['obs'] = 'dsig/dxdQ2'
        bin['value'] = get_sigma_dxdQ2(rs, x, Q2, F2, FL, F3, sign)
        bin['x'] = x
        bin['Q2'] = Q2
        bin['y'] = Q2 / x / (rs**2 - par.M2)

    return data
Esempio n. 7
0
    def set_pdf(self,refer,target):

        ##--set LHAPDF path
        lhapdf.pathsPrepend("/home/taebh/2021_Research/share/LHAPDF")
        self.nnpdf = lhapdf.mkPDF(refer,0)
        self.PDFsets = lhapdf.mkPDFs(target)
        self.numPDF = len(self.PDFsets)
 def __init__(self, subprocess_dir, param_card = None, beam_energy = 6500, fac_scale = 2 * 91.2 + 200, PDF_name = "NNPDF30_lo_as_0130/0") : 
     self.matrices = get_matrices(subprocess_dir, param_card = None)
     self.beam_energy = beam_energy
     self.fac_scale = fac_scale
     self.pdf = lhapdf.mkPDF(PDF_name)
     self.partons = {}
     for k, v in self.matrices.iteritems() :
         self.partons[k] = get_parton_flavor(k)
Esempio n. 9
0
    def as_uncert(self,target1,target2):

        Alphas1 = lhapdf.mkPDF(target1,0)
        Alphas2 = lhapdf.mkPDF(target2,0)
        
        sumw = 0
        for i in range(self.numEvents):
            sumw += (Alphas1.xfxQ(self.id1[i],self.x1[i],self.Q[i])*Alphas1.xfxQ(self.id2[i],self.x2[i],self.Q[i]))/(self.nnpdf.xfxQ(self.id1[i],self.x1[i],self.Q[i])*self.nnpdf.xfxQ(self.id2[i],self.x2[i],self.Q[i]))
        R_Alphas1 = sumw/self.numEvents
        
        sumw = 0
        for i in range(self.numEvents):
            sumw += (Alphas2.xfxQ(self.id1[i],self.x1[i],self.Q[i])*Alphas2.xfxQ(self.id2[i],self.x2[i],self.Q[i]))/(self.nnpdf.xfxQ(self.id1[i],self.x1[i],self.Q[i])*self.nnpdf.xfxQ(self.id2[i],self.x2[i],self.Q[i]))
        R_Alphas2 = sumw/self.numEvents
        
        self.As_uncert = (R_Alphas1-R_Alphas2)/2
        return self.As_uncert
Esempio n. 10
0
 def __init__(self,name,central_only=False,ismc=False):
     print 'loading ',name
     self.name=name
     self.ismc=ismc
     self.central_only=central_only
     if central_only==True:
         self.central=lhapdf.mkPDF(name,0)
     else:
         self.SETS=lhapdf.mkPDFs(name)
Esempio n. 11
0
File: master.py Progetto: Jeff182/CJ
  def __init__(self,name,X=[None],central_only=False):

    self.name=name
    self.central_only=central_only
    if central_only==True:
      self.central=lhapdf.mkPDF(name,0)
    else:
      self.SETS=lhapdf.mkPDFs(name)
    if X[0]==None: self.X=np.linspace(1e-3,0.99,1000)
    else: self.X=X
Esempio n. 12
0
 def __init__(self,
              subprocess_dir,
              param_card=None,
              beam_energy=6500,
              fac_scale=2 * 91.2 + 200,
              PDF_name="NNPDF30_lo_as_0130/0"):
     self.matrices = get_matrices(subprocess_dir, param_card=None)
     self.beam_energy = beam_energy
     self.fac_scale = fac_scale
     self.pdf = lhapdf.mkPDF(PDF_name)
     self.partons = {}
     for k, v in self.matrices.iteritems():
         self.partons[k] = get_parton_flavor(k)
Esempio n. 13
0
def get_pdf(pdf_name, Xgrid, Q0, rep=0):

    Nx = len(Xgrid)

    GLUON = np.zeros(Nx, dtype=float)

    GLUON_LHAPDF = lhapdf.mkPDF(pdf_name, rep)

    for ix in range(Nx):
        x = Xgrid[ix]
        GLUON[ix] = GLUON_LHAPDF.xfxQ(0, x, Q0)

    return GLUON
Esempio n. 14
0
def setup_pdf_objs(all_pdfs, cache={}):
    import lhapdf
    lhapdf.setVerbosity(1)
    os.environ['LHAPDF_DATA_PATH'] = '/cvmfs/sft.cern.ch/lcg/releases/MCGenerators/lhapdf/6.2.1-7149a/x86_64-centos7-gcc8-opt/share/LHAPDF/'

    paths = [
    '/cvmfs/sft.cern.ch/lcg/external/lhapdfsets/current/',
    ]
    lhapdf.setPaths(paths)

    pdf_objs = {}
    for p in all_pdfs:
        if p in cache:
            pdf_objs[p] = cache[p]
        else:
            pdf_objs[p] = lhapdf.mkPDF(p)
            cache[p] = pdf_objs[p]
    return pdf_objs
Esempio n. 15
0
def getWeightedHistograms( filename, treename, nExp, pdfs ):
    tree = readTree( filename, treename )
    nGen = tree.GetEntries()
    originalPdf = lhapdf.mkPDF("cteq6l1")

    out = {}
    binning = [ 100, 120, 160, 200, 270, 350 ] # overflow ist last bin
    import array
    for name, pdfSet in pdfs.iteritems():
        for i in range(len(pdfSet)):
            out[name+"_%s"%i] = ROOT.TH1F( name+"_%s"%i, "", len(binning)-1, array.array('d', binning) )

    for event in tree:
        originalWeight = originalPdf.xfxQ( event.id1, event.x1, event.scale ) * originalPdf.xfxQ( event.id2, event.x2, event.scale )
        for name, pdfSet in pdfs.iteritems():
            for i,pdf in enumerate(pdfSet):
                weight = pdf.xfxQ( event.id1, event.x1, event.scale ) * pdf.xfxQ( event.id2, event.x2, event.scale ) / originalWeight
                out[name+"_%s"%i].Fill( event.met, event.weight*weight*nExp/nGen )
    return out
Esempio n. 16
0
def genPDFs(filename, pdfset, flavor, Q, nlines):
    f = open(filename, "w")
    f.write("x\t")
    for i in range(nlines + 1):
        f.write("%d\t" % i)
    f.write("\n")
    pdflist = np.arange((nlines + 2) * 1000,
                        dtype=np.float64).reshape(1000, nlines + 2)
    xlist = 10**np.linspace(np.log10(2.035e-7), 0, 1000)
    for i in range(1000):
        pdflist[i, 0] = xlist[i]
    for id in range(nlines + 1):
        pdf = lhapdf.mkPDF(pdfset, id)
        for i in range(1000):
            pdflist[i, id + 1] = pdf.xfxQ(flavor, xlist[i], Q) / xlist[i]
    for i in range(1000):
        for j in range(nlines + 2):
            f.write("%.6E\t" % pdflist[i, j])
        f.write("\n")
    f.close()
    return
Esempio n. 17
0
def get_red_sigtot(wdir, dirname, iset, iF2, iFL, iF3, data, current):
    import lhapdf

    global par
    par = AUX()
    stf = lhapdf.mkPDF(dirname, iset)

    for bin in data:
        xmin = bin['xmin']
        xmax = bin['xmax']
        q2min = bin['Q2min']
        q2max = bin['Q2max']
        sign = bin['sign']
        rs = bin['rs']
        bin['sigtot'] = red_integrate(stf, sign, rs, xmin, xmax, q2min, q2max,
                                      iF2, iFL, iF3, 0, current)
        bin['<x>'] = integrate(stf, sign, rs, xmin, xmax, q2min, q2max, iF2,
                               iFL, iF3, 1) / bin['sigtot']
        bin['<Q2>'] = integrate(stf, sign, rs, xmin, xmax, q2min, q2max, iF2,
                                iFL, iF3, 2) / bin['sigtot']

    return data
Esempio n. 18
0
def main():
    # create a new luminosity function for the $\gamma\gamma$ initial state
    lumi = pineappl.lumi()
    pdg_ids = [22, 22]
    ckm_factors = [1.0]
    lumi.add(pdg_ids, ckm_factors)

    # only LO $\alpha_\mathrm{s}^0 \alpha^2 \log^0(\xi_\mathrm{R}) \log^0(\xi_\mathrm{F})$
    orders = [0, 2, 0, 0]
    bins = [
        0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3,
        1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4
    ]
    grid = pineappl.grid(lumi, orders, bins)

    # fill the grid with phase-space points
    print('Generating events, please wait...')
    fill_grid(grid, 100000)

    # load pdf for testing
    pdf = lhapdf.mkPDF('NNPDF31_nlo_as_0118_luxqed', 0)

    def xfx(id, x, q2, p):
        return pdf.xfxQ2(id, x, q2)

    def alphas(q2, p):
        return pdf.alphasQ2(q2)

    # perform convolution
    dxsec = grid.convolute(xfx, xfx, alphas, None, None, 1.0, 1.0)
    for i in range(len(dxsec)):
        print(f'{bins[i]:.1f} {bins[i + 1]:.1f} {dxsec[i]:.3e}')

    # write the grid to disk
    filename = 'DY-LO-AA.pineappl'
    print(f'Writing PineAPPL grid to disk: {filename}')
    grid.write(filename)
Esempio n. 19
0
#!/usr/bin/env python
import sys, os
import numpy as np
from scipy.integrate import quad, fixed_quad
try:
    import lhapdf
    pdf = lhapdf.mkPDF("CJ15nlo", 0)
    mc = pdf.quarkThreshold(4)
    mb = pdf.quarkThreshold(5)
except:
    print 'lhapdf not found. you wont be able to compute idis'

TR = 0.5
CF = 4. / 3.
alfa = 1 / 137.036
M = 0.93891897
apU = 4.0 / 9.0
apD = 1.0 / 9.0
couplings = {}
couplings['p'] = {1: apD, 2: apU, 3: apD, 4: apU, 5: apD}
couplings['n'] = {1: apU, 2: apD, 3: apD, 4: apU, 5: apD}
fmap = {}

F2 = {'p': {}, 'n': {}}
FL = {'p': {}, 'n': {}}


def integrator(f, xmin, xmax, method='gauss', n=100):
    f = np.vectorize(f)
    if method == 'quad':
        return quad(f, xmin, xmax)[0]
Esempio n. 20
0
    def __init__(self,
                 e_cm=1000,
                 pdf=False,
                 delr_cut=0.4,
                 pt_cut=10,
                 rap_maxcut=2.4,
                 pdf_type=None,
                 pdf_dir=None,
                 lhapdf_dir=None,
                 process=None,
                 device=None,
                 *args,
                 **kwargs):
        """

        Parameters
        ----------
        e_cm : float or torch.Tensor
            Centre-of-mass energy of a central two-body collision.
        pdf: boolean
            If True, the beams are assuemed to be proton beams and the PDFs are included in the calculation.
        delr_cut: float or torch.Tensor
            The minimum angular distance between each pair of the outgoing particles. 
        pt_cut: float or torch.Tensor
            The minimal transversal momentum of each outgoing particle.
        rap_maxcut: float or torch.Tensor
            The maximal rapidity of each outgoing particle. -1 means no cut.
        pdf_type: String
            The name of the PDF set to be used by LHAPDF.
        pdf_dir: String
            The directory whre the PDF data sets are stored.
        lhapdf_dir: String
            The path to the LHAPDF shared-object file.
        process: String
            The name given by MadGraph5_aMC@NLO to the subprocess.
        device: torch.device
            Default device where the parameters are stored
        """

        logger.debug(process)
        self.pdf = pdf
        self.pdf_obj = None

        #Try to import LHAPDF. If this is not possible, PDFs are not included
        if self.pdf and lhapdf_dir == None:
            logger.error(
                "The directory of the LHAPDF module was not given. PDFs are not included"
            )
            self.pdf = False
        if self.pdf:
            if lhapdf_dir not in sys.path:
                sys.path.append(lhapdf_dir)
            try:
                import lhapdf
                self.pdf_obj = lhapdf.mkPDF(pdf_type, 0)
            except Exception as e:
                logger.error("LHAPDF could not be imported")
                logger.debug(e)
                self.pdf = False

        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

        #Try to import the matrix element shared-object file
        if BASE_DIR + "/integrands/mg/" + process not in sys.path:
            sys.path.append(BASE_DIR + "/integrands/mg/" + process)
        try:
            import matrix2py
        except Exception as e:
            logger.error("The matrix elements could not be imported")
            logger.debug(e)

        self.process = process
        self.E_cm = sanitize_variable(e_cm, device)
        self.delR_cut = sanitize_variable(delr_cut, device)
        self.pT_cut = sanitize_variable(pt_cut, device)
        self.rap_maxcut = sanitize_variable(rap_maxcut, device)
        self.default_device = device

        #the matrix element needs to be initialised
        matrix2py.initialisemodel(BASE_DIR + "/integrands/mg/" + process +
                                  "/param/param_card.dat")
        #parses the output documents in order to get the correct pdg codes
        #and masses
        parser = ParseParams(self.process, BASE_DIR)
        (pdg, external_masses) = parser.parse()

        self.pdg = pdg

        logger.info("# ingoing particles: " + str(len(external_masses[0])))
        logger.info("Ingoing pdg codes: " + str(pdg[0]) + " " + str(pdg[1]))
        logger.info("PDFs active: " + str(self.pdf))
        logger.info("# outgoing particles: " + str(len(external_masses[1])))

        if ((len(external_masses[0])) != 2 and self.pdf):
            logger.info("No PDF support for other cases than 2 body collision")
            self.pdf = False

        #initialising of the phase space generator
        self.this_process_E_cm = max(self.E_cm, sum(external_masses[1]) * 2.)
        self.my_ps_generator = FlatInvertiblePhasespace(external_masses[0],
                                                        external_masses[1],
                                                        pdf=self.pdf_obj,
                                                        pdf_active=self.pdf,
                                                        lhapdf_dir=lhapdf_dir,
                                                        tau=False)

        #determination of the #dof
        if not self.pdf:
            self.d = self.my_ps_generator.nDimPhaseSpace(
            )  # number of dimensions
        else:
            self.d = self.my_ps_generator.nDimPhaseSpace(
            ) + 2  # number of dimensions

        super(CrossSection, self).__init__(self.d)
Esempio n. 21
0
def compare_alphas(pdfname, ax):
    """
    Computes the alphas difference pdfflow vs lhapdf and returns
    axes for plots
    Parameters:
        pdfname: string
        ax: matplotlib.axes.Axes object
    Return:
        matplotlib.axes.Axes object
    """
    p = pdf.mkPDF(pdfname, DIRNAME)
    name = '\_'.join(pdfname.split('_'))

    s = time.time()
    p.alphas_trace()
    print("".join([
        f"\nPDFflow alphas, pdf set:{pdfname}",
        f"\n\tBuilding graph time: {time.time()-s}\n"
    ]))

    if p is None:
        p = pdf.mkPDF(pdfname, DIRNAME)
    l_pdf = lhapdf.mkPDF(pdfname)
    name = '\_'.join(pdfname.split('_'))

    q = np.logspace(-3, 9, 10000, dtype=float)

    s_time = time.time()
    vl = np.array([l_pdf.alphasQ(iq) for iq in q])
    l_time = time.time()
    vp = p.py_alphasQ(q)
    p_time = time.time()

    ax.plot(q, np.abs(vp - vl) / (np.abs(vl) + EPS))
    ax.hlines(1e-3,
              plt.xlim()[0],
              plt.xlim()[1],
              linestyles='dotted',
              color='red')
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlim([1e-3, 1e9])
    ax.set_ylim([EPS, 0.01])

    ax = set_ticks(ax, -3, 9, 13, 'x', 4)
    ax.tick_params(axis='x',
                   which='both',
                   direction='in',
                   bottom=True,
                   labelbottom=True,
                   top=True,
                   labeltop=False)

    ax = set_ticks(ax, -15, -3, 16, 'y')

    ax.title.set_text(r'%s, $\alpha_s(Q)$' % name)
    ax.set_xlabel(r'$Q$', fontsize=17)

    print("\nDry run time comparison for pdf %s:" % pdfname)
    print("{:>10}:{:>15.8f}".format("lhapdf", l_time - s_time))
    print("{:>10}:{:>15.8f}".format("pdfflow", p_time - l_time))

    return ax
Esempio n. 22
0
def accumulate_times(pdfname, dev0, dev1, no_lhapdf):
    """
    Computes performance times
    Parameters:
        dev0: str, device name over which run pdfflow
        dev1: str, device name over which run pdfflow
    """
    with tf.device(dev0):
        p0 = pdf.mkPDF(pdfname, DIRNAME)
        p0.trace()

    with tf.device(dev1):
        p1 = pdf.mkPDF(pdfname, DIRNAME)
        p1.trace()

    if no_lhapdf:
        l_pdf = lhapdf.mkPDF(pdfname)
    else:
        l_pdf = None

    xmin = np.exp(p0.grids[0][0].log_xmin)
    xmax = np.exp(p0.grids[0][0].log_xmax)
    q2min = np.sqrt(np.exp(p0.grids[0][0].log_q2min))
    q2max = np.sqrt(np.exp(p0.grids[0][-1].log_q2max))

    t_pdf0 = []
    t_pdf1 = []
    t_lha = []

    n = np.linspace(1e5, 1e6, 20)
    for j in range(10):
        t0 = []
        t1 = []
        t2 = []
        for i in tqdm.tqdm(n):
            a_x = np.random.uniform(xmin, xmax, [
                int(i),
            ])
            a_q2 = np.exp(
                np.random.uniform(np.log(q2min), np.log(q2max), [
                    int(i),
                ]))
            with tf.device(dev0):
                t_ = test_pdfflow(p0, a_x, a_q2)
            t0 += [t_]

            with tf.device(dev1):
                t_ = test_pdfflow(p1, a_x, a_q2)
            t1 += [t_]

            t_ = test_lhapdf(l_pdf, a_x, a_q2) if no_lhapdf else []
            t2 += [t_]

        t_pdf0 += [t0]
        t_pdf1 += [t1]
        t_lha += [t2]

    t_pdf0 = np.stack(t_pdf0)
    t_pdf1 = np.stack(t_pdf1)
    t_lha = np.stack(t_lha)

    return n, t_pdf0, t_pdf1, t_lha
Esempio n. 23
0
#!/usr/bin/python
import numpy as np
from sys import path
path.append("./")

import DSSV
DSSV.dssvini()

import lhapdf
lhapdf.setVerbosity(0)
pdf = lhapdf.mkPDF("DSSV2014",0);

def DSSVxfxQ2(pid,x,Q2):
	DUV,DDV,DUBAR,DDBAR,DSTR,DGLU = DSSV.dssvgupdate(x,Q2)
	if -2 == pid: return DDBAR
	if -1 == pid: return DUBAR
	if 1 == pid: return DUBAR+DUV
	if 2 == pid: return DDBAR+DDV
	if 3 == pid or -3 == pid: return DSTR
	if 21 == pid: return DGLU
	raise "unknown PID"

pids = [-3, -2, -1, 1, 2, 3, 21]

xs = """1.000000e-05 4.000000e-05 6.700000e-05 1.000000e-04 1.400000e-04 2.000000e-04 3.000000e-04 4.500000e-04 6.700000e-04 1.000000e-03 1.400000e-03 2.000000e-03 3.000000e-03 4.500000e-03 6.700000e-03 1.000000e-02 1.400000e-02 2.000000e-02 3.000000e-02 4.500000e-02 6.000000e-02 8.000000e-02 1.000000e-01 1.250000e-01 1.500000e-01 1.750000e-01 2.000000e-01 2.250000e-01 2.500000e-01 2.750000e-01 3.000000e-01 3.250000e-01 3.500000e-01 3.750000e-01 4.000000e-01 4.500000e-01 5.000000e-01 5.500000e-01 6.000000e-01 6.500000e-01 7.000000e-01 7.500000e-01 8.000000e-01 8.500000e-01 9.000000e-01 9.500000e-01 1.000000e+00"""
Qs = """8.944272e-01 1.000000e+00 1.118034e+00 1.224745e+00 1.414214e+00 1.581139e+00 2.000000e+00 2.529822e+00 3.162278e+00 3.872983e+00 5.000000e+00 6.324555e+00 8.000000e+00 1.000000e+01 1.341641e+01 1.788854e+01 2.408319e+01 3.162278e+01 4.242641e+01 5.656854e+01 7.615773e+01 1.000000e+02 1.341641e+02 1.788854e+02 2.408319e+02 3.162278e+02 4.242641e+02 5.656854e+02 7.615773e+02 1.000000e+03"""

def printGrid():
	for xx in xs.split(" "):
		x = float(xx)
		for QQ in Qs.split(" "):
Esempio n. 24
0
def pvdis_errors(wdir, idxs, tar, lum='100:fb-1'):

    for idx in idxs:
        conf['aux'] = AUX()
        conf['eweak'] = EWEAK()
        data = pd.read_excel('%s/sim/%s%s.xlsx' % (wdir, idx, tar),
                             index=False)
        data = data.to_dict(orient='list')
        target = data['target'][0]
        l = len(data['value'])
        X = np.array(data['X'])
        Q2 = np.array(data['Q2'])
        Xup = np.array(data['Xup'])
        Xdo = np.array(data['Xdo'])
        Q2up = np.array(data['Q2up'])
        Q2do = np.array(data['Q2do'])

        RS = data['RS'][0]
        S = RS**2

        M2 = conf['aux'].M2

        if target == 'd': M2 = 4 * M2

        #--luminosity
        lum = convert_lum(lum)

        dx = Xup - Xdo
        dQ2 = Q2up - Q2do

        bins = dx * dQ2

        GF = conf['aux'].GF

        if target == 'p': tabname = 'JAM4EIC_p'
        if target == 'd': tabname = 'JAM4EIC_d'

        stf = lhapdf.mkPDF(tabname, 0)

        #--integrate over bin
        #--get structure functions
        #F2g  = lambda x,q2: stf.xfxQ2(900,x,q2)
        #FLg  = lambda x,q2: stf.xfxQ2(901,x,q2)
        #F2gZ = lambda x,q2: stf.xfxQ2(902,x,q2)
        #FLgZ = lambda x,q2: stf.xfxQ2(903,x,q2)
        #F3gZ = lambda x,q2: stf.xfxQ2(904,x,q2)

        #rho2 = lambda x,q2: 1 + 4*x**2*M2/q2

        #y=lambda x,q2: (q2/2/x)/((S-M2)/2)

        #YP = lambda x,q2: y(x,q2)**2*(rho2(x,q2)+1)/2 - 2*y(x,q2) +2
        #YM = lambda x,q2: 1-(1-y(x,q2))**2

        #sin2w = lambda q2: conf['eweak'].get_sin2w(q2)
        #alpha = lambda q2: conf['eweak'].get_alpha(q2)

        #gA = -0.5
        #gV = lambda q2: -0.5 + 2*sin2w(q2)

        #C  = lambda q2: GF*q2/(2*np.sqrt(2)*np.pi*alpha(q2))

        #C1 = lambda x,q2: 2*np.pi*alpha(q2)**2/(x*y(x,q2)*q2)

        #T1g  = lambda x,q2: YP(x,q2)*F2g(x,q2)  - y(x,q2)**2*FLg(x,q2)
        #T1gZ = lambda x,q2: YP(x,q2)*F2gZ(x,q2) - y(x,q2)**2*FLgZ(x,q2)

        #T2 = lambda x,q2: x*YM(x,q2)*F3gZ(x,q2)

        #_ddsigR = lambda x,q2: C1(x,q2)*(T1g(x,q2) + C(q2)*(gV(q2)-gA)*(T1gZ(x,q2) - T2(x,q2)))
        #_ddsigL = lambda x,q2: C1(x,q2)*(T1g(x,q2) + C(q2)*(gV(q2)+gA)*(T1gZ(x,q2) + T2(x,q2)))

        #z1,w1 = np.polynomial.legendre.leggauss(5)
        #z2,w2 = np.polynomial.legendre.leggauss(5)

        #ddsigR = np.zeros((len(X),len(z1),len(z2)))
        #ddsigL = np.zeros((len(X),len(z1),len(z2)))
        #for i in range(len(X)):
        #    _x   = 0.5*((Xup[i] -Xdo[i])*z1  + Xup[i]  + Xdo[i])
        #    _q2  = 0.5*((Q2up[i]-Q2do[i])*z2 + Q2up[i] + Q2do[i])
        #    xjac  = 0.5*(Xup[i]-Xdo[i])
        #    q2jac = 0.5*(Q2up[i]-Q2do[i])
        #    for j in range(len(_x)):
        #        for k in range(len(_q2)):
        #            ddsigR[i][j][k] = _ddsigR(_x[j],_q2[k])*xjac*q2jac
        #            ddsigL[i][j][k] = _ddsigL(_x[j],_q2[k])*xjac*q2jac

        ##--integrate over Q2
        #dsigR = np.sum(w2*ddsigR,axis=2)
        #dsigL = np.sum(w2*ddsigL,axis=2)

        ##--integrate over X
        #sigR = np.sum(w1*dsigR,axis=1)
        #sigL = np.sum(w1*dsigL,axis=1)

        #--multiply by bin
        #--get structure functions
        F2g = np.array([stf.xfxQ2(900, X[i], Q2[i]) for i in range(l)])
        FLg = np.array([stf.xfxQ2(901, X[i], Q2[i]) for i in range(l)])
        F2gZ = np.array([stf.xfxQ2(902, X[i], Q2[i]) for i in range(l)])
        FLgZ = np.array([stf.xfxQ2(903, X[i], Q2[i]) for i in range(l)])
        F3gZ = np.array([stf.xfxQ2(904, X[i], Q2[i]) for i in range(l)])

        rho2 = 1 + 4 * X**2 * M2 / Q2

        y = (Q2 / 2 / X) / ((S - M2) / 2)

        YP = y**2 * (rho2 + 1) / 2 - 2 * y + 2
        YM = 1 - (1 - y)**2

        sin2w = np.array([conf['eweak'].get_sin2w(q2) for q2 in Q2])
        alpha = np.array([conf['eweak'].get_alpha(q2) for q2 in Q2])

        gA = -0.5
        gV = -0.5 + 2 * sin2w

        C = GF * Q2 / (2 * np.sqrt(2) * np.pi * alpha)

        C1 = 2 * np.pi * alpha**2 / (X * y * Q2) * bins

        T1g = YP * F2g - y**2 * FLg
        T1gZ = YP * F2gZ - y**2 * FLgZ

        T2 = X * YM * F3gZ

        sigR = C1 * (T1g + C * (gV - gA) * (T1gZ - T2))
        sigL = C1 * (T1g + C * (gV + gA) * (T1gZ + T2))

        NR = lum * sigR
        NL = lum * sigL

        C = 4 / (NR + NL)**4

        T1 = NL**2 * NR
        T2 = NR**2 * NL

        stat2 = C * (T1 + T2)

        stat = np.sqrt(stat2)

        #--add syst errors and save new excel sheet
        data['stat_u'] = stat

        print stat
        df = pd.DataFrame(data)
        df.to_excel('%s/sim/%s%s.xlsx' % (wdir, idx, tar), index=False)
Esempio n. 25
0
def install_lhapdf(pdfset):
    try:
        lhapdf.mkPDF(pdfset)
    except RuntimeError:
        sp.run(["lhapdf", "install", pdfset])
Esempio n. 26
0
    sys.argv[1] + "TeV.root")

##--get generator information
id1 = events["Events"].array("pdg1")
x1 = events["Events"].array("x1")
id2 = events["Events"].array("pdg2")
x2 = events["Events"].array("x2")
xpdf1 = events["Events"].array("xpdf1")
xpdf2 = events["Events"].array("xpdf2")
Q = events["Events"].array("scalePDF")

##--set LHAPDF path
lhapdf.pathsPrepend("/home/taebh/2021_Research/share/LHAPDF")

numEvents = len(id1)
nnpdf = lhapdf.mkPDF("NNPDF31_nnlo_as_0118_mc_hessian_pdfas", 0)
PDFsets = lhapdf.mkPDFs("CT18NNLO")
numPDF = len(PDFsets)
reweight = np.empty([numPDF])

for j in range(numPDF):
    sumw = 0
    ct18 = PDFsets[j]
    for i in range(numEvents):
        sumw += (ct18.xfxQ(id1[i], x1[i], Q[i]) * ct18.xfxQ(
            id2[i], x2[i], Q[i])) / (nnpdf.xfxQ(id1[i], x1[i], Q[i]) *
                                     nnpdf.xfxQ(id2[i], x2[i], Q[i]))
    reweight[j] = sumw / numEvents

a = np.square(reweight[1:] - reweight[0])
Esempio n. 27
0
#!/usr/bin/env python
import os, sys
import numpy as np
import scipy as sp
import lhapdf

nnpdf = lhapdf.mkPDF("NNPDF30_lo_as_0118", 0)
mmht = lhapdf.mkPDF("MMHT2014lo68cl", 0)
cj15 = lhapdf.mkPDF("CJ15lo", 0)
ct14 = lhapdf.mkPDF("CT14lo", 0)

f = open("pdfgrid.txt", "w")
f.write("x \t NNPDF3 \t MMHT14 \t CJ15 \t CT14\n")

xlist = 10**np.linspace(np.log10(2.035e-7), 0, 2000)
nnpdflist = xlist.copy()
mmhtlist = xlist.copy()
cj15list = xlist.copy()
ct14list = xlist.copy()

for i in range(2000):
    nnpdflist[i] = nnpdf.xfxQ(3, xlist[i], 2.0) - nnpdf.xfxQ(-3, xlist[i], 2.0)
    mmhtlist[i] = mmht.xfxQ(3, xlist[i], 2.0) - mmht.xfxQ(-3, xlist[i], 2.0)
    cj15list[i] = cj15.xfxQ(3, xlist[i], 2.0) - cj15.xfxQ(-3, xlist[i], 2.0)
    ct14list[i] = ct14.xfxQ(3, xlist[i], 2.0) - ct14.xfxQ(-3, xlist[i], 2.0)

for i in range(2000):
    f.write("%.6E \t %.6E \t %.6E \t %.6E \t %.6E\n" %
            (xlist[i], nnpdflist[i] / xlist[i], mmhtlist[i] / xlist[i],
             cj15list[i] / xlist[i], ct14list[i] / xlist[i]))
Esempio n. 28
0
def get_stf(X, Q2, tabname, iset, iF2, iFL, iF3):
    stf = lhapdf.mkPDF(tabname, iset)
    F2 = np.array([stf.xfxQ2(iF2, x, Q2) for x in X])
    FL = np.array([stf.xfxQ2(iFL, x, Q2) for x in X])
    F3 = np.array([stf.xfxQ2(iF3, x, Q2) for x in X])
    return F2, FL, F3
Esempio n. 29
0
#! /usr/bin/env python

## Python LHAPDF6 usage example

import lhapdf

## Getting a PDF member object
p = lhapdf.mkPDF("CT10", 0)
p = lhapdf.mkPDF("CT10/0")

## Gluon PDF querying at x=0.001, Q2=10000
print p.xfxQ2(21, 1e-3, 1e4)

## Basic all-flavour PDF querying at x=0.01, Q=M_Z
for pid in p.flavors():
    print p.xfxQ(pid, 0.01, 91.2)

# TODO: demonstrate looping over PDF set members
pset = lhapdf.getPDFSet("CT10nlo")
print pset.description
pcentral = pset.mkPDF(0)
pdfs1 = pset.mkPDFs()
pdfs2 = lhapdf.mkPDFs("CT10nlo") # a direct way to get all the set's PDFs

## Filling a numpy 2D array with xf(x,Q) samples
import numpy as np
xs = [x for x in np.logspace(-7, 0, 5)]
qs = [q for q in np.logspace(1, 4, 4)]
gluon_xfs = np.empty([len(xs), len(qs)])
for ix, x in enumerate(xs):
    for iq, q in enumerate(qs):
Esempio n. 30
0
parser.add_argument("-o", "--outfile", dest="outfile",
                    action="store", type=str, required=True,
                    help='output grid file', metavar="OUTFILE")

parser.add_argument("-n","--noerror", dest="noerror",
                    action="store_true",
                    help='do not rescale error by alphas')

parser.add_argument("-p","--putas", dest="putas",
                    action="store_true",
                    help='multiply (rather than divide) by alphas')

args = parser.parse_args()

mHs = 125.**2
pdf=lhapdf.mkPDF('PDF4LHC15_nlo_100',0)

def s(beta):
    return 4.*mHs/(1-beta**2)

input_grid = np.loadtxt(args.infile).tolist()
output_grid = []

for beta, cost, vfin, vfinerr in input_grid:
    mursq=s(beta)/4
    alphas = pdf.alphasQ2(mursq)
    if args.noerror:
        if args.putas:
            output_grid.append([beta, cost, vfin*(alphas**2), vfinerr])
        else:
            output_grid.append([beta, cost, vfin/(alphas**2), vfinerr])
Esempio n. 31
0
def printGrid():
	for xx in xs.split(" "):
		x = float(xx)
		for QQ in Qs.split(" "):
			Q = float(QQ)
			vs = []
			for pid in pids:
				xf = MorfinTungBxfxQ2(pid,x,Q**2)
				vs.append(xf)
			print (" ".join(map(lambda(v): "%.7e"%v,vs)))
printGrid()

import lhapdf
lhapdf.setVerbosity(0)
pdf = lhapdf.mkPDF("cteq66",0);

def compare():
	for t in range(50):
		x = .27 + t/500.
		pid = -1
		Q2 = 5.**2
		l = pdf.xfxQ2(pid,x,Q2)
		d = MorfinTungBxfxQ2(pid,x,Q2)
		print "x=%e: |%e - %e| = %e i.e. %.4f%%"%(x,l,d,abs(l-d),abs(l-d)/d*100.)
#compare()

def printHeatMap():
	Nx = 150
	NQ2 = 70
	pid = 21
Esempio n. 32
0
def lhapdf_xfs(pdf_name, xs, flavors, Q2):
    pdf_information = lhapdf.getPDFSet(pdf_name)
    n_xs = len(xs)
    Q = np.sqrt(Q2)

    if (pdf_information.errorType == 'hessian') or (pdf_information.errorType
                                                    == 'symmhessian'):
        ## 'lhapdf.getPDFSet("ABMP16_3_nlo").errorType' is 'symmhessian'
        pdf_0 = lhapdf.mkPDF(pdf_name, 0)
        xfs = {}
        for flavor in flavors:
            xfs[flavor] = {
                'center': np.zeros(n_xs),
                'difference': np.zeros(n_xs)
            }
        for i in range(1, ((pdf_information.size - 1) / 2) + 1):
            pdf_plus = lhapdf.mkPDF(pdf_name, 2 * i)
            pdf_minus = lhapdf.mkPDF(pdf_name, 2 * i - 1)
            for j in range(n_xs):
                for flavor in flavors:
                    if flavor == 'uv':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            2, xs[j], Q) - pdf_0.xfxQ(-2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(2, xs[j], Q) -
                            pdf_plus.xfxQ(-2, xs[j], Q) -
                            (pdf_minus.xfxQ(2, xs[j], Q) -
                             pdf_minus.xfxQ(-2, xs[j], Q)))**2.0
                    elif flavor == 'dv':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            1, xs[j], Q) - pdf_0.xfxQ(-1, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(1, xs[j], Q) -
                            pdf_plus.xfxQ(-1, xs[j], Q) -
                            (pdf_minus.xfxQ(1, xs[j], Q) -
                             pdf_minus.xfxQ(-1, xs[j], Q)))**2.0
                    elif flavor == 'u':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(2, xs[j], Q) -
                            pdf_minus.xfxQ(2, xs[j], Q))**2.0
                    elif flavor == 'd':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(1, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(1, xs[j], Q) -
                            pdf_minus.xfxQ(1, xs[j], Q))**2.0
                    elif flavor == 'd/u':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            1, xs[j], Q) / pdf_0.xfxQ(2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            (pdf_plus.xfxQ(1, xs[j], Q) -
                             pdf_minus.xfxQ(1, xs[j], Q)) /
                            pdf_0.xfxQ(2, xs[j], Q))**2.0
                    elif flavor == 'db+ub':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            -1, xs[j], Q) + pdf_0.xfxQ(-2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(-1, xs[j], Q) +
                            pdf_plus.xfxQ(-2, xs[j], Q) -
                            (pdf_minus.xfxQ(-1, xs[j], Q) +
                             pdf_minus.xfxQ(-2, xs[j], Q)))**2.0
                    elif flavor == 'db-ub':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            -1, xs[j], Q) - pdf_0.xfxQ(-2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(-1, xs[j], Q) -
                            pdf_plus.xfxQ(-2, xs[j], Q) -
                            (pdf_minus.xfxQ(-1, xs[j], Q) -
                             pdf_minus.xfxQ(-2, xs[j], Q)))**2.0
                    elif flavor == 's+sb':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            3, xs[j], Q) + pdf_0.xfxQ(-3, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(3, xs[j], Q) +
                            pdf_plus.xfxQ(-3, xs[j], Q) -
                            (pdf_minus.xfxQ(3, xs[j], Q) +
                             pdf_minus.xfxQ(-3, xs[j], Q)))**2.0
                    elif flavor == 'g':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(21, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(21, xs[j], Q) -
                            pdf_minus.xfxQ(21, xs[j], Q))**2.0
                    elif flavor == 'rs':
                        if pdf_name == 'CJ15nlo':
                            ## R_s is set to be 0.4 in CJ15
                            xfs[flavor]['center'][j] = 0.4
                            xfs[flavor]['difference'][j] += 0.0
                        else:
                            xfs[flavor]['center'][j] = (pdf_0.xfxQ(
                                3, xs[j], Q) + pdf_0.xfxQ(-3, xs[j], Q)) / (
                                    pdf_0.xfxQ(-1, xs[j], Q) +
                                    pdf_0.xfxQ(-2, xs[j], Q))
                            xfs[flavor]['difference'][j] += ((pdf_plus.xfxQ(3, xs[j], Q) + pdf_plus.xfxQ(-3, xs[j], Q) - (pdf_minus.xfxQ(3, xs[j], Q) + pdf_minus.xfxQ(-3, xs[j], Q))) / \
                                (pdf_0.xfxQ(-1, xs[j], Q) + pdf_0.xfxQ(-2, xs[j], Q))) ** 2.0

        for flavor in flavors:
            xfs[flavor]['difference'] = 0.5 * np.sqrt(
                xfs[flavor]['difference'])

    elif pdf_information.errorType == 'replicas':
        pdf_all = lhapdf.mkPDFs(pdf_name)

        xfs = {}
        xfs_temp = {}
        for flavor in flavors:
            xfs[flavor] = {'center': [], 'difference': []}
        for i in range(n_xs):
            for flavor in flavors:
                xfs_temp[flavor] = []
            for pdf_individual in pdf_all:
                for flavor in flavors:
                    if flavor == 'uv':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(2, xs[i], Q) -
                            pdf_individual.xfxQ(-2, xs[i], Q))
                    elif flavor == 'dv':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(1, xs[i], Q) -
                            pdf_individual.xfxQ(-1, xs[i], Q))
                    elif flavor == 'u':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(2, xs[i], Q))
                    elif flavor == 'd':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(1, xs[i], Q))
                    elif flavor == 'd/u':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(1, xs[i], Q) /
                            pdf_individual.xfxQ(2, xs[i], Q))
                    elif flavor == 'db+ub':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(-1, xs[i], Q) +
                            pdf_individual.xfxQ(-2, xs[i], Q))
                    elif flavor == 'db-ub':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(-1, xs[i], Q) -
                            pdf_individual.xfxQ(-2, xs[i], Q))
                    elif flavor == 's+sb':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(3, xs[i], Q) +
                            pdf_individual.xfxQ(-3, xs[i], Q))
                    elif flavor == 'g':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(21, xs[i], Q))
                    elif flavor == 'rs':
                        xfs_temp[flavor].append(
                            (pdf_individual.xfxQ(3, xs[i], Q) +
                             pdf_individual.xfxQ(-3, xs[i], Q)) /
                            (pdf_individual.xfxQ(-1, xs[i], Q) +
                             pdf_individual.xfxQ(-2, xs[i], Q)))

            for flavor in flavors:
                xfs[flavor]['center'].append(np.mean(xfs_temp[flavor], axis=0))
                xfs[flavor]['difference'].append(
                    np.std(xfs_temp[flavor], axis=0))

        for flavor in flavors:
            xfs[flavor]['center'] = np.array(xfs[flavor]['center'])
            xfs[flavor]['difference'] = np.array(xfs[flavor]['difference'])

    return xfs
Esempio n. 33
0
def loadPDF(outDir="output", lhapdfDir='xfitter_pdf'):
    lhapdf.pathsAppend(outDir)
    pdf = lhapdf.mkPDF(lhapdfDir)
    return pdf
Esempio n. 34
0
import lhapdf
lhapdf.version()

lhapdf.setPaths(["/home/wdconinc/.local/share/lhapdf"])

p = {}
menu = []
for n in lhapdf.availablePDFSets():
    p[n] = lhapdf.mkPDF(n)
    menu.append((n, n))

import numpy as np
from ipywidgets import interact, fixed

from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, Dropdown, MultiSelect
from bokeh.models.widgets import Tabs, Panel
from bokeh.io import push_notebook, show, output_notebook
from bokeh.plotting import figure

x = np.logspace(-6, 0, 100)
y = [p["CT10"].xfxQ2(1, x, 0.1) for x in x]

plot = []
line = []
panels = []

for i, axis_type in enumerate(["linear", "log"]):
    plot.append(
Esempio n. 35
0
 def pdf(self):
     import lhapdf
     return lhapdf.mkPDF(self.lhapdf)
Esempio n. 36
0
def main(pdfname, pid, no_tex=True):
    """Testing PDFflow vs LHAPDF performance."""
    mpl.rcParams['text.usetex'] = no_tex
    mpl.rcParams['savefig.format'] = 'pdf'
    mpl.rcParams['figure.figsize'] = [11, 5.5]
    mpl.rcParams['axes.titlesize'] = 20
    mpl.rcParams['ytick.labelsize'] = 17
    mpl.rcParams['xtick.labelsize'] = 17
    mpl.rcParams['legend.fontsize'] = 14

    import pdfflow.pflow as pdf

    p = pdf.mkPDF(pdfname, DIRNAME)
    l_pdf = lhapdf.mkPDF(pdfname)
    name = '\_'.join(pdfname.split('_'))

    s = time.time()
    p.trace()
    print("\nPDFflow\n\tBuilding graph time: %f\n" % (time.time() - s))

    fig = plt.figure()
    gs = fig.add_gridspec(nrows=1, ncols=2, wspace=0.05)
    ax = fig.add_subplot(gs[0])
    x = np.logspace(-12, 0, 10000, dtype=float)
    q2 = np.array([1.65, 1.7, 4.92, 1e2, 1e3, 1e4, 1e5, 1e6, 2e6],
                  dtype=float)**2
    for iq2 in q2:
        vl = np.array([l_pdf.xfxQ2(pid, ix, iq2) for ix in x])
        vp = p.py_xfxQ2(pid, float_me(x), float_me([iq2] * len(x)))

        ax.plot(x,
                np.abs(vp - vl) / (np.abs(vl) + EPS),
                label=r'$Q=%s$' % sci_notation(iq2**0.5, 2))

    ax.hlines(1e-3,
              plt.xlim()[0],
              plt.xlim()[1],
              linestyles='dotted',
              color='red')
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlim([1e-12, 1.])
    ax.set_ylim([EPS, .01])

    ax = set_ticks(ax, -12, 0, 13, 'x', 4)
    ax.tick_params(axis='x',
                   which='both',
                   direction='in',
                   bottom=True,
                   labelbottom=True,
                   top=True,
                   labeltop=False)

    ax = set_ticks(ax, -15, -3, 16, 'y')
    ax.tick_params(axis='y',
                   which='both',
                   direction='in',
                   left=True,
                   labelleft=True,
                   right=True,
                   labelright=False)

    ax.set_title(r'%s, flav = %d' % (name, pid))
    ylabel = r'$\displaystyle{r_{i}(x,Q)}$' if no_tex else '$r_{i}$(x,Q)'
    ax.set_ylabel(ylabel, fontsize=20)
    ax.set_xlabel(r'$x$', fontsize=17)
    ax.legend(frameon=False,
              ncol=2,
              loc='upper right',
              bbox_to_anchor=(1.02, 0.9))

    x = np.array([1e-10, 1e-9, 1.1e-9, 5e-7, 1e-6, 1e-4, 1e-2, 0.5, 0.99],
                 dtype=float)
    q2 = np.logspace(1, 7, 10000, dtype=float)**2
    ax = fig.add_subplot(gs[1])
    for ix in x:
        s_time = time.time()
        vl = np.array([l_pdf.xfxQ2(pid, ix, iq2) for iq2 in q2])
        l_time = time.time()
        vp = p.py_xfxQ2(pid, float_me([ix] * len(q2)), float_me(q2))
        p_time = time.time()

        ax.plot(q2**0.5,
                np.abs(vp - vl) / (np.abs(vl) + EPS),
                label=r'$x=%s$' % sci_notation(ix, 1))

    ax.hlines(1e-3,
              plt.xlim()[0],
              plt.xlim()[1],
              linestyles='dotted',
              color='red')
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlim([1, 1e7])
    ax.set_ylim([EPS, .01])

    ax = set_ticks(ax, 1, 7, 9, 'x')
    ax.tick_params(axis='x',
                   which='both',
                   direction='in',
                   top=True,
                   labeltop=False,
                   bottom=True,
                   labelbottom=True)

    ax = set_ticks(ax, -15, -3, 16, 'y')
    ax.tick_params(axis='y',
                   which='both',
                   direction='in',
                   right=True,
                   labelright=False,
                   left=True,
                   labelleft=False)

    ax.set_title(r'%s, flav = %d' % (name, pid))
    ax.set_xlabel(r'$Q$', fontsize=17)
    ax.legend(frameon=False,
              ncol=2,
              loc='upper right',
              bbox_to_anchor=(1.02, 0.9))
    plt.savefig('diff_%s_flav%d.pdf' % (pdfname.replace('/', '-'), pid),
                bbox_inches='tight',
                dpi=250)
    plt.close()

    print("\nDry run time comparison:")
    print("{:>10}:{:>15.8f}".format("lhapdf", l_time - s_time))
    print("{:>10}:{:>15.8f}".format("pdfflow", p_time - l_time))