Exemplo n.º 1
0
def test_Dict():
    assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}"
    assert str(Dict({
        1: x**2,
        2: y * x
    })) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}")
    assert sstr(Dict({1: x**2, 2: y * x})) == "{1: x**2, 2: x*y}"
Exemplo n.º 2
0
def test_Dict():
    assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == '{1: x + 1}'
    assert str(Dict({
        1: x**2,
        2: y * x
    })) in ('{1: x**2, 2: x*y}', '{2: x*y, 1: x**2}')
    assert sstr(Dict({1: x**2, 2: y * x})) == '{1: x**2, 2: x*y}'
Exemplo n.º 3
0
def test_domains():
    X, Y = Die('x', 6), Die('y', 6)
    x, y = X.symbol, Y.symbol
    # Domains
    d = where(X > Y)
    assert d.condition == (x > y)
    d = where(And(X > Y, Y > 3))
    assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y,
                                                 4)), And(Eq(x, 6), Eq(y, 5)),
                                And(Eq(x, 6), Eq(y, 4)))
    assert len(d.elements) == 3

    assert len(pspace(X + Y).domain.elements) == 36

    Z = Die('x', 4)

    pytest.raises(ValueError,
                  lambda: P(X > Z))  # Two domains with same internal symbol

    assert pspace(X + Y).domain.set == FiniteSet(1, 2, 3, 4, 5, 6)**2

    assert where(X > 3).set == FiniteSet(4, 5, 6)
    assert X.pspace.domain.dict == FiniteSet(
        *[Dict({X.symbol: i}) for i in range(1, 7)])

    assert where(X > Y).dict == FiniteSet(*[
        Dict({
            X.symbol: i,
            Y.symbol: j
        }) for i in range(1, 7) for j in range(1, 7) if i > j
    ])
Exemplo n.º 4
0
def test_gcd_terms():
    f = 2*(x + 1)*(x + 4)/(5*x**2 + 5) + (2*x + 2)*(x + 5)/(x**2 + 1)/5 + \
        (2*x + 2)*(x + 6)/(5*x**2 + 5)

    assert _gcd_terms(f) == (Rational(6, 5) * ((1 + x) / (1 + x**2)), 5 + x, 1)
    assert _gcd_terms(Add.make_args(f)) == \
        (Rational(6, 5)*((1 + x)/(1 + x**2)), 5 + x, 1)

    newf = Rational(6, 5) * ((1 + x) * (5 + x) / (1 + x**2))
    assert gcd_terms(f) == newf
    args = Add.make_args(f)
    # non-Basic sequences of terms treated as terms of Add
    assert gcd_terms(list(args)) == newf
    assert gcd_terms(tuple(args)) == newf
    assert gcd_terms(set(args)) == newf
    # but a Basic sequence is treated as a container
    assert gcd_terms(Tuple(*args)) != newf
    assert gcd_terms(Basic(Tuple(1, 3*y + 3*x*y), Tuple(1, 3))) == \
        Basic((1, 3*y*(x + 1)), (1, 3))
    # but we shouldn't change keys of a dictionary or some may be lost
    assert gcd_terms(Dict((x*(1 + y), 2), (x + x*y, y + x*y))) == \
        Dict({x*(y + 1): 2, x + x*y: y*(1 + x)})

    assert gcd_terms((2 * x + 2)**3 +
                     (2 * x + 2)**2) == 4 * (x + 1)**2 * (2 * x + 3)

    assert gcd_terms(0) == 0
    assert gcd_terms(1) == 1
    assert gcd_terms(x) == x
    assert gcd_terms(2 + 2 * x) == Mul(2, 1 + x, evaluate=False)
    arg = x * (2 * x + 4 * y)
    garg = 2 * x * (x + 2 * y)
    assert gcd_terms(arg) == garg
    assert gcd_terms(sin(arg)) == sin(garg)

    # issue sympy/sympy#6139-like
    alpha, alpha1, alpha2, alpha3 = symbols('alpha:4')
    a = alpha**2 - alpha * x**2 + alpha + x**3 - x * (alpha + 1)
    rep = {
        alpha: (1 + sqrt(5)) / 2 + alpha1 * x + alpha2 * x**2 + alpha3 * x**3
    }
    s = (a / (x - alpha)).subs(rep).series(x, 0, 1)
    assert simplify(collect(s, x)) == -sqrt(5) / 2 - Rational(3, 2) + O(x)

    # issue sympy/sympy#5917
    assert _gcd_terms([Integer(0), Integer(0)]) == (0, 0, 1)
    assert _gcd_terms([2 * x + 4]) == (2, x + 2, 1)

    eq = x / (x + 1 / x)
    assert gcd_terms(eq, fraction=False) == eq
Exemplo n.º 5
0
def test_IndexedBase_subs():
    i = Symbol('i', integer=True)
    A = IndexedBase(a)
    B = IndexedBase(b)
    C = IndexedBase(c)
    assert A[i] == B[i].subs({b: a})
    assert isinstance(C[1].subs({C: Dict({1: 2})}), type(A[1]))
Exemplo n.º 6
0
def test_ndim_array_initiation():
    arr_with_one_element = ImmutableDenseNDimArray([23])
    assert len(arr_with_one_element) == 1
    assert arr_with_one_element[0] == 23
    assert arr_with_one_element[:] == [23]
    assert arr_with_one_element.rank() == 1

    arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')])
    assert len(arr_with_symbol_element) == 1
    assert arr_with_symbol_element[0] == Symbol('x')
    assert arr_with_symbol_element[:] == [Symbol('x')]
    assert arr_with_symbol_element.rank() == 1

    number5 = 5
    vector = ImmutableDenseNDimArray.zeros(number5)
    assert len(vector) == number5
    assert vector.shape == (number5, )
    assert vector.rank() == 1

    vector = ImmutableSparseNDimArray.zeros(number5)
    assert len(vector) == number5
    assert vector.shape == (number5, )
    assert vector._sparse_array == Dict()
    assert vector.rank() == 1

    n_dim_array = ImmutableDenseNDimArray(range(3**4), (
        3,
        3,
        3,
        3,
    ))
    assert len(n_dim_array) == 3 * 3 * 3 * 3
    assert n_dim_array.shape == (3, 3, 3, 3)
    assert n_dim_array.rank() == 4

    array_shape = (3, 3, 3, 3)
    sparse_array = ImmutableSparseNDimArray.zeros(*array_shape)
    assert len(sparse_array._sparse_array) == 0
    assert len(sparse_array) == 3 * 3 * 3 * 3
    assert n_dim_array.shape == array_shape
    assert n_dim_array.rank() == 4

    one_dim_array = ImmutableDenseNDimArray([2, 3, 1])
    assert len(one_dim_array) == 3
    assert one_dim_array.shape == (3, )
    assert one_dim_array.rank() == 1
    assert one_dim_array.tolist() == [2, 3, 1]

    shape = (3, 3)
    array_with_many_args = ImmutableSparseNDimArray.zeros(*shape)
    assert len(array_with_many_args) == 3 * 3
    assert array_with_many_args.shape == shape
    assert array_with_many_args[0, 0] == 0
    assert array_with_many_args.rank() == 2
Exemplo n.º 7
0
def test_Dict():
    x, y, z = symbols('x y z')
    d = Dict({x: 1, y: 2, z: 3})
    assert d[x] == 1
    assert d[y] == 2
    pytest.raises(KeyError, lambda: d[2])
    assert len(d) == 3
    assert set(d.keys()) == {x, y, z}
    assert set(d.values()) == {Integer(1), Integer(2), Integer(3)}
    assert d.get(5, 'default') == 'default'
    assert x in d and z in d and 5 not in d
    assert d.has(x) and d.has(1)  # Diofant Basic .has method

    # Test input types
    # input - a python dict
    # input - items as args - Diofant style
    assert (Dict({x: 1, y: 2, z: 3}) == Dict((x, 1), (y, 2), (z, 3)))

    pytest.raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3))))
    with pytest.raises(NotImplementedError):
        d[5] = 6  # assert immutability

    assert set(d.items()) == {
        Tuple(x, Integer(1)),
        Tuple(y, Integer(2)),
        Tuple(z, Integer(3))
    }
    assert set(d) == {x, y, z}
    assert str(d) == '{x: 1, y: 2, z: 3}'
    assert d.__repr__(
    ) == "Dict(Tuple(Symbol('x'), Integer(1)), Tuple(Symbol('y'), Integer(2)), Tuple(Symbol('z'), Integer(3)))"

    # Test creating a Dict from a Dict.
    d = Dict({x: 1, y: 2, z: 3})
    assert d == Dict(d)
Exemplo n.º 8
0
    def __new__(cls, *args, **kwargs):

        shape, flat_list = cls._handle_ndarray_creation_inputs(*args, **kwargs)
        shape = Tuple(*map(_sympify, shape))
        loop_size = functools.reduce(lambda x, y: x * y, shape) if shape else 0

        # Sparse array:
        if isinstance(flat_list, (dict, Dict)):
            sparse_array = Dict(flat_list)
        else:
            sparse_array = {}
            for i, el in enumerate(flatten(flat_list)):
                if el != 0:
                    sparse_array[i] = _sympify(el)

        sparse_array = Dict(sparse_array)

        self = Expr.__new__(cls, sparse_array, shape, **kwargs)
        self._shape = shape
        self._rank = len(shape)
        self._loop_size = loop_size
        self._sparse_array = sparse_array

        return self
Exemplo n.º 9
0
def test_dict_set():
    a, b = map(Wild, 'ab')

    f = 3 * cos(4 * x)
    r = f.match(a * cos(b * x))
    assert r == {a: 3, b: 4}
    e = a / b * sin(b * x)
    assert e.subs(r) == r[a] / r[b] * sin(r[b] * x)
    assert e.subs(r) == 3 * sin(4 * x) / 4
    s = set(r.items())
    assert e.subs(s) == r[a] / r[b] * sin(r[b] * x)
    assert e.subs(s) == 3 * sin(4 * x) / 4

    assert e.subs(r) == r[a] / r[b] * sin(r[b] * x)
    assert e.subs(r) == 3 * sin(4 * x) / 4
    assert x.subs(Dict((x, 1))) == 1
Exemplo n.º 10
0
def test_ProductPSpace():
    X = Normal('X', 0, 1)
    Y = Normal('Y', 0, 1)
    px = X.pspace
    py = Y.pspace
    assert pspace(X + Y) == ProductPSpace(px, py)
    assert pspace(X + Y) == ProductPSpace(py, px)

    X = Die('X', 2)
    Y = Die('Y', 2)

    assert (pspace(X + Y).density ==
            Dict((frozenset({('X', 1), ('Y', 2)}), Rational(1, 4)),
                 (frozenset({('X', 1), ('Y', 1)}), Rational(1, 4)),
                 (frozenset({('X', 2), ('Y', 1)}), Rational(1, 4)),
                 (frozenset({('X', 2), ('Y', 2)}), Rational(1, 4))))
    d = pspace(X + Y).domain
    assert ((X.symbol, 1), (Y.symbol, 2)) in d
    assert ((X.symbol, 0), (Y.symbol, 2)) not in d

    Z = Die('Z', 2)
    d1 = pspace(X + Y).domain
    assert ProductDomain(d1, Z.pspace.domain) == pspace(X + Y + Z).domain
Exemplo n.º 11
0
 def __new__(cls, density):
     density = Dict(density)
     return Basic.__new__(cls, density)