Example #1
0
    def __new__(cls, partition):
        """
        Generates a new partition object.

        This method also verifies if the arguments passed are
        valid and raises a ValueError if they are not.

        Examples
        ========

        >>> from sympy.combinatorics.partitions import Partition
        >>> a = Partition([[1, 2], [3]])
        >>> a
        {{1, 2}, {3}}
        >>> a.partition
        [[1, 2], [3]]
        >>> len(a)
        2
        >>> a.members
        (1, 2, 3)

        """
        args = partition
        if not all(isinstance(part, list) for part in args):
            raise ValueError("Partition should be a list of lists.")

        # sort so we have a canonical reference for RGS
        partition = sorted(sum(partition, []), key=default_sort_key)
        if has_dups(partition):
            raise ValueError("Partition contained duplicated elements.")

        obj = C.FiniteSet.__new__(cls, list(map(C.FiniteSet, args)))
        obj.members = tuple(partition)
        obj.size = len(partition)
        return obj
Example #2
0
    def __new__(cls, partition):
        """
        Generates a new partition object.

        This method also verifies if the arguments passed are
        valid and raises a ValueError if they are not.

        Examples
        ========

        >>> from sympy.combinatorics.partitions import Partition
        >>> a = Partition([[1, 2], [3]])
        >>> a
        {{1, 2}, {3}}
        >>> a.partition
        [[1, 2], [3]]
        >>> len(a)
        2
        >>> a.members
        (1, 2, 3)

        """
        args = partition
        if not all(isinstance(part, list) for part in args):
            raise ValueError("Partition should be a list of lists.")

        # sort so we have a canonical reference for RGS
        partition = sorted(sum(partition, []), key=default_sort_key)
        if has_dups(partition):
            raise ValueError("Partition contained duplicated elements.")

        obj = C.FiniteSet.__new__(cls, map(C.FiniteSet, args))
        obj.members = tuple(partition)
        obj.size = len(partition)
        return obj
Example #3
0
    def preprocess(cls, gens):
        if isinstance(gens, Basic):
            gens = (gens, )
        elif len(gens) == 1 and hasattr(gens[0], '__iter__'):
            gens = gens[0]

        if gens == (None, ):
            gens = ()
        elif has_dups(gens):
            raise GeneratorsError("duplicated generators: %s" % str(gens))
        elif any(gen.is_commutative is False for gen in gens):
            raise GeneratorsError("non-commutative generators: %s" % str(gens))

        return tuple(gens)
Example #4
0
    def preprocess(cls, gens):
        if isinstance(gens, Basic):
            gens = (gens,)
        elif len(gens) == 1 and hasattr(gens[0], '__iter__'):
            gens = gens[0]

        if gens == (None,):
            gens = ()
        elif has_dups(gens):
            raise GeneratorsError("duplicated generators: %s" % str(gens))
        elif any(gen.is_commutative is False for gen in gens):
            raise GeneratorsError("non-commutative generators: %s" % str(gens))

        return tuple(gens)
Example #5
0
    def preprocess(cls, gens):
        from sympy import Wild, Symbol
        from sympy.tensor.indexed import Slice, Indexed
        from sympy.functions.elementary.exponential import ExpBase
        if isinstance(gens, Basic):
            gens = (gens, )
        elif len(gens) == 1 and hasattr(
                gens[0], '__iter__') and not isinstance(
                    gens[0], (Wild, Slice, Indexed, Symbol, ExpBase)):
            gens = gens[0]

        if gens == (None, ):
            gens = ()
        elif has_dups(gens):
            raise GeneratorsError("duplicated generators: %s" % str(gens))


#         elif any(gen.is_commutative == False for gen in gens):
#             raise GeneratorsError("non-commutative generators: %s" % str(gens))

        return tuple(gens)
Example #6
0
def test_has_dups():
    assert has_dups(set()) is False
    assert has_dups(list(range(3))) is False
    assert has_dups([1, 2, 1]) is True
Example #7
0
 def eval(cls, *args):
     if all(isinstance(a, (int, Integer)) for a in args):
         return eval_levicivita(*args)
     if has_dups(args):
         return S.Zero
Example #8
0
def pde_separate(eq, fun, sep, strategy='mul'):
    """Separate variables in partial differential equation either by additive
    or multiplicative separation approach. It tries to rewrite an equation so
    that one of the specified variables occurs on a different side of the
    equation than the others.

    :param eq: Partial differential equation

    :param fun: Original function F(x, y, z)

    :param sep: List of separated functions [X(x), u(y, z)]

    :param strategy: Separation strategy. You can choose between additive
        separation ('add') and multiplicative separation ('mul') which is
        default.

    Examples
    ========

    >>> from sympy import E, Eq, Function, pde_separate, Derivative as D
    >>> from sympy.abc import x, t
    >>> u, X, T = map(Function, 'uXT')

    >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
    >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='add')
    [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]

    >>> eq = Eq(D(u(x, t), x, 2), D(u(x, t), t, 2))
    >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='mul')
    [Derivative(X(x), x, x)/X(x), Derivative(T(t), t, t)/T(t)]

    See Also
    ========
    pde_separate_add, pde_separate_mul
    """

    do_add = False
    if strategy == 'add':
        do_add = True
    elif strategy == 'mul':
        do_add = False
    else:
        assert ValueError('Unknown strategy: %s' % strategy)

    if isinstance(eq, Equality):
        if eq.rhs != 0:
            return pde_separate(Eq(eq.lhs - eq.rhs), fun, sep, strategy)
    assert eq.rhs == 0

    # Handle arguments
    orig_args = list(fun.args)
    subs_args = []
    for s in sep:
        for j in range(0, len(s.args)):
            subs_args.append(s.args[j])

    if do_add:
        functions = reduce(operator.add, sep)
    else:
        functions = reduce(operator.mul, sep)

    # Check whether variables match
    if len(subs_args) != len(orig_args):
        raise ValueError("Variable counts do not match")
    # Check for duplicate arguments like  [X(x), u(x, y)]
    if has_dups(subs_args):
        raise ValueError("Duplicate substitution arguments detected")
    # Check whether the variables match
    if set(orig_args) != set(subs_args):
        raise ValueError("Arguments do not match")

    # Substitute original function with separated...
    result = eq.lhs.subs(fun, functions).doit()

    # Divide by terms when doing multiplicative separation
    if not do_add:
        eq = 0
        for i in result.args:
            eq += i/functions
        result = eq

    svar = subs_args[0]
    dvar = subs_args[1:]
    return _separate(result, svar, dvar)
Example #9
0
 def eval(cls, *args):
     if all(isinstance(a, (int, Integer)) for a in args):
         return eval_levicivita(*args)
     if has_dups(args):
         return S.Zero
Example #10
0
def test_has_dups():
    assert has_dups(set()) is False
    assert has_dups(range(3)) is False
    assert has_dups([1, 2, 1]) is True
Example #11
0
    def __new__(cls, sym, condition, base_set=S.UniversalSet):
        from sympy.core.function import BadSignatureError
        from sympy.utilities.iterables import flatten, has_dups
        sym = _sympify(sym)
        flat = flatten([sym])
        if has_dups(flat):
            raise BadSignatureError("Duplicate symbols detected")
        base_set = _sympify(base_set)
        if not isinstance(base_set, Set):
            raise TypeError('base set should be a Set object, not %s' %
                            base_set)
        condition = _sympify(condition)

        if isinstance(condition, FiniteSet):
            condition_orig = condition
            temp = (Eq(lhs, 0) for lhs in condition)
            condition = And(*temp)
            SymPyDeprecationWarning(
                feature="Using {} for condition".format(condition_orig),
                issue=17651,
                deprecated_since_version='1.5',
                useinstead="{} for condition".format(condition)).warn()

        condition = as_Boolean(condition)

        if condition is S.true:
            return base_set

        if condition is S.false:
            return S.EmptySet

        if isinstance(base_set, EmptySet):
            return base_set

        # no simple answers, so now check syms
        for i in flat:
            if not getattr(i, '_diff_wrt', False):
                raise ValueError('`%s` is not symbol-like' % i)

        if base_set.contains(sym) is S.false:
            raise TypeError('sym `%s` is not in base_set `%s`' %
                            (sym, base_set))

        know = None
        if isinstance(base_set, FiniteSet):
            sifted = sift(base_set,
                          lambda _: fuzzy_bool(condition.subs(sym, _)))
            if sifted[None]:
                know = FiniteSet(*sifted[True])
                base_set = FiniteSet(*sifted[None])
            else:
                return FiniteSet(*sifted[True])

        if isinstance(base_set, cls):
            s, c, b = base_set.args

            def sig(s):
                return cls(s, Eq(adummy, 0)).as_dummy().sym

            sa, sb = map(sig, (sym, s))
            if sa != sb:
                raise BadSignatureError('sym does not match sym of base set')
            reps = dict(zip(flatten([sym]), flatten([s])))
            if s == sym:
                condition = And(condition, c)
                base_set = b
            elif not c.free_symbols & sym.free_symbols:
                reps = {v: k for k, v in reps.items()}
                condition = And(condition, c.xreplace(reps))
                base_set = b
            elif not condition.free_symbols & s.free_symbols:
                sym = sym.xreplace(reps)
                condition = And(condition.xreplace(reps), c)
                base_set = b

        # flatten ConditionSet(Contains(ConditionSet())) expressions
        if isinstance(condition, Contains) and (sym == condition.args[0]):
            if isinstance(condition.args[1], Set):
                return condition.args[1].intersect(base_set)

        rv = Basic.__new__(cls, sym, condition, base_set)
        return rv if know is None else Union(know, rv)