Example #1
0
    def print_unit_base(self, unit):
        """
        Useless method.

        DO NOT USE, use instead ``convert_to``.

        Give the string expression of a unit in term of the basis.

        Units are displayed by decreasing power.
        """
        SymPyDeprecationWarning(
            deprecated_since_version="1.2",
            issue=13336,
            feature="print_unit_base",
            useinstead="convert_to",
        ).warn()
        from sympy.physics.units import convert_to
        return convert_to(unit, self._base_units)
Example #2
0
    def sort_dims(dims):
        """
        Useless method, kept for compatibility with previous versions.

        DO NOT USE.

        Sort dimensions given in argument using their str function.

        This function will ensure that we get always the same tuple for a given
        set of dimensions.
        """
        SymPyDeprecationWarning(
            deprecated_since_version="1.2",
            issue=13336,
            feature="sort_dims",
            useinstead="sorted(..., key=default_sort_key)",
        ).warn()
        return tuple(sorted(dims, key=str))
Example #3
0
def _get_coord_sys_from_expr(expr, coord_sys=None):
    """
    expr : expression
        The coordinate system is extracted from this parameter.
    """
    if coord_sys is not None:
        SymPyDeprecationWarning(feature="coord_sys parameter",
                                useinstead="do not use it",
                                deprecated_since_version="1.1").warn()

    try:
        coord_sys = list(expr.atoms(CoordSys3D))
        if len(coord_sys) == 1:
            return coord_sys[0]
        else:
            return None
    except:
        return None
Example #4
0
    def is_dimensionless(self):
        """
        Check if the dimension object really has a dimension.

        A dimension should have at least one component with non-zero power.
        """
        if self.name == 1:
            return True

        from sympy.physics.units.systems.si import dimsys_default
        SymPyDeprecationWarning(
            deprecated_since_version="1.2",
            issue=13336,
            feature="wrong class",
        ).warn()
        dimensional_dependencies=dimsys_default

        return dimensional_dependencies.get_dimensional_dependencies(self) == {}
Example #5
0
File: kane.py Project: royels/sympy
    def linearize(self, **kwargs):
        """ Linearize the equations of motion about a symbolic operating point.

        If kwarg A_and_B is False (default), returns M, A, B, r for the
        linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.

        If kwarg A_and_B is True, returns A, B, r for the linearized form
        dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
        computationally intensive if there are many symbolic parameters. For
        this reason, it may be more desirable to use the default A_and_B=False,
        returning M, A, and B. Values may then be substituted in to these
        matrices, and the state space form found as
        A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.

        In both cases, r is found as all dynamicsymbols in the equations of
        motion that are not part of q, u, q', or u'. They are sorted in
        canonical form.

        The operating points may be also entered using the ``op_point`` kwarg.
        This takes a dictionary of {symbol: value}, or a an iterable of such
        dictionaries. The values may be numberic or symbolic. The more values
        you can specify beforehand, the faster this computation will run.

        As part of the deprecation cycle, the new method will not be used unless
        the kwarg ``new_method`` is set to True. If the kwarg is missing, or set
        to false, the old linearization method will be used. After next release
        the need for this kwarg will be removed.

        For more documentation, please see the ``Linearizer`` class."""

        if 'new_method' not in kwargs or not kwargs['new_method']:
            # User is still using old code.
            SymPyDeprecationWarning(
                'The linearize class method has changed '
                'to a new interface, the old method is deprecated. To '
                'use the new method, set the kwarg `new_method=True`. '
                'For more information, read the docstring '
                'of `linearize`.').warn()
            return self._old_linearize()
        # Remove the new method flag, before passing kwargs to linearize
        kwargs.pop('new_method')
        linearizer = self.to_linearizer()
        result = linearizer.linearize(**kwargs)
        return result + (linearizer.r, )
Example #6
0
    def __new__(cls, *args, evaluate=None, _sympify=True):
        # Allow faster processing by passing ``_sympify=False``, if all arguments
        # are already sympified.
        if _sympify:
            args = list(map(_sympify_, args))

        # Disallow non-Expr args in Add/Mul
        typ = cls._args_type
        if typ is not None:
            from .relational import Relational
            if any(isinstance(arg, Relational) for arg in args):
                raise TypeError("Relational cannot be used in %s" %
                                cls.__name__)

            # This should raise TypeError once deprecation period is over:
            if not all(isinstance(arg, typ) for arg in args):
                SymPyDeprecationWarning(feature="Add/Mul with non-Expr args",
                                        useinstead="Expr args",
                                        issue=19445,
                                        deprecated_since_version="1.7").warn()

        if evaluate is None:
            evaluate = global_parameters.evaluate
        if not evaluate:
            obj = cls._from_args(args)
            obj = cls._exec_constructor_postprocessors(obj)
            return obj

        args = [a for a in args if a is not cls.identity]

        if len(args) == 0:
            return cls.identity
        if len(args) == 1:
            return args[0]

        c_part, nc_part, order_symbols = cls.flatten(args)
        is_commutative = not nc_part
        obj = cls._from_args(c_part + nc_part, is_commutative)
        obj = cls._exec_constructor_postprocessors(obj)

        if order_symbols is not None:
            from sympy.series.order import Order
            return Order(obj, *order_symbols)
        return obj
Example #7
0
    def _dod_to_DomainMatrix(cls, rows, cols, dod, types):

        if not all(issubclass(typ, Expr) for typ in types):
            SymPyDeprecationWarning(
                feature="non-Expr objects in a Matrix",
                useinstead="list of lists, TableForm or some other data structure",
                issue=21497,
                deprecated_since_version="1.9"
            ).warn()

        rep = DomainMatrix(dod, (rows, cols), EXRAW)

        if all(issubclass(typ, Rational) for typ in types):
            if all(issubclass(typ, Integer) for typ in types):
                rep = rep.convert_to(ZZ)
            else:
                rep = rep.convert_to(QQ)

        return rep
Example #8
0
def dim_simplify(expr):
    """
    NOTE: this function could be deprecated in the future.

    Simplify expression by recursively evaluating the dimension arguments.

    This function proceeds to a very rough dimensional analysis. It tries to
    simplify expression with dimensions, and it deletes all what multiplies a
    dimension without being a dimension. This is necessary to avoid strange
    behavior when Add(L, L) be transformed into Mul(2, L).
    """
    SymPyDeprecationWarning(
        deprecated_since_version="1.2",
        feature="dimensional simplification function",
        issue=13336,
        useinstead="don't use",
    ).warn()
    _, expr = Quantity._collect_factor_and_dimension(expr)
    return expr
Example #9
0
    def __getitem__(self, key):
        """
        Useless method, kept for compatibility with previous versions.

        DO NOT USE.

        Shortcut to the get_dim method, using key access.
        """
        SymPyDeprecationWarning(
            deprecated_since_version="1.2",
            issue=13336,
            feature="the get [ ] operator",
            useinstead="the dimension definition",
        ).warn()
        d = self.get_dim(key)
        #TODO: really want to raise an error?
        if d is None:
            raise KeyError(key)
        return d
Example #10
0
    def __new__(cls, lhs, rhs=None, **options):

        if rhs is None:
            SymPyDeprecationWarning(feature="Eq(expr) with rhs default to 0",
                                    useinstead="Eq(expr, 0)",
                                    issue=16587,
                                    deprecated_since_version="1.5").warn()
            rhs = 0
        evaluate = options.pop('evaluate', global_parameters.evaluate)
        lhs = _sympify(lhs)
        rhs = _sympify(rhs)
        if evaluate:
            val = is_eq(lhs, rhs)
            if val is None:
                return cls(lhs, rhs, evaluate=False)
            else:
                return _sympify(val)

        return Relational.__new__(cls, lhs, rhs)
Example #11
0
def theano_code(expr, cache=None, **kwargs):
    """
    Convert a Sympy expression into a Theano graph variable.

    Parameters
    ==========

    expr : sympy.core.expr.Expr
        Sympy expression object to convert.

    cache : dict
        Cached Theano variables (see :class:`TheanoPrinter.cache
        <TheanoPrinter>`). Defaults to the module-level global cache.

    dtypes : dict
        Passed to :meth:`.TheanoPrinter.doprint`.

    broadcastables : dict
        Passed to :meth:`.TheanoPrinter.doprint`.

    Returns
    =======

    theano.gof.graph.Variable
        A variable corresponding to the expression's value in a Theano symbolic
        expression graph.

    """
    SymPyDeprecationWarning(
        feature="sympy.printing.theanocode",
        useinstead=
        "Theano is deprecated; use Aesara and sympy.printing.aesaracode",
        issue=21150,
        deprecated_since_version="1.8").warn()

    if not theano:
        raise ImportError("theano is required for theano_code")

    if cache is None:
        cache = global_cache

    return TheanoPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
    def extend(self,
               new_base_dims,
               new_derived_dims=[],
               new_dim_deps={},
               name=None,
               description=None):
        if (name is not None) or (description is not None):
            SymPyDeprecationWarning(
                deprecated_since_version="1.2",
                issue=13336,
                feature="name and descriptions of DimensionSystem",
                useinstead="do not specify `name` or `description`",
            ).warn()

        deps = dict(self.dimensional_dependencies)
        deps.update(new_dim_deps)

        return DimensionSystem(
            tuple(self.base_dims) + tuple(new_base_dims),
            tuple(self.derived_dims) + tuple(new_derived_dims), deps)
Example #13
0
def ones(*args, **kwargs):
    """Returns a matrix of ones with ``rows`` rows and ``cols`` columns;
    if ``cols`` is omitted a square matrix will be returned.

    See Also
    ========

    zeros
    eye
    diag
    """

    if 'c' in kwargs:
        kwargs['cols'] = kwargs.pop('c')
        SymPyDeprecationWarning("use of kwarg 'c' is deprecated",
                                useinstead="cols",
                                deprecated_since_version="1.1")
    from .dense import Matrix

    return Matrix.ones(*args, **kwargs)
Example #14
0
def register_handler(key, handler):
    """
    Register a handler in the ask system. key must be a string and handler a
    class inheriting from AskHandler.

    .. deprecated:: 1.8.
        Use multipledispatch handler instead. See :obj:`~.Predicate`.

    """
    SymPyDeprecationWarning(feature="register_handler() function",
                            useinstead="multipledispatch handler of Predicate",
                            issue=20873,
                            deprecated_since_version="1.8").warn()
    if isinstance(key, Predicate):
        key = key.name.name
    Qkey = getattr(Q, key, None)
    if Qkey is not None:
        Qkey.add_handler(handler)
    else:
        setattr(Q, key, Predicate(key, handlers=[handler]))
Example #15
0
def numbered_symbols(prefix='x', cls=None, start=0, *args, **assumptions):
    """
    Generate an infinite stream of Symbols consisting of a prefix and
    increasing subscripts.

    Parameters
    ----------
    prefix : str, optional
        The prefix to use. By default, this function will generate symbols of
        the form "x0", "x1", etc.

    cls : class, optional
        The class to use. By default, it uses Symbol, but you can also use Wild.

    start : int, optional
        The start number.  By default, it is 0.

    Returns
    -------
    sym : Symbol
        The subscripted symbols.
    """
    if 'dummy' in assumptions:
        SymPyDeprecationWarning(
            feature="'dummy=True' to create numbered Dummy symbols",
            useinstead="cls=Dummy",
            issue=3378,
            deprecated_since_version="0.7.0",
        ).warn()
        if assumptions.pop('dummy'):
            cls = C.Dummy

    if cls is None:
        # We can't just make the default cls=C.Symbol because it isn't
        # imported yet.
        cls = C.Symbol

    while True:
        name = '%s%s' % (prefix, start)
        yield cls(name, *args, **assumptions)
        start += 1
Example #16
0
    def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None, name=None, description=None):
        if (name is not None) or (description is not None):
            SymPyDeprecationWarning(
                deprecated_since_version="1.2",
                issue=13336,
                feature="name and descriptions of DimensionSystem",
                useinstead="do not specify `name` or `description`",
            ).warn()

        deps = dict(self.dimensional_dependencies)
        if new_dim_deps:
            deps.update(new_dim_deps)

        new_dim_sys = DimensionSystem(
            tuple(self.base_dims) + tuple(new_base_dims),
            tuple(self.derived_dims) + tuple(new_derived_dims),
            deps
        )
        new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
        new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
        return new_dim_sys
Example #17
0
    def _print_Permutation(self, expr):
        print("Warning: _print_Permutation was called")
        from sympy.combinatorics.permutations import Permutation, Cycle
        from sympy.utilities.exceptions import SymPyDeprecationWarning

        perm_cyclic = Permutation.print_cyclic
        if perm_cyclic is not None:
            SymPyDeprecationWarning(
                feature="Permutation.print_cyclic = {}".format(perm_cyclic),
                useinstead="init_printing(perm_cyclic={})".format(perm_cyclic),
                issue=15201,
                deprecated_since_version="1.6").warn()
        else:
            perm_cyclic = self._settings.get("perm_cyclic", True)

        if perm_cyclic:
            if not expr.size:
                return '()'
            # before taking Cycle notation, see if the last element is
            # a singleton and move it to the head of the string
            s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
            last = s.rfind('(')
            if not last == 0 and ',' not in s[last:]:
                s = s[last:] + s[:last]
            s = s.replace(',', '')
            return s
        else:
            s = expr.support()
            if not s:
                if expr.size < 5:
                    return 'Permutation(%s)' % self._print(expr.array_form)
                return 'Permutation([], size=%s)' % self._print(expr.size)
            trim = self._print(
                expr.array_form[:s[-1] +
                                1]) + ', size=%s' % self._print(expr.size)
            use = full = self._print(expr.array_form)
            if len(trim) < len(full):
                use = trim
            return 'Permutation(%s)' % use
Example #18
0
def _issue_7853_dep_check(namespaces, namespace, expr):
    """Used for checking things passed into modules kwarg for deprecation
    issue #7853. This function and the call to it in lambdify should be
    deleted once the cycle has ended."""

    # If some module changed `ImmutableMatrix` to be something else
    mat = namespace.get('ImmutableMatrix', False)
    if not mat or 'numpy' not in namespaces or ('%s.%s' % (mat.__module__,
            mat.__name__) == 'numpy.matrixlib.defmatrix.matrix'):
        return
    dicts = [m for m in namespaces if isinstance(m, dict)]
    test = lambda expr: hasattr(expr, 'is_Matrix') and expr.is_Matrix
    if test(expr) and not [d for d in dicts if 'ImmutableMatrix' in d]:
        SymPyDeprecationWarning(
                "Currently, `sympy.Matrix` is replaced with `numpy.matrix` if "
                "the NumPy package is utilized in lambdify. In future versions "
                "of SymPy (> 0.7.6), we will default to replacing "
                "`sympy.Matrix` with `numpy.array`. To use the future "
                "behavior now, supply the kwarg "
                "`modules=[{'ImmutableMatrix': numpy.array}, 'numpy']`. "
                "The old behavior can be retained in future versions by "
                "supplying `modules=[{'ImmutableMatrix': numpy.matrix}, "
                "'numpy']`.", issue=7853).warn()
Example #19
0
def mechanics_printing(**kwargs):

    # mechanics_printing has slightly different functionality in 0.7.5 but
    # shouldn't fundamentally need a deprecation warning so we do this
    # little wrapper that gives the warning that things have changed.

    # TODO : Remove this warning in the release after SymPy 0.7.5

    # The message is only printed if this function is called with no args,
    # as was the previous only way to call it.

    def dict_is_empty(D):
        for k in D:
            return False
        return True

    if dict_is_empty(kwargs):
        msg = ('See the doc string for slight changes to this function: '
               'keyword args may be needed for the desired effect. '
               'Otherwise use sympy.physics.vector.init_vprinting directly.')
        SymPyDeprecationWarning(filldedent(msg)).warn()

    init_vprinting(**kwargs)
Example #20
0
def zeros(r, c=None, cls=None):
    """Returns a matrix of zeros with ``r`` rows and ``c`` columns;
    if ``c`` is omitted a square matrix will be returned.

    See Also
    ========

    ones
    eye
    diag
    """
    if cls is None:
        from dense import Matrix as cls
    if is_sequence(r):
        SymPyDeprecationWarning(
            feature="The syntax zeros([%i, %i])" % tuple(r),
            useinstead="zeros(%i, %i)." % tuple(r),
            issue=3381, deprecated_since_version="0.7.2",
        ).warn()
        r, c = r
    else:
        c = r if c is None else c
    r, c = [int(i) for i in [r, c]]
    return cls.zeros(r, c)
Example #21
0
    def __new__(cls, name, **assumptions):
        """Symbols are identified by name and assumptions::

        >>> from sympy import Symbol
        >>> Symbol("x") == Symbol("x")
        True
        >>> Symbol("x", real=True) == Symbol("x", real=False)
        False

        """

        if 'dummy' in assumptions:
            SymPyDeprecationWarning(
                feature="Symbol('x', dummy=True)",
                useinstead="Dummy() or symbols(..., cls=Dummy)").warn()
            if assumptions.pop('dummy'):
                return Dummy(name, **assumptions)
        if assumptions.get('zero', False):
            return S.Zero
        is_commutative = fuzzy_bool(assumptions.get('commutative', True))
        if is_commutative is None:
            raise ValueError('''Symbol commutativity must be True or False.''')
        assumptions['commutative'] = is_commutative
        return Symbol.__xnew_cached_(cls, name, **assumptions)
Example #22
0
    def _sanitize(assumptions, obj=None):
        """Remove None, covert values to bool, check commutativity *in place*.
        """

        # be strict about commutativity
        is_commutative = fuzzy_bool(assumptions.get('commutative', True))
        if is_commutative is None:
            whose = '%s ' % obj.__name__ if obj else ''
            raise ValueError('%scommutativity must be True or False.' % whose)
        assumptions['commutative'] = is_commutative

        # sanitize other assumptions so 1 -> True and 0 -> False
        for key in list(assumptions.keys()):
            from collections import defaultdict
            from sympy.utilities.exceptions import SymPyDeprecationWarning
            keymap = defaultdict(lambda: None)
            keymap.update({
                'bounded': 'finite',
                'unbounded': 'infinite',
                'infinitesimal': 'zero'
            })
            if keymap[key]:
                SymPyDeprecationWarning(
                    feature="%s assumption" % key,
                    useinstead="%s" % keymap[key],
                    issue=8071,
                    deprecated_since_version="0.7.6").warn()
                assumptions[keymap[key]] = assumptions[key]
                assumptions.pop(key)
                key = keymap[key]

            v = assumptions[key]
            if v is None:
                assumptions.pop(key)
                continue
            assumptions[key] = bool(v)
Example #23
0
    def _print_Permutation(self, expr):
        from sympy.combinatorics.permutations import Permutation, Cycle
        from sympy.utilities.exceptions import SymPyDeprecationWarning

        perm_cyclic = Permutation.print_cyclic
        if perm_cyclic is not None:
            SymPyDeprecationWarning(
                feature="Permutation.print_cyclic = {}".format(perm_cyclic),
                useinstead="init_printing(perm_cyclic={})".format(perm_cyclic),
                issue=15201,
                deprecated_since_version="1.6",
            ).warn()
        else:
            perm_cyclic = self._settings.get("perm_cyclic", True)

        if perm_cyclic:
            if not expr.size:
                return "Permutation()"
            # before taking Cycle notation, see if the last element is
            # a singleton and move it to the head of the string
            s = Cycle(expr)(expr.size - 1).__repr__()[len("Cycle") :]
            last = s.rfind("(")
            if not last == 0 and "," not in s[last:]:
                s = s[last:] + s[:last]
            return "Permutation%s" % s
        else:
            s = expr.support()
            if not s:
                if expr.size < 5:
                    return "Permutation(%s)" % str(expr.array_form)
                return "Permutation([], size=%s)" % expr.size
            trim = str(expr.array_form[: s[-1] + 1]) + ", size=%s" % expr.size
            use = full = str(expr.array_form)
            if len(trim) < len(full):
                use = trim
            return "Permutation(%s)" % use
Example #24
0
def _warn_sympy_deprecation():
    SymPyDeprecationWarning(feature="foo",
                            useinstead="bar",
                            issue=1,
                            deprecated_since_version="0.0.0").warn()
Example #25
0
def differentiate_finite(expr,
                         *symbols,
                         points=1,
                         x0=None,
                         wrt=None,
                         evaluate=False):
    r""" Differentiate expr and replace Derivatives with finite differences.

    Parameters
    ==========

    expr : expression
    \*symbols : differentiate with respect to symbols
    points: sequence, coefficient or undefined function, optional
        see ``Derivative.as_finite_difference``
    x0: number or Symbol, optional
        see ``Derivative.as_finite_difference``
    wrt: Symbol, optional
        see ``Derivative.as_finite_difference``

    Examples
    ========

    >>> from sympy import sin, Function, differentiate_finite
    >>> from sympy.abc import x, y, h
    >>> f, g = Function('f'), Function('g')
    >>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h])
    -f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h)

    ``differentiate_finite`` works on any expression, including the expressions
    with embedded derivatives:

    >>> differentiate_finite(f(x) + sin(x), x, 2)
    -2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1)
    >>> differentiate_finite(f(x, y), x, y)
    f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2)
    >>> differentiate_finite(f(x)*g(x).diff(x), x)
    (-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2)

    To make finite difference with non-constant discretization step use
    undefined functions:

    >>> dx = Function('dx')
    >>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x))
    -(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) +
    g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) +
    (-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) +
    g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x)

    """
    if any(term.is_Derivative for term in list(preorder_traversal(expr))):
        evaluate = False

    Dexpr = expr.diff(*symbols, evaluate=evaluate)
    if evaluate:
        SymPyDeprecationWarning(feature="``evaluate`` flag",
                                issue=17881,
                                deprecated_since_version="1.5").warn()
        return Dexpr.replace(
            lambda arg: arg.is_Derivative, lambda arg: arg.
            as_finite_difference(points=points, x0=x0, wrt=wrt))
    else:
        DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt)
        return DFexpr.replace(
            lambda arg: isinstance(arg, Subs),
            lambda arg: arg.expr.as_finite_difference(
                points=points, x0=arg.point[0], wrt=arg.variables[0]))
Example #26
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
Example #27
0
    def __new__(cls, sym, condition, base_set=S.UniversalSet):
        # nonlinsolve uses ConditionSet to return an unsolved system
        # of equations (see _return_conditionset in solveset) so until
        # that is changed we do minimal checking of the args
        sym = _sympify(sym)
        base_set = _sympify(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 isinstance(sym, Tuple):  # unsolved eqns syntax
            return Basic.__new__(cls, sym, condition, base_set)

        if not isinstance(base_set, Set):
            raise TypeError("expecting set for base_set")

        if condition is S.false:
            return S.EmptySet
        elif condition is S.true:
            return base_set
        if isinstance(base_set, EmptySet):
            return 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, base_set = base_set.args
            if sym == s:
                condition = And(condition, c)
            elif sym not in c.free_symbols:
                condition = And(condition, c.xreplace({s: sym}))
            elif s not in condition.free_symbols:
                condition = And(condition.xreplace({sym: s}), c)
                sym = s
            else:
                # user will have to use cls.sym to get symbol
                dum = Symbol("lambda")
                if dum in condition.free_symbols or dum in c.free_symbols:
                    dum = Dummy(str(dum))
                condition = And(condition.xreplace({sym: dum}),
                                c.xreplace({s: dum}))
                sym = dum

        if not isinstance(sym, Symbol):
            s = Dummy("lambda")
            if s not in condition.xreplace({sym: s}).free_symbols:
                raise ValueError(
                    "non-symbol dummy not recognized in condition")

        rv = Basic.__new__(cls, sym, condition, base_set)
        return rv if know is None else Union(know, rv)
Example #28
0
 def unicode(self):
     SymPyDeprecationWarning(feature="``prettyForm.unicode`` attribute",
                             useinstead="``stringPrict.s`` attribute",
                             deprecated_since_version="1.7").warn()
     return self._unicode
Example #29
0
def _is_diagonalizable(M, reals_only=False, **kwargs):
    """Returns ``True`` if a matrix is diagonalizable.

    Parameters
    ==========

    reals_only : bool, optional
        If ``True``, it tests whether the matrix can be diagonalized
        to contain only real numbers on the diagonal.


        If ``False``, it tests whether the matrix can be diagonalized
        at all, even with numbers that may not be real.

    Examples
    ========

    Example of a diagonalizable matrix:

    >>> from sympy import Matrix
    >>> M = Matrix([[1, 2, 0], [0, 3, 0], [2, -4, 2]])
    >>> M.is_diagonalizable()
    True

    Example of a non-diagonalizable matrix:

    >>> M = Matrix([[0, 1], [0, 0]])
    >>> M.is_diagonalizable()
    False

    Example of a matrix that is diagonalized in terms of non-real entries:

    >>> M = Matrix([[0, 1], [-1, 0]])
    >>> M.is_diagonalizable(reals_only=False)
    True
    >>> M.is_diagonalizable(reals_only=True)
    False

    See Also
    ========

    is_diagonal
    diagonalize
    """

    if 'clear_cache' in kwargs:
        SymPyDeprecationWarning(feature='clear_cache',
                                deprecated_since_version=1.4,
                                issue=15887).warn()

    if 'clear_subproducts' in kwargs:
        SymPyDeprecationWarning(feature='clear_subproducts',
                                deprecated_since_version=1.4,
                                issue=15887).warn()

    if not M.is_square:
        return False

    if all(e.is_real for e in M) and M.is_symmetric():
        return True

    if all(e.is_complex for e in M) and M.is_hermitian:
        return True

    return _is_diagonalizable_with_eigen(M, reals_only=reals_only)[0]
Example #30
0
def CoordSysCartesian(*args, **kwargs):
    SymPyDeprecationWarning(feature="CoordSysCartesian",
                            useinstead="CoordSys3D",
                            issue=12865,
                            deprecated_since_version="1.1").warn()
    return CoordSys3D(*args, **kwargs)