예제 #1
0
    def arbitrary_point(self, parameter='t'):
        """A parameterized point on the polygon.

        The parameter, varying from 0 to 1, assigns points to the position on
        the perimeter that is that fraction of the total perimeter. So the
        point evaluated at t=1/2 would return the point from the first vertex
        that is 1/2 way around the polygon.

        Parameters
        ----------
        parameter : str, optional
            Default value is 't'.

        Returns
        -------
        arbitrary_point : Point

        Raises
        ------
        ValueError
            When `parameter` already appears in the Polygon's definition.

        See Also
        --------
        Point

        Examples
        --------
        >>> from sympy import Polygon, S, Symbol
        >>> t = Symbol('t', real=True)
        >>> tri = Polygon((0, 0), (1, 0), (1, 1))
        >>> p = tri.arbitrary_point('t')
        >>> perimeter = tri.perimeter
        >>> s1, s2 = [s.length for s in tri.sides[:2]]
        >>> p.subs(t, (s1 + s2/2)/perimeter)
        Point(1, 1/2)

        """
        t = _symbol(parameter)
        if t.name in (f.name for f in self.free_symbols):
            raise ValueError(
                'Symbol %s already appears in object and cannot be used as a parameter.'
                % t.name)
        sides = []
        perimeter = self.perimeter
        perim_fraction_start = 0
        for s in self.sides:
            side_perim_fraction = s.length / perimeter
            perim_fraction_end = perim_fraction_start + side_perim_fraction
            pt = s.arbitrary_point(parameter).subs(
                t, (t - perim_fraction_start) / side_perim_fraction)
            sides.append(
                (pt, (perim_fraction_start <= t < perim_fraction_end)))
            perim_fraction_start = perim_fraction_end
        return Piecewise(*sides)
예제 #2
0
def real_root(arg, n=None):
    """Return the real nth-root of arg if possible. If n is omitted then
    all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this
    will only create a real root of a principle root -- the presence of
    other factors may cause the result to not be real.

    Examples
    ========

    >>> from sympy import root, real_root, Rational
    >>> from sympy.abc import x, n

    >>> real_root(-8, 3)
    -2
    >>> root(-8, 3)
    2*(-1)**(1/3)
    >>> real_root(_)
    -2

    If one creates a non-principle root and applies real_root, the
    result will not be real (so use with caution):

    >>> root(-8, 3, 2)
    -2*(-1)**(2/3)
    >>> real_root(_)
    -2*(-1)**(2/3)


    See Also
    ========

    sympy.polys.rootoftools.rootof
    sympy.core.power.integer_nthroot
    root, sqrt
    """
    from sympy import im, Piecewise
    if n is not None:
        try:
            n = as_int(n)
            arg = sympify(arg)
            if arg.is_positive or arg.is_negative:
                rv = root(arg, n)
            else:
                raise ValueError
        except ValueError:
            return root(arg, n) * Piecewise(
                (S.One, ~Equality(im(arg), 0)),
                (Pow(S.NegativeOne, S.One / n)**(2 * floor(n / 2)),
                 And(Equality(n % 2, 1), arg < 0)), (S.One, True))
    else:
        rv = sympify(arg)
    n1pow = Transform(
        lambda x: -(-x.base)**x.exp, lambda x: x.is_Pow and x.base.is_negative
        and x.exp.is_Rational and x.exp.p == 1 and x.exp.q % 2)
    return rv.xreplace(n1pow)
예제 #3
0
def test_diff_nth_derivative():
    f = Function("f")
    n = Symbol("n", integer=True)

    expr = diff(sin(x), (x, n))
    expr2 = diff(f(x), (x, 2))
    expr3 = diff(f(x), (x, n))

    assert expr.subs(sin(x), cos(-x)) == Derivative(cos(-x), (x, n))
    assert expr.subs(n, 1).doit() == cos(x)
    assert expr.subs(n, 2).doit() == -sin(x)

    assert expr2.subs(Derivative(f(x), x), y) == Derivative(y, x)
    # Currently not supported (cannot determine if `n > 1`):
    #assert expr3.subs(Derivative(f(x), x), y) == Derivative(y, (x, n-1))
    assert expr3 == Derivative(f(x), (x, n))

    assert diff(x, (x, n)) == Piecewise((x, Eq(n, 0)), (1, Eq(n, 1)),
                                        (0, True))
    assert diff(2 * x, (x, n)).dummy_eq(
        Sum(
            Piecewise(
                (2 * x * factorial(n) / (factorial(y) * factorial(-y + n)),
                 Eq(y, 0) & Eq(Max(0, -y + n), 0)),
                (2 * factorial(n) / (factorial(y) * factorial(-y + n)),
                 Eq(y, 0) & Eq(Max(0, -y + n), 1)), (0, True)), (y, 0, n)))
    # TODO: assert diff(x**2, (x, n)) == x**(2-n)*ff(2, n)
    exprm = x * sin(x)
    mul_diff = diff(exprm, (x, n))
    assert isinstance(mul_diff, Sum)
    for i in range(5):
        assert mul_diff.subs(n, i).doit() == exprm.diff((x, i)).expand()

    exprm2 = 2 * y * x * sin(x) * cos(x) * log(x) * exp(x)
    dex = exprm2.diff((x, n))
    assert isinstance(dex, Sum)
    for i in range(7):
        assert dex.subs(n, i).doit().expand() == \
        exprm2.diff((x, i)).expand()

    assert (cos(x) * sin(y)).diff([[x, y, z]]) == NDimArray(
        [-sin(x) * sin(y), cos(x) * cos(y), 0])
예제 #4
0
def test_issue_11865():
    if not matplotlib:
        skip("Matplotlib not the default backend")

    k = Symbol('k', integer=True)
    f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True))
    p = plot(f, show=False)
    # Random number of segments, probably more than 100, but we want to see
    # that there are segments generated, as opposed to when the bug was present
    # and that there are no exceptions.
    assert len(p[0].get_data()[0]) >= 30
예제 #5
0
def test_binomial_quantile():
    X = Binomial('X', 50, S.Half)
    assert quantile(X)(0.95) == S(31)
    assert median(X) == FiniteSet(25)

    X = Binomial('X', 5, S.Half)
    p = Symbol("p", positive=True)
    assert quantile(X)(p) == Piecewise((nan, p > S.One), (S.Zero, p <= Rational(1, 32)),\
        (S.One, p <= Rational(3, 16)), (S(2), p <= S.Half), (S(3), p <= Rational(13, 16)),\
        (S(4), p <= Rational(31, 32)), (S(5), p <= S.One))
    assert median(X) == FiniteSet(2, 3)
예제 #6
0
def test_numpy_piecewise_regression():
    """
    NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
    breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
    See gh-9747 and gh-9749 for details.
    """
    printer = NumPyPrinter()
    p = Piecewise((1, x < 0), (0, True))
    assert printer.doprint(p) == \
        'numpy.select([numpy.less(x, 0),True], [1,0], default=numpy.nan)'
    assert printer.module_imports == {'numpy': {'select', 'less', 'nan'}}
예제 #7
0
 def pdf(self, *syms):
     n, theta = self.n, self.theta
     condi = isinstance(self.n, Integer)
     if not (isinstance(syms[0], IndexedBase) or condi):
         raise ValueError("Please use IndexedBase object for syms as "
                          "the dimension is symbolic")
     term_1 = factorial(n) / rf(theta, n)
     if condi:
         term_2 = Mul.fromiter(theta**syms[j] /
                               ((j + 1)**syms[j] * factorial(syms[j]))
                               for j in range(n))
         cond = Eq(sum([(k + 1) * syms[k] for k in range(n)]), n)
         return Piecewise((term_1 * term_2, cond), (0, True))
     syms = syms[0]
     j, k = symbols('j, k', positive=True, integer=True)
     term_2 = Product(
         theta**syms[j] / ((j + 1)**syms[j] * factorial(syms[j])),
         (j, 0, n - 1))
     cond = Eq(Sum((k + 1) * syms[k], (k, 0, n - 1)), n)
     return Piecewise((term_1 * term_2, cond), (0, True))
예제 #8
0
def test_printmethod():
    # In each case, printmethod is called to test
    # its working

    obj = CustomPrintedObject()
    assert LambdaPrinter().doprint(obj) == 'lambda'
    assert TensorflowPrinter().doprint(obj) == 'tensorflow'
    assert NumExprPrinter().doprint(obj) == "evaluate('numexpr', truediv=True)"

    assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \
            "evaluate('where((x >= 0), y, z)', truediv=True)"
예제 #9
0
def _minmax_as_Piecewise(op, *args):
    # helper for Min/Max rewrite as Piecewise
    from sympy.functions.elementary.piecewise import Piecewise

    ec = []
    for i, a in enumerate(args):
        c = []
        for j in range(i + 1, len(args)):
            c.append(Relational(a, args[j], op))
        ec.append((a, And(*c)))
    return Piecewise(*ec)
예제 #10
0
def real_root(arg, n=None, evaluate=None):
    """Return the real nth-root of arg if possible. If n is omitted then
    all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this
    will only create a real root of a principal root -- the presence of
    other factors may cause the result to not be real.

    The parameter evaluate determines if the expression should be evaluated.
    If None, its value is taken from global_evaluate.

    Examples
    ========

    >>> from sympy import root, real_root, Rational
    >>> from sympy.abc import x, n

    >>> real_root(-8, 3)
    -2
    >>> root(-8, 3)
    2*(-1)**(1/3)
    >>> real_root(_)
    -2

    If one creates a non-principal root and applies real_root, the
    result will not be real (so use with caution):

    >>> root(-8, 3, 2)
    -2*(-1)**(2/3)
    >>> real_root(_)
    -2*(-1)**(2/3)


    See Also
    ========

    sympy.polys.rootoftools.rootof
    sympy.core.power.integer_nthroot
    root, sqrt
    """
    from sympy.functions.elementary.complexes import Abs, im, sign
    from sympy.functions.elementary.piecewise import Piecewise
    if n is not None:
        return Piecewise(
            (root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
            (Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),
            And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
            (root(arg, n, evaluate=evaluate), True))
    rv = sympify(arg)
    n1pow = Transform(lambda x: -(-x.base)**x.exp,
                      lambda x:
                      x.is_Pow and
                      x.base.is_negative and
                      x.exp.is_Rational and
                      x.exp.p == 1 and x.exp.q % 2)
    return rv.xreplace(n1pow)
예제 #11
0
def test_m_piecewise_():
    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x + 2, x > 1), (1, True),
                   evaluate=False)
    name_expr = ("pwtest", pw)
    result, = codegen(name_expr, "Octave", header=False, empty=False)
    source = result[1]
    expected = ("function out1 = pwtest(x)\n"
                "  out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n"
                "  (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n"
                "  (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n"
                "end\n")
    assert source == expected
예제 #12
0
    def compute_quantile(self, **kwargs):
        """ Compute the Quantile from the PDF.

        Returns a Lambda.
        """
        x = Dummy('x', integer=True)
        p = Dummy('p', real=True)
        left_bound = self.set.inf
        pdf = self.pdf(x)
        cdf = summation(pdf, (x, left_bound, x), **kwargs)
        set = ((x, p <= cdf), )
        return Lambda(p, Piecewise(*set))
예제 #13
0
    def compute_quantile(self, **kwargs):
        """ Compute the Quantile from the PDF.

        Returns a Lambda.
        """
        x, p = symbols('x, p', real=True, cls=Dummy)
        left_bound = self.set.start

        pdf = self.pdf(x)
        cdf = integrate(pdf, (x, left_bound, x), **kwargs)
        quantile = solveset(cdf - p, x, self.set)
        return Lambda(p, Piecewise((quantile, (p >= 0) & (p <= 1) ), (nan, True)))
예제 #14
0
def test_product_spaces():
    X1 = Geometric('X1', S.Half)
    X2 = Geometric('X2', Rational(1, 3))
    #assert str(P(X1 + X2 < 3, evaluate=False)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """\
    #    + """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, -oo, -1))"""
    n = Dummy('n')
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        assert P(X1 + X2 < 3, evaluate=False).rewrite(Sum).dummy_eq(
            Sum(Piecewise((2**(-n) / 4, n + 2 >= 1), (0, True)),
                (n, -oo, -1)) / 3)
    #assert str(P(X1 + X2 > 3)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """ +\
    #    """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, 1, oo))"""
    assert P(X1 + X2 > 3).dummy_eq(
        Sum(
            Piecewise((2**(X2 - n - 2) *
                       (Rational(2, 3))**(X2 - 1) / 6, -X2 + n + 3 >= 1),
                      (0, True)), (X2, 1, oo), (n, 1, oo)))
    #    assert str(P(Eq(X1 + X2, 3))) == """Sum(Piecewise((2**(X2 - 2)*(2/3)**(X2 - 1)/6, """ +\
    #        """X2 <= 2), (0, True)), (X2, 1, oo))"""
    assert P(Eq(X1 + X2, 3)) == Rational(1, 12)
예제 #15
0
def test_yule_simon():
    from sympy.core.singleton import S
    rho = S(3)
    x = YuleSimon('x', rho)
    assert simplify(E(x)) == rho / (rho - 1)
    assert simplify(variance(x)) == rho**2 / ((rho - 1)**2 * (rho - 2))
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        assert isinstance(E(x, evaluate=False), Expectation)
    # To test the cdf function
    assert cdf(x)(x) == Piecewise((-beta(floor(x), 4) * floor(x) + 1, x >= 1),
                                  (0, True))
예제 #16
0
def test_preorder_traversal():
    expr = z + w * (x + y)
    expected1 = [z + w * (x + y), z, w * (x + y), w, x + y, y, x]
    expected2 = [z + w * (x + y), z, w * (x + y), w, x + y, x, y]
    expected3 = [z + w * (x + y), w * (x + y), w, x + y, y, x, z]
    assert list(preorder_traversal(expr)) in [expected1, expected2, expected3]

    expr = Piecewise((x, x < 1), (x**2, True))
    assert list(preorder_traversal(expr)) == [
        Piecewise((x, x < 1), (x**2, True)),
        ExprCondPair(x, x < 1), x, x < 1, x, 1,
        ExprCondPair(x**2, True), x**2, x, 2, True
    ]
    assert list(postorder_traversal(Integral(x**2, (x, 0, 1)))) == [
        x, 2, x**2, x, 0, 1, (0, 1), (x, (0, 1)), ((x, (0, 1)), ),
        Integral(x**2, (x, 0, 1))
    ]
    assert list(postorder_traversal(
        ('abc',
         ('d',
          'ef')))) == ['abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))]
예제 #17
0
def test_postorder_traversal():
    expr = z + w * (x + y)
    expected1 = [z, w, y, x, x + y, w * (x + y), z + w * (x + y)]
    expected2 = [z, w, x, y, x + y, w * (x + y), z + w * (x + y)]
    expected3 = [w, y, x, x + y, w * (x + y), z, z + w * (x + y)]
    assert list(postorder_traversal(expr)) in [expected1, expected2, expected3]

    expr = Piecewise((x, x < 1), (x**2, True))
    assert list(postorder_traversal(expr)) == [
        x, x, 1, x < 1,
        ExprCondPair(x, x < 1), x, 2, x**2, True,
        ExprCondPair(x**2, True),
        Piecewise((x, x < 1), (x**2, True))
    ]
    assert list(preorder_traversal(Integral(x**2, (x, 0, 1)))) == [
        Integral(x**2, (x, 0, 1)), x**2, x, 2,
        Tuple(x, 0, 1), x, 0, 1
    ]
    assert list(preorder_traversal(
        ('abc', ('d', 'ef')))) == [('abc', ('d', 'ef')), 'abc', ('d', 'ef'),
                                   'd', 'ef']
예제 #18
0
def test_fcode_Piecewise():
    x = symbols('x')
    expr = Piecewise((x, x < 1), (x**2, True))
    # Check that inline conditional (merge) fails if standard isn't 95+
    raises(NotImplementedError, lambda: fcode(expr))
    code = fcode(expr, standard=95)
    expected = "      merge(x, x**2, x < 1)"
    assert code == expected
    assert fcode(Piecewise((x, x < 1), (x**2, True)),
                 assign_to="var") == ("      if (x < 1) then\n"
                                      "         var = x\n"
                                      "      else\n"
                                      "         var = x**2\n"
                                      "      end if")
    a = cos(x) / x
    b = sin(x) / x
    for i in range(10):
        a = diff(a, x)
        b = diff(b, x)
    expected = (
        "      if (x < 0) then\n"
        "         weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n"
        "     @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n"
        "     @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n"
        "     @ )/x**10 + 3628800*cos(x)/x**11\n"
        "      else\n"
        "         weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n"
        "     @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n"
        "     @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n"
        "     @ )/x**10 + 3628800*sin(x)/x**11\n"
        "      end if")
    code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name")
    assert code == expected
    code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)),
                 standard=95)
    expected = "      merge(x, merge(x**2, sin(x), x > 1), x < 1)"
    assert code == expected
    # Check that Piecewise without a True (default) condition error
    expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
    raises(ValueError, lambda: fcode(expr))
예제 #19
0
def test_heurisch_wrapper():
    f = 1 / (y + x)
    assert heurisch_wrapper(f, x) == log(x + y)
    f = 1 / (y - x)
    assert heurisch_wrapper(f, x) == -log(x - y)
    f = 1 / ((y - x) * (y + x))
    assert heurisch_wrapper(f, x) == Piecewise(
        (-log(x - y) / (2 * y) + log(x + y) / (2 * y), Ne(y, 0)),
        (1 / x, True))
    # issue 6926
    f = sqrt(x**2 / ((y - x) * (y + x)))
    assert heurisch_wrapper(f, x) == x*sqrt(-x**2/(x**2 - y**2)) \
    - y**2*sqrt(-x**2/(x**2 - y**2))/x
예제 #20
0
def test_messy():
    from sympy.functions.elementary.complexes import re
    from sympy.functions.elementary.hyperbolic import (acosh, acoth)
    from sympy.functions.elementary.piecewise import Piecewise
    from sympy.functions.elementary.trigonometric import (asin, atan)
    from sympy.functions.special.bessel import besselj
    from sympy.functions.special.error_functions import (Chi, E1, Shi, Si)
    from sympy.integrals.transforms import (fourier_transform,
                                            laplace_transform)
    assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi / 2) / s, 0, True)

    assert laplace_transform(Shi(x), x, s) == (acoth(s) / s, -oo, s**2 > 1)

    # where should the logs be simplified?
    assert laplace_transform(Chi(x), x,
                             s) == ((log(s**(-2)) - log(1 - 1 / s**2)) /
                                    (2 * s), -oo, s**2 > 1)

    # TODO maybe simplify the inequalities? when the simplification
    # allows for generators instead of symbols this will work
    assert laplace_transform(besselj(a, x), x, s)[1:] == \
        (0, (re(a) > -2) & (re(a) > -1))

    # NOTE s < 0 can be done, but argument reduction is not good enough yet
    ans = fourier_transform(besselj(1, x) / x, x, s, noconds=False)
    assert tuple([ans[0].factor(deep=True).expand(), ans[1]]) == \
        (Piecewise((0, (s > 1/(2*pi)) | (s < -1/(2*pi))),
                   (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0)
    # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons)
    #                       - folding could be better

    assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \
        log(1 + sqrt(2))
    assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \
        log(S.Half + sqrt(2)/2)

    assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \
        Piecewise((-acosh(1/x), abs(x**(-2)) > 1), (I*asin(1/x), True))
예제 #21
0
def test_issue_6746():
    y = Symbol('y')
    n = Symbol('n')
    assert manualintegrate(y**x, x) == Piecewise(
        (y**x/log(y), Ne(log(y), 0)), (x, True))
    assert manualintegrate(y**(n*x), x) == Piecewise(
        (Piecewise(
            (y**(n*x)/log(y), Ne(log(y), 0)),
            (n*x, True)
        )/n, Ne(n, 0)),
        (x, True))
    assert manualintegrate(exp(n*x), x) == Piecewise(
        (exp(n*x)/n, Ne(n, 0)), (x, True))

    y = Symbol('y', positive=True)
    assert manualintegrate((y + 1)**x, x) == (y + 1)**x/log(y + 1)
    y = Symbol('y', zero=True)
    assert manualintegrate((y + 1)**x, x) == x
    y = Symbol('y')
    n = Symbol('n', nonzero=True)
    assert manualintegrate(y**(n*x), x) == Piecewise(
        (y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True))/n
    y = Symbol('y', positive=True)
    assert manualintegrate((y + 1)**(n*x), x) == \
        (y + 1)**(n*x)/(n*log(y + 1))
    a = Symbol('a', negative=True)
    b = Symbol('b')
    assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b))
    b = Symbol('b', negative=True)
    assert manualintegrate(1/(a + b*x**2), x) == \
        atan(x/(sqrt(-a)*sqrt(-1/b)))/(b*sqrt(-a)*sqrt(-1/b))
    assert manualintegrate(1/((x**a + y**b + 4)*sqrt(a*x**2 + 1)), x) == \
        y**(-b)*Integral(x**(-a)/(y**(-b)*sqrt(a*x**2 + 1) +
        x**(-a)*sqrt(a*x**2 + 1) + 4*x**(-a)*y**(-b)*sqrt(a*x**2 + 1)), x)
    assert manualintegrate(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) == \
        Integral(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x)
    assert manualintegrate(1/(x - a**x + x*b**2), x) == \
        Integral(1/(-a**x + b**2*x + x), x)
예제 #22
0
    def compute_cdf(self, **kwargs):
        """ Compute the CDF from the PDF.

        Returns a Lambda.
        """
        x, z = symbols('x, z', real=True, cls=Dummy)
        left_bound = self.set.start

        # CDF is integral of PDF from left bound to z
        pdf = self.pdf(x)
        cdf = integrate(pdf.doit(), (x, left_bound, z), **kwargs)
        # CDF Ensure that CDF left of left_bound is zero
        cdf = Piecewise((cdf, z >= left_bound), (0, True))
        return Lambda(z, cdf)
예제 #23
0
def test_postorder_traversal():
    expr = z + w*(x + y)
    expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z]
    assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
    assert list(postorder_traversal(expr, keys=True)) == expected

    expr = Piecewise((x, x < 1), (x**2, True))
    expected = [
        x, 1, x, x < 1, ExprCondPair(x, x < 1),
        2, x, x**2, true,
        ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True))
    ]
    assert list(postorder_traversal(expr, keys=default_sort_key)) == expected
    assert list(postorder_traversal(
        [expr], keys=default_sort_key)) == expected + [[expr]]

    assert list(postorder_traversal(Integral(x**2, (x, 0, 1)),
        keys=default_sort_key)) == [
            2, x, x**2, 0, 1, x, Tuple(x, 0, 1),
            Integral(x**2, Tuple(x, 0, 1))
        ]
    assert list(postorder_traversal(('abc', ('d', 'ef')))) == [
        'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))]
예제 #24
0
    def compute_cdf(self, expr, **kwargs):
        if not self.domain.set.is_Interval:
            raise ValueError(
                "CDF not well defined on multivariate expressions")

        d = self.compute_density(expr, **kwargs)
        x, z = symbols('x, z', real=True, cls=Dummy)
        left_bound = self.domain.set.start

        # CDF is integral of PDF from left bound to z
        cdf = integrate(d(x), (x, left_bound, z), **kwargs)
        # CDF Ensure that CDF left of left_bound is zero
        cdf = Piecewise((cdf, z >= left_bound), (0, True))
        return Lambda(z, cdf)
예제 #25
0
def apply(x, w=None):
    n = x.shape[0]
    i = Symbol.i(integer=True)
    j = Symbol.j(integer=True)

    if w is None:
        w = Symbol.w(shape=(n, n, n), definition=LAMBDA[j:n](Swap(n, 0, j)))

    assert w.shape == (n, n, n)
    assert w[j].definition == Swap(n, 0, j)

    return Equality(
        LAMBDA[i:n](x[w[j][i] @ LAMBDA[i:n](i)]), LAMBDA[i:n](Piecewise(
            (x[0], Equality(i, j)), (x[j], Equality(i, 0)), (x[i], True))))
예제 #26
0
def apply(n, k, A=None):
    j = Symbol.j(domain=Interval(0, k, integer=True))
    if A is None:
        x = Symbol.x(shape=(oo, ), dtype=dtype.integer, finite=True)
        i = Symbol.i(integer=True)
        s1_quote = Symbol("s'_1",
                          definition=Stirling.conditionset(n, k + 1, x))
        x_quote = Symbol("x'",
                         definition=LAMBDA[i:k + 1](Piecewise(
                             ({n} | x[i], Equality(i, j)), (x[i], True))))
        A = Symbol.A(definition=LAMBDA[j](UNION[x[:k + 1]:s1_quote]
                                          ({x_quote.set_comprehension()})))

    return Equality(abs(UNION[j](A[j])), Sum[j](abs(A[j])))
예제 #27
0
def test_jl_piecewise_():
    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
    name_expr = ("pwtest", pw)
    result, = codegen(name_expr, "Julia", header=False, empty=False)
    source = result[1]
    expected = (
        "function pwtest(x)\n"
        "    out1 = ((x < -1) ? (0) :\n"
        "    (x <= 1) ? (x.^2) :\n"
        "    (x > 1) ? (2 - x) : (1))\n"
        "    return out1\n"
        "end\n"
    )
    assert source == expected
 def eval_zeta_function(self, f, limits):
     """
     Check whether the function matches with the zeta function.
     If it matches, then return a `Piecewise` expression because
     zeta function does not converge unless `s > 1` and `q > 0`
     """
     i, a, b = limits
     w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
     result = f.match((w * i + y) ** (-z))
     if result is not None and b == S.Infinity:
         coeff = 1 / result[w] ** result[z]
         s = result[z]
         q = result[y] / result[w] + a
         return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
예제 #29
0
파일: frv.py 프로젝트: vishalbelsare/sympy
 def compute_expectation(self, expr, rvs=None, **kwargs):
     rvs = rvs or self.values
     expr = rv_subs(expr, rvs)
     probs = [self.prob_of(elem) for elem in self.domain]
     if isinstance(expr, (Logic, Relational)):
         parse_domain = [tuple(elem)[0][1] for elem in self.domain]
         bools = [expr.xreplace(dict(elem)) for elem in self.domain]
     else:
         parse_domain = [expr.xreplace(dict(elem)) for elem in self.domain]
         bools = [True for elem in self.domain]
     return sum([
         Piecewise((prob * elem, blv), (S.Zero, True))
         for prob, elem, blv in zip(probs, parse_domain, bools)
     ])
예제 #30
0
def prove(Eq):    
    n = Symbol.n(integer=True, positive=True)
    Eq << apply(n)
    x = Eq[0].rhs.variable.base
    P = Eq[0].lhs
    P_quote = Eq[1].lhs
    
    i = Symbol.i(integer=True)
    
    x_quote = Symbol("x'", definition=LAMBDA[i:n + 1](Piecewise((n, Equality(i, n)), (x[i], True))))
    Eq.x_quote_definition = x_quote.this.definition
    
    Eq << Eq.x_quote_definition[:n]
    
    Eq.mapping = Eq[-1].this.rhs().function.simplify()
    
    Eq << Eq.x_quote_definition[i]
    
    Eq << Eq[-1].set.union_comprehension((i, 0, n - 1))
    
    Eq.x_quote_n_definition = Eq[-2].subs(i, n)
    
    Eq << sets.imply.conditionset.apply(P)
    
    Eq << Eq[-2].subs(Eq[-1])
    
    Eq.P2P_quote = ForAll[x[:n]:P](Contains(x_quote, P_quote), plausible=True)
    
    Eq << Eq.P2P_quote.definition.split()
    
    Eq << sets.imply.conditionset.apply(P_quote)
    
    Eq << Eq[-1].split()
    
    Eq << Eq[-2].reversed + Eq.x_quote_n_definition
    
    Eq.mapping_quote = ForAll[x[:n + 1]:P_quote](Equality(x_quote, x[:n + 1]), plausible=True)
    
    Eq << Eq.mapping_quote.this.function.bisect(Slice[-1:]).split()
    
    Eq << Eq[-1].subs(Eq.mapping)
    
    Eq << ForAll[x[:n + 1]:P_quote](Contains(x[:n], P), plausible=True)

    Eq << Eq[-1].definition
    
    Eq << sets.forall_contains.forall_contains.forall_equality.forall_equality.imply.equality.apply(Eq[-1], Eq.P2P_quote, Eq.mapping_quote, Eq.mapping)
    
    Eq << Eq[-1].reversed