Esempio n. 1
0
def test_p_roots():
    weightf = orth.legendre(5).weight_func
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, weightf, -1., 1., 5)
    verify_gauss_quad(orth.p_roots,
                      orth.eval_legendre,
                      weightf,
                      -1.,
                      1.,
                      25,
                      atol=1e-13)
    verify_gauss_quad(orth.p_roots,
                      orth.eval_legendre,
                      weightf,
                      -1.,
                      1.,
                      100,
                      atol=1e-12)

    x, w = orth.p_roots(5, False)
    y, v, m = orth.p_roots(5, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    muI, muI_err = integrate.quad(weightf, -1, 1)
    assert_allclose(m, muI, rtol=muI_err)

    assert_raises(ValueError, orth.p_roots, 0)
    assert_raises(ValueError, orth.p_roots, 3.3)
Esempio n. 2
0
def gauss_quad_2d(func, a, b, n, *args):  #Legendre
    [x, wx] = p_roots(n[0] + 1)
    [y, wy] = p_roots(n[1] + 1)
    x, y = np.meshgrid(x, y)
    wx, wy = np.meshgrid(wx, wy)
    I_G = 0.5*(b[0]-a[0])*0.5*(b[1]-a[1])*np.sum(wx*wy*\
              func(0.5*(b[0]-a[0])*x+0.5*(b[0]+a[0]),0.5*(b[1]-a[1])*y+0.5*(b[1]+a[1]),*args))
    return I_G
Esempio n. 3
0
    def __init__(self,n1,n2):
        
        self.n1=n1
        self.n2=n2
        self.xi1,self.w1 = p_roots(n1)
        self.xi2,self.w2 = p_roots(n2)
            
            

        
Esempio n. 4
0
def test_p_roots():
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, 5)
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, 25, atol=1e-13)
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, 100, atol=1e-12)

    x, w = orth.p_roots(5, False)
    y, v, m = orth.p_roots(5, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    assert_raises(ValueError, orth.p_roots, 0)
    assert_raises(ValueError, orth.p_roots, 3.3)
Esempio n. 5
0
def test_p_roots():
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, 5)
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, 25, atol=1e-13)
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, 100, atol=1e-12)

    x, w = orth.p_roots(5, False)
    y, v, m = orth.p_roots(5, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    assert_raises(ValueError, orth.p_roots, 0)
    assert_raises(ValueError, orth.p_roots, 3.3)
Esempio n. 6
0
    def setup(self, L, U, N, discontinuities=None, **kwargs):

        super(GaussQuad, self).setup(L, U, N, **kwargs)

        k = self.k
        L = self.L
        U = self.U
        N = self.N

        if k:
            # compute quad weights and points
            if self.qtype == 'GaussLegendre':
                from scipy.special.orthogonal import p_roots
                xi, w = p_roots(k)
            elif self.qtype == 'ClenshawCurtis':
                import nodes
                xi = np.asarray(map(float, nodes.clenshaw_curtis_nodes(k-1)))
                w  = np.asarray(map(float, nodes.clenshaw_curtis_weights(k-1)))

            # compute cell edges and adjust if necessary
            edges = np.linspace(L, U, N+1)
            jumps = getattr(self, 'discontinuities', discontinuities)
            if self.adjust and jumps:
                edges = adjust(edges, jumps)

            # compute quad weights and points
            x = np.zeros(k*N)
            P = np.zeros(k*N)

            for i in range(N):
                dx2 = 0.5 * (edges[i+1] - edges[i])
                for l in range(k):
                    x[i*k+l] = edges[i] + dx2 * (xi[l] + 1.0)
                    P[i*k+l] = dx2 * w[l]

            self.P = P
            self.x = x

        else:

            # compute quad weights and points
            if self.qtype == 'GaussLegendre':
                from scipy.special.orthogonal import p_roots
                xi, w = p_roots(N)
            elif self.qtype == 'ClenshawCurtis':
                import nodes
                xi = np.asarray(map(float, nodes.clenshaw_curtis_nodes(N-1)))
                w  = np.asarray(map(float, nodes.clenshaw_curtis_weights(N-1)))

            self.P = w * (U - L)/2.0
            self.x = (U + L)/2 + (U - L)/2 * xi
Esempio n. 7
0
File: topo.py Progetto: shigh/pyfem
    def get_quadrature(self, n):
        xg, wg = p_roots(n)
        xg2, wg2 = p_roots(n + 1)
        x = np.zeros((n * (n + 1), 2), dtype=np.double)
        w = np.zeros(n * (n + 1), dtype=np.double)

        for i in range(n + 1):
            for j in range(n):
                p = i * n + j
                x[p, 0] = xg[j]
                x[p, 1] = xg2[i]
                w[p] = wg2[i] * wg[j]

        return x, w
Esempio n. 8
0
def gaussian_latitudes(n):
    """
    Calculate latitudes of Gaussian grid of n values.
    """
    from scipy.special.orthogonal import p_roots

    return np.degrees(np.arcsin(np.real(p_roots(n)[0])))
Esempio n. 9
0
def tminus_longdouble(tmin,tmax,n,norm,root,tp,ntheta=10000,nG=20):
    tplus_func=interp1d(np.log(np.longdouble(tp[:,0])/np.longdouble(tmin)),np.longdouble(tp[:,1]))
    theta=np.logspace(np.log10(np.longdouble(tmin)),np.log10(np.longdouble(tmax)),ntheta)
    # 
    tminus=np.zeros((ntheta,2))
    tminus[:,0]=np.longdouble(theta)
    z=np.log(theta/np.longdouble(tmin))
    tminus[:,1]=tplus_func(z)
    [x,w] = p_roots(nG+1)
    integ_limits=np.insert(np.log(root/tmin),0,0)
    for iz in range(len(z)):
        result=0.
        good_integ=(integ_limits<=z[iz])
        integ_limits_good=integ_limits[good_integ]
        for il in range(1,len(integ_limits_good)):
            delta_limit=integ_limits_good[il]-integ_limits_good[il-1]
            y_in=0.5*delta_limit*x+0.5*(integ_limits_good[il]+integ_limits_good[il-1])
            y=y_in[y_in>=0.]
            result+=delta_limit*0.5*sum(w[y_in>=0.]*tminus_integ(y,z[iz],tplus_func))
        # print(il)
        delta_limit=z[iz]-integ_limits_good[-1]
        y_in=x*(delta_limit*0.5)+(z[iz]+integ_limits_good[-1])*0.5
        y=y_in[y_in>=0.]
        result+=delta_limit*0.5*sum(w[y_in>=0.]*tminus_integ(y,z[iz],tplus_func))
        tminus[iz,1]+=result
    return tminus
Esempio n. 10
0
 def setQuadrature(self, maxOrder, verbose=False):
     super(Uniform, self).setQuadrature(maxOrder)
     pts, wts = quads.p_roots(self.quadOrd)
     self.pts = self.convertToActual(pts)
     for w, wt in enumerate(wts):
         wts[w] = wt / (2. * self.range)
     self.wts = wts
Esempio n. 11
0
def _cached_p_roots(n):

    if n in _cached_p_roots.cache:
        return _cached_p_roots.cache[n]

    _cached_p_roots.cache[n] = p_roots(n)
    return _cached_p_roots.cache[n]
Esempio n. 12
0
def test_p_roots():
    weightf = orth.legendre(5).weight_func
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, weightf, -1.0, 1.0, 5)
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, weightf, -1.0, 1.0, 25, atol=1e-13)
    verify_gauss_quad(orth.p_roots, orth.eval_legendre, weightf, -1.0, 1.0, 100, atol=1e-12)

    x, w = orth.p_roots(5, False)
    y, v, m = orth.p_roots(5, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    muI, muI_err = integrate.quad(weightf, -1, 1)
    assert_allclose(m, muI, rtol=muI_err)

    assert_raises(ValueError, orth.p_roots, 0)
    assert_raises(ValueError, orth.p_roots, 3.3)
Esempio n. 13
0
def gauss1(f, n):
    """gaussian quadrature for weight=1 on (-1,1)"""
    [x,w] = p_roots(n+1)
    result = 0
    for i in range(n+1):
        result = result + w[i]*f(x[i])
    return result
Esempio n. 14
0
    def gauss(self):
        """
        Integrate over the interval 0 to 1. Generate the grid to
        evaluate the function on with scipy.special.orthogonal's
        p_roots, also generates the weights. p_roots gave the gauss
        points in 1d so we make kgrid 3D with itertools.product, then
        shift to 0 to 1. Similarly make the weights 3D. Then run the
        loops according to haw many bands we are calculating.

        """
        self.start = 0
        # For even functions do 0.5
        self.end = 1.0
        self.kgrid, self.weights = p_roots(self.points)
        self.kgrid = np.real(self.kgrid)
        self.kgrid = np.asarray([x for x in product(self.kgrid, repeat=3)])
        self.kgrid = (self.end - self.start) * (self.kgrid +
                                                1) / 2.0 + self.start
        self.weights = np.asarray(
            [np.product(x) for x in product(self.weights, repeat=3)])
        if self.bandnum == 'all':
            for num in range(1, len(self.coeffs.keys()) + 1):
                self.num = str(num)
                self._gaussintegral()
        else:
            for num in range(1, self.bandnum + 1):
                self.num = str(num)
                self._gaussintegral()
Esempio n. 15
0
 def setQuadrature(self,maxOrder,verbose=False):
   super(Uniform,self).setQuadrature(maxOrder)
   pts,wts = quads.p_roots(self.quadOrd)
   self.pts=self.convertToActual(pts)
   for w,wt in enumerate(wts):
     wts[w]=wt/(2.*self.range)
   self.wts=wts
Esempio n. 16
0
    def gauss(self):
        """
        Integrate over the interval 0 to 1. Generate the grid to
        evaluate the function on with scipy.special.orthogonal's
        p_roots, also generates the weights. p_roots gave the gauss
        points in 1d so we make kgrid 3D with itertools.product, then
        shift to 0 to 1. Similarly make the weights 3D. Then run the
        loops according to haw many bands we are calculating.

        """
        self.start = 0
        # For even functions do 0.5
        self.end = 1.0
        self.kgrid, self.weights = p_roots(self.points)
        self.kgrid = np.real(self.kgrid)
        self.kgrid = np.asarray([x for x in product(self.kgrid, repeat=3)])
        self.kgrid = (self.end-self.start)*(self.kgrid+1)/2.0 + self.start
        self.weights = np.asarray([np.product(x) for x in
                                   product(self.weights, repeat=3)])
        if self.bandnum == 'all':
            for num in range(1, len(self.coeffs.keys())+1):
                self.num = str(num)
                self._gaussintegral()
        else:
            for num in range(1, self.bandnum+1):
                self.num = str(num)
                self._gaussintegral()
Esempio n. 17
0
    def __init__(self, calc, xc='RPA', filename=None,
                 skip_gamma=False, qsym=True, nlambda=8,
                 nfrequencies=16, frequency_max=800.0, frequency_scale=2.0,
                 frequencies=None, weights=None, density_cut=1.e-6,
                 wcomm=None, chicomm=None, world=mpi.world,
                 unit_cells=None, tag=None,
                 txt=sys.stdout):

        RPACorrelation.__init__(self, calc, xc=xc, filename=filename,
                                skip_gamma=skip_gamma, qsym=qsym,
                                nfrequencies=nfrequencies, nlambda=nlambda,
                                frequency_max=frequency_max,
                                frequency_scale=frequency_scale,
                                frequencies=frequencies, weights=weights,
                                wcomm=wcomm, chicomm=chicomm, world=world,
                                txt=txt)

        self.l_l, self.weight_l = p_roots(nlambda)
        self.l_l = (self.l_l + 1.0) * 0.5
        self.weight_l *= 0.5
        self.xc = xc
        self.density_cut = density_cut
        if unit_cells is None:
            unit_cells = self.calc.wfs.kd.N_c
        self.unit_cells = unit_cells
        if tag is None:
            tag = self.calc.atoms.get_chemical_formula(mode='hill')
        self.tag = tag
    def discretizeLegendreBis(self, Axis_i):
        x_L = []
        w_L = []
        if (len(self.listOfBorders[Axis_i]) - 1) != len(
                self.listOfNbPointsOnEachIntervalForFinalDiscretization_Axis_k[
                    Axis_i]):
            warnings.warn(
                "error",
                'nb of extremes must be equal to nb of elements in list of nb of points/sub-interval '
            )
        else:
            for i in range(
                    len(self.
                        listOfNbPointsOnEachIntervalForFinalDiscretization_Axis_k[
                            Axis_i])):
                [xi, wi] = p_roots(
                    self.
                    listOfNbPointsOnEachIntervalForFinalDiscretization_Axis_k[
                        Axis_i][i])
                coefi = self.getCoefAffine(self.listOfBorders[Axis_i][i],
                                           self.listOfBorders[Axis_i][i + 1],
                                           -1, 1)
                xi = self.transformeAffine(xi, coefi)
                wi = ((self.listOfBorders[Axis_i][i + 1] -
                       self.listOfBorders[Axis_i][i]) / 2.0) * wi

                x_L = x_L + list(xi)
                w_L = w_L + list(wi)
        self.listOfTuckerGridNodes_Axis_k[Axis_i] = np.asarray(x_L)
        self.weights[Axis_i] = w_L
Esempio n. 19
0
def test_j_roots():
    rf = lambda a, b: lambda n, mu: orth.j_roots(n, a, b, mu)
    ef = lambda a, b: lambda n, x: orth.eval_jacobi(n, a, b, x)
    wf = lambda a, b: lambda x: (1 - x) ** a * (1 + x) ** b

    vgq = verify_gauss_quad
    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1.0, 1.0, 5)
    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1.0, 1.0, 25, atol=1e-12)
    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1.0, 1.0, 100, atol=1e-11)

    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1.0, 1.0, 5)
    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1.0, 1.0, 25, atol=1.5e-13)
    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1.0, 1.0, 100, atol=1e-12)

    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1.0, 1.0, 5, atol=2e-13)
    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1.0, 1.0, 25, atol=2e-13)
    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1.0, 1.0, 100, atol=1e-12)

    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1.0, 1.0, 5)
    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1.0, 1.0, 25, atol=1e-13)
    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1.0, 1.0, 100, atol=2e-13)

    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1.0, 1.0, 5)
    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1.0, 1.0, 25)
    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1.0, 1.0, 100, atol=1e-13)

    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1.0, 1.0, 5, atol=1e-13)
    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1.0, 1.0, 25, atol=2e-13)
    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1.0, 1.0, 100, atol=1e-11)

    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1.0, 1.0, 5)
    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1.0, 1.0, 25, atol=1e-13)
    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1.0, 1.0, 100, atol=1e-13)

    # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
    xj, wj = orth.j_roots(6, 0.0, 0.0)
    xl, wl = orth.p_roots(6)
    assert_allclose(xj, xl, 1e-14, 1e-14)
    assert_allclose(wj, wl, 1e-14, 1e-14)

    # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
    xj, wj = orth.j_roots(6, 4.0, 4.0)
    xc, wc = orth.cg_roots(6, 4.5)
    assert_allclose(xj, xc, 1e-14, 1e-14)
    assert_allclose(wj, wc, 1e-14, 1e-14)

    x, w = orth.j_roots(5, 2, 3, False)
    y, v, m = orth.j_roots(5, 2, 3, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    muI, muI_err = integrate.quad(wf(2, 3), -1, 1)
    assert_allclose(m, muI, rtol=muI_err)

    assert_raises(ValueError, orth.j_roots, 0, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3.3, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3, -2, 1)
    assert_raises(ValueError, orth.j_roots, 3, 1, -2)
    assert_raises(ValueError, orth.j_roots, 3, -2, -2)
Esempio n. 20
0
def gauss(f, a, b, n):
    """gaussian quadrature for weight=1 on (a,b)"""
    [x,w] = p_roots(n+1)
    result = 0
    for i in range(n+1):
        temp = (b-a)*x[i]/2 + (b+a)/2
        result = result + w[i]*f(temp)
    return (b-a)*result/2
Esempio n. 21
0
def gaussian_quadrature(func, n, a, b):
    """ Integrates a function using the Gaussian quadratures of n nodes 
    with accuracy O((b-a)^2*n). """

    x, w = p_roots(n + 1)
    G = 0.5 * (b - a) * sum(w * func(0.5 * (b - a) * x + 0.5 * (b + a)))

    return G
Esempio n. 22
0
def gauss_contour(vertices, points_per_segment):
    """
    On the line connecting each pair of vertices, generates
    points and weights using Gauss-Legendre quadrature.
    """
    segment_count = len(vertices) - 1
    points = weights = sp.empty(0, complex)
    for i in range(segment_count):
        try:    (x, w) = p_roots(points_per_segment[i])
        except: (x, w) = p_roots(points_per_segment)
        a = vertices[i]
        b = vertices[i + 1]
        scaled_x = (x * (b - a) + (a + b))/2
        scaled_w = w * (b - a)/2
        points = sp.hstack((points, scaled_x))
        weights = sp.hstack((weights, scaled_w))
    return (points, weights)
Esempio n. 23
0
 def setQuadrature(self,maxOrder,verbose=False):
   super(Uniform,self).setQuadrature(maxOrder)
   #standard Legendre quadrature
   pts,wts = quads.p_roots(self.quadOrd)
   self.pts,self.wts,self.quadOrds=super(Uniform,self).checkPoints(pts,wts)
   self.quaddict = {}
   for o,order in enumerate(self.quadOrds):
     self.quaddict[order]=(self.pts[o],self.wts[o])
Esempio n. 24
0
def gl_nodes(npts, a, b):
    """
    Return the nodes for `npts`-point Gauss-Legendre quadrature over the
    interval [a, b].
    """
    # The default definition is over [-1, 1]; shift and scale.
    nodes, wts = p_roots(npts)
    # return 0.5*(nodes + 1.)
    return a + 0.5 * (b - a) * (nodes + 1.)
Esempio n. 25
0
def _cached_p_roots(n):
    """
    Cache p_roots results to speed up calls of the fixed_quad function.
    """
    if n in _cached_p_roots.cache:
        return _cached_p_roots.cache[n]

    _cached_p_roots.cache[n] = p_roots(n)
    return _cached_p_roots.cache[n]
Esempio n. 26
0
 def setQuadrature(self, maxOrder, verbose=False):
     super(Uniform, self).setQuadrature(maxOrder)
     #standard Legendre quadrature
     pts, wts = quads.p_roots(self.quadOrd)
     self.pts, self.wts, self.quadOrds = super(Uniform,
                                               self).checkPoints(pts, wts)
     self.quaddict = {}
     for o, order in enumerate(self.quadOrds):
         self.quaddict[order] = (self.pts[o], self.wts[o])
Esempio n. 27
0
def _cached_p_roots(n):
    """
    Cache p_roots results for speeding up multiple calls of the fixed_quad function.
    """
    if n in _cached_p_roots.cache:
        return _cached_p_roots.cache[n]

    _cached_p_roots.cache[n] = p_roots(n)
    return _cached_p_roots.cache[n]
Esempio n. 28
0
def _cached_p_roots(n):
    """
    Cache p_roots results to speed up calls of the fixed_quad function.
    """
    if n in _cached_p_roots.cache:
        return _cached_p_roots.cache[n]

    _cached_p_roots.cache[n] = p_roots(n)
    return _cached_p_roots.cache[n]
Esempio n. 29
0
def _cached_p_roots(n):
    """
    Cache p_roots results for speeding up multiple calls of the fixed_quad function.
    """
    if n in _cached_p_roots.cache:
        return _cached_p_roots.cache[n]

    _cached_p_roots.cache[n] = p_roots(n)
    return _cached_p_roots.cache[n]
Esempio n. 30
0
def gl_nodes(npts, a, b):
    """
    Return the nodes for `npts`-point Gauss-Legendre quadrature over the
    interval [a, b].
    """
    # The default definition is over [-1, 1]; shift and scale.
    nodes, wts = p_roots(npts)
    # return 0.5*(nodes + 1.)
    return a + 0.5*(b - a)*(nodes + 1.)
Esempio n. 31
0
def gauss_nodes(n, a, b):
    """
        Get Gaussian Legraend nodes and weights
    """
    [x, w] = p_roots(n)
    x = (b - a) * x + (b + a)
    x /= 2
    w *= 0.5 * (b - a)
    return x, w
Esempio n. 32
0
def get_gauss_legendre_points(nw=16, frequency_max=800.0, frequency_scale=2.0):
    y_w, weights_w = p_roots(nw)
    ys = 0.5 - 0.5 * y_w
    ys = ys[::-1]
    w = (-np.log(1 - ys))**frequency_scale
    w *= frequency_max / w[-1]
    alpha = (-np.log(1 - ys[-1]))**frequency_scale / frequency_max
    transform = (-np.log(1 - ys))**(frequency_scale - 1) \
        / (1 - ys) * frequency_scale / alpha
    return w, weights_w * transform / 2
    def discretizeLegendre(self, Axis_i):
        [xi, self.weights[Axis_i]] = p_roots(
            self.
            listOfNbPointsOnEachIntervalForFinalDiscretization_Axis_kTotal[
                Axis_i])

        self.getDxiAfterTransf(
            xi, Axis_i)  # Update self.listOfTuckerGridNodes_Axis_k[Axis_i]

        self.weights[Axis_i] = (self.lx[Axis_i] / 2) * self.weights[Axis_i]
Esempio n. 34
0
def gauss_quadratur(xs,a,b,f):
    
    [x,w] = p_roots(len(xs))
    summe = 0.0
    #print len(x)
    for i in range (0,len(x)):
        xu = (b-a)/2 * x[i] + (a+b)/2
        summe = summe + (w[i] * f(xu))
    return (b-a)/2 * summe
    """
Esempio n. 35
0
 def setQuadrature(self, inputfile=None, order=2, verbose=False):
     if verbose:
         print 'set quadrature for', self.name
     #get order from input file
     if inputfile != None:
         self.order = inputfile('Variables/' + self.name + '/order', 2)
     else:
         self.order = order
     #standard legendre quadrature
     self.pts, self.wts = quads.p_roots(self.order)
Esempio n. 36
0
 def setQuadrature(self,inputfile=None,order=2,verbose=False):
   if verbose:
     print 'set quadrature for',self.name
   #get order from input file
   if inputfile != None:
     self.order=inputfile('Variables/'+self.name+'/order',2)
   else:
     self.order=order
   #standard legendre quadrature
   self.pts,self.wts = quads.p_roots(self.order)
Esempio n. 37
0
def test_j_roots():
    roots = lambda a, b: lambda n, mu: orth.j_roots(n, a, b, mu)
    evalf = lambda a, b: lambda n, x: orth.eval_jacobi(n, a, b, x)

    verify_gauss_quad(roots(-0.5, -0.75), evalf(-0.5, -0.75), 5)
    verify_gauss_quad(roots(-0.5, -0.75), evalf(-0.5, -0.75), 25, atol=1e-12)
    verify_gauss_quad(roots(-0.5, -0.75), evalf(-0.5, -0.75), 100, atol=1e-11)

    verify_gauss_quad(roots(0.5, -0.5), evalf(0.5, -0.5), 5)
    verify_gauss_quad(roots(0.5, -0.5), evalf(0.5, -0.5), 25, atol=1e-13)
    verify_gauss_quad(roots(0.5, -0.5), evalf(0.5, -0.5), 100, atol=1e-12)

    verify_gauss_quad(roots(1, 0.5), evalf(1, 0.5), 5, atol=2e-13)
    verify_gauss_quad(roots(1, 0.5), evalf(1, 0.5), 25, atol=2e-13)
    verify_gauss_quad(roots(1, 0.5), evalf(1, 0.5), 100, atol=1e-12)

    verify_gauss_quad(roots(0.9, 2), evalf(0.9, 2), 5)
    verify_gauss_quad(roots(0.9, 2), evalf(0.9, 2), 25, atol=1e-13)
    verify_gauss_quad(roots(0.9, 2), evalf(0.9, 2), 100, atol=2e-13)

    verify_gauss_quad(roots(18.24, 27.3), evalf(18.24, 27.3), 5)
    verify_gauss_quad(roots(18.24, 27.3), evalf(18.24, 27.3), 25)
    verify_gauss_quad(roots(18.24, 27.3), evalf(18.24, 27.3), 100, atol=1e-13)

    verify_gauss_quad(roots(47.1, -0.2), evalf(47.1, -0.2), 5, atol=1e-13)
    verify_gauss_quad(roots(47.1, -0.2), evalf(47.1, -0.2), 25, atol=1e-13)
    verify_gauss_quad(roots(47.1, -0.2), evalf(47.1, -0.2), 100, atol=1e-11)

    verify_gauss_quad(roots(2.25, 68.9), evalf(2.25, 68.9), 5)
    verify_gauss_quad(roots(2.25, 68.9), evalf(2.25, 68.9), 25, atol=1e-13)
    verify_gauss_quad(roots(2.25, 68.9), evalf(2.25, 68.9), 100, atol=1e-13)

    # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
    xj, wj = orth.j_roots(6, 0.0, 0.0)
    xl, wl = orth.p_roots(6)
    assert_allclose(xj, xl, 1e-14, 1e-14)
    assert_allclose(wj, wl, 1e-14, 1e-14)

    # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
    xj, wj = orth.j_roots(6, 4.0, 4.0)
    xc, wc = orth.cg_roots(6, 4.5)
    assert_allclose(xj, xc, 1e-14, 1e-14)
    assert_allclose(wj, wc, 1e-14, 1e-14)

    x, w = orth.j_roots(5, 2, 3, False)
    y, v, m = orth.j_roots(5, 2, 3, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    assert_raises(ValueError, orth.j_roots, 0, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3.3, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3, -2, 1)
    assert_raises(ValueError, orth.j_roots, 3, 1, -2)
    assert_raises(ValueError, orth.j_roots, 3, -2, -2)
Esempio n. 38
0
def fixed_quad(func, a, b, n, args=()):
    [x, w] = p_roots(n)
    x = real(x)
    #y = (b-a)*(x+1)/2.0 + a
    sum_integral = 0
    i = 0
    for xi in x:
        sum_integral = sum_integral + w[i] * func(
            (b - a) * (xi + 1) / 2.0 + a, *args)
        i = i + 1
    return (b - a) / 2.0 * sum_integral
Esempio n. 39
0
def get_gauss_legendre_points(nw=16, frequency_max=800.0, frequency_scale=2.0):
    y_w, weights_w = p_roots(nw)
    y_w = y_w.real
    ys = 0.5 - 0.5 * y_w
    ys = ys[::-1]
    w = (-np.log(1 - ys))**frequency_scale
    w *= frequency_max / w[-1]
    alpha = (-np.log(1 - ys[-1]))**frequency_scale / frequency_max
    transform = (-np.log(1 - ys))**(frequency_scale - 1) \
        / (1 - ys) * frequency_scale / alpha
    return w, weights_w * transform / 2
def fixed_quad_me(func, a, b, args=(), n=5):
    """
    My version of fixed quad which will then be able to sum over NaNs. 
    """
    [x,w] = p_roots(n)
    x = real(x)
    ainf, binf = map(isinf, (a,b))
    if ainf or binf:
        raise ValueError("Gaussian quadrature is only avalible for finite limits.")
    y = (b-a)*(x+1)/2.0 + a
    return (b-a)/2.0*np.nansum(w*func(y,*args),0), None
Esempio n. 41
0
def test_j_roots():
    roots = lambda a, b: lambda n, mu: orth.j_roots(n, a, b, mu)
    evalf = lambda a, b: lambda n, x: orth.eval_jacobi(n, a, b, x)

    verify_gauss_quad(roots(-0.5, -0.75), evalf(-0.5, -0.75), 5)
    verify_gauss_quad(roots(-0.5, -0.75), evalf(-0.5, -0.75), 25, atol=1e-12)
    verify_gauss_quad(roots(-0.5, -0.75), evalf(-0.5, -0.75), 100, atol=1e-11)

    verify_gauss_quad(roots(0.5, -0.5), evalf(0.5, -0.5), 5)
    verify_gauss_quad(roots(0.5, -0.5), evalf(0.5, -0.5), 25, atol=1e-13)
    verify_gauss_quad(roots(0.5, -0.5), evalf(0.5, -0.5), 100, atol=1e-12)

    verify_gauss_quad(roots(1, 0.5), evalf(1, 0.5), 5, atol=2e-13)
    verify_gauss_quad(roots(1, 0.5), evalf(1, 0.5), 25, atol=2e-13)
    verify_gauss_quad(roots(1, 0.5), evalf(1, 0.5), 100, atol=1e-12)

    verify_gauss_quad(roots(0.9, 2), evalf(0.9, 2), 5)
    verify_gauss_quad(roots(0.9, 2), evalf(0.9, 2), 25, atol=1e-13)
    verify_gauss_quad(roots(0.9, 2), evalf(0.9, 2), 100, atol=2e-13)

    verify_gauss_quad(roots(18.24, 27.3), evalf(18.24, 27.3), 5)
    verify_gauss_quad(roots(18.24, 27.3), evalf(18.24, 27.3), 25)
    verify_gauss_quad(roots(18.24, 27.3), evalf(18.24, 27.3), 100, atol=1e-13)

    verify_gauss_quad(roots(47.1, -0.2), evalf(47.1, -0.2), 5, atol=1e-13)
    verify_gauss_quad(roots(47.1, -0.2), evalf(47.1, -0.2), 25, atol=1e-13)
    verify_gauss_quad(roots(47.1, -0.2), evalf(47.1, -0.2), 100, atol=1e-11)

    verify_gauss_quad(roots(2.25, 68.9), evalf(2.25, 68.9), 5)
    verify_gauss_quad(roots(2.25, 68.9), evalf(2.25, 68.9), 25, atol=1e-13)
    verify_gauss_quad(roots(2.25, 68.9), evalf(2.25, 68.9), 100, atol=1e-13)

    # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
    xj, wj = orth.j_roots(6, 0.0, 0.0)
    xl, wl = orth.p_roots(6)
    assert_allclose(xj, xl, 1e-14, 1e-14)
    assert_allclose(wj, wl, 1e-14, 1e-14)

    # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
    xj, wj = orth.j_roots(6, 4.0, 4.0)
    xc, wc = orth.cg_roots(6, 4.5)
    assert_allclose(xj, xc, 1e-14, 1e-14)
    assert_allclose(wj, wc, 1e-14, 1e-14)

    x, w = orth.j_roots(5, 2, 3, False)
    y, v, m = orth.j_roots(5, 2, 3, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    assert_raises(ValueError, orth.j_roots, 0, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3.3, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3, -2, 1)
    assert_raises(ValueError, orth.j_roots, 3, 1, -2)
    assert_raises(ValueError, orth.j_roots, 3, -2, -2)
Esempio n. 42
0
 def ft(self, x):
     x = x * self._supp * np.pi
     nroots = 2 * self._supp
     if self._supp % 2 == 0:
         nroots += 1
     q, weights = p_roots(nroots)
     ind = q > 0
     weights = weights[ind]
     q = q[ind]
     kq = np.outer(x, q) if len(x.shape) == 1 else np.einsum(
         'ij,k->ijk', x, q)
     arr = np.sum(weights * self._raw(q) * np.cos(kq), axis=-1)
     return self._supp * arr
Esempio n. 43
0
def quad_data(n, interval):
    from scipy.special.orthogonal import p_roots

    a, b = interval

    # transform gauss quadrature data
    midpoint = (a+b)/2
    length = b-a
    orig_particles, orig_gauss_weights = p_roots(n)
    particles = [midpoint + x*length/2 for x in orig_particles]
    gauss_weights = length/2*orig_gauss_weights

    return particles, gauss_weights
Esempio n. 44
0
def quad_data(n, interval):
    from scipy.special.orthogonal import p_roots

    a, b = interval

    # transform gauss quadrature data
    midpoint = (a + b) / 2
    length = b - a
    orig_particles, orig_gauss_weights = p_roots(n)
    particles = [midpoint + x * length / 2 for x in orig_particles]
    gauss_weights = length / 2 * orig_gauss_weights

    return particles, gauss_weights
Esempio n. 45
0
def rule(n,a=0.,b=1.,kind='legendre'):
    # if table entry does not exist, generate it
    try:
        x,w=quad_table[kind+'_'+str(n)]
    except:
        if kind=='legendre': x,w=so.p_roots(n)
        else: sys.exit('undefined quadrature kind "'+kind+'"')

        # append to table
        quad_table.setdefault[kind+'_'+str(n),(x,w)]


    # return shifted and scaled rule
    return a+x*(b-a),w*(b-a)
Esempio n. 46
0
File: topo.py Progetto: shigh/pyfem
    def get_quadrature(self, n):
        xg, wg = p_roots(n)
        x = np.zeros((n ** 3, 3), dtype=np.double)
        w = np.zeros(n ** 3, dtype=np.double)

        for i in range(n):
            for j in range(n):
                for k in range(n):
                    p = i * n * n + j * n + k
                    x[p, 0] = xg[k]
                    x[p, 1] = xg[j]
                    x[p, 2] = xg[i]
                    w[p] = wg[i] * wg[j] * wg[k]

        return x, w
Esempio n. 47
0
def gauss_contour(vertices, order):
    """
Generates a contour using Gauss-Legendre quadrature.
"""
    (x, w) = p_roots(order)
    num_segments = len(vertices) - 1
    points = weights = sp.empty(0, complex)
    for i in range(num_segments):
        a = vertices[i]
        b = vertices[i + 1]
        scaled_x = (x * (b - a) + (a + b))/2
        scaled_w = w * (b - a)/2
        points = sp.hstack((points, scaled_x))
        weights = sp.hstack((weights, scaled_w))
    return (points, weights)
def fixed_quad(func,a,b,args=(),n=5):
    """
    Compute a definite integral using fixed-order Gaussian quadrature.

    Integrate `func` from `a` to `b` using Gaussian quadrature of
    order `n`.

    Parameters
    ----------
    func : callable
        A Python function or method to integrate (must accept vector inputs).
    a : float
        Lower limit of integration.
    b : float
        Upper limit of integration.
    args : tuple, optional
        Extra arguments to pass to function, if any.
    n : int, optional
        Order of quadrature integration. Default is 5.

    Returns
    -------
    val : float
        Gaussian quadrature approximation to the integral

    See Also
    --------
    quad : adaptive quadrature using QUADPACK
    dblquad : double integrals
    tplquad : triple integrals
    romberg : adaptive Romberg quadrature
    quadrature : adaptive Gaussian quadrature
    romb : integrators for sampled data
    simps : integrators for sampled data
    cumtrapz : cumulative integration for sampled data
    ode : ODE integrator
    odeint : ODE integrator

    """
    [x,w] = p_roots(n)
    x = real(x)
    ainf, binf = map(isinf,(a,b))
    if ainf or binf:
        raise ValueError("Gaussian quadrature is only available for "
                "finite limits.")
    y = (b-a)*(x+1)/2.0 + a
    return (b-a)/2.0*sum(w*func(y,*args),0), None
Esempio n. 49
0
    def __init__(self, k=None, qtype='GaussLegendre'):

        if k:
            if qtype == 'GaussLegendre':
                name = 'GENClarkGL(' + str(k) + ')'
                from scipy.special.orthogonal import p_roots
                self.xi, self.w = p_roots(k)
            elif qtype == 'ClenshawCurtis':
                name = 'GENClarkCC(' + str(k) + ')'
                import nodes
                self.xi = np.asarray(map(float, nodes.clenshaw_curtis_nodes(k-1)))
                self.w  = np.asarray(map(float, nodes.clenshaw_curtis_weights(k-1)))
        else:
            name = 'GENClarkQP'

        self.k = k
        self.name = name
Esempio n. 50
0
    def __init__(self,
                 calc,
                 xc='RPA',
                 filename=None,
                 skip_gamma=False,
                 qsym=True,
                 nlambda=8,
                 nfrequencies=16,
                 frequency_max=800.0,
                 frequency_scale=2.0,
                 frequencies=None,
                 weights=None,
                 density_cut=1.e-6,
                 world=mpi.world,
                 nblocks=1,
                 unit_cells=None,
                 tag=None,
                 txt=sys.stdout):

        RPACorrelation.__init__(self,
                                calc,
                                xc=xc,
                                filename=filename,
                                skip_gamma=skip_gamma,
                                qsym=qsym,
                                nfrequencies=nfrequencies,
                                nlambda=nlambda,
                                frequency_max=frequency_max,
                                frequency_scale=frequency_scale,
                                frequencies=frequencies,
                                weights=weights,
                                world=world,
                                nblocks=nblocks,
                                txt=txt)

        self.l_l, self.weight_l = p_roots(nlambda)
        self.l_l = (self.l_l + 1.0) * 0.5
        self.weight_l *= 0.5
        self.xc = xc
        self.density_cut = density_cut
        if unit_cells is None:
            unit_cells = self.calc.wfs.kd.N_c
        self.unit_cells = unit_cells
        if tag is None:
            tag = self.calc.atoms.get_chemical_formula(mode='hill')
        self.tag = tag
def quad01(n,kind='gauss-legendre'):
    """get n-point quadrature rules on [0,1] and keep them in table
    
    """

    try:
        x,w=quad01_table[kind+'_'+str(n)]
    except:
        # if table entry does not exist, generate it
        if kind=='gauss-legendre': 
            x,w=so.p_roots(n)
            x=(x+1)/2
            w=w/2
        else:
            sys.exit('undefined quadrature kind="'+kind+'"')
        quad01_table[kind+'_'+str(n)]=(x,w)

    return x,w
    def integrate(self, n, m=None):
        # for simplicity, I'm not going to implement subitervals
        # I'm pretty sure with Guassian Quadrature it doesn't make sense to
        # and you will get a better approximation using the full function
        """
        if m is None:
            m = self.N

        subintervals = self._get_subintervals(m)
        """

        # I couldn't figure out how to calculate the quadrature weights manually
        # so we cheat and use scipy
        [X, A] = p_roots(n)

        if self.verbose:
            print("X:", X)
            print("A:", A)
            print()

        # The above assume (a, b) = (-1, 1)
        # we do a change of variables to convert them to any interval
        scale, shift = self.change_of_variables(self.a, self.b)
        X = [shift + scale * x for x in X]
        A = [scale * Ai for Ai in A]

        if self.verbose:
            print("CoV X:", X)
            print("CoV A:", A)
            print()

        # I add these only so the printing looks better
        #X = [self.a] + X + [self.b]
        #A = [0] + A + [0]

        # reinitializing everything so our functions work
        super(GaussianQuadrature, self).__init__(X,
                                                 self.f,
                                                 var=str(self.var),
                                                 verbose=self.verbose)

        # calling our generic quadrature integration approximation
        return super(GaussianQuadrature, self).integrate(A=A)
Esempio n. 53
0
    def calculate_error_l2_norm(self, dY):
        """
        Returns the L2 norm of the vector dY.

        E.g. the square root of the sum of squares of the components of dY.
        """
        solutions = []
        norm = 0.
        for mi in range(len(self._meshes)):
            for ei in range(len(self._meshes[mi].elements)):
                e = self._meshes[mi].elements[ei]
                # change this to gauss points:
                x_vals, w = p_roots(20)
                norm_e_squared = 0.
                for i, x in enumerate(x_vals):
                    norm_e_squared += w[i] * \
                            self.get_sol_value(mi, ei, dY, x,
                                    count_lift=False)**2
                norm_e_squared *= e.jacobian
                norm += norm_e_squared
        return sqrt(norm)
Esempio n. 54
0
def fixed_quad(func,a,b,args=(),n=5):
    """Compute a definite integral using fixed-order Gaussian quadrature.

  Description:

    Integrate func from a to b using Gaussian quadrature of order n.

  Inputs:

    func -- a Python function or method to integrate
            (must accept vector inputs)
    a -- lower limit of integration
    b -- upper limit of integration
    args -- extra arguments to pass to function.
    n -- order of quadrature integration.

  Outputs: (val, None)

    val -- Gaussian quadrature approximation to the integral.

  See also:

    quad - adaptive quadrature using QUADPACK
    dblquad, tplquad - double and triple integrals
    romberg - adaptive Romberg quadrature
    quadrature - adaptive Gaussian quadrature
    romb, simps, trapz - integrators for sampled data
    cumtrapz - cumulative integration for sampled data
    ode, odeint - ODE integrators
    """
    [x,w] = p_roots(n)
    x = real(x)
    ainf, binf = map(isinf,(a,b))
    if ainf or binf:
        raise ValueError, "Gaussian quadrature is only available for " \
              "finite limits."
    y = (b-a)*(x+1)/2.0 + a
    return (b-a)/2.0*sum(w*func(y,*args),0), None
Esempio n. 55
0
def fixed_quad(func, a, b, args=(), n=5):
    """Compute a definite integral using fixed-order Gaussian quadrature.

  Description:

    Integrate func from a to b using Gaussian quadrature of order n.

  Inputs:

    func -- a Python function or method to integrate
            (must accept vector inputs)
    a -- lower limit of integration
    b -- upper limit of integration
    args -- extra arguments to pass to function.
    n -- order of quadrature integration.

  Outputs: (val, None)

    val -- Gaussian quadrature approximation to the integral.

  See also:

    quad - adaptive quadrature using QUADPACK
    dblquad, tplquad - double and triple integrals
    romberg - adaptive Romberg quadrature
    quadrature - adaptive Gaussian quadrature
    romb, simps, trapz - integrators for sampled data
    cumtrapz - cumulative integration for sampled data
    ode, odeint - ODE integrators
    """
    [x, w] = p_roots(n)
    x = real(x)
    ainf, binf = map(isinf, (a, b))
    if ainf or binf:
        raise ValueError, "Gaussian quadrature is only available for " \
              "finite limits."
    y = (b - a) * (x + 1) / 2.0 + a
    return (b - a) / 2.0 * sum(w * func(y, *args), 0), None
Esempio n. 56
0
def test_j_roots():
    rf = lambda a, b: lambda n, mu: orth.j_roots(n, a, b, mu)
    ef = lambda a, b: lambda n, x: orth.eval_jacobi(n, a, b, x)
    wf = lambda a, b: lambda x: (1 - x)**a * (1 + x)**b

    vgq = verify_gauss_quad
    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., 5)
    vgq(rf(-0.5, -0.75),
        ef(-0.5, -0.75),
        wf(-0.5, -0.75),
        -1.,
        1.,
        25,
        atol=1e-12)
    vgq(rf(-0.5, -0.75),
        ef(-0.5, -0.75),
        wf(-0.5, -0.75),
        -1.,
        1.,
        100,
        atol=1e-11)

    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 5)
    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 25, atol=1.5e-13)
    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 100, atol=1e-12)

    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 5, atol=2e-13)
    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 25, atol=2e-13)
    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 100, atol=1e-12)

    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 5)
    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 25, atol=1e-13)
    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 100, atol=2e-13)

    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 5)
    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 25)
    vgq(rf(18.24, 27.3),
        ef(18.24, 27.3),
        wf(18.24, 27.3),
        -1.,
        1.,
        100,
        atol=1e-13)

    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 5, atol=1e-13)
    vgq(rf(47.1, -0.2),
        ef(47.1, -0.2),
        wf(47.1, -0.2),
        -1.,
        1.,
        25,
        atol=2e-13)
    vgq(rf(47.1, -0.2),
        ef(47.1, -0.2),
        wf(47.1, -0.2),
        -1.,
        1.,
        100,
        atol=1e-11)

    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 5)
    vgq(rf(2.25, 68.9),
        ef(2.25, 68.9),
        wf(2.25, 68.9),
        -1.,
        1.,
        25,
        atol=1e-13)
    vgq(rf(2.25, 68.9),
        ef(2.25, 68.9),
        wf(2.25, 68.9),
        -1.,
        1.,
        100,
        atol=1e-13)

    # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
    xj, wj = orth.j_roots(6, 0.0, 0.0)
    xl, wl = orth.p_roots(6)
    assert_allclose(xj, xl, 1e-14, 1e-14)
    assert_allclose(wj, wl, 1e-14, 1e-14)

    # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
    xj, wj = orth.j_roots(6, 4.0, 4.0)
    xc, wc = orth.cg_roots(6, 4.5)
    assert_allclose(xj, xc, 1e-14, 1e-14)
    assert_allclose(wj, wc, 1e-14, 1e-14)

    x, w = orth.j_roots(5, 2, 3, False)
    y, v, m = orth.j_roots(5, 2, 3, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    muI, muI_err = integrate.quad(wf(2, 3), -1, 1)
    assert_allclose(m, muI, rtol=muI_err)

    assert_raises(ValueError, orth.j_roots, 0, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3.3, 1, 1)
    assert_raises(ValueError, orth.j_roots, 3, -2, 1)
    assert_raises(ValueError, orth.j_roots, 3, 1, -2)
    assert_raises(ValueError, orth.j_roots, 3, -2, -2)
Esempio n. 57
0
    def Telles(self, pxi1, pxi2, e, mesh, k):
        # Collocation point at (pxi1,pxi2)
        # See research log pg. 789
        xy = np.array((
            [-1, 1, -1, -1],  # T1
            [1, 1, -1, 1],  # T2
            [1, -1, 1, 1],  # T3
            [-1, -1, 1, -1]))  # T4

        # Ftheta function
        def F(i, theta):
            if i == 0:
                return (-1 - pxi2) / np.sin(theta)
            elif i == 1:
                return (1 - pxi1) / np.cos(theta)
            elif i == 2:
                return (1 - pxi2) / np.sin(theta)
            elif i == 3:
                return (-1 - pxi1) / np.cos(theta)

        # Which triangles to calculate
        which = np.array([False, False, False, False])
        if pxi2 > -1:
            which[0] = True
        if pxi1 < 1:
            which[1] = True
        if pxi2 < 1:
            which[2] = True
        if pxi1 > -1:
            which[3] = True

        xi1 = []
        xi2 = []
        w1 = []
        w2 = []
        J = []
        for i in xrange(4):
            if which[i]:

                x1, x2, y1, y2 = xy[i]
                theta1 = np.arctan2(y1 - pxi2, x1 - pxi1)
                theta2 = np.arctan2(y2 - pxi2, x2 - pxi1)
                if theta1 < 0: theta1 += 2 * np.pi
                if i == 1 and theta1 > 0: theta1 -= 2 * np.pi
                if theta2 < 0: theta2 += 2 * np.pi
                theta, wtheta = p_roots(self.n1)
                theta = theta * 0.5 * (theta2 - theta1) + 0.5 * (theta1 +
                                                                 theta2)
                wtheta = wtheta * 0.5 * (theta2 - theta1)

                if e.num_integration_cells > 1:
                    s = np.arange(0, e.num_integration_cells).reshape(-1, 1)
                    theta = (
                        (theta - theta1 +
                         (theta2 - theta1) * s) / e.num_integration_cells +
                        theta1).reshape(-1, )
                    wtheta = np.repeat([wtheta / e.num_integration_cells],
                                       e.num_integration_cells,
                                       axis=0).reshape(-1, )

                Ftheta = F(i, theta)
                theta = (np.repeat(theta, self.n2))
                wtheta = (np.repeat(wtheta, self.n2))
                rho, wrho = p_roots(self.n2)

                if e.num_integration_cells > 1:
                    rho = ((rho - 1 + 2 * s) / e.num_integration_cells +
                           1).reshape(-1, )
                    wrho = np.repeat([wrho / e.num_integration_cells],
                                     e.num_integration_cells,
                                     axis=0).reshape(-1, )

                rho = np.vstack([rho * 0.5 * Ftheta[i] + 0.5 * Ftheta[i]]
                                for i in xrange(self.n1)).reshape(-1, )
                wrho = np.vstack([wrho * 0.5 * Ftheta[i]]
                                 for i in xrange(self.n1)).reshape(-1, )

                xi1.append(rho * np.cos(theta) + pxi1)
                xi2.append(rho * np.sin(theta) + pxi2)
                w1.append(wtheta)
                w2.append(wrho)
                J.append(rho)

        xi1 = np.array(xi1).reshape(-1, )
        xi2 = np.array(xi2).reshape(-1, )
        w1 = np.array(w1).reshape(-1, )
        w2 = np.array(w2).reshape(-1, )
        J = np.array(J).reshape(-1, )

        return xi1, xi2, w1 * J, w2 * J