Ejemplo n.º 1
0
def decoding3dMaxRe(l) :
	if l is 0 : return numpy.array([1])
	import sympy
	x=sympy.Symbol("x")
	maxRoot = max((float(root) for root in sympy.solve(sympy.legendre(l+1,x),x)))
	return numpy.array([1.]+ [float(sympy.legendre(m, maxRoot))
		for m in xrange(1,l+1)])
Ejemplo n.º 2
0
 def sympy_basis(self, i=0):
     x = sympy.symbols('x')
     if i < self.N - 4:
         f = (sympy.legendre(i, x) - 2 * (2 * i + 5.) /
              (2 * i + 7.) * sympy.legendre(i + 2, x) +
              ((2 * i + 3.) / (2 * i + 7.)) * sympy.legendre(i + 4, x))
     else:
         f = 0
         for j, c in enumerate(
                 BCBiharmonicBasis.coefficient_matrix()[i - (self.N - 4)]):
             f += c * sympy.legendre(j, x)
     return f
def test_gegenbauer():
    n = Symbol("n")
    a = Symbol("a")

    assert gegenbauer(0, a, x) == 1
    assert gegenbauer(1, a, x) == 2*a*x
    assert gegenbauer(2, a, x) == -a + x**2*(2*a**2 + 2*a)
    assert gegenbauer(3, a, x) == \
        x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)

    assert gegenbauer(-1, a, x) == 0
    assert gegenbauer(n, S(1)/2, x) == legendre(n, x)
    assert gegenbauer(n, 1, x) == chebyshevu(n, x)
    assert gegenbauer(n, -1, x) == 0

    X = gegenbauer(n, a, x)
    assert isinstance(X, gegenbauer)

    assert gegenbauer(n, a, -x) == (-1)**n*gegenbauer(n, a, x)
    assert gegenbauer(n, a, 0) == 2**n*sqrt(pi) * \
        gamma(a + n/2)/(gamma(a)*gamma(-n/2 + S(1)/2)*gamma(n + 1))
    assert gegenbauer(n, a, 1) == gamma(2*a + n)/(gamma(2*a)*gamma(n + 1))

    assert gegenbauer(n, Rational(3, 4), -1) == zoo

    m = Symbol("m", positive=True)
    assert gegenbauer(m, a, oo) == oo*RisingFactorial(a, m)

    assert conjugate(gegenbauer(n, a, x)) == gegenbauer(n, conjugate(a), conjugate(x))

    assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n)
    assert diff(gegenbauer(n, a, x), x) == 2*a*gegenbauer(n - 1, a + 1, x)
Ejemplo n.º 4
0
 def gen_legendre_basis(n):
     if n==-2:
         return  (1-1*z)/2
     elif n==-1:
         return (1+1*z)/2
     else:
         return ((2*(n+3)-3)/2.)**0.5*integrate(legendre((n+1),x),(x,-1,z))
Ejemplo n.º 5
0
def gauss_lobatto_points(p):
    """
    Returns the list of Gauss-Lobatto points of the order 'p'.
    """
    x = Symbol("x")
    print "creating"
    e = legendre(p, x).diff(x)
    e = Poly(e, x)
    print "polydone"
    if e == 0:
        return []
    print "roots"
    if e == 1:
        r = []
    else:
        with workdps(40):
            r, err = polyroots(e.all_coeffs(), error=True)
        #if err > 1e-40:
        #    raise Exception("Internal Error: Root is not precise")
    print "done"
    p = []
    p.append("-1.0")
    for x in r:
        if abs(x) < 1e-40: x = 0
        p.append(str(x))
    p.append("1.0")
    return p
Ejemplo n.º 6
0
def gauss_lobatto_points(p):
    """
    Returns the list of Gauss-Lobatto points of the order 'p'.
    """
    x = Symbol("x")
    print "creating"
    e = legendre(p, x).diff(x)
    e = Poly(e, x)
    print "polydone"
    if e == 0:
        return []
    print "roots"
    if e == 1:
        r = []
    else:
        with workdps(40):
            r, err = polyroots(e.all_coeffs(), error=True)
        #if err > 1e-40:
        #    raise Exception("Internal Error: Root is not precise")
    print "done"
    p = []
    p.append("-1.0")
    for x in r:
        if abs(x) < 1e-40: x = 0
        p.append(str(x))
    p.append("1.0")
    return p
Ejemplo n.º 7
0
def test_jacobi():
    n = Symbol("n")
    a = Symbol("a")
    b = Symbol("b")

    assert jacobi(0, a, b, x) == 1
    assert jacobi(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1)

    assert jacobi(n, a, a, x) == RisingFactorial(a + 1, n)*gegenbauer(n, a + S(1)/2, x)/RisingFactorial(2*a + 1, n)
    assert jacobi(n, a, -a, x) == ((-1)**a*(-x + 1)**(-a/2)*(x + 1)**(a/2)*assoc_legendre(n, a, x)*
                                   factorial(-a + n)*gamma(a + n + 1)/(factorial(a + n)*gamma(n + 1)))
    assert jacobi(n, -b, b, x) == ((-x + 1)**(b/2)*(x + 1)**(-b/2)*assoc_legendre(n, b, x)*
                                   gamma(-b + n + 1)/gamma(n + 1))
    assert jacobi(n, 0, 0, x) == legendre(n, x)
    assert jacobi(n, S.Half, S.Half, x) == RisingFactorial(S(3)/2, n)*chebyshevu(n, x)/factorial(n + 1)
    assert jacobi(n, -S.Half, -S.Half, x) == RisingFactorial(S(1)/2, n)*chebyshevt(n, x)/factorial(n)

    X = jacobi(n, a, b, x)
    assert isinstance(X, jacobi)

    assert jacobi(n, a, b, -x) == (-1)**n*jacobi(n, b, a, x)
    assert jacobi(n, a, b, 0) == 2**(-n)*gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(factorial(n)*gamma(a + 1))
    assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n)/factorial(n)

    m = Symbol("m", positive=True)
    assert jacobi(m, a, b, oo) == oo*RisingFactorial(a + b + m + 1, m)

    assert conjugate(jacobi(m, a, b, x)) == jacobi(m, conjugate(a), conjugate(b), conjugate(x))

    assert diff(jacobi(n,a,b,x), n) == Derivative(jacobi(n, a, b, x), n)
    assert diff(jacobi(n,a,b,x), x) == (a/2 + b/2 + n/2 + S(1)/2)*jacobi(n - 1, a + 1, b + 1, x)
Ejemplo n.º 8
0
def legendre_norm(i, x):
    """
    Returns the normalized integrated Legendre polynomial.
    """
    f = legendre(i, x)
    n = sqrt(integrate(f**2, (x, -1, 1)))
    return f/n
Ejemplo n.º 9
0
def test_manualintegrate_orthogonal_poly():
    n = symbols('n')
    a, b = 7, S(5)/3
    polys = [jacobi(n, a, b, x), gegenbauer(n, a, x), chebyshevt(n, x),
        chebyshevu(n, x), legendre(n, x), hermite(n, x), laguerre(n, x),
        assoc_laguerre(n, a, x)]
    for p in polys:
        integral = manualintegrate(p, x)
        for deg in [-2, -1, 0, 1, 3, 5, 8]:
            # some accept negative "degree", some do not
            try:
                p_subbed = p.subs(n, deg)
            except ValueError:
                continue
            assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0

        # can also integrate simple expressions with these polynomials
        q = x*p.subs(x, 2*x + 1)
        integral = manualintegrate(q, x)
        for deg in [2, 4, 7]:
            assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0

        # cannot integrate with respect to any other parameter
        t = symbols('t')
        for i in range(len(p.args) - 1):
            new_args = list(p.args)
            new_args[i] = t
            assert isinstance(manualintegrate(p.func(*new_args), t), Integral)
def test_assoc_legendre():
    Plm = assoc_legendre
    Q = sqrt(1 - x**2)

    assert Plm(0, 0, x) == 1
    assert Plm(1, 0, x) == x
    assert Plm(1, 1, x) == -Q
    assert Plm(2, 0, x) == (3 * x**2 - 1) / 2
    assert Plm(2, 1, x) == -3 * x * Q
    assert Plm(2, 2, x) == 3 * Q**2
    assert Plm(3, 0, x) == (5 * x**3 - 3 * x) / 2
    assert Plm(3, 1,
               x).expand() == ((3 * (1 - 5 * x**2) / 2).expand() * Q).expand()
    assert Plm(3, 2, x) == 15 * x * Q**2
    assert Plm(3, 3, x) == -15 * Q**3

    # negative m
    assert Plm(1, -1, x) == -Plm(1, 1, x) / 2
    assert Plm(2, -2, x) == Plm(2, 2, x) / 24
    assert Plm(2, -1, x) == -Plm(2, 1, x) / 6
    assert Plm(3, -3, x) == -Plm(3, 3, x) / 720
    assert Plm(3, -2, x) == Plm(3, 2, x) / 120
    assert Plm(3, -1, x) == -Plm(3, 1, x) / 12

    n = Symbol("n")
    m = Symbol("m")

    X = Plm(n, m, x)
    assert isinstance(X, assoc_legendre)

    assert Plm(n, 0, x) == legendre(n, x)

    assert conjugate(assoc_legendre(n, m, x)) == \
        assoc_legendre(n, conjugate(m), conjugate(x))
    raises(ValueError, lambda: Plm(0, 1, x))
Ejemplo n.º 11
0
def int_legendre_bath_kernel(n):
    ''' Generates an analytical expression for the integration over
        the product between Legendre polynomial Pn(x) and the time
        Green's function expression, for use in generating Legendre
        bath orbitals.

    Parameters
    ----------
    n : int
        order of Legendre polynomial

    Returns
    -------
    expr : sympy.Expr
        sympy expression
    '''

    t = sp.symbols('t', real=True)
    a = sp.symbols('e', nonzero=True, real=True)
    b = sp.symbols('beta', positive=True, nonzero=True, real=True)

    pn = sp.legendre(n, 2.0 * t / b + 1.0)
    gf = sp.exp(-a * (t + sp.Heaviside(a) * b))

    expr = sp.integrate(pn * gf, t)

    return expr
Ejemplo n.º 12
0
Archivo: smolyak.py Proyecto: zoidy/puq
    def polyrs(self, uhat):
        "Compute the polynomial for the response surface."
        import sympy

        dim = len(self.params)
        var = []
        for i, p in enumerate(self.params):
            var.append(sympy.Symbol(str(p.name)))

        chaos = chaos_sequence(dim, self.level)
        chaos = np.int_(chaos)

        for d in range(0, dim):
            poly = np.array(map(lambda x: sympy.legendre(x, var[d]), chaos[:, d]))
            if d == 0:
                s = poly
            else:
                s *= poly

        eqn = np.sum(uhat * s)
        for i, p in enumerate(self.params):
            pmin, pmax = p.pdf.srange
            c = (pmax + pmin) / 2.0
            s = (pmax - pmin) / 2.0
            eqn = eqn.subs(var[i], (var[i] - c)/s)
        return sympy.sstr(eqn.expand().evalf())
Ejemplo n.º 13
0
def test_assoc_legendre():
    Plm = assoc_legendre
    Q = sqrt(1 - x**2)

    assert Plm(0, 0, x) == 1
    assert Plm(1, 0, x) == x
    assert Plm(1, 1, x) == -Q
    assert Plm(2, 0, x) == (3*x**2 - 1)/2
    assert Plm(2, 1, x) == -3*x*Q
    assert Plm(2, 2, x) == 3*Q**2
    assert Plm(3, 0, x) == (5*x**3 - 3*x)/2
    assert Plm(3, 1, x).expand() == (( 3*(1 - 5*x**2)/2 ).expand() * Q).expand()
    assert Plm(3, 2, x) == 15*x * Q**2
    assert Plm(3, 3, x) == -15 * Q**3

    # negative m
    assert Plm(1, -1, x) == -Plm(1, 1, x)/2
    assert Plm(2, -2, x) == Plm(2, 2, x)/24
    assert Plm(2, -1, x) == -Plm(2, 1, x)/6
    assert Plm(3, -3, x) == -Plm(3, 3, x)/720
    assert Plm(3, -2, x) == Plm(3, 2, x)/120
    assert Plm(3, -1, x) == -Plm(3, 1, x)/12

    n = Symbol("n")
    m = Symbol("m")

    X = Plm(n, m, x)
    assert isinstance(X, assoc_legendre)

    assert Plm(n, 0, x) == legendre(n, x)

    raises(ValueError, lambda: Plm(-1, 0, x))
    raises(ValueError, lambda: Plm(0, 1, x))
Ejemplo n.º 14
0
def test_manualintegrate_orthogonal_poly():
    n = symbols("n")
    a, b = 7, Rational(5, 3)
    polys = [
        jacobi(n, a, b, x),
        gegenbauer(n, a, x),
        chebyshevt(n, x),
        chebyshevu(n, x),
        legendre(n, x),
        hermite(n, x),
        laguerre(n, x),
        assoc_laguerre(n, a, x),
    ]
    for p in polys:
        integral = manualintegrate(p, x)
        for deg in [-2, -1, 0, 1, 3, 5, 8]:
            # some accept negative "degree", some do not
            try:
                p_subbed = p.subs(n, deg)
            except ValueError:
                continue
            assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0

        # can also integrate simple expressions with these polynomials
        q = x * p.subs(x, 2 * x + 1)
        integral = manualintegrate(q, x)
        for deg in [2, 4, 7]:
            assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0

        # cannot integrate with respect to any other parameter
        t = symbols("t")
        for i in range(len(p.args) - 1):
            new_args = list(p.args)
            new_args[i] = t
            assert isinstance(manualintegrate(p.func(*new_args), t), Integral)
Ejemplo n.º 15
0
def d_theta(angle,k_v,R_v,alpha_v,An):
    '''Off-axis level, :math:`D_{\\theta}`, for piston in a sphere
    
    Parameters
    ----------
    angle : mpmath.mpf
        Azimuth/elevation angle in radians
    k_v : mpmath.mpf
        Wavenumber
    alpha: mpmath.mpf   
        Piston equivalent aperture in radians. 
    An : mpmath.matrix
        An is a required pre-calculated matrix which results from the 
        satisfying the conditions of the model - specific to each parameter
        set.
    
    Returns
    -------
    abs(rel_level()) : mpmath.mpf   
        The off-axis value at angle :math:`\theta`
    '''
    num = 4 
    N_v = An.rows
    denom  = (k_v**2)*(R_v**2)*mpmath.sin(alpha_v)**2
    part1 = num/denom
    jn_matrix = mpmath.matrix([I**f for f in range(N_v)])
    legendre_matrix = mpmath.matrix([legendre(n_v, mpmath.cos(angle)) for n_v in range(N_v)])
    Anjn = HP(An,jn_matrix).doit()
    part2_matrix = HP(Anjn,legendre_matrix).doit() 
    part2 = sum(part2_matrix)
    rel_level = lambdify([], -part1*part2, 'mpmath')
    return abs(rel_level())
Ejemplo n.º 16
0
def test_gegenbauer():
    n = Symbol("n")
    a = Symbol("a")

    assert gegenbauer(0, a, x) == 1
    assert gegenbauer(1, a, x) == 2 * a * x
    assert gegenbauer(2, a, x) == -a + x**2 * (2 * a**2 + 2 * a)
    assert gegenbauer(3, a, x) == \
        x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)

    assert gegenbauer(-1, a, x) == 0
    assert gegenbauer(n, S(1) / 2, x) == legendre(n, x)
    assert gegenbauer(n, 1, x) == chebyshevu(n, x)
    assert gegenbauer(n, -1, x) == 0

    X = gegenbauer(n, a, x)
    assert isinstance(X, gegenbauer)

    assert gegenbauer(n, a, -x) == (-1)**n * gegenbauer(n, a, x)
    assert gegenbauer(n, a, 0) == 2**n*sqrt(pi) * \
        gamma(a + n/2)/(gamma(a)*gamma(-n/2 + S(1)/2)*gamma(n + 1))
    assert gegenbauer(n, a,
                      1) == gamma(2 * a + n) / (gamma(2 * a) * gamma(n + 1))

    assert gegenbauer(n, Rational(3, 4), -1) == zoo

    m = Symbol("m", positive=True)
    assert gegenbauer(m, a, oo) == oo * RisingFactorial(a, m)

    assert conjugate(gegenbauer(n,
                                a, x)) == gegenbauer(n, conjugate(a),
                                                     conjugate(x))

    assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n)
    assert diff(gegenbauer(n, a, x), x) == 2 * a * gegenbauer(n - 1, a + 1, x)
Ejemplo n.º 17
0
def legendre_norm(i, x):
    """
    Returns the normalized integrated Legendre polynomial.
    """
    f = legendre(i, x)
    n = sqrt(integrate(f**2, (x, -1, 1)))
    return f / n
Ejemplo n.º 18
0
    def polyrs(self, uhat):
        "Compute the polynomial for the response surface."
        import sympy

        dim = len(self.params)
        var = []
        for i, p in enumerate(self.params):
            var.append(sympy.Symbol(str(p.name)))

        chaos = chaos_sequence(dim, self.level)
        chaos = np.int_(chaos)
        for d in range(0, dim):
            poly = np.array(
                list(map(lambda x: sympy.legendre(int(x), var[d]), chaos[:,
                                                                         d])))
            if d == 0:
                s = poly
            else:
                s *= poly

        eqn = np.sum(uhat * s)
        for i, p in enumerate(self.params):
            pmin, pmax = p.pdf.srange
            c = (pmax + pmin) / 2.0
            s = (pmax - pmin) / 2.0
            eqn = eqn.subs(var[i], (var[i] - c) / s)
        return sympy.sstr(eqn.expand().evalf())
Ejemplo n.º 19
0
def solve_eq(pad: Expr) -> dict:
    # expand left term
    left = cancel(expand_func(pad).subs(sin(theta)**2, 1 - cos(theta)**2))
    terms_lft = tuple(expend_cos(left, theta))

    # expand right term
    b0, b1, b2, b3, b4 = symbols('b_0 b_1 b_2 b_3 b_4', real=True)
    right = cancel(b0 + b1 * legendre(1, cos(theta)) +
                   b2 * legendre(2, cos(theta)) +
                   b3 * legendre(3, cos(theta)) + b4 * legendre(4, cos(theta)))
    terms_rgt = tuple(expend_cos(right, theta))

    # solve equations
    b4_cmpx = simplify(cancel(solve((terms_lft[4] - terms_rgt[4]), b4)[0]))
    b4_real = simplify(re(expand(b4_cmpx)))
    b3_cmpx = simplify(cancel(solve((terms_lft[3] - terms_rgt[3]), b3)[0]))
    b3_real = simplify(re(expand(b3_cmpx)))
    b3_amp, b3_shift = amp_and_shift(b3_real, phi)
    b2_cmpx = simplify(
        cancel(solve((terms_lft[2] - terms_rgt[2]).subs(b4, b4_cmpx), b2)[0]))
    b2_real = simplify(re(expand(b2_cmpx)))
    b1_cmpx = simplify(
        cancel(solve((terms_lft[1] - terms_rgt[1]).subs(b3, b3_cmpx), b1)[0]))
    b1_real = simplify(re(expand(b1_cmpx)))
    b1_amp, b1_shift = amp_and_shift(b1_real, phi)
    b0_cmpx = simplify(
        cancel(
            solve(
                (terms_lft[0] - terms_rgt[0]).subs(b4,
                                                   b4_cmpx).subs(b2, b2_cmpx),
                b0)[0]))
    b0_real = simplify(re(expand(b0_cmpx)))
    b1m3_real = simplify(cancel(b1_real - b3_real * 2 / 3))
    b1m3_amp, b1m3_shift = amp_and_shift(b1m3_real, phi)
    return {
        'beta1': b1_real / b0_real,
        'beta1_amp': b1_amp / b0_real,
        'beta1_shift': b1_shift,
        'beta2': b2_real / b0_real,
        'beta3': b3_real / b0_real,
        'beta3_amp': b3_amp / b0_real,
        'beta3_shift': b3_shift,
        'beta4': b4_real / b0_real,
        'beta1m3': b1m3_real / b0_real,
        'beta1m3_amp': b1m3_amp / b0_real,
        'beta1m3_shift': b1m3_shift,
    }
Ejemplo n.º 20
0
def test_jacobi():
    n = Symbol("n")
    a = Symbol("a")
    b = Symbol("b")

    assert jacobi(0, a, b, x) == 1
    assert jacobi(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1)

    assert jacobi(n, a, a, x) == RisingFactorial(
        a + 1, n)*gegenbauer(n, a + S.Half, x)/RisingFactorial(2*a + 1, n)
    assert jacobi(n, a, -a, x) == ((-1)**a*(-x + 1)**(-a/2)*(x + 1)**(a/2)*assoc_legendre(n, a, x)*
                                   factorial(-a + n)*gamma(a + n + 1)/(factorial(a + n)*gamma(n + 1)))
    assert jacobi(n, -b, b, x) == ((-x + 1)**(b/2)*(x + 1)**(-b/2)*assoc_legendre(n, b, x)*
                                   gamma(-b + n + 1)/gamma(n + 1))
    assert jacobi(n, 0, 0, x) == legendre(n, x)
    assert jacobi(n, S.Half, S.Half, x) == RisingFactorial(
        Rational(3, 2), n)*chebyshevu(n, x)/factorial(n + 1)
    assert jacobi(n, Rational(-1, 2), Rational(-1, 2), x) == RisingFactorial(
        S.Half, n)*chebyshevt(n, x)/factorial(n)

    X = jacobi(n, a, b, x)
    assert isinstance(X, jacobi)

    assert jacobi(n, a, b, -x) == (-1)**n*jacobi(n, b, a, x)
    assert jacobi(n, a, b, 0) == 2**(-n)*gamma(a + n + 1)*hyper(
        (-b - n, -n), (a + 1,), -1)/(factorial(n)*gamma(a + 1))
    assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n)/factorial(n)

    m = Symbol("m", positive=True)
    assert jacobi(m, a, b, oo) == oo*RisingFactorial(a + b + m + 1, m)
    assert unchanged(jacobi, n, a, b, oo)

    assert conjugate(jacobi(m, a, b, x)) == \
        jacobi(m, conjugate(a), conjugate(b), conjugate(x))

    _k = Dummy('k')
    assert diff(jacobi(n, a, b, x), n) == Derivative(jacobi(n, a, b, x), n)
    assert diff(jacobi(n, a, b, x), a).dummy_eq(Sum((jacobi(n, a, b, x) +
        (2*_k + a + b + 1)*RisingFactorial(_k + b + 1, -_k + n)*jacobi(_k, a,
        b, x)/((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)))/(_k + a
        + b + n + 1), (_k, 0, n - 1)))
    assert diff(jacobi(n, a, b, x), b).dummy_eq(Sum(((-1)**(-_k + n)*(2*_k +
        a + b + 1)*RisingFactorial(_k + a + 1, -_k + n)*jacobi(_k, a, b, x)/
        ((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)) + jacobi(n, a,
        b, x))/(_k + a + b + n + 1), (_k, 0, n - 1)))
    assert diff(jacobi(n, a, b, x), x) == \
        (a/2 + b/2 + n/2 + S.Half)*jacobi(n - 1, a + 1, b + 1, x)

    assert jacobi_normalized(n, a, b, x) == \
           (jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)
                                    /((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1))))

    raises(ValueError, lambda: jacobi(-2.1, a, b, x))
    raises(ValueError, lambda: jacobi(Dummy(positive=True, integer=True), 1, 2, oo))

    assert jacobi(n, a, b, x).rewrite("polynomial").dummy_eq(Sum((S.Half - x/2)
        **_k*RisingFactorial(-n, _k)*RisingFactorial(_k + a + 1, -_k + n)*
        RisingFactorial(a + b + n + 1, _k)/factorial(_k), (_k, 0, n))/factorial(n))
    raises(ArgumentIndexError, lambda: jacobi(n, a, b, x).fdiff(5))
Ejemplo n.º 21
0
def test_gegenbauer():
    n = Symbol("n")
    a = Symbol("a")

    assert gegenbauer(0, a, x) == 1
    assert gegenbauer(1, a, x) == 2 * a * x
    assert gegenbauer(2, a, x) == -a + x**2 * (2 * a**2 + 2 * a)
    assert gegenbauer(
        3, a, x) == x**3 * (4 * a**3 / 3 + 4 * a**2 +
                            a * Rational(8, 3)) + x * (-2 * a**2 - 2 * a)

    assert gegenbauer(-1, a, x) == 0
    assert gegenbauer(n, S.Half, x) == legendre(n, x)
    assert gegenbauer(n, 1, x) == chebyshevu(n, x)
    assert gegenbauer(n, -1, x) == 0

    X = gegenbauer(n, a, x)
    assert isinstance(X, gegenbauer)

    assert gegenbauer(n, a, -x) == (-1)**n * gegenbauer(n, a, x)
    assert gegenbauer(n, a, 0) == 2**n * sqrt(pi) * gamma(a + n / 2) / (
        gamma(a) * gamma(-n / 2 + S.Half) * gamma(n + 1))
    assert gegenbauer(n, a,
                      1) == gamma(2 * a + n) / (gamma(2 * a) * gamma(n + 1))

    assert gegenbauer(n, Rational(3, 4), -1) is zoo
    assert gegenbauer(n, Rational(1, 4),
                      -1) == (sqrt(2) * cos(pi * (n + S.One / 4)) *
                              gamma(n + S.Half) / (sqrt(pi) * gamma(n + 1)))

    m = Symbol("m", positive=True)
    assert gegenbauer(m, a, oo) == oo * RisingFactorial(a, m)
    assert unchanged(gegenbauer, n, a, oo)

    assert conjugate(gegenbauer(n,
                                a, x)) == gegenbauer(n, conjugate(a),
                                                     conjugate(x))

    _k = Dummy("k")

    assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n)
    assert diff(gegenbauer(n, a, x), a).dummy_eq(
        Sum(
            (2 * (-1)**(-_k + n) + 2) * (_k + a) * gegenbauer(_k, a, x) /
            ((-_k + n) * (_k + 2 * a + n)) +
            ((2 * _k + 2) / ((_k + 2 * a) * (2 * _k + 2 * a + 1)) + 2 /
             (_k + 2 * a + n)) * gegenbauer(n, a, x),
            (_k, 0, n - 1),
        ))
    assert diff(gegenbauer(n, a, x), x) == 2 * a * gegenbauer(n - 1, a + 1, x)

    assert (gegenbauer(n, a, x).rewrite("polynomial").dummy_eq(
        Sum(
            (-1)**_k * (2 * x)**(-2 * _k + n) * RisingFactorial(a, -_k + n) /
            (factorial(_k) * factorial(-2 * _k + n)),
            (_k, 0, floor(n / 2)),
        )))

    raises(ArgumentIndexError, lambda: gegenbauer(n, a, x).fdiff(4))
Ejemplo n.º 22
0
def legendre_int(i, x):
    """
    Returns the normalized integrated Legendre polynomial.
    """
    y = Symbol("y", dummy=True)
    f = legendre(i, y)
    n = sqrt(integrate(f**2, (y, -1, 1)))
    return integrate(f, (y, -1, x)) / n
Ejemplo n.º 23
0
def legendre_int(i, x):
    """
    Returns the normalized integrated Legendre polynomial.
    """
    y = Symbol("y", dummy=True)
    f = legendre(i, y)
    n = sqrt(integrate(f**2, (y, -1, 1)))
    return integrate(f, (y, -1, x))/n
Ejemplo n.º 24
0
 def sympy_basis(self, i=0):
     x = sympy.symbols('x')
     if i < 4:
         f = 0
         for j, c in enumerate(self.coefficient_matrix()[i]):
             f += c * sympy.legendre(j, x)
         return f
     else:
         raise AttributeError('Only four bases, i < 4')
Ejemplo n.º 25
0
def acceptance( cosTheta1, phi, cosTheta2, i_max, j_max, k_max, numEvents, c):
	returnValue = 0.
        for i in range(i_max+1):
		for k in range(3):
			for j in range(0, 5, 2): # must have l >= k
 				if (j < k): continue
 				P_i  = N(legendre(i,    cosTheta2))
				Y_jk = abs(N(Zlm(j, k, acos(cosTheta1), phi)))
				#print returnValue, P_i, Y_jk, c[i][j][k]
 				returnValue += c[i][k][j]*(P_i * Y_jk);
	return returnValue
Ejemplo n.º 26
0
def __init_halfsummed_pn():
    n = symbols('n', integer=True, positive=True)
    expr = (legendre(n-1, 0)-legendre(n+1, 0))/(2*n+1)
    f = memoize(lambdify(n, expr, ('math', 'mpmath', 'numpy')))

    @vectorize
    def summed(n, region='top'):
        if n < 0:
            raise ValueError("Par 'n' is invalid!")
        elif n == 0:
            return 1.0
        elif n % 2 == 0:
            return 0.0
        if region == 'top':
            return f(n)
        elif region == 'btm':
            return -f(n)
        else:
            raise ValueError("Par 'region' have to be 'top' or 'btm'!")
    return summed
Ejemplo n.º 27
0
def test_assoc_legendre():
    Plm = assoc_legendre
    Q = sqrt(1 - x**2)

    assert Plm(0, 0, x) == 1
    assert Plm(1, 0, x) == x
    assert Plm(1, 1, x) == -Q
    assert Plm(2, 0, x) == (3 * x**2 - 1) / 2
    assert Plm(2, 1, x) == -3 * x * Q
    assert Plm(2, 2, x) == 3 * Q**2
    assert Plm(3, 0, x) == (5 * x**3 - 3 * x) / 2
    assert Plm(3, 1,
               x).expand() == ((3 * (1 - 5 * x**2) / 2).expand() * Q).expand()
    assert Plm(3, 2, x) == 15 * x * Q**2
    assert Plm(3, 3, x) == -15 * Q**3

    # negative m
    assert Plm(1, -1, x) == -Plm(1, 1, x) / 2
    assert Plm(2, -2, x) == Plm(2, 2, x) / 24
    assert Plm(2, -1, x) == -Plm(2, 1, x) / 6
    assert Plm(3, -3, x) == -Plm(3, 3, x) / 720
    assert Plm(3, -2, x) == Plm(3, 2, x) / 120
    assert Plm(3, -1, x) == -Plm(3, 1, x) / 12

    n = Symbol("n")
    m = Symbol("m")
    X = Plm(n, m, x)
    assert isinstance(X, assoc_legendre)

    assert Plm(n, 0, x) == legendre(n, x)
    assert Plm(n, m, 0) == 2**m * sqrt(pi) / (gamma(-m / 2 - n / 2 + S.Half) *
                                              gamma(-m / 2 + n / 2 + 1))

    assert diff(Plm(m, n, x),
                x) == (m * x * assoc_legendre(m, n, x) -
                       (m + n) * assoc_legendre(m - 1, n, x)) / (x**2 - 1)

    _k = Dummy("k")
    assert (Plm(m, n, x).rewrite("polynomial").dummy_eq(
        (1 - x**2)**(n / 2) * Sum(
            (-1)**_k * 2**(-m) * x**(-2 * _k + m - n) *
            factorial(-2 * _k + 2 * m) /
            (factorial(_k) * factorial(-_k + m) * factorial(-2 * _k + m - n)),
            (_k, 0, floor(m / 2 - n / 2)),
        )))
    assert conjugate(assoc_legendre(n, m, x)) == assoc_legendre(
        n, conjugate(m), conjugate(x))
    raises(ValueError, lambda: Plm(0, 1, x))
    raises(ValueError, lambda: Plm(-1, 1, x))
    raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(1))
    raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(2))
    raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(4))
Ejemplo n.º 28
0
def gauss_lobatto_jacobi_quadruature_points_weights(n=5):
    """
    compute Gauss-Lobatto-Jacobi (GLJ) quadrature weights and points [-1, 1]
    using the sympy symbolic package and analytical definitions of these points

    somehow seems not to work for even numbers n >= 10, I assume this is a bug
    in sympy

    :param n: number of integration points (order + 1)
    :type n: integer

    :returns: tuple of two numpy arrays of floats containing the points and
        weights
    """
    x = sp.symbols('x')

    # GLL points are defined as the roots of the derivative of a sum of
    # Legendre Polynomials and include the boundaries
    Pn_bar = (sp.legendre(n-1, x) + sp.legendre(n, x)) / (1 + x)
    dPn_bar = sp.cancel((1 - x ** 2) * sp.diff(Pn_bar, x))

    # evaluate and sort
    pointsl = []
    for i in np.arange(n):
        p = sp.RootOf(dPn_bar, i)
        pointsl.append(p.evalf())

    pointsl.sort()

    # weights
    weightsl = []
    for p in pointsl:
        if p == -1.:
            wi = 8. / (n ** 2 * (n + 1) * (n - 1))
        else:
            wi = 4. / ((n + 1) * (n - 1) * Pn_bar.subs(x, p) ** 2)
        weightsl.append(wi)

    return np.array(pointsl, dtype='float'), np.array(weightsl, dtype='float')
Ejemplo n.º 29
0
def d_theta(angle, k_v, R_v, alpha_v, An):
    num = 4
    N_v = An.rows
    denom = (k_v**2) * (R_v**2) * mpmath.sin(alpha_v)**2
    part1 = num / denom
    jn_matrix = mpmath.matrix([I**f for f in range(N_v)])
    legendre_matrix = mpmath.matrix(
        [legendre(n_v, mpmath.cos(angle)) for n_v in range(N_v)])
    Anjn = HP(An, jn_matrix).doit()
    part2_matrix = HP(Anjn, legendre_matrix).doit()
    part2 = sum(part2_matrix)
    rel_level = lambdify([], -part1 * part2, 'mpmath')
    return abs(rel_level())
Ejemplo n.º 30
0
def gauss_lobatto_jacobi_quadruature_points_weights(n=5):
    """
    compute Gauss-Lobatto-Jacobi (GLJ) quadrature weights and points [-1, 1]
    using the sympy symbolic package and analytical definitions of these points

    somehow seems not to work for even numbers n >= 10, I assume this is a bug
    in sympy

    :param n: number of integration points (order + 1)
    :type n: integer

    :returns: tuple of two numpy arrays of floats containing the points and
        weights
    """
    x = sp.symbols('x')

    # GLL points are defined as the roots of the derivative of a sum of
    # Legendre Polynomials and include the boundaries
    Pn_bar = (sp.legendre(n - 1, x) + sp.legendre(n, x)) / (1 + x)
    dPn_bar = sp.cancel((1 - x**2) * sp.diff(Pn_bar, x))

    # evaluate and sort
    pointsl = []
    for i in np.arange(n):
        p = sp.RootOf(dPn_bar, i)
        pointsl.append(p.evalf())

    pointsl.sort()

    # weights
    weightsl = []
    for p in pointsl:
        if p == -1.:
            wi = 8. / (n**2 * (n + 1) * (n - 1))
        else:
            wi = 4. / ((n + 1) * (n - 1) * Pn_bar.subs(x, p)**2)
        weightsl.append(wi)

    return np.array(pointsl, dtype='float'), np.array(weightsl, dtype='float')
Ejemplo n.º 31
0
def test_jacobi():
    n = Symbol("n")
    a = Symbol("a")
    b = Symbol("b")

    assert jacobi(0, a, b, x) == 1
    assert jacobi(1, a, b, x) == a / 2 - b / 2 + x * (a / 2 + b / 2 + 1)

    assert jacobi(n, a, a, x) == RisingFactorial(a + 1, n) * gegenbauer(
        n, a + S(1) / 2, x) / RisingFactorial(2 * a + 1, n)
    assert jacobi(n, a, -a,
                  x) == ((-1)**a * (-x + 1)**(-a / 2) * (x + 1)**(a / 2) *
                         assoc_legendre(n, a, x) * factorial(-a + n) *
                         gamma(a + n + 1) / (factorial(a + n) * gamma(n + 1)))
    assert jacobi(n, -b, b, x) == ((-x + 1)**(b / 2) * (x + 1)**(-b / 2) *
                                   assoc_legendre(n, b, x) *
                                   gamma(-b + n + 1) / gamma(n + 1))
    assert jacobi(n, 0, 0, x) == legendre(n, x)
    assert jacobi(n, S.Half,
                  S.Half, x) == RisingFactorial(S(3) / 2, n) * chebyshevu(
                      n, x) / factorial(n + 1)
    assert jacobi(
        n, -S.Half, -S.Half,
        x) == RisingFactorial(S(1) / 2, n) * chebyshevt(n, x) / factorial(n)

    X = jacobi(n, a, b, x)
    assert isinstance(X, jacobi)

    assert jacobi(n, a, b, -x) == (-1)**n * jacobi(n, b, a, x)
    assert jacobi(n, a, b, 0) == 2**(-n) * gamma(a + n + 1) * hyper(
        (-b - n, -n), (a + 1, ), -1) / (factorial(n) * gamma(a + 1))
    assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n) / factorial(n)

    m = Symbol("m", positive=True)
    assert jacobi(m, a, b, oo) == oo * RisingFactorial(a + b + m + 1, m)

    assert conjugate(jacobi(m, a, b, x)) == \
        jacobi(m, conjugate(a), conjugate(b), conjugate(x))

    assert diff(jacobi(n, a, b, x), n) == Derivative(jacobi(n, a, b, x), n)
    assert diff(jacobi(n, a, b, x), x) == \
        (a/2 + b/2 + n/2 + S(1)/2)*jacobi(n - 1, a + 1, b + 1, x)

    assert jacobi_normalized(n, a, b, x) == \
           (jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)
                                    /((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1))))

    raises(ValueError, lambda: jacobi(-2.1, a, b, x))
    raises(ValueError,
           lambda: jacobi(Dummy(positive=True, integer=True), 1, 2, oo))
Ejemplo n.º 32
0
def legendre(n, var):
    """Calculate Legendre_n(var)
      var : angle

    :param n: 
    :param var: 

    """
    from sympy import Rational
    from sympy.abc import x
    from sympy.utilities.lambdify import lambdify
    from sympy import legendre
    l = legendre(Rational(n), x)
    return lambdify(x, l, "tensorflow")(var)
Ejemplo n.º 33
0
def gen(i_deg):
    # array of polynomials
    l_pols = []

    l_xib = sympy.symbols('xib')  # coordinates of the basis [-1,1]
    l_xi = sympy.symbols('xi_1')  # mapped coordinates in [0,1]

    # derive polynomials
    for l_de in range(0, i_deg + 1):
        # add legendre polynomials, shifted to interval [0,1]
        l_pols = l_pols + [
            sympy.legendre(l_de, l_xib).subs(l_xib, (2 * l_xi - 1))
        ]

    l_syms = [l_xi]
    return l_syms, l_pols
Ejemplo n.º 34
0
    def doit(self, superdeep: bool = False, **hints):
        """Sympy doit.

        Parameters
        ----------
        superdeep : bool
            whether to substitute LgP for Sympy legendre(l, x)
        hints : dict
            standard hints for doit

        """
        L, X = self.args  # values
        if superdeep:
            return legendre(L, X)
        else:
            return self.__class__(l=L, x=X)
Ejemplo n.º 35
0
def main():

    print(__doc__)

    x = symbols('x')

    # a numpy array we can apply the ufuncs to
    grid = np.linspace(-1, 1, 1000)

    # set mpmath precision to 20 significant numbers for verification
    mpmath.mp.dps = 20

    print("Compiling legendre ufuncs and checking results:")

    # Let's also plot the ufunc's we generate
    plot1 = Plot(visible=False)
    for n in range(6):

        # Setup the SymPy expression to ufuncify
        expr = legendre(n, x)
        print("The polynomial of degree %i is" % n)
        pprint(expr)

        # This is where the magic happens:
        binary_poly = ufuncify(x, expr)

        # It's now ready for use with numpy arrays
        polyvector = binary_poly(grid)

        # let's check the values against mpmath's legendre function
        maxdiff = 0
        for j in range(len(grid)):
            precise_val = mpmath.legendre(n, grid[j])
            diff = abs(polyvector[j] - precise_val)
            if diff > maxdiff:
                maxdiff = diff
        print("The largest error in applied ufunc was %e" % maxdiff)
        assert maxdiff < 1e-14

        # We can also attach the autowrapped legendre polynomial to a sympy
        # function and plot values as they are calculated by the binary function
        g = implemented_function('g', binary_poly)
        plot1[n] = g(x), [200]

    print(
        "Here's a plot with values calculated by the wrapped binary functions")
    plot1.show()
Ejemplo n.º 36
0
def main():

    print(__doc__)

    x = symbols('x')

    # a numpy array we can apply the ufuncs to
    grid = np.linspace(-1, 1, 1000)

    # set mpmath precision to 20 significant numbers for verification
    mpmath.mp.dps = 20

    print("Compiling legendre ufuncs and checking results:")

    # Let's also plot the ufunc's we generate
    for n in range(6):

        # Setup the SymPy expression to ufuncify
        expr = legendre(n, x)
        print("The polynomial of degree %i is" % n)
        pprint(expr)

        # This is where the magic happens:
        binary_poly = ufuncify(x, expr)

        # It's now ready for use with numpy arrays
        polyvector = binary_poly(grid)

        # let's check the values against mpmath's legendre function
        maxdiff = 0
        for j in range(len(grid)):
            precise_val = mpmath.legendre(n, grid[j])
            diff = abs(polyvector[j] - precise_val)
            if diff > maxdiff:
                maxdiff = diff
        print("The largest error in applied ufunc was %e" % maxdiff)
        assert maxdiff < 1e-14

        # We can also attach the autowrapped legendre polynomial to a sympy
        # function and plot values as they are calculated by the binary function
        plot1 = plt.pyplot.plot(grid, polyvector, hold=True)


    print("Here's a plot with values calculated by the wrapped binary functions")
    # plt.pyplot.show()
    pltshow(plt)
Ejemplo n.º 37
0
def gauss_lobatto_points(p):
    """
    Returns the list of Gauss-Lobatto points of the order 'p'.
    """
    x = Symbol("x")
    e = (1-x**2)*legendre(p, x).diff(x)
    e = Poly(e, x)
    if e == 0:
        return []
    with workdps(40):
        r, err = polyroots(e.all_coeffs(), error=True)
    if err > 1e-40:
        raise Exception("Internal Error: Root is not precise")
    p = []
    for x in r:
        if abs(x) < 1e-40: x = 0
        p.append(str(x))
    return p
Ejemplo n.º 38
0
    def test_five_points(self):
        import numpy as np
        import sympy

        t_symb = sympy.Symbol('t')
        num_points = 5
        p4 = sympy.legendre(num_points - 1, t_symb)
        p4_prime = p4.diff(t_symb)
        start = -1.0
        stop = 1.0
        all_nodes = self._call_func_under_test(start, stop, num_points)
        self.assertEqual(all_nodes[0], start)
        self.assertEqual(all_nodes[-1], stop)
        inner_nodes = all_nodes[1:-1]
        # Make sure the computed roots are actually roots.
        self.assertTrue(np.allclose(
            [float(p4_prime.subs({t_symb: root}))
             for root in inner_nodes], 0))
Ejemplo n.º 39
0
def max_rE_gains_3d(order, numeric=True):
    """max rE for a given order is the largest root of the order+1 Legendre
    polynomial"""

    x = sp.symbols('x')
    lp = sp.legendre_poly(order + 1, x)

    # there are more efficient methods to find the roots of the Legendre
    # polynomials, but this is good enough for our purposes
    # See discussion at:
    #   https://math.stackexchange.com/questions/12160/roots-of-legendre-polynomial
    if order < 5 and not numeric:
        roots = sp.roots(lp)
    else:
        roots = sp.nroots(lp)

    # the roots can be in the keys of a dictionary or in a list,
    # this works for either one
    max_rE = np.max([*roots])

    return [sp.legendre(n, max_rE) for n in range(order + 1)]
Ejemplo n.º 40
0
def gauss_quadruature_points_weights(n=5):
    """
    compute Gaussian quadrature weights and points [-1, 1] using the sympy
    symbolic package and analytical definitions of these points

    somehow seems not to work for even numbers n >= 10, I assume this is a bug
    in sympy

    :param n: number of integration points (order + 1)
    :type n: integer

    :returns: tuple of two numpy arrays of floats containing the points and
        weights
    """
    x = sp.symbols('x')

    # Gauss points are defined as the roots of the Legendre Polynomials
    Pn = sp.legendre(n, x)

    # evaluate and sort
    pointsl = []
    for i in np.arange(n):
        p = sp.RootOf(Pn, i)
        pointsl.append(p.evalf())

    pointsl.sort()

    # weights are found through the derivative of the Legendre Polynomials
    dPn = sp.diff(Pn)

    # evaluate
    weightsl = []
    for p in pointsl:
        wi = 2. / ((1 - p**2) * dPn.subs(x, p)**2)
        weightsl.append(wi)

    return np.array(pointsl, dtype='float'), np.array(weightsl, dtype='float')
Ejemplo n.º 41
0
def gauss_quadruature_points_weights(n=5):
    """
    compute Gaussian quadrature weights and points [-1, 1] using the sympy
    symbolic package and analytical definitions of these points

    somehow seems not to work for even numbers n >= 10, I assume this is a bug
    in sympy

    :param n: number of integration points (order + 1)
    :type n: integer

    :returns: tuple of two numpy arrays of floats containing the points and
        weights
    """
    x = sp.symbols('x')

    # Gauss points are defined as the roots of the Legendre Polynomials
    Pn = sp.legendre(n, x)

    # evaluate and sort
    pointsl = []
    for i in np.arange(n):
        p = sp.RootOf(Pn, i)
        pointsl.append(p.evalf())

    pointsl.sort()

    # weights are found through the derivative of the Legendre Polynomials
    dPn = sp.diff(Pn)

    # evaluate
    weightsl = []
    for p in pointsl:
        wi = 2. / ((1 - p ** 2) * dPn.subs(x, p) ** 2)
        weightsl.append(wi)

    return np.array(pointsl, dtype='float'), np.array(weightsl, dtype='float')
Ejemplo n.º 42
0
    def __init__(self, n=None, verbose=False):
        self.n = n
        prec = dps = Float.getdps()
        self.prec = prec

        # Reuse old nodes
        if n in _gausscache:
            cacheddps, xs, ws = _gausscache[n]
            if cacheddps >= dps:
                self.x = [x for x in xs]
                self.w = [w for w in ws]
                return

        if verbose:
            print ("calculating nodes for degree-%i Gauss-Legendre "
                "quadrature..." % n)

        Float.store()
        Float.setdps(2*prec + 5)

        self.x = [None] * n
        self.w = [None] * n

        pf = polyfunc(legendre(n, 'x'), True)

        for k in xrange(n//2 + 1):
            if verbose and k % 4 == 0:
                print "  node", k, "of", n//2
            x, w = _gaussnode(pf, k, n)
            self.x[k] = x
            self.x[n-k-1] = -x
            self.w[k] = self.w[n-k-1] = w

        _gausscache[n] = (dps, self.x, self.w)

        Float.revert()
Ejemplo n.º 43
0
def test_legendre():
    assert legendre(0, x) == 1
    assert legendre(1, x) == x
    assert legendre(2, x) == ((3 * x ** 2 - 1) / 2).expand()
    assert legendre(3, x) == ((5 * x ** 3 - 3 * x) / 2).expand()
    assert legendre(4, x) == ((35 * x ** 4 - 30 * x ** 2 + 3) / 8).expand()
    assert legendre(5, x) == ((63 * x ** 5 - 70 * x ** 3 + 15 * x) / 8).expand()
    assert legendre(6, x) == ((231 * x ** 6 - 315 * x ** 4 + 105 * x ** 2 - 5) / 16).expand()

    assert legendre(10, -1) == 1
    assert legendre(11, -1) == -1
    assert legendre(10, 1) == 1
    assert legendre(11, 1) == 1
    assert legendre(10, 0) != 0
    assert legendre(11, 0) == 0

    assert roots(legendre(4, x), x) == {
        (Rational(3, 7) - Rational(2, 35) * 30 ** S.Half) ** S.Half: 1,
        -(Rational(3, 7) - Rational(2, 35) * 30 ** S.Half) ** S.Half: 1,
        (Rational(3, 7) + Rational(2, 35) * 30 ** S.Half) ** S.Half: 1,
        -(Rational(3, 7) + Rational(2, 35) * 30 ** S.Half) ** S.Half: 1,
    }
Ejemplo n.º 44
0
    '''
    ka_sintheta = k*kwargs['a']*np.sin(theta)
    numerator = 2*besselj(1, ka_sintheta).evalf()#2*bessel_firstkind(1, ka_sintheta)

    try:
        rp_theta = np.abs(numerator/ka_sintheta)
    except:
        rp_theta = 0
    return rp_theta


##### Vibrating cap on sphere
Wn, Pn, h2n, h2n_prime, theta, w0, n, theta0, k, R, H_theta, kR = symbols(
        'Wn Pn h2n h2n_prime theta w0 n theta0 k R H_theta kR')
# take equation 6 to define Wn now
Wn = 0.5 * w0 * (legendre(n - 1, cos(theta0)) - legendre(n + 1, cos(theta0)))

h2n = hankel2(n, kR)
# h2n_prime_term = diff(hankel2(n, k*R), k*R)
h2n_prime_term = diff(h2n, kR)

# equation 23
common_term = ((I ** n) * Wn) / h2n_prime_term
denominator = summation(common_term, (n, 0, 20))

numerator_term = common_term * legendre(n, cos(theta))
numerator = summation(numerator_term, (n, 0, 20))

H_theta = Abs(numerator / denominator)

calc_H_theta = lambdify((theta, k, R, theta0, kR,w0), H_theta)
Ejemplo n.º 45
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function("f")
    assert latex(f(x)) == "\\operatorname{f}{\\left (x \\right )}"

    beta = Function("beta")

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2 * x ** 2), fold_func_brackets=True) == r"\sin {2 x^{2}}"
    assert latex(sin(x ** 2), fold_func_brackets=True) == r"\sin {x^{2}}"

    assert latex(asin(x) ** 2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x) ** 2, inv_trig_style="full") == r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x) ** 2, inv_trig_style="power") == r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x ** 2), inv_trig_style="power", fold_func_brackets=True) == r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x ** 3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y) ** 2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x ** 3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y) ** 2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r"\gamma\left(x, y\right)"
    assert latex(uppergamma(x, y)) == r"\Gamma\left(x, y\right)"

    assert latex(cot(x)) == r"\cot{\left (x \right )}"
    assert latex(coth(x)) == r"\coth{\left (x \right )}"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(root(x, y)) == r"x^{\frac{1}{y}}"
    assert latex(arg(x)) == r"\arg{\left (x \right )}"
    assert latex(zeta(x)) == r"\zeta\left(x\right)"

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x) ** 2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y) ** 2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x) ** 2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x, y) ** 2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n) ** 2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r"\operatorname{Ei}{\left (x \right )}"
    assert latex(Ei(x) ** 2) == r"\operatorname{Ei}^{2}{\left (x \right )}"
    assert latex(expint(x, y) ** 2) == r"\operatorname{E}_{x}^{2}\left(y\right)"
    assert latex(Shi(x) ** 2) == r"\operatorname{Shi}^{2}{\left (x \right )}"
    assert latex(Si(x) ** 2) == r"\operatorname{Si}^{2}{\left (x \right )}"
    assert latex(Ci(x) ** 2) == r"\operatorname{Ci}^{2}{\left (x \right )}"
    assert latex(Chi(x) ** 2) == r"\operatorname{Chi}^{2}{\left (x \right )}"

    assert latex(jacobi(n, a, b, x)) == r"P_{n}^{\left(a,b\right)}\left(x\right)"
    assert latex(jacobi(n, a, b, x) ** 2) == r"\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}"
    assert latex(gegenbauer(n, a, x)) == r"C_{n}^{\left(a\right)}\left(x\right)"
    assert latex(gegenbauer(n, a, x) ** 2) == r"\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}"
    assert latex(chebyshevt(n, x)) == r"T_{n}\left(x\right)"
    assert latex(chebyshevt(n, x) ** 2) == r"\left(T_{n}\left(x\right)\right)^{2}"
    assert latex(chebyshevu(n, x)) == r"U_{n}\left(x\right)"
    assert latex(chebyshevu(n, x) ** 2) == r"\left(U_{n}\left(x\right)\right)^{2}"
    assert latex(legendre(n, x)) == r"P_{n}\left(x\right)"
    assert latex(legendre(n, x) ** 2) == r"\left(P_{n}\left(x\right)\right)^{2}"
    assert latex(assoc_legendre(n, a, x)) == r"P_{n}^{\left(a\right)}\left(x\right)"
    assert latex(assoc_legendre(n, a, x) ** 2) == r"\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}"
    assert latex(laguerre(n, x)) == r"L_{n}\left(x\right)"
    assert latex(laguerre(n, x) ** 2) == r"\left(L_{n}\left(x\right)\right)^{2}"
    assert latex(assoc_laguerre(n, a, x)) == r"L_{n}^{\left(a\right)}\left(x\right)"
    assert latex(assoc_laguerre(n, a, x) ** 2) == r"\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}"
    assert latex(hermite(n, x)) == r"H_{n}\left(x\right)"
    assert latex(hermite(n, x) ** 2) == r"\left(H_{n}\left(x\right)\right)^{2}"

    # Test latex printing of function names with "_"
    assert latex(polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0) ** 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Ejemplo n.º 46
0
def gen_lobatto(max_order):
    assert max_order > 2

    x = sm.symbols('x')

    lobs = [0, 1]
    lobs[0] = (1 - x) / 2
    lobs[1] = (1 + x) / 2

    dlobs = [lob.diff('x') for lob in lobs]

    legs = [sm.legendre(0, 'y')]
    clegs = [sm.ccode(legs[0])]
    dlegs = [sm.legendre(0, 'y').diff('y')]
    cdlegs = [sm.ccode(dlegs[0])]

    clobs = [sm.ccode(lob) for lob in lobs]
    cdlobs = [sm.ccode(dlob) for dlob in dlobs]

    denoms = []  # for lobs.

    for ii in range(2, max_order + 1):
        coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % ii)
        leg = sm.legendre(ii - 1, 'y')

        pleg = leg.as_poly()
        coefs = pleg.all_coeffs()
        denom = max(sm.denom(val) for val in coefs)

        cleg = sm.ccode(sm.horner(leg * denom) / denom)

        dleg = leg.diff('y')
        cdleg = sm.ccode(sm.horner(dleg * denom) / denom)

        lob = sm.simplify(coef * sm.integrate(leg, ('y', -1, x)))
        lobnc = sm.simplify(sm.integrate(leg, ('y', -1, x)))

        plobnc = lobnc.as_poly()
        coefs = plobnc.all_coeffs()
        denom = sm.denom(coef) * max(sm.denom(val) for val in coefs)

        clob = sm.ccode(sm.horner(lob * denom) / denom)

        dlob = lob.diff('x')
        cdlob = sm.ccode(sm.horner(dlob * denom) / denom)

        legs.append(leg)
        clegs.append(cleg)
        dlegs.append(dleg)
        cdlegs.append(cdleg)
        lobs.append(lob)
        clobs.append(clob)
        dlobs.append(dlob)
        cdlobs.append(cdlob)
        denoms.append(denom)

    coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % (max_order + 1))
    leg = sm.legendre(max_order, 'y')

    pleg = leg.as_poly()
    coefs = pleg.all_coeffs()
    denom = max(sm.denom(val) for val in coefs)

    cleg = sm.ccode(sm.horner(leg * denom) / denom)

    dleg = leg.diff('y')
    cdleg = sm.ccode(sm.horner(dleg * denom) / denom)

    legs.append(leg)
    clegs.append(cleg)
    dlegs.append(dleg)
    cdlegs.append(cdleg)

    kerns = []
    ckerns = []
    dkerns = []
    cdkerns = []
    for ii, lob in enumerate(lobs[2:]):
        kern = sm.simplify(lob / (lobs[0] * lobs[1]))
        dkern = kern.diff('x')

        denom = denoms[ii] / 4
        ckern = sm.ccode(sm.horner(kern * denom) / denom)
        cdkern = sm.ccode(sm.horner(dkern * denom) / denom)

        kerns.append(kern)
        ckerns.append(ckern)
        dkerns.append(dkern)
        cdkerns.append(cdkern)

    return (legs, clegs, dlegs, cdlegs, lobs, clobs, dlobs, cdlobs, kerns,
            ckerns, dkerns, cdkerns, denoms)
Ejemplo n.º 47
0
def gen_lobatto(max_order):
    assert max_order > 2

    x = sm.symbols('x')

    lobs = [0, 1]
    lobs[0] = (1 - x) / 2
    lobs[1] = (1 + x) / 2

    dlobs = [lob.diff('x') for lob in lobs]

    legs = [sm.legendre(0, 'y')]
    clegs = [sm.ccode(legs[0])]
    dlegs = [sm.legendre(0, 'y').diff('y')]
    cdlegs = [sm.ccode(dlegs[0])]

    clobs = [sm.ccode(lob) for lob in lobs]
    cdlobs = [sm.ccode(dlob) for dlob in dlobs]

    denoms = [] # for lobs.

    for ii in range(2, max_order + 1):
        coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % ii)
        leg = sm.legendre(ii - 1, 'y')

        pleg = leg.as_poly()
        coefs = pleg.all_coeffs()
        denom = max(sm.denom(val) for val in coefs)

        cleg = sm.ccode(sm.horner(leg*denom)/denom)

        dleg = leg.diff('y')
        cdleg = sm.ccode(sm.horner(dleg*denom)/denom)

        lob = sm.simplify(coef * sm.integrate(leg, ('y', -1, x)))
        lobnc = sm.simplify(sm.integrate(leg, ('y', -1, x)))

        plobnc = lobnc.as_poly()
        coefs = plobnc.all_coeffs()
        denom = sm.denom(coef) * max(sm.denom(val) for val in coefs)

        clob = sm.ccode(sm.horner(lob*denom)/denom)

        dlob = lob.diff('x')
        cdlob = sm.ccode(sm.horner(dlob*denom)/denom)

        legs.append(leg)
        clegs.append(cleg)
        dlegs.append(dleg)
        cdlegs.append(cdleg)
        lobs.append(lob)
        clobs.append(clob)
        dlobs.append(dlob)
        cdlobs.append(cdlob)
        denoms.append(denom)

    coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % (max_order + 1))
    leg = sm.legendre(max_order, 'y')

    pleg = leg.as_poly()
    coefs = pleg.all_coeffs()
    denom = max(sm.denom(val) for val in coefs)

    cleg = sm.ccode(sm.horner(leg*denom)/denom)

    dleg = leg.diff('y')
    cdleg = sm.ccode(sm.horner(dleg*denom)/denom)

    legs.append(leg)
    clegs.append(cleg)
    dlegs.append(dleg)
    cdlegs.append(cdleg)

    kerns = []
    ckerns = []
    dkerns = []
    cdkerns = []
    for ii, lob in enumerate(lobs[2:]):
        kern = sm.simplify(lob / (lobs[0] * lobs[1]))
        dkern = kern.diff('x')

        denom = denoms[ii] / 4
        ckern = sm.ccode(sm.horner(kern*denom)/denom)
        cdkern = sm.ccode(sm.horner(dkern*denom)/denom)

        kerns.append(kern)
        ckerns.append(ckern)
        dkerns.append(dkern)
        cdkerns.append(cdkern)

    return (legs, clegs, dlegs, cdlegs,
            lobs, clobs, dlobs, cdlobs,
            kerns, ckerns, dkerns, cdkerns,
            denoms)
Ejemplo n.º 48
0
from sympy import HadamardProduct as HP
from beamshapes.special_functions import h2_nz
import tqdm
x, alpha, index, k, m, n, p, r1, R, theta, y, z = symbols(
    'x alpha index k m n p r1 R theta,y,z')
jj, nn = symbols('jj nn')

mpmath.mp.dps = dps

from beamshapes.special_functions import sph_hankel2
from beamshapes.utilities import args_to_mpmath, args_to_str

r1 = (R * cos(alpha)) / cos(theta)

# eqn 12.106
Pn_costheta = legendre(n, cos(theta))
Pm_costheta = legendre(m, cos(theta))
Pnminus1_costheta = Pn_costheta.subs(n, n - 1)
Pnplus1_costheta = Pn_costheta.subs(n, n + 1)

h2_n_kr1 = h2_nz.subs({'z': k * r1})
h2_nminus1_kr1 = h2_n_kr1.subs({'n': n - 1})
h2_nplut1_kr1 = h2_n_kr1.subs({'n': n + 1})

imn_bigbracket = (n * h2_nminus1_kr1 -
                  (n + 1) * h2_nplut1_kr1) * Pn_costheta * cos(theta) + n * (
                      n + 1) * h2_n_kr1 * (Pnminus1_costheta -
                                           Pnplus1_costheta) / (k * r1)

Imn = Integral(imn_bigbracket * Pm_costheta * (r1**2 / R**2) * tan(theta),
               (theta, 0, alpha))
Ejemplo n.º 49
0
def test_legendre():
    raises(ValueError, lambda: legendre(-1, x))
    assert legendre(0, x) == 1
    assert legendre(1, x) == x
    assert legendre(2, x) == ((3*x**2 - 1)/2).expand()
    assert legendre(3, x) == ((5*x**3 - 3*x)/2).expand()
    assert legendre(4, x) == ((35*x**4 - 30*x**2 + 3)/8).expand()
    assert legendre(5, x) == ((63*x**5 - 70*x**3 + 15*x)/8).expand()
    assert legendre(6, x) == ((231*x**6 - 315*x**4 + 105*x**2 - 5)/16).expand()

    assert legendre(10, -1) == 1
    assert legendre(11, -1) == -1
    assert legendre(10, 1) == 1
    assert legendre(11, 1) == 1
    assert legendre(10, 0) != 0
    assert legendre(11, 0) == 0

    assert roots(legendre(4, x), x) == {
        sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
        -sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
        sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
        -sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
    }

    n = Symbol("n")

    X = legendre(n, x)
    assert isinstance(X, legendre)

    assert legendre(-n, x) == legendre(n - 1, x)
    assert legendre(n, -x) == (-1)**n*legendre(n, x)

    assert conjugate(legendre(n, x)) == legendre(n, conjugate(x))

    assert diff(legendre(n, x), x) == \
        n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
    assert diff(legendre(n, x), n) == Derivative(legendre(n, x), n)
Ejemplo n.º 50
0
def test_legendre():
    raises(ValueError, 'legendre(-1, x)')
    assert legendre(0, x) == 1
    assert legendre(1, x) == x
    assert legendre(2, x) == ((3*x**2-1)/2).expand()
    assert legendre(3, x) == ((5*x**3-3*x)/2).expand()
    assert legendre(4, x) == ((35*x**4-30*x**2+3)/8).expand()
    assert legendre(5, x) == ((63*x**5-70*x**3+15*x)/8).expand()
    assert legendre(6, x) == ((231*x**6-315*x**4+105*x**2-5)/16).expand()

    assert legendre(10, -1) == 1
    assert legendre(11, -1) == -1
    assert legendre(10, 1) == 1
    assert legendre(11, 1) == 1
    assert legendre(10, 0) != 0
    assert legendre(11, 0) == 0

    assert roots(legendre(4,x), x) == {
         sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
        -sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
         sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
        -sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
    }
Ejemplo n.º 51
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,
                                  k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x,
                         y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}'

    assert latex(jacobi(n, a, b,
                        x)) == r'P_{n}^{\left(a,b\right)}\left(x\right)'
    assert latex(jacobi(
        n, a, b,
        x)**2) == r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
    assert latex(gegenbauer(n, a,
                            x)) == r'C_{n}^{\left(a\right)}\left(x\right)'
    assert latex(gegenbauer(
        n, a,
        x)**2) == r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
    assert latex(chebyshevt(n,
                            x)**2) == r'\left(T_{n}\left(x\right)\right)^{2}'
    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
    assert latex(chebyshevu(n,
                            x)**2) == r'\left(U_{n}\left(x\right)\right)^{2}'
    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_legendre(n, a,
                                x)) == r'P_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_legendre(
        n, a,
        x)**2) == r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_laguerre(n, a,
                                x)) == r'L_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_laguerre(
        n, a,
        x)**2) == r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**
                 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Ejemplo n.º 52
0

a, z = sympy.symbols("a z")
a0, z0 = 0, numpy.pi/2
epsilon = a*1e-15 + z*1e-15
order = 5
nSamples = 70
angles = numpy.arange(0,nSamples+1)*2*numpy.pi/nSamples
w = 2*math.pi*spectralRange/spectrumBins * numpy.arange(spectrumBins)

if False:
	print "Checking that the azimuthal formula is equivalent to the zenital formula"
	for l in xrange(0,order+1) :
	#	pattern1 = sum([sh_normalization2(l,m)*sympy.assoc_legendre(l,m,sympy.cos(z))*sympy.assoc_legendre(l,m,1) for m in xrange(0,l+1)])
	#	pattern1 = sh_normalization2(l,0)*sympy.assoc_legendre(l,0,sympy.cos(z))
		pattern1 = sh_normalization2(l,0)*sympy.legendre(l,sympy.cos(z))
		pylab.polar(angles, [ pattern1.subs(z,angle)/(2*l+1) for angle in angles ], label="Zenital %s"%l)

		pattern2 = sum([sh_normalization2(l,m)*sympy.cos(m*z)*sympy.assoc_legendre(l,m,0)**2 for m in xrange(0,l+1)])
		pylab.polar(angles, [ pattern2.subs(z,angle)/(2*l+1) for angle in angles ], label="Azimuthal %s"%l)
	pylab.title("Zenital vs Azimuthal variation",horizontalalignment='center', verticalalignment='baseline', position=(.5,-.1))
	pylab.rgrids(numpy.arange(.4,1,.2),angle=220)
	pylab.legend(loc=2)
	pylab.savefig(figurePath(__file__,"pdf"))
	pylab.show()
# We take the azimuthal formula which is faster
print "Computing component patterns"
patternComponents = [
	sh_normalization2(l,0)*sympy.legendre(l,sympy.cos(z))
	for l in xrange(0,order+1)
	]
Ejemplo n.º 53
0
	def __init__(self, decoding) :
		self.x = sympy.symbols("x")
		self.pattern = sum( (decoding[l] * sh_normalization2(l,0) * sympy.legendre(l,self.x) for l in xrange(0,len(decoding)) ))
		print self.pattern
Ejemplo n.º 54
0
def basis_functions(deg):
    '''Polynomial basis of degree P^deg[-1, 1] of Lengendre polynomials.'''
    return [legendre(k, Symbol('x')) for k in range(deg+1)]
Ejemplo n.º 55
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == r'f{\left (x \right )}'
    assert latex(f) == r'f'

    g = Function('g')
    assert latex(g(x, y)) == r'g{\left (x,y \right )}'
    assert latex(g) == r'g'

    h = Function('h')
    assert latex(h(x, y, z)) == r'h{\left (x,y,z \right )}'
    assert latex(h) == r'h'

    Li = Function('Li')
    assert latex(Li) == r'\operatorname{Li}'
    assert latex(Li(x)) == r'\operatorname{Li}{\left (x \right )}'

    beta = Function('beta')

    # not to be confused with the beta function
    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(beta) == r"\beta"

    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(
        FallingFactorial(3, k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\left\lvert{x}\right\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(
        polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(elliptic_k(z)) == r"K\left(z\right)"
    assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)"
    assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)"
    assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)"
    assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)"
    assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)"
    assert latex(elliptic_e(z)) == r"E\left(z\right)"
    assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)"
    assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)"
    assert latex(elliptic_pi(x, y, z)**2) == \
        r"\Pi^{2}\left(x; y\middle| z\right)"
    assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)"
    assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}', latex(Chi(x)**2)

    assert latex(
        jacobi(n, a, b, x)) == r'P_{n}^{\left(a,b\right)}\left(x\right)'
    assert latex(jacobi(n, a, b, x)**2) == r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
    assert latex(
        gegenbauer(n, a, x)) == r'C_{n}^{\left(a\right)}\left(x\right)'
    assert latex(gegenbauer(n, a, x)**2) == r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
    assert latex(
        chebyshevt(n, x)**2) == r'\left(T_{n}\left(x\right)\right)^{2}'
    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
    assert latex(
        chebyshevu(n, x)**2) == r'\left(U_{n}\left(x\right)\right)^{2}'
    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
    assert latex(
        assoc_legendre(n, a, x)) == r'P_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_legendre(n, a, x)**2) == r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
    assert latex(
        assoc_laguerre(n, a, x)) == r'L_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_laguerre(n, a, x)**2) == r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'

    theta = Symbol("theta", real=True)
    phi = Symbol("phi", real=True)
    assert latex(Ynm(n,m,theta,phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)'
    assert latex(Ynm(n, m, theta, phi)**3) == r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
    assert latex(Znm(n,m,theta,phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)'
    assert latex(Znm(n, m, theta, phi)**3) == r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(
        0)**3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"

    assert latex(totient(n)) == r'\phi\left( n \right)'

    # some unknown function name should get rendered with \operatorname
    fjlkd = Function('fjlkd')
    assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left (x \right )}'
    # even when it is referred to without an argument
    assert latex(fjlkd) == r'\operatorname{fjlkd}'