Пример #1
0
def field_isomorphism(a, b, **args):
    """Construct an isomorphism between two number fields. """
    a, b = sympify(a), sympify(b)

    if not a.is_AlgebraicNumber:
        a = AlgebraicNumber(a)

    if not b.is_AlgebraicNumber:
        b = AlgebraicNumber(b)

    if a == b:
        return a.coeffs()

    n = a.minpoly.degree()
    m = b.minpoly.degree()

    if n == 1:
        return [a.root]

    if m % n != 0:
        return

    if args.get('fast', True):
        try:
            result = field_isomorphism_pslq(a, b)

            if result is not None:
                return result
        except NotImplementedError:
            pass

    return field_isomorphism_factor(a, b)
Пример #2
0
    def __new__(cls, domain, density):
        density = {sympify(key): sympify(val) for key, val in density.items()}
        public_density = Dict(density)

        obj = PSpace.__new__(cls, domain, public_density)
        obj._density = density
        return obj
Пример #3
0
    def __init__(self, var, update_string, program_variables=None, is_random_var=False, random_var=None):
        self.is_random_var = is_random_var
        self.random_var = random_var
        self.var = var

        # check if this is a RV or expression update
        rv = re.search(r"RV\((?P<params>.+)\)", update_string)
        if rv is not None:
            self.is_random_var = True
            dist, *params = map(str.strip, rv.group('params').split(','))
            params = list(map(sympify, params))
            self.random_var = RandomVar(dist, params, var_name=str(self.var))

        # here: if not is_random_var == else
        if not self.is_random_var:
            self.branches = []
            branches = update_string.split(";")
            for update in branches:
                if '@' in update:
                    exp, prob = update.split("@")
                else:
                    exp, prob = update, 1-sum([b[1] for b in self.branches])
                prob = sympify(prob)
                if prob.is_Float:
                    prob = Rational(str(prob))
                if not prob.is_zero:
                    exp = make_symbols_positive(sympify(exp), program_variables)
                    prob = make_symbols_positive(prob, program_variables)
                    self.branches.append((sympify(exp), prob))
            if sum([b[1] for b in self.branches]) != 1:
                raise Exception(f"Branch probabilities for {self.var} update do not sum up to 1. Terminating.")
Пример #4
0
def test_sympyissue_6046():
    assert str(sympify('Q & C', locals=_clash1)) == 'C & Q'
    assert str(sympify('pi(x)', locals=_clash2)) == 'pi(x)'
    assert str(sympify('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
    locals = {}
    exec('from diofant.abc import S, O', locals)  # pylint: disable=exec-used
    assert str(sympify('O&S', locals)) == 'O & S'
Пример #5
0
def test_product_basic():
    H, T = 'H', 'T'
    unit_line = Interval(0, 1)
    d6 = FiniteSet(1, 2, 3, 4, 5, 6)
    d4 = FiniteSet(1, 2, 3, 4)
    coin = FiniteSet(H, T)

    square = unit_line * unit_line

    assert (0, 0) in square
    assert 0 not in square
    assert (H, T) in coin ** 2
    assert (.5, .5, .5) in square * unit_line
    assert (H, 3, 3) in coin*d6*d6
    HH, TT = sympify(H), sympify(T)
    assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)}

    assert (d4*d4).is_subset(d6*d6)

    assert (square.complement(Interval(-oo, oo)*Interval(-oo, oo)) ==
            Union((Interval(-oo, 0, True, True) +
                   Interval(1, oo, True, True))*Interval(-oo, oo),
                  Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
                                     Interval(1, oo, True, True))))

    assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
    assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
    assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)

    assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square)  # segment in square

    assert len(coin*coin*coin) == 8
    assert len(S.EmptySet*S.EmptySet) == 0
    assert len(S.EmptySet*coin) == 0
    pytest.raises(TypeError, lambda: len(coin*Interval(0, 2)))
Пример #6
0
def test_sympyissue_7840():
    # daveknippers' example
    C393 = sympify(
        'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \
        C391 > 2.35), (C392, True)), True))'
    )
    C391 = sympify(
        'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))'
    )
    C393 = C393.subs({'C391': C391})
    # simple substitution
    sub = {}
    sub['C390'] = 0.703451854
    sub['C392'] = 1.01417794
    ss_answer = C393.subs(sub)
    # cse
    substitutions, new_eqn = cse(C393)
    for pair in substitutions:
        sub[pair[0].name] = pair[1].subs(sub)
    cse_answer = new_eqn[0].subs(sub)
    # both methods should be the same
    assert ss_answer == cse_answer

    # GitRay's example
    expr = Piecewise((Symbol('ON'), Eq(Symbol('mode'), Symbol('ON'))),
                     (Piecewise((Piecewise((Symbol('OFF'), Symbol('x') < Symbol('threshold')),
                                           (Symbol('ON'), true)), Eq(Symbol('mode'), Symbol('AUTO'))),
                                (Symbol('OFF'), true)), true))
    substitutions, new_eqn = cse(expr)
    # this Piecewise should be exactly the same
    assert new_eqn[0] == expr
    # there should not be any replacements
    assert len(substitutions) < 1
Пример #7
0
def test_sympyify_iterables():
    ans = [Rational(3, 10), Rational(1, 5)]
    assert sympify(['.3', '.2'], rational=True) == ans
    assert sympify({'.3', '.2'}, rational=True) == set(ans)
    assert sympify(('.3', '.2'), rational=True) == Tuple(*ans)
    assert sympify({x: 0, y: 1}) == {x: 0, y: 1}
    assert sympify(['1', '2', ['3', '4']]) == [Integer(1), Integer(2), [Integer(3), Integer(4)]]
Пример #8
0
def test_sympyissue_7840():
    # daveknippers' example
    C393 = sympify(
        'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \
        C391 > 2.35), (C392, True)), True))')
    C391 = sympify(
        'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))'
    )
    C393 = C393.subs({'C391': C391})
    # simple substitution
    sub = {}
    sub['C390'] = 0.703451854
    sub['C392'] = 1.01417794
    ss_answer = C393.subs(sub)
    # cse
    substitutions, new_eqn = cse(C393)
    for pair in substitutions:
        sub[pair[0].name] = pair[1].subs(sub)
    cse_answer = new_eqn[0].subs(sub)
    # both methods should be the same
    assert ss_answer == cse_answer

    # GitRay's example
    expr = Piecewise(
        (Symbol('ON'), Eq(Symbol('mode'), Symbol('ON'))), (Piecewise(
            (Piecewise(
                (Symbol('OFF'), Symbol('x') < Symbol('threshold')),
                (Symbol('ON'), true)), Eq(Symbol('mode'), Symbol('AUTO'))),
            (Symbol('OFF'), true)), true))
    substitutions, new_eqn = cse(expr)
    # this Piecewise should be exactly the same
    assert new_eqn[0] == expr
    # there should not be any replacements
    assert len(substitutions) < 1
Пример #9
0
def test_product_basic():
    H, T = 'H', 'T'
    unit_line = Interval(0, 1)
    d6 = FiniteSet(1, 2, 3, 4, 5, 6)
    d4 = FiniteSet(1, 2, 3, 4)
    coin = FiniteSet(H, T)

    square = unit_line * unit_line

    assert (0, 0) in square
    assert 0 not in square
    assert (H, T) in coin ** 2
    assert (.5, .5, .5) in square * unit_line
    assert (H, 3, 3) in coin*d6*d6
    HH, TT = sympify(H), sympify(T)
    assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)}

    assert (d4*d4).is_subset(d6*d6)

    assert (square.complement(Interval(-oo, oo)*Interval(-oo, oo)) ==
            Union((Interval(-oo, 0, True, True) +
                   Interval(1, oo, True, True))*Interval(-oo, oo),
                  Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
                                     Interval(1, oo, True, True))))

    assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
    assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
    assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)

    assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square)  # segment in square

    assert len(coin*coin*coin) == 8
    assert len(S.EmptySet*S.EmptySet) == 0
    assert len(S.EmptySet*coin) == 0
    pytest.raises(TypeError, lambda: len(coin*Interval(0, 2)))
Пример #10
0
    def run(self, result: Result):
        if result.AST.is_known():
            return result

        # Martingale expression has to be <= 0 eventually
        if not is_invariant(self.martingale_expression, self.program):
            return result

        # Eventually one branch of LG_{i+1} - LG_i has to decrease more or equal than constant
        branches = get_cases_for_expression(sympify(self.program.loop_guard),
                                            self.program)
        if self.program.contains_rvs:
            branches = split_expressions_on_rvs(branches, self.program)
        for branch, prob in branches:
            bounds = bound_store.get_bounds_of_expr(
                branch - sympify(self.program.loop_guard))
            n = symbols("n", integer=True, positive=True)
            if is_dominating_or_same(bounds.upper,
                                     sympify(-1),
                                     n,
                                     direction=Direction.NegInf):
                result.AST = Answer.TRUE
                result.add_witness(
                    ASTWitness(self.program.loop_guard,
                               self.martingale_expression, branch,
                               bounds.upper, prob))
                return result

        return result
Пример #11
0
def test_sympyissue_10773():
    with evaluate(False):
        ans = Mul(Integer(-10), Pow(Integer(5), Integer(-1)))
    assert sympify('-10/5', evaluate=False) == ans

    with evaluate(False):
        ans = Mul(Integer(-10), Pow(Integer(-5), Integer(-1)))
    assert sympify('-10/-5', evaluate=False) == ans
Пример #12
0
def test_sympyissue_4988():
    C = Symbol('C')
    vars = {}
    vars['C'] = C
    exp1 = sympify('C')
    assert exp1 == C  # Make sure it did not get mixed up with diofant.C

    exp2 = sympify('C', vars)
    assert exp2 == C  # Make sure it did not get mixed up with diofant.C
Пример #13
0
def test_sympify_gmpy():
    if HAS_GMPY:
        import gmpy2 as gmpy

        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Пример #14
0
def test_sympify5():
    class A:
        def __str__(self):
            raise TypeError

    with pytest.raises(SympifyError) as err:
        sympify(A())
    assert re.match(r"^Sympify of expression '<diofant\.tests\.core\.test_sympify"
                    r"\.test_sympify5\.<locals>\.A object at 0x[0-9a-f]+>' failed,"
                    ' because of exception being raised:\nTypeError: $', str(err.value))
Пример #15
0
def test_lambda_raises():
    pytest.raises(NotImplementedError,
                  lambda: sympify('lambda *args: args'))  # args argument error
    pytest.raises(
        NotImplementedError,
        lambda: sympify('lambda **kwargs: kwargs'))  # kwargs argument error
    pytest.raises(SympifyError,
                  lambda: sympify('lambda x = 1: x'))  # Keyword argument error
    with pytest.raises(SympifyError):
        sympify('lambda: 1', strict=True)
Пример #16
0
def test_sympify2():
    class A:
        def _diofant_(self):
            return Symbol('x')**3

    a = A()

    assert sympify(a, strict=True) == x**3
    assert sympify(a) == x**3
    assert a == x**3
Пример #17
0
def _minimal_polynomial_sq(p, n, x):
    """
    Returns the minimal polynomial for the ``nth-root`` of a sum of surds
    or ``None`` if it fails.

    Parameters
    ==========

    p : sum of surds
    n : positive integer
    x : variable of the returned polynomial

    Examples
    ========

    >>> from diofant import sqrt
    >>> from diofant.abc import x

    >>> q = 1 + sqrt(2) + sqrt(3)
    >>> _minimal_polynomial_sq(q, 3, x)
    x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
    """
    from diofant.simplify.simplify import _is_sum_surds

    p = sympify(p)
    n = sympify(n)
    r = _is_sum_surds(p)
    if not n.is_Integer or not n > 0 or not _is_sum_surds(p):
        return
    pn = p**Rational(1, n)
    # eliminate the square roots
    p -= x
    while 1:
        p1 = _separate_sq(p)
        if p1 is p:
            p = p1.subs({x: x**n})
            break
        else:
            p = p1

    # _separate_sq eliminates field extensions in a minimal way, so that
    # if n = 1 then `p = constant*(minimal_polynomial(p))`
    # if n > 1 it contains the minimal polynomial as a factor.
    if n == 1:
        p1 = Poly(p)
        if p.coeff(x**p1.degree(x)) < 0:
            p = -p
        p = p.primitive()[1]
        return p
    # by construction `p` has root `pn`
    # the minimal polynomial is the factor vanishing in x = pn
    factors = factor_list(p)[1]

    result = _choose_factor(factors, x, pn)
    return result
Пример #18
0
 def __init__(self, ranking_martingale, martingale_expression, bound):
     super(PASTWitness, self).__init__("PAST")
     ranking_martingale = sympify(ranking_martingale).as_expr()
     martingale_expression = sympify(martingale_expression).as_expr()
     bound = sympify(bound).as_expr()
     self.data = {
         "Ranking SM": ranking_martingale,
         "SM expression": martingale_expression,
         "SM expression bound": bound,
     }
     self.explanation = f"Eventually, '{ranking_martingale}' is a ranking supermartingale. That's because eventually\n" \
                        f"the bound of the supermartingale expression is '{bound}'."
Пример #19
0
def test_nsimplify():
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2
    assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == \
        sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == \
        sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \
        sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \
        2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
        sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8
    assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \
        -pi/4 - log(2) + Rational(7, 4)
    assert nsimplify(x/7.0) == x/7
    assert nsimplify(pi/1e2) == pi/100
    assert nsimplify(pi/1e2, rational=False) == pi/100.0
    assert nsimplify(pi/1e-7) == 10000000*pi
    assert not nsimplify(
        factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float)
    e = x**0.0
    assert e.is_Pow and nsimplify(x**0.0) == 1
    assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
    assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3)
    assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
    assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3)
    assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
    assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
    assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
    assert nsimplify(-203.1) == -Rational(2031, 10)
    assert nsimplify(.2, tolerance=0) == S.One/5
    assert nsimplify(-.2, tolerance=0) == -S.One/5
    assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000)
    assert nsimplify(-.2222, tolerance=0) == -Rational(1111, 5000)
    # issue 7211, PR 4112
    assert nsimplify(Float(2e-8)) == Rational(1, 50000000)
    # issue 7322 direct test
    assert nsimplify(1e-42, rational=True) != 0
Пример #20
0
 def __init__(self, repulsing_martingale, martingale_expression):
     super(NONPASTWitness, self).__init__("Not PAST")
     repulsing_martingale = sympify(repulsing_martingale).as_expr()
     martingale_expression = sympify(martingale_expression).as_expr()
     self.data = {
         "Repulsing SM": repulsing_martingale,
         "SM expression": martingale_expression,
     }
     self.explanation = f"There is always a positive probability of having a next iteration.\n" \
                        f"Moreover, '{repulsing_martingale}' eventually is a repulsing supermartingale\n" \
                        f"decreasing with epsilons '0'. Also, the repulsing SM has differences bounded\n" \
                        f"by a constant."
Пример #21
0
def test_Wild_properties():
    # these tests only include Atoms
    x = Symbol("x")
    y = Symbol("y")
    p = Symbol("p", positive=True)
    k = Symbol("k", integer=True)
    n = Symbol("n", integer=True, positive=True)

    given_patterns = [
        x, y, p, k, -k, n, -n,
        sympify(-3),
        sympify(3), pi,
        Rational(3, 2), I
    ]

    def integerp(k):
        return k.is_integer

    def positivep(k):
        return k.is_positive

    def symbolp(k):
        return k.is_Symbol

    def realp(k):
        return k.is_extended_real

    S = Wild("S", properties=[symbolp])
    R = Wild("R", properties=[realp])
    Y = Wild("Y", exclude=[x, p, k, n])
    P = Wild("P", properties=[positivep])
    K = Wild("K", properties=[integerp])
    N = Wild("N", properties=[positivep, integerp])

    given_wildcards = [S, R, Y, P, K, N]

    goodmatch = {
        S: (x, y, p, k, n),
        R: (p, k, -k, n, -n, -3, 3, pi, Rational(3, 2)),
        Y: (y, -3, 3, pi, Rational(3, 2), I),
        P: (p, n, 3, pi, Rational(3, 2)),
        K: (k, -k, n, -n, -3, 3),
        N: (n, 3)
    }

    for A in given_wildcards:
        for pat in given_patterns:
            d = pat.match(A)
            if pat in goodmatch[A]:
                assert d[A] in goodmatch[A]
            else:
                assert d is None
Пример #22
0
    def __new__(cls, *args):
        n = args[BinomialDistribution._argnames.index('n')]
        p = args[BinomialDistribution._argnames.index('p')]
        n_sym = sympify(n)
        p_sym = sympify(p)

        if fuzzy_not(fuzzy_and((n_sym.is_integer, n_sym.is_nonnegative))):
            raise ValueError("'n' must be positive integer. n = %s." % str(n))
        elif fuzzy_not(
                fuzzy_and((p_sym.is_nonnegative, (p_sym - 1).is_nonpositive))):
            raise ValueError("'p' must be: 0 <= p <= 1 . p = %s" % str(p))
        else:
            return super(BinomialDistribution, cls).__new__(cls, *args)
Пример #23
0
    def compute_moment(self, k):
        if self.distribution == 'finite':
            return sum([p * (b ** k) for b, p in self.parameters])

        if self.distribution == 'uniform':
            l, u = self.parameters
            return (u**(k+1)-l**(k+1))/((k+1)*(u-l))

        if self.distribution == 'gauss' or self.distribution == 'normal':
            mu, sigma_squared = self.parameters
            # For low moments avoid scipy.stats.moments as it does not support
            # parametric parameters. In the future get all moments directly,
            # using the following properties:
            # https://math.stackexchange.com/questions/1945448/methods-for-finding-raw-moments-of-the-normal-distribution
            if k == 0:
                return 1
            elif k == 1:
                return mu
            elif k == 2:
                return mu**2 + sigma_squared
            elif k == 3:
                return mu*(mu**2 + 3*sigma_squared)
            elif k == 4:
                return mu**4 + 6*mu**2*sigma_squared + 3*sigma_squared**2
            moment = norm(loc=mu, scale=sqrt(sigma_squared)).moment(k)
            return Rational(moment)

        if self.distribution == 'unknown':
            return sympify(f"{self.var_name}(0)^{k}")
Пример #24
0
def _minpoly_cos(ex, x):
    """
    Returns the minimal polynomial of ``cos(ex)``
    see http://mathworld.wolfram.com/TrigonometryAngles.html
    """
    from diofant import sqrt
    c, a = ex.args[0].as_coeff_Mul()
    if a is pi:
        if c.is_rational:
            if c.p == 1:
                if c.q == 7:
                    return 8 * x**3 - 4 * x**2 - 4 * x + 1
                if c.q == 9:
                    return 8 * x**3 - 6 * x + 1
            elif c.p == 2:
                q = sympify(c.q)
                if q.is_prime:
                    s = _minpoly_sin(ex, x)
                    return _mexpand(s.subs({x: sqrt((1 - x) / 2)}))

            # for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
            n = int(c.q)
            a = dup_chebyshevt(n, ZZ)
            a = [x**(n - i) * a[i] for i in range(n + 1)]
            r = Add(*a) - (-1)**c.p
            _, factors = factor_list(r)
            res = _choose_factor(factors, x, ex)
            return res

    raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
Пример #25
0
def pspace(expr):
    """
    Returns the underlying Probability Space of a random expression.

    For internal use.

    Examples
    ========

    >>> from diofant.stats import pspace, Normal
    >>> from diofant.stats.rv import ProductPSpace
    >>> X = Normal('X', 0, 1)
    >>> pspace(2*X + 1) == X.pspace
    True
    """

    expr = sympify(expr)
    rvs = random_symbols(expr)
    if not rvs:
        raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
    # If only one space present
    if all(rv.pspace == rvs[0].pspace for rv in rvs):
        return rvs[0].pspace
    # Otherwise make a product space
    return ProductPSpace(*[rv.pspace for rv in rvs])
Пример #26
0
def to_number_field(extension, theta=None, **args):
    """Express `extension` in the field generated by `theta`. """
    gen = args.get('gen')

    if hasattr(extension, '__iter__'):
        extension = list(extension)
    else:
        extension = [extension]

    if len(extension) == 1 and type(extension[0]) is tuple:
        return AlgebraicNumber(extension[0])

    minpoly, coeffs = primitive_element(extension, gen, polys=True)
    root = sum(coeff * ext for coeff, ext in zip(coeffs, extension))

    if theta is None:
        return AlgebraicNumber((minpoly, root))
    else:
        theta = sympify(theta)

        if not theta.is_AlgebraicNumber:
            theta = AlgebraicNumber(theta, gen=gen)

        coeffs = field_isomorphism(root, theta)

        if coeffs is not None:
            return AlgebraicNumber(theta, coeffs)
        else:
            raise IsomorphismFailed("%s is not in a subfield of %s" %
                                    (root, theta.root))
Пример #27
0
def isolate(alg, eps=None, fast=False):
    """Give a rational isolating interval for an algebraic number. """
    alg = sympify(alg)

    if alg.is_Rational:
        return alg, alg
    elif not alg.is_extended_real:
        raise NotImplementedError(
            "complex algebraic numbers are not supported")

    func = lambdify((), alg, modules="mpmath", printer=IntervalPrinter())

    poly = minpoly(alg, polys=True)
    intervals = poly.intervals(sqf=True)

    dps, done = mp.dps, False

    try:
        while not done:
            alg = func()

            for a, b in intervals:
                if a <= alg.a and alg.b <= b:
                    done = True
                    break
            else:
                mp.dps *= 2
    finally:
        mp.dps = dps

    if eps is not None:
        a, b = poly.refine_root(a, b, eps=eps, fast=fast)

    return a, b
Пример #28
0
 def __init__(self, repulsing_martingale, martingale_expression, epsilons,
              cs):
     super(NONASTWitness, self).__init__("Not AST")
     repulsing_martingale = sympify(repulsing_martingale).as_expr()
     martingale_expression = sympify(martingale_expression).as_expr()
     epsilons = sympify(epsilons).as_expr()
     cs = sympify(cs).as_expr()
     self.data = {
         "Repulsing SM": repulsing_martingale,
         "SM expression": martingale_expression,
         "Epsilons": epsilons,
         "Cs": cs
     }
     self.explanation = f"There is always a positive probability of having a next iteration.\n" \
                        f"Moreover, '{repulsing_martingale}' eventually is a repulsing supermartingale\n" \
                        f"decreasing with epsilons '{epsilons}'. Also, the repulsing SM has differences bound\n" \
                        f"by '{cs}' which is O(epsilons)."
Пример #29
0
    def run(self, result: Result):
        if result.PAST.is_known() and result.AST.is_known():
            return result

        # Martingale expression has to be <= 0 eventually
        if not is_invariant(self.martingale_expression, self.program):
            return result

        branches = get_cases_for_expression(sympify(self.program.loop_guard),
                                            self.program)
        if self.program.contains_rvs:
            branches = split_expressions_on_rvs(branches, self.program)
        branches = [
            simplify(branch - sympify(self.program.loop_guard))
            for branch, _ in branches
        ]
        bounds = [bound_store.get_bounds_of_expr(case) for case in branches]
Пример #30
0
 def __init__(self, martingale, martingale_expression, decreasing_branch,
              bound, prob):
     super(ASTWitness, self).__init__("AST")
     martingale = sympify(martingale).as_expr()
     martingale_expression = sympify(martingale_expression).as_expr()
     decreasing_branch = sympify(decreasing_branch).as_expr()
     bound = sympify(bound).as_expr()
     self.data = {
         "SM": martingale,
         "SM expression": martingale_expression,
         "Decreasing branch": decreasing_branch,
         "Branch change bound": bound,
         "Probability": prob
     }
     self.explanation = f"Eventually, '{martingale}' is a supermartingale. Also eventually, taking the branch\n" \
                        f"'{decreasing_branch}' (which happens with probability {prob}) " \
                        f"changes the supermartingale by at least {bound}."
Пример #31
0
def get_loop_guard_change(program: Program):
    """
    Returns E[LG_{n+1} - LG_{n}]
    """
    n = symbols("n", integer=True, positive=True)
    lg = sympify(LOOP_GUARD_VAR).as_poly(program.variables)
    expected_lg = get_expected(program, lg)
    expected_lg_plus = expected_lg.xreplace({n: n + 1})
    return expand(expected_lg_plus - expected_lg)
Пример #32
0
def test_sympyissue_8821():
    s = str(pi.evalf(128))
    p = N(s)
    assert abs(sin(p)) < 1e-15
    p = N(s, 64)
    assert abs(sin(p)) < 1e-64
    s = str(pi.evalf(128))
    p = sympify(s)
    assert abs(sin(p)) < 1e-127
Пример #33
0
def test_Tuple():
    t = (1, 2, 3, 4)
    st = Tuple(*t)
    assert set(sympify(t)) == set(st)
    assert len(t) == len(st)
    assert set(sympify(t[:2])) == set(st[:2])
    assert isinstance(st[:], Tuple)
    assert st == Tuple(1, 2, 3, 4)
    assert st.func(*st.args) == st
    t2 = (p, q, r, s)
    st2 = Tuple(*t2)
    assert st2.atoms() == set(t2)
    assert st == st2.subs({p: 1, q: 2, r: 3, s: 4})
    # issue sympy/sympy#5505
    assert all(isinstance(arg, Basic) for arg in st.args)
    assert Tuple(p, 1).subs({p: 0}) == Tuple(0, 1)
    assert Tuple(p, Tuple(p, 1)).subs({p: 0}) == Tuple(0, Tuple(0, 1))

    assert Tuple(t2) == Tuple(Tuple(*t2))
Пример #34
0
 def t(m, a, b):
     a, b = sympify([a, b])
     m_ = m
     m = hyperexpand(m)
     if not m == Piecewise((a, abs(z) < 1), (b, abs(1/z) < 1), (m_, True)):
         return False
     if not (m.args[0].args[0] == a and m.args[1].args[0] == b):
         return False
     z0 = randcplx()/10
     if abs(m.subs({z: z0}) - a.subs({z: z0})).evalf(strict=False) > 1e-10:
         return False
     if abs(m.subs({z: 1/z0}) - b.subs({z: 1/z0})).evalf(strict=False) > 1e-10:
         return False
     return True
Пример #35
0
def test_numexpr_printer():
    # if translation/printing is done incorrectly then evaluating
    # a lambdified numexpr expression will throw an exception

    blacklist = ('where', 'complex', 'contains')
    arg_tuple = (x, y, z)  # some functions take more than one argument
    for sym in NumExprPrinter._numexpr_functions:
        if sym in blacklist:
            continue
        ssym = sympify(sym)
        if hasattr(ssym, '_nargs'):
            nargs = ssym._nargs[0]
        else:
            nargs = 1
        args = arg_tuple[:nargs]
        f = lambdify(args, ssym(*args), modules='numexpr')
        assert f(*(1, )*nargs) is not None
Пример #36
0
def test_mathematica():
    d = {
        '- 6x': '-6*x',
        'Sin[x]^2': 'sin(x)**2',
        '2(x-1)': '2*(x-1)',
        '(x-1)2': '(x-1)*2',
        '(x-y)': '(x-y)',
        '3y+8': '3*y+8',
        'Arcsin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
        'x+y': 'x+y',
        '355/113': '355/113',
        '2.718281828': '2.718281828',
        'Sin[12]': 'sin(12)',
        'Exp[Log[4]]': 'exp(log(4))',
        '(x+1)(x+3)': '(x+1)*(x+3)',
        'Cos[Arccos[3.6]]': 'cos(acos(3.6))',
        'Cos[x]==Sin[y]': 'cos(x)==sin(y)',
        '2*Sin[x+y]': '2*sin(x+y)',
        'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
        'Sin[Cos[x]]': 'sin(cos(x))',
        '2*Sqrt[x+y]': '2*sqrt(x+y)'}   # Test case from the issue sympy/sympy#4259
    for e in d:
        assert mathematica(e) == sympify(d[e])
Пример #37
0
def NS(e, n=15, **options):
    return sstr(sympify(e).evalf(n, **options), full_prec=True)
Пример #38
0
def test_S_repr_is_identity():
    p = Piecewise((10, Eq(x, 0)), (12, True))
    q = sympify(repr(p))
    assert p == q
Пример #39
0
def test_as_immutable():
    X = Matrix([[1, 2], [3, 4]])
    assert sympify(X) == X.as_immutable() == ImmutableMatrix([[1, 2], [3, 4]])
    X = SparseMatrix(5, 5, {})
    assert sympify(X) == X.as_immutable() == ImmutableSparseMatrix(
        [[0 for i in range(5)] for i in range(5)])
Пример #40
0
def test_cdf():
    D = Die('D', 6)
    o = Integer(1)

    assert cdf(
        D) == sympify({1: o/6, 2: o/3, 3: o/2, 4: 2*o/3, 5: 5*o/6, 6: o})
Пример #41
0
 def eval(cls, arg):
     arg = sympify(arg)
     if arg == 0:
         return sympify(0)
Пример #42
0
def NS(e, n=15, **options):
    return str(sympify(e).evalf(n, **options))