예제 #1
0
 def test_legroots(self) :
     assert_almost_equal(leg.legroots([1]), [])
     assert_almost_equal(leg.legroots([1, 2]), [-.5])
     for i in range(2, 5) :
         tgt = np.linspace(-1, 1, i)
         res = leg.legroots(leg.legfromroots(tgt))
         assert_almost_equal(trim(res), trim(tgt))
예제 #2
0
 def test_legroots(self) :
     assert_almost_equal(leg.legroots([1]), [])
     assert_almost_equal(leg.legroots([1, 2]), [-.5])
     for i in range(2,5) :
         tgt = np.linspace(-1, 1, i)
         res = leg.legroots(leg.legfromroots(tgt))
         assert_almost_equal(trim(res), trim(tgt))
예제 #3
0
def weights_roots(order, rules='Gauss-Lobatto'):
    c_leg = [1] if order == 0 else [i//order for i in xrange(order+1)]
    c_dleg = lgd.legder(c_leg)

    if rules == 'Gauss-Lobatto':
        xs = np.array( [-1] + list( lgd.legroots(c_dleg) ) + [1] )
        ws = 2 / ( order * (order + 1) * (lgd.legval(xs, c_leg)**2) )

    elif rules == 'Gauss-Legendre':
        xs = lgd.legroots(c_leg)
        ws = 2 / ( (1 - xs**2) * (lgd.legval(xs, c_dleg)**2) )

    return xs, ws
예제 #4
0
	def _legendre_roots(self, c):
		r""" Compute the roots of the scaled and shifted Legendre polynomial
		"""
		lam = legroots(c)
		lam = self._inverse_transform(lam)		

		return lam
예제 #5
0
    def make_grid(self):
        import numpy as np
        from numpy.polynomial.legendre import legder, legroots, legval

        N = self._N
        self.NN = N + 1
        L = self.L

        factor = L / 2

        d1 = np.zeros((N + 1, N + 1))

        cp = legder([0] * N + [1])
        zg = np.hstack([-1.0, legroots(cp), 1.0])

        P_N = legval(zg, [0] * N + [1])

        with np.errstate(divide='ignore'):
            d1 = P_N[:, None] / (P_N[None, :] * (zg[:, None] - zg[None, :]))

        d1[np.diag_indices(N + 1)] = 0.0
        d1[0, 0] = -N * (N + 1) / 4
        d1[N, N] = +N * (N + 1) / 4

        d2 = np.dot(d1, d1)

        self.zg = (zg + 1) * L / 2 + self.zmin
        self.d0 = np.eye(self.NN)
        self.d1 = d1 / factor
        self.d2 = d2 / factor**2

        # Call other objects that depend on the grid
        for callback in self._observers:
            callback()
예제 #6
0
def GL_Quad_2D(integrand, lowZ, upZ, lowPhi, upPhi, N, args):
    #Weight Function
    def weight(arg):
        w = (2.0 * (1 - (arg**2))) / (
            (N * (Legendre(arg, N - 1) - arg * Legendre(arg, N)))**2)
        return w

    #Create list of roots for P_N
    rootIndex = np.zeros(N + 1)
    rootIndex[N] = 1
    roots = legroots(rootIndex)

    #Equally spaced points for trapzeoidal integration method for phi
    Npoints = 100
    deltaPhi = (upPhi - lowPhi) / Npoints
    phiVals = np.linspace(lowPhi, upPhi, Npoints + 1)

    value = 0
    for z_i in roots:
        phiValue = 0
        for phi in phiVals:
            phiValue = (deltaPhi) * integrand(
                ((upZ - lowZ) / 2.0) * z_i +
                ((upZ + lowZ) / 2.0), phi, *args) + phiValue
        value = weight(z_i) * phiValue + value

    value = ((upZ - lowZ) / 2.0) * value
    return value
    def _getNodes(self):
        """
        Computes Gauss-Lobatto integration nodes.

        Calculates the Gauss-Lobatto integration nodes via a root calculation of derivatives of the legendre
        polynomials. Note that the precision of float 64 is not guarantied.

        Copyright by Dieter Moser, 2014

        Returns:
            np.ndarray: array of Gauss-Lobatto nodes
        """

        M = self.num_nodes
        a = self.tleft
        b = self.tright

        roots = leg.legroots(
            leg.legder(np.array([0] * (M - 1) + [1], dtype=np.float64)))
        nodes = np.array(np.append([-1.0], np.append(roots, [1.0])),
                         dtype=np.float64)

        nodes = (a * (1 - nodes) + b * (1 + nodes)) / 2

        return nodes
예제 #8
0
def GL_Quad(integrand, lowerBound, upperBound, N, args):
    #Weight Function
    def weight(x):
        w = (2.0 * (1 -
                    (x**2))) / ((N *
                                 (Legendre(x, N - 1) - x * Legendre(x, N)))**2)
        return w

    #Create list of roots for P_N
    rootIndex = np.zeros(N + 1)
    rootIndex[N] = 1
    roots = legroots(rootIndex)

    value = 0
    for x_i in roots:
        value = weight(x_i) * integrand(
            ((upperBound - lowerBound) / 2.0) * x_i +
            ((upperBound + lowerBound) / 2.0), *args) + value

    value = ((upperBound - lowerBound) / 2.0) * value
    return value


# def test(x, N, fn):
#     val = np.cos(x)
#     return val
#
# def randomness(x):
#     return 0
#
# Nval = 10
# integralValue = GL_Quad(test, -3, 3, 20, args=(10, randomness,))
# print integralValue - 2*np.sin(3)
예제 #9
0
파일: scaling.py 프로젝트: bjorgve/mrpy
def roots(order):
    coef = []
    for n in range(0, order+1):
        if n == order:
            coef.append(1)
        else:
            coef.append(0)
    return .5*(leg.legroots(coef) + 1)
예제 #10
0
def quad_custom(fun, n=10):
    P_n = [0 for i in range(1, n)] + [1]
    P_n_roots = leg.legroots(P_n)
    d_P_n = leg.legder(P_n)
    d_P_n_vals = leg.legval(P_n_roots, d_P_n)
    weights = 2 / ((1 - np.power(P_n_roots, 2)) * np.power(d_P_n_vals, 2))
    result = np.sum(weights * fun(P_n_roots))
    return result
예제 #11
0
 def test_collocation_points_legendre_gauss(self):
     for num_coll_points in range(2, 13):
         coefs = np.zeros(num_coll_points + 1)
         coefs[-1] = 1.
         coll_points_numpy = legendre.legroots(coefs)
         mesh = Mesh1D(num_coll_points, Basis.Legendre, Quadrature.Gauss)
         coll_points_spectre = collocation_points(mesh)
         np.testing.assert_allclose(coll_points_numpy, coll_points_spectre,
                                    1e-12, 1e-12)
예제 #12
0
파일: SP_FP.py 프로젝트: jeandeville/PIE
def defFluxPoints(n):
    res = np.zeros(n)
    res[0] = -1.0
    res[-1] = 1.0
    coeff = np.zeros(n - 1)
    coeff[-1] = 1.0
    roots = leg.legroots(coeff)
    for i in range(1, n - 1):
        res[i] = roots[i - 1]
    return res
예제 #13
0
파일: roots.py 프로젝트: joedaws/qonet
def leg_roots_vec():
    roots = {}
    # loop over all degrees up to MAXD
    for i in range(0, MAXD):
        c = np.zeros(MAXD)
        c[i] = 1
        r = leg.legroots(c)
        roots.update({i: r})

    return roots
예제 #14
0
    def _compute_nodes(self):
        """Computes Gauss-Lobatto integration nodes.

        Calculates the Gauss-Lobatto integration nodes via a root calculation of derivatives of the legendre
        polynomials.
        Note that the precision of float 64 is not guarantied.
        """
        roots = leg.legroots(leg.legder(np.array([0] * (self.num_nodes - 1) +
                                                 [1], dtype=np.float64)))
        self._nodes = np.array(np.append([-1.0], np.append(roots, [1.0])),
                               dtype=np.float64)
예제 #15
0
def GaussQuad(f, xi, xf, n, M):
    I = 0
    c = np.append(np.zeros(M), 1)
    x = lg.legroots(c)
    w = 0 * x
    d = lg.legder(c)
    for i in range(len(x)):
        w[i] = 2. / ((1 - x[i]**2) * (lg.legval(x[i], d))**2)
    for i in range(M):
        I += w[i] * f(n, interval(x[i], xf, xi))
    I *= 0.5 * (xf - xi)

    return I
예제 #16
0
파일: roots.py 프로젝트: joedaws/qonet
def get_leg_scalfac(deg):
    testpt = 0.5
    c = np.zeros(MAXD)
    c[deg] = 1
    val = leg.legval(testpt, c, tensor=False)
    r = leg.legroots(c)
    prod = 1
    for root in r:
        prod = prod * (testpt - root)

    scalfac = val / prod

    return scalfac
예제 #17
0
def get_leg_roots():
    roots = {}
    # loop over all degrees up to MAXD
    for i in range(0, MAXD):
        c = np.zeros(MAXD)
        c[i] = 1
        r = leg.legroots(c)
        roots.update({i: r})

    # save roots to file
    w = csv.writer(open(LEGF, "w"))
    for key, val in roots.items():
        w.writerow([key, val])

    return
예제 #18
0
def gauss_lobatto_points(start, stop, num_points):
    r"""Get the node points for Gauss-Lobatto quadrature.

    Using :math:`n` points, this quadrature is accurate to degree
    :math:`2n - 3`. The node points are :math:`x_1 = -1`,
    :math:`x_n = 1` and the interior are :math:`n - 2` roots of
    :math:`P'_{n - 1}(x)`.

    Though we don't compute them here, the weights are
    :math:`w_1 = w_n = \frac{2}{n(n - 1)}` and for the interior points

    .. math::

       w_j = \frac{2}{n(n - 1) \left[P_{n - 1}\left(x_j\right)\right]^2}

    This is in contrast to the scheme used in Gaussian quadrature, which
    use roots of :math:`P_n(x)` as nodes and use the weights

    .. math::

       w_j = \frac{2}{\left(1 - x_j\right)^2
                \left[P'_n\left(x_j\right)\right]^2}

    .. note::

       This method is **not** generic enough to accommodate non-NumPy
       types as it relies on the :mod:`numpy.polynomial.legendre`.

    :type start: float
    :param start: The beginning of the interval.

    :type stop: float
    :param stop: The end of the interval.

    :type num_points: int
    :param num_points: The number of points to use.

    :rtype: :class:`numpy.ndarray`
    :returns: 1D array, the interior quadrature nodes.
    """
    p_n_minus1 = [0] * (num_points - 1) + [1]
    inner_nodes = legendre.legroots(legendre.legder(p_n_minus1))
    # Utilize symmetry about 0.
    inner_nodes = 0.5 * (inner_nodes - inner_nodes[::-1])
    if start != -1.0 or stop != 1.0:
        # [-1, 1] --> [0, 2] --> [0, stop - start] --> [start, stop]
        inner_nodes = start + (inner_nodes + 1.0) * 0.5 * (stop - start)
    return np.hstack([[start], inner_nodes, [stop]])
예제 #19
0
    def _getNodes(self):
        """
        Copyright by Dieter Moser, 2014
        Computes Gauss-Lobatto integration nodes.

        Calculates the Gauss-Lobatto integration nodes via a root calculation of derivatives of the legendre
        polynomials. Note that the precision of float 64 is not guarantied.
        """
        M = self.num_nodes
        a = self.tleft
        b = self.tright

        roots = leg.legroots(leg.legder(np.array([0] * (M - 1) + [1], dtype=np.float64)))
        nodes = np.array(np.append([-1.0], np.append(roots, [1.0])), dtype=np.float64)

        nodes = (a * (1 - nodes) + b * (1 + nodes)) / 2

        return nodes
예제 #20
0
def GL_Quad_2D(integrand, lowZ, upZ, lowPhi, upPhi, N, round, args):

    if round == 1:

        def conformalFactor(z, phi):
            return 1
    elif round == 0:

        def conformalFactor(z, phi):
            return psi4(z, phi)

    #Weight Function
    def weight(arg):
        w = (2.0 * (1 - (arg**2))) / (
            (N * (Legendre(arg, N - 1) - arg * Legendre(arg, N)))**2)
        return w

    #Create list of roots for P_N
    rootIndex = np.zeros(N + 1)
    rootIndex[N] = 1
    roots = legroots(rootIndex)

    #Equally spaced points for trapzeoidal integration method for phi
    Npoints = 100
    deltaPhi = (upPhi - lowPhi) / Npoints
    phiVals = np.linspace(lowPhi, upPhi - deltaPhi, Npoints)

    # Zpoints = 1000
    # deltaZ = (upZ-lowZ)/Zpoints
    # Zvals = np.linspace(lowZ, upZ, Zpoints+1)
    # ztracker = 0

    value = 0
    for z_i in roots:
        phiValue = 0
        for phi in phiVals:
            phiValue = deltaPhi * conformalFactor(z_i, phi) * integrand(
                ((upZ - lowZ) / 2.0) * z_i +
                ((upZ + lowZ) / 2.0), phi, *args) + phiValue
        value = weight(z_i) * phiValue + value

    value = ((upZ - lowZ) / 2.0) * value
    return value
예제 #21
0
def GL_Quad(integrand, lowerBound, upperBound, N, args):
    #Weight Function
    def weight(x):
        w = (2.0 * (1 -
                    (x**2))) / ((N *
                                 (Legendre(x, N - 1) - x * Legendre(x, N)))**2)
        return w

    #Create list of roots for P_N
    rootIndex = np.zeros(N + 1)
    rootIndex[N] = 1
    roots = legroots(rootIndex)

    value = 0
    for x_i in roots:
        value = weight(x_i) * integrand(
            ((upperBound - lowerBound) / 2.0) * x_i +
            ((upperBound + lowerBound) / 2.0), *args) + value

    value = ((upperBound - lowerBound) / 2.0) * value
    return value
예제 #22
0
파일: __init__.py 프로젝트: 1950/sawbuck
def legroots(cs):
    from numpy.polynomial.legendre import legroots
    return legroots(cs)
예제 #23
0
from scipy.interpolate import interp1d

Nin = 10                                    # Number of data points in 
Nout = 50                                    # Number of points we want to project onto
Nfine = Nin**2                              # Number of points for plotting pretty 
Xin = np.linspace(-1,1,Nin)                 # The space of points
Fin = np.cos(20*Xin)+np.sin(7*Xin)          # Evaluate some fake data
Xfine = np.linspace(-1,1,Nfine)             # Linspace for plotting pretty
Fspline = interp1d(Xin,Fin,kind='cubic')    # A spline interpolation of the data
Xout = np.linspace(-1,1,Nout-1)             # Probably don't need this since we want to plot at the GLL nodes
I = np.eye(Nout)                            # A hack for choosing the right polynomial orders 
zero = np.zeros(Nout-1)


# Build our set of GLL nodes
pts = legendre.legroots(legendre.legder(I[-1])) # GLL points
Xi = [-1, list(pts), 1]
Xi = np.hstack(Xi)
#print "GLL Points:", Xi

# Build the weight set
weights = np.zeros([len(Xi)])
for i in range(len(Xi)-2):
    weights[i+1] = 2/((Nout)*(Nout-1)*(legendre.legval(Xi[i+1],I[-1]))**2)

weights[0]=2.0/((Nout)*(Nout-1))
weights[-1]=weights[0]
#print "GLL Weights:", weights

# Calculate the norms    
norms = np.zeros(Nout)
a = -1
b = 1
"""something special only for you"""
print("We have a function:\nf(x)=P(n,x)*P(m,x)")
N = int(input("Enter n for the above function"))
M = int(input("Enter m for the above function"))
print("Degree of f(x)=", N + M)
#no. of steps
n = int(
    input("enter N so that degree of f(x) is smaller than equal to 2N-1\t"))
"""finding roots of nth legendre polynomial and storing it in t"""
Q = []
for i in range(n):
    Q.append(0)
Q.append(1)
t = leg.legroots(Q)
#print(t)

#solution finding
sol = 0
for i in range(n):
    u = ((b - a) / 2) * t[i] + (a + b) / 2
    #print(u)
    #weight
    w = 2 * (1 - t[i]**2) / (((n + 1)**2) * (P(n + 1, t[i]))**2)
    #print(w)
    sol1 = w * func(N, M, u)
    sol = sol + sol1

#solution Found
main_sol = (b - a) * sol / 2
def lagrange(N, x0=x0, x1=x1, C_a=1.3, C_f=1.0, grid='cheb0'):

    #x = np.linspace(x0, x1, N+1)
    if grid == 'cheb0':
        dummy = np.zeros(N)
        dummy[-1] = 1
        x = np.sort(np.array(cheb.chebroots(dummy).tolist() + [-1, 1]))
        x = 0.5 * (x1 - x0) * x + 0.5 * (x1 + x0)

    if grid == 'cheb1':
        dummy = np.zeros(N + 1)
        dummy[-1] = 1
        x = np.sort(
            np.array(cheb.chebroots(cheb.chebder(dummy)).tolist() + [-1, 1]))
        x = 0.5 * (x1 - x0) * x + 0.5 * (x1 + x0)

    if grid == 'legendre0':
        dummy = np.zeros(N)
        dummy[-1] = 1
        x = np.sort(np.array(leg.legroots(dummy).tolist() + [-1, 1]))
        x = 0.5 * (x1 - x0) * x + 0.5 * (x1 + x0)

    if grid == 'legendre1':
        dummy = np.zeros(N + 1)
        dummy[-1] = 1
        x = np.sort(
            np.array(leg.legroots(leg.legder(dummy)).tolist() + [-1, 1]))
        x = 0.5 * (x1 - x0) * x + 0.5 * (x1 + x0)

    #x = 0.5*(x1-x0)*np.cos( np.pi / N * np.arange(N,-1,-1) )+ 0.5*(x1+x0)

    #x = 0.5*(x1-x0)*np.cos( np.pi / (N+1) * ( np.arange(N+1,0,-1) -0.5) )+ 0.5*(x1+x0)

    xx, yy = np.meshgrid(x, x)

    AA = yy - xx
    AA[AA == 0] = 1

    a = np.prod(AA, axis=1)

    #mth lagrangian polynomial
    def phi(y, m):
        """Evaluates m-th Lagrangian polynomial at point y"""

        return np.prod((y - x)[np.arange(len(x)) != m]) / a[m]

    np.seterr(all='ignore')
    D = 1 / AA
    np.seterr(all='raise')

    D = D - np.diag(np.diag(D))

    D_diag = np.diag(np.sum(D, axis=1))

    D = np.multiply(np.multiply(D.T, a).T, 1 / a) + D_diag

    #Initialization of nonlinear part
    Uxy = np.zeros([N + 1, N + 1, N + 1])

    #Integration matrix for integrals of between x_k and x_N
    #W1 = np.zeros( [N+1, N+1] )

    #Integration matrix for integrals of between x_0 and x_k

    for kk in xrange(N + 1):

        for ii in xrange(N + 1):
            #if kk<=ii:
            #W1[kk, ii] = quad(phi, x[kk] , x[-1] , args=(ii,) )[0]

            if kk >= ii:
                #W2[kk, ii] = quad(phi, x[0] , x[kk] , args=(ii,) )[0]

                dummy = x[kk] - x[ii] - xx
                dummy[np.diag_indices(N + 1)] = 1
                Uxy[kk, ii, :] = np.prod(dummy, axis=1) / a

    #Aggregation in

    a_ker = np.vectorize(partial(agg_kernel, C_a=C_a))

    Ain = 0.5 * a_ker(yy - xx, xx)

    Ain[0] = 0

    #Aggregation out

    Aout = a_ker(yy, xx - yy)
    Aout[-1] = 0

    #Initialization of fragmentation in
    frag = np.vectorize(partial(fragmentation, C_f=C_f))

    Fin = gam(yy, xx)
    Fin[-1] = 0

    Fin = np.multiply(Fin, frag(x))
    #Fin[np.diag_indices(N+1)]*=0.5

    return x, D, Fin, Ain, Aout, Uxy
예제 #26
0
파일: __init__.py 프로젝트: Bankq/CS6998
def legroots(cs):
    from numpy.polynomial.legendre import legroots
    return legroots(cs)
예제 #27
0
#

exec(open('common_imports.py').read())
from utils.weighted_orthpoly_solver import orthpoly_coef
import numpy.polynomial.chebyshev as cheb
import numpy.polynomial.legendre as lege

# For getting orthogonal polynomial coefficients.
n_poly_order = 100
V = orthpoly_coef(None, 'legendre', n_poly_order)
#x_sample = sin( pi * (-n_poly_order/2 + arange(n_poly_order+1))/(n_poly_order+1) )
x_sample = lege.legroots(1 * (arange(n_poly_order + 2) == n_poly_order + 1))
get_fq_coef = lambda f: np.linalg.solve(V, f(x_sample))
#get_fq_coef = lambda f: orthpoly_coef(f, 'legendre', n_poly_order)
#get_fq_coef = lambda f: cheb.Chebyshev.interpolate(f, n_poly_order).coef

#
act_fun = 'tanh'

cost_l = lambda pm: cost_flat(ans_xy, pm, layer_dims, active_function=act_fun)
cost_g = ag.jacobian(cost_l)
cost_h = ag.hessian(cost_l)

# ANN function
ann_theta_x = lambda pm, x: np.squeeze(
    net_predict(x, wb_flat2layers(pm, layer_dims), active_function=act_fun))
ann_g = ag.jacobian(ann_theta_x, argnum=0)
ann_h = ag.hessian(ann_theta_x, argnum=0)

# value for parameters and input
layer_dims = [1, 2000, 1]