Example #1
0
def test_point3D():
    p1 = Point3D(x1, x2, x3)
    p2 = Point3D(y1, y2, y3)
    p3 = Point3D(0, 0, 0)
    p4 = Point3D(1, 1, 1)
    p5 = Point3D(0, 1, 2)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
    assert p4*5 == Point3D(5, 5, 5)
    assert -p2 == Point3D(-y1, -y2, -y3)

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
    assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
                                         half + half*x3)
    assert Point3D.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point3D.distance(p3, p4) == sqrt(3)
    assert Point3D.distance(p1, p1) == 0
    assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)

    p1_1 = Point3D(x1, x1, x1)
    p1_2 = Point3D(y2, y2, y2)
    p1_3 = Point3D(x1 + 1, x1, x1)
    assert Point3D.is_collinear(p3)
    assert Point3D.is_collinear(p3, p4)
    assert Point3D.is_collinear(p3, p4, p1_1, p1_2)
    assert Point3D.is_collinear(p3, p4, p1_1, p1_3) is False
    assert Point3D.is_collinear(p3, p3, p4, p5) is False

    assert p3.intersection(Point3D(0, 0, 0)) == [p3]
    assert p3.intersection(p4) == []


    assert p4 * 5 == Point3D(5, 5, 5)
    assert p4 / 5 == Point3D(0.2, 0.2, 0.2)

    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)

    # Point differences should be simplified
    assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
        Point3D(0, -1, 1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point3D(1, 1, 1)
    assert p.scale(2, 3) == Point3D(2, 3, 1)
    assert p.translate(1, 2) == Point3D(2, 3, 1)
    assert p.translate(1) == Point3D(2, 1, 1)
    assert p.translate(z=1) == Point3D(1, 1, 2)
    assert p.translate(*p.args) == Point3D(2, 2, 2)
Example #2
0
def test_composite_sums():
    f = Rational(1, 2)*(7 - 6*n + Rational(1, 7)*n**3)
    s = summation(f, (n, a, b))
    assert not isinstance(s, Sum)
    A = 0
    for i in range(-3, 5):
        A += f.subs(n, i)
    B = s.subs(a, -3).subs(b, 4)
    assert A == B
Example #3
0
def test_behavior2():
    x = Symbol('x')
    p = Wild('p')

    e = Rational(6)
    assert e.match(2*p) == {p: 3}

    e = 3*x + 3 + 6/x
    a = Wild('a', exclude = [x])
    assert e.expand().match(a*x**2 + a*x + 2*a) == None
    assert e.expand().match(p*x**2 + p*x + 2*p) == {p: 3/x}
Example #4
0
def test_symbol():
    x = Symbol('x')
    a,b,c,p,q = map(Wild, 'abcpq')

    e = x
    assert e.match(x) == {}
    assert e.match(a) == {a: x}

    e = Rational(5)
    assert e.match(c) == {c: 5}
    assert e.match(e) == {}
    assert e.match(e+1) == None
Example #5
0
 def __new__(cls, p, q=None, prec=15):
     rat = Rational.__new__(cls, p, q)
     if isinstance(rat, (Integer, Infinity)):
         return rat
     obj = Expr.__new__(cls)
     obj.p = rat.p
     obj.q = rat.q
     obj.prec = prec
     return obj
Example #6
0
def test_pow_im():
    for m in (-2, -1, 2):
        for d in (3, 4, 5):
            b = m * I
            for i in range(1, 4 * d + 1):
                e = Rational(i, d)
                assert (b ** e - b.n() ** e.n()).n(2, chop=1e-10) == 0

    e = Rational(7, 3)
    assert (2 * x * I) ** e == 4 * 2 ** Rational(1, 3) * (I * x) ** e  # same as Wolfram Alpha
    im = symbols("im", imaginary=True)
    assert (2 * im * I) ** e == 4 * 2 ** Rational(1, 3) * (I * im) ** e

    args = [I, I, I, I, 2]
    e = Rational(1, 3)
    ans = 2 ** e
    assert Mul(*args, **dict(evaluate=False)) ** e == ans
    assert Mul(*args) ** e == ans
    args = [I, I, I, 2]
    e = Rational(1, 3)
    ans = -(-1) ** Rational(5, 6) * 2 ** e
    assert Mul(*args, **dict(evaluate=False)) ** e == ans
    assert Mul(*args) ** e == ans
    args = [I, I, 2]
    e = Rational(1, 3)
    ans = (-2) ** e
    assert Mul(*args, **dict(evaluate=False)) ** e == ans
    assert Mul(*args) ** e == ans
Example #7
0
def test_pow_im():
    for m in (-2, -1, 2):
        for d in (3, 4, 5):
            b = m*I
            for i in range(1, 4*d + 1):
                e = Rational(i, d)
                assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0

    e = Rational(7, 3)
    assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e  # same as Wolfram Alpha
    im = symbols('im', imaginary=True)
    assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e

    args = [I, I, I, I, 2]
    e = Rational(1, 3)
    ans = 2**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans
    args = [I, I, I, 2]
    e = Rational(1, 3)
    ans = 2**e*(-I)**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans
    args.append(-3)
    ans = (6*I)**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans
    args.append(-1)
    ans = (-6*I)**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans

    args = [I, I, 2]
    e = Rational(1, 3)
    ans = (-2)**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans
    args.append(-3)
    ans = (6)**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans
    args.append(-1)
    ans = (-6)**e
    assert Mul(*args, evaluate=False)**e == ans
    assert Mul(*args)**e == ans
    assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I
    assert Mul(I*Pow(I, S.Half, evaluate=False)) == (-1)**Rational(3, 4)
Example #8
0
def test_frac():
    assert isinstance(frac(x), frac)
    assert frac(oo) == AccumBounds(0, 1)
    assert frac(-oo) == AccumBounds(0, 1)
    assert frac(zoo) is nan

    assert frac(n) == 0
    assert frac(nan) is nan
    assert frac(Rational(4, 3)) == Rational(1, 3)
    assert frac(-Rational(4, 3)) == Rational(2, 3)
    assert frac(Rational(-4, 3)) == Rational(2, 3)

    r = Symbol('r', real=True)
    assert frac(I * r) == I * frac(r)
    assert frac(1 + I * r) == I * frac(r)
    assert frac(0.5 + I * r) == 0.5 + I * frac(r)
    assert frac(n + I * r) == I * frac(r)
    assert frac(n + I * k) == 0
    assert unchanged(frac, x + I * x)
    assert frac(x + I * n) == frac(x)

    assert frac(x).rewrite(floor) == x - floor(x)
    assert frac(x).rewrite(ceiling) == x + ceiling(-x)
    assert frac(y).rewrite(floor).subs(y, pi) == frac(pi)
    assert frac(y).rewrite(floor).subs(y, -E) == frac(-E)
    assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi)
    assert frac(y).rewrite(ceiling).subs(y, E) == frac(E)

    assert Eq(frac(y), y - floor(y))
    assert Eq(frac(y), y + ceiling(-y))

    r = Symbol('r', real=True)
    p_i = Symbol('p_i', integer=True, positive=True)
    n_i = Symbol('p_i', integer=True, negative=True)
    np_i = Symbol('np_i', integer=True, nonpositive=True)
    nn_i = Symbol('nn_i', integer=True, nonnegative=True)
    p_r = Symbol('p_r', real=True, positive=True)
    n_r = Symbol('n_r', real=True, negative=True)
    np_r = Symbol('np_r', real=True, nonpositive=True)
    nn_r = Symbol('nn_r', real=True, nonnegative=True)

    # Real frac argument, integer rhs
    assert frac(r) <= p_i
    assert not frac(r) <= n_i
    assert (frac(r) <= np_i).has(Le)
    assert (frac(r) <= nn_i).has(Le)
    assert frac(r) < p_i
    assert not frac(r) < n_i
    assert not frac(r) < np_i
    assert (frac(r) < nn_i).has(Lt)
    assert not frac(r) >= p_i
    assert frac(r) >= n_i
    assert frac(r) >= np_i
    assert (frac(r) >= nn_i).has(Ge)
    assert not frac(r) > p_i
    assert frac(r) > n_i
    assert (frac(r) > np_i).has(Gt)
    assert (frac(r) > nn_i).has(Gt)

    assert not Eq(frac(r), p_i)
    assert not Eq(frac(r), n_i)
    assert Eq(frac(r), np_i).has(Eq)
    assert Eq(frac(r), nn_i).has(Eq)

    assert Ne(frac(r), p_i)
    assert Ne(frac(r), n_i)
    assert Ne(frac(r), np_i).has(Ne)
    assert Ne(frac(r), nn_i).has(Ne)

    # Real frac argument, real rhs
    assert (frac(r) <= p_r).has(Le)
    assert not frac(r) <= n_r
    assert (frac(r) <= np_r).has(Le)
    assert (frac(r) <= nn_r).has(Le)
    assert (frac(r) < p_r).has(Lt)
    assert not frac(r) < n_r
    assert not frac(r) < np_r
    assert (frac(r) < nn_r).has(Lt)
    assert (frac(r) >= p_r).has(Ge)
    assert frac(r) >= n_r
    assert frac(r) >= np_r
    assert (frac(r) >= nn_r).has(Ge)
    assert (frac(r) > p_r).has(Gt)
    assert frac(r) > n_r
    assert (frac(r) > np_r).has(Gt)
    assert (frac(r) > nn_r).has(Gt)

    assert not Eq(frac(r), n_r)
    assert Eq(frac(r), p_r).has(Eq)
    assert Eq(frac(r), np_r).has(Eq)
    assert Eq(frac(r), nn_r).has(Eq)

    assert Ne(frac(r), p_r).has(Ne)
    assert Ne(frac(r), n_r)
    assert Ne(frac(r), np_r).has(Ne)
    assert Ne(frac(r), nn_r).has(Ne)

    # Real frac argument, +/- oo rhs
    assert frac(r) < oo
    assert frac(r) <= oo
    assert not frac(r) > oo
    assert not frac(r) >= oo

    assert not frac(r) < -oo
    assert not frac(r) <= -oo
    assert frac(r) > -oo
    assert frac(r) >= -oo

    assert frac(r) < 1
    assert frac(r) <= 1
    assert not frac(r) > 1
    assert not frac(r) >= 1

    assert not frac(r) < 0
    assert (frac(r) <= 0).has(Le)
    assert (frac(r) > 0).has(Gt)
    assert frac(r) >= 0

    # Some test for numbers
    assert frac(r) <= sqrt(2)
    assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le)
    assert not frac(r) <= sqrt(2) - sqrt(3)
    assert not frac(r) >= sqrt(2)
    assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge)
    assert frac(r) >= sqrt(2) - sqrt(3)

    assert not Eq(frac(r), sqrt(2))
    assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq)
    assert not Eq(frac(r), sqrt(2) - sqrt(3))
    assert Ne(frac(r), sqrt(2))
    assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne)
    assert Ne(frac(r), sqrt(2) - sqrt(3))

    assert frac(p_i, evaluate=False).is_zero
    assert frac(p_i, evaluate=False).is_finite
    assert frac(p_i, evaluate=False).is_integer
    assert frac(p_i, evaluate=False).is_real
    assert frac(r).is_finite
    assert frac(r).is_real
    assert frac(r).is_zero is None
    assert frac(r).is_integer is None

    assert frac(oo).is_finite
    assert frac(oo).is_real
Example #9
0
def test_point3D():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    x3 = Symbol('x3', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    y3 = Symbol('y3', real=True)
    half = Rational(1, 2)
    p1 = Point3D(x1, x2, x3)
    p2 = Point3D(y1, y2, y3)
    p3 = Point3D(0, 0, 0)
    p4 = Point3D(1, 1, 1)
    p5 = Point3D(0, 1, 2)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
    assert p4*5 == Point3D(5, 5, 5)
    assert -p2 == Point3D(-y1, -y2, -y3)

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
    assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
                                         half + half*x3)
    assert Point3D.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point3D.distance(p3, p4) == sqrt(3)
    assert Point3D.distance(p1, p1) == 0
    assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)

    p1_1 = Point3D(x1, x1, x1)
    p1_2 = Point3D(y2, y2, y2)
    p1_3 = Point3D(x1 + 1, x1, x1)
    # according to the description in the docs, points are collinear
    # if they like on a single line.  Thus a single point should always
    # be collinear
    assert Point3D.are_collinear(p3)
    assert Point3D.are_collinear(p3, p4)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
    assert Point3D.are_collinear(p3, p3, p4, p5) is False

    assert p3.intersection(Point3D(0, 0, 0)) == [p3]
    assert p3.intersection(p4) == []


    assert p4 * 5 == Point3D(5, 5, 5)
    assert p4 / 5 == Point3D(0.2, 0.2, 0.2)

    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)

    # Point differences should be simplified
    assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
        Point3D(0, -1, 1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point3D(1, 1, 1)
    assert p.scale(2, 3) == Point3D(2, 3, 1)
    assert p.translate(1, 2) == Point3D(2, 3, 1)
    assert p.translate(1) == Point3D(2, 1, 1)
    assert p.translate(z=1) == Point3D(1, 1, 2)
    assert p.translate(*p.args) == Point3D(2, 2, 2)

    # Test __new__
    assert Point3D(Point3D(1, 2, 3), 4, 5, evaluate=False) ==  Point3D(1, 2, 3)


    # Test length property returns correctly
    assert p.length == 0
    assert p1_1.length == 0
    assert p1_2.length == 0

    # Test are_colinear type error
    raises(TypeError, lambda: Point3D.are_collinear(p, x))

    # Test are_coplanar
    planar2 = Point3D(1, -1, 1)
    planar3 = Point3D(-1, 1, 1)
    assert Point3D.are_coplanar(p, planar2, planar3) == True
    assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
    raises(ValueError, lambda: Point3D.are_coplanar(p, planar2))
    planar2 = Point3D(1, 1, 2)
    planar3 = Point3D(1, 1, 3)
    raises(ValueError, lambda: Point3D.are_coplanar(p, planar2, planar3))

    # Test Intersection
    assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]

    # Test Scale
    assert planar2.scale(1, 1, 1) == planar2
    assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
    assert planar2.scale(1, 1, 1, p3) == planar2

    # Test Transform
    identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
    assert p.transform(identity) == p
    trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
    assert p.transform(trans) == Point3D(2, 2, 2)
    raises(ValueError, lambda: p.transform(p))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))

    # Test Equals
    assert p.equals(x1) == False

    # Test __sub__
    p_2d = Point(0, 0)
    raises(ValueError, lambda: (p - p_2d))
Example #10
0
def test_match_exclude():
    x = Symbol('x')
    y = Symbol('y')
    p = Wild("p")
    q = Wild("q")
    r = Wild("r")

    e = Rational(6)
    assert e.match(2*p) == {p: 3}

    e = 3/(4*x + 5)
    assert e.match(3/(p*x + q)) == {p: 4, q: 5}

    e = 3/(4*x + 5)
    assert e.match(p/(q*x + r)) == {p: 3, q: 4, r: 5}

    e = 2/(x + 1)
    assert e.match(p/(q*x + r)) == {p: 2, q: 1, r: 1}

    e = 1/(x + 1)
    assert e.match(p/(q*x + r)) == {p: 1, q: 1, r: 1}

    e = 4*x + 5
    assert e.match(p*x + q) == {p: 4, q: 5}

    e = 4*x + 5*y + 6
    assert e.match(p*x + q*y + r) == {p: 4, q: 5, r: 6}

    a = Wild('a', exclude=[x])

    e = 3*x
    assert e.match(p*x) == {p: 3}
    assert e.match(a*x) == {a: 3}

    e = 3*x**2
    assert e.match(p*x) == {p: 3*x}
    assert e.match(a*x) is None

    e = 3*x + 3 + 6/x
    assert e.match(p*x**2 + p*x + 2*p) == {p: 3/x}
    assert e.match(a*x**2 + a*x + 2*a) is None
Example #11
0
 def _represent_JzOp(self, basis, **options):
     if self.j == Rational(1, 2):
         if self.m == Rational(1, 2):
             return Matrix([1, 1]) / sqrt(2)
         elif self.m == -Rational(1, 2):
             return Matrix([1, -1]) / sqrt(2)
Example #12
0
LaguerreF = binomial(n + alpha, n - k) * (-x) ** k / factorial(k)
LaguerreP = Sum(LaguerreF, (k, 0, n))

for alphavar in range(4):
    for nvar in range(4):
        print alphavar, nvar, LaguerreP.subs(n, nvar).subs(alpha, alphavar).doit(), LaguerreP.subs(n, nvar).subs(
            alpha, alphavar
        ).doit() == laguerre_poly(
            nvar, x, alpha=alphavar
        )  # True

(LaguerreF.subs(n, n + 1) / LaguerreF).simplify()  # (alpha + n + 1)/(-k + n + 1)
(LaguerreF.subs(k, k + 1) / LaguerreF).simplify()  # x*(k - n)/((k + 1)*(alpha + k + 1))

LegendreF = Rat(1) / (Rat(2) ** n) * (binomial(n, k)) ** 2 * (x - Rat(1)) ** k * (x + Rat(1)) ** (n - k)
LegendreP = Sum(LegendreF, (k, 0, n))

for nvar in range(4):
    legendre_poly(nvar, x) == LegendreP.subs(n, nvar).doit().expand()  # True

(LegendreF.subs(n, n + 1) / LegendreF).simplify()  # (n + 1)**2*(x + 1)/(2*(k - n - 1)**2)
(LegendreF.subs(k, k + 1) / LegendreF).simplify()  # (k - n)**2*(x - 1)/((k + 1)**2*(x + 1))

JacobiF = (
    Rat(1)
    / (Rat(2) ** n)
    * binomial(n + alpha, n - k)
    * binomial(n + beta, k)
    * (x - Rat(1)) ** k
    * (x + Rat(1)) ** (n - k)
Example #13
0
    def Fstar_F_rectlinear(
        self,
        gmeq: Union[Equations, EquationsIdtx],
        job_name: str,
        pr: Parameters,
        do_zoom: bool = False,
        fig_size: Optional[Tuple[float, float]] = None,
        dpi: Optional[int] = None,
    ) -> None:
        """Plot :math:`F^*`, :math:`F` on rectilinear axes."""
        name: str = f'{job_name}_Fstar_F_rectlinear{"_zoom" if do_zoom else ""}'
        _ = self.create_figure(name, fig_size=fig_size, dpi=dpi)
        axes: Axes = plt.gca()

        eta_ = pr.model.eta
        if do_zoom:
            if eta_ == Rational(3, 2):
                plt.xlim(0.98, 1.07)
                plt.ylim(0.15, 0.23)
                eta_xy_label = (0.2, 0.85)
            else:
                plt.xlim(0.7, 1.2)
                plt.ylim(-0.4, 0)
                eta_xy_label = (0.8, 0.8)
        else:
            if eta_ == Rational(3, 2):
                plt.xlim(0, 2)
                plt.ylim(-4, 0.6)
                eta_xy_label = (0.7, 0.8)
            else:
                plt.xlim(0, 2.5)
                plt.ylim(-2, 0)
                eta_xy_label = (0.8, 0.7)

        # Critical, bounding angles
        pz_max_ = -1.5
        px_abmax_ = -pz_max_ * (self.tanbeta_max
                                if self.tanbeta_max > 0 else 1)
        pz_abmax_ = pz_max_
        vx_abmax_, vz_abmax_ = self.v_from_gstar_lambda(px_abmax_, pz_abmax_)
        px_abcrit_ = -pz_max_ * gmeq.tanbeta_crit
        pz_abcrit_ = pz_max_
        vx_abcrit_, vz_abcrit_ = self.v_from_gstar_lambda(
            px_abcrit_, pz_abcrit_)

        # Lines visualizing critical, bounding angles: ray velocity
        if eta_ == Rational(3, 2):
            plt.plot(
                [0, vx_abmax_],
                [0, vz_abmax_],
                "-",
                color="r",
                alpha=0.4,
                lw=2,
                label=r"$\alpha_{\mathrm{lim}}$",
            )

        # Indicatrix aka F=1 for rays
        plt.plot(
            self.v_supc_array[:, 0],
            self.v_supc_array[:, 1],
            "r" if eta_ > 1 else "DarkRed",
            lw=2,
            ls="-",
            label=r"$F=1$,  $\beta\geq\beta_\mathrm{c}$",
        )
        plt.plot(
            [0, vx_abcrit_],
            [0, vz_abcrit_],
            "-.",
            color="DarkRed" if eta_ > 1 else "r",
            lw=1,
            label=r"$\alpha_{\mathrm{c}}$",
        )
        plt.plot(
            self.v_infc_array[:, 0],
            self.v_infc_array[:, 1],
            "DarkRed" if eta_ > 1 else "r",
            lw=1 if eta_ == Rational(3, 2) and not do_zoom else 2,
            ls="-",
            label=r"$F=1$,  $\beta <\beta_\mathrm{c}$",
        )

        # Lines visualizing critical, bounding angles: normal slowness
        if eta_ == Rational(3, 2) and not do_zoom:
            plt.plot(
                np.array([0, px_abmax_]),
                [0, pz_abmax_],
                "-b",
                alpha=0.4,
                lw=1.5,
                label=r"$\beta_{\mathrm{max}}$",
            )

        # Figuratrix aka F*=1 for surfaces
        if not do_zoom:
            plt.plot(
                self.p_supc_array[:, 0],
                self.p_supc_array[:, 1],
                "b" if eta_ > 1 else "DarkBlue",
                lw=2,
                ls="-",
                label=r"$F^*\!\!=1$,  $\beta\geq\beta_\mathrm{c}$",
            )
            plt.plot(
                [0, px_abcrit_],
                [0, pz_abcrit_],
                "--",
                color="DarkBlue" if eta_ > 1 else "b",
                lw=1,
                label=r"$\beta_{\mathrm{c}}$",
            )
            plt.plot(
                self.p_infc_array[:, 0],
                self.p_infc_array[:, 1],
                "DarkBlue" if eta_ > 1 else "b",
                lw=2,
                ls="-",
                label=r"$F^*\!\!=1$,  $\beta<\beta_\mathrm{c}$",
            )

        pz_ = -float(
            solve(self.H_parametric_eqn.subs({px: pz *
                                              (gmeq.tanbeta_crit)}), pz)[0])
        px_ = self.px_H_lambda(pz_)
        (vx_, vz_) = self.v_from_gstar_lambda(px_, pz_)
        if eta_ != Rational(3, 2):
            plt.plot([vx_], [-vz_], "o", color="r", ms=5)
        if not do_zoom:
            plt.plot([px_], [-pz_],
                     "o",
                     color="DarkBlue" if eta_ > 1 else "b",
                     ms=5)

        plt.xlabel(r"$p_x$ (for $F^*$)  or  $v^x$ (for $F$)", fontsize=14)
        plt.ylabel(r"$p_z$ (for $F^*$)  or  $v^z$ (for $F$)", fontsize=14)

        axes.set_aspect(1)
        plt.text(
            *eta_xy_label,
            rf"$\eta={gmeq.eta_}$",
            transform=axes.transAxes,
            horizontalalignment="center",
            verticalalignment="center",
            fontsize=15,
            color="k",
        )

        if eta_ == Rational(3, 2):
            loc_ = "lower right" if do_zoom else "lower left"
        else:
            loc_ = "upper left" if do_zoom else "lower right"
        plt.legend(loc=loc_)

        self.convex_concave_annotations(do_zoom, eta_)

        plt.grid(True, ls=":")
Example #14
0
    def __init__(
        self,
        gmeq: Union[Equations, EquationsIdtx],
        pr: Parameters,
        sub_: Dict,
        varphi_: float = 1,
    ) -> None:
        """Initialize: constructor method."""
        super().__init__()
        self.H_parametric_eqn = (Eq((2 * gmeq.H_eqn.rhs)**2, 1).subs({
            varphi_r(rvec):
            varphi_,
            xiv:
            xiv_0
        }).subs(sub_))

        if pr.model.eta == Rational(3, 2):
            pz_min_eqn = Eq(
                pz_min,
                (solve(
                    Eq(
                        ((solve(
                            Eq(4 * gmeq.H_eqn.rhs**2,
                               1).subs({varphi_r(rvec): varphi}),
                            px**2,
                        )[2]).args[0].args[0].args[0])**2,
                        0,
                    ),
                    pz**4,
                )[0])**Rational(1, 4),
            )
            px_min_eqn = Eq(
                px_min,
                solve(
                    simplify(
                        gmeq.H_eqn.subs({
                            varphi_r(rvec): varphi
                        }).subs({pz:
                                 pz_min_eqn.rhs})).subs({H: Rational(1, 2)}),
                    px,
                )[0],
            )
            tanbeta_max_eqn = Eq(
                tan(beta_max),
                ((px_min / pz_min).subs(e2d(px_min_eqn))).subs(
                    e2d(pz_min_eqn)),
            )
            self.tanbeta_max = float(N(tanbeta_max_eqn.rhs))
        else:
            pz_min_eqn = Eq(pz_min, 0)
            px_min_eqn = Eq(
                px_min,
                sqrt(
                    solve(
                        Eq(
                            (solve(
                                Eq(4 * gmeq.H_eqn.rhs**2,
                                   1).subs({varphi_r(rvec): varphi}),
                                pz**2,
                            )[:])[0],
                            0,
                        ),
                        px**2,
                    )[1]),
            )
            tanbeta_max_eqn = Eq(tan(beta_max), oo)
            self.tanbeta_max = 0.0

        pz_min_ = round(float(N(pz_min_eqn.rhs.subs({varphi: varphi_}))), 8)

        px_H_solns = [
            simplify(sqrt(soln))
            for soln in solve(self.H_parametric_eqn, px**2)
        ]
        px_H_soln_ = [
            soln for soln in px_H_solns
            if Abs(im(N(soln.subs({pz: 1})))) < 1e-10
        ][0]
        self.px_H_lambda = lambdify([pz], simplify(px_H_soln_))

        pz_max_ = 10**4 if pr.model.eta == Rational(3, 2) else 10**2
        pz_array = -(10**np.linspace(
            np.log10(pz_min_ if pz_min_ > 0 else 1e-6),
            np.log10(pz_max_),
            1000,
        ))
        px_array = self.px_H_lambda(pz_array)
        p_array = np.vstack([px_array, pz_array]).T
        tanbeta_crit = float(N(gmeq.tanbeta_crit_eqn.rhs))

        self.p_infc_array = p_array[np.abs(p_array[:, 0] /
                                           p_array[:, 1]) < tanbeta_crit]
        self.p_supc_array = p_array[np.abs(p_array[:, 0] /
                                           p_array[:, 1]) >= tanbeta_crit]

        v_from_gstar_lambda_tmp = lambdify(
            (px, pz),
            N(
                gmeq.gstar_varphi_pxpz_eqn.subs({
                    varphi_r(rvec): varphi_
                }).rhs * Matrix([px, pz])),
        )
        self.v_from_gstar_lambda = lambda px_, pz_: (v_from_gstar_lambda_tmp(
            px_, pz_)).flatten()

        def v_lambda(pa):
            return np.array([(self.v_from_gstar_lambda(px_, pz_))
                             for px_, pz_ in pa])

        self.v_infc_array = v_lambda(self.p_infc_array)
        self.v_supc_array = v_lambda(self.p_supc_array)
Example #15
0
def test_issue_10610():
    assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3)
Example #16
0
def test_issue_13332():
    assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) *
                (6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36)
Example #17
0
def test_calculate_series():
    # needs gruntz calculate_series to go to n = 32
    assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1
    # needs gruntz calculate_series to go to n = 128
    assert limit(x**101.1/(1 + x**101.1), x, oo) == 1
Example #18
0
def test_issue_6560():
    e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) +
                             35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1)))
    assert limit(e, y, oo) == (5*x**3 + 3*x**2 - 3*x - 1)/4
Example #19
0
def test_issue_4090():
    assert limit(1/(x + 3), x, 2) == Rational(1, 5)
    assert limit(1/(x + pi), x, 2) == S.One/(2 + pi)
    assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7
    assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi)
Example #20
0
def test_pretty_basic():
    assert pretty(-Rational(1) / 2) == '-1/2'
    assert pretty( -Rational(13)/22 ) == \
"""\
  13\n\
- --\n\
  22\
"""
    expr = oo
    ascii_str = \
"""\
oo\
"""
    ucode_str = \
u"""\
∞\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (x**2)
    ascii_str = \
"""\
 2\n\
x \
"""
    ucode_str = \
u"""\
 2\n\
x \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = 1 / x
    ascii_str = \
"""\
1\n\
-\n\
x\
"""
    ucode_str = \
u"""\
1\n\
─\n\
x\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = y * x**-2
    ascii_str = \
"""\
y \n\
--\n\
 2\n\
x \
"""
    ucode_str = \
u"""\
y \n\
──\n\
 2\n\
x \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = x**Rational(-5, 2)
    ascii_str = \
"""\
 1  \n\
----\n\
 5/2\n\
x   \
"""
    ucode_str = \
u"""\
 1  \n\
────\n\
 5/2\n\
x   \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (-2)**x
    ascii_str = \
"""\
    x\n\
(-2) \
"""
    ucode_str = \
u"""\
    x\n\
(-2) \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    # See issue 1824
    expr = Pow(3, 1, evaluate=False)
    ascii_str = \
"""\
 1\n\
3 \
"""
    ucode_str = \
u"""\
 1\n\
3 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (x**2 + x + 1)
    ascii_str_1 = \
"""\
         2\n\
1 + x + x \
"""
    ascii_str_2 = \
"""\
 2       \n\
x + x + 1\
"""
    ascii_str_3 = \
"""\
 2       \n\
x + 1 + x\
"""
    ucode_str_1 = \
u"""\
         2\n\
1 + x + x \
"""
    ucode_str_2 = \
u"""\
 2       \n\
x + x + 1\
"""
    ucode_str_3 = \
u"""\
 2       \n\
x + 1 + x\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]

    expr = 1 - x
    ascii_str_1 = \
"""\
1 - x\
"""
    ascii_str_2 = \
"""\
-x + 1\
"""
    ucode_str_1 = \
u"""\
1 - x\
"""
    ucode_str_2 = \
u"""\
-x + 1\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = 1 - 2 * x
    ascii_str_1 = \
"""\
1 - 2*x\
"""
    ascii_str_2 = \
"""\
-2*x + 1\
"""
    ucode_str_1 = \
u"""\
1 - 2⋅x\
"""
    ucode_str_2 = \
u"""\
-2⋅x + 1\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = x / y
    ascii_str = \
"""\
x\n\
-\n\
y\
"""
    ucode_str = \
u"""\
x\n\
─\n\
y\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = -x / y
    ascii_str = \
"""\
-x\n\
--\n\
y \
"""
    ucode_str = \
u"""\
-x\n\
──\n\
y \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (x + 2) / y
    ascii_str_1 = \
"""\
2 + x\n\
-----\n\
  y  \
"""
    ascii_str_2 = \
"""\
x + 2\n\
-----\n\
  y  \
"""
    ucode_str_1 = \
u"""\
2 + x\n\
─────\n\
  y  \
"""
    ucode_str_2 = \
u"""\
x + 2\n\
─────\n\
  y  \
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = (1 + x) * y
    ascii_str_1 = \
"""\
y*(1 + x)\
"""
    ascii_str_2 = \
"""\
(1 + x)*y\
"""
    ascii_str_3 = \
"""\
y*(x + 1)\
"""
    ucode_str_1 = \
u"""\
y⋅(1 + x)\
"""
    ucode_str_2 = \
u"""\
(1 + x)⋅y\
"""
    ucode_str_3 = \
u"""\
y⋅(x + 1)\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]

    # Test for correct placement of the negative sign
    expr = -5 * x / (x + 10)
    ascii_str_1 = \
"""\
 -5*x \n\
------\n\
10 + x\
"""
    ascii_str_2 = \
"""\
 -5*x \n\
------\n\
x + 10\
"""
    ucode_str_1 = \
u"""\
 -5⋅x \n\
──────\n\
10 + x\
"""
    ucode_str_2 = \
u"""\
 -5⋅x \n\
──────\n\
x + 10\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = 1 - Rational(3, 2) * (x + 1)
    ascii_str = \
"""\
       3*x\n\
-1/2 - ---\n\
        2 \
"""
    ucode_str = \
u"""\
       3⋅x\n\
-1/2 - ───\n\
        2 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str
Example #21
0
def test_pretty_integrals():
    expr = Integral(log(x), x)
    ascii_str = \
"""\
  /         \n\
 |          \n\
 | log(x) dx\n\
 |          \n\
/           \
"""
    ucode_str = \
u"""\
⌠          \n\
⎮ log(x) dx\n\
⌡          \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral(x**2, x)
    ascii_str = \
"""\
  /     \n\
 |      \n\
 |  2   \n\
 | x  dx\n\
 |      \n\
/       \
"""
    ucode_str = \
u"""\
⌠      \n\
⎮  2   \n\
⎮ x  dx\n\
⌡      \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral((sin(x))**2 / (tan(x))**2)
    ascii_str = \
"""\
  /          \n\
 |           \n\
 |    2      \n\
 | sin (x)   \n\
 | ------- dx\n\
 |    2      \n\
 | tan (x)   \n\
 |           \n\
/            \
"""
    ucode_str = \
u"""\
⌠           \n\
⎮    2      \n\
⎮ sin (x)   \n\
⎮ ─────── dx\n\
⎮    2      \n\
⎮ tan (x)   \n\
⌡           \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral(x**(2**x), x)
    ascii_str = \
"""\
  /        \n\
 |         \n\
 |  / x\   \n\
 |  \\2 /   \n\
 | x     dx\n\
 |         \n\
/          \
"""
    ucode_str = \
u"""\
⌠         \n\
⎮  ⎛ x⎞   \n\
⎮  ⎝2 ⎠   \n\
⎮ x     dx\n\
⌡         \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral(x**2, (x, 1, 2))
    ascii_str = \
"""\
  2      \n\
  /      \n\
 |       \n\
 |   2   \n\
 |  x  dx\n\
 |       \n\
/        \n\
1        \
"""
    ucode_str = \
u"""\
2      \n\
⌠      \n\
⎮  2   \n\
⎮ x  dx\n\
⌡      \n\
1      \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral(x**2, (x, Rational(1, 2), 10))
    ascii_str = \
"""\
 10      \n\
  /      \n\
 |       \n\
 |   2   \n\
 |  x  dx\n\
 |       \n\
/        \n\
1/2      \
"""
    ucode_str = \
u"""\
 10      \n\
 ⌠       \n\
 ⎮   2   \n\
 ⎮  x  dx\n\
 ⌡       \n\
1/2      \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral(x**2 * y**2, x, y)
    ascii_str = \
"""\
  /  /           \n\
 |  |            \n\
 |  |  2  2      \n\
 |  | x *y  dx dy\n\
 |  |            \n\
/  /             \
"""
    ucode_str = \
u"""\
⌠ ⌠            \n\
⎮ ⎮  2  2      \n\
⎮ ⎮ x ⋅y  dx dy\n\
⌡ ⌡            \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Integral(sin(th) / cos(ph), (th, 0, pi), (ph, 0, 2 * pi))
    ascii_str = \
"""\
 2*pi pi                           \n\
   /   /                           \n\
  |   |                            \n\
  |   |  sin(theta)                \n\
  |   |  ---------- d(theta) d(phi)\n\
  |   |   cos(phi)                 \n\
  |   |                            \n\
 /   /                             \n\
 0   0                             \
"""
    ucode_str = \
u"""\
2⋅π π             \n\
 ⌠  ⌠             \n\
 ⎮  ⎮ sin(θ)      \n\
 ⎮  ⎮ ────── dθ dφ\n\
 ⎮  ⎮ cos(φ)      \n\
 ⌡  ⌡             \n\
 0  0             \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str
Example #22
0
def test_pretty_sqrt():
    expr = sqrt(2)
    ascii_str = \
"""\
  ___\n\
\/ 2 \
"""
    ucode_str = \
u"""\
  ⎽⎽⎽\n\
╲╱ 2 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = 2**Rational(1, 3)
    ascii_str = \
"""\
3 ___\n\
\/ 2 \
"""
    ucode_str = \
u"""\
3 ⎽⎽⎽\n\
╲╱ 2 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = 2**Rational(1, 1000)
    ascii_str = \
"""\
1000___\n\
  \/ 2 \
"""
    ucode_str = \
u"""\
1000⎽⎽⎽\n\
  ╲╱ 2 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = sqrt(x**2 + 1)
    ascii_str = \
"""\
   ________\n\
  /      2 \n\
\/  1 + x  \
"""
    ucode_str = \
u"""\
   ⎽⎽⎽⎽⎽⎽⎽⎽\n\
  ╱      2 \n\
╲╱  1 + x  \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (1 + sqrt(5))**Rational(1, 3)
    ascii_str = \
"""\
   ___________\n\
3 /       ___ \n\
\/  1 + \/ 5  \
"""
    ucode_str = \
u"""\
   ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽\n\
3 ╱       ⎽⎽⎽ \n\
╲╱  1 + ╲╱ 5  \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = 2**(1 / x)
    ascii_str = \
"""\
x ___\n\
\/ 2 \
"""
    ucode_str = \
u"""\
x ⎽⎽⎽\n\
╲╱ 2 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = sqrt(2 + pi)
    ascii_str = \
"""\
  ________\n\
\/ 2 + pi \
"""
    ucode_str = \
u"""\
  ⎽⎽⎽⎽⎽⎽⎽\n\
╲╱ 2 + π \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (2 + (1 + x**2) / (2 + x))**Rational(
        1, 4) + (1 + x**Rational(1, 1000)) / sqrt(3 + x**2)
    ascii_str = \
"""\
                   ____________\n\
    1000___       /          2 \n\
1 +   \/ x       /      1 + x  \n\
----------- + 4 /   2 + ------ \n\
   ________   \/        2 + x  \n\
  /      2                     \n\
\/  3 + x                      \
"""
    ucode_str = \
u"""\
                   ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽\n\
    1000⎽⎽⎽       ╱          2 \n\
1 +   ╲╱ x       ╱      1 + x  \n\
─────────── + 4 ╱   2 + ────── \n\
   ⎽⎽⎽⎽⎽⎽⎽⎽   ╲╱        2 + x  \n\
  ╱      2                     \n\
╲╱  3 + x                      \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str
Example #23
0
    def random_point(self, seed=None):
        """A random point on the ellipse.

        Returns
        =======

        point : Point

        See Also
        ========

        sympy.geometry.point.Point
        arbitrary_point : Returns parameterized point on ellipse

        Notes
        -----

        A random point may not appear to be on the ellipse, ie, `p in e` may
        return False. This is because the coordinates of the point will be
        floating point values, and when these values are substituted into the
        equation for the ellipse the result may not be zero because of floating
        point rounding error.

        Examples
        ========

        >>> from sympy import Point, Ellipse, Segment
        >>> e1 = Ellipse(Point(0, 0), 3, 2)
        >>> e1.random_point() # gives some random point
        Point(...)
        >>> p1 = e1.random_point(seed=0); p1.n(2)
        Point(2.1, 1.4)

        The random_point method assures that the point will test as being
        in the ellipse:

        >>> p1 in e1
        True

        Notes
        =====

        An arbitrary_point with a random value of t substituted into it may
        not test as being on the ellipse because the expression tested that
        a point is on the ellipse doesn't simplify to zero and doesn't evaluate
        exactly to zero:

        >>> from sympy.abc import t
        >>> e1.arbitrary_point(t)
        Point(3*cos(t), 2*sin(t))
        >>> p2 = _.subs(t, 0.1)
        >>> p2 in e1
        False

        Note that arbitrary_point routine does not take this approach. A value for
        cos(t) and sin(t) (not t) is substituted into the arbitrary point. There is
        a small chance that this will give a point that will not test as being
        in the ellipse, so the process is repeated (up to 10 times) until a
        valid point is obtained.

        """
        from sympy import sin, cos, Rational
        t = _symbol('t')
        x, y = self.arbitrary_point(t).args
        # get a random value in [-1, 1) corresponding to cos(t)
        # and confirm that it will test as being in the ellipse
        if seed is not None:
            rng = random.Random(seed)
        else:
            rng = random
        for i in range(10):  # should be enough?
            # simplify this now or else the Float will turn s into a Float
            c = 2*Rational(rng.random()) - 1
            s = sqrt(1 - c**2)
            p1 = Point(x.subs(cos(t), c), y.subs(sin(t), s))
            if p1 in self:
                return p1
        raise GeometryError(
            'Having problems generating a point in the ellipse.')
Example #24
0
def test_moment_generating_function():
    t = symbols('t', positive=True)

    # Symbolic tests
    a, b, c = symbols('a b c')

    mgf = moment_generating_function(Beta('x', a, b))(t)
    assert mgf == hyper((a, ), (a + b, ), t)

    mgf = moment_generating_function(Chi('x', a))(t)
    assert mgf == sqrt(2)*t*gamma(a/2 + S.Half)*\
        hyper((a/2 + S.Half,), (Rational(3, 2),), t**2/2)/gamma(a/2) +\
        hyper((a/2,), (S.Half,), t**2/2)

    mgf = moment_generating_function(ChiSquared('x', a))(t)
    assert mgf == (1 - 2 * t)**(-a / 2)

    mgf = moment_generating_function(Erlang('x', a, b))(t)
    assert mgf == (1 - t / b)**(-a)

    mgf = moment_generating_function(ExGaussian("x", a, b, c))(t)
    assert mgf == exp(a * t + b**2 * t**2 / 2) / (1 - t / c)

    mgf = moment_generating_function(Exponential('x', a))(t)
    assert mgf == a / (a - t)

    mgf = moment_generating_function(Gamma('x', a, b))(t)
    assert mgf == (-b * t + 1)**(-a)

    mgf = moment_generating_function(Gumbel('x', a, b))(t)
    assert mgf == exp(b * t) * gamma(-a * t + 1)

    mgf = moment_generating_function(Gompertz('x', a, b))(t)
    assert mgf == b * exp(b) * expint(t / a, b)

    mgf = moment_generating_function(Laplace('x', a, b))(t)
    assert mgf == exp(a * t) / (-b**2 * t**2 + 1)

    mgf = moment_generating_function(Logistic('x', a, b))(t)
    assert mgf == exp(a * t) * beta(-b * t + 1, b * t + 1)

    mgf = moment_generating_function(Normal('x', a, b))(t)
    assert mgf == exp(a * t + b**2 * t**2 / 2)

    mgf = moment_generating_function(Pareto('x', a, b))(t)
    assert mgf == b * (-a * t)**b * uppergamma(-b, -a * t)

    mgf = moment_generating_function(QuadraticU('x', a, b))(t)
    assert str(mgf) == (
        "(3*(t*(-4*b + (a + b)**2) + 4)*exp(b*t) - "
        "3*(t*(a**2 + 2*a*(b - 2) + b**2) + 4)*exp(a*t))/(t**2*(a - b)**3)")

    mgf = moment_generating_function(RaisedCosine('x', a, b))(t)
    assert mgf == pi**2 * exp(a * t) * sinh(b * t) / (b * t *
                                                      (b**2 * t**2 + pi**2))

    mgf = moment_generating_function(Rayleigh('x', a))(t)
    assert mgf == sqrt(2)*sqrt(pi)*a*t*(erf(sqrt(2)*a*t/2) + 1)\
        *exp(a**2*t**2/2)/2 + 1

    mgf = moment_generating_function(Triangular('x', a, b, c))(t)
    assert str(mgf) == ("(-2*(-a + b)*exp(c*t) + 2*(-a + c)*exp(b*t) + "
                        "2*(b - c)*exp(a*t))/(t**2*(-a + b)*(-a + c)*(b - c))")

    mgf = moment_generating_function(Uniform('x', a, b))(t)
    assert mgf == (-exp(a * t) + exp(b * t)) / (t * (-a + b))

    mgf = moment_generating_function(UniformSum('x', a))(t)
    assert mgf == ((exp(t) - 1) / t)**a

    mgf = moment_generating_function(WignerSemicircle('x', a))(t)
    assert mgf == 2 * besseli(1, a * t) / (a * t)

    # Numeric tests

    mgf = moment_generating_function(Beta('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 1) == hyper((2, ), (3, ), 1) / 2

    mgf = moment_generating_function(Chi('x', 1))(t)
    assert mgf.diff(t).subs(t, 1) == sqrt(2) * hyper(
        (1, ), (Rational(3, 2), ), S.Half) / sqrt(pi) + hyper(
            (Rational(3, 2), ),
            (Rational(3, 2), ), S.Half) + 2 * sqrt(2) * hyper(
                (2, ), (Rational(5, 2), ), S.Half) / (3 * sqrt(pi))

    mgf = moment_generating_function(ChiSquared('x', 1))(t)
    assert mgf.diff(t).subs(t, 1) == I

    mgf = moment_generating_function(Erlang('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 0) == 1

    mgf = moment_generating_function(ExGaussian("x", 0, 1, 1))(t)
    assert mgf.diff(t).subs(t, 2) == -exp(2)

    mgf = moment_generating_function(Exponential('x', 1))(t)
    assert mgf.diff(t).subs(t, 0) == 1

    mgf = moment_generating_function(Gamma('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 0) == 1

    mgf = moment_generating_function(Gumbel('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 0) == EulerGamma + 1

    mgf = moment_generating_function(Gompertz('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 1) == -e * meijerg(((), (1, 1)),
                                                  ((0, 0, 0), ()), 1)

    mgf = moment_generating_function(Laplace('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 0) == 1

    mgf = moment_generating_function(Logistic('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 0) == beta(1, 1)

    mgf = moment_generating_function(Normal('x', 0, 1))(t)
    assert mgf.diff(t).subs(t, 1) == exp(S.Half)

    mgf = moment_generating_function(Pareto('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 0) == expint(1, 0)

    mgf = moment_generating_function(QuadraticU('x', 1, 2))(t)
    assert mgf.diff(t).subs(t, 1) == -12 * e - 3 * exp(2)

    mgf = moment_generating_function(RaisedCosine('x', 1, 1))(t)
    assert mgf.diff(t).subs(t, 1) == -2*e*pi**2*sinh(1)/\
    (1 + pi**2)**2 + e*pi**2*cosh(1)/(1 + pi**2)

    mgf = moment_generating_function(Rayleigh('x', 1))(t)
    assert mgf.diff(t).subs(t, 0) == sqrt(2) * sqrt(pi) / 2

    mgf = moment_generating_function(Triangular('x', 1, 3, 2))(t)
    assert mgf.diff(t).subs(t, 1) == -e + exp(3)

    mgf = moment_generating_function(Uniform('x', 0, 1))(t)
    assert mgf.diff(t).subs(t, 1) == 1

    mgf = moment_generating_function(UniformSum('x', 1))(t)
    assert mgf.diff(t).subs(t, 1) == 1

    mgf = moment_generating_function(WignerSemicircle('x', 1))(t)
    assert mgf.diff(t).subs(t, 1) == -2*besseli(1, 1) + besseli(2, 1) +\
        besseli(0, 1)
Example #25
0
def test_ops():
    k0 = Ket(0)
    k1 = Ket(1)
    k = 2*I*k0 - (x/sqrt(2))*k1
    assert k == Add(Mul(2, I, k0),
        Mul(Rational(-1, 2), x, Pow(2, S.Half), k1))
Example #26
0
    def Fstar_F_polar(
        self,
        gmeq: Union[Equations, EquationsIdtx],
        job_name: str,
        pr: Parameters,
        fig_size: Optional[Tuple[float, float]] = None,
        dpi: Optional[int] = None,
    ) -> None:
        """Plot :math:`F^*`, :math:`F` on log-polar axes."""
        name = f"{job_name}_Fstar_F_polar"
        _ = self.create_figure(name, fig_size=fig_size, dpi=dpi)

        eta_ = pr.model.eta

        scale_fn = np.log10
        if eta_ > 1:
            r_min_, r_max_ = 0.1, 100

            def alpha_fn(a):
                return np.pi - a

        else:
            r_min_, r_max_ = 0.1, 10

            def alpha_fn(a):
                return a

        def v_scale_fn(v):
            return scale_fn(v) * 1

        # Lines visualizing critical, bounding angles: ray velocity
        if eta_ > 1:
            plt.polar(
                [np.pi / 2 + (np.arctan(gmeq.tanalpha_ext))] * 2,
                [scale_fn(r_min_), scale_fn(r_max_)],
                "-",
                color="r" if eta_ > 1 else "DarkRed",
                alpha=0.4,
                lw=2,
                label=r"$\alpha_{\mathrm{lim}}$",
            )
        plt.polar(
            alpha_fn(
                np.arcsin(self.v_supc_array[:, 0] /
                          norm(self.v_supc_array, axis=1))),
            v_scale_fn(norm(self.v_supc_array, axis=1)),
            "r" if eta_ > 1 else "DarkRed",
            label=r"$F=1$,  $\beta\geq\beta_\mathrm{c}$",
        )
        plt.polar(
            [np.pi / 2 + (np.arctan(gmeq.tanalpha_ext))] * 2,
            [scale_fn(r_min_), scale_fn(r_max_)],
            "-.",
            color="DarkRed" if eta_ > 1 else "r",
            lw=1,
            label=r"$\alpha_{\mathrm{c}}$",
        )
        plt.polar(
            alpha_fn(
                np.arcsin(self.v_infc_array[:, 0] /
                          norm(self.v_infc_array, axis=1))),
            v_scale_fn(norm(self.v_infc_array, axis=1)),
            "DarkRed" if eta_ > 1 else "r",
            lw=None if eta_ == Rational(3, 2) else None,
            label=r"$F=1$,  $\beta <\beta_\mathrm{c}$",
        )

        unit_circle_array = np.array(
            [[theta_, 1] for theta_ in np.linspace(0, (np.pi / 2) * 1.2, 100)])
        plt.polar(
            unit_circle_array[:, 0],
            scale_fn(unit_circle_array[:, 1]),
            "-",
            color="g",
            lw=1,
            label="unit circle",
        )

        if eta_ > 1:
            plt.polar(
                [np.arctan(self.tanbeta_max)] * 2,
                [scale_fn(r_min_), scale_fn(r_max_)],
                "-",
                color="b",
                alpha=0.3,
                lw=1.5,
                label=r"$\beta_{\mathrm{max}}$",
            )
        plt.polar(
            np.arcsin(self.p_supc_array[:, 0] /
                      norm(self.p_supc_array, axis=1)),
            scale_fn(norm(self.p_supc_array, axis=1)),
            "b" if eta_ > 1 else "DarkBlue",
            label=r"$F^*\!\!=1$,  $\beta\geq\beta_\mathrm{c}$",
        )
        plt.polar(
            [np.arctan(gmeq.tanbeta_crit)] * 2,
            [scale_fn(r_min_), scale_fn(r_max_)],
            "--",
            color="DarkBlue" if eta_ > 1 else "b",
            lw=1,
            label=r"$\beta_{\mathrm{c}}$",
        )
        plt.polar(
            np.arcsin(self.p_infc_array[:, 0] /
                      norm(self.p_infc_array, axis=1)),
            scale_fn(norm(self.p_infc_array, axis=1)),
            "DarkBlue" if eta_ > 1 else "b",
            label=r"$F^*\!\!=1$,  $\beta<\beta_\mathrm{c}$",
        )

        plt.polar(
            (np.arcsin(self.p_supc_array[-1, 0] / norm(self.p_supc_array[-1]))
             + np.arcsin(self.p_infc_array[0, 0] / norm(self.p_infc_array[0])))
            / 2,
            (scale_fn(norm(self.p_infc_array[0])) +
             scale_fn(norm(self.p_supc_array[-1]))) / 2,
            "o",
            color="DarkBlue" if eta_ > 1 else "b",
        )

        axes: Axes = plt.gca()
        axes.set_theta_zero_location("S")
        horiz_label = r"$\log_{10}{p}$  or  $\log_{10}{v}$"
        vert_label = r"$\log_{10}{v}$  or  $\log_{10}{p}$"

        xtick_labels_base = [r"$\beta=0^{\!\circ}$", r"$\beta=30^{\!\circ}$"]
        theta_list: List[float]
        if eta_ > 1:
            theta_max_ = 20
            axes.set_thetamax(90 + theta_max_)
            axes.text(
                np.deg2rad(85 + theta_max_),
                0.5,
                vert_label,
                rotation=theta_max_,
                ha="center",
                va="bottom",
                fontsize=15,
            )
            axes.text(
                np.deg2rad(-8),
                1.2,
                horiz_label,
                rotation=90,
                ha="right",
                va="bottom",
                fontsize=15,
            )
            theta_list = [0, 1 / 6, 2 / 6, 3 / 6, np.deg2rad(110) / np.pi]
            xtick_labels = xtick_labels_base + [
                r"$\beta=60^{\!\circ}$",
                r"$\alpha=0^{\!\circ}$",
                r"$\alpha=20^{\!\circ}$",
            ]
            eta_xy_label = (1.15, 0.9)
            legend_xy = (1.0, 0.0)
            plt.text(
                *[(np.pi / 2) * 1.07, 0.4],
                "convex",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=8,
                fontsize=15,
                color="DarkRed",
            )
            plt.text(
                *[(np.pi / 2) * 1.17, 0.28],
                "concave",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=13,
                fontsize=11,
                color="r",
            )
            plt.text(
                *[(np.pi / 3) * 0.925, 0.5],
                "concave",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=-35,
                fontsize=15,
                color="b",
            )
            plt.text(
                *[(np.pi / 6) * 0.7, 0.85],
                "convex",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=68,
                fontsize=15,
                color="DarkBlue",
            )
        else:
            theta_max_ = 0
            axes.set_thetamax(90 + theta_max_)
            axes.text(
                np.deg2rad(92 + theta_max_),
                axes.get_rmax() / 5,
                vert_label,
                rotation=theta_max_,
                ha="right",
                va="bottom",
                fontsize=15,
            )
            axes.text(
                np.deg2rad(-8),
                axes.get_rmax() / 5,
                horiz_label,
                rotation=90,
                ha="right",
                va="bottom",
                fontsize=15,
            )
            theta_list = [0, 1 / 6, 2 / 6, 3 / 6]
            xtick_labels = xtick_labels_base + [
                r"$\beta=60^{\!\circ}\!\!,\, \alpha=-30^{\!\circ}$",
                r"$\beta=90^{\!\circ}\!\!,\, \alpha=0^{\!\circ}$",
            ]
            eta_xy_label = (1.2, 0.75)
            legend_xy = (0.9, 0.0)
            plt.text(
                *[(np.pi / 2) * 0.94, 0.4],
                "concave",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=11,
                fontsize=15,
                color="r",
            )
            plt.text(
                *[(np.pi / 2) * 0.9, -0.07],
                "convex",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=72,
                fontsize=13,
                color="DarkRed",
            )
            plt.text(
                *[(np.pi / 4) * 1.2, 0.12],
                "convex",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=60,
                fontsize=15,
                color="DarkBlue",
            )
            plt.text(
                *[(np.pi / 6) * 0.5, 0.4],
                "concave",
                horizontalalignment="center",
                verticalalignment="center",
                rotation=50,
                fontsize=15,
                color="b",
            )
            plt.polar(
                alpha_fn(
                    np.arcsin(self.v_supc_array[:, 0] /
                              norm(self.v_supc_array, axis=1))),
                v_scale_fn(norm(self.v_supc_array, axis=1)),
                "DarkRed",
            )

        plt.polar(
            alpha_fn((np.arcsin(self.v_supc_array[-1, 0] / norm(
                self.v_supc_array[-1])) + np.arcsin(
                    self.v_infc_array[0, 0] / norm(self.v_infc_array[0]))) /
                     2),
            (v_scale_fn(norm(self.v_infc_array[0])) +
             v_scale_fn(norm(self.v_supc_array[-1]))) / 2,
            "o",
            color="DarkRed" if eta_ > 1 else "r",
        )

        xtick_posns = [np.pi * theta_ for theta_ in theta_list]
        plt.xticks(xtick_posns, xtick_labels, ha="left", fontsize=15)

        plt.text(
            *eta_xy_label,
            rf"$\eta={gmeq.eta_}$",
            transform=axes.transAxes,
            horizontalalignment="center",
            verticalalignment="center",
            fontsize=18,
            color="k",
        )
        plt.legend(loc=legend_xy)

        axes.tick_params(axis="x",
                         pad=0,
                         left=True,
                         length=5,
                         width=1,
                         direction="out")

        axes.set_aspect(1)
        axes.set_rmax(scale_fn(r_max_))
        axes.set_rmin(scale_fn(r_min_))
        axes.set_thetamin(0)
        plt.grid(False, ls=":")
Example #27
0
def test_expand():
    assert expand_func(besselj(S.Half, z).rewrite(jn)) == \
        sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
    assert expand_func(bessely(S.Half, z).rewrite(yn)) == \
        -sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z))

    # XXX: teach sin/cos to work around arguments like
    # x*exp_polar(I*pi*n/2).  Then change besselsimp -> expand_func
    assert besselsimp(besselj(S.Half, z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
    assert besselsimp(besselj(Rational(-1, 2), z)) == sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z))
    assert besselsimp(besselj(Rational(5, 2), z)) == \
        -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2))
    assert besselsimp(besselj(Rational(-5, 2), z)) == \
        -sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2))

    assert besselsimp(bessely(S.Half, z)) == \
        -(sqrt(2)*cos(z))/(sqrt(pi)*sqrt(z))
    assert besselsimp(bessely(Rational(-1, 2), z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
    assert besselsimp(bessely(Rational(5, 2), z)) == \
        sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2))
    assert besselsimp(bessely(Rational(-5, 2), z)) == \
        -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2))

    assert besselsimp(besseli(S.Half, z)) == sqrt(2)*sinh(z)/(sqrt(pi)*sqrt(z))
    assert besselsimp(besseli(Rational(-1, 2), z)) == \
        sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
    assert besselsimp(besseli(Rational(5, 2), z)) == \
        sqrt(2)*(z**2*sinh(z) - 3*z*cosh(z) + 3*sinh(z))/(sqrt(pi)*z**Rational(5, 2))
    assert besselsimp(besseli(Rational(-5, 2), z)) == \
        sqrt(2)*(z**2*cosh(z) - 3*z*sinh(z) + 3*cosh(z))/(sqrt(pi)*z**Rational(5, 2))

    assert besselsimp(besselk(S.Half, z)) == \
        besselsimp(besselk(Rational(-1, 2), z)) == sqrt(pi)*exp(-z)/(sqrt(2)*sqrt(z))
    assert besselsimp(besselk(Rational(5, 2), z)) == \
        besselsimp(besselk(Rational(-5, 2), z)) == \
        sqrt(2)*sqrt(pi)*(z**2 + 3*z + 3)*exp(-z)/(2*z**Rational(5, 2))

    n = Symbol('n', integer=True, positive=True)

    assert expand_func(besseli(n + 2, z)) == \
        besseli(n, z) + (-2*n - 2)*(-2*n*besseli(n, z)/z + besseli(n - 1, z))/z
    assert expand_func(besselj(n + 2, z)) == \
        -besselj(n, z) + (2*n + 2)*(2*n*besselj(n, z)/z - besselj(n - 1, z))/z
    assert expand_func(besselk(n + 2, z)) == \
        besselk(n, z) + (2*n + 2)*(2*n*besselk(n, z)/z + besselk(n - 1, z))/z
    assert expand_func(bessely(n + 2, z)) == \
        -bessely(n, z) + (2*n + 2)*(2*n*bessely(n, z)/z - bessely(n - 1, z))/z

    assert expand_func(besseli(n + S.Half, z).rewrite(jn)) == \
        (sqrt(2)*sqrt(z)*exp(-I*pi*(n + S.Half)/2) *
         exp_polar(I*pi/4)*jn(n, z*exp_polar(I*pi/2))/sqrt(pi))
    assert expand_func(besselj(n + S.Half, z).rewrite(jn)) == \
        sqrt(2)*sqrt(z)*jn(n, z)/sqrt(pi)

    r = Symbol('r', real=True)
    p = Symbol('p', positive=True)
    i = Symbol('i', integer=True)

    for besselx in [besselj, bessely, besseli, besselk]:
        assert besselx(i, p).is_extended_real is True
        assert besselx(i, x).is_extended_real is None
        assert besselx(x, z).is_extended_real is None

    for besselx in [besselj, besseli]:
        assert besselx(i, r).is_extended_real is True
    for besselx in [bessely, besselk]:
        assert besselx(i, r).is_extended_real is None

    for besselx in [besselj, bessely, besseli, besselk]:
        assert expand_func(besselx(oo, x)) == besselx(oo, x, evaluate=False)
        assert expand_func(besselx(-oo, x)) == besselx(-oo, x, evaluate=False)
Example #28
0
 def _eval_rewrite_as_plusminus(self, *args):
     a = args[0]
     return JzOp(a)**2 +\
         Rational(1,2)*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
Example #29
0
    def particles(self, model):
        totalGroup = list(model.gaugeGroups)
        totalGroup = r' $\times$ '.join(totalGroup)

        # Fermions
        fermions = []

        for name, f in model.Fermions.items():
            if f.conj:
                continue
            gen = str(f.gen) if type(f.gen) == int else '$'+self.totex(f.gen)+'$'

            rep = [0]*len(model.gaugeGroups)
            for g, qnb in f.Qnb.items():
                gPos = list(model.gaugeGroups).index(g)

                if model.gaugeGroups[g].abelian:
                    repName = ('+' if qnb > 0 else '') + self.totex(Rational(qnb))
                else:
                    repName = model.gaugeGroups[g].repName(qnb)

                    # Fill Dynkin dic
                    for r,v in model.gaugeGroups[g].repDic.items():
                        self.dynkin[str(list(r))] = v[4]
                        self.dynkin[str(tuple(r))] = v[4]

                rep[gPos] = '$' + repName + '$'


            repStr = '('+', '.join(rep)+')' if len(rep) > 1 else rep[0]
            fermions.append(('$'+self.totex(Symbol(name))+'$', gen, repStr))

        self.string += ('\n' + r"""
\subsection{Fermions}
""")
        if fermions != []:
            self.string += (r"""
\begin{table}[h]
\renewcommand{\arraystretch}{1.15}
\centering
\begin{tabular}{c@{\hskip .66cm}c@{\hskip .66cm}c}
\hline
Name & Generations & """ + totalGroup + r"""\\ \hline \\ [-2ex]
""" +
" \\\\[.2cm]\n".join([r' & '.join(f) for f in fermions]) +
r""" \\[.1cm] \hline
\end{tabular}
\end{table}""")
        else:
            self.string += "\n\\emph{None.}\n"

        # Scalars
        scalars = []

        for name, s in model.Particles.items():
            if name in model.Fermions or s.conj:
                continue
            gen = str(s.gen) if type(s.gen) == int else '$'+self.totex(s.gen)+'$'

            rep = [0]*len(model.gaugeGroups)
            for g, qnb in s.Qnb.items():
                gPos = list(model.gaugeGroups).index(g)

                if model.gaugeGroups[g].abelian:
                    repName = ('+' if qnb > 0 else '') + self.totex(Rational(qnb))
                else:
                    repName = model.gaugeGroups[g].repName(qnb)
                rep[gPos] = '$' + repName + '$'

            # Norm*(re + im) formatting
            if s.cplx:
                if isinstance(s.norm, Mul) and len(s.norm.args) == 2 and s.norm.args[1]**(-2) == s.norm.args[0]:
                    expr = '\\frac{1}{'+self.totex(s.norm.args[1])+'}'
                elif s.norm != 1:
                    expr = self.totex(s.norm)
                else:
                    expr = ''

                real = ' + i\\, '.join([self.totex(r._name) for r in s.realFields])
                if s.norm != 1:
                    real = ' \\left(' + real + '\\right)'

                expr = '$' + expr + real + '$'
            else:
                expr = '/'
            repStr = '('+', '.join(rep)+')' if len(rep) > 1 else rep[0]
            scalars.append(('$'+self.totex(Symbol(name))+'$', str(s.cplx), expr, gen, repStr))


        self.string += ('\n' + r"""
\subsection{Scalars}
""")
        if scalars != []:
            self.string += (r"""
\begin{table}[h]
\renewcommand{\arraystretch}{1.15}
\centering
\begin{tabular}{c@{\hskip .66cm}c@{\hskip .66cm}ccc}
\hline
Name & Complex & Expression & Generations & """ + totalGroup + r"""\\ \hline \\ [-2ex]
""" +
" \\\\[.2cm]\n".join([r' & '.join(s) for s in scalars]) +
r""" \\[.1cm] \hline
\end{tabular}
\end{table}""")
        else:
            self.string += "\n\\emph{None.}\n"
Example #30
0
def test_simplify_relational():
    assert simplify(x*(y + 1) - x*y - x + 1 < x) == (x > 1)
    assert simplify(x*(y + 1) - x*y - x - 1 < x) == (x > -1)
    assert simplify(x < x*(y + 1) - x*y - x + 1) == (x < 1)
    r = S.One < x
    # canonical operations are not the same as simplification,
    # so if there is no simplification, canonicalization will
    # be done unless the measure forbids it
    assert simplify(r) == r.canonical
    assert simplify(r, ratio=0) != r.canonical
    # this is not a random test; in _eval_simplify
    # this will simplify to S.false and that is the
    # reason for the 'if r.is_Relational' in Relational's
    # _eval_simplify routine
    assert simplify(-(2**(pi*Rational(3, 2)) + 6**pi)**(1/pi) +
                    2*(2**(pi/2) + 3**pi)**(1/pi) < 0) is S.false
    # canonical at least
    assert Eq(y, x).simplify() == Eq(x, y)
    assert Eq(x - 1, 0).simplify() == Eq(x, 1)
    assert Eq(x - 1, x).simplify() == S.false
    assert Eq(2*x - 1, x).simplify() == Eq(x, 1)
    assert Eq(2*x, 4).simplify() == Eq(x, 2)
    z = cos(1)**2 + sin(1)**2 - 1  # z.is_zero is None
    assert Eq(z*x, 0).simplify() == S.true

    assert Ne(y, x).simplify() == Ne(x, y)
    assert Ne(x - 1, 0).simplify() == Ne(x, 1)
    assert Ne(x - 1, x).simplify() == S.true
    assert Ne(2*x - 1, x).simplify() == Ne(x, 1)
    assert Ne(2*x, 4).simplify() == Ne(x, 2)
    assert Ne(z*x, 0).simplify() == S.false

    # No real-valued assumptions
    assert Ge(y, x).simplify() == Le(x, y)
    assert Ge(x - 1, 0).simplify() == Ge(x, 1)
    assert Ge(x - 1, x).simplify() == S.false
    assert Ge(2*x - 1, x).simplify() == Ge(x, 1)
    assert Ge(2*x, 4).simplify() == Ge(x, 2)
    assert Ge(z*x, 0).simplify() == S.true
    assert Ge(x, -2).simplify() == Ge(x, -2)
    assert Ge(-x, -2).simplify() == Le(x, 2)
    assert Ge(x, 2).simplify() == Ge(x, 2)
    assert Ge(-x, 2).simplify() == Le(x, -2)

    assert Le(y, x).simplify() == Ge(x, y)
    assert Le(x - 1, 0).simplify() == Le(x, 1)
    assert Le(x - 1, x).simplify() == S.true
    assert Le(2*x - 1, x).simplify() == Le(x, 1)
    assert Le(2*x, 4).simplify() == Le(x, 2)
    assert Le(z*x, 0).simplify() == S.true
    assert Le(x, -2).simplify() == Le(x, -2)
    assert Le(-x, -2).simplify() == Ge(x, 2)
    assert Le(x, 2).simplify() == Le(x, 2)
    assert Le(-x, 2).simplify() == Ge(x, -2)

    assert Gt(y, x).simplify() == Lt(x, y)
    assert Gt(x - 1, 0).simplify() == Gt(x, 1)
    assert Gt(x - 1, x).simplify() == S.false
    assert Gt(2*x - 1, x).simplify() == Gt(x, 1)
    assert Gt(2*x, 4).simplify() == Gt(x, 2)
    assert Gt(z*x, 0).simplify() == S.false
    assert Gt(x, -2).simplify() == Gt(x, -2)
    assert Gt(-x, -2).simplify() == Lt(x, 2)
    assert Gt(x, 2).simplify() == Gt(x, 2)
    assert Gt(-x, 2).simplify() == Lt(x, -2)

    assert Lt(y, x).simplify() == Gt(x, y)
    assert Lt(x - 1, 0).simplify() == Lt(x, 1)
    assert Lt(x - 1, x).simplify() == S.true
    assert Lt(2*x - 1, x).simplify() == Lt(x, 1)
    assert Lt(2*x, 4).simplify() == Lt(x, 2)
    assert Lt(z*x, 0).simplify() == S.false
    assert Lt(x, -2).simplify() == Lt(x, -2)
    assert Lt(-x, -2).simplify() == Gt(x, 2)
    assert Lt(x, 2).simplify() == Lt(x, 2)
    assert Lt(-x, 2).simplify() == Gt(x, -2)
Example #31
0
def test_polynomial_relation_simplification():
    assert Ge(3*x*(x + 1) + 4, 3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))]
    assert Le(-(3*x*(x + 1) + 4), -3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))]
    assert ((x**2+3)*(x**2-1)+3*x >= 2*x**2).simplify() in [(x**4 + 3*x >= 3), (-x**4 - 3*x <= -3)]
Example #32
0
def test_point3D():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    x3 = Symbol('x3', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    y3 = Symbol('y3', real=True)
    half = Rational(1, 2)
    p1 = Point3D(x1, x2, x3)
    p2 = Point3D(y1, y2, y3)
    p3 = Point3D(0, 0, 0)
    p4 = Point3D(1, 1, 1)
    p5 = Point3D(0, 1, 2)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
    assert p4*5 == Point3D(5, 5, 5)
    assert -p2 == Point3D(-y1, -y2, -y3)

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
    assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
                                         half + half*x3)
    assert Point3D.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point3D.distance(p3, p4) == sqrt(3)
    assert Point3D.distance(p1, p1) == 0
    assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)

    p1_1 = Point3D(x1, x1, x1)
    p1_2 = Point3D(y2, y2, y2)
    p1_3 = Point3D(x1 + 1, x1, x1)
    Point3D.are_collinear(p3)
    assert Point3D.are_collinear(p3, p4)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
    assert Point3D.are_collinear(p3, p3, p4, p5) is False

    assert p3.intersection(Point3D(0, 0, 0)) == [p3]
    assert p3.intersection(p4) == []


    assert p4 * 5 == Point3D(5, 5, 5)
    assert p4 / 5 == Point3D(0.2, 0.2, 0.2)

    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)

    # Point differences should be simplified
    assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
        Point3D(0, -1, 1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point3D(1, 1, 1)
    assert p.scale(2, 3) == Point3D(2, 3, 1)
    assert p.translate(1, 2) == Point3D(2, 3, 1)
    assert p.translate(1) == Point3D(2, 1, 1)
    assert p.translate(z=1) == Point3D(1, 1, 2)
    assert p.translate(*p.args) == Point3D(2, 2, 2)

    # Test __new__
    assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float


    # Test length property returns correctly
    assert p.length == 0
    assert p1_1.length == 0
    assert p1_2.length == 0

    # Test are_colinear type error
    raises(TypeError, lambda: Point3D.are_collinear(p, x))

    # Test are_coplanar
    assert Point.are_coplanar()
    assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0))
    assert Point.are_coplanar((1, 2, 0), (1, 2, 3))
    with warnings.catch_warnings(record=True) as w:
        raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3)))
    assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3))
    assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False
    planar2 = Point3D(1, -1, 1)
    planar3 = Point3D(-1, 1, 1)
    assert Point3D.are_coplanar(p, planar2, planar3) == True
    assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
    assert Point.are_coplanar(p, planar2)
    planar2 = Point3D(1, 1, 2)
    planar3 = Point3D(1, 1, 3)
    assert Point3D.are_coplanar(p, planar2, planar3)  # line, not plane
    plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2))
    assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)])

    # all 2D points are coplanar
    assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True

    # Test Intersection
    assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]

    # Test Scale
    assert planar2.scale(1, 1, 1) == planar2
    assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
    assert planar2.scale(1, 1, 1, p3) == planar2

    # Test Transform
    identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
    assert p.transform(identity) == p
    trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
    assert p.transform(trans) == Point3D(2, 2, 2)
    raises(ValueError, lambda: p.transform(p))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))

    # Test Equals
    assert p.equals(x1) == False

    # Test __sub__
    p_4d = Point(0, 0, 0, 1)
    with warnings.catch_warnings(record=True) as w:
        assert p - p_4d == Point(1, 1, 1, -1)
        assert len(w) == 1
    p_4d3d = Point(0, 0, 1, 0)
    with warnings.catch_warnings(record=True) as w:
        assert p - p_4d3d == Point(1, 1, 0, 0)
        assert len(w) == 1
Example #33
0
def test_ceiling():

    assert ceiling(nan) is nan

    assert ceiling(oo) is oo
    assert ceiling(-oo) is -oo
    assert ceiling(zoo) is zoo

    assert ceiling(0) == 0

    assert ceiling(1) == 1
    assert ceiling(-1) == -1

    assert ceiling(E) == 3
    assert ceiling(-E) == -2

    assert ceiling(2 * E) == 6
    assert ceiling(-2 * E) == -5

    assert ceiling(pi) == 4
    assert ceiling(-pi) == -3

    assert ceiling(S.Half) == 1
    assert ceiling(Rational(-1, 2)) == 0

    assert ceiling(Rational(7, 3)) == 3
    assert ceiling(-Rational(7, 3)) == -2

    assert ceiling(Float(17.0)) == 17
    assert ceiling(-Float(17.0)) == -17

    assert ceiling(Float(7.69)) == 8
    assert ceiling(-Float(7.69)) == -7

    assert ceiling(I) == I
    assert ceiling(-I) == -I
    e = ceiling(i)
    assert e.func is ceiling and e.args[0] == i

    assert ceiling(oo * I) == oo * I
    assert ceiling(-oo * I) == -oo * I
    assert ceiling(exp(I * pi / 4) * oo) == exp(I * pi / 4) * oo

    assert ceiling(2 * I) == 2 * I
    assert ceiling(-2 * I) == -2 * I

    assert ceiling(I / 2) == I
    assert ceiling(-I / 2) == 0

    assert ceiling(E + 17) == 20
    assert ceiling(pi + 2) == 6

    assert ceiling(E + pi) == 6
    assert ceiling(I + pi) == I + 4

    assert ceiling(ceiling(pi)) == 4
    assert ceiling(ceiling(y)) == ceiling(y)
    assert ceiling(ceiling(x)) == ceiling(x)

    assert unchanged(ceiling, x)
    assert unchanged(ceiling, 2 * x)
    assert unchanged(ceiling, k * x)

    assert ceiling(k) == k
    assert ceiling(2 * k) == 2 * k
    assert ceiling(k * n) == k * n

    assert unchanged(ceiling, k / 2)

    assert unchanged(ceiling, x + y)

    assert ceiling(x + 3) == ceiling(x) + 3
    assert ceiling(x + k) == ceiling(x) + k

    assert ceiling(y + 3) == ceiling(y) + 3
    assert ceiling(y + k) == ceiling(y) + k

    assert ceiling(3 + pi + y * I) == 7 + ceiling(y) * I

    assert ceiling(k + n) == k + n

    assert unchanged(ceiling, x * I)
    assert ceiling(k * I) == k * I

    assert ceiling(Rational(23, 10) - E * I) == 3 - 2 * I

    assert ceiling(sin(1)) == 1
    assert ceiling(sin(-1)) == 0

    assert ceiling(exp(2)) == 8

    assert ceiling(-log(8) / log(2)) != -2
    assert int(ceiling(-log(8) / log(2)).evalf(chop=True)) == -3

    assert ceiling(factorial(50)/exp(1)) == \
        11188719610782480504630258070757734324011354208865721592720336801

    assert (ceiling(y) >= y) == True
    assert (ceiling(y) > y) == False
    assert (ceiling(y) < y) == False
    assert (ceiling(y) <= y) == False
    assert (ceiling(x) >= x).is_Relational  # x could be non-real
    assert (ceiling(x) < x).is_Relational
    assert (ceiling(x) >= y).is_Relational  # arg is not same as rhs
    assert (ceiling(x) < y).is_Relational
    assert (ceiling(y) >= -oo) == True
    assert (ceiling(y) > -oo) == True
    assert (ceiling(y) <= oo) == True
    assert (ceiling(y) < oo) == True

    assert ceiling(y).rewrite(floor) == -floor(-y)
    assert ceiling(y).rewrite(frac) == y + frac(-y)
    assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi)
    assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E)
    assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi)
    assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E)

    assert Eq(ceiling(y), y + frac(-y))
    assert Eq(ceiling(y), -floor(-y))

    neg = Symbol('neg', negative=True)
    nn = Symbol('nn', nonnegative=True)
    pos = Symbol('pos', positive=True)
    np = Symbol('np', nonpositive=True)

    assert (ceiling(neg) <= 0) == True
    assert (ceiling(neg) < 0) == (neg <= -1)
    assert (ceiling(neg) > 0) == False
    assert (ceiling(neg) >= 0) == (neg > -1)
    assert (ceiling(neg) > -3) == (neg > -3)
    assert (ceiling(neg) <= 10) == (neg <= 10)

    assert (ceiling(nn) < 0) == False
    assert (ceiling(nn) >= 0) == True

    assert (ceiling(pos) < 0) == False
    assert (ceiling(pos) <= 0) == False
    assert (ceiling(pos) > 0) == True
    assert (ceiling(pos) >= 0) == True
    assert (ceiling(pos) >= 1) == True
    assert (ceiling(pos) > 5) == (pos > 5)

    assert (ceiling(np) <= 0) == True
    assert (ceiling(np) > 0) == False

    assert ceiling(neg).is_positive == False
    assert ceiling(neg).is_nonpositive == True
    assert ceiling(nn).is_positive is None
    assert ceiling(nn).is_nonpositive is None
    assert ceiling(pos).is_positive == True
    assert ceiling(pos).is_nonpositive == False
    assert ceiling(np).is_positive == False
    assert ceiling(np).is_nonpositive == True

    assert (ceiling(7, evaluate=False) >= 7) == True
    assert (ceiling(7, evaluate=False) > 7) == False
    assert (ceiling(7, evaluate=False) <= 7) == True
    assert (ceiling(7, evaluate=False) < 7) == False

    assert (ceiling(7, evaluate=False) >= 6) == True
    assert (ceiling(7, evaluate=False) > 6) == True
    assert (ceiling(7, evaluate=False) <= 6) == False
    assert (ceiling(7, evaluate=False) < 6) == False

    assert (ceiling(7, evaluate=False) >= 8) == False
    assert (ceiling(7, evaluate=False) > 8) == False
    assert (ceiling(7, evaluate=False) <= 8) == True
    assert (ceiling(7, evaluate=False) < 8) == True

    assert (ceiling(x) <= 5.5) == Le(ceiling(x), 5.5, evaluate=False)
    assert (ceiling(x) >= -3.2) == Ge(ceiling(x), -3.2, evaluate=False)
    assert (ceiling(x) < 2.9) == Lt(ceiling(x), 2.9, evaluate=False)
    assert (ceiling(x) > -1.7) == Gt(ceiling(x), -1.7, evaluate=False)

    assert (ceiling(y) <= 5.5) == (y <= 5)
    assert (ceiling(y) >= -3.2) == (y > -4)
    assert (ceiling(y) < 2.9) == (y <= 2)
    assert (ceiling(y) > -1.7) == (y > -2)

    assert (ceiling(y) <= n) == (y <= n)
    assert (ceiling(y) >= n) == (y > n - 1)
    assert (ceiling(y) < n) == (y <= n - 1)
    assert (ceiling(y) > n) == (y > n)
Example #34
0
def test_point():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    half = Rational(1, 2)
    p1 = Point(x1, x2)
    p2 = Point(y1, y2)
    p3 = Point(0, 0)
    p4 = Point(1, 1)
    p5 = Point(0, 1)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point(y1 - x1, y2 - x2)
    assert p4*5 == Point(5, 5)
    assert -p2 == Point(-y1, -y2)
    raises(ValueError, lambda: Point(3, I))
    raises(ValueError, lambda: Point(2*I, I))
    raises(ValueError, lambda: Point(3 + I, I))

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point.midpoint(p3, p4) == Point(half, half)
    assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
    assert Point.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point.distance(p3, p4) == sqrt(2)
    assert Point.distance(p1, p1) == 0
    assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)

    assert Point.taxicab_distance(p4, p3) == 2

    p1_1 = Point(x1, x1)
    p1_2 = Point(y2, y2)
    p1_3 = Point(x1 + 1, x1)
    assert Point.is_collinear(p3)
    assert Point.is_collinear(p3, p4)
    assert Point.is_collinear(p3, p4, p1_1, p1_2)
    assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
    assert Point.is_collinear(p3, p3, p4, p5) is False
    line = Line(Point(1,0), slope = 1)
    raises(TypeError, lambda: Point.is_collinear(line))
    raises(TypeError, lambda: p1_1.is_collinear(line))

    assert p3.intersection(Point(0, 0)) == [p3]
    assert p3.intersection(p4) == []

    assert p1.dot(p4) == x1 + x2
    assert p3.dot(p4) == 0
    assert p4.dot(p5) == 1

    x_pos = Symbol('x', real=True, positive=True)
    p2_1 = Point(x_pos, 0)
    p2_2 = Point(0, x_pos)
    p2_3 = Point(-x_pos, 0)
    p2_4 = Point(0, -x_pos)
    p2_5 = Point(x_pos, 5)
    assert Point.is_concyclic(p2_1)
    assert Point.is_concyclic(p2_1, p2_2)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_5) is False
    assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False

    assert p4.scale(2, 3) == Point(2, 3)
    assert p3.scale(2, 3) == p3

    assert p4.rotate(pi, Point(0.5, 0.5)) == p3
    assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
    assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)

    assert p4 * 5 == Point(5, 5)
    assert p4 / 5 == Point(0.2, 0.2)

    raises(ValueError, lambda: Point(0, 0) + 10)

    # Point differences should be simplified
    assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point(1, 0)
    assert p.rotate(pi/2) == Point(0, 1)
    assert p.rotate(pi/2, p) == p
    p = Point(1, 1)
    assert p.scale(2, 3) == Point(2, 3)
    assert p.translate(1, 2) == Point(2, 3)
    assert p.translate(1) == Point(2, 1)
    assert p.translate(y=1) == Point(1, 2)
    assert p.translate(*p.args) == Point(2, 2)

    # Check invalid input for transform
    raises(ValueError, lambda: p3.transform(p3))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
Example #35
0
def test_union():
    N = Normal('N', 3, 2)
    assert simplify(P(N**2 - N > 2)) == \
        -erf(sqrt(2))/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2)
    assert simplify(P(N**2 - 4 > 0)) == \
        -erf(5*sqrt(2)/4)/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2)
Example #36
0
def test_nested_floor_ceiling():
    assert floor(-floor(ceiling(x**3) / y)) == -floor(ceiling(x**3) / y)
    assert ceiling(-floor(ceiling(x**3) / y)) == -floor(ceiling(x**3) / y)
    assert floor(ceiling(-floor(x**Rational(7, 2) / y))) == -floor(
        x**Rational(7, 2) / y)
    assert -ceiling(-ceiling(floor(x) / y)) == ceiling(floor(x) / y)
Example #37
0
def test_Or():
    N = Normal('N', 0, 1)
    assert simplify(P(Or(N > 2, N < 1))) == \
        -erf(sqrt(2))/2 - erfc(sqrt(2)/2)/2 + Rational(3, 2)
    assert P(Or(N < 0, N < 1)) == P(N < 1)
    assert P(Or(N > 0, N < 0)) == 1
Example #38
0
def test_airyai():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airyai(z), airyai)

    assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3)))
    assert airyai(oo) == 0
    assert airyai(-oo) == 0

    assert diff(airyai(z), z) == airyaiprime(z)

    assert series(airyai(z), z, 0, 3) == (
        3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3))

    assert airyai(z).rewrite(hyper) == (
        -3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) +
         3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3))))

    assert isinstance(airyai(z).rewrite(besselj), airyai)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
                  besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
    assert airyai(z).rewrite(besseli) == (
        -z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) +
         (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3)
    assert airyai(p).rewrite(besseli) == (
        sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) -
                 besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3)

    assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == (
        -sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 +
         (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
Example #39
0
    def RGEs(self, model):
        Printer.RGE = True

        self.string += "\n\n\\section{Renormalization Group Equations}\n"

        translation = {'GaugeCouplings': 'Gauge couplings',
                       'Yukawas': 'Yukawa couplings',
                       'QuarticTerms': 'Quartic couplings',
                       'TrilinearTerms' : 'Trilinear couplings',
                       'ScalarMasses': 'Scalar mass couplings',
                       'FermionMasses': 'Fermion mass couplings',
                       'Vevs': 'Vacuum-expectation values'}

        self.string += '\\subsection{Convention}\n\\begin{equation*}\n'

        if self.betaFactor == 1:
            beta = r'\mu \frac{d X}{d \mu}'
        else:
            X = Symbol('X')
            if self.betaFactor == Rational(1,2):
                beta = r'\mu^2 \frac{d X}{d \mu^2}'
            elif isinstance(self.betaFactor, Mul) and Rational(1,2) in self.betaFactor.args:
                    self.betaFactor *= Rational(2)
                    beta = r'\mu^2 \frac{d}{d \mu^2}\left(' + latex(self.betaFactor*X) + r'\right)'
            else:
                beta = r'\mu \frac{d}{d \mu}\left(' + latex(self.betaFactor*X) + r'\right)'


        self.string += r'\beta\left(X\right) \equiv ' + beta

        if model.betaExponent(Symbol('n')) != 0:
            self.string += r'\equiv' + '+'.join([latex(sympify(f'1/(4*pi)**({model.betaExponent(n)})', evaluate=False))+'\\beta^{('+str(n)+')}(X)' for n in range(1, 1+max(model.nLoops))])
        else:
            self.string += r'\equiv' + '+'.join(['\\beta^{('+str(n)+')}(X)' for n in range(1, 1+max(model.nLoops))])

        self.string += '\n\\end{equation*}\n'

        if ( ('sub' in model.substitutions and model.substitutions['sub'] != {})
          or ('yukMat' in model.substitutions and model.substitutions['yukMat'] != {})
          or ('zero' in model.substitutions and model.substitutions['zero'] != {}) ):

            self.string += '\\subsection{Definitions and substitutions}\n'

            if 'zero' in model.substitutions and model.substitutions['zero'] != {}:
                nPerLine = 5
                i = 0
                n0 = len(model.substitutions['zero'])
                n = n0
                while n > 0:
                    if n > nPerLine:
                        group = list(model.substitutions['zero'].items())[i:i+nPerLine]
                        n -= nPerLine
                        i += nPerLine
                    else:
                        group = list(model.substitutions['zero'].items())[i:]
                        n = 0

                    self.string += '\\begin{equation*}\n'
                    self.string += ' \\quad,\\quad '.join([self.totex(v) + '=' + self.totex(0) for k,v in group]) + '\n'
                    self.string += '\\end{equation*}\n'


            if 'yukMat' in model.substitutions and model.substitutions['yukMat'] != {}:
                nPerLine = 3
                i = 0
                n0 = len(model.substitutions['yukMat'])
                n = n0
                while n > 0:
                    if n > nPerLine:
                        group = list(model.substitutions['yukMat'].items())[i:i+nPerLine]
                        n -= nPerLine
                        i += nPerLine
                    else:
                        group = list(model.substitutions['yukMat'].items())[i:]
                        n = 0

                    self.string += '\\begin{equation*}\n'
                    self.string += ' \\quad,\\quad '.join([self.totex(model.allCouplings[k][1]) + '=' + self.totex(v[1]) for k,v in group]) + '\n'
                    self.string += '\\end{equation*}\n'


            if 'sub' in model.substitutions and model.substitutions['sub'] != {}:
                nPerLine = 3
                i = 0
                n0 = len(model.substitutions['sub'])
                n = n0
                while n > 0:
                    if n > nPerLine:
                        group = list(model.substitutions['sub'].items())[i:i+nPerLine]
                        n -= nPerLine
                        i += nPerLine
                    else:
                        group = list(model.substitutions['sub'].items())[i:]
                        n = 0

                    self.string += '\\begin{equation*}\n'
                    self.string += ' \\quad,\\quad '.join([self.totex(v[0]) + '\equiv' + self.totex(v[1], baseMul=True) for k,v in group]) + '\n'
                    self.string += '\\end{equation*}\n'

        for cType, dic in model.couplingRGEs.items():
            if dic == {}:
                continue
            if 'Anomalous' in cType:
                continue

            self.string += "\n\n\\subsection{" + translation[cType] + "}\n{\\allowdisplaybreaks\n"

            if cType in model.NonZeroCouplingRGEs:
                self.string += r'\emph{\textbf{Warning:} The following couplings were set to 0 in the model file, but have a non-zero \mbox{$\beta$-function}.'
                self.string += '\n' + r'This may lead to an inconsistent RG flow, except if these couplings can be safely approximated to 0 at all considered energy scales : ' + '\n}\n'
                self.string += r'\begin{center}' + '\n'
                self.string += '$' + '$, $'.join([(str(c) if str(c) not in self.latex else self.latex[str(c)]) for c in model.NonZeroCouplingRGEs[cType][0]]) + '$ .\n'
                self.string += r'\end{center}' + '\n'

            if cType == 'Vevs':
                self.string += self.vevs(model)

            for c in dic[0]:
                for n in range(model.loopDic[cType]):
                    RGE = dic[n][c]
                    cSymb = model.allCouplings[c][1]

                    self.string += "\n\\begin{align*}\n\\begin{autobreak}\n"
                    if type(RGE) != list:
                        self.string += '\\beta^{('+str(n+1)+')}(' + self.totex(cSymb) + ') ='
                        self.string += self.totex(RGE, sort=True, cType=cType)
                    else:
                        self.string += '\\left.\\beta^{('+str(n+1)+')}(' + self.totex(cSymb) + ')\\right\\rvert_{i j} ='
                        totalRGE = RGE[0]
                        for k,v in RGE[1].items():
                            if not isMinus(v.args[0] if isinstance(v, Add) else v):
                                totalRGE += Delta(Symbol('i'), k[0], Symbol('j'), k[1])*v
                            else:
                                totalRGE -= Delta(Symbol('i'), k[0], Symbol('j'), k[1])*(-1*v)

                        self.string += self.totex(expand(totalRGE), sort=True, cType=cType)

                    self.string += "\n\\end{autobreak}\n\\end{align*}"

            if cType not in model.NonZeroCouplingRGEs:
                self.string += "\n}"
                continue

            dic = model.NonZeroCouplingRGEs[cType]

            for c in dic[0]:
                for n in range(model.loopDic[cType]):
                    RGE = dic[n][c]

                    self.string += "\n\\begin{align*}\n\\begin{autobreak}\n"
                    self.string += '\\beta^{('+str(n+1)+')}(' + self.latex[str(c)] + ') ='
                    self.string += self.totex(RGE, sort=True, cType=cType).replace('\\left(', '\\big(').replace('\\right)', '\\big)')

                    self.string += "\n\\end{autobreak}\n\\end{align*}"

            self.string += "\n}"
Example #40
0
def test_airybiprime():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airybiprime(z), airybiprime)

    assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3))
    assert airybiprime(oo) is oo
    assert airybiprime(-oo) == 0

    assert diff(airybiprime(z), z) == z*airybi(z)

    assert series(airybiprime(z), z, 0, 3) == (
        3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3))

    assert airybiprime(z).rewrite(hyper) == (
        3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) +
        3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3)))

    assert isinstance(airybiprime(z).rewrite(besselj), airybiprime)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
                  besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
    assert airybiprime(z).rewrite(besseli) == (
        sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) +
                 (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3)
    assert airybiprime(p).rewrite(besseli) == (
        sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3)

    assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == (
        sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 +
        (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
Example #41
0
def test_issue_13324():
    X = Uniform('X', 0, 1)
    assert E(X, X > S.Half) == Rational(3, 4)
    assert E(X, X > 0) == S.Half
Example #42
0
def test_point():
    p1 = Point(x1, x2)
    p2 = Point(y1, y2)
    p3 = Point(0, 0)
    p4 = Point(1, 1)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point(y1 - x1, y2 - x2)
    assert p4 * 5 == Point(5, 5)
    assert -p2 == Point(-y1, -y2)

    assert Point.midpoint(p3, p4) == Point(half, half)
    assert Point.midpoint(p1, p4) == Point(half + half * x1, half + half * x2)
    assert Point.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point.distance(p3, p4) == sqrt(2)
    assert Point.distance(p1, p1) == 0
    assert Point.distance(p3, p2) == sqrt(p2.x ** 2 + p2.y ** 2)

    p1_1 = Point(x1, x1)
    p1_2 = Point(y2, y2)
    p1_3 = Point(x1 + 1, x1)
    assert Point.is_collinear(p3)
    assert Point.is_collinear(p3, p4)
    assert Point.is_collinear(p3, p4, p1_1, p1_2)
    assert Point.is_collinear(p3, p4, p1_1, p1_3) == False

    assert p3.intersection(Point(0, 0)) == [p3]
    assert p3.intersection(p4) == []

    x_pos = Symbol("x", real=True, positive=True)
    p2_1 = Point(x_pos, 0)
    p2_2 = Point(0, x_pos)
    p2_3 = Point(-x_pos, 0)
    p2_4 = Point(0, -x_pos)
    p2_5 = Point(x_pos, 5)
    assert Point.is_concyclic(p2_1)
    assert Point.is_concyclic(p2_1, p2_2)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_5) == False
    assert Point.is_concyclic(p4, p4 * 2, p4 * 3) == False

    assert p4.scale(2, 3) == Point(2, 3)
    assert p3.scale(2, 3) == p3

    assert p4.rotate(pi, Point(0.5, 0.5)) == p3
    assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
    assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)

    assert p4 * 5 == Point(5, 5)
    assert p4 / 5 == Point(0.2, 0.2)

    raises(ValueError, lambda: Point(0, 0) + 10)

    # Point differences should be simplified
    assert Point(x * (x - 1), y) - Point(x ** 2 - x, y + 1) == Point(0, -1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point(1, 0)
    assert p.rotate(pi / 2) == Point(0, 1)
    assert p.rotate(pi / 2, p) == p
    p = Point(1, 1)
    assert p.scale(2, 3) == Point(2, 3)
    assert p.translate(1, 2) == Point(2, 3)
    assert p.translate(1) == Point(2, 1)
    assert p.translate(y=1) == Point(1, 2)
    assert p.translate(*p.args) == Point(2, 2)
Example #43
0
def test_floor():

    assert floor(nan) is nan

    assert floor(oo) is oo
    assert floor(-oo) is -oo
    assert floor(zoo) is zoo

    assert floor(0) == 0

    assert floor(1) == 1
    assert floor(-1) == -1

    assert floor(E) == 2
    assert floor(-E) == -3

    assert floor(2 * E) == 5
    assert floor(-2 * E) == -6

    assert floor(pi) == 3
    assert floor(-pi) == -4

    assert floor(S.Half) == 0
    assert floor(Rational(-1, 2)) == -1

    assert floor(Rational(7, 3)) == 2
    assert floor(Rational(-7, 3)) == -3
    assert floor(-Rational(7, 3)) == -3

    assert floor(Float(17.0)) == 17
    assert floor(-Float(17.0)) == -17

    assert floor(Float(7.69)) == 7
    assert floor(-Float(7.69)) == -8

    assert floor(I) == I
    assert floor(-I) == -I
    e = floor(i)
    assert e.func is floor and e.args[0] == i

    assert floor(oo * I) == oo * I
    assert floor(-oo * I) == -oo * I
    assert floor(exp(I * pi / 4) * oo) == exp(I * pi / 4) * oo

    assert floor(2 * I) == 2 * I
    assert floor(-2 * I) == -2 * I

    assert floor(I / 2) == 0
    assert floor(-I / 2) == -I

    assert floor(E + 17) == 19
    assert floor(pi + 2) == 5

    assert floor(E + pi) == 5
    assert floor(I + pi) == 3 + I

    assert floor(floor(pi)) == 3
    assert floor(floor(y)) == floor(y)
    assert floor(floor(x)) == floor(x)

    assert unchanged(floor, x)
    assert unchanged(floor, 2 * x)
    assert unchanged(floor, k * x)

    assert floor(k) == k
    assert floor(2 * k) == 2 * k
    assert floor(k * n) == k * n

    assert unchanged(floor, k / 2)

    assert unchanged(floor, x + y)

    assert floor(x + 3) == floor(x) + 3
    assert floor(x + k) == floor(x) + k

    assert floor(y + 3) == floor(y) + 3
    assert floor(y + k) == floor(y) + k

    assert floor(3 + I * y + pi) == 6 + floor(y) * I

    assert floor(k + n) == k + n

    assert unchanged(floor, x * I)
    assert floor(k * I) == k * I

    assert floor(Rational(23, 10) - E * I) == 2 - 3 * I

    assert floor(sin(1)) == 0
    assert floor(sin(-1)) == -1

    assert floor(exp(2)) == 7

    assert floor(log(8) / log(2)) != 2
    assert int(floor(log(8) / log(2)).evalf(chop=True)) == 3

    assert floor(factorial(50)/exp(1)) == \
        11188719610782480504630258070757734324011354208865721592720336800

    assert (floor(y) < y) == False
    assert (floor(y) <= y) == True
    assert (floor(y) > y) == False
    assert (floor(y) >= y) == False
    assert (floor(x) <= x).is_Relational  # x could be non-real
    assert (floor(x) > x).is_Relational
    assert (floor(x) <= y).is_Relational  # arg is not same as rhs
    assert (floor(x) > y).is_Relational
    assert (floor(y) <= oo) == True
    assert (floor(y) < oo) == True
    assert (floor(y) >= -oo) == True
    assert (floor(y) > -oo) == True

    assert floor(y).rewrite(frac) == y - frac(y)
    assert floor(y).rewrite(ceiling) == -ceiling(-y)
    assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi)
    assert floor(y).rewrite(frac).subs(y, E) == floor(E)
    assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E)
    assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi)

    assert Eq(floor(y), y - frac(y))
    assert Eq(floor(y), -ceiling(-y))

    neg = Symbol('neg', negative=True)
    nn = Symbol('nn', nonnegative=True)
    pos = Symbol('pos', positive=True)
    np = Symbol('np', nonpositive=True)

    assert (floor(neg) < 0) == True
    assert (floor(neg) <= 0) == True
    assert (floor(neg) > 0) == False
    assert (floor(neg) >= 0) == False
    assert (floor(neg) <= -1) == True
    assert (floor(neg) >= -3) == (neg >= -3)
    assert (floor(neg) < 5) == (neg < 5)

    assert (floor(nn) < 0) == False
    assert (floor(nn) >= 0) == True

    assert (floor(pos) < 0) == False
    assert (floor(pos) <= 0) == (pos < 1)
    assert (floor(pos) > 0) == (pos >= 1)
    assert (floor(pos) >= 0) == True
    assert (floor(pos) >= 3) == (pos >= 3)

    assert (floor(np) <= 0) == True
    assert (floor(np) > 0) == False

    assert floor(neg).is_negative == True
    assert floor(neg).is_nonnegative == False
    assert floor(nn).is_negative == False
    assert floor(nn).is_nonnegative == True
    assert floor(pos).is_negative == False
    assert floor(pos).is_nonnegative == True
    assert floor(np).is_negative is None
    assert floor(np).is_nonnegative is None

    assert (floor(7, evaluate=False) >= 7) == True
    assert (floor(7, evaluate=False) > 7) == False
    assert (floor(7, evaluate=False) <= 7) == True
    assert (floor(7, evaluate=False) < 7) == False

    assert (floor(7, evaluate=False) >= 6) == True
    assert (floor(7, evaluate=False) > 6) == True
    assert (floor(7, evaluate=False) <= 6) == False
    assert (floor(7, evaluate=False) < 6) == False

    assert (floor(7, evaluate=False) >= 8) == False
    assert (floor(7, evaluate=False) > 8) == False
    assert (floor(7, evaluate=False) <= 8) == True
    assert (floor(7, evaluate=False) < 8) == True

    assert (floor(x) <= 5.5) == Le(floor(x), 5.5, evaluate=False)
    assert (floor(x) >= -3.2) == Ge(floor(x), -3.2, evaluate=False)
    assert (floor(x) < 2.9) == Lt(floor(x), 2.9, evaluate=False)
    assert (floor(x) > -1.7) == Gt(floor(x), -1.7, evaluate=False)

    assert (floor(y) <= 5.5) == (y < 6)
    assert (floor(y) >= -3.2) == (y >= -3)
    assert (floor(y) < 2.9) == (y < 3)
    assert (floor(y) > -1.7) == (y >= -1)

    assert (floor(y) <= n) == (y < n + 1)
    assert (floor(y) >= n) == (y >= n)
    assert (floor(y) < n) == (y < n)
    assert (floor(y) > n) == (y >= n + 1)