예제 #1
0
def test_iterable_ordered_iter():
    ordered = [list(), tuple(), Tuple(), Matrix([[]])]
    unordered = [set()]
    not_sympy_iterable = [{}, '', u'']
    assert all(ordered_iter(i) for i in ordered)
    assert all(not ordered_iter(i) for i in unordered)
    assert all(iterable(i) for i in ordered + unordered)
    assert all(not iterable(i) for i in not_sympy_iterable)
    assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
예제 #2
0
def test_iterable_ordered_iter():
    ordered = [list(), tuple(), Tuple(), Matrix([[]])]
    unordered = [set()]
    not_sympy_iterable = [{}, '']
    assert all(ordered_iter(i) for i in ordered)
    assert all(not ordered_iter(i) for i in unordered)
    assert all(iterable(i) for i in ordered + unordered)
    assert all(not iterable(i) for i in not_sympy_iterable)
    assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
예제 #3
0
 def ok(a):
     """Return True if the input args for diff are ok"""
     if not a: return False
     if a[0].is_Symbol is False: return False
     s_at = [i for i in range(len(a)) if a[i].is_Symbol]
     n_at = [i for i in range(len(a)) if not a[i].is_Symbol]
     # every symbol is followed by symbol or int
     # every number is followed by a symbol
     return (all([a[i+1].is_Symbol or a[i+1].is_Integer
         for i in s_at if i+1<len(a)]) and
         all([a[i+1].is_Symbol
         for i in n_at if i+1<len(a)]))
예제 #4
0
 def ok(a):
     """Return True if the input args for diff are ok"""
     if not a: return False
     if a[0].is_Symbol is False: return False
     s_at = [i for i in range(len(a)) if a[i].is_Symbol]
     n_at = [i for i in range(len(a)) if not a[i].is_Symbol]
     # every symbol is followed by symbol or int
     # every number is followed by a symbol
     return (all([a[i+1].is_Symbol or a[i+1].is_Integer
         for i in s_at if i+1<len(a)]) and
         all([a[i+1].is_Symbol
         for i in n_at if i+1<len(a)]))
예제 #5
0
파일: polygon.py 프로젝트: Jerryy/sympy
    def __eq__(self, o):
        if not isinstance(o, Polygon) or len(self) != len(o):
            return False

        # See if self can ever be traversed (cw or ccw) from any of its
        # vertices to match all points of o
        n = len(self)
        o0 = o[0]
        for i0 in xrange(n):
            if self[i0] == o0:
                if all(self[(i0 + i) % n] == o[i] for i in xrange(1, n)):
                    return True
                if all(self[(i0 - i) % n] == o[i] for i in xrange(1, n)):
                    return True
        return False
예제 #6
0
    def __eq__(self, o):
        if not isinstance(o, Polygon) or len(self) != len(o):
            return False

        # See if self can ever be traversed (cw or ccw) from any of its
        # vertices to match all points of o
        n = len(self)
        o0 = o[0]
        for i0 in xrange(n):
            if self[i0] == o0:
                if all(self[(i0 + i) % n] == o[i] for i in xrange(1, n)):
                    return True
                if all(self[(i0 - i) % n] == o[i] for i in xrange(1, n)):
                    return True
        return False
예제 #7
0
def generate_derangements(perm):
    """
    Routine to generate derangements.

    TODO: This will be rewritten to use the
    ECO operator approach once the permutations
    branch is in master.

    Examples:
    >>> from sympy.utilities.iterables import generate_derangements
    >>> list(generate_derangements([0,1,2]))
    [[1, 2, 0], [2, 0, 1]]
    >>> list(generate_derangements([0,1,2,3]))
    [[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], \
    [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], \
    [3, 2, 1, 0]]
    >>> list(generate_derangements([0,1,1]))
    []
    """
    indices = range(len(perm))
    p = itertools.permutations(indices)
    for rv in \
            uniq(tuple(perm[i] for i in idx) \
                 for idx in p if all(perm[k] != \
                                     perm[idx[k]] for k in xrange(len(perm)))):
        yield list(rv)
예제 #8
0
파일: iterables.py 프로젝트: Jerryy/sympy
def generate_derangements(perm):
    """
    Routine to generate derangements.

    TODO: This will be rewritten to use the
    ECO operator approach once the permutations
    branch is in master.

    Examples:
    >>> from sympy.utilities.iterables import generate_derangements
    >>> list(generate_derangements([0,1,2]))
    [[1, 2, 0], [2, 0, 1]]
    >>> list(generate_derangements([0,1,2,3]))
    [[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], \
    [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], \
    [3, 2, 1, 0]]
    >>> list(generate_derangements([0,1,1]))
    []
    """
    indices = range(len(perm))
    p = itertools.permutations(indices)
    for rv in \
            uniq(tuple(perm[i] for i in idx) \
                 for idx in p if all(perm[k] != \
                                     perm[idx[k]] for k in xrange(len(perm)))):
        yield list(rv)
예제 #9
0
파일: order.py 프로젝트: sherjilozair/sympy
    def __new__(cls, expr, *symbols, **assumptions):

        expr = sympify(expr).expand()
        if expr is S.NaN:
            return S.NaN

        if symbols:
            symbols = map(sympify, symbols)
            if not all(isinstance(s, Symbol) for s in symbols):
                raise NotImplementedError(
                    'Order at points other than 0 not supported.')
        else:
            symbols = list(expr.free_symbols)

        if expr.is_Order:

            new_symbols = list(expr.variables)
            for s in symbols:
                if s not in new_symbols:
                    new_symbols.append(s)
            if len(new_symbols) == len(expr.variables):
                return expr
            symbols = new_symbols

        elif symbols:

            if expr.is_Add:
                lst = expr.extract_leading_order(*symbols)
                expr = Add(*[f.expr for (e, f) in lst])
            elif expr:
                if len(symbols) > 1:
                    # TODO
                    # We cannot use compute_leading_term because that only
                    # works in one symbol.
                    expr = expr.as_leading_term(*symbols)
                else:
                    expr = expr.compute_leading_term(symbols[0])
                coeff, terms = expr.as_coeff_mul()
                expr = Mul(*[t for t in terms if t.has(*symbols)])

        if expr is S.Zero:
            return expr
        elif not expr.has(*symbols):
            expr = S.One

        # create Order instance:
        symbols.sort(Basic.compare)
        obj = Expr.__new__(cls, expr, *symbols, **assumptions)

        return obj
예제 #10
0
파일: order.py 프로젝트: Jerryy/sympy
    def __new__(cls, expr, *symbols, **assumptions):

        expr = sympify(expr).expand()
        if expr is S.NaN:
            return S.NaN

        if symbols:
            symbols = map(sympify, symbols)
            if not all(isinstance(s, Symbol) for s in symbols):
                raise NotImplementedError('Order at points other than 0 not supported.')
        else:
            symbols = list(expr.free_symbols)

        if expr.is_Order:

            new_symbols = list(expr.variables)
            for s in symbols:
                if s not in new_symbols:
                    new_symbols.append(s)
            if len(new_symbols) == len(expr.variables):
                return expr
            symbols = new_symbols

        elif symbols:

            if expr.is_Add:
                lst = expr.extract_leading_order(*symbols)
                expr = Add(*[f.expr for (e,f) in lst])
            elif expr:
                if len(symbols) > 1:
                    # TODO
                    # We cannot use compute_leading_term because that only
                    # works in one symbol.
                    expr = expr.as_leading_term(*symbols)
                else:
                    expr = expr.compute_leading_term(symbols[0])
                coeff, terms = expr.as_coeff_mul()
                expr = Mul(*[t for t in terms if t.has(*symbols)])

        if expr is S.Zero:
            return expr
        elif not expr.has(*symbols):
            expr = S.One

        # create Order instance:
        symbols.sort(key=cmp_to_key(Basic.compare))
        obj = Expr.__new__(cls, expr, *symbols, **assumptions)

        return obj
예제 #11
0
def test_Subs():
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f = Function('f')

    assert Subs(f(x), x, 0).doit() == f(0)
    assert Subs(f(x**2), x**2, 0).doit() == f(0)
    assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
    assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
    raises(ValueError, 'Subs(f(x, y), (x, y), (0, 0, 1))')
    raises(ValueError, 'Subs(f(x, y), (x, x, y), (0, 0, 1))')

    assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
    assert all([
        isinstance(v, Dummy) for v in Subs(f(x, y), (x, y), (0, 1)).variables
    ])
    assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)

    assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
    assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
    assert Subs(f(x) * y, (x, y), (0, 1)) == Subs(f(y) * x, (y, x), (0, 1))
    assert Subs(f(x) * y, (x, y), (1, 1)) == Subs(f(y) * x, (x, y), (1, 1))

    assert Subs(f(x), x, 0).subs(x, 1) == Subs(f(x), x, 0)
    assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
    assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
    assert Subs(y * f(x), x, y).subs(y, 2) == Subs(2 * f(x), x, 2)
    assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2 * y

    assert Subs(f(x), x, 0).free_symbols == set([])
    assert Subs(f(x, y), x, z).free_symbols == set([y, z])

    assert Subs(f(x).diff(x), x, 0).doit() == Subs(f(x).diff(x), x, 0)
    assert Subs(1 + f(x).diff(x), x, 0).doit() == 1 + Subs(f(x).diff(x), x, 0)
    assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
            2*Subs(Derivative(f(x, 2), x), x, 0)
    assert Subs(y**2 * f(x), x, 0).diff(y) == 2 * y * f(0)

    e = Subs(y**2 * f(x), x, y)
    assert e.diff(y) == e.doit().diff(
        y) == y**2 * Derivative(f(y), y) + 2 * y * f(y)

    assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2 * Subs(f(x), x, 0)
    e1 = Subs(z * f(x), x, 1)
    e2 = Subs(z * f(y), y, 1)
    assert e1 + e2 == 2 * e1
    assert e1.__hash__() == e2.__hash__()
    assert Subs(z * f(x + 1), x, 1) not in [e1, e2]
예제 #12
0
def test_Subs():
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f = Function('f')

    assert Subs(f(x), x, 0).doit() == f(0)
    assert Subs(f(x**2), x**2, 0).doit() == f(0)
    assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
    assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
    raises(ValueError, 'Subs(f(x, y), (x, y), (0, 0, 1))')
    raises(ValueError, 'Subs(f(x, y), (x, x, y), (0, 0, 1))')

    assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
    assert all([
        isinstance(v, Dummy) for v in Subs(f(x, y), (x, y), (0, 1)).variables
    ])
    assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)

    assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
    assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
    assert Subs(f(x) * y, (x, y), (0, 1)) == Subs(f(y) * x, (y, x), (0, 1))
    assert Subs(f(x) * y, (x, y), (1, 1)) == Subs(f(y) * x, (x, y), (1, 1))

    assert Subs(f(x), x, 0).subs(x, 1) == Subs(f(x), x, 0)
    assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
    assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
    assert Subs(y * f(x), x, y).subs(y, 2) == Subs(2 * f(x), x, 2)
    assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2 * y

    assert Subs(f(x), x, 0).free_symbols == set([])
    assert Subs(f(x, y), x, z).free_symbols == set([y, z])

    assert Subs(f(x).diff(x), x, 0).doit() == Subs(f(x).diff(x), x, 0)
    assert Subs(1 + f(x).diff(x), x, 0).doit() == 1 + Subs(f(x).diff(x), x, 0)
    assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
            2*Subs(Derivative(f(x, 2), x), x, 0)
    assert Subs(y**2 * f(x), x, 0).diff(y) == 2 * y * f(0)

    e = Subs(y**2 * f(x), x, y)
    assert e.diff(y) == e.doit().diff(
        y) == y**2 * Derivative(f(y), y) + 2 * y * f(y)

    assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2 * Subs(f(x), x, 0)
    e1 = Subs(z * f(x), x, 1)
    e2 = Subs(z * f(y), y, 1)
    assert e1 + e2 == 2 * e1
    assert e1.__hash__() == e2.__hash__()
    assert Subs(z * f(x + 1), x, 1) not in [e1, e2]
예제 #13
0
def _sympy_tensor_product(*matrices):
    """Compute the tensor product of a sequence of sympy Matrices.

    This is the standard Kronecker product of matrices [1].

    Parameters
    ==========
    matrices : tuple of Matrix instances
        The matrices to take the tensor product of.

    Returns
    =======
    matrix : Matrix
        The tensor product matrix.

    Examples
    ========

        >>> from sympy import I, Matrix, symbols
        >>> from sympy.physics.quantum.matrixutils import _sympy_tensor_product

        >>> m1 = Matrix([[1,2],[3,4]])
        >>> m2 = Matrix([[1,0],[0,1]])
        >>> _sympy_tensor_product(m1, m2)
        [1, 0, 2, 0]
        [0, 1, 0, 2]
        [3, 0, 4, 0]
        [0, 3, 0, 4]
        >>> _sympy_tensor_product(m2, m1)
        [1, 2, 0, 0]
        [3, 4, 0, 0]
        [0, 0, 1, 2]
        [0, 0, 3, 4]

    References
    ==========

    [1] http://en.wikipedia.org/wiki/Kronecker_product
    """
    # Make sure we have a sequence of Matrices
    testmat = [isinstance(m, Matrix) for m in matrices]
    if not all(testmat):
        raise TypeError('Sequence of Matrices expected, got: %s' %
                        repr(matrices))

    # Pull out the first element in the product.
    matrix_expansion = matrices[-1]
    # Do the tensor product working from right to left.
    for mat in reversed(matrices[:-1]):
        rows = mat.rows
        cols = mat.cols
        # Go through each row appending tensor product to.
        # running matrix_expansion.
        for i in range(rows):
            start = matrix_expansion * mat[i * cols]
            # Go through each column joining each item
            for j in range(cols - 1):
                start = start.row_join(matrix_expansion *
                                       mat[i * cols + j + 1])
            # If this is the first element, make it the start of the
            # new row.
            if i == 0:
                next = start
            else:
                next = next.col_join(start)
        matrix_expansion = next
    return matrix_expansion
예제 #14
0
파일: matrixutils.py 프로젝트: Jerryy/sympy
def _sympy_tensor_product(*matrices):
    """Compute the tensor product of a sequence of sympy Matrices.

    This is the standard Kronecker product of matrices [1].

    Parameters
    ==========
    matrices : tuple of Matrix instances
        The matrices to take the tensor product of.

    Returns
    =======
    matrix : Matrix
        The tensor product matrix.

    Examples
    ========

        >>> from sympy import I, Matrix, symbols
        >>> from sympy.physics.quantum.matrixutils import _sympy_tensor_product

        >>> m1 = Matrix([[1,2],[3,4]])
        >>> m2 = Matrix([[1,0],[0,1]])
        >>> _sympy_tensor_product(m1, m2)
        [1, 0, 2, 0]
        [0, 1, 0, 2]
        [3, 0, 4, 0]
        [0, 3, 0, 4]
        >>> _sympy_tensor_product(m2, m1)
        [1, 2, 0, 0]
        [3, 4, 0, 0]
        [0, 0, 1, 2]
        [0, 0, 3, 4]

    References
    ==========

    [1] http://en.wikipedia.org/wiki/Kronecker_product
    """
    # Make sure we have a sequence of Matrices
    testmat = [isinstance(m, Matrix) for m in matrices]
    if not all(testmat):
        raise TypeError(
            'Sequence of Matrices expected, got: %s' % repr(matrices)
        )

    # Pull out the first element in the product.
    matrix_expansion  = matrices[-1]
    # Do the tensor product working from right to left.
    for mat in reversed(matrices[:-1]):
        rows = mat.rows
        cols = mat.cols
        # Go through each row appending tensor product to.
        # running matrix_expansion.
        for i in range(rows):
            start = matrix_expansion*mat[i*cols]
            # Go through each column joining each item
            for j in range(cols-1):
                start = start.row_join(
                    matrix_expansion*mat[i*cols+j+1]
                )
            # If this is the first element, make it the start of the
            # new row.
            if i == 0:
                next = start
            else:
                next = next.col_join(start)
        matrix_expansion = next
    return matrix_expansion