Ejemplo n.º 1
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
    raises(KeyError, lambda: d[2])
    assert len(d) == 3
    assert set(d.keys()) == set((x, y, z))
    assert set(d.values()) == set((S(1), S(2), S(3)))
    assert d.get(5, 'default') == 'default'
    assert x in d and z in d and not 5 in d
    assert d.has(x) and d.has(1)  # SymPy Basic .has method

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

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

    assert set(d.items()) == set((Tuple(x, S(1)), Tuple(y,
                                                        S(2)), Tuple(z, S(3))))
    assert set(d) == set([x, y, z])
    assert str(d) == '{x: 1, y: 2, z: 3}'
    assert d.__repr__() == '{x: 1, y: 2, z: 3}'
Ejemplo 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}"
Ejemplo 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)

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

    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)
Ejemplo n.º 4
0
    def __new__(cls, iterable=None, shape=None, **kwargs):
        from sympy.utilities.iterables import flatten

        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
        shape = Tuple(*map(_sympify, shape))
        cls._check_special_bounds(flat_list, 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 = Basic.__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
Ejemplo n.º 5
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 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 5917
    assert _gcd_terms([S.Zero, S.Zero]) == (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
    eq = x / 2 / y + 1 / x / y
    assert gcd_terms(eq, fraction=True, clear=True) == \
        (x**2 + 2)/(2*x*y)
    assert gcd_terms(eq, fraction=True, clear=False) == \
        (x**2/2 + 1)/(x*y)
    assert gcd_terms(eq, fraction=False, clear=True) == \
        (x + 2/x)/(2*y)
    assert gcd_terms(eq, fraction=False, clear=False) == \
        (x/2 + 1/x)/y
    def _register_as_base_dim(self):
        SymPyDeprecationWarning(deprecated_since_version="1.2",
                                issue=13336,
                                feature="do not call ._register_as_base_dim()",
                                useinstead="DimensionSystem").warn()
        if not self.name.is_Symbol:
            raise TypeError("Base dimensions need to have symbolic name")

        name = self.name
        if name in dimsys_default.dimensional_dependencies:
            raise IndexError("already in dependencies dict")
        # Horrible code:
        d = dict(dimsys_default.dimensional_dependencies)
        d[name] = Dict({name: 1})
        dimsys_default._args = (dimsys_default.args[:2] + (Dict(d), ))
Ejemplo n.º 7
0
def test_latex_dict():
    d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4}
    assert latex(
        d
    ) == '\\begin{Bmatrix}1 : 1, & x : 3, & x^{2} : 2, & x^{3} : 4\\end{Bmatrix}'
    D = Dict(d)
    assert latex(
        D
    ) == '\\begin{Bmatrix}1 : 1, & x : 3, & x^{2} : 2, & x^{3} : 4\\end{Bmatrix}'
Ejemplo n.º 8
0
def rv(name, cls, *args):
    args = list(map(sympify, args))
    i = 0
    while i < len(args):  # Converting to Dict since dict is not hashable
        if isinstance(args[i], dict):
            args[i] = Dict(args[i])
        i += 1
    dist = cls(*args)
    dist.check(*args)
    return SingleFinitePSpace(name, dist).value
Ejemplo n.º 9
0
 def _new(cls, *args, **kwargs):
     s = MutableSparseMatrix(*args)
     rows = Integer(s.rows)
     cols = Integer(s.cols)
     mat = Dict(s._smat)
     obj = Basic.__new__(cls, rows, cols, mat)
     obj.rows = s.rows
     obj.cols = s.cols
     obj._smat = s._smat
     return obj
Ejemplo n.º 10
0
def test_RoutineCall():
    test = routine('test', (a, b, c), expr)
    rcall = test(1, 2, 3)
    assert rcall.routine == test
    assert rcall.arguments == (1, 2, 3)
    assert rcall.returns == ScalarRoutineCallResult(rcall, -1)
    assert rcall.inplace == Dict()
    # Multiple results
    test = routine('test', (a, b, c, out), (expr, inp_expr))
    rcall = test(1, 2, 3, out)
    assert rcall.arguments == (1, 2, 3, out)
    assert rcall.returns == ScalarRoutineCallResult(rcall, -1)
    assert rcall.inplace == Dict({out: ScalarRoutineCallResult(rcall, out)})
    # Matrix result
    test = routine('test', (a, b, c, x), (expr, mat_expr))
    rcall = test(1, 2, 3, x)
    assert rcall.arguments == (1, 2, 3, x)
    assert rcall.returns == ScalarRoutineCallResult(rcall, -1)
    assert rcall.inplace == Dict({x: MatrixRoutineCallResult(rcall, x)})
Ejemplo n.º 11
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
Ejemplo n.º 12
0
 def __new__(cls, density):
     density = Dict(density)
     for k in density.values():
         k_sym = sympify(k)
         if fuzzy_not(
                 fuzzy_and(
                     (k_sym.is_nonnegative, (k_sym - 1).is_nonpositive))):
             raise ValueError(
                 "Probability at a point must be between 0 and 1.")
     sum_sym = sum(density.values())
     if sum_sym != 1:
         raise ValueError("Total Probability must be equal to 1.")
     return Basic.__new__(cls, density)
Ejemplo n.º 13
0
    def _visit_Dict(self, stmt):

        d = {}
        for key, value in zip(stmt.keys, stmt.values):

            key = self._visit(key)
            value = self._visit(value)

            # sympy does not allow keys to be strings

            if isinstance(key, LiteralString):
                errors.report(SYMPY_RESTRICTION_DICT_KEYS, severity='error')

            d[key] = value
        return Dict(d)
Ejemplo n.º 14
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 = Basic.__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
Ejemplo n.º 15
0
def test_dict_set():
    a, b, c = map(Wild, 'abc')

    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
Ejemplo n.º 16
0
    def _visit_DictNode(self, stmt):

        d = {}
        for i in stmt.value:
            if not isinstance(i, DictitemNode):
                raise PyccelSyntaxError('Expecting a DictitemNode')

            key = self._visit(i.key)
            value = self._visit(i.value)

            # sympy does not allow keys to be strings

            if isinstance(key, str):
                errors.report(SYMPY_RESTRICTION_DICT_KEYS, severity='error')

            d[key] = value
        return Dict(d)
Ejemplo n.º 17
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
    raises(KeyError, lambda: d[2])
    raises(KeyError, lambda: d['2'])
    assert len(d) == 3
    assert set(d.keys()) == {x, y, z}
    assert set(d.values()) == {S.One, S(2), S(3)}
    assert d.get(5, 'default') == 'default'
    assert d.get('5', 'default') == 'default'
    assert x in d and z in d and not 5 in d and not '5' in d
    assert d.has(x) and d.has(1)  # SymPy Basic .has method

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

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

    assert set(d.items()) == {Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))}
    assert set(d) == {x, y, z}
    assert str(d) == '{x: 1, y: 2, z: 3}'
    assert d.__repr__() == '{x: 1, y: 2, z: 3}'

    # Test creating a Dict from a Dict.
    d = Dict({x: 1, y: 2, z: 3})
    assert d == Dict(d)

    # Test for supporting defaultdict
    d = defaultdict(int)
    assert d[x] == 0
    assert d[y] == 0
    assert d[z] == 0
    assert Dict(d)
    d = Dict(d)
    assert len(d) == 3
    assert set(d.keys()) == {x, y, z}
    assert set(d.values()) == {S.Zero, S.Zero, S.Zero}
Ejemplo n.º 18
0
 def parse_dict(d):
     return Dict({parse_dim_name(i): j for i, j in d.items()})
Ejemplo n.º 19
0
    def __new__(cls, base_dims, derived_dims=[], dimensional_dependencies={}, name=None, descr=None):
        dimensional_dependencies = dict(dimensional_dependencies)

        if (name is not None) or (descr is not None):
            SymPyDeprecationWarning(
                deprecated_since_version="1.2",
                issue=13336,
                useinstead="do not define a `name` or `descr`",
            ).warn()

        def parse_dim(dim):
            if isinstance(dim, string_types):
                dim = Dimension(Symbol(dim))
            elif isinstance(dim, Dimension):
                pass
            elif isinstance(dim, Symbol):
                dim = Dimension(dim)
            else:
                raise TypeError("%s wrong type" % dim)
            return dim

        base_dims = [parse_dim(i) for i in base_dims]
        derived_dims = [parse_dim(i) for i in derived_dims]

        for dim in base_dims:
            dim = dim.name
            if (dim in dimensional_dependencies
                and (len(dimensional_dependencies[dim]) != 1 or
                dimensional_dependencies[dim].get(dim, None) != 1)):
                raise IndexError("Repeated value in base dimensions")
            dimensional_dependencies[dim] = Dict({dim: 1})

        def parse_dim_name(dim):
            if isinstance(dim, Dimension):
                return dim.name
            elif isinstance(dim, string_types):
                return Symbol(dim)
            elif isinstance(dim, Symbol):
                return dim
            else:
                raise TypeError("unrecognized type %s for %s" % (type(dim), dim))

        for dim in dimensional_dependencies.keys():
            dim = parse_dim(dim)
            if (dim not in derived_dims) and (dim not in base_dims):
                derived_dims.append(dim)

        def parse_dict(d):
            return Dict({parse_dim_name(i): j for i, j in d.items()})

        # Make sure everything is a SymPy type:
        dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
                                    dimensional_dependencies.items()}

        for dim in derived_dims:
            if dim in base_dims:
                raise ValueError("Dimension %s both in base and derived" % dim)
            if dim.name not in dimensional_dependencies:
                # TODO: should this raise a warning?
                dimensional_dependencies[dim] = Dict({dim.name: 1})

        base_dims.sort(key=default_sort_key)
        derived_dims.sort(key=default_sort_key)

        base_dims = Tuple(*base_dims)
        derived_dims = Tuple(*derived_dims)
        dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
        obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
        return obj
Ejemplo n.º 20
0
def test_factorint():
    assert primefactors(123456) == [2, 3, 643]
    assert factorint(0) == {0: 1}
    assert factorint(1) == {}
    assert factorint(-1) == {-1: 1}
    assert factorint(-2) == {-1: 1, 2: 1}
    assert factorint(-16) == {-1: 1, 2: 4}
    assert factorint(2) == {2: 1}
    assert factorint(126) == {2: 1, 3: 2, 7: 1}
    assert factorint(123456) == {2: 6, 3: 1, 643: 1}
    assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
    assert factorint(64015937) == {7993: 1, 8009: 1}
    assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
    #issue 19683
    assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
    #issue 17676
    assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
    assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
    assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}

    assert factorint(0, multiple=True) == [0]
    assert factorint(1, multiple=True) == []
    assert factorint(-1, multiple=True) == [-1]
    assert factorint(-2, multiple=True) == [-1, 2]
    assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
    assert factorint(2, multiple=True) == [2]
    assert factorint(24, multiple=True) == [2, 2, 2, 3]
    assert factorint(126, multiple=True) == [2, 3, 3, 7]
    assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
    assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
    assert factorint(64015937, multiple=True) == [7993, 8009]
    assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]

    assert factorint(fac(1, evaluate=False)) == {}
    assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
    assert factorint(fac(15, evaluate=False)) == \
        {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
    assert factorint(fac(20, evaluate=False)) == \
        {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
    assert factorint(fac(23, evaluate=False)) == \
        {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}

    assert multiproduct(factorint(fac(200))) == fac(200)
    assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
    for b, e in factorint(fac(150)).items():
        assert e == fac_multiplicity(150, b)
    for b, e in factorint(fac(150, evaluate=False)).items():
        assert e == fac_multiplicity(150, b)
    assert factorint(103005006059**7) == {103005006059: 7}
    assert factorint(31337**191) == {31337: 191}
    assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
        {2: 1000, 3: 500, 257: 127, 383: 60}
    assert len(factorint(fac(10000))) == 1229
    assert len(factorint(fac(10000, evaluate=False))) == 1229
    assert factorint(12932983746293756928584532764589230) == \
        {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
    assert factorint(727719592270351) == {727719592270351: 1}
    assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
    for n in range(60000):
        assert multiproduct(factorint(n)) == n
    assert pollard_rho(2**64 + 1, seed=1) == 274177
    assert pollard_rho(19, seed=1) is None
    assert factorint(3, limit=2) == {3: 1}
    assert factorint(12345) == {3: 1, 5: 1, 823: 1}
    assert factorint(
        12345, limit=3) == {4115: 1, 3: 1}  # the 5 is greater than the limit
    assert factorint(1, limit=1) == {}
    assert factorint(0, 3) == {0: 1}
    assert factorint(12, limit=1) == {12: 1}
    assert factorint(30, limit=2) == {2: 1, 15: 1}
    assert factorint(16, limit=2) == {2: 4}
    assert factorint(124, limit=3) == {2: 2, 31: 1}
    assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
    p1 = nextprime(2**32)
    p2 = nextprime(2**16)
    p3 = nextprime(p2)
    assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
    assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
    assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
    assert factorint(primorial(17) + 1, use_pm1=0) == \
        {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
    # when prime b is closer than approx sqrt(8*p) to prime p then they are
    # "close" and have a trivial factorization
    a = nextprime(2**2**8)  # 78 digits
    b = nextprime(a + 2**2**4)
    assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))

    raises(ValueError, lambda: pollard_rho(4))
    raises(ValueError, lambda: pollard_pm1(3))
    raises(ValueError, lambda: pollard_pm1(10, B=2))
    # verbose coverage
    n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
    assert 'with primes' in capture(lambda: factorint(n, verbose=1))
    capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))

    n = nextprime(2**17)
    capture(lambda: factorint(n**3, verbose=1))  # perfect power termination
    capture(lambda: factorint(2*n, verbose=1))  # factoring complete msg

    # exceed 1st
    n = nextprime(2**17)
    n *= nextprime(n)
    assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
    n *= nextprime(n)
    assert len(factorint(n)) == 3
    assert len(factorint(n, limit=p1)) == 3
    n *= nextprime(2*n)
    # exceed 2nd
    assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
    assert capture(
        lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
    # non-prime pm1 result
    n = nextprime(8069)
    n *= nextprime(2*n)*nextprime(2*n, 2)
    capture(lambda: factorint(n, verbose=1))  # non-prime pm1 result
    # factor fermat composite
    p1 = nextprime(2**17)
    p2 = nextprime(2*p1)
    assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
    # Test for non integer input
    raises(ValueError, lambda: factorint(4.5))
    # test dict/Dict input
    sans = '2**10*3**3'
    n = {4: 2, 12: 3}
    assert str(factorint(n)) == sans
    assert str(factorint(Dict(n))) == sans
Ejemplo n.º 21
0
def test_ndim_array_initiation():
    arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0, ))
    assert len(arr_with_no_elements) == 0
    assert arr_with_no_elements.rank() == 1

    raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0, )))
    raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0, )))
    raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=()))

    raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0, )))
    raises(ValueError,
           lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0, )))
    raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=()))

    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[:] == ImmutableDenseNDimArray([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[:] == ImmutableDenseNDimArray([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

    shape = (long(3), long(3))
    array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape)
    assert len(array_with_long_shape) == 3 * 3
    assert array_with_long_shape.shape == shape
    assert array_with_long_shape[long(0), long(0)] == 0
    assert array_with_long_shape.rank() == 2

    vector_with_long_shape = ImmutableDenseNDimArray(range(5), long(5))
    assert len(vector_with_long_shape) == 5
    assert vector_with_long_shape.shape == (long(5), )
    assert vector_with_long_shape.rank() == 1
    raises(ValueError, lambda: vector_with_long_shape[long(5)])

    from sympy.abc import x
    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
        rank_zero_array = ArrayType(x)
        assert len(rank_zero_array) == 1
        assert rank_zero_array.shape == ()
        assert rank_zero_array.rank() == 0
        assert rank_zero_array[()] == x
        raises(ValueError, lambda: rank_zero_array[0])
Ejemplo n.º 22
0
 def _new(cls, *args, **kwargs):
     s = SparseMatrix(*args)
     rows = Integer(s.rows)
     cols = Integer(s.cols)
     mat = Dict(s._smat)
     return Basic.__new__(cls, rows, cols, mat)
Ejemplo n.º 23
0
 def __new__(cls, density):
     density = Dict(density)
     return Basic.__new__(cls, density)
Ejemplo n.º 24
0
def to_sympy(stmt):

    if isinstance(stmt, NamedAbstraction):
        name = stmt.name
        expr = to_sympy(stmt.abstraction)
        return expr

    elif isinstance(stmt, Abstraction):
        args = [to_sympy(i) for i in stmt.args]
        expr = to_sympy(stmt.expr)

        func = Lambda(args, expr)
        # add a name for the lambda expression
        # TODO improve this by implementing a new class
        #      for Lambda in lampy
        setattr(func, 'name', 'lambda_{}'.format(random_string(4)))

        return func

    elif isinstance(stmt, Application):
        name = stmt.name
        first = to_sympy(stmt.args[0])

        if name in _internal_map_functors:
            if not isinstance(first, (Lambda, BasicMap)):
                func_name = str(stmt.args[0])
                func = FunctionSymbol(func_name)

            else:
                func = first

            arguments = stmt.args[1:]
            arguments = [to_sympy(i) for i in arguments]

            return _map_registery[name](func, arguments)

        elif name == 'reduce':
            if not (len(stmt.args) == 2):
                raise ValueError('Wrong number of arguments for reduce')

            op = stmt.args[0]
            if not op in _internal_reduction_operators:
                msg = "Only 'add' and 'mul' reduction operators are available"
                raise ValueError(msg)

            target = to_sympy(stmt.args[1])

            if op == 'add':
                return AddReduce(target)

            elif op == 'mul':
                return MulReduce(target)

        elif name == 'partial':
            if not isinstance(first, Lambda):
                func_name = str(stmt.args[0])
                func = FunctionSymbol(func_name)

            else:
                func = first

            arguments = stmt.args[1:]
            arguments = [to_sympy(i) for i in arguments]

            assert (all([isinstance(i, Tuple) for i in arguments]))

            # ...
            d = {}
            for i in arguments:
                key = i[0]
                value = i[1]

                d[key] = value

            arguments = Dict(d)
            # ...

            return PartialFunction(func, arguments)

        else:
            args = [to_sympy(i) for i in stmt.args]

            return Function(name)(*args)

    elif isinstance(stmt, (int, float)):
        return stmt

    elif isinstance(stmt, str):
        if stmt == '_':
            return _

        else:
            return sympify(stmt)

    elif isinstance(stmt, ValuedItem):
        key = to_sympy(stmt.name)
        value = to_sympy(stmt.value)
        return Tuple(key, value)

    else:
        raise TypeError('Not implemented for {}'.format(type(stmt)))
Ejemplo n.º 25
0
def test_diagram():
    A = Object("A")
    B = Object("B")
    C = Object("C")

    f = NamedMorphism(A, B, "f")
    g = NamedMorphism(B, C, "g")
    id_A = IdentityMorphism(A)
    id_B = IdentityMorphism(B)

    empty = EmptySet()

    # Test the addition of identities.
    d1 = Diagram([f])

    assert d1.objects == FiniteSet(A, B)
    assert d1.hom(A, B) == (FiniteSet(f), empty)
    assert d1.hom(A, A) == (FiniteSet(id_A), empty)
    assert d1.hom(B, B) == (FiniteSet(id_B), empty)

    assert d1 == Diagram([id_A, f])
    assert d1 == Diagram([f, f])

    # Test the addition of composites.
    d2 = Diagram([f, g])
    homAC = d2.hom(A, C)[0]

    assert d2.objects == FiniteSet(A, B, C)
    assert g * f in d2.premises.keys()
    assert homAC == FiniteSet(g * f)

    # Test equality, inequality and hash.
    d11 = Diagram([f])

    assert d1 == d11
    assert d1 != d2
    assert hash(d1) == hash(d11)

    d11 = Diagram({f: "unique"})
    assert d1 != d11

    # Make sure that (re-)adding composites (with new properties)
    # works as expected.
    d = Diagram([f, g], {g * f: "unique"})
    assert d.conclusions == Dict({g * f: FiniteSet("unique")})

    # Check the hom-sets when there are premises and conclusions.
    assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
    d = Diagram([f, g], [g * f])
    assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))

    # Check how the properties of composite morphisms are computed.
    d = Diagram({f: ["unique", "isomorphism"], g: "unique"})
    assert d.premises[g * f] == FiniteSet("unique")

    # Check that conclusion morphisms with new objects are not allowed.
    d = Diagram([f], [g])
    assert d.conclusions == Dict({})

    # Test an empty diagram.
    d = Diagram()
    assert d.premises == Dict({})
    assert d.conclusions == Dict({})
    assert d.objects == empty

    # Check a SymPy Dict object.
    d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"}))
    assert d.premises[g * f] == FiniteSet("unique")

    # Check the addition of components of composite morphisms.
    d = Diagram([g * f])
    assert f in d.premises
    assert g in d.premises

    # Check subdiagrams.
    d = Diagram([f, g], {g * f: "unique"})

    d1 = Diagram([f])
    assert d.is_subdiagram(d1)
    assert not d1.is_subdiagram(d)

    d = Diagram([NamedMorphism(B, A, "f'")])
    assert not d.is_subdiagram(d1)
    assert not d1.is_subdiagram(d)

    d1 = Diagram([f, g], {g * f: ["unique", "something"]})
    assert not d.is_subdiagram(d1)
    assert not d1.is_subdiagram(d)

    d = Diagram({f: "blooh"})
    d1 = Diagram({f: "bleeh"})
    assert not d.is_subdiagram(d1)
    assert not d1.is_subdiagram(d)

    d = Diagram([f, g], {f: "unique", g * f: "veryunique"})
    d1 = d.subdiagram_from_objects(FiniteSet(A, B))
    assert d1 == Diagram([f], {f: "unique"})
    raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A,
           Object("D"))))

    raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"}))