Source code for sympy.core.assumptions

This module contains the machinery handling assumptions.

All symbolic objects have assumption attributes that can be accessed via
.is_<assumption name> attribute.

Assumptions determine certain properties of symbolic objects and can
have 3 possible values: True, False, None.  True is returned if the
object has the property and False is returned if it doesn't or can't
(i.e. doesn't make sense):

    >>> from sympy import I
    >>> I.is_algebraic
    >>> I.is_real
    >>> I.is_prime

When the property cannot be determined (or when a method is not
implemented) None will be returned, e.g. a generic symbol, x, may or
may not be positive so a value of None is returned for x.is_positive.

By default, all symbolic values are in the largest set in the given context
without specifying the property. For example, a symbol that has a property
being integer, is also real, complex, etc.

Here follows a list of possible assumption names:

.. glossary::

        object commutes with any other object with
        respect to multiplication operation.

        object can have only values from the set
        of complex numbers.

        object value is a number that can be written as a real
        number multiplied by the imaginary unit ``I``.  See
        [3]_.  Please note, that ``0`` is not considered to be an
        imaginary number, see
        `issue #7649 <>`_.

        object can have only values from the set
        of real numbers.

        object can have only values from the set
        of integers.

        object can have only values from the set of
        odd (even) integers [2]_.

        object is a natural number greater than ``1`` that has
        no positive divisors other than ``1`` and itself.  See [6]_.

        object is a positive integer that has at least one positive
        divisor other than ``1`` or the number itself.  See [4]_.

        object has the value of ``0``.

        object is a real number that is not zero.

        object can have only values from the set
        of rationals.

        object can have only values from the set
        of algebraic numbers [11]_.

        object can have only values from the set
        of transcendental numbers [10]_.

        object value cannot be represented exactly by Rational, see [5]_.

        object absolute value is bounded (arbitrarily large).
        See [7]_, [8]_, [9]_.

        object can have only negative (nonnegative)
        values [1]_.

        object can have only positive (only
        nonpositive) values.

        object belongs to the field of hermitian
        (antihermitian) operators.


    >>> from sympy import Symbol
    >>> x = Symbol('x', real=True); x
    >>> x.is_real
    >>> x.is_complex

See Also

.. seealso::



Assumption values are stored in obj._assumptions dictionary or
are returned by getter methods (with property decorators) or are
attributes of objects/classes.


.. [1]
.. [2]
.. [3]
.. [4]
.. [5]
.. [6]
.. [7]
.. [8]
.. [9]
.. [10]
.. [11]

from __future__ import print_function, division

from sympy.core.facts import FactRules, FactKB
from sympy.core.core import BasicMeta
from sympy.core.compatibility import integer_types

from random import shuffle

_assume_rules = FactRules([

    'integer        ->  rational',
    'rational       ->  real',
    'rational       ->  algebraic',
    'algebraic      ->  complex',
    'real           ->  complex',
    'real           ->  hermitian',
    'imaginary      ->  complex',
    'imaginary      ->  antihermitian',
    'complex        ->  commutative',

    'odd            ==  integer & !even',
    'even           ==  integer & !odd',

    'real           ==  negative | zero | positive',
    'transcendental ==  complex & !algebraic',

    'negative       ==  nonpositive & nonzero',
    'positive       ==  nonnegative & nonzero',
    'zero           ==  nonnegative & nonpositive',

    'nonpositive    ==  real & !positive',
    'nonnegative    ==  real & !negative',

    'zero           ->  even & finite',

    'prime          ->  integer & positive',
    'composite      ->  integer & positive & !prime',
    '!composite     ->  !positive | !even | prime',

    'irrational     ==  real & !rational',

    'imaginary      ->  !real',

    'infinite       ->  !finite',
    'noninteger     ==  real & !integer',
    'nonzero        ==  real & !zero',

_assume_defined = _assume_rules.defined_facts.copy()
_assume_defined = frozenset(_assume_defined)

class StdFactKB(FactKB):
    """A FactKB specialised for the built-in rules

    This is the only kind of FactKB that Basic objects should use.
    rules = _assume_rules

    def __init__(self, facts=None):
        # save a copy of the facts dict
        if not facts:
            self._generator = {}
        elif not isinstance(facts, FactKB):
            self._generator = facts.copy()
            self._generator = facts.generator
        if facts:

    def copy(self):
        return self.__class__(self)

    def generator(self):
        return self._generator.copy()

def as_property(fact):
    """Convert a fact name to the name of the corresponding property"""
    return 'is_%s' % fact

def make_property(fact):
    """Create the automagic property corresponding to a fact."""

    def getit(self):
            return self._assumptions[fact]
        except KeyError:
            if self._assumptions is self.default_assumptions:
                self._assumptions = self.default_assumptions.copy()
            return _ask(fact, self)

    getit.func_name = as_property(fact)
    return property(getit)

def _ask(fact, obj):
    Find the truth value for a property of an object.

    This function is called when a request is made to see what a fact
    value is.

    For this we use several techniques:

    First, the fact-evaluation function is tried, if it exists (for
    example _eval_is_integer). Then we try related facts. For example

        rational   -->   integer

    another example is joined rule:

        integer & !odd  --> even

    so in the latter case if we are looking at what 'even' value is,
    'integer' and 'odd' facts will be asked.

    In all cases, when we settle on some fact value, its implications are
    deduced, and the result is cached in ._assumptions.
    assumptions = obj._assumptions
    handler_map = obj._prop_handler

    # Store None into the assumptions so that recursive attempts at
    # evaluating the same fact don't trigger infinite recursion.
    assumptions._tell(fact, None)

    # First try the assumption evaluation function if it exists
        evaluate = handler_map[fact]
    except KeyError:
        a = evaluate(obj)
        if a is not None:
            assumptions.deduce_all_facts(((fact, a),))
            return a

    # Try assumption's prerequisites
    prereq = list(_assume_rules.prereq[fact])
    for pk in prereq:
        if pk in assumptions:
        if pk in handler_map:
            _ask(pk, obj)

            # we might have found the value of fact
            ret_val = assumptions.get(fact)
            if ret_val is not None:
                return ret_val

    # Note: the result has already been cached
    return None

class ManagedProperties(BasicMeta):
    """Metaclass for classes with old-style assumptions"""
    def __init__(cls, *args, **kws):
        BasicMeta.__init__(cls, *args, **kws)

        local_defs = {}
        for k in _assume_defined:
            attrname = as_property(k)
            v = cls.__dict__.get(attrname, '')
            if isinstance(v, (bool, integer_types, type(None))):
                if v is not None:
                    v = bool(v)
                local_defs[k] = v

        defs = {}
        for base in reversed(cls.__bases__):
            assumptions = getattr(base, '_explicit_class_assumptions', None)
            if assumptions is not None:

        cls._explicit_class_assumptions = defs
        cls.default_assumptions = StdFactKB(defs)

        cls._prop_handler = {}
        for k in _assume_defined:
            eval_is_meth = getattr(cls, '_eval_is_%s' % k, None)
            if eval_is_meth is not None:
                cls._prop_handler[k] = eval_is_meth

        # Put definite results directly into the class dict, for speed
        for k, v in cls.default_assumptions.items():
            setattr(cls, as_property(k), v)

        # protection e.g. for Integer.is_even=F <- (Rational.is_integer=F)
        derived_from_bases = set()
        for base in cls.__bases__:
            default_assumptions = getattr(base, 'default_assumptions', None)
            # is an assumption-aware class
            if default_assumptions is not None:

        for fact in derived_from_bases - set(cls.default_assumptions):
            pname = as_property(fact)
            if pname not in cls.__dict__:
                setattr(cls, pname, make_property(fact))

        # Finally, add any missing automagic property (e.g. for Basic)
        for fact in _assume_defined:
            pname = as_property(fact)
            if not hasattr(cls, pname):
                setattr(cls, pname, make_property(fact))