hash
stringlengths
64
64
content
stringlengths
0
1.51M
d621e885367152049f875649a71f6760a389ce43dc314afb1543292bcf43439b
"""Tools for setting up interactive sessions. """ from sympy.external.gmpy import GROUND_TYPES from sympy.external.importtools import version_tuple from sympy.interactive.printing import init_printing from sympy.utilities.misc import ARCH preexec_source = """\ from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing() """ verbose_message = """\ These commands were executed: %(source)s Documentation can be found at https://docs.sympy.org/%(version)s """ no_ipython = """\ Could not locate IPython. Having IPython installed is greatly recommended. See http://ipython.scipy.org for more details. If you use Debian/Ubuntu, just install the 'ipython' package and start isympy again. """ def _make_message(ipython=True, quiet=False, source=None): """Create a banner for an interactive session. """ from sympy import __version__ as sympy_version from sympy import SYMPY_DEBUG import sys import os if quiet: return "" python_version = "%d.%d.%d" % sys.version_info[:3] if ipython: shell_name = "IPython" else: shell_name = "Python" info = ['ground types: %s' % GROUND_TYPES] cache = os.getenv('SYMPY_USE_CACHE') if cache is not None and cache.lower() == 'no': info.append('cache: off') if SYMPY_DEBUG: info.append('debugging: on') args = shell_name, sympy_version, python_version, ARCH, ', '.join(info) message = "%s console for SymPy %s (Python %s-%s) (%s)\n" % args if source is None: source = preexec_source _source = "" for line in source.split('\n')[:-1]: if not line: _source += '\n' else: _source += '>>> ' + line + '\n' doc_version = sympy_version if 'dev' in doc_version: doc_version = "dev" else: doc_version = "%s/" % doc_version message += '\n' + verbose_message % {'source': _source, 'version': doc_version} return message def int_to_Integer(s): """ Wrap integer literals with Integer. This is based on the decistmt example from http://docs.python.org/library/tokenize.html. Only integer literals are converted. Float literals are left alone. Examples ======== >>> from sympy import Integer # noqa: F401 >>> from sympy.interactive.session import int_to_Integer >>> s = '1.2 + 1/2 - 0x12 + a1' >>> int_to_Integer(s) '1.2 +Integer (1 )/Integer (2 )-Integer (0x12 )+a1 ' >>> s = 'print (1/2)' >>> int_to_Integer(s) 'print (Integer (1 )/Integer (2 ))' >>> exec(s) 0.5 >>> exec(int_to_Integer(s)) 1/2 """ from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP from io import StringIO def _is_int(num): """ Returns true if string value num (with token NUMBER) represents an integer. """ # XXX: Is there something in the standard library that will do this? if '.' in num or 'j' in num.lower() or 'e' in num.lower(): return False return True result = [] g = generate_tokens(StringIO(s).readline) # tokenize the string for toknum, tokval, _, _, _ in g: if toknum == NUMBER and _is_int(tokval): # replace NUMBER tokens result.extend([ (NAME, 'Integer'), (OP, '('), (NUMBER, tokval), (OP, ')') ]) else: result.append((toknum, tokval)) return untokenize(result) def enable_automatic_int_sympification(shell): """ Allow IPython to automatically convert integer literals to Integer. """ import ast old_run_cell = shell.run_cell def my_run_cell(cell, *args, **kwargs): try: # Check the cell for syntax errors. This way, the syntax error # will show the original input, not the transformed input. The # downside here is that IPython magic like %timeit will not work # with transformed input (but on the other hand, IPython magic # that doesn't expect transformed input will continue to work). ast.parse(cell) except SyntaxError: pass else: cell = int_to_Integer(cell) old_run_cell(cell, *args, **kwargs) shell.run_cell = my_run_cell def enable_automatic_symbols(shell): """Allow IPython to automatically create symbols (``isympy -a``). """ # XXX: This should perhaps use tokenize, like int_to_Integer() above. # This would avoid re-executing the code, which can lead to subtle # issues. For example: # # In [1]: a = 1 # # In [2]: for i in range(10): # ...: a += 1 # ...: # # In [3]: a # Out[3]: 11 # # In [4]: a = 1 # # In [5]: for i in range(10): # ...: a += 1 # ...: print b # ...: # b # b # b # b # b # b # b # b # b # b # # In [6]: a # Out[6]: 12 # # Note how the for loop is executed again because `b` was not defined, but `a` # was already incremented once, so the result is that it is incremented # multiple times. import re re_nameerror = re.compile( "name '(?P<symbol>[A-Za-z_][A-Za-z0-9_]*)' is not defined") def _handler(self, etype, value, tb, tb_offset=None): """Handle :exc:`NameError` exception and allow injection of missing symbols. """ if etype is NameError and tb.tb_next and not tb.tb_next.tb_next: match = re_nameerror.match(str(value)) if match is not None: # XXX: Make sure Symbol is in scope. Otherwise you'll get infinite recursion. self.run_cell("%(symbol)s = Symbol('%(symbol)s')" % {'symbol': match.group("symbol")}, store_history=False) try: code = self.user_ns['In'][-1] except (KeyError, IndexError): pass else: self.run_cell(code, store_history=False) return None finally: self.run_cell("del %s" % match.group("symbol"), store_history=False) stb = self.InteractiveTB.structured_traceback( etype, value, tb, tb_offset=tb_offset) self._showtraceback(etype, value, stb) shell.set_custom_exc((NameError,), _handler) def init_ipython_session(shell=None, argv=[], auto_symbols=False, auto_int_to_Integer=False): """Construct new IPython session. """ import IPython if version_tuple(IPython.__version__) >= version_tuple('0.11'): if not shell: # use an app to parse the command line, and init config # IPython 1.0 deprecates the frontend module, so we import directly # from the terminal module to prevent a deprecation message from being # shown. if version_tuple(IPython.__version__) >= version_tuple('1.0'): from IPython.terminal import ipapp else: from IPython.frontend.terminal import ipapp app = ipapp.TerminalIPythonApp() # don't draw IPython banner during initialization: app.display_banner = False app.initialize(argv) shell = app.shell if auto_symbols: enable_automatic_symbols(shell) if auto_int_to_Integer: enable_automatic_int_sympification(shell) return shell else: from IPython.Shell import make_IPython return make_IPython(argv) def init_python_session(): """Construct new Python session. """ from code import InteractiveConsole class SymPyConsole(InteractiveConsole): """An interactive console with readline support. """ def __init__(self): ns_locals = dict() InteractiveConsole.__init__(self, locals=ns_locals) try: import rlcompleter import readline except ImportError: pass else: import os import atexit readline.set_completer(rlcompleter.Completer(ns_locals).complete) readline.parse_and_bind('tab: complete') if hasattr(readline, 'read_history_file'): history = os.path.expanduser('~/.sympy-history') try: readline.read_history_file(history) except OSError: pass atexit.register(readline.write_history_file, history) return SymPyConsole() def init_session(ipython=None, pretty_print=True, order=None, use_unicode=None, use_latex=None, quiet=False, auto_symbols=False, auto_int_to_Integer=False, str_printer=None, pretty_printer=None, latex_printer=None, argv=[]): """ Initialize an embedded IPython or Python session. The IPython session is initiated with the --pylab option, without the numpy imports, so that matplotlib plotting can be interactive. Parameters ========== pretty_print: boolean If True, use pretty_print to stringify; if False, use sstrrepr to stringify. order: string or None There are a few different settings for this parameter: lex (default), which is lexographic order; grlex, which is graded lexographic order; grevlex, which is reversed graded lexographic order; old, which is used for compatibility reasons and for long expressions; None, which sets it to lex. use_unicode: boolean or None If True, use unicode characters; if False, do not use unicode characters. use_latex: boolean or None If True, use latex rendering if IPython GUI's; if False, do not use latex rendering. quiet: boolean If True, init_session will not print messages regarding its status; if False, init_session will print messages regarding its status. auto_symbols: boolean If True, IPython will automatically create symbols for you. If False, it will not. The default is False. auto_int_to_Integer: boolean If True, IPython will automatically wrap int literals with Integer, so that things like 1/2 give Rational(1, 2). If False, it will not. The default is False. ipython: boolean or None If True, printing will initialize for an IPython console; if False, printing will initialize for a normal console; The default is None, which automatically determines whether we are in an ipython instance or not. str_printer: function, optional, default=None A custom string printer function. This should mimic sympy.printing.sstrrepr(). pretty_printer: function, optional, default=None A custom pretty printer. This should mimic sympy.printing.pretty(). latex_printer: function, optional, default=None A custom LaTeX printer. This should mimic sympy.printing.latex() This should mimic sympy.printing.latex(). argv: list of arguments for IPython See sympy.bin.isympy for options that can be used to initialize IPython. See Also ======== sympy.interactive.printing.init_printing: for examples and the rest of the parameters. Examples ======== >>> from sympy import init_session, Symbol, sin, sqrt >>> sin(x) #doctest: +SKIP NameError: name 'x' is not defined >>> init_session() #doctest: +SKIP >>> sin(x) #doctest: +SKIP sin(x) >>> sqrt(5) #doctest: +SKIP ___ \\/ 5 >>> init_session(pretty_print=False) #doctest: +SKIP >>> sqrt(5) #doctest: +SKIP sqrt(5) >>> y + x + y**2 + x**2 #doctest: +SKIP x**2 + x + y**2 + y >>> init_session(order='grlex') #doctest: +SKIP >>> y + x + y**2 + x**2 #doctest: +SKIP x**2 + y**2 + x + y >>> init_session(order='grevlex') #doctest: +SKIP >>> y * x**2 + x * y**2 #doctest: +SKIP x**2*y + x*y**2 >>> init_session(order='old') #doctest: +SKIP >>> x**2 + y**2 + x + y #doctest: +SKIP x + y + x**2 + y**2 >>> theta = Symbol('theta') #doctest: +SKIP >>> theta #doctest: +SKIP theta >>> init_session(use_unicode=True) #doctest: +SKIP >>> theta # doctest: +SKIP \u03b8 """ import sys in_ipython = False if ipython is not False: try: import IPython except ImportError: if ipython is True: raise RuntimeError("IPython is not available on this system") ip = None else: try: from IPython import get_ipython ip = get_ipython() except ImportError: ip = None in_ipython = bool(ip) if ipython is None: ipython = in_ipython if ipython is False: ip = init_python_session() mainloop = ip.interact else: ip = init_ipython_session(ip, argv=argv, auto_symbols=auto_symbols, auto_int_to_Integer=auto_int_to_Integer) if version_tuple(IPython.__version__) >= version_tuple('0.11'): # runsource is gone, use run_cell instead, which doesn't # take a symbol arg. The second arg is `store_history`, # and False means don't add the line to IPython's history. ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False) # Enable interactive plotting using pylab. try: ip.enable_pylab(import_all=False) except Exception: # Causes an import error if matplotlib is not installed. # Causes other errors (depending on the backend) if there # is no display, or if there is some problem in the # backend, so we have a bare "except Exception" here pass if not in_ipython: mainloop = ip.mainloop if auto_symbols and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')): raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above") if auto_int_to_Integer and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')): raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above") _preexec_source = preexec_source ip.runsource(_preexec_source, symbol='exec') init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode, use_latex=use_latex, ip=ip, str_printer=str_printer, pretty_printer=pretty_printer, latex_printer=latex_printer) message = _make_message(ipython, quiet, _preexec_source) if not in_ipython: print(message) mainloop() sys.exit('Exiting ...') else: print(message) import atexit atexit.register(lambda: print("Exiting ...\n"))
8d4a2185c835ad365604212cfba45ec692276d8be0453891f2baa37af957a36c
"""Power series evaluation and manipulation using sparse Polynomials Implementing a new function --------------------------- There are a few things to be kept in mind when adding a new function here:: - The implementation should work on all possible input domains/rings. Special cases include the ``EX`` ring and a constant term in the series to be expanded. There can be two types of constant terms in the series: + A constant value or symbol. + A term of a multivariate series not involving the generator, with respect to which the series is to expanded. Strictly speaking, a generator of a ring should not be considered a constant. However, for series expansion both the cases need similar treatment (as the user does not care about inner details), i.e, use an addition formula to separate the constant part and the variable part (see rs_sin for reference). - All the algorithms used here are primarily designed to work for Taylor series (number of iterations in the algo equals the required order). Hence, it becomes tricky to get the series of the right order if a Puiseux series is input. Use rs_puiseux? in your function if your algorithm is not designed to handle fractional powers. Extending rs_series ------------------- To make a function work with rs_series you need to do two things:: - Many sure it works with a constant term (as explained above). - If the series contains constant terms, you might need to extend its ring. You do so by adding the new terms to the rings as generators. ``PolyRing.compose`` and ``PolyRing.add_gens`` are two functions that do so and need to be called every time you expand a series containing a constant term. Look at rs_sin and rs_series for further reference. """ from sympy.polys.domains import QQ, EX from sympy.polys.rings import PolyElement, ring, sring from sympy.polys.polyerrors import DomainError from sympy.polys.monomials import (monomial_min, monomial_mul, monomial_div, monomial_ldiv) from mpmath.libmp.libintmath import ifac from sympy.core import PoleError, Function, Expr from sympy.core.numbers import Rational, igcd from sympy.functions import sin, cos, tan, atan, exp, atanh, tanh, log, ceiling from sympy.utilities.misc import as_int from mpmath.libmp.libintmath import giant_steps import math def _invert_monoms(p1): """ Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in ``x``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import _invert_monoms >>> R, x = ring('x', ZZ) >>> p = x**2 + 2*x + 3 >>> _invert_monoms(p) 3*x**2 + 2*x + 1 See Also ======== sympy.polys.densebasic.dup_reverse """ terms = list(p1.items()) terms.sort() deg = p1.degree() R = p1.ring p = R.zero cv = p1.listcoeffs() mv = p1.listmonoms() for i in range(len(mv)): p[(deg - mv[i][0],)] = cv[i] return p def _giant_steps(target): """Return a list of precision steps for the Newton's method""" res = giant_steps(2, target) if res[0] != 2: res = [2] + res return res def rs_trunc(p1, x, prec): """ Truncate the series in the ``x`` variable with precision ``prec``, that is, modulo ``O(x**prec)`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_trunc >>> R, x = ring('x', QQ) >>> p = x**10 + x**5 + x + 1 >>> rs_trunc(p, x, 12) x**10 + x**5 + x + 1 >>> rs_trunc(p, x, 10) x**5 + x + 1 """ R = p1.ring p = R.zero i = R.gens.index(x) for exp1 in p1: if exp1[i] >= prec: continue p[exp1] = p1[exp1] return p def rs_is_puiseux(p, x): """ Test if ``p`` is Puiseux series in ``x``. Raise an exception if it has a negative power in ``x``. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_is_puiseux >>> R, x = ring('x', QQ) >>> p = x**QQ(2,5) + x**QQ(2,3) + x >>> rs_is_puiseux(p, x) True """ index = p.ring.gens.index(x) for k in p: if k[index] != int(k[index]): return True if k[index] < 0: raise ValueError('The series is not regular in %s' % x) return False def rs_puiseux(f, p, x, prec): """ Return the puiseux series for `f(p, x, prec)`. To be used when function ``f`` is implemented only for regular series. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_puiseux, rs_exp >>> R, x = ring('x', QQ) >>> p = x**QQ(2,5) + x**QQ(2,3) + x >>> rs_puiseux(rs_exp,p, x, 1) 1/2*x**(4/5) + x**(2/3) + x**(2/5) + 1 """ index = p.ring.gens.index(x) n = 1 for k in p: power = k[index] if isinstance(power, Rational): num, den = power.as_numer_denom() n = int(n*den // igcd(n, den)) elif power != int(power): den = power.denominator n = int(n*den // igcd(n, den)) if n != 1: p1 = pow_xin(p, index, n) r = f(p1, x, prec*n) n1 = QQ(1, n) if isinstance(r, tuple): r = tuple([pow_xin(rx, index, n1) for rx in r]) else: r = pow_xin(r, index, n1) else: r = f(p, x, prec) return r def rs_puiseux2(f, p, q, x, prec): """ Return the puiseux series for `f(p, q, x, prec)`. To be used when function ``f`` is implemented only for regular series. """ index = p.ring.gens.index(x) n = 1 for k in p: power = k[index] if isinstance(power, Rational): num, den = power.as_numer_denom() n = n*den // igcd(n, den) elif power != int(power): den = power.denominator n = n*den // igcd(n, den) if n != 1: p1 = pow_xin(p, index, n) r = f(p1, q, x, prec*n) n1 = QQ(1, n) r = pow_xin(r, index, n1) else: r = f(p, q, x, prec) return r def rs_mul(p1, p2, x, prec): """ Return the product of the given two series, modulo ``O(x**prec)``. ``x`` is the series variable or its position in the generators. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_mul >>> R, x = ring('x', QQ) >>> p1 = x**2 + 2*x + 1 >>> p2 = x + 1 >>> rs_mul(p1, p2, x, 3) 3*x**2 + 3*x + 1 """ R = p1.ring p = R.zero if R.__class__ != p2.ring.__class__ or R != p2.ring: raise ValueError('p1 and p2 must have the same ring') iv = R.gens.index(x) if not isinstance(p2, PolyElement): raise ValueError('p1 and p2 must have the same ring') if R == p2.ring: get = p.get items2 = list(p2.items()) items2.sort(key=lambda e: e[0][iv]) if R.ngens == 1: for exp1, v1 in p1.items(): for exp2, v2 in items2: exp = exp1[0] + exp2[0] if exp < prec: exp = (exp, ) p[exp] = get(exp, 0) + v1*v2 else: break else: monomial_mul = R.monomial_mul for exp1, v1 in p1.items(): for exp2, v2 in items2: if exp1[iv] + exp2[iv] < prec: exp = monomial_mul(exp1, exp2) p[exp] = get(exp, 0) + v1*v2 else: break p.strip_zero() return p def rs_square(p1, x, prec): """ Square the series modulo ``O(x**prec)`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_square >>> R, x = ring('x', QQ) >>> p = x**2 + 2*x + 1 >>> rs_square(p, x, 3) 6*x**2 + 4*x + 1 """ R = p1.ring p = R.zero iv = R.gens.index(x) get = p.get items = list(p1.items()) items.sort(key=lambda e: e[0][iv]) monomial_mul = R.monomial_mul for i in range(len(items)): exp1, v1 = items[i] for j in range(i): exp2, v2 = items[j] if exp1[iv] + exp2[iv] < prec: exp = monomial_mul(exp1, exp2) p[exp] = get(exp, 0) + v1*v2 else: break p = p.imul_num(2) get = p.get for expv, v in p1.items(): if 2*expv[iv] < prec: e2 = monomial_mul(expv, expv) p[e2] = get(e2, 0) + v**2 p.strip_zero() return p def rs_pow(p1, n, x, prec): """ Return ``p1**n`` modulo ``O(x**prec)`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_pow >>> R, x = ring('x', QQ) >>> p = x + 1 >>> rs_pow(p, 4, x, 3) 6*x**2 + 4*x + 1 """ R = p1.ring if isinstance(n, Rational): np = int(n.p) nq = int(n.q) if nq != 1: res = rs_nth_root(p1, nq, x, prec) if np != 1: res = rs_pow(res, np, x, prec) else: res = rs_pow(p1, np, x, prec) return res n = as_int(n) if n == 0: if p1: return R(1) else: raise ValueError('0**0 is undefined') if n < 0: p1 = rs_pow(p1, -n, x, prec) return rs_series_inversion(p1, x, prec) if n == 1: return rs_trunc(p1, x, prec) if n == 2: return rs_square(p1, x, prec) if n == 3: p2 = rs_square(p1, x, prec) return rs_mul(p1, p2, x, prec) p = R(1) while 1: if n & 1: p = rs_mul(p1, p, x, prec) n -= 1 if not n: break p1 = rs_square(p1, x, prec) n = n // 2 return p def rs_subs(p, rules, x, prec): """ Substitution with truncation according to the mapping in ``rules``. Return a series with precision ``prec`` in the generator ``x`` Note that substitutions are not done one after the other >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_subs >>> R, x, y = ring('x, y', QQ) >>> p = x**2 + y**2 >>> rs_subs(p, {x: x+ y, y: x+ 2*y}, x, 3) 2*x**2 + 6*x*y + 5*y**2 >>> (x + y)**2 + (x + 2*y)**2 2*x**2 + 6*x*y + 5*y**2 which differs from >>> rs_subs(rs_subs(p, {x: x+ y}, x, 3), {y: x+ 2*y}, x, 3) 5*x**2 + 12*x*y + 8*y**2 Parameters ---------- p : :class:`~.PolyElement` Input series. rules : ``dict`` with substitution mappings. x : :class:`~.PolyElement` in which the series truncation is to be done. prec : :class:`~.Integer` order of the series after truncation. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_subs >>> R, x, y = ring('x, y', QQ) >>> rs_subs(x**2+y**2, {y: (x+y)**2}, x, 3) 6*x**2*y**2 + x**2 + 4*x*y**3 + y**4 """ R = p.ring ngens = R.ngens d = R(0) for i in range(ngens): d[(i, 1)] = R.gens[i] for var in rules: d[(R.index(var), 1)] = rules[var] p1 = R(0) p_keys = sorted(p.keys()) for expv in p_keys: p2 = R(1) for i in range(ngens): power = expv[i] if power == 0: continue if (i, power) not in d: q, r = divmod(power, 2) if r == 0 and (i, q) in d: d[(i, power)] = rs_square(d[(i, q)], x, prec) elif (i, power - 1) in d: d[(i, power)] = rs_mul(d[(i, power - 1)], d[(i, 1)], x, prec) else: d[(i, power)] = rs_pow(d[(i, 1)], power, x, prec) p2 = rs_mul(p2, d[(i, power)], x, prec) p1 += p2*p[expv] return p1 def _has_constant_term(p, x): """ Check if ``p`` has a constant term in ``x`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import _has_constant_term >>> R, x = ring('x', QQ) >>> p = x**2 + x + 1 >>> _has_constant_term(p, x) True """ R = p.ring iv = R.gens.index(x) zm = R.zero_monom a = [0]*R.ngens a[iv] = 1 miv = tuple(a) for expv in p: if monomial_min(expv, miv) == zm: return True return False def _get_constant_term(p, x): """Return constant term in p with respect to x Note that it is not simply `p[R.zero_monom]` as there might be multiple generators in the ring R. We want the `x`-free term which can contain other generators. """ R = p.ring i = R.gens.index(x) zm = R.zero_monom a = [0]*R.ngens a[i] = 1 miv = tuple(a) c = 0 for expv in p: if monomial_min(expv, miv) == zm: c += R({expv: p[expv]}) return c def _check_series_var(p, x, name): index = p.ring.gens.index(x) m = min(p, key=lambda k: k[index])[index] if m < 0: raise PoleError("Asymptotic expansion of %s around [oo] not " "implemented." % name) return index, m def _series_inversion1(p, x, prec): """ Univariate series inversion ``1/p`` modulo ``O(x**prec)``. The Newton method is used. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import _series_inversion1 >>> R, x = ring('x', QQ) >>> p = x + 1 >>> _series_inversion1(p, x, 4) -x**3 + x**2 - x + 1 """ if rs_is_puiseux(p, x): return rs_puiseux(_series_inversion1, p, x, prec) R = p.ring zm = R.zero_monom c = p[zm] # giant_steps does not seem to work with PythonRational numbers with 1 as # denominator. This makes sure such a number is converted to integer. if prec == int(prec): prec = int(prec) if zm not in p: raise ValueError("No constant term in series") if _has_constant_term(p - c, x): raise ValueError("p cannot contain a constant term depending on " "parameters") one = R(1) if R.domain is EX: one = 1 if c != one: # TODO add check that it is a unit p1 = R(1)/c else: p1 = R(1) for precx in _giant_steps(prec): t = 1 - rs_mul(p1, p, x, precx) p1 = p1 + rs_mul(p1, t, x, precx) return p1 def rs_series_inversion(p, x, prec): """ Multivariate series inversion ``1/p`` modulo ``O(x**prec)``. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_series_inversion >>> R, x, y = ring('x, y', QQ) >>> rs_series_inversion(1 + x*y**2, x, 4) -x**3*y**6 + x**2*y**4 - x*y**2 + 1 >>> rs_series_inversion(1 + x*y**2, y, 4) -x*y**2 + 1 >>> rs_series_inversion(x + x**2, x, 4) x**3 - x**2 + x - 1 + x**(-1) """ R = p.ring if p == R.zero: raise ZeroDivisionError zm = R.zero_monom index = R.gens.index(x) m = min(p, key=lambda k: k[index])[index] if m: p = mul_xin(p, index, -m) prec = prec + m if zm not in p: raise NotImplementedError("No constant term in series") if _has_constant_term(p - p[zm], x): raise NotImplementedError("p - p[0] must not have a constant term in " "the series variables") r = _series_inversion1(p, x, prec) if m != 0: r = mul_xin(r, index, -m) return r def _coefficient_t(p, t): r"""Coefficient of `x_i**j` in p, where ``t`` = (i, j)""" i, j = t R = p.ring expv1 = [0]*R.ngens expv1[i] = j expv1 = tuple(expv1) p1 = R(0) for expv in p: if expv[i] == j: p1[monomial_div(expv, expv1)] = p[expv] return p1 def rs_series_reversion(p, x, n, y): r""" Reversion of a series. ``p`` is a series with ``O(x**n)`` of the form $p = ax + f(x)$ where $a$ is a number different from 0. $f(x) = \sum_{k=2}^{n-1} a_kx_k$ Parameters ========== a_k : Can depend polynomially on other variables, not indicated. x : Variable with name x. y : Variable with name y. Returns ======= Solve $p = y$, that is, given $ax + f(x) - y = 0$, find the solution $x = r(y)$ up to $O(y^n)$. Algorithm ========= If $r_i$ is the solution at order $i$, then: $ar_i + f(r_i) - y = O\left(y^{i + 1}\right)$ and if $r_{i + 1}$ is the solution at order $i + 1$, then: $ar_{i + 1} + f(r_{i + 1}) - y = O\left(y^{i + 2}\right)$ We have, $r_{i + 1} = r_i + e$, such that, $ae + f(r_i) = O\left(y^{i + 2}\right)$ or $e = -f(r_i)/a$ So we use the recursion relation: $r_{i + 1} = r_i - f(r_i)/a$ with the boundary condition: $r_1 = y$ Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_series_reversion, rs_trunc >>> R, x, y, a, b = ring('x, y, a, b', QQ) >>> p = x - x**2 - 2*b*x**2 + 2*a*b*x**2 >>> p1 = rs_series_reversion(p, x, 3, y); p1 -2*y**2*a*b + 2*y**2*b + y**2 + y >>> rs_trunc(p.compose(x, p1), y, 3) y """ if rs_is_puiseux(p, x): raise NotImplementedError R = p.ring nx = R.gens.index(x) y = R(y) ny = R.gens.index(y) if _has_constant_term(p, x): raise ValueError("p must not contain a constant term in the series " "variable") a = _coefficient_t(p, (nx, 1)) zm = R.zero_monom assert zm in a and len(a) == 1 a = a[zm] r = y/a for i in range(2, n): sp = rs_subs(p, {x: r}, y, i + 1) sp = _coefficient_t(sp, (ny, i))*y**i r -= sp/a return r def rs_series_from_list(p, c, x, prec, concur=1): """ Return a series `sum c[n]*p**n` modulo `O(x**prec)`. It reduces the number of multiplications by summing concurrently. `ax = [1, p, p**2, .., p**(J - 1)]` `s = sum(c[i]*ax[i]` for i in `range(r, (r + 1)*J))*p**((K - 1)*J)` with `K >= (n + 1)/J` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_series_from_list, rs_trunc >>> R, x = ring('x', QQ) >>> p = x**2 + x + 1 >>> c = [1, 2, 3] >>> rs_series_from_list(p, c, x, 4) 6*x**3 + 11*x**2 + 8*x + 6 >>> rs_trunc(1 + 2*p + 3*p**2, x, 4) 6*x**3 + 11*x**2 + 8*x + 6 >>> pc = R.from_list(list(reversed(c))) >>> rs_trunc(pc.compose(x, p), x, 4) 6*x**3 + 11*x**2 + 8*x + 6 """ # TODO: Add this when it is documented in Sphinx """ See Also ======== sympy.polys.rings.PolyRing.compose """ R = p.ring n = len(c) if not concur: q = R(1) s = c[0]*q for i in range(1, n): q = rs_mul(q, p, x, prec) s += c[i]*q return s J = int(math.sqrt(n) + 1) K, r = divmod(n, J) if r: K += 1 ax = [R(1)] q = R(1) if len(p) < 20: for i in range(1, J): q = rs_mul(q, p, x, prec) ax.append(q) else: for i in range(1, J): if i % 2 == 0: q = rs_square(ax[i//2], x, prec) else: q = rs_mul(q, p, x, prec) ax.append(q) # optimize using rs_square pj = rs_mul(ax[-1], p, x, prec) b = R(1) s = R(0) for k in range(K - 1): r = J*k s1 = c[r] for j in range(1, J): s1 += c[r + j]*ax[j] s1 = rs_mul(s1, b, x, prec) s += s1 b = rs_mul(b, pj, x, prec) if not b: break k = K - 1 r = J*k if r < n: s1 = c[r]*R(1) for j in range(1, J): if r + j >= n: break s1 += c[r + j]*ax[j] s1 = rs_mul(s1, b, x, prec) s += s1 return s def rs_diff(p, x): """ Return partial derivative of ``p`` with respect to ``x``. Parameters ========== x : :class:`~.PolyElement` with respect to which ``p`` is differentiated. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_diff >>> R, x, y = ring('x, y', QQ) >>> p = x + x**2*y**3 >>> rs_diff(p, x) 2*x*y**3 + 1 """ R = p.ring n = R.gens.index(x) p1 = R.zero mn = [0]*R.ngens mn[n] = 1 mn = tuple(mn) for expv in p: if expv[n]: e = monomial_ldiv(expv, mn) p1[e] = R.domain_new(p[expv]*expv[n]) return p1 def rs_integrate(p, x): """ Integrate ``p`` with respect to ``x``. Parameters ========== x : :class:`~.PolyElement` with respect to which ``p`` is integrated. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_integrate >>> R, x, y = ring('x, y', QQ) >>> p = x + x**2*y**3 >>> rs_integrate(p, x) 1/3*x**3*y**3 + 1/2*x**2 """ R = p.ring p1 = R.zero n = R.gens.index(x) mn = [0]*R.ngens mn[n] = 1 mn = tuple(mn) for expv in p: e = monomial_mul(expv, mn) p1[e] = R.domain_new(p[expv]/(expv[n] + 1)) return p1 def rs_fun(p, f, *args): r""" Function of a multivariate series computed by substitution. The case with f method name is used to compute `rs\_tan` and `rs\_nth\_root` of a multivariate series: `rs\_fun(p, tan, iv, prec)` tan series is first computed for a dummy variable _x, i.e, `rs\_tan(\_x, iv, prec)`. Then we substitute _x with p to get the desired series Parameters ========== p : :class:`~.PolyElement` The multivariate series to be expanded. f : `ring\_series` function to be applied on `p`. args[-2] : :class:`~.PolyElement` with respect to which, the series is to be expanded. args[-1] : Required order of the expanded series. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_fun, _tan1 >>> R, x, y = ring('x, y', QQ) >>> p = x + x*y + x**2*y + x**3*y**2 >>> rs_fun(p, _tan1, x, 4) 1/3*x**3*y**3 + 2*x**3*y**2 + x**3*y + 1/3*x**3 + x**2*y + x*y + x """ _R = p.ring R1, _x = ring('_x', _R.domain) h = int(args[-1]) args1 = args[:-2] + (_x, h) zm = _R.zero_monom # separate the constant term of the series # compute the univariate series f(_x, .., 'x', sum(nv)) if zm in p: x1 = _x + p[zm] p1 = p - p[zm] else: x1 = _x p1 = p if isinstance(f, str): q = getattr(x1, f)(*args1) else: q = f(x1, *args1) a = sorted(q.items()) c = [0]*h for x in a: c[x[0][0]] = x[1] p1 = rs_series_from_list(p1, c, args[-2], args[-1]) return p1 def mul_xin(p, i, n): r""" Return `p*x_i**n`. `x\_i` is the ith variable in ``p``. """ R = p.ring q = R(0) for k, v in p.items(): k1 = list(k) k1[i] += n q[tuple(k1)] = v return q def pow_xin(p, i, n): """ >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import pow_xin >>> R, x, y = ring('x, y', QQ) >>> p = x**QQ(2,5) + x + x**QQ(2,3) >>> index = p.ring.gens.index(x) >>> pow_xin(p, index, 15) x**15 + x**10 + x**6 """ R = p.ring q = R(0) for k, v in p.items(): k1 = list(k) k1[i] *= n q[tuple(k1)] = v return q def _nth_root1(p, n, x, prec): """ Univariate series expansion of the nth root of ``p``. The Newton method is used. """ if rs_is_puiseux(p, x): return rs_puiseux2(_nth_root1, p, n, x, prec) R = p.ring zm = R.zero_monom if zm not in p: raise NotImplementedError('No constant term in series') n = as_int(n) assert p[zm] == 1 p1 = R(1) if p == 1: return p if n == 0: return R(1) if n == 1: return p if n < 0: n = -n sign = 1 else: sign = 0 for precx in _giant_steps(prec): tmp = rs_pow(p1, n + 1, x, precx) tmp = rs_mul(tmp, p, x, precx) p1 += p1/n - tmp/n if sign: return p1 else: return _series_inversion1(p1, x, prec) def rs_nth_root(p, n, x, prec): """ Multivariate series expansion of the nth root of ``p``. Parameters ========== p : Expr The polynomial to computer the root of. n : integer The order of the root to be computed. x : :class:`~.PolyElement` prec : integer Order of the expanded series. Notes ===== The result of this function is dependent on the ring over which the polynomial has been defined. If the answer involves a root of a constant, make sure that the polynomial is over a real field. It cannot yet handle roots of symbols. Examples ======== >>> from sympy.polys.domains import QQ, RR >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_nth_root >>> R, x, y = ring('x, y', QQ) >>> rs_nth_root(1 + x + x*y, -3, x, 3) 2/9*x**2*y**2 + 4/9*x**2*y + 2/9*x**2 - 1/3*x*y - 1/3*x + 1 >>> R, x, y = ring('x, y', RR) >>> rs_nth_root(3 + x + x*y, 3, x, 2) 0.160249952256379*x*y + 0.160249952256379*x + 1.44224957030741 """ if n == 0: if p == 0: raise ValueError('0**0 expression') else: return p.ring(1) if n == 1: return rs_trunc(p, x, prec) R = p.ring index = R.gens.index(x) m = min(p, key=lambda k: k[index])[index] p = mul_xin(p, index, -m) prec -= m if _has_constant_term(p - 1, x): zm = R.zero_monom c = p[zm] if R.domain is EX: c_expr = c.as_expr() const = c_expr**QQ(1, n) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() const = R(c_expr**(QQ(1, n))) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") else: try: # RealElement doesn't support const = R(c**Rational(1, n)) # exponentiation with mpq object except ValueError: # as exponent raise DomainError("The given series cannot be expanded in " "this domain.") res = rs_nth_root(p/c, n, x, prec)*const else: res = _nth_root1(p, n, x, prec) if m: m = QQ(m, n) res = mul_xin(res, index, m) return res def rs_log(p, x, prec): """ The Logarithm of ``p`` modulo ``O(x**prec)``. Notes ===== Truncation of ``integral dx p**-1*d p/dx`` is used. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_log >>> R, x = ring('x', QQ) >>> rs_log(1 + x, x, 8) 1/7*x**7 - 1/6*x**6 + 1/5*x**5 - 1/4*x**4 + 1/3*x**3 - 1/2*x**2 + x >>> rs_log(x**QQ(3, 2) + 1, x, 5) 1/3*x**(9/2) - 1/2*x**3 + x**(3/2) """ if rs_is_puiseux(p, x): return rs_puiseux(rs_log, p, x, prec) R = p.ring if p == 1: return R.zero c = _get_constant_term(p, x) if c: const = 0 if c == 1: pass else: c_expr = c.as_expr() if R.domain is EX: const = log(c_expr) elif isinstance(c, PolyElement): try: const = R(log(c_expr)) except ValueError: R = R.add_gens([log(c_expr)]) p = p.set_ring(R) x = x.set_ring(R) c = c.set_ring(R) const = R(log(c_expr)) else: try: const = R(log(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") dlog = p.diff(x) dlog = rs_mul(dlog, _series_inversion1(p, x, prec), x, prec - 1) return rs_integrate(dlog, x) + const else: raise NotImplementedError def rs_LambertW(p, x, prec): """ Calculate the series expansion of the principal branch of the Lambert W function. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_LambertW >>> R, x, y = ring('x, y', QQ) >>> rs_LambertW(x + x*y, x, 3) -x**2*y**2 - 2*x**2*y - x**2 + x*y + x See Also ======== LambertW """ if rs_is_puiseux(p, x): return rs_puiseux(rs_LambertW, p, x, prec) R = p.ring p1 = R(0) if _has_constant_term(p, x): raise NotImplementedError("Polynomial must not have constant term in " "the series variables") if x in R.gens: for precx in _giant_steps(prec): e = rs_exp(p1, x, precx) p2 = rs_mul(e, p1, x, precx) - p p3 = rs_mul(e, p1 + 1, x, precx) p3 = rs_series_inversion(p3, x, precx) tmp = rs_mul(p2, p3, x, precx) p1 -= tmp return p1 else: raise NotImplementedError def _exp1(p, x, prec): r"""Helper function for `rs\_exp`. """ R = p.ring p1 = R(1) for precx in _giant_steps(prec): pt = p - rs_log(p1, x, precx) tmp = rs_mul(pt, p1, x, precx) p1 += tmp return p1 def rs_exp(p, x, prec): """ Exponentiation of a series modulo ``O(x**prec)`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_exp >>> R, x = ring('x', QQ) >>> rs_exp(x**2, x, 7) 1/6*x**6 + 1/2*x**4 + x**2 + 1 """ if rs_is_puiseux(p, x): return rs_puiseux(rs_exp, p, x, prec) R = p.ring c = _get_constant_term(p, x) if c: if R.domain is EX: c_expr = c.as_expr() const = exp(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() const = R(exp(c_expr)) except ValueError: R = R.add_gens([exp(c_expr)]) p = p.set_ring(R) x = x.set_ring(R) c = c.set_ring(R) const = R(exp(c_expr)) else: try: const = R(exp(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") p1 = p - c # Makes use of SymPy functions to evaluate the values of the cos/sin # of the constant term. return const*rs_exp(p1, x, prec) if len(p) > 20: return _exp1(p, x, prec) one = R(1) n = 1 c = [] for k in range(prec): c.append(one/n) k += 1 n *= k r = rs_series_from_list(p, c, x, prec) return r def _atan(p, iv, prec): """ Expansion using formula. Faster on very small and univariate series. """ R = p.ring mo = R(-1) c = [-mo] p2 = rs_square(p, iv, prec) for k in range(1, prec): c.append(mo**k/(2*k + 1)) s = rs_series_from_list(p2, c, iv, prec) s = rs_mul(s, p, iv, prec) return s def rs_atan(p, x, prec): """ The arctangent of a series Return the series expansion of the atan of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_atan >>> R, x, y = ring('x, y', QQ) >>> rs_atan(x + x*y, x, 4) -1/3*x**3*y**3 - x**3*y**2 - x**3*y - 1/3*x**3 + x*y + x See Also ======== atan """ if rs_is_puiseux(p, x): return rs_puiseux(rs_atan, p, x, prec) R = p.ring const = 0 if _has_constant_term(p, x): zm = R.zero_monom c = p[zm] if R.domain is EX: c_expr = c.as_expr() const = atan(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() const = R(atan(c_expr)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") else: try: const = R(atan(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") # Instead of using a closed form formula, we differentiate atan(p) to get # `1/(1+p**2) * dp`, whose series expansion is much easier to calculate. # Finally we integrate to get back atan dp = p.diff(x) p1 = rs_square(p, x, prec) + R(1) p1 = rs_series_inversion(p1, x, prec - 1) p1 = rs_mul(dp, p1, x, prec - 1) return rs_integrate(p1, x) + const def rs_asin(p, x, prec): """ Arcsine of a series Return the series expansion of the asin of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_asin >>> R, x, y = ring('x, y', QQ) >>> rs_asin(x, x, 8) 5/112*x**7 + 3/40*x**5 + 1/6*x**3 + x See Also ======== asin """ if rs_is_puiseux(p, x): return rs_puiseux(rs_asin, p, x, prec) if _has_constant_term(p, x): raise NotImplementedError("Polynomial must not have constant term in " "series variables") R = p.ring if x in R.gens: # get a good value if len(p) > 20: dp = rs_diff(p, x) p1 = 1 - rs_square(p, x, prec - 1) p1 = rs_nth_root(p1, -2, x, prec - 1) p1 = rs_mul(dp, p1, x, prec - 1) return rs_integrate(p1, x) one = R(1) c = [0, one, 0] for k in range(3, prec, 2): c.append((k - 2)**2*c[-2]/(k*(k - 1))) c.append(0) return rs_series_from_list(p, c, x, prec) else: raise NotImplementedError def _tan1(p, x, prec): r""" Helper function of :func:`rs_tan`. Return the series expansion of tan of a univariate series using Newton's method. It takes advantage of the fact that series expansion of atan is easier than that of tan. Consider `f(x) = y - \arctan(x)` Let r be a root of f(x) found using Newton's method. Then `f(r) = 0` Or `y = \arctan(x)` where `x = \tan(y)` as required. """ R = p.ring p1 = R(0) for precx in _giant_steps(prec): tmp = p - rs_atan(p1, x, precx) tmp = rs_mul(tmp, 1 + rs_square(p1, x, precx), x, precx) p1 += tmp return p1 def rs_tan(p, x, prec): """ Tangent of a series. Return the series expansion of the tan of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_tan >>> R, x, y = ring('x, y', QQ) >>> rs_tan(x + x*y, x, 4) 1/3*x**3*y**3 + x**3*y**2 + x**3*y + 1/3*x**3 + x*y + x See Also ======== _tan1, tan """ if rs_is_puiseux(p, x): r = rs_puiseux(rs_tan, p, x, prec) return r R = p.ring const = 0 c = _get_constant_term(p, x) if c: if R.domain is EX: c_expr = c.as_expr() const = tan(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() const = R(tan(c_expr)) except ValueError: R = R.add_gens([tan(c_expr, )]) p = p.set_ring(R) x = x.set_ring(R) c = c.set_ring(R) const = R(tan(c_expr)) else: try: const = R(tan(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") p1 = p - c # Makes use of SymPy functions to evaluate the values of the cos/sin # of the constant term. t2 = rs_tan(p1, x, prec) t = rs_series_inversion(1 - const*t2, x, prec) return rs_mul(const + t2, t, x, prec) if R.ngens == 1: return _tan1(p, x, prec) else: return rs_fun(p, rs_tan, x, prec) def rs_cot(p, x, prec): """ Cotangent of a series Return the series expansion of the cot of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_cot >>> R, x, y = ring('x, y', QQ) >>> rs_cot(x, x, 6) -2/945*x**5 - 1/45*x**3 - 1/3*x + x**(-1) See Also ======== cot """ # It can not handle series like `p = x + x*y` where the coefficient of the # linear term in the series variable is symbolic. if rs_is_puiseux(p, x): r = rs_puiseux(rs_cot, p, x, prec) return r i, m = _check_series_var(p, x, 'cot') prec1 = prec + 2*m c, s = rs_cos_sin(p, x, prec1) s = mul_xin(s, i, -m) s = rs_series_inversion(s, x, prec1) res = rs_mul(c, s, x, prec1) res = mul_xin(res, i, -m) res = rs_trunc(res, x, prec) return res def rs_sin(p, x, prec): """ Sine of a series Return the series expansion of the sin of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_sin >>> R, x, y = ring('x, y', QQ) >>> rs_sin(x + x*y, x, 4) -1/6*x**3*y**3 - 1/2*x**3*y**2 - 1/2*x**3*y - 1/6*x**3 + x*y + x >>> rs_sin(x**QQ(3, 2) + x*y**QQ(7, 5), x, 4) -1/2*x**(7/2)*y**(14/5) - 1/6*x**3*y**(21/5) + x**(3/2) + x*y**(7/5) See Also ======== sin """ if rs_is_puiseux(p, x): return rs_puiseux(rs_sin, p, x, prec) R = x.ring if not p: return R(0) c = _get_constant_term(p, x) if c: if R.domain is EX: c_expr = c.as_expr() t1, t2 = sin(c_expr), cos(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() t1, t2 = R(sin(c_expr)), R(cos(c_expr)) except ValueError: R = R.add_gens([sin(c_expr), cos(c_expr)]) p = p.set_ring(R) x = x.set_ring(R) c = c.set_ring(R) t1, t2 = R(sin(c_expr)), R(cos(c_expr)) else: try: t1, t2 = R(sin(c)), R(cos(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") p1 = p - c # Makes use of SymPy cos, sin functions to evaluate the values of the # cos/sin of the constant term. return rs_sin(p1, x, prec)*t2 + rs_cos(p1, x, prec)*t1 # Series is calculated in terms of tan as its evaluation is fast. if len(p) > 20 and R.ngens == 1: t = rs_tan(p/2, x, prec) t2 = rs_square(t, x, prec) p1 = rs_series_inversion(1 + t2, x, prec) return rs_mul(p1, 2*t, x, prec) one = R(1) n = 1 c = [0] for k in range(2, prec + 2, 2): c.append(one/n) c.append(0) n *= -k*(k + 1) return rs_series_from_list(p, c, x, prec) def rs_cos(p, x, prec): """ Cosine of a series Return the series expansion of the cos of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_cos >>> R, x, y = ring('x, y', QQ) >>> rs_cos(x + x*y, x, 4) -1/2*x**2*y**2 - x**2*y - 1/2*x**2 + 1 >>> rs_cos(x + x*y, x, 4)/x**QQ(7, 5) -1/2*x**(3/5)*y**2 - x**(3/5)*y - 1/2*x**(3/5) + x**(-7/5) See Also ======== cos """ if rs_is_puiseux(p, x): return rs_puiseux(rs_cos, p, x, prec) R = p.ring c = _get_constant_term(p, x) if c: if R.domain is EX: c_expr = c.as_expr() _, _ = sin(c_expr), cos(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() _, _ = R(sin(c_expr)), R(cos(c_expr)) except ValueError: R = R.add_gens([sin(c_expr), cos(c_expr)]) p = p.set_ring(R) x = x.set_ring(R) c = c.set_ring(R) else: try: _, _ = R(sin(c)), R(cos(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") p1 = p - c # Makes use of SymPy cos, sin functions to evaluate the values of the # cos/sin of the constant term. p_cos = rs_cos(p1, x, prec) p_sin = rs_sin(p1, x, prec) R = R.compose(p_cos.ring).compose(p_sin.ring) p_cos.set_ring(R) p_sin.set_ring(R) t1, t2 = R(sin(c_expr)), R(cos(c_expr)) return p_cos*t2 - p_sin*t1 # Series is calculated in terms of tan as its evaluation is fast. if len(p) > 20 and R.ngens == 1: t = rs_tan(p/2, x, prec) t2 = rs_square(t, x, prec) p1 = rs_series_inversion(1+t2, x, prec) return rs_mul(p1, 1 - t2, x, prec) one = R(1) n = 1 c = [] for k in range(2, prec + 2, 2): c.append(one/n) c.append(0) n *= -k*(k - 1) return rs_series_from_list(p, c, x, prec) def rs_cos_sin(p, x, prec): r""" Return the tuple ``(rs_cos(p, x, prec)`, `rs_sin(p, x, prec))``. Is faster than calling rs_cos and rs_sin separately """ if rs_is_puiseux(p, x): return rs_puiseux(rs_cos_sin, p, x, prec) t = rs_tan(p/2, x, prec) t2 = rs_square(t, x, prec) p1 = rs_series_inversion(1 + t2, x, prec) return (rs_mul(p1, 1 - t2, x, prec), rs_mul(p1, 2*t, x, prec)) def _atanh(p, x, prec): """ Expansion using formula Faster for very small and univariate series """ R = p.ring one = R(1) c = [one] p2 = rs_square(p, x, prec) for k in range(1, prec): c.append(one/(2*k + 1)) s = rs_series_from_list(p2, c, x, prec) s = rs_mul(s, p, x, prec) return s def rs_atanh(p, x, prec): """ Hyperbolic arctangent of a series Return the series expansion of the atanh of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_atanh >>> R, x, y = ring('x, y', QQ) >>> rs_atanh(x + x*y, x, 4) 1/3*x**3*y**3 + x**3*y**2 + x**3*y + 1/3*x**3 + x*y + x See Also ======== atanh """ if rs_is_puiseux(p, x): return rs_puiseux(rs_atanh, p, x, prec) R = p.ring const = 0 if _has_constant_term(p, x): zm = R.zero_monom c = p[zm] if R.domain is EX: c_expr = c.as_expr() const = atanh(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() const = R(atanh(c_expr)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") else: try: const = R(atanh(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") # Instead of using a closed form formula, we differentiate atanh(p) to get # `1/(1-p**2) * dp`, whose series expansion is much easier to calculate. # Finally we integrate to get back atanh dp = rs_diff(p, x) p1 = - rs_square(p, x, prec) + 1 p1 = rs_series_inversion(p1, x, prec - 1) p1 = rs_mul(dp, p1, x, prec - 1) return rs_integrate(p1, x) + const def rs_sinh(p, x, prec): """ Hyperbolic sine of a series Return the series expansion of the sinh of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_sinh >>> R, x, y = ring('x, y', QQ) >>> rs_sinh(x + x*y, x, 4) 1/6*x**3*y**3 + 1/2*x**3*y**2 + 1/2*x**3*y + 1/6*x**3 + x*y + x See Also ======== sinh """ if rs_is_puiseux(p, x): return rs_puiseux(rs_sinh, p, x, prec) t = rs_exp(p, x, prec) t1 = rs_series_inversion(t, x, prec) return (t - t1)/2 def rs_cosh(p, x, prec): """ Hyperbolic cosine of a series Return the series expansion of the cosh of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_cosh >>> R, x, y = ring('x, y', QQ) >>> rs_cosh(x + x*y, x, 4) 1/2*x**2*y**2 + x**2*y + 1/2*x**2 + 1 See Also ======== cosh """ if rs_is_puiseux(p, x): return rs_puiseux(rs_cosh, p, x, prec) t = rs_exp(p, x, prec) t1 = rs_series_inversion(t, x, prec) return (t + t1)/2 def _tanh(p, x, prec): r""" Helper function of :func:`rs_tanh` Return the series expansion of tanh of a univariate series using Newton's method. It takes advantage of the fact that series expansion of atanh is easier than that of tanh. See Also ======== _tanh """ R = p.ring p1 = R(0) for precx in _giant_steps(prec): tmp = p - rs_atanh(p1, x, precx) tmp = rs_mul(tmp, 1 - rs_square(p1, x, prec), x, precx) p1 += tmp return p1 def rs_tanh(p, x, prec): """ Hyperbolic tangent of a series Return the series expansion of the tanh of ``p``, about 0. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_tanh >>> R, x, y = ring('x, y', QQ) >>> rs_tanh(x + x*y, x, 4) -1/3*x**3*y**3 - x**3*y**2 - x**3*y - 1/3*x**3 + x*y + x See Also ======== tanh """ if rs_is_puiseux(p, x): return rs_puiseux(rs_tanh, p, x, prec) R = p.ring const = 0 if _has_constant_term(p, x): zm = R.zero_monom c = p[zm] if R.domain is EX: c_expr = c.as_expr() const = tanh(c_expr) elif isinstance(c, PolyElement): try: c_expr = c.as_expr() const = R(tanh(c_expr)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") else: try: const = R(tanh(c)) except ValueError: raise DomainError("The given series cannot be expanded in " "this domain.") p1 = p - c t1 = rs_tanh(p1, x, prec) t = rs_series_inversion(1 + const*t1, x, prec) return rs_mul(const + t1, t, x, prec) if R.ngens == 1: return _tanh(p, x, prec) else: return rs_fun(p, _tanh, x, prec) def rs_newton(p, x, prec): """ Compute the truncated Newton sum of the polynomial ``p`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_newton >>> R, x = ring('x', QQ) >>> p = x**2 - 2 >>> rs_newton(p, x, 5) 8*x**4 + 4*x**2 + 2 """ deg = p.degree() p1 = _invert_monoms(p) p2 = rs_series_inversion(p1, x, prec) p3 = rs_mul(p1.diff(x), p2, x, prec) res = deg - p3*x return res def rs_hadamard_exp(p1, inverse=False): """ Return ``sum f_i/i!*x**i`` from ``sum f_i*x**i``, where ``x`` is the first variable. If ``invers=True`` return ``sum f_i*i!*x**i`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_hadamard_exp >>> R, x = ring('x', QQ) >>> p = 1 + x + x**2 + x**3 >>> rs_hadamard_exp(p) 1/6*x**3 + 1/2*x**2 + x + 1 """ R = p1.ring if R.domain != QQ: raise NotImplementedError p = R.zero if not inverse: for exp1, v1 in p1.items(): p[exp1] = v1/int(ifac(exp1[0])) else: for exp1, v1 in p1.items(): p[exp1] = v1*int(ifac(exp1[0])) return p def rs_compose_add(p1, p2): """ compute the composed sum ``prod(p2(x - beta) for beta root of p1)`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import rs_compose_add >>> R, x = ring('x', QQ) >>> f = x**2 - 2 >>> g = x**2 - 3 >>> rs_compose_add(f, g) x**4 - 10*x**2 + 1 References ========== .. [1] A. Bostan, P. Flajolet, B. Salvy and E. Schost "Fast Computation with Two Algebraic Numbers", (2002) Research Report 4579, Institut National de Recherche en Informatique et en Automatique """ R = p1.ring x = R.gens[0] prec = p1.degree()*p2.degree() + 1 np1 = rs_newton(p1, x, prec) np1e = rs_hadamard_exp(np1) np2 = rs_newton(p2, x, prec) np2e = rs_hadamard_exp(np2) np3e = rs_mul(np1e, np2e, x, prec) np3 = rs_hadamard_exp(np3e, True) np3a = (np3[(0,)] - np3)/x q = rs_integrate(np3a, x) q = rs_exp(q, x, prec) q = _invert_monoms(q) q = q.primitive()[1] dp = p1.degree()*p2.degree() - q.degree() # `dp` is the multiplicity of the zeroes of the resultant; # these zeroes are missed in this computation so they are put here. # if p1 and p2 are monic irreducible polynomials, # there are zeroes in the resultant # if and only if p1 = p2 ; in fact in that case p1 and p2 have a # root in common, so gcd(p1, p2) != 1; being p1 and p2 irreducible # this means p1 = p2 if dp: q = q*x**dp return q _convert_func = { 'sin': 'rs_sin', 'cos': 'rs_cos', 'exp': 'rs_exp', 'tan': 'rs_tan', 'log': 'rs_log' } def rs_min_pow(expr, series_rs, a): """Find the minimum power of `a` in the series expansion of expr""" series = 0 n = 2 while series == 0: series = _rs_series(expr, series_rs, a, n) n *= 2 R = series.ring a = R(a) i = R.gens.index(a) return min(series, key=lambda t: t[i])[i] def _rs_series(expr, series_rs, a, prec): # TODO Use _parallel_dict_from_expr instead of sring as sring is # inefficient. For details, read the todo in sring. args = expr.args R = series_rs.ring # expr does not contain any function to be expanded if not any(arg.has(Function) for arg in args) and not expr.is_Function: return series_rs if not expr.has(a): return series_rs elif expr.is_Function: arg = args[0] if len(args) > 1: raise NotImplementedError R1, series = sring(arg, domain=QQ, expand=False, series=True) series_inner = _rs_series(arg, series, a, prec) # Why do we need to compose these three rings? # # We want to use a simple domain (like ``QQ`` or ``RR``) but they don't # support symbolic coefficients. We need a ring that for example lets # us have `sin(1)` and `cos(1)` as coefficients if we are expanding # `sin(x + 1)`. The ``EX`` domain allows all symbolic coefficients, but # that makes it very complex and hence slow. # # To solve this problem, we add only those symbolic elements as # generators to our ring, that we need. Here, series_inner might # involve terms like `sin(4)`, `exp(a)`, etc, which are not there in # R1 or R. Hence, we compose these three rings to create one that has # the generators of all three. R = R.compose(R1).compose(series_inner.ring) series_inner = series_inner.set_ring(R) series = eval(_convert_func[str(expr.func)])(series_inner, R(a), prec) return series elif expr.is_Mul: n = len(args) for arg in args: # XXX Looks redundant if not arg.is_Number: R1, _ = sring(arg, expand=False, series=True) R = R.compose(R1) min_pows = list(map(rs_min_pow, args, [R(arg) for arg in args], [a]*len(args))) sum_pows = sum(min_pows) series = R(1) for i in range(n): _series = _rs_series(args[i], R(args[i]), a, prec - sum_pows + min_pows[i]) R = R.compose(_series.ring) _series = _series.set_ring(R) series = series.set_ring(R) series *= _series series = rs_trunc(series, R(a), prec) return series elif expr.is_Add: n = len(args) series = R(0) for i in range(n): _series = _rs_series(args[i], R(args[i]), a, prec) R = R.compose(_series.ring) _series = _series.set_ring(R) series = series.set_ring(R) series += _series return series elif expr.is_Pow: R1, _ = sring(expr.base, domain=QQ, expand=False, series=True) R = R.compose(R1) series_inner = _rs_series(expr.base, R(expr.base), a, prec) return rs_pow(series_inner, expr.exp, series_inner.ring(a), prec) # The `is_constant` method is buggy hence we check it at the end. # See issue #9786 for details. elif isinstance(expr, Expr) and expr.is_constant(): return sring(expr, domain=QQ, expand=False, series=True)[1] else: raise NotImplementedError def rs_series(expr, a, prec): """Return the series expansion of an expression about 0. Parameters ========== expr : :class:`Expr` a : :class:`Symbol` with respect to which expr is to be expanded prec : order of the series expansion Currently supports multivariate Taylor series expansion. This is much faster that SymPy's series method as it uses sparse polynomial operations. It automatically creates the simplest ring required to represent the series expansion through repeated calls to sring. Examples ======== >>> from sympy.polys.ring_series import rs_series >>> from sympy import sin, cos, exp, tan, symbols, QQ >>> a, b, c = symbols('a, b, c') >>> rs_series(sin(a) + exp(a), a, 5) 1/24*a**4 + 1/2*a**2 + 2*a + 1 >>> series = rs_series(tan(a + b)*cos(a + c), a, 2) >>> series.as_expr() -a*sin(c)*tan(b) + a*cos(c)*tan(b)**2 + a*cos(c) + cos(c)*tan(b) >>> series = rs_series(exp(a**QQ(1,3) + a**QQ(2, 5)), a, 1) >>> series.as_expr() a**(11/15) + a**(4/5)/2 + a**(2/5) + a**(2/3)/2 + a**(1/3) + 1 """ R, series = sring(expr, domain=QQ, expand=False, series=True) if a not in R.symbols: R = R.add_gens([a, ]) series = series.set_ring(R) series = _rs_series(expr, series, a, prec) R = series.ring gen = R(a) prec_got = series.degree(gen) + 1 if prec_got >= prec: return rs_trunc(series, gen, prec) else: # increase the requested number of terms to get the desired # number keep increasing (up to 9) until the received order # is different than the original order and then predict how # many additional terms are needed for more in range(1, 9): p1 = _rs_series(expr, series, a, prec=prec + more) gen = gen.set_ring(p1.ring) new_prec = p1.degree(gen) + 1 if new_prec != prec_got: prec_do = ceiling(prec + (prec - prec_got)*more/(new_prec - prec_got)) p1 = _rs_series(expr, series, a, prec=prec_do) while p1.degree(gen) + 1 < prec: p1 = _rs_series(expr, series, a, prec=prec_do) gen = gen.set_ring(p1.ring) prec_do *= 2 break else: break else: raise ValueError('Could not calculate %s terms for %s' % (str(prec), expr)) return rs_trunc(p1, gen, prec)
46d32330018e06a1580317f1ad59cd09de41db2ecddff3118ffd1ea95e9e637d
"""OO layer for several polynomial representations. """ from sympy.core.numbers import oo from sympy.core.sympify import CantSympify from sympy.polys.polyerrors import CoercionFailed, NotReversible, NotInvertible from sympy.polys.polyutils import PicklableWithSlots class GenericPoly(PicklableWithSlots): """Base class for low-level polynomial representations. """ def ground_to_ring(f): """Make the ground domain a ring. """ return f.set_domain(f.dom.get_ring()) def ground_to_field(f): """Make the ground domain a field. """ return f.set_domain(f.dom.get_field()) def ground_to_exact(f): """Make the ground domain exact. """ return f.set_domain(f.dom.get_exact()) @classmethod def _perify_factors(per, result, include): if include: coeff, factors = result factors = [ (per(g), k) for g, k in factors ] if include: return coeff, factors else: return factors from sympy.polys.densebasic import ( dmp_validate, dup_normal, dmp_normal, dup_convert, dmp_convert, dmp_from_sympy, dup_strip, dup_degree, dmp_degree_in, dmp_degree_list, dmp_negative_p, dup_LC, dmp_ground_LC, dup_TC, dmp_ground_TC, dmp_ground_nth, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_ground_p, dup_from_dict, dmp_from_dict, dmp_to_dict, dmp_deflate, dmp_inject, dmp_eject, dmp_terms_gcd, dmp_list_terms, dmp_exclude, dmp_slice_in, dmp_permute, dmp_to_tuple,) from sympy.polys.densearith import ( dmp_add_ground, dmp_sub_ground, dmp_mul_ground, dmp_quo_ground, dmp_exquo_ground, dmp_abs, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dmp_sqr, dup_pow, dmp_pow, dmp_pdiv, dmp_prem, dmp_pquo, dmp_pexquo, dmp_div, dup_rem, dmp_rem, dmp_quo, dmp_exquo, dmp_add_mul, dmp_sub_mul, dmp_max_norm, dmp_l1_norm, dmp_l2_norm_squared) from sympy.polys.densetools import ( dmp_clear_denoms, dmp_integrate_in, dmp_diff_in, dmp_eval_in, dup_revert, dmp_ground_trunc, dmp_ground_content, dmp_ground_primitive, dmp_ground_monic, dmp_compose, dup_decompose, dup_shift, dup_transform, dmp_lift) from sympy.polys.euclidtools import ( dup_half_gcdex, dup_gcdex, dup_invert, dmp_subresultants, dmp_resultant, dmp_discriminant, dmp_inner_gcd, dmp_gcd, dmp_lcm, dmp_cancel) from sympy.polys.sqfreetools import ( dup_gff_list, dmp_norm, dmp_sqf_p, dmp_sqf_norm, dmp_sqf_part, dmp_sqf_list, dmp_sqf_list_include) from sympy.polys.factortools import ( dup_cyclotomic_p, dmp_irreducible_p, dmp_factor_list, dmp_factor_list_include) from sympy.polys.rootisolation import ( dup_isolate_real_roots_sqf, dup_isolate_real_roots, dup_isolate_all_roots_sqf, dup_isolate_all_roots, dup_refine_real_root, dup_count_real_roots, dup_count_complex_roots, dup_sturm, dup_cauchy_upper_bound, dup_cauchy_lower_bound, dup_mignotte_sep_bound_squared) from sympy.polys.polyerrors import ( UnificationFailed, PolynomialError) def init_normal_DMP(rep, lev, dom): return DMP(dmp_normal(rep, lev, dom), dom, lev) class DMP(PicklableWithSlots, CantSympify): """Dense Multivariate Polynomials over `K`. """ __slots__ = ('rep', 'lev', 'dom', 'ring') def __init__(self, rep, dom, lev=None, ring=None): if lev is not None: # Not possible to check with isinstance if type(rep) is dict: rep = dmp_from_dict(rep, lev, dom) elif not isinstance(rep, list): rep = dmp_ground(dom.convert(rep), lev) else: rep, lev = dmp_validate(rep) self.rep = rep self.lev = lev self.dom = dom self.ring = ring def __repr__(f): return "%s(%s, %s, %s)" % (f.__class__.__name__, f.rep, f.dom, f.ring) def __hash__(f): return hash((f.__class__.__name__, f.to_tuple(), f.lev, f.dom, f.ring)) def unify(f, g): """Unify representations of two multivariate polynomials. """ if not isinstance(g, DMP) or f.lev != g.lev: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if f.dom == g.dom and f.ring == g.ring: return f.lev, f.dom, f.per, f.rep, g.rep else: lev, dom = f.lev, f.dom.unify(g.dom) ring = f.ring if g.ring is not None: if ring is not None: ring = ring.unify(g.ring) else: ring = g.ring F = dmp_convert(f.rep, lev, f.dom, dom) G = dmp_convert(g.rep, lev, g.dom, dom) def per(rep, dom=dom, lev=lev, kill=False): if kill: if not lev: return rep else: lev -= 1 return DMP(rep, dom, lev, ring) return lev, dom, per, F, G def per(f, rep, dom=None, kill=False, ring=None): """Create a DMP out of the given representation. """ lev = f.lev if kill: if not lev: return rep else: lev -= 1 if dom is None: dom = f.dom if ring is None: ring = f.ring return DMP(rep, dom, lev, ring) @classmethod def zero(cls, lev, dom, ring=None): return DMP(0, dom, lev, ring) @classmethod def one(cls, lev, dom, ring=None): return DMP(1, dom, lev, ring) @classmethod def from_list(cls, rep, lev, dom): """Create an instance of ``cls`` given a list of native coefficients. """ return cls(dmp_convert(rep, lev, None, dom), dom, lev) @classmethod def from_sympy_list(cls, rep, lev, dom): """Create an instance of ``cls`` given a list of SymPy coefficients. """ return cls(dmp_from_sympy(rep, lev, dom), dom, lev) def to_dict(f, zero=False): """Convert ``f`` to a dict representation with native coefficients. """ return dmp_to_dict(f.rep, f.lev, f.dom, zero=zero) def to_sympy_dict(f, zero=False): """Convert ``f`` to a dict representation with SymPy coefficients. """ rep = dmp_to_dict(f.rep, f.lev, f.dom, zero=zero) for k, v in rep.items(): rep[k] = f.dom.to_sympy(v) return rep def to_list(f): """Convert ``f`` to a list representation with native coefficients. """ return f.rep def to_sympy_list(f): """Convert ``f`` to a list representation with SymPy coefficients. """ def sympify_nested_list(rep): out = [] for val in rep: if isinstance(val, list): out.append(sympify_nested_list(val)) else: out.append(f.dom.to_sympy(val)) return out return sympify_nested_list(f.rep) def to_tuple(f): """ Convert ``f`` to a tuple representation with native coefficients. This is needed for hashing. """ return dmp_to_tuple(f.rep, f.lev) @classmethod def from_dict(cls, rep, lev, dom): """Construct and instance of ``cls`` from a ``dict`` representation. """ return cls(dmp_from_dict(rep, lev, dom), dom, lev) @classmethod def from_monoms_coeffs(cls, monoms, coeffs, lev, dom, ring=None): return DMP(dict(list(zip(monoms, coeffs))), dom, lev, ring) def to_ring(f): """Make the ground domain a ring. """ return f.convert(f.dom.get_ring()) def to_field(f): """Make the ground domain a field. """ return f.convert(f.dom.get_field()) def to_exact(f): """Make the ground domain exact. """ return f.convert(f.dom.get_exact()) def convert(f, dom): """Convert the ground domain of ``f``. """ if f.dom == dom: return f else: return DMP(dmp_convert(f.rep, f.lev, f.dom, dom), dom, f.lev) def slice(f, m, n, j=0): """Take a continuous subsequence of terms of ``f``. """ return f.per(dmp_slice_in(f.rep, m, n, j, f.lev, f.dom)) def coeffs(f, order=None): """Returns all non-zero coefficients from ``f`` in lex order. """ return [ c for _, c in dmp_list_terms(f.rep, f.lev, f.dom, order=order) ] def monoms(f, order=None): """Returns all non-zero monomials from ``f`` in lex order. """ return [ m for m, _ in dmp_list_terms(f.rep, f.lev, f.dom, order=order) ] def terms(f, order=None): """Returns all non-zero terms from ``f`` in lex order. """ return dmp_list_terms(f.rep, f.lev, f.dom, order=order) def all_coeffs(f): """Returns all coefficients from ``f``. """ if not f.lev: if not f: return [f.dom.zero] else: return [ c for c in f.rep ] else: raise PolynomialError('multivariate polynomials not supported') def all_monoms(f): """Returns all monomials from ``f``. """ if not f.lev: n = dup_degree(f.rep) if n < 0: return [(0,)] else: return [ (n - i,) for i, c in enumerate(f.rep) ] else: raise PolynomialError('multivariate polynomials not supported') def all_terms(f): """Returns all terms from a ``f``. """ if not f.lev: n = dup_degree(f.rep) if n < 0: return [((0,), f.dom.zero)] else: return [ ((n - i,), c) for i, c in enumerate(f.rep) ] else: raise PolynomialError('multivariate polynomials not supported') def lift(f): """Convert algebraic coefficients to rationals. """ return f.per(dmp_lift(f.rep, f.lev, f.dom), dom=f.dom.dom) def deflate(f): """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """ J, F = dmp_deflate(f.rep, f.lev, f.dom) return J, f.per(F) def inject(f, front=False): """Inject ground domain generators into ``f``. """ F, lev = dmp_inject(f.rep, f.lev, f.dom, front=front) return f.__class__(F, f.dom.dom, lev) def eject(f, dom, front=False): """Eject selected generators into the ground domain. """ F = dmp_eject(f.rep, f.lev, dom, front=front) return f.__class__(F, dom, f.lev - len(dom.symbols)) def exclude(f): r""" Remove useless generators from ``f``. Returns the removed generators and the new excluded ``f``. Examples ======== >>> from sympy.polys.polyclasses import DMP >>> from sympy.polys.domains import ZZ >>> DMP([[[ZZ(1)]], [[ZZ(1)], [ZZ(2)]]], ZZ).exclude() ([2], DMP([[1], [1, 2]], ZZ, None)) """ J, F, u = dmp_exclude(f.rep, f.lev, f.dom) return J, f.__class__(F, f.dom, u) def permute(f, P): r""" Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`. Examples ======== >>> from sympy.polys.polyclasses import DMP >>> from sympy.polys.domains import ZZ >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 0, 2]) DMP([[[2], []], [[1, 0], []]], ZZ, None) >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 2, 0]) DMP([[[1], []], [[2, 0], []]], ZZ, None) """ return f.per(dmp_permute(f.rep, P, f.lev, f.dom)) def terms_gcd(f): """Remove GCD of terms from the polynomial ``f``. """ J, F = dmp_terms_gcd(f.rep, f.lev, f.dom) return J, f.per(F) def add_ground(f, c): """Add an element of the ground domain to ``f``. """ return f.per(dmp_add_ground(f.rep, f.dom.convert(c), f.lev, f.dom)) def sub_ground(f, c): """Subtract an element of the ground domain from ``f``. """ return f.per(dmp_sub_ground(f.rep, f.dom.convert(c), f.lev, f.dom)) def mul_ground(f, c): """Multiply ``f`` by a an element of the ground domain. """ return f.per(dmp_mul_ground(f.rep, f.dom.convert(c), f.lev, f.dom)) def quo_ground(f, c): """Quotient of ``f`` by a an element of the ground domain. """ return f.per(dmp_quo_ground(f.rep, f.dom.convert(c), f.lev, f.dom)) def exquo_ground(f, c): """Exact quotient of ``f`` by a an element of the ground domain. """ return f.per(dmp_exquo_ground(f.rep, f.dom.convert(c), f.lev, f.dom)) def abs(f): """Make all coefficients in ``f`` positive. """ return f.per(dmp_abs(f.rep, f.lev, f.dom)) def neg(f): """Negate all coefficients in ``f``. """ return f.per(dmp_neg(f.rep, f.lev, f.dom)) def add(f, g): """Add two multivariate polynomials ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_add(F, G, lev, dom)) def sub(f, g): """Subtract two multivariate polynomials ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_sub(F, G, lev, dom)) def mul(f, g): """Multiply two multivariate polynomials ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_mul(F, G, lev, dom)) def sqr(f): """Square a multivariate polynomial ``f``. """ return f.per(dmp_sqr(f.rep, f.lev, f.dom)) def pow(f, n): """Raise ``f`` to a non-negative power ``n``. """ if isinstance(n, int): return f.per(dmp_pow(f.rep, n, f.lev, f.dom)) else: raise TypeError("``int`` expected, got %s" % type(n)) def pdiv(f, g): """Polynomial pseudo-division of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) q, r = dmp_pdiv(F, G, lev, dom) return per(q), per(r) def prem(f, g): """Polynomial pseudo-remainder of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_prem(F, G, lev, dom)) def pquo(f, g): """Polynomial pseudo-quotient of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_pquo(F, G, lev, dom)) def pexquo(f, g): """Polynomial exact pseudo-quotient of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_pexquo(F, G, lev, dom)) def div(f, g): """Polynomial division with remainder of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) q, r = dmp_div(F, G, lev, dom) return per(q), per(r) def rem(f, g): """Computes polynomial remainder of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_rem(F, G, lev, dom)) def quo(f, g): """Computes polynomial quotient of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_quo(F, G, lev, dom)) def exquo(f, g): """Computes polynomial exact quotient of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) res = per(dmp_exquo(F, G, lev, dom)) if f.ring and res not in f.ring: from sympy.polys.polyerrors import ExactQuotientFailed raise ExactQuotientFailed(f, g, f.ring) return res def degree(f, j=0): """Returns the leading degree of ``f`` in ``x_j``. """ if isinstance(j, int): return dmp_degree_in(f.rep, j, f.lev) else: raise TypeError("``int`` expected, got %s" % type(j)) def degree_list(f): """Returns a list of degrees of ``f``. """ return dmp_degree_list(f.rep, f.lev) def total_degree(f): """Returns the total degree of ``f``. """ return max(sum(m) for m in f.monoms()) def homogenize(f, s): """Return homogeneous polynomial of ``f``""" td = f.total_degree() result = {} new_symbol = (s == len(f.terms()[0][0])) for term in f.terms(): d = sum(term[0]) if d < td: i = td - d else: i = 0 if new_symbol: result[term[0] + (i,)] = term[1] else: l = list(term[0]) l[s] += i result[tuple(l)] = term[1] return DMP(result, f.dom, f.lev + int(new_symbol), f.ring) def homogeneous_order(f): """Returns the homogeneous order of ``f``. """ if f.is_zero: return -oo monoms = f.monoms() tdeg = sum(monoms[0]) for monom in monoms: _tdeg = sum(monom) if _tdeg != tdeg: return None return tdeg def LC(f): """Returns the leading coefficient of ``f``. """ return dmp_ground_LC(f.rep, f.lev, f.dom) def TC(f): """Returns the trailing coefficient of ``f``. """ return dmp_ground_TC(f.rep, f.lev, f.dom) def nth(f, *N): """Returns the ``n``-th coefficient of ``f``. """ if all(isinstance(n, int) for n in N): return dmp_ground_nth(f.rep, N, f.lev, f.dom) else: raise TypeError("a sequence of integers expected") def max_norm(f): """Returns maximum norm of ``f``. """ return dmp_max_norm(f.rep, f.lev, f.dom) def l1_norm(f): """Returns l1 norm of ``f``. """ return dmp_l1_norm(f.rep, f.lev, f.dom) def l2_norm_squared(f): """Return squared l2 norm of ``f``. """ return dmp_l2_norm_squared(f.rep, f.lev, f.dom) def clear_denoms(f): """Clear denominators, but keep the ground domain. """ coeff, F = dmp_clear_denoms(f.rep, f.lev, f.dom) return coeff, f.per(F) def integrate(f, m=1, j=0): """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """ if not isinstance(m, int): raise TypeError("``int`` expected, got %s" % type(m)) if not isinstance(j, int): raise TypeError("``int`` expected, got %s" % type(j)) return f.per(dmp_integrate_in(f.rep, m, j, f.lev, f.dom)) def diff(f, m=1, j=0): """Computes the ``m``-th order derivative of ``f`` in ``x_j``. """ if not isinstance(m, int): raise TypeError("``int`` expected, got %s" % type(m)) if not isinstance(j, int): raise TypeError("``int`` expected, got %s" % type(j)) return f.per(dmp_diff_in(f.rep, m, j, f.lev, f.dom)) def eval(f, a, j=0): """Evaluates ``f`` at the given point ``a`` in ``x_j``. """ if not isinstance(j, int): raise TypeError("``int`` expected, got %s" % type(j)) return f.per(dmp_eval_in(f.rep, f.dom.convert(a), j, f.lev, f.dom), kill=True) def half_gcdex(f, g): """Half extended Euclidean algorithm, if univariate. """ lev, dom, per, F, G = f.unify(g) if not lev: s, h = dup_half_gcdex(F, G, dom) return per(s), per(h) else: raise ValueError('univariate polynomial expected') def gcdex(f, g): """Extended Euclidean algorithm, if univariate. """ lev, dom, per, F, G = f.unify(g) if not lev: s, t, h = dup_gcdex(F, G, dom) return per(s), per(t), per(h) else: raise ValueError('univariate polynomial expected') def invert(f, g): """Invert ``f`` modulo ``g``, if possible. """ lev, dom, per, F, G = f.unify(g) if not lev: return per(dup_invert(F, G, dom)) else: raise ValueError('univariate polynomial expected') def revert(f, n): """Compute ``f**(-1)`` mod ``x**n``. """ if not f.lev: return f.per(dup_revert(f.rep, n, f.dom)) else: raise ValueError('univariate polynomial expected') def subresultants(f, g): """Computes subresultant PRS sequence of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) R = dmp_subresultants(F, G, lev, dom) return list(map(per, R)) def resultant(f, g, includePRS=False): """Computes resultant of ``f`` and ``g`` via PRS. """ lev, dom, per, F, G = f.unify(g) if includePRS: res, R = dmp_resultant(F, G, lev, dom, includePRS=includePRS) return per(res, kill=True), list(map(per, R)) return per(dmp_resultant(F, G, lev, dom), kill=True) def discriminant(f): """Computes discriminant of ``f``. """ return f.per(dmp_discriminant(f.rep, f.lev, f.dom), kill=True) def cofactors(f, g): """Returns GCD of ``f`` and ``g`` and their cofactors. """ lev, dom, per, F, G = f.unify(g) h, cff, cfg = dmp_inner_gcd(F, G, lev, dom) return per(h), per(cff), per(cfg) def gcd(f, g): """Returns polynomial GCD of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_gcd(F, G, lev, dom)) def lcm(f, g): """Returns polynomial LCM of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_lcm(F, G, lev, dom)) def cancel(f, g, include=True): """Cancel common factors in a rational function ``f/g``. """ lev, dom, per, F, G = f.unify(g) if include: F, G = dmp_cancel(F, G, lev, dom, include=True) else: cF, cG, F, G = dmp_cancel(F, G, lev, dom, include=False) F, G = per(F), per(G) if include: return F, G else: return cF, cG, F, G def trunc(f, p): """Reduce ``f`` modulo a constant ``p``. """ return f.per(dmp_ground_trunc(f.rep, f.dom.convert(p), f.lev, f.dom)) def monic(f): """Divides all coefficients by ``LC(f)``. """ return f.per(dmp_ground_monic(f.rep, f.lev, f.dom)) def content(f): """Returns GCD of polynomial coefficients. """ return dmp_ground_content(f.rep, f.lev, f.dom) def primitive(f): """Returns content and a primitive form of ``f``. """ cont, F = dmp_ground_primitive(f.rep, f.lev, f.dom) return cont, f.per(F) def compose(f, g): """Computes functional composition of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_compose(F, G, lev, dom)) def decompose(f): """Computes functional decomposition of ``f``. """ if not f.lev: return list(map(f.per, dup_decompose(f.rep, f.dom))) else: raise ValueError('univariate polynomial expected') def shift(f, a): """Efficiently compute Taylor shift ``f(x + a)``. """ if not f.lev: return f.per(dup_shift(f.rep, f.dom.convert(a), f.dom)) else: raise ValueError('univariate polynomial expected') def transform(f, p, q): """Evaluate functional transformation ``q**n * f(p/q)``.""" if f.lev: raise ValueError('univariate polynomial expected') lev, dom, per, P, Q = p.unify(q) lev, dom, per, F, P = f.unify(per(P, dom, lev)) lev, dom, per, F, Q = per(F, dom, lev).unify(per(Q, dom, lev)) if not lev: return per(dup_transform(F, P, Q, dom)) else: raise ValueError('univariate polynomial expected') def sturm(f): """Computes the Sturm sequence of ``f``. """ if not f.lev: return list(map(f.per, dup_sturm(f.rep, f.dom))) else: raise ValueError('univariate polynomial expected') def cauchy_upper_bound(f): """Computes the Cauchy upper bound on the roots of ``f``. """ if not f.lev: return dup_cauchy_upper_bound(f.rep, f.dom) else: raise ValueError('univariate polynomial expected') def cauchy_lower_bound(f): """Computes the Cauchy lower bound on the nonzero roots of ``f``. """ if not f.lev: return dup_cauchy_lower_bound(f.rep, f.dom) else: raise ValueError('univariate polynomial expected') def mignotte_sep_bound_squared(f): """Computes the squared Mignotte bound on root separations of ``f``. """ if not f.lev: return dup_mignotte_sep_bound_squared(f.rep, f.dom) else: raise ValueError('univariate polynomial expected') def gff_list(f): """Computes greatest factorial factorization of ``f``. """ if not f.lev: return [ (f.per(g), k) for g, k in dup_gff_list(f.rep, f.dom) ] else: raise ValueError('univariate polynomial expected') def norm(f): """Computes ``Norm(f)``.""" r = dmp_norm(f.rep, f.lev, f.dom) return f.per(r, dom=f.dom.dom) def sqf_norm(f): """Computes square-free norm of ``f``. """ s, g, r = dmp_sqf_norm(f.rep, f.lev, f.dom) return s, f.per(g), f.per(r, dom=f.dom.dom) def sqf_part(f): """Computes square-free part of ``f``. """ return f.per(dmp_sqf_part(f.rep, f.lev, f.dom)) def sqf_list(f, all=False): """Returns a list of square-free factors of ``f``. """ coeff, factors = dmp_sqf_list(f.rep, f.lev, f.dom, all) return coeff, [ (f.per(g), k) for g, k in factors ] def sqf_list_include(f, all=False): """Returns a list of square-free factors of ``f``. """ factors = dmp_sqf_list_include(f.rep, f.lev, f.dom, all) return [ (f.per(g), k) for g, k in factors ] def factor_list(f): """Returns a list of irreducible factors of ``f``. """ coeff, factors = dmp_factor_list(f.rep, f.lev, f.dom) return coeff, [ (f.per(g), k) for g, k in factors ] def factor_list_include(f): """Returns a list of irreducible factors of ``f``. """ factors = dmp_factor_list_include(f.rep, f.lev, f.dom) return [ (f.per(g), k) for g, k in factors ] def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): """Compute isolating intervals for roots of ``f``. """ if not f.lev: if not all: if not sqf: return dup_isolate_real_roots(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) else: return dup_isolate_real_roots_sqf(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) else: if not sqf: return dup_isolate_all_roots(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) else: return dup_isolate_all_roots_sqf(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) else: raise PolynomialError( "Cannot isolate roots of a multivariate polynomial") def refine_root(f, s, t, eps=None, steps=None, fast=False): """ Refine an isolating interval to the given precision. ``eps`` should be a rational number. """ if not f.lev: return dup_refine_real_root(f.rep, s, t, f.dom, eps=eps, steps=steps, fast=fast) else: raise PolynomialError( "Cannot refine a root of a multivariate polynomial") def count_real_roots(f, inf=None, sup=None): """Return the number of real roots of ``f`` in ``[inf, sup]``. """ return dup_count_real_roots(f.rep, f.dom, inf=inf, sup=sup) def count_complex_roots(f, inf=None, sup=None): """Return the number of complex roots of ``f`` in ``[inf, sup]``. """ return dup_count_complex_roots(f.rep, f.dom, inf=inf, sup=sup) @property def is_zero(f): """Returns ``True`` if ``f`` is a zero polynomial. """ return dmp_zero_p(f.rep, f.lev) @property def is_one(f): """Returns ``True`` if ``f`` is a unit polynomial. """ return dmp_one_p(f.rep, f.lev, f.dom) @property def is_ground(f): """Returns ``True`` if ``f`` is an element of the ground domain. """ return dmp_ground_p(f.rep, None, f.lev) @property def is_sqf(f): """Returns ``True`` if ``f`` is a square-free polynomial. """ return dmp_sqf_p(f.rep, f.lev, f.dom) @property def is_monic(f): """Returns ``True`` if the leading coefficient of ``f`` is one. """ return f.dom.is_one(dmp_ground_LC(f.rep, f.lev, f.dom)) @property def is_primitive(f): """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """ return f.dom.is_one(dmp_ground_content(f.rep, f.lev, f.dom)) @property def is_linear(f): """Returns ``True`` if ``f`` is linear in all its variables. """ return all(sum(monom) <= 1 for monom in dmp_to_dict(f.rep, f.lev, f.dom).keys()) @property def is_quadratic(f): """Returns ``True`` if ``f`` is quadratic in all its variables. """ return all(sum(monom) <= 2 for monom in dmp_to_dict(f.rep, f.lev, f.dom).keys()) @property def is_monomial(f): """Returns ``True`` if ``f`` is zero or has only one term. """ return len(f.to_dict()) <= 1 @property def is_homogeneous(f): """Returns ``True`` if ``f`` is a homogeneous polynomial. """ return f.homogeneous_order() is not None @property def is_irreducible(f): """Returns ``True`` if ``f`` has no factors over its domain. """ return dmp_irreducible_p(f.rep, f.lev, f.dom) @property def is_cyclotomic(f): """Returns ``True`` if ``f`` is a cyclotomic polynomial. """ if not f.lev: return dup_cyclotomic_p(f.rep, f.dom) else: return False def __abs__(f): return f.abs() def __neg__(f): return f.neg() def __add__(f, g): if not isinstance(g, DMP): try: g = f.per(dmp_ground(f.dom.convert(g), f.lev)) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: g = f.ring.convert(g) except (CoercionFailed, NotImplementedError): return NotImplemented return f.add(g) def __radd__(f, g): return f.__add__(g) def __sub__(f, g): if not isinstance(g, DMP): try: g = f.per(dmp_ground(f.dom.convert(g), f.lev)) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: g = f.ring.convert(g) except (CoercionFailed, NotImplementedError): return NotImplemented return f.sub(g) def __rsub__(f, g): return (-f).__add__(g) def __mul__(f, g): if isinstance(g, DMP): return f.mul(g) else: try: return f.mul_ground(g) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: return f.mul(f.ring.convert(g)) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __truediv__(f, g): if isinstance(g, DMP): return f.exquo(g) else: try: return f.mul_ground(g) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: return f.exquo(f.ring.convert(g)) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __rtruediv__(f, g): if isinstance(g, DMP): return g.exquo(f) elif f.ring is not None: try: return f.ring.convert(g).exquo(f) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __rmul__(f, g): return f.__mul__(g) def __pow__(f, n): return f.pow(n) def __divmod__(f, g): return f.div(g) def __mod__(f, g): return f.rem(g) def __floordiv__(f, g): if isinstance(g, DMP): return f.quo(g) else: try: return f.quo_ground(g) except TypeError: return NotImplemented def __eq__(f, g): try: _, _, _, F, G = f.unify(g) if f.lev == g.lev: return F == G except UnificationFailed: pass return False def __ne__(f, g): return not f == g def eq(f, g, strict=False): if not strict: return f == g else: return f._strict_eq(g) def ne(f, g, strict=False): return not f.eq(g, strict=strict) def _strict_eq(f, g): return isinstance(g, f.__class__) and f.lev == g.lev \ and f.dom == g.dom \ and f.rep == g.rep def __lt__(f, g): _, _, _, F, G = f.unify(g) return F < G def __le__(f, g): _, _, _, F, G = f.unify(g) return F <= G def __gt__(f, g): _, _, _, F, G = f.unify(g) return F > G def __ge__(f, g): _, _, _, F, G = f.unify(g) return F >= G def __bool__(f): return not dmp_zero_p(f.rep, f.lev) def init_normal_DMF(num, den, lev, dom): return DMF(dmp_normal(num, lev, dom), dmp_normal(den, lev, dom), dom, lev) class DMF(PicklableWithSlots, CantSympify): """Dense Multivariate Fractions over `K`. """ __slots__ = ('num', 'den', 'lev', 'dom', 'ring') def __init__(self, rep, dom, lev=None, ring=None): num, den, lev = self._parse(rep, dom, lev) num, den = dmp_cancel(num, den, lev, dom) self.num = num self.den = den self.lev = lev self.dom = dom self.ring = ring @classmethod def new(cls, rep, dom, lev=None, ring=None): num, den, lev = cls._parse(rep, dom, lev) obj = object.__new__(cls) obj.num = num obj.den = den obj.lev = lev obj.dom = dom obj.ring = ring return obj @classmethod def _parse(cls, rep, dom, lev=None): if isinstance(rep, tuple): num, den = rep if lev is not None: if isinstance(num, dict): num = dmp_from_dict(num, lev, dom) if isinstance(den, dict): den = dmp_from_dict(den, lev, dom) else: num, num_lev = dmp_validate(num) den, den_lev = dmp_validate(den) if num_lev == den_lev: lev = num_lev else: raise ValueError('inconsistent number of levels') if dmp_zero_p(den, lev): raise ZeroDivisionError('fraction denominator') if dmp_zero_p(num, lev): den = dmp_one(lev, dom) else: if dmp_negative_p(den, lev, dom): num = dmp_neg(num, lev, dom) den = dmp_neg(den, lev, dom) else: num = rep if lev is not None: if isinstance(num, dict): num = dmp_from_dict(num, lev, dom) elif not isinstance(num, list): num = dmp_ground(dom.convert(num), lev) else: num, lev = dmp_validate(num) den = dmp_one(lev, dom) return num, den, lev def __repr__(f): return "%s((%s, %s), %s, %s)" % (f.__class__.__name__, f.num, f.den, f.dom, f.ring) def __hash__(f): return hash((f.__class__.__name__, dmp_to_tuple(f.num, f.lev), dmp_to_tuple(f.den, f.lev), f.lev, f.dom, f.ring)) def poly_unify(f, g): """Unify a multivariate fraction and a polynomial. """ if not isinstance(g, DMP) or f.lev != g.lev: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if f.dom == g.dom and f.ring == g.ring: return (f.lev, f.dom, f.per, (f.num, f.den), g.rep) else: lev, dom = f.lev, f.dom.unify(g.dom) ring = f.ring if g.ring is not None: if ring is not None: ring = ring.unify(g.ring) else: ring = g.ring F = (dmp_convert(f.num, lev, f.dom, dom), dmp_convert(f.den, lev, f.dom, dom)) G = dmp_convert(g.rep, lev, g.dom, dom) def per(num, den, cancel=True, kill=False, lev=lev): if kill: if not lev: return num/den else: lev = lev - 1 if cancel: num, den = dmp_cancel(num, den, lev, dom) return f.__class__.new((num, den), dom, lev, ring=ring) return lev, dom, per, F, G def frac_unify(f, g): """Unify representations of two multivariate fractions. """ if not isinstance(g, DMF) or f.lev != g.lev: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if f.dom == g.dom and f.ring == g.ring: return (f.lev, f.dom, f.per, (f.num, f.den), (g.num, g.den)) else: lev, dom = f.lev, f.dom.unify(g.dom) ring = f.ring if g.ring is not None: if ring is not None: ring = ring.unify(g.ring) else: ring = g.ring F = (dmp_convert(f.num, lev, f.dom, dom), dmp_convert(f.den, lev, f.dom, dom)) G = (dmp_convert(g.num, lev, g.dom, dom), dmp_convert(g.den, lev, g.dom, dom)) def per(num, den, cancel=True, kill=False, lev=lev): if kill: if not lev: return num/den else: lev = lev - 1 if cancel: num, den = dmp_cancel(num, den, lev, dom) return f.__class__.new((num, den), dom, lev, ring=ring) return lev, dom, per, F, G def per(f, num, den, cancel=True, kill=False, ring=None): """Create a DMF out of the given representation. """ lev, dom = f.lev, f.dom if kill: if not lev: return num/den else: lev -= 1 if cancel: num, den = dmp_cancel(num, den, lev, dom) if ring is None: ring = f.ring return f.__class__.new((num, den), dom, lev, ring=ring) def half_per(f, rep, kill=False): """Create a DMP out of the given representation. """ lev = f.lev if kill: if not lev: return rep else: lev -= 1 return DMP(rep, f.dom, lev) @classmethod def zero(cls, lev, dom, ring=None): return cls.new(0, dom, lev, ring=ring) @classmethod def one(cls, lev, dom, ring=None): return cls.new(1, dom, lev, ring=ring) def numer(f): """Returns the numerator of ``f``. """ return f.half_per(f.num) def denom(f): """Returns the denominator of ``f``. """ return f.half_per(f.den) def cancel(f): """Remove common factors from ``f.num`` and ``f.den``. """ return f.per(f.num, f.den) def neg(f): """Negate all coefficients in ``f``. """ return f.per(dmp_neg(f.num, f.lev, f.dom), f.den, cancel=False) def add(f, g): """Add two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_add(dmp_mul(F_num, G_den, lev, dom), dmp_mul(F_den, G_num, lev, dom), lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den) def sub(f, g): """Subtract two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_sub_mul(F_num, F_den, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_sub(dmp_mul(F_num, G_den, lev, dom), dmp_mul(F_den, G_num, lev, dom), lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den) def mul(f, g): """Multiply two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_mul(F_num, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_mul(F_num, G_num, lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den) def pow(f, n): """Raise ``f`` to a non-negative power ``n``. """ if isinstance(n, int): num, den = f.num, f.den if n < 0: num, den, n = den, num, -n return f.per(dmp_pow(num, n, f.lev, f.dom), dmp_pow(den, n, f.lev, f.dom), cancel=False) else: raise TypeError("``int`` expected, got %s" % type(n)) def quo(f, g): """Computes quotient of fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = F_num, dmp_mul(F_den, G, lev, dom) else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_mul(F_num, G_den, lev, dom) den = dmp_mul(F_den, G_num, lev, dom) res = per(num, den) if f.ring is not None and res not in f.ring: from sympy.polys.polyerrors import ExactQuotientFailed raise ExactQuotientFailed(f, g, f.ring) return res exquo = quo def invert(f, check=True): """Computes inverse of a fraction ``f``. """ if check and f.ring is not None and not f.ring.is_unit(f): raise NotReversible(f, f.ring) res = f.per(f.den, f.num, cancel=False) return res @property def is_zero(f): """Returns ``True`` if ``f`` is a zero fraction. """ return dmp_zero_p(f.num, f.lev) @property def is_one(f): """Returns ``True`` if ``f`` is a unit fraction. """ return dmp_one_p(f.num, f.lev, f.dom) and \ dmp_one_p(f.den, f.lev, f.dom) def __neg__(f): return f.neg() def __add__(f, g): if isinstance(g, (DMP, DMF)): return f.add(g) try: return f.add(f.half_per(g)) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: return f.add(f.ring.convert(g)) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __radd__(f, g): return f.__add__(g) def __sub__(f, g): if isinstance(g, (DMP, DMF)): return f.sub(g) try: return f.sub(f.half_per(g)) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: return f.sub(f.ring.convert(g)) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __rsub__(f, g): return (-f).__add__(g) def __mul__(f, g): if isinstance(g, (DMP, DMF)): return f.mul(g) try: return f.mul(f.half_per(g)) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: return f.mul(f.ring.convert(g)) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __rmul__(f, g): return f.__mul__(g) def __pow__(f, n): return f.pow(n) def __truediv__(f, g): if isinstance(g, (DMP, DMF)): return f.quo(g) try: return f.quo(f.half_per(g)) except TypeError: return NotImplemented except (CoercionFailed, NotImplementedError): if f.ring is not None: try: return f.quo(f.ring.convert(g)) except (CoercionFailed, NotImplementedError): pass return NotImplemented def __rtruediv__(self, g): r = self.invert(check=False)*g if self.ring and r not in self.ring: from sympy.polys.polyerrors import ExactQuotientFailed raise ExactQuotientFailed(g, self, self.ring) return r def __eq__(f, g): try: if isinstance(g, DMP): _, _, _, (F_num, F_den), G = f.poly_unify(g) if f.lev == g.lev: return dmp_one_p(F_den, f.lev, f.dom) and F_num == G else: _, _, _, F, G = f.frac_unify(g) if f.lev == g.lev: return F == G except UnificationFailed: pass return False def __ne__(f, g): try: if isinstance(g, DMP): _, _, _, (F_num, F_den), G = f.poly_unify(g) if f.lev == g.lev: return not (dmp_one_p(F_den, f.lev, f.dom) and F_num == G) else: _, _, _, F, G = f.frac_unify(g) if f.lev == g.lev: return F != G except UnificationFailed: pass return True def __lt__(f, g): _, _, _, F, G = f.frac_unify(g) return F < G def __le__(f, g): _, _, _, F, G = f.frac_unify(g) return F <= G def __gt__(f, g): _, _, _, F, G = f.frac_unify(g) return F > G def __ge__(f, g): _, _, _, F, G = f.frac_unify(g) return F >= G def __bool__(f): return not dmp_zero_p(f.num, f.lev) def init_normal_ANP(rep, mod, dom): return ANP(dup_normal(rep, dom), dup_normal(mod, dom), dom) class ANP(PicklableWithSlots, CantSympify): """Dense Algebraic Number Polynomials over a field. """ __slots__ = ('rep', 'mod', 'dom') def __init__(self, rep, mod, dom): # Not possible to check with isinstance if type(rep) is dict: self.rep = dup_from_dict(rep, dom) else: if isinstance(rep, list): rep = [dom.convert(a) for a in rep] else: rep = [dom.convert(rep)] self.rep = dup_strip(rep) if isinstance(mod, DMP): self.mod = mod.rep else: if isinstance(mod, dict): self.mod = dup_from_dict(mod, dom) else: self.mod = dup_strip(mod) self.dom = dom def __repr__(f): return "%s(%s, %s, %s)" % (f.__class__.__name__, f.rep, f.mod, f.dom) def __hash__(f): return hash((f.__class__.__name__, f.to_tuple(), dmp_to_tuple(f.mod, 0), f.dom)) def unify(f, g): """Unify representations of two algebraic numbers. """ if not isinstance(g, ANP) or f.mod != g.mod: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if f.dom == g.dom: return f.dom, f.per, f.rep, g.rep, f.mod else: dom = f.dom.unify(g.dom) F = dup_convert(f.rep, f.dom, dom) G = dup_convert(g.rep, g.dom, dom) if dom != f.dom and dom != g.dom: mod = dup_convert(f.mod, f.dom, dom) else: if dom == f.dom: mod = f.mod else: mod = g.mod per = lambda rep: ANP(rep, mod, dom) return dom, per, F, G, mod def per(f, rep, mod=None, dom=None): return ANP(rep, mod or f.mod, dom or f.dom) @classmethod def zero(cls, mod, dom): return ANP(0, mod, dom) @classmethod def one(cls, mod, dom): return ANP(1, mod, dom) def to_dict(f): """Convert ``f`` to a dict representation with native coefficients. """ return dmp_to_dict(f.rep, 0, f.dom) def to_sympy_dict(f): """Convert ``f`` to a dict representation with SymPy coefficients. """ rep = dmp_to_dict(f.rep, 0, f.dom) for k, v in rep.items(): rep[k] = f.dom.to_sympy(v) return rep def to_list(f): """Convert ``f`` to a list representation with native coefficients. """ return f.rep def to_sympy_list(f): """Convert ``f`` to a list representation with SymPy coefficients. """ return [ f.dom.to_sympy(c) for c in f.rep ] def to_tuple(f): """ Convert ``f`` to a tuple representation with native coefficients. This is needed for hashing. """ return dmp_to_tuple(f.rep, 0) @classmethod def from_list(cls, rep, mod, dom): return ANP(dup_strip(list(map(dom.convert, rep))), mod, dom) def neg(f): return f.per(dup_neg(f.rep, f.dom)) def add(f, g): dom, per, F, G, mod = f.unify(g) return per(dup_add(F, G, dom)) def sub(f, g): dom, per, F, G, mod = f.unify(g) return per(dup_sub(F, G, dom)) def mul(f, g): dom, per, F, G, mod = f.unify(g) return per(dup_rem(dup_mul(F, G, dom), mod, dom)) def pow(f, n): """Raise ``f`` to a non-negative power ``n``. """ if isinstance(n, int): if n < 0: F, n = dup_invert(f.rep, f.mod, f.dom), -n else: F = f.rep return f.per(dup_rem(dup_pow(F, n, f.dom), f.mod, f.dom)) else: raise TypeError("``int`` expected, got %s" % type(n)) def div(f, g): dom, per, F, G, mod = f.unify(g) return (per(dup_rem(dup_mul(F, dup_invert(G, mod, dom), dom), mod, dom)), f.zero(mod, dom)) def rem(f, g): dom, _, _, G, mod = f.unify(g) s, h = dup_half_gcdex(G, mod, dom) if h == [dom.one]: return f.zero(mod, dom) else: raise NotInvertible("zero divisor") def quo(f, g): dom, per, F, G, mod = f.unify(g) return per(dup_rem(dup_mul(F, dup_invert(G, mod, dom), dom), mod, dom)) exquo = quo def LC(f): """Returns the leading coefficient of ``f``. """ return dup_LC(f.rep, f.dom) def TC(f): """Returns the trailing coefficient of ``f``. """ return dup_TC(f.rep, f.dom) @property def is_zero(f): """Returns ``True`` if ``f`` is a zero algebraic number. """ return not f @property def is_one(f): """Returns ``True`` if ``f`` is a unit algebraic number. """ return f.rep == [f.dom.one] @property def is_ground(f): """Returns ``True`` if ``f`` is an element of the ground domain. """ return not f.rep or len(f.rep) == 1 def __pos__(f): return f def __neg__(f): return f.neg() def __add__(f, g): if isinstance(g, ANP): return f.add(g) else: try: return f.add(f.per(g)) except (CoercionFailed, TypeError): return NotImplemented def __radd__(f, g): return f.__add__(g) def __sub__(f, g): if isinstance(g, ANP): return f.sub(g) else: try: return f.sub(f.per(g)) except (CoercionFailed, TypeError): return NotImplemented def __rsub__(f, g): return (-f).__add__(g) def __mul__(f, g): if isinstance(g, ANP): return f.mul(g) else: try: return f.mul(f.per(g)) except (CoercionFailed, TypeError): return NotImplemented def __rmul__(f, g): return f.__mul__(g) def __pow__(f, n): return f.pow(n) def __divmod__(f, g): return f.div(g) def __mod__(f, g): return f.rem(g) def __truediv__(f, g): if isinstance(g, ANP): return f.quo(g) else: try: return f.quo(f.per(g)) except (CoercionFailed, TypeError): return NotImplemented def __eq__(f, g): try: _, _, F, G, _ = f.unify(g) return F == G except UnificationFailed: return False def __ne__(f, g): try: _, _, F, G, _ = f.unify(g) return F != G except UnificationFailed: return True def __lt__(f, g): _, _, F, G, _ = f.unify(g) return F < G def __le__(f, g): _, _, F, G, _ = f.unify(g) return F <= G def __gt__(f, g): _, _, F, G, _ = f.unify(g) return F > G def __ge__(f, g): _, _, F, G, _ = f.unify(g) return F >= G def __bool__(f): return bool(f.rep)
abbe500357b4ac7f53a556d3188c1181e8ac345b7eec789171d3d411d1d83761
"""Advanced tools for dense recursive polynomials in ``K[x]`` or ``K[X]``. """ from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_lshift, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_sqr, dup_div, dup_rem, dmp_rem, dmp_expand, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, ) from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_to_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_zero, dmp_ground, dmp_zero_p, dup_to_raw_dict, dup_from_raw_dict, dmp_zeros ) from sympy.polys.polyerrors import ( MultivariatePolynomialError, DomainError ) from sympy.utilities import variations from math import ceil as _ceil, log as _log def dup_integrate(f, m, K): """ Computes the indefinite integral of ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> R.dup_integrate(x**2 + 2*x, 1) 1/3*x**3 + x**2 >>> R.dup_integrate(x**2 + 2*x, 2) 1/12*x**4 + 1/3*x**3 """ if m <= 0 or not f: return f g = [K.zero]*m for i, c in enumerate(reversed(f)): n = i + 1 for j in range(1, m): n *= i + j + 1 g.insert(0, K.exquo(c, K(n))) return g def dmp_integrate(f, m, u, K): """ Computes the indefinite integral of ``f`` in ``x_0`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) >>> R.dmp_integrate(x + 2*y, 1) 1/2*x**2 + 2*x*y >>> R.dmp_integrate(x + 2*y, 2) 1/6*x**3 + x**2*y """ if not u: return dup_integrate(f, m, K) if m <= 0 or dmp_zero_p(f, u): return f g, v = dmp_zeros(m, u - 1, K), u - 1 for i, c in enumerate(reversed(f)): n = i + 1 for j in range(1, m): n *= i + j + 1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g def _rec_integrate_in(g, m, v, i, j, K): """Recursive helper for :func:`dmp_integrate_in`.""" if i == j: return dmp_integrate(g, m, v, K) w, i = v - 1, i + 1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in g ], v) def dmp_integrate_in(f, m, j, u, K): """ Computes the indefinite integral of ``f`` in ``x_j`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) >>> R.dmp_integrate_in(x + 2*y, 1, 0) 1/2*x**2 + 2*x*y >>> R.dmp_integrate_in(x + 2*y, 1, 1) x*y + y**2 """ if j < 0 or j > u: raise IndexError("0 <= j <= u expected, got u = %d, j = %d" % (u, j)) return _rec_integrate_in(f, m, u, 0, j, K) def dup_diff(f, m, K): """ ``m``-th order derivative of a polynomial in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_diff(x**3 + 2*x**2 + 3*x + 4, 1) 3*x**2 + 4*x + 3 >>> R.dup_diff(x**3 + 2*x**2 + 3*x + 4, 2) 6*x + 4 """ if m <= 0: return f n = dup_degree(f) if n < m: return [] deriv = [] if m == 1: for coeff in f[:-m]: deriv.append(K(n)*coeff) n -= 1 else: for coeff in f[:-m]: k = n for i in range(n - 1, n - m, -1): k *= i deriv.append(K(k)*coeff) n -= 1 return dup_strip(deriv) def dmp_diff(f, m, u, K): """ ``m``-th order derivative in ``x_0`` of a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1 >>> R.dmp_diff(f, 1) y**2 + 2*y + 3 >>> R.dmp_diff(f, 2) 0 """ if not u: return dup_diff(f, m, K) if m <= 0: return f n = dmp_degree(f, u) if n < m: return dmp_zero(u) deriv, v = [], u - 1 if m == 1: for coeff in f[:-m]: deriv.append(dmp_mul_ground(coeff, K(n), v, K)) n -= 1 else: for coeff in f[:-m]: k = n for i in range(n - 1, n - m, -1): k *= i deriv.append(dmp_mul_ground(coeff, K(k), v, K)) n -= 1 return dmp_strip(deriv, u) def _rec_diff_in(g, m, v, i, j, K): """Recursive helper for :func:`dmp_diff_in`.""" if i == j: return dmp_diff(g, m, v, K) w, i = v - 1, i + 1 return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in g ], v) def dmp_diff_in(f, m, j, u, K): """ ``m``-th order derivative in ``x_j`` of a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1 >>> R.dmp_diff_in(f, 1, 0) y**2 + 2*y + 3 >>> R.dmp_diff_in(f, 1, 1) 2*x*y + 2*x + 4*y + 3 """ if j < 0 or j > u: raise IndexError("0 <= j <= %s expected, got %s" % (u, j)) return _rec_diff_in(f, m, u, 0, j, K) def dup_eval(f, a, K): """ Evaluate a polynomial at ``x = a`` in ``K[x]`` using Horner scheme. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_eval(x**2 + 2*x + 3, 2) 11 """ if not a: return K.convert(dup_TC(f, K)) result = K.zero for c in f: result *= a result += c return result def dmp_eval(f, a, u, K): """ Evaluate a polynomial at ``x_0 = a`` in ``K[X]`` using the Horner scheme. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_eval(2*x*y + 3*x + y + 2, 2) 5*y + 8 """ if not u: return dup_eval(f, a, K) if not a: return dmp_TC(f, K) result, v = dmp_LC(f, K), u - 1 for coeff in f[1:]: result = dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff, v, K) return result def _rec_eval_in(g, a, v, i, j, K): """Recursive helper for :func:`dmp_eval_in`.""" if i == j: return dmp_eval(g, a, v, K) v, i = v - 1, i + 1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v) def dmp_eval_in(f, a, j, u, K): """ Evaluate a polynomial at ``x_j = a`` in ``K[X]`` using the Horner scheme. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 2*x*y + 3*x + y + 2 >>> R.dmp_eval_in(f, 2, 0) 5*y + 8 >>> R.dmp_eval_in(f, 2, 1) 7*x + 4 """ if j < 0 or j > u: raise IndexError("0 <= j <= %s expected, got %s" % (u, j)) return _rec_eval_in(f, a, u, 0, j, K) def _rec_eval_tail(g, i, A, u, K): """Recursive helper for :func:`dmp_eval_tail`.""" if i == u: return dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c, i + 1, A, u, K) for c in g ] if i < u - len(A) + 1: return h else: return dup_eval(h, A[-u + i - 1], K) def dmp_eval_tail(f, A, u, K): """ Evaluate a polynomial at ``x_j = a_j, ...`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 2*x*y + 3*x + y + 2 >>> R.dmp_eval_tail(f, [2]) 7*x + 4 >>> R.dmp_eval_tail(f, [2, 2]) 18 """ if not A: return f if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A, u, K) if u == len(A) - 1: return e else: return dmp_strip(e, u - len(A)) def _rec_diff_eval(g, m, a, v, i, j, K): """Recursive helper for :func:`dmp_diff_eval`.""" if i == j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i = v - 1, i + 1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g ], v) def dmp_diff_eval_in(f, m, a, j, u, K): """ Differentiate and evaluate a polynomial in ``x_j`` at ``a`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1 >>> R.dmp_diff_eval_in(f, 1, 2, 0) y**2 + 2*y + 3 >>> R.dmp_diff_eval_in(f, 1, 2, 1) 6*x + 11 """ if j > u: raise IndexError("-%s <= j < %s expected, got %s" % (u, u, j)) if not j: return dmp_eval(dmp_diff(f, m, u, K), a, u, K) return _rec_diff_eval(f, m, a, u, 0, j, K) def dup_trunc(f, p, K): """ Reduce a ``K[x]`` polynomial modulo a constant ``p`` in ``K``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_trunc(2*x**3 + 3*x**2 + 5*x + 7, ZZ(3)) -x**3 - x + 1 """ if K.is_ZZ: g = [] for c in f: c = c % p if c > p // 2: g.append(c - p) else: g.append(c) else: g = [ c % p for c in f ] return dup_strip(g) def dmp_trunc(f, p, u, K): """ Reduce a ``K[X]`` polynomial modulo a polynomial ``p`` in ``K[Y]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3 >>> g = (y - 1).drop(x) >>> R.dmp_trunc(f, g) 11*x**2 + 11*x + 5 """ return dmp_strip([ dmp_rem(c, p, u - 1, K) for c in f ], u) def dmp_ground_trunc(f, p, u, K): """ Reduce a ``K[X]`` polynomial modulo a constant ``p`` in ``K``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3 >>> R.dmp_ground_trunc(f, ZZ(3)) -x**2 - x*y - y """ if not u: return dup_trunc(f, p, K) v = u - 1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ], u) def dup_monic(f, K): """ Divide all coefficients by ``LC(f)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> R.dup_monic(3*x**2 + 6*x + 9) x**2 + 2*x + 3 >>> R, x = ring("x", QQ) >>> R.dup_monic(3*x**2 + 4*x + 2) x**2 + 4/3*x + 2/3 """ if not f: return f lc = dup_LC(f, K) if K.is_one(lc): return f else: return dup_exquo_ground(f, lc, K) def dmp_ground_monic(f, u, K): """ Divide all coefficients by ``LC(f)`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y + 6*x**2 + 3*x*y + 9*y + 3 >>> R.dmp_ground_monic(f) x**2*y + 2*x**2 + x*y + 3*y + 1 >>> R, x,y = ring("x,y", QQ) >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3 >>> R.dmp_ground_monic(f) x**2*y + 8/3*x**2 + 5/3*x*y + 2*x + 2/3*y + 1 """ if not u: return dup_monic(f, K) if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return f else: return dmp_exquo_ground(f, lc, u, K) def dup_content(f, K): """ Compute the GCD of coefficients of ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_content(f) 2 >>> R, x = ring("x", QQ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_content(f) 2 """ from sympy.polys.domains import QQ if not f: return K.zero cont = K.zero if K == QQ: for c in f: cont = K.gcd(cont, c) else: for c in f: cont = K.gcd(cont, c) if K.is_one(cont): break return cont def dmp_ground_content(f, u, K): """ Compute the GCD of coefficients of ``f`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> f = 2*x*y + 6*x + 4*y + 12 >>> R.dmp_ground_content(f) 2 >>> R, x,y = ring("x,y", QQ) >>> f = 2*x*y + 6*x + 4*y + 12 >>> R.dmp_ground_content(f) 2 """ from sympy.polys.domains import QQ if not u: return dup_content(f, K) if dmp_zero_p(f, u): return K.zero cont, v = K.zero, u - 1 if K == QQ: for c in f: cont = K.gcd(cont, dmp_ground_content(c, v, K)) else: for c in f: cont = K.gcd(cont, dmp_ground_content(c, v, K)) if K.is_one(cont): break return cont def dup_primitive(f, K): """ Compute content and the primitive form of ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_primitive(f) (2, 3*x**2 + 4*x + 6) >>> R, x = ring("x", QQ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_primitive(f) (2, 3*x**2 + 4*x + 6) """ if not f: return K.zero, f cont = dup_content(f, K) if K.is_one(cont): return cont, f else: return cont, dup_quo_ground(f, cont, K) def dmp_ground_primitive(f, u, K): """ Compute content and the primitive form of ``f`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> f = 2*x*y + 6*x + 4*y + 12 >>> R.dmp_ground_primitive(f) (2, x*y + 3*x + 2*y + 6) >>> R, x,y = ring("x,y", QQ) >>> f = 2*x*y + 6*x + 4*y + 12 >>> R.dmp_ground_primitive(f) (2, x*y + 3*x + 2*y + 6) """ if not u: return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f cont = dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f else: return cont, dmp_quo_ground(f, cont, u, K) def dup_extract(f, g, K): """ Extract common content from a pair of polynomials in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_extract(6*x**2 + 12*x + 18, 4*x**2 + 8*x + 12) (2, 3*x**2 + 6*x + 9, 2*x**2 + 4*x + 6) """ fc = dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dup_quo_ground(f, gcd, K) g = dup_quo_ground(g, gcd, K) return gcd, f, g def dmp_ground_extract(f, g, u, K): """ Extract common content from a pair of polynomials in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_ground_extract(6*x*y + 12*x + 18, 4*x*y + 8*x + 12) (2, 3*x*y + 6*x + 9, 2*x*y + 4*x + 6) """ fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_quo_ground(f, gcd, u, K) g = dmp_quo_ground(g, gcd, u, K) return gcd, f, g def dup_real_imag(f, K): """ Return bivariate polynomials ``f1`` and ``f2``, such that ``f = f1 + f2*I``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dup_real_imag(x**3 + x**2 + x + 1) (x**3 + x**2 - 3*x*y**2 + x - y**2 + 1, 3*x**2*y + 2*x*y - y**3 + y) """ if not K.is_ZZ and not K.is_QQ: raise DomainError("computing real and imaginary parts is not supported over %s" % K) f1 = dmp_zero(1) f2 = dmp_zero(1) if not f: return f1, f2 g = [[[K.one, K.zero]], [[K.one], []]] h = dmp_ground(f[0], 2) for c in f[1:]: h = dmp_mul(h, g, 2, K) h = dmp_add_term(h, dmp_ground(c, 1), 0, 2, K) H = dup_to_raw_dict(h) for k, h in H.items(): m = k % 4 if not m: f1 = dmp_add(f1, h, 1, K) elif m == 1: f2 = dmp_add(f2, h, 1, K) elif m == 2: f1 = dmp_sub(f1, h, 1, K) else: f2 = dmp_sub(f2, h, 1, K) return f1, f2 def dup_mirror(f, K): """ Evaluate efficiently the composition ``f(-x)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_mirror(x**3 + 2*x**2 - 4*x + 2) -x**3 + 2*x**2 + 4*x + 2 """ f = list(f) for i in range(len(f) - 2, -1, -2): f[i] = -f[i] return f def dup_scale(f, a, K): """ Evaluate efficiently composition ``f(a*x)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_scale(x**2 - 2*x + 1, ZZ(2)) 4*x**2 - 4*x + 1 """ f, n, b = list(f), len(f) - 1, a for i in range(n - 1, -1, -1): f[i], b = b*f[i], b*a return f def dup_shift(f, a, K): """ Evaluate efficiently Taylor shift ``f(x + a)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_shift(x**2 - 2*x + 1, ZZ(2)) x**2 + 2*x + 1 """ f, n = list(f), len(f) - 1 for i in range(n, 0, -1): for j in range(0, i): f[j + 1] += a*f[j] return f def dup_transform(f, p, q, K): """ Evaluate functional transformation ``q**n * f(p/q)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_transform(x**2 - 2*x + 1, x**2 + 1, x - 1) x**4 - 2*x**3 + 5*x**2 - 4*x + 4 """ if not f: return [] n = len(f) - 1 h, Q = [f[0]], [[K.one]] for i in range(0, n): Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q = dup_mul_ground(q, c, K) h = dup_add(h, q, K) return h def dup_compose(f, g, K): """ Evaluate functional composition ``f(g)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_compose(x**2 + x, x - 1) x**2 - x """ if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return [] h = [f[0]] for c in f[1:]: h = dup_mul(h, g, K) h = dup_add_term(h, c, 0, K) return h def dmp_compose(f, g, u, K): """ Evaluate functional composition ``f(g)`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_compose(x*y + 2*x + y, y) y**2 + 3*y """ if not u: return dup_compose(f, g, K) if dmp_zero_p(f, u): return f h = [f[0]] for c in f[1:]: h = dmp_mul(h, g, u, K) h = dmp_add_term(h, c, 0, u, K) return h def _dup_right_decompose(f, s, K): """Helper function for :func:`_dup_decompose`.""" n = len(f) - 1 lc = dup_LC(f, K) f = dup_to_raw_dict(f) g = { s: K.one } r = n // s for i in range(1, s): coeff = K.zero for j in range(0, i): if not n + j - i in f: continue if not s - j in g: continue fc, gc = f[n + j - i], g[s - j] coeff += (i - r*j)*fc*gc g[s - i] = K.quo(coeff, i*r*lc) return dup_from_raw_dict(g, K) def _dup_left_decompose(f, h, K): """Helper function for :func:`_dup_decompose`.""" g, i = {}, 0 while f: q, r = dup_div(f, h, K) if dup_degree(r) > 0: return None else: g[i] = dup_LC(r, K) f, i = q, i + 1 return dup_from_raw_dict(g, K) def _dup_decompose(f, K): """Helper function for :func:`dup_decompose`.""" df = len(f) - 1 for s in range(2, df): if df % s != 0: continue h = _dup_right_decompose(f, s, K) if h is not None: g = _dup_left_decompose(f, h, K) if g is not None: return g, h return None def dup_decompose(f, K): """ Computes functional decomposition of ``f`` in ``K[x]``. Given a univariate polynomial ``f`` with coefficients in a field of characteristic zero, returns list ``[f_1, f_2, ..., f_n]``, where:: f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) and ``f_2, ..., f_n`` are monic and homogeneous polynomials of at least second degree. Unlike factorization, complete functional decompositions of polynomials are not unique, consider examples: 1. ``f o g = f(x + b) o (g - b)`` 2. ``x**n o x**m = x**m o x**n`` 3. ``T_n o T_m = T_m o T_n`` where ``T_n`` and ``T_m`` are Chebyshev polynomials. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_decompose(x**4 - 2*x**3 + x**2) [x**2, x**2 - x] References ========== .. [1] [Kozen89]_ """ F = [] while True: result = _dup_decompose(f, K) if result is not None: f, h = result F = [h] + F else: break return [f] + F def dmp_lift(f, u, K): """ Convert algebraic coefficients to integers in ``K[X]``. Examples ======== >>> from sympy.polys import ring, QQ >>> from sympy import I >>> K = QQ.algebraic_field(I) >>> R, x = ring("x", K) >>> f = x**2 + K([QQ(1), QQ(0)])*x + K([QQ(2), QQ(0)]) >>> R.dmp_lift(f) x**8 + 2*x**6 + 9*x**4 - 8*x**2 + 16 """ if K.is_GaussianField: K1 = K.as_AlgebraicField() f = dmp_convert(f, u, K, K1) K = K1 if not K.is_Algebraic: raise DomainError( 'computation can be done only in an algebraic domain') F, monoms, polys = dmp_to_dict(f, u), [], [] for monom, coeff in F.items(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for perm in perms: G = dict(F) for sign, monom in zip(perm, monoms): if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f, K): """ Compute the number of sign variations of ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_sign_variations(x**4 - x**2 - x + 1) 2 """ prev, k = K.zero, 0 for coeff in f: if K.is_negative(coeff*prev): k += 1 if coeff: prev = coeff return k def dup_clear_denoms(f, K0, K1=None, convert=False): """ Clear denominators, i.e. transform ``K_0`` to ``K_1``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = QQ(1,2)*x + QQ(1,3) >>> R.dup_clear_denoms(f, convert=False) (6, 3*x + 2) >>> R.dup_clear_denoms(f, convert=True) (6, 3*x + 2) """ if K1 is None: if K0.has_assoc_Ring: K1 = K0.get_ring() else: K1 = K0 common = K1.one for c in f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common, K0) if not convert: return common, f else: return common, dup_convert(f, K0, K1) def _rec_clear_denoms(g, v, K0, K1): """Recursive helper for :func:`dmp_clear_denoms`.""" common = K1.one if not v: for c in g: common = K1.lcm(common, K0.denom(c)) else: w = v - 1 for c in g: common = K1.lcm(common, _rec_clear_denoms(c, w, K0, K1)) return common def dmp_clear_denoms(f, u, K0, K1=None, convert=False): """ Clear denominators, i.e. transform ``K_0`` to ``K_1``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) >>> f = QQ(1,2)*x + QQ(1,3)*y + 1 >>> R.dmp_clear_denoms(f, convert=False) (6, 3*x + 2*y + 6) >>> R.dmp_clear_denoms(f, convert=True) (6, 3*x + 2*y + 6) """ if not u: return dup_clear_denoms(f, K0, K1, convert=convert) if K1 is None: if K0.has_assoc_Ring: K1 = K0.get_ring() else: K1 = K0 common = _rec_clear_denoms(f, u, K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if not convert: return common, f else: return common, dmp_convert(f, u, K0, K1) def dup_revert(f, n, K): """ Compute ``f**(-1)`` mod ``x**n`` using Newton iteration. This function computes first ``2**n`` terms of a polynomial that is a result of inversion of a polynomial modulo ``x**n``. This is useful to efficiently compute series expansion of ``1/f``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = -QQ(1,720)*x**6 + QQ(1,24)*x**4 - QQ(1,2)*x**2 + 1 >>> R.dup_revert(f, 8) 61/720*x**6 + 5/24*x**4 + 1/2*x**2 + 1 """ g = [K.revert(dup_TC(f, K))] h = [K.one, K.zero, K.zero] N = int(_ceil(_log(n, 2))) for i in range(1, N + 1): a = dup_mul_ground(g, K(2), K) b = dup_mul(f, dup_sqr(g, K), K) g = dup_rem(dup_sub(a, b, K), h, K) h = dup_lshift(h, dup_degree(h), K) return g def dmp_revert(f, g, u, K): """ Compute ``f**(-1)`` mod ``x**n`` using Newton iteration. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) """ if not u: return dup_revert(f, g, K) else: raise MultivariatePolynomialError(f, g)
b1481f00f10762aad40e9fa28d4d778571bcd6f8348bf4e6966d1c97da0e166c
"""User-friendly public interface to polynomial functions. """ from functools import wraps, reduce from operator import mul from typing import Optional from sympy.core import ( S, Expr, Add, Tuple ) from sympy.core.basic import Basic from sympy.core.decorators import _sympifyit from sympy.core.exprtools import Factors, factor_nc, factor_terms from sympy.core.evalf import ( pure_complex, evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath) from sympy.core.function import Derivative from sympy.core.mul import Mul, _keep_coeff from sympy.core.numbers import ilcm, I, Integer from sympy.core.relational import Relational, Equality from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol from sympy.core.sympify import sympify, _sympify from sympy.core.traversal import preorder_traversal, bottom_up from sympy.logic.boolalg import BooleanAtom from sympy.polys import polyoptions as options from sympy.polys.constructor import construct_domain from sympy.polys.domains import FF, QQ, ZZ from sympy.polys.domains.domainelement import DomainElement from sympy.polys.fglmtools import matrix_fglm from sympy.polys.groebnertools import groebner as _groebner from sympy.polys.monomials import Monomial from sympy.polys.orderings import monomial_key from sympy.polys.polyclasses import DMP, DMF, ANP from sympy.polys.polyerrors import ( OperationNotSupported, DomainError, CoercionFailed, UnificationFailed, GeneratorsNeeded, PolynomialError, MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, GeneratorsError, ) from sympy.polys.polyutils import ( basic_from_dict, _sort_gens, _unify_gens, _dict_reorder, _dict_from_expr, _parallel_dict_from_expr, ) from sympy.polys.rationaltools import together from sympy.polys.rootisolation import dup_isolate_real_roots_list from sympy.utilities import group, public, filldedent from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import iterable, sift # Required to avoid errors import sympy.polys import mpmath from mpmath.libmp.libhyper import NoConvergence def _polifyit(func): @wraps(func) def wrapper(f, g): g = _sympify(g) if isinstance(g, Poly): return func(f, g) elif isinstance(g, Expr): try: g = f.from_expr(g, *f.gens) except PolynomialError: if g.is_Matrix: return NotImplemented expr_method = getattr(f.as_expr(), func.__name__) result = expr_method(g) if result is not NotImplemented: sympy_deprecation_warning( """ Mixing Poly with non-polynomial expressions in binary operations is deprecated. Either explicitly convert the non-Poly operand to a Poly with as_poly() or convert the Poly to an Expr with as_expr(). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-poly-nonpoly-binary-operations", ) return result else: return func(f, g) else: return NotImplemented return wrapper @public class Poly(Basic): """ Generic class for representing and operating on polynomial expressions. See :ref:`polys-docs` for general documentation. Poly is a subclass of Basic rather than Expr but instances can be converted to Expr with the :py:meth:`~.Poly.as_expr` method. .. deprecated:: 1.6 Combining Poly with non-Poly objects in binary operations is deprecated. Explicitly convert both objects to either Poly or Expr first. See :ref:`deprecated-poly-nonpoly-binary-operations`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y Create a univariate polynomial: >>> Poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') Create a univariate polynomial with specific domain: >>> from sympy import sqrt >>> Poly(x**2 + 2*x + sqrt(3), domain='R') Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR') Create a multivariate polynomial: >>> Poly(y*x**2 + x*y + 1) Poly(x**2*y + x*y + 1, x, y, domain='ZZ') Create a univariate polynomial, where y is a constant: >>> Poly(y*x**2 + x*y + 1,x) Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]') You can evaluate the above polynomial as a function of y: >>> Poly(y*x**2 + x*y + 1,x).eval(2) 6*y + 1 See Also ======== sympy.core.expr.Expr """ __slots__ = ('rep', 'gens') is_commutative = True is_Poly = True _op_priority = 10.001 def __new__(cls, rep, *gens, **args): """Create a new polynomial instance out of something useful. """ opt = options.build_options(gens, args) if 'order' in opt: raise NotImplementedError("'order' keyword is not implemented yet") if isinstance(rep, (DMP, DMF, ANP, DomainElement)): return cls._from_domain_element(rep, opt) elif iterable(rep, exclude=str): if isinstance(rep, dict): return cls._from_dict(rep, opt) else: return cls._from_list(list(rep), opt) else: rep = sympify(rep) if rep.is_Poly: return cls._from_poly(rep, opt) else: return cls._from_expr(rep, opt) # Poly does not pass its args to Basic.__new__ to be stored in _args so we # have to emulate them here with an args property that derives from rep # and gens which are instance attributes. This also means we need to # define _hashable_content. The _hashable_content is rep and gens but args # uses expr instead of rep (expr is the Basic version of rep). Passing # expr in args means that Basic methods like subs should work. Using rep # otherwise means that Poly can remain more efficient than Basic by # avoiding creating a Basic instance just to be hashable. @classmethod def new(cls, rep, *gens): """Construct :class:`Poly` instance from raw representation. """ if not isinstance(rep, DMP): raise PolynomialError( "invalid polynomial representation: %s" % rep) elif rep.lev != len(gens) - 1: raise PolynomialError("invalid arguments: %s, %s" % (rep, gens)) obj = Basic.__new__(cls) obj.rep = rep obj.gens = gens return obj @property def expr(self): return basic_from_dict(self.rep.to_sympy_dict(), *self.gens) @property def args(self): return (self.expr,) + self.gens def _hashable_content(self): return (self.rep,) + self.gens @classmethod def from_dict(cls, rep, *gens, **args): """Construct a polynomial from a ``dict``. """ opt = options.build_options(gens, args) return cls._from_dict(rep, opt) @classmethod def from_list(cls, rep, *gens, **args): """Construct a polynomial from a ``list``. """ opt = options.build_options(gens, args) return cls._from_list(rep, opt) @classmethod def from_poly(cls, rep, *gens, **args): """Construct a polynomial from a polynomial. """ opt = options.build_options(gens, args) return cls._from_poly(rep, opt) @classmethod def from_expr(cls, rep, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return cls._from_expr(rep, opt) @classmethod def _from_dict(cls, rep, opt): """Construct a polynomial from a ``dict``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "Cannot initialize from 'dict' without generators") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: for monom, coeff in rep.items(): rep[monom] = domain.convert(coeff) return cls.new(DMP.from_dict(rep, level, domain), *gens) @classmethod def _from_list(cls, rep, opt): """Construct a polynomial from a ``list``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "Cannot initialize from 'list' without generators") elif len(gens) != 1: raise MultivariatePolynomialError( "'list' representation not supported") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: rep = list(map(domain.convert, rep)) return cls.new(DMP.from_list(rep, level, domain), *gens) @classmethod def _from_poly(cls, rep, opt): """Construct a polynomial from a polynomial. """ if cls != rep.__class__: rep = cls.new(rep.rep, *rep.gens) gens = opt.gens field = opt.field domain = opt.domain if gens and rep.gens != gens: if set(rep.gens) != set(gens): return cls._from_expr(rep.as_expr(), opt) else: rep = rep.reorder(*gens) if 'domain' in opt and domain: rep = rep.set_domain(domain) elif field is True: rep = rep.to_field() return rep @classmethod def _from_expr(cls, rep, opt): """Construct a polynomial from an expression. """ rep, opt = _dict_from_expr(rep, opt) return cls._from_dict(rep, opt) @classmethod def _from_domain_element(cls, rep, opt): gens = opt.gens domain = opt.domain level = len(gens) - 1 rep = [domain.convert(rep)] return cls.new(DMP.from_list(rep, level, domain), *gens) def __hash__(self): return super().__hash__() @property def free_symbols(self): """ Free symbols of a polynomial expression. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 1).free_symbols {x} >>> Poly(x**2 + y).free_symbols {x, y} >>> Poly(x**2 + y, x).free_symbols {x, y} >>> Poly(x**2 + y, x, z).free_symbols {x, y} """ symbols = set() gens = self.gens for i in range(len(gens)): for monom in self.monoms(): if monom[i]: symbols |= gens[i].free_symbols break return symbols | self.free_symbols_in_domain @property def free_symbols_in_domain(self): """ Free symbols of the domain of ``self``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols_in_domain set() >>> Poly(x**2 + y).free_symbols_in_domain set() >>> Poly(x**2 + y, x).free_symbols_in_domain {y} """ domain, symbols = self.rep.dom, set() if domain.is_Composite: for gen in domain.symbols: symbols |= gen.free_symbols elif domain.is_EX: for coeff in self.coeffs(): symbols |= coeff.free_symbols return symbols @property def gen(self): """ Return the principal generator. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).gen x """ return self.gens[0] @property def domain(self): """Get the ground domain of a :py:class:`~.Poly` Returns ======= :py:class:`~.Domain`: Ground domain of the :py:class:`~.Poly`. Examples ======== >>> from sympy import Poly, Symbol >>> x = Symbol('x') >>> p = Poly(x**2 + x) >>> p Poly(x**2 + x, x, domain='ZZ') >>> p.domain ZZ """ return self.get_domain() @property def zero(self): """Return zero polynomial with ``self``'s properties. """ return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens) @property def one(self): """Return one polynomial with ``self``'s properties. """ return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens) @property def unit(self): """Return unit polynomial with ``self``'s properties. """ return self.new(self.rep.unit(self.rep.lev, self.rep.dom), *self.gens) def unify(f, g): """ Make ``f`` and ``g`` belong to the same domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f, g = Poly(x/2 + 1), Poly(2*x + 1) >>> f Poly(1/2*x + 1, x, domain='QQ') >>> g Poly(2*x + 1, x, domain='ZZ') >>> F, G = f.unify(g) >>> F Poly(1/2*x + 1, x, domain='QQ') >>> G Poly(2*x + 1, x, domain='QQ') """ _, per, F, G = f._unify(g) return per(F), per(G) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if isinstance(f.rep, DMP) and isinstance(g.rep, DMP): gens = _unify_gens(f.gens, g.gens) dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1 if f.gens != gens: f_monoms, f_coeffs = _dict_reorder( f.rep.to_dict(), f.gens, gens) if f.rep.dom != dom: f_coeffs = [dom.convert(c, f.rep.dom) for c in f_coeffs] F = DMP(dict(list(zip(f_monoms, f_coeffs))), dom, lev) else: F = f.rep.convert(dom) if g.gens != gens: g_monoms, g_coeffs = _dict_reorder( g.rep.to_dict(), g.gens, gens) if g.rep.dom != dom: g_coeffs = [dom.convert(c, g.rep.dom) for c in g_coeffs] G = DMP(dict(list(zip(g_monoms, g_coeffs))), dom, lev) else: G = g.rep.convert(dom) else: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) cls = f.__class__ def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G def per(f, rep, gens=None, remove=None): """ Create a Poly out of the given representation. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x, y >>> from sympy.polys.polyclasses import DMP >>> a = Poly(x**2 + 1) >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y]) Poly(y + 1, y, domain='ZZ') """ if gens is None: gens = f.gens if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return f.rep.dom.to_sympy(rep) return f.__class__.new(rep, *gens) def set_domain(f, domain): """Set the ground domain of ``f``. """ opt = options.build_options(f.gens, {'domain': domain}) return f.per(f.rep.convert(opt.domain)) def get_domain(f): """Get the ground domain of ``f``. """ return f.rep.dom def set_modulus(f, modulus): """ Set the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2) Poly(x**2 + 1, x, modulus=2) """ modulus = options.Modulus.preprocess(modulus) return f.set_domain(FF(modulus)) def get_modulus(f): """ Get the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, modulus=2).get_modulus() 2 """ domain = f.get_domain() if domain.is_FiniteField: return Integer(domain.characteristic()) else: raise PolynomialError("not a polynomial over a Galois field") def _eval_subs(f, old, new): """Internal implementation of :func:`subs`. """ if old in f.gens: if new.is_number: return f.eval(old, new) else: try: return f.replace(old, new) except PolynomialError: pass return f.as_expr().subs(old, new) def exclude(f): """ Remove unnecessary generators from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import a, b, c, d, x >>> Poly(a + x, a, b, c, d, x).exclude() Poly(a + x, a, x, domain='ZZ') """ J, new = f.rep.exclude() gens = [] for j in range(len(f.gens)): if j not in J: gens.append(f.gens[j]) return f.per(new, gens=gens) def replace(f, x, y=None, **_ignore): # XXX this does not match Basic's signature """ Replace ``x`` with ``y`` in generators list. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1, x).replace(x, y) Poly(y**2 + 1, y, domain='ZZ') """ if y is None: if f.is_univariate: x, y = f.gen, x else: raise PolynomialError( "syntax supported only in univariate case") if x == y or x not in f.gens: return f if x in f.gens and y not in f.gens: dom = f.get_domain() if not dom.is_Composite or y not in dom.symbols: gens = list(f.gens) gens[gens.index(x)] = y return f.per(f.rep, gens=gens) raise PolynomialError("Cannot replace %s with %s in %s" % (x, y, f)) def match(f, *args, **kwargs): """Match expression from Poly. See Basic.match()""" return f.as_expr().match(*args, **kwargs) def reorder(f, *gens, **args): """ Efficiently apply new order of generators. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y**2, x, y).reorder(y, x) Poly(y**2*x + x**2, y, x, domain='ZZ') """ opt = options.Options((), args) if not gens: gens = _sort_gens(f.gens, opt=opt) elif set(f.gens) != set(gens): raise PolynomialError( "generators list can differ only up to order of elements") rep = dict(list(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens)))) return f.per(DMP(rep, f.rep.dom, len(gens) - 1), gens=gens) def ltrim(f, gen): """ Remove dummy generators from ``f`` that are to the left of specified ``gen`` in the generators as ordered. When ``gen`` is an integer, it refers to the generator located at that position within the tuple of generators of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y) Poly(y**2 + y*z**2, y, z, domain='ZZ') >>> Poly(z, x, y, z).ltrim(-1) Poly(z, z, domain='ZZ') """ rep = f.as_dict(native=True) j = f._gen_to_level(gen) terms = {} for monom, coeff in rep.items(): if any(monom[:j]): # some generator is used in the portion to be trimmed raise PolynomialError("Cannot left trim %s" % f) terms[monom[j:]] = coeff gens = f.gens[j:] return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens) def has_only_gens(f, *gens): """ Return ``True`` if ``Poly(f, *gens)`` retains ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y) True >>> Poly(x*y + z, x, y, z).has_only_gens(x, y) False """ indices = set() for gen in gens: try: index = f.gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: indices.add(index) for monom in f.monoms(): for i, elt in enumerate(monom): if i not in indices and elt: return False return True def to_ring(f): """ Make the ground domain a ring. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, domain=QQ).to_ring() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'to_ring'): result = f.rep.to_ring() else: # pragma: no cover raise OperationNotSupported(f, 'to_ring') return f.per(result) def to_field(f): """ Make the ground domain a field. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(x**2 + 1, x, domain=ZZ).to_field() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_field'): result = f.rep.to_field() else: # pragma: no cover raise OperationNotSupported(f, 'to_field') return f.per(result) def to_exact(f): """ Make the ground domain exact. Examples ======== >>> from sympy import Poly, RR >>> from sympy.abc import x >>> Poly(x**2 + 1.0, x, domain=RR).to_exact() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_exact'): result = f.rep.to_exact() else: # pragma: no cover raise OperationNotSupported(f, 'to_exact') return f.per(result) def retract(f, field=None): """ Recalculate the ground domain of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x, domain='QQ[y]') >>> f Poly(x**2 + 1, x, domain='QQ[y]') >>> f.retract() Poly(x**2 + 1, x, domain='ZZ') >>> f.retract(field=True) Poly(x**2 + 1, x, domain='QQ') """ dom, rep = construct_domain(f.as_dict(zero=True), field=field, composite=f.domain.is_Composite or None) return f.from_dict(rep, f.gens, domain=dom) def slice(f, x, m, n=None): """Take a continuous subsequence of terms of ``f``. """ if n is None: j, m, n = 0, x, m else: j = f._gen_to_level(x) m, n = int(m), int(n) if hasattr(f.rep, 'slice'): result = f.rep.slice(m, n, j) else: # pragma: no cover raise OperationNotSupported(f, 'slice') return f.per(result) def coeffs(f, order=None): """ Returns all non-zero coefficients from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x + 3, x).coeffs() [1, 2, 3] See Also ======== all_coeffs coeff_monomial nth """ return [f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order)] def monoms(f, order=None): """ Returns all non-zero monomials from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms() [(2, 0), (1, 2), (1, 1), (0, 1)] See Also ======== all_monoms """ return f.rep.monoms(order=order) def terms(f, order=None): """ Returns all non-zero terms from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms() [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)] See Also ======== all_terms """ return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order)] def all_coeffs(f): """ Returns all coefficients from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_coeffs() [1, 0, 2, -1] """ return [f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs()] def all_monoms(f): """ Returns all monomials from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_monoms() [(3,), (2,), (1,), (0,)] See Also ======== all_terms """ return f.rep.all_monoms() def all_terms(f): """ Returns all terms from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_terms() [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)] """ return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms()] def termwise(f, func, *gens, **args): """ Apply a function to all terms of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> def func(k, coeff): ... k = k[0] ... return coeff//10**(2-k) >>> Poly(x**2 + 20*x + 400).termwise(func) Poly(x**2 + 2*x + 4, x, domain='ZZ') """ terms = {} for monom, coeff in f.terms(): result = func(monom, coeff) if isinstance(result, tuple): monom, coeff = result else: coeff = result if coeff: if monom not in terms: terms[monom] = coeff else: raise PolynomialError( "%s monomial was generated twice" % monom) return f.from_dict(terms, *(gens or f.gens), **args) def length(f): """ Returns the number of non-zero terms in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x - 1).length() 3 """ return len(f.as_dict()) def as_dict(f, native=False, zero=False): """ Switch to a ``dict`` representation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict() {(0, 1): -1, (1, 2): 2, (2, 0): 1} """ if native: return f.rep.to_dict(zero=zero) else: return f.rep.to_sympy_dict(zero=zero) def as_list(f, native=False): """Switch to a ``list`` representation. """ if native: return f.rep.to_list() else: return f.rep.to_sympy_list() def as_expr(f, *gens): """ Convert a Poly instance to an Expr instance. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 2*x*y**2 - y, x, y) >>> f.as_expr() x**2 + 2*x*y**2 - y >>> f.as_expr({x: 5}) 10*y**2 - y + 25 >>> f.as_expr(5, 6) 379 """ if not gens: return f.expr if len(gens) == 1 and isinstance(gens[0], dict): mapping = gens[0] gens = list(f.gens) for gen, value in mapping.items(): try: index = gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: gens[index] = value return basic_from_dict(f.rep.to_sympy_dict(), *gens) def as_poly(self, *gens, **args): """Converts ``self`` to a polynomial or returns ``None``. >>> from sympy import sin >>> from sympy.abc import x, y >>> print((x**2 + x*y).as_poly()) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + x*y).as_poly(x, y)) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + sin(y)).as_poly(x, y)) None """ try: poly = Poly(self, *gens, **args) if not poly.is_Poly: return None else: return poly except PolynomialError: return None def lift(f): """ Convert algebraic coefficients to rationals. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**2 + I*x + 1, x, extension=I).lift() Poly(x**4 + 3*x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'lift'): result = f.rep.lift() else: # pragma: no cover raise OperationNotSupported(f, 'lift') return f.per(result) def deflate(f): """ Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate() ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'deflate'): J, result = f.rep.deflate() else: # pragma: no cover raise OperationNotSupported(f, 'deflate') return J, f.per(result) def inject(f, front=False): """ Inject ground domain generators into ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x) >>> f.inject() Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ') >>> f.inject(front=True) Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ') """ dom = f.rep.dom if dom.is_Numerical: return f elif not dom.is_Poly: raise DomainError("Cannot inject generators over %s" % dom) if hasattr(f.rep, 'inject'): result = f.rep.inject(front=front) else: # pragma: no cover raise OperationNotSupported(f, 'inject') if front: gens = dom.symbols + f.gens else: gens = f.gens + dom.symbols return f.new(result, *gens) def eject(f, *gens): """ Eject selected generators into the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) >>> f.eject(x) Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') >>> f.eject(y) Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') """ dom = f.rep.dom if not dom.is_Numerical: raise DomainError("Cannot eject generators over %s" % dom) k = len(gens) if f.gens[:k] == gens: _gens, front = f.gens[k:], True elif f.gens[-k:] == gens: _gens, front = f.gens[:-k], False else: raise NotImplementedError( "can only eject front or back generators") dom = dom.inject(*gens) if hasattr(f.rep, 'eject'): result = f.rep.eject(dom, front=front) else: # pragma: no cover raise OperationNotSupported(f, 'eject') return f.new(result, *_gens) def terms_gcd(f): """ Remove GCD of terms from the polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd() ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'terms_gcd'): J, result = f.rep.terms_gcd() else: # pragma: no cover raise OperationNotSupported(f, 'terms_gcd') return J, f.per(result) def add_ground(f, coeff): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).add_ground(2) Poly(x + 3, x, domain='ZZ') """ if hasattr(f.rep, 'add_ground'): result = f.rep.add_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'add_ground') return f.per(result) def sub_ground(f, coeff): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).sub_ground(2) Poly(x - 1, x, domain='ZZ') """ if hasattr(f.rep, 'sub_ground'): result = f.rep.sub_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'sub_ground') return f.per(result) def mul_ground(f, coeff): """ Multiply ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).mul_ground(2) Poly(2*x + 2, x, domain='ZZ') """ if hasattr(f.rep, 'mul_ground'): result = f.rep.mul_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'mul_ground') return f.per(result) def quo_ground(f, coeff): """ Quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).quo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).quo_ground(2) Poly(x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'quo_ground'): result = f.rep.quo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'quo_ground') return f.per(result) def exquo_ground(f, coeff): """ Exact quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).exquo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).exquo_ground(2) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 3 in ZZ """ if hasattr(f.rep, 'exquo_ground'): result = f.rep.exquo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'exquo_ground') return f.per(result) def abs(f): """ Make all coefficients in ``f`` positive. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).abs() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'abs'): result = f.rep.abs() else: # pragma: no cover raise OperationNotSupported(f, 'abs') return f.per(result) def neg(f): """ Negate all coefficients in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).neg() Poly(-x**2 + 1, x, domain='ZZ') >>> -Poly(x**2 - 1, x) Poly(-x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'neg'): result = f.rep.neg() else: # pragma: no cover raise OperationNotSupported(f, 'neg') return f.per(result) def add(f, g): """ Add two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).add(Poly(x - 2, x)) Poly(x**2 + x - 1, x, domain='ZZ') >>> Poly(x**2 + 1, x) + Poly(x - 2, x) Poly(x**2 + x - 1, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.add_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'add'): result = F.add(G) else: # pragma: no cover raise OperationNotSupported(f, 'add') return per(result) def sub(f, g): """ Subtract two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x)) Poly(x**2 - x + 3, x, domain='ZZ') >>> Poly(x**2 + 1, x) - Poly(x - 2, x) Poly(x**2 - x + 3, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.sub_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'sub'): result = F.sub(G) else: # pragma: no cover raise OperationNotSupported(f, 'sub') return per(result) def mul(f, g): """ Multiply two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x)) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') >>> Poly(x**2 + 1, x)*Poly(x - 2, x) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.mul_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'mul'): result = F.mul(G) else: # pragma: no cover raise OperationNotSupported(f, 'mul') return per(result) def sqr(f): """ Square a polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).sqr() Poly(x**2 - 4*x + 4, x, domain='ZZ') >>> Poly(x - 2, x)**2 Poly(x**2 - 4*x + 4, x, domain='ZZ') """ if hasattr(f.rep, 'sqr'): result = f.rep.sqr() else: # pragma: no cover raise OperationNotSupported(f, 'sqr') return f.per(result) def pow(f, n): """ Raise ``f`` to a non-negative power ``n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).pow(3) Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') >>> Poly(x - 2, x)**3 Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') """ n = int(n) if hasattr(f.rep, 'pow'): result = f.rep.pow(n) else: # pragma: no cover raise OperationNotSupported(f, 'pow') return f.per(result) def pdiv(f, g): """ Polynomial pseudo-division of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x)) (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pdiv'): q, r = F.pdiv(G) else: # pragma: no cover raise OperationNotSupported(f, 'pdiv') return per(q), per(r) def prem(f, g): """ Polynomial pseudo-remainder of ``f`` by ``g``. Caveat: The function prem(f, g, x) can be safely used to compute in Z[x] _only_ subresultant polynomial remainder sequences (prs's). To safely compute Euclidean and Sturmian prs's in Z[x] employ anyone of the corresponding functions found in the module sympy.polys.subresultants_qq_zz. The functions in the module with suffix _pg compute prs's in Z[x] employing rem(f, g, x), whereas the functions with suffix _amv compute prs's in Z[x] employing rem_z(f, g, x). The function rem_z(f, g, x) differs from prem(f, g, x) in that to compute the remainder polynomials in Z[x] it premultiplies the divident times the absolute value of the leading coefficient of the divisor raised to the power degree(f, x) - degree(g, x) + 1. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x)) Poly(20, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'prem'): result = F.prem(G) else: # pragma: no cover raise OperationNotSupported(f, 'prem') return per(result) def pquo(f, g): """ Polynomial pseudo-quotient of ``f`` by ``g``. See the Caveat note in the function prem(f, g). Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x)) Poly(2*x + 4, x, domain='ZZ') >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pquo'): result = F.pquo(G) else: # pragma: no cover raise OperationNotSupported(f, 'pquo') return per(result) def pexquo(f, g): """ Polynomial exact pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pexquo'): try: result = F.pexquo(G) except ExactQuotientFailed as exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'pexquo') return per(result) def div(f, g, auto=True): """ Polynomial division with remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x)) (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ')) >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False) (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'div'): q, r = F.div(G) else: # pragma: no cover raise OperationNotSupported(f, 'div') if retract: try: Q, R = q.to_ring(), r.to_ring() except CoercionFailed: pass else: q, r = Q, R return per(q), per(r) def rem(f, g, auto=True): """ Computes the polynomial remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x)) Poly(5, x, domain='ZZ') >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False) Poly(x**2 + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'rem'): r = F.rem(G) else: # pragma: no cover raise OperationNotSupported(f, 'rem') if retract: try: r = r.to_ring() except CoercionFailed: pass return per(r) def quo(f, g, auto=True): """ Computes polynomial quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x)) Poly(1/2*x + 1, x, domain='QQ') >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'quo'): q = F.quo(G) else: # pragma: no cover raise OperationNotSupported(f, 'quo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def exquo(f, g, auto=True): """ Computes polynomial exact quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'exquo'): try: q = F.exquo(G) except ExactQuotientFailed as exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'exquo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def _gen_to_level(f, gen): """Returns level associated with the given generator. """ if isinstance(gen, int): length = len(f.gens) if -length <= gen < length: if gen < 0: return length + gen else: return gen else: raise PolynomialError("-%s <= gen < %s expected, got %s" % (length, length, gen)) else: try: return f.gens.index(sympify(gen)) except ValueError: raise PolynomialError( "a valid generator expected, got %s" % gen) def degree(f, gen=0): """ Returns degree of ``f`` in ``x_j``. The degree of 0 is negative infinity. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree() 2 >>> Poly(x**2 + y*x + y, x, y).degree(y) 1 >>> Poly(0, x).degree() -oo """ j = f._gen_to_level(gen) if hasattr(f.rep, 'degree'): return f.rep.degree(j) else: # pragma: no cover raise OperationNotSupported(f, 'degree') def degree_list(f): """ Returns a list of degrees of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree_list() (2, 1) """ if hasattr(f.rep, 'degree_list'): return f.rep.degree_list() else: # pragma: no cover raise OperationNotSupported(f, 'degree_list') def total_degree(f): """ Returns the total degree of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).total_degree() 2 >>> Poly(x + y**5, x, y).total_degree() 5 """ if hasattr(f.rep, 'total_degree'): return f.rep.total_degree() else: # pragma: no cover raise OperationNotSupported(f, 'total_degree') def homogenize(f, s): """ Returns the homogeneous polynomial of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3) >>> f.homogenize(z) Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ') """ if not isinstance(s, Symbol): raise TypeError("``Symbol`` expected, got %s" % type(s)) if s in f.gens: i = f.gens.index(s) gens = f.gens else: i = len(f.gens) gens = f.gens + (s,) if hasattr(f.rep, 'homogenize'): return f.per(f.rep.homogenize(i), gens=gens) raise OperationNotSupported(f, 'homogeneous_order') def homogeneous_order(f): """ Returns the homogeneous order of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. This degree is the homogeneous order of ``f``. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4) >>> f.homogeneous_order() 5 """ if hasattr(f.rep, 'homogeneous_order'): return f.rep.homogeneous_order() else: # pragma: no cover raise OperationNotSupported(f, 'homogeneous_order') def LC(f, order=None): """ Returns the leading coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC() 4 """ if order is not None: return f.coeffs(order)[0] if hasattr(f.rep, 'LC'): result = f.rep.LC() else: # pragma: no cover raise OperationNotSupported(f, 'LC') return f.rep.dom.to_sympy(result) def TC(f): """ Returns the trailing coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).TC() 0 """ if hasattr(f.rep, 'TC'): result = f.rep.TC() else: # pragma: no cover raise OperationNotSupported(f, 'TC') return f.rep.dom.to_sympy(result) def EC(f, order=None): """ Returns the last non-zero coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).EC() 3 """ if hasattr(f.rep, 'coeffs'): return f.coeffs(order)[-1] else: # pragma: no cover raise OperationNotSupported(f, 'EC') def coeff_monomial(f, monom): """ Returns the coefficient of ``monom`` in ``f`` if there, else None. Examples ======== >>> from sympy import Poly, exp >>> from sympy.abc import x, y >>> p = Poly(24*x*y*exp(8) + 23*x, x, y) >>> p.coeff_monomial(x) 23 >>> p.coeff_monomial(y) 0 >>> p.coeff_monomial(x*y) 24*exp(8) Note that ``Expr.coeff()`` behaves differently, collecting terms if possible; the Poly must be converted to an Expr to use that method, however: >>> p.as_expr().coeff(x) 24*y*exp(8) + 23 >>> p.as_expr().coeff(y) 24*x*exp(8) >>> p.as_expr().coeff(x*y) 24*exp(8) See Also ======== nth: more efficient query using exponents of the monomial's generators """ return f.nth(*Monomial(monom, f.gens).exponents) def nth(f, *N): """ Returns the ``n``-th coefficient of ``f`` where ``N`` are the exponents of the generators in the term of interest. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x, y >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2) 2 >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2) 2 >>> Poly(4*sqrt(x)*y) Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ') >>> _.nth(1, 1) 4 See Also ======== coeff_monomial """ if hasattr(f.rep, 'nth'): if len(N) != len(f.gens): raise ValueError('exponent of each generator must be specified') result = f.rep.nth(*list(map(int, N))) else: # pragma: no cover raise OperationNotSupported(f, 'nth') return f.rep.dom.to_sympy(result) def coeff(f, x, n=1, right=False): # the semantics of coeff_monomial and Expr.coeff are different; # if someone is working with a Poly, they should be aware of the # differences and chose the method best suited for the query. # Alternatively, a pure-polys method could be written here but # at this time the ``right`` keyword would be ignored because Poly # doesn't work with non-commutatives. raise NotImplementedError( 'Either convert to Expr with `as_expr` method ' 'to use Expr\'s coeff method or else use the ' '`coeff_monomial` method of Polys.') def LM(f, order=None): """ Returns the leading monomial of ``f``. The Leading monomial signifies the monomial having the highest power of the principal generator in the expression f. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM() x**2*y**0 """ return Monomial(f.monoms(order)[0], f.gens) def EM(f, order=None): """ Returns the last non-zero monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM() x**0*y**1 """ return Monomial(f.monoms(order)[-1], f.gens) def LT(f, order=None): """ Returns the leading term of ``f``. The Leading term signifies the term having the highest power of the principal generator in the expression f along with its coefficient. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT() (x**2*y**0, 4) """ monom, coeff = f.terms(order)[0] return Monomial(monom, f.gens), coeff def ET(f, order=None): """ Returns the last non-zero term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET() (x**0*y**1, 3) """ monom, coeff = f.terms(order)[-1] return Monomial(monom, f.gens), coeff def max_norm(f): """ Returns maximum norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).max_norm() 3 """ if hasattr(f.rep, 'max_norm'): result = f.rep.max_norm() else: # pragma: no cover raise OperationNotSupported(f, 'max_norm') return f.rep.dom.to_sympy(result) def l1_norm(f): """ Returns l1 norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).l1_norm() 6 """ if hasattr(f.rep, 'l1_norm'): result = f.rep.l1_norm() else: # pragma: no cover raise OperationNotSupported(f, 'l1_norm') return f.rep.dom.to_sympy(result) def clear_denoms(self, convert=False): """ Clear denominators, but keep the ground domain. Examples ======== >>> from sympy import Poly, S, QQ >>> from sympy.abc import x >>> f = Poly(x/2 + S(1)/3, x, domain=QQ) >>> f.clear_denoms() (6, Poly(3*x + 2, x, domain='QQ')) >>> f.clear_denoms(convert=True) (6, Poly(3*x + 2, x, domain='ZZ')) """ f = self if not f.rep.dom.is_Field: return S.One, f dom = f.get_domain() if dom.has_assoc_Ring: dom = f.rep.dom.get_ring() if hasattr(f.rep, 'clear_denoms'): coeff, result = f.rep.clear_denoms() else: # pragma: no cover raise OperationNotSupported(f, 'clear_denoms') coeff, f = dom.to_sympy(coeff), f.per(result) if not convert or not dom.has_assoc_Ring: return coeff, f else: return coeff, f.to_ring() def rat_clear_denoms(self, g): """ Clear denominators in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2/y + 1, x) >>> g = Poly(x**3 + y, x) >>> p, q = f.rat_clear_denoms(g) >>> p Poly(x**2 + y, x, domain='ZZ[y]') >>> q Poly(y*x**3 + y**2, x, domain='ZZ[y]') """ f = self dom, per, f, g = f._unify(g) f = per(f) g = per(g) if not (dom.is_Field and dom.has_assoc_Ring): return f, g a, f = f.clear_denoms(convert=True) b, g = g.clear_denoms(convert=True) f = f.mul_ground(b) g = g.mul_ground(a) return f, g def integrate(self, *specs, **args): """ Computes indefinite integral of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).integrate() Poly(1/3*x**3 + x**2 + x, x, domain='QQ') >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0)) Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ') """ f = self if args.get('auto', True) and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'integrate'): if not specs: return f.per(f.rep.integrate(m=1)) rep = f.rep for spec in specs: if isinstance(spec, tuple): gen, m = spec else: gen, m = spec, 1 rep = rep.integrate(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'integrate') def diff(f, *specs, **kwargs): """ Computes partial derivative of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).diff() Poly(2*x + 2, x, domain='ZZ') >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1)) Poly(2*x*y, x, y, domain='ZZ') """ if not kwargs.get('evaluate', True): return Derivative(f, *specs, **kwargs) if hasattr(f.rep, 'diff'): if not specs: return f.per(f.rep.diff(m=1)) rep = f.rep for spec in specs: if isinstance(spec, tuple): gen, m = spec else: gen, m = spec, 1 rep = rep.diff(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'diff') _eval_derivative = diff def eval(self, x, a=None, auto=True): """ Evaluate ``f`` at ``a`` in the given variable. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 2*x + 3, x).eval(2) 11 >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2) Poly(5*y + 8, y, domain='ZZ') >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f.eval({x: 2}) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f.eval({x: 2, y: 5}) Poly(2*z + 31, z, domain='ZZ') >>> f.eval({x: 2, y: 5, z: 7}) 45 >>> f.eval((2, 5)) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') """ f = self if a is None: if isinstance(x, dict): mapping = x for gen, value in mapping.items(): f = f.eval(gen, value) return f elif isinstance(x, (tuple, list)): values = x if len(values) > len(f.gens): raise ValueError("too many values provided") for gen, value in zip(f.gens, values): f = f.eval(gen, value) return f else: j, a = 0, x else: j = f._gen_to_level(x) if not hasattr(f.rep, 'eval'): # pragma: no cover raise OperationNotSupported(f, 'eval') try: result = f.rep.eval(a, j) except CoercionFailed: if not auto: raise DomainError("Cannot evaluate at %s in %s" % (a, f.rep.dom)) else: a_domain, [a] = construct_domain([a]) new_domain = f.get_domain().unify_with_symbols(a_domain, f.gens) f = f.set_domain(new_domain) a = new_domain.convert(a, a_domain) result = f.rep.eval(a, j) return f.per(result, remove=j) def __call__(f, *values): """ Evaluate ``f`` at the give values. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f(2) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5, 7) 45 """ return f.eval(values) def half_gcdex(f, g, auto=True): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).half_gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'half_gcdex'): s, h = F.half_gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'half_gcdex') return per(s), per(h) def gcdex(f, g, auto=True): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'gcdex'): s, t, h = F.gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcdex') return per(s), per(t), per(h) def invert(f, g, auto=True): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x)) Poly(-4/3, x, domain='QQ') >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x)) Traceback (most recent call last): ... NotInvertible: zero divisor """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'invert'): result = F.invert(G) else: # pragma: no cover raise OperationNotSupported(f, 'invert') return per(result) def revert(f, n): """ Compute ``f**(-1)`` mod ``x**n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(1, x).revert(2) Poly(1, x, domain='ZZ') >>> Poly(1 + x, x).revert(1) Poly(1, x, domain='ZZ') >>> Poly(x**2 - 2, x).revert(2) Traceback (most recent call last): ... NotReversible: only units are reversible in a ring >>> Poly(1/x, x).revert(1) Traceback (most recent call last): ... PolynomialError: 1/x contains an element of the generators set """ if hasattr(f.rep, 'revert'): result = f.rep.revert(int(n)) else: # pragma: no cover raise OperationNotSupported(f, 'revert') return f.per(result) def subresultants(f, g): """ Computes the subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x)) [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')] """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'subresultants'): result = F.subresultants(G) else: # pragma: no cover raise OperationNotSupported(f, 'subresultants') return list(map(per, result)) def resultant(f, g, includePRS=False): """ Computes the resultant of ``f`` and ``g`` via PRS. If includePRS=True, it includes the subresultant PRS in the result. Because the PRS is used to calculate the resultant, this is more efficient than calling :func:`subresultants` separately. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x) >>> f.resultant(Poly(x**2 - 1, x)) 4 >>> f.resultant(Poly(x**2 - 1, x), includePRS=True) (4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')]) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'resultant'): if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) else: # pragma: no cover raise OperationNotSupported(f, 'resultant') if includePRS: return (per(result, remove=0), list(map(per, R))) return per(result, remove=0) def discriminant(f): """ Computes the discriminant of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x + 3, x).discriminant() -8 """ if hasattr(f.rep, 'discriminant'): result = f.rep.discriminant() else: # pragma: no cover raise OperationNotSupported(f, 'discriminant') return f.per(result, remove=0) def dispersionset(f, g=None): r"""Compute the *dispersion set* of two polynomials. For two polynomials `f(x)` and `g(x)` with `\deg f > 0` and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as: .. math:: \operatorname{J}(f, g) & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\} For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`. Examples ======== >>> from sympy import poly >>> from sympy.polys.dispersion import dispersion, dispersionset >>> from sympy.abc import x Dispersion set and dispersion of a simple polynomial: >>> fp = poly((x - 3)*(x + 3), x) >>> sorted(dispersionset(fp)) [0, 6] >>> dispersion(fp) 6 Note that the definition of the dispersion is not symmetric: >>> fp = poly(x**4 - 3*x**2 + 1, x) >>> gp = fp.shift(-3) >>> sorted(dispersionset(fp, gp)) [2, 3, 4] >>> dispersion(fp, gp) 4 >>> sorted(dispersionset(gp, fp)) [] >>> dispersion(gp, fp) -oo Computing the dispersion also works over field extensions: >>> from sympy import sqrt >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>') >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>') >>> sorted(dispersionset(fp, gp)) [2] >>> sorted(dispersionset(gp, fp)) [1, 4] We can even perform the computations for polynomials having symbolic coefficients: >>> from sympy.abc import a >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) >>> sorted(dispersionset(fp)) [0, 1] See Also ======== dispersion References ========== 1. [ManWright94]_ 2. [Koepf98]_ 3. [Abramov71]_ 4. [Man93]_ """ from sympy.polys.dispersion import dispersionset return dispersionset(f, g) def dispersion(f, g=None): r"""Compute the *dispersion* of polynomials. For two polynomials `f(x)` and `g(x)` with `\deg f > 0` and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as: .. math:: \operatorname{dis}(f, g) & := \max\{ J(f,g) \cup \{0\} \} \\ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \} and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`. Examples ======== >>> from sympy import poly >>> from sympy.polys.dispersion import dispersion, dispersionset >>> from sympy.abc import x Dispersion set and dispersion of a simple polynomial: >>> fp = poly((x - 3)*(x + 3), x) >>> sorted(dispersionset(fp)) [0, 6] >>> dispersion(fp) 6 Note that the definition of the dispersion is not symmetric: >>> fp = poly(x**4 - 3*x**2 + 1, x) >>> gp = fp.shift(-3) >>> sorted(dispersionset(fp, gp)) [2, 3, 4] >>> dispersion(fp, gp) 4 >>> sorted(dispersionset(gp, fp)) [] >>> dispersion(gp, fp) -oo Computing the dispersion also works over field extensions: >>> from sympy import sqrt >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>') >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>') >>> sorted(dispersionset(fp, gp)) [2] >>> sorted(dispersionset(gp, fp)) [1, 4] We can even perform the computations for polynomials having symbolic coefficients: >>> from sympy.abc import a >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) >>> sorted(dispersionset(fp)) [0, 1] See Also ======== dispersionset References ========== 1. [ManWright94]_ 2. [Koepf98]_ 3. [Abramov71]_ 4. [Man93]_ """ from sympy.polys.dispersion import dispersion return dispersion(f, g) def cofactors(f, g): """ Returns the GCD of ``f`` and ``g`` and their cofactors. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x)) (Poly(x - 1, x, domain='ZZ'), Poly(x + 1, x, domain='ZZ'), Poly(x - 2, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'cofactors'): h, cff, cfg = F.cofactors(G) else: # pragma: no cover raise OperationNotSupported(f, 'cofactors') return per(h), per(cff), per(cfg) def gcd(f, g): """ Returns the polynomial GCD of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x)) Poly(x - 1, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'gcd'): result = F.gcd(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcd') return per(result) def lcm(f, g): """ Returns polynomial LCM of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x)) Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'lcm'): result = F.lcm(G) else: # pragma: no cover raise OperationNotSupported(f, 'lcm') return per(result) def trunc(f, p): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3) Poly(-x**3 - x + 1, x, domain='ZZ') """ p = f.rep.dom.convert(p) if hasattr(f.rep, 'trunc'): result = f.rep.trunc(p) else: # pragma: no cover raise OperationNotSupported(f, 'trunc') return f.per(result) def monic(self, auto=True): """ Divides all coefficients by ``LC(f)``. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic() Poly(x**2 + 2*x + 3, x, domain='QQ') >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic() Poly(x**2 + 4/3*x + 2/3, x, domain='QQ') """ f = self if auto and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'monic'): result = f.rep.monic() else: # pragma: no cover raise OperationNotSupported(f, 'monic') return f.per(result) def content(f): """ Returns the GCD of polynomial coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(6*x**2 + 8*x + 12, x).content() 2 """ if hasattr(f.rep, 'content'): result = f.rep.content() else: # pragma: no cover raise OperationNotSupported(f, 'content') return f.rep.dom.to_sympy(result) def primitive(f): """ Returns the content and a primitive form of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 8*x + 12, x).primitive() (2, Poly(x**2 + 4*x + 6, x, domain='ZZ')) """ if hasattr(f.rep, 'primitive'): cont, result = f.rep.primitive() else: # pragma: no cover raise OperationNotSupported(f, 'primitive') return f.rep.dom.to_sympy(cont), f.per(result) def compose(f, g): """ Computes the functional composition of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x, x).compose(Poly(x - 1, x)) Poly(x**2 - x, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'compose'): result = F.compose(G) else: # pragma: no cover raise OperationNotSupported(f, 'compose') return per(result) def decompose(f): """ Computes a functional decomposition of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose() [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')] """ if hasattr(f.rep, 'decompose'): result = f.rep.decompose() else: # pragma: no cover raise OperationNotSupported(f, 'decompose') return list(map(f.per, result)) def shift(f, a): """ Efficiently compute Taylor shift ``f(x + a)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).shift(2) Poly(x**2 + 2*x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'shift'): result = f.rep.shift(a) else: # pragma: no cover raise OperationNotSupported(f, 'shift') return f.per(result) def transform(f, p, q): """ Efficiently evaluate the functional transformation ``q**n * f(p/q)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x)) Poly(4, x, domain='ZZ') """ P, Q = p.unify(q) F, P = f.unify(P) F, Q = F.unify(Q) if hasattr(F.rep, 'transform'): result = F.rep.transform(P.rep, Q.rep) else: # pragma: no cover raise OperationNotSupported(F, 'transform') return F.per(result) def sturm(self, auto=True): """ Computes the Sturm sequence of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm() [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'), Poly(3*x**2 - 4*x + 1, x, domain='QQ'), Poly(2/9*x + 25/9, x, domain='QQ'), Poly(-2079/4, x, domain='QQ')] """ f = self if auto and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'sturm'): result = f.rep.sturm() else: # pragma: no cover raise OperationNotSupported(f, 'sturm') return list(map(f.per, result)) def gff_list(f): """ Computes greatest factorial factorization of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> Poly(f).gff_list() [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'gff_list'): result = f.rep.gff_list() else: # pragma: no cover raise OperationNotSupported(f, 'gff_list') return [(f.per(g), k) for g, k in result] def norm(f): """ Computes the product, ``Norm(f)``, of the conjugates of a polynomial ``f`` defined over a number field ``K``. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> a, b = sqrt(2), sqrt(3) A polynomial over a quadratic extension. Two conjugates x - a and x + a. >>> f = Poly(x - a, x, extension=a) >>> f.norm() Poly(x**2 - 2, x, domain='QQ') A polynomial over a quartic extension. Four conjugates x - a, x - a, x + a and x + a. >>> f = Poly(x - a, x, extension=(a, b)) >>> f.norm() Poly(x**4 - 4*x**2 + 4, x, domain='QQ') """ if hasattr(f.rep, 'norm'): r = f.rep.norm() else: # pragma: no cover raise OperationNotSupported(f, 'norm') return f.per(r) def sqf_norm(f): """ Computes square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm() >>> s 1 >>> f Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>') >>> r Poly(x**4 - 4*x**2 + 16, x, domain='QQ') """ if hasattr(f.rep, 'sqf_norm'): s, g, r = f.rep.sqf_norm() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_norm') return s, f.per(g), f.per(r) def sqf_part(f): """ Computes square-free part of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 3*x - 2, x).sqf_part() Poly(x**2 - x - 2, x, domain='ZZ') """ if hasattr(f.rep, 'sqf_part'): result = f.rep.sqf_part() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_part') return f.per(result) def sqf_list(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 >>> Poly(f).sqf_list() (2, [(Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) >>> Poly(f).sqf_list(all=True) (2, [(Poly(1, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) """ if hasattr(f.rep, 'sqf_list'): coeff, factors = f.rep.sqf_list(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list') return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] def sqf_list_include(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly, expand >>> from sympy.abc import x >>> f = expand(2*(x + 1)**3*x**4) >>> f 2*x**7 + 6*x**6 + 6*x**5 + 2*x**4 >>> Poly(f).sqf_list_include() [(Poly(2, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] >>> Poly(f).sqf_list_include(all=True) [(Poly(2, x, domain='ZZ'), 1), (Poly(1, x, domain='ZZ'), 2), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'sqf_list_include'): factors = f.rep.sqf_list_include(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list_include') return [(f.per(g), k) for g, k in factors] def factor_list(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list() (2, [(Poly(x + y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]) """ if hasattr(f.rep, 'factor_list'): try: coeff, factors = f.rep.factor_list() except DomainError: return S.One, [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list') return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] def factor_list_include(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list_include() [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)] """ if hasattr(f.rep, 'factor_list_include'): try: factors = f.rep.factor_list_include() except DomainError: return [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list_include') return [(f.per(g), k) for g, k in factors] def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used. References ========== .. [#] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. .. [#] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).intervals() [((-2, -1), 1), ((1, 2), 1)] >>> Poly(x**2 - 3, x).intervals(eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = QQ.convert(inf) if sup is not None: sup = QQ.convert(sup) if hasattr(f.rep, 'intervals'): result = f.rep.intervals( all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: # pragma: no cover raise OperationNotSupported(f, 'intervals') if sqf: def _real(interval): s, t = interval return (QQ.to_sympy(s), QQ.to_sympy(t)) if not all: return list(map(_real, result)) def _complex(rectangle): (u, v), (s, t) = rectangle return (QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)) real_part, complex_part = result return list(map(_real, real_part)), list(map(_complex, complex_part)) else: def _real(interval): (s, t), k = interval return ((QQ.to_sympy(s), QQ.to_sympy(t)), k) if not all: return list(map(_real, result)) def _complex(rectangle): ((u, v), (s, t)), k = rectangle return ((QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)), k) real_part, complex_part = result return list(map(_real, real_part)), list(map(_complex, complex_part)) def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2) (19/11, 26/15) """ if check_sqf and not f.is_sqf: raise PolynomialError("only square-free polynomials supported") s, t = QQ.convert(s), QQ.convert(t) if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if steps is not None: steps = int(steps) elif eps is None: steps = 1 if hasattr(f.rep, 'refine_root'): S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast) else: # pragma: no cover raise OperationNotSupported(f, 'refine_root') return QQ.to_sympy(S), QQ.to_sympy(T) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**4 - 4, x).count_roots(-3, 3) 2 >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I) 1 """ inf_real, sup_real = True, True if inf is not None: inf = sympify(inf) if inf is S.NegativeInfinity: inf = None else: re, im = inf.as_real_imag() if not im: inf = QQ.convert(inf) else: inf, inf_real = list(map(QQ.convert, (re, im))), False if sup is not None: sup = sympify(sup) if sup is S.Infinity: sup = None else: re, im = sup.as_real_imag() if not im: sup = QQ.convert(sup) else: sup, sup_real = list(map(QQ.convert, (re, im))), False if inf_real and sup_real: if hasattr(f.rep, 'count_real_roots'): count = f.rep.count_real_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_real_roots') else: if inf_real and inf is not None: inf = (inf, QQ.zero) if sup_real and sup is not None: sup = (sup, QQ.zero) if hasattr(f.rep, 'count_complex_roots'): count = f.rep.count_complex_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_complex_roots') return Integer(count) def root(f, index, radicals=True): """ Get an indexed root of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4) >>> f.root(0) -1/2 >>> f.root(1) 2 >>> f.root(2) 2 >>> f.root(3) Traceback (most recent call last): ... IndexError: root index out of [-3, 2] range, got 3 >>> Poly(x**5 + x + 1).root(0) CRootOf(x**3 - x**2 + 1, 0) """ return sympy.polys.rootoftools.rootof(f, index, radicals=radicals) def real_roots(f, multiple=True, radicals=True): """ Return a list of real roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).real_roots() [CRootOf(x**3 + x + 1, 0)] """ reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals) if multiple: return reals else: return group(reals, multiple=False) def all_roots(f, multiple=True, radicals=True): """ Return a list of real and complex roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).all_roots() [CRootOf(x**3 + x + 1, 0), CRootOf(x**3 + x + 1, 1), CRootOf(x**3 + x + 1, 2)] """ roots = sympy.polys.rootoftools.CRootOf.all_roots(f, radicals=radicals) if multiple: return roots else: return group(roots, multiple=False) def nroots(f, n=15, maxsteps=50, cleanup=True): """ Compute numerical approximations of roots of ``f``. Parameters ========== n ... the number of digits to calculate maxsteps ... the maximum number of iterations to do If the accuracy `n` cannot be reached in `maxsteps`, it will raise an exception. You need to rerun with higher maxsteps. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3).nroots(n=15) [-1.73205080756888, 1.73205080756888] >>> Poly(x**2 - 3).nroots(n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ if f.is_multivariate: raise MultivariatePolynomialError( "Cannot compute numerical roots of %s" % f) if f.degree() <= 0: return [] # For integer and rational coefficients, convert them to integers only # (for accuracy). Otherwise just try to convert the coefficients to # mpmath.mpc and raise an exception if the conversion fails. if f.rep.dom is ZZ: coeffs = [int(coeff) for coeff in f.all_coeffs()] elif f.rep.dom is QQ: denoms = [coeff.q for coeff in f.all_coeffs()] fac = ilcm(*denoms) coeffs = [int(coeff*fac) for coeff in f.all_coeffs()] else: coeffs = [coeff.evalf(n=n).as_real_imag() for coeff in f.all_coeffs()] try: coeffs = [mpmath.mpc(*coeff) for coeff in coeffs] except TypeError: raise DomainError("Numerical domain expected, got %s" % \ f.rep.dom) dps = mpmath.mp.dps mpmath.mp.dps = n from sympy.functions.elementary.complexes import sign try: # We need to add extra precision to guard against losing accuracy. # 10 times the degree of the polynomial seems to work well. roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=False, extraprec=f.degree()*10) # Mpmath puts real roots first, then complex ones (as does all_roots) # so we make sure this convention holds here, too. roots = list(map(sympify, sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) except NoConvergence: try: # If roots did not converge try again with more extra precision. roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=False, extraprec=f.degree()*15) roots = list(map(sympify, sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) except NoConvergence: raise NoConvergence( 'convergence to root failed; try n < %s or maxsteps > %s' % ( n, maxsteps)) finally: mpmath.mp.dps = dps return roots def ground_roots(f): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots() {0: 2, 1: 2} """ if f.is_multivariate: raise MultivariatePolynomialError( "Cannot compute ground roots of %s" % f) roots = {} for factor, k in f.factor_list()[1]: if factor.is_linear: a, b = factor.all_coeffs() roots[-b/a] = k return roots def nth_power_roots_poly(f, n): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**4 - x**2 + 1) >>> f.nth_power_roots_poly(2) Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(3) Poly(x**4 + 2*x**2 + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(4) Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(12) Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ') """ if f.is_multivariate: raise MultivariatePolynomialError( "must be a univariate polynomial") N = sympify(n) if N.is_Integer and N >= 1: n = int(N) else: raise ValueError("'n' must an integer and n >= 1, got %s" % n) x = f.gen t = Dummy('t') r = f.resultant(f.__class__.from_expr(x**n - t, x, t)) return r.replace(t, x) def same_root(f, a, b): """ Decide whether two roots of this polynomial are equal. Examples ======== >>> from sympy import Poly, cyclotomic_poly, exp, I, pi >>> f = Poly(cyclotomic_poly(5)) >>> r0 = exp(2*I*pi/5) >>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)] >>> print(indices) [3] Raises ====== DomainError If the domain of the polynomial is not :ref:`ZZ`, :ref:`QQ`, :ref:`RR`, or :ref:`CC`. MultivariatePolynomialError If the polynomial is not univariate. PolynomialError If the polynomial is of degree < 2. """ if f.is_multivariate: raise MultivariatePolynomialError( "Must be a univariate polynomial") dom_delta_sq = f.rep.mignotte_sep_bound_squared() delta_sq = f.domain.get_field().to_sympy(dom_delta_sq) # We have delta_sq = delta**2, where delta is a lower bound on the # minimum separation between any two roots of this polynomial. # Let eps = delta/3, and define eps_sq = eps**2 = delta**2/9. eps_sq = delta_sq / 9 r, _, _, _ = evalf(1/eps_sq, 1, {}) n = fastlog(r) # Then 2^n > 1/eps**2. m = (n // 2) + (n % 2) # Then 2^(-m) < eps. ev = lambda x: quad_to_mpmath(_evalf_with_bounded_error(x, m=m)) # Then for any complex numbers a, b we will have # |a - ev(a)| < eps and |b - ev(b)| < eps. # So if |ev(a) - ev(b)|**2 < eps**2, then # |ev(a) - ev(b)| < eps, hence |a - b| < 3*eps = delta. A, B = ev(a), ev(b) return (A.real - B.real)**2 + (A.imag - B.imag)**2 < eps_sq def cancel(f, g, include=False): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x)) (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True) (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) if hasattr(F, 'cancel'): result = F.cancel(G, include=include) else: # pragma: no cover raise OperationNotSupported(f, 'cancel') if not include: if dom.has_assoc_Ring: dom = dom.get_ring() cp, cq, p, q = result cp = dom.to_sympy(cp) cq = dom.to_sympy(cq) return cp/cq, per(p), per(q) else: return tuple(map(per, result)) @property def is_zero(f): """ Returns ``True`` if ``f`` is a zero polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_zero True >>> Poly(1, x).is_zero False """ return f.rep.is_zero @property def is_one(f): """ Returns ``True`` if ``f`` is a unit polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_one False >>> Poly(1, x).is_one True """ return f.rep.is_one @property def is_sqf(f): """ Returns ``True`` if ``f`` is a square-free polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).is_sqf False >>> Poly(x**2 - 1, x).is_sqf True """ return f.rep.is_sqf @property def is_monic(f): """ Returns ``True`` if the leading coefficient of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 2, x).is_monic True >>> Poly(2*x + 2, x).is_monic False """ return f.rep.is_monic @property def is_primitive(f): """ Returns ``True`` if GCD of the coefficients of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 6*x + 12, x).is_primitive False >>> Poly(x**2 + 3*x + 6, x).is_primitive True """ return f.rep.is_primitive @property def is_ground(f): """ Returns ``True`` if ``f`` is an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x, x).is_ground False >>> Poly(2, x).is_ground True >>> Poly(y, x).is_ground True """ return f.rep.is_ground @property def is_linear(f): """ Returns ``True`` if ``f`` is linear in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x + y + 2, x, y).is_linear True >>> Poly(x*y + 2, x, y).is_linear False """ return f.rep.is_linear @property def is_quadratic(f): """ Returns ``True`` if ``f`` is quadratic in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x*y + 2, x, y).is_quadratic True >>> Poly(x*y**2 + 2, x, y).is_quadratic False """ return f.rep.is_quadratic @property def is_monomial(f): """ Returns ``True`` if ``f`` is zero or has only one term. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(3*x**2, x).is_monomial True >>> Poly(3*x**2 + 1, x).is_monomial False """ return f.rep.is_monomial @property def is_homogeneous(f): """ Returns ``True`` if ``f`` is a homogeneous polynomial. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y, x, y).is_homogeneous True >>> Poly(x**3 + x*y, x, y).is_homogeneous False """ return f.rep.is_homogeneous @property def is_irreducible(f): """ Returns ``True`` if ``f`` has no factors over its domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible True >>> Poly(x**2 + 1, x, modulus=2).is_irreducible False """ return f.rep.is_irreducible @property def is_univariate(f): """ Returns ``True`` if ``f`` is a univariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_univariate True >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate False >>> Poly(x*y**2 + x*y + 1, x).is_univariate True >>> Poly(x**2 + x + 1, x, y).is_univariate False """ return len(f.gens) == 1 @property def is_multivariate(f): """ Returns ``True`` if ``f`` is a multivariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_multivariate False >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate True >>> Poly(x*y**2 + x*y + 1, x).is_multivariate False >>> Poly(x**2 + x + 1, x, y).is_multivariate True """ return len(f.gens) != 1 @property def is_cyclotomic(f): """ Returns ``True`` if ``f`` is a cyclotomic polnomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 >>> Poly(f).is_cyclotomic False >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 >>> Poly(g).is_cyclotomic True """ return f.rep.is_cyclotomic def __abs__(f): return f.abs() def __neg__(f): return f.neg() @_polifyit def __add__(f, g): return f.add(g) @_polifyit def __radd__(f, g): return g.add(f) @_polifyit def __sub__(f, g): return f.sub(g) @_polifyit def __rsub__(f, g): return g.sub(f) @_polifyit def __mul__(f, g): return f.mul(g) @_polifyit def __rmul__(f, g): return g.mul(f) @_sympifyit('n', NotImplemented) def __pow__(f, n): if n.is_Integer and n >= 0: return f.pow(n) else: return NotImplemented @_polifyit def __divmod__(f, g): return f.div(g) @_polifyit def __rdivmod__(f, g): return g.div(f) @_polifyit def __mod__(f, g): return f.rem(g) @_polifyit def __rmod__(f, g): return g.rem(f) @_polifyit def __floordiv__(f, g): return f.quo(g) @_polifyit def __rfloordiv__(f, g): return g.quo(f) @_sympifyit('g', NotImplemented) def __truediv__(f, g): return f.as_expr()/g.as_expr() @_sympifyit('g', NotImplemented) def __rtruediv__(f, g): return g.as_expr()/f.as_expr() @_sympifyit('other', NotImplemented) def __eq__(self, other): f, g = self, other if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if f.gens != g.gens: return False if f.rep.dom != g.rep.dom: return False return f.rep == g.rep @_sympifyit('g', NotImplemented) def __ne__(f, g): return not f == g def __bool__(f): return not f.is_zero def eq(f, g, strict=False): if not strict: return f == g else: return f._strict_eq(sympify(g)) def ne(f, g, strict=False): return not f.eq(g, strict=strict) def _strict_eq(f, g): return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True) @public class PurePoly(Poly): """Class for representing pure polynomials. """ def _hashable_content(self): """Allow SymPy to hash Poly instances. """ return (self.rep,) def __hash__(self): return super().__hash__() @property def free_symbols(self): """ Free symbols of a polynomial. Examples ======== >>> from sympy import PurePoly >>> from sympy.abc import x, y >>> PurePoly(x**2 + 1).free_symbols set() >>> PurePoly(x**2 + y).free_symbols set() >>> PurePoly(x**2 + y, x).free_symbols {y} """ return self.free_symbols_in_domain @_sympifyit('other', NotImplemented) def __eq__(self, other): f, g = self, other if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if len(f.gens) != len(g.gens): return False if f.rep.dom != g.rep.dom: try: dom = f.rep.dom.unify(g.rep.dom, f.gens) except UnificationFailed: return False f = f.set_domain(dom) g = g.set_domain(dom) return f.rep == g.rep def _strict_eq(f, g): return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if len(f.gens) != len(g.gens): raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)): raise UnificationFailed("Cannot unify %s with %s" % (f, g)) cls = f.__class__ gens = f.gens dom = f.rep.dom.unify(g.rep.dom, gens) F = f.rep.convert(dom) G = g.rep.convert(dom) def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G @public def poly_from_expr(expr, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return _poly_from_expr(expr, opt) def _poly_from_expr(expr, opt): """Construct a polynomial from an expression. """ orig, expr = expr, sympify(expr) if not isinstance(expr, Basic): raise PolificationFailed(opt, orig, expr) elif expr.is_Poly: poly = expr.__class__._from_poly(expr, opt) opt.gens = poly.gens opt.domain = poly.domain if opt.polys is None: opt.polys = True return poly, opt elif opt.expand: expr = expr.expand() rep, opt = _dict_from_expr(expr, opt) if not opt.gens: raise PolificationFailed(opt, orig, expr) monoms, coeffs = list(zip(*list(rep.items()))) domain = opt.domain if domain is None: opt.domain, coeffs = construct_domain(coeffs, opt=opt) else: coeffs = list(map(domain.from_sympy, coeffs)) rep = dict(list(zip(monoms, coeffs))) poly = Poly._from_dict(rep, opt) if opt.polys is None: opt.polys = False return poly, opt @public def parallel_poly_from_expr(exprs, *gens, **args): """Construct polynomials from expressions. """ opt = options.build_options(gens, args) return _parallel_poly_from_expr(exprs, opt) def _parallel_poly_from_expr(exprs, opt): """Construct polynomials from expressions. """ if len(exprs) == 2: f, g = exprs if isinstance(f, Poly) and isinstance(g, Poly): f = f.__class__._from_poly(f, opt) g = g.__class__._from_poly(g, opt) f, g = f.unify(g) opt.gens = f.gens opt.domain = f.domain if opt.polys is None: opt.polys = True return [f, g], opt origs, exprs = list(exprs), [] _exprs, _polys = [], [] failed = False for i, expr in enumerate(origs): expr = sympify(expr) if isinstance(expr, Basic): if expr.is_Poly: _polys.append(i) else: _exprs.append(i) if opt.expand: expr = expr.expand() else: failed = True exprs.append(expr) if failed: raise PolificationFailed(opt, origs, exprs, True) if _polys: # XXX: this is a temporary solution for i in _polys: exprs[i] = exprs[i].as_expr() reps, opt = _parallel_dict_from_expr(exprs, opt) if not opt.gens: raise PolificationFailed(opt, origs, exprs, True) from sympy.functions.elementary.piecewise import Piecewise for k in opt.gens: if isinstance(k, Piecewise): raise PolynomialError("Piecewise generators do not make sense") coeffs_list, lengths = [], [] all_monoms = [] all_coeffs = [] for rep in reps: monoms, coeffs = list(zip(*list(rep.items()))) coeffs_list.extend(coeffs) all_monoms.append(monoms) lengths.append(len(coeffs)) domain = opt.domain if domain is None: opt.domain, coeffs_list = construct_domain(coeffs_list, opt=opt) else: coeffs_list = list(map(domain.from_sympy, coeffs_list)) for k in lengths: all_coeffs.append(coeffs_list[:k]) coeffs_list = coeffs_list[k:] polys = [] for monoms, coeffs in zip(all_monoms, all_coeffs): rep = dict(list(zip(monoms, coeffs))) poly = Poly._from_dict(rep, opt) polys.append(poly) if opt.polys is None: opt.polys = bool(_polys) return polys, opt def _update_args(args, key, value): """Add a new ``(key, value)`` pair to arguments ``dict``. """ args = dict(args) if key not in args: args[key] = value return args @public def degree(f, gen=0): """ Return the degree of ``f`` in the given variable. The degree of 0 is negative infinity. Examples ======== >>> from sympy import degree >>> from sympy.abc import x, y >>> degree(x**2 + y*x + 1, gen=x) 2 >>> degree(x**2 + y*x + 1, gen=y) 1 >>> degree(0, x) -oo See also ======== sympy.polys.polytools.Poly.total_degree degree_list """ f = sympify(f, strict=True) gen_is_Num = sympify(gen, strict=True).is_Number if f.is_Poly: p = f isNum = p.as_expr().is_Number else: isNum = f.is_Number if not isNum: if gen_is_Num: p, _ = poly_from_expr(f) else: p, _ = poly_from_expr(f, gen) if isNum: return S.Zero if f else S.NegativeInfinity if not gen_is_Num: if f.is_Poly and gen not in p.gens: # try recast without explicit gens p, _ = poly_from_expr(f.as_expr()) if gen not in p.gens: return S.Zero elif not f.is_Poly and len(f.free_symbols) > 1: raise TypeError(filldedent(''' A symbolic generator of interest is required for a multivariate expression like func = %s, e.g. degree(func, gen = %s) instead of degree(func, gen = %s). ''' % (f, next(ordered(f.free_symbols)), gen))) result = p.degree(gen) return Integer(result) if isinstance(result, int) else S.NegativeInfinity @public def total_degree(f, *gens): """ Return the total_degree of ``f`` in the given variables. Examples ======== >>> from sympy import total_degree, Poly >>> from sympy.abc import x, y >>> total_degree(1) 0 >>> total_degree(x + x*y) 2 >>> total_degree(x + x*y, x) 1 If the expression is a Poly and no variables are given then the generators of the Poly will be used: >>> p = Poly(x + x*y, y) >>> total_degree(p) 1 To deal with the underlying expression of the Poly, convert it to an Expr: >>> total_degree(p.as_expr()) 2 This is done automatically if any variables are given: >>> total_degree(p, x) 1 See also ======== degree """ p = sympify(f) if p.is_Poly: p = p.as_expr() if p.is_Number: rv = 0 else: if f.is_Poly: gens = gens or f.gens rv = Poly(p, gens).total_degree() return Integer(rv) @public def degree_list(f, *gens, **args): """ Return a list of degrees of ``f`` in all variables. Examples ======== >>> from sympy import degree_list >>> from sympy.abc import x, y >>> degree_list(x**2 + y*x + 1) (2, 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('degree_list', 1, exc) degrees = F.degree_list() return tuple(map(Integer, degrees)) @public def LC(f, *gens, **args): """ Return the leading coefficient of ``f``. Examples ======== >>> from sympy import LC >>> from sympy.abc import x, y >>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y) 4 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('LC', 1, exc) return F.LC(order=opt.order) @public def LM(f, *gens, **args): """ Return the leading monomial of ``f``. Examples ======== >>> from sympy import LM >>> from sympy.abc import x, y >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('LM', 1, exc) monom = F.LM(order=opt.order) return monom.as_expr() @public def LT(f, *gens, **args): """ Return the leading term of ``f``. Examples ======== >>> from sympy import LT >>> from sympy.abc import x, y >>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y) 4*x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('LT', 1, exc) monom, coeff = F.LT(order=opt.order) return coeff*monom.as_expr() @public def pdiv(f, g, *gens, **args): """ Compute polynomial pseudo-division of ``f`` and ``g``. Examples ======== >>> from sympy import pdiv >>> from sympy.abc import x >>> pdiv(x**2 + 1, 2*x - 4) (2*x + 4, 20) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('pdiv', 2, exc) q, r = F.pdiv(G) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r @public def prem(f, g, *gens, **args): """ Compute polynomial pseudo-remainder of ``f`` and ``g``. Examples ======== >>> from sympy import prem >>> from sympy.abc import x >>> prem(x**2 + 1, 2*x - 4) 20 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('prem', 2, exc) r = F.prem(G) if not opt.polys: return r.as_expr() else: return r @public def pquo(f, g, *gens, **args): """ Compute polynomial pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pquo >>> from sympy.abc import x >>> pquo(x**2 + 1, 2*x - 4) 2*x + 4 >>> pquo(x**2 - 1, 2*x - 1) 2*x + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('pquo', 2, exc) try: q = F.pquo(G) except ExactQuotientFailed: raise ExactQuotientFailed(f, g) if not opt.polys: return q.as_expr() else: return q @public def pexquo(f, g, *gens, **args): """ Compute polynomial exact pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pexquo >>> from sympy.abc import x >>> pexquo(x**2 - 1, 2*x - 2) 2*x + 2 >>> pexquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('pexquo', 2, exc) q = F.pexquo(G) if not opt.polys: return q.as_expr() else: return q @public def div(f, g, *gens, **args): """ Compute polynomial division of ``f`` and ``g``. Examples ======== >>> from sympy import div, ZZ, QQ >>> from sympy.abc import x >>> div(x**2 + 1, 2*x - 4, domain=ZZ) (0, x**2 + 1) >>> div(x**2 + 1, 2*x - 4, domain=QQ) (x/2 + 1, 5) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('div', 2, exc) q, r = F.div(G, auto=opt.auto) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r @public def rem(f, g, *gens, **args): """ Compute polynomial remainder of ``f`` and ``g``. Examples ======== >>> from sympy import rem, ZZ, QQ >>> from sympy.abc import x >>> rem(x**2 + 1, 2*x - 4, domain=ZZ) x**2 + 1 >>> rem(x**2 + 1, 2*x - 4, domain=QQ) 5 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('rem', 2, exc) r = F.rem(G, auto=opt.auto) if not opt.polys: return r.as_expr() else: return r @public def quo(f, g, *gens, **args): """ Compute polynomial quotient of ``f`` and ``g``. Examples ======== >>> from sympy import quo >>> from sympy.abc import x >>> quo(x**2 + 1, 2*x - 4) x/2 + 1 >>> quo(x**2 - 1, x - 1) x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('quo', 2, exc) q = F.quo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q @public def exquo(f, g, *gens, **args): """ Compute polynomial exact quotient of ``f`` and ``g``. Examples ======== >>> from sympy import exquo >>> from sympy.abc import x >>> exquo(x**2 - 1, x - 1) x + 1 >>> exquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('exquo', 2, exc) q = F.exquo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q @public def half_gcdex(f, g, *gens, **args): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import half_gcdex >>> from sympy.abc import x >>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (3/5 - x/5, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: s, h = domain.half_gcdex(a, b) except NotImplementedError: raise ComputationFailed('half_gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(h) s, h = F.half_gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), h.as_expr() else: return s, h @public def gcdex(f, g, *gens, **args): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import gcdex >>> from sympy.abc import x >>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (3/5 - x/5, x**2/5 - 6*x/5 + 2, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: s, t, h = domain.gcdex(a, b) except NotImplementedError: raise ComputationFailed('gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(t), domain.to_sympy(h) s, t, h = F.gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), t.as_expr(), h.as_expr() else: return s, t, h @public def invert(f, g, *gens, **args): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import invert, S, mod_inverse >>> from sympy.abc import x >>> invert(x**2 - 1, 2*x - 1) -4/3 >>> invert(x**2 - 1, x - 1) Traceback (most recent call last): ... NotInvertible: zero divisor For more efficient inversion of Rationals, use the :obj:`~.mod_inverse` function: >>> mod_inverse(3, 5) 2 >>> (S(2)/5).invert(S(7)/3) 5/2 See Also ======== sympy.core.numbers.mod_inverse """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.invert(a, b)) except NotImplementedError: raise ComputationFailed('invert', 2, exc) h = F.invert(G, auto=opt.auto) if not opt.polys: return h.as_expr() else: return h @public def subresultants(f, g, *gens, **args): """ Compute subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import subresultants >>> from sympy.abc import x >>> subresultants(x**2 + 1, x**2 - 1) [x**2 + 1, x**2 - 1, -2] """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('subresultants', 2, exc) result = F.subresultants(G) if not opt.polys: return [r.as_expr() for r in result] else: return result @public def resultant(f, g, *gens, includePRS=False, **args): """ Compute resultant of ``f`` and ``g``. Examples ======== >>> from sympy import resultant >>> from sympy.abc import x >>> resultant(x**2 + 1, x**2 - 1) 4 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('resultant', 2, exc) if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) if not opt.polys: if includePRS: return result.as_expr(), [r.as_expr() for r in R] return result.as_expr() else: if includePRS: return result, R return result @public def discriminant(f, *gens, **args): """ Compute discriminant of ``f``. Examples ======== >>> from sympy import discriminant >>> from sympy.abc import x >>> discriminant(x**2 + 2*x + 3) -8 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('discriminant', 1, exc) result = F.discriminant() if not opt.polys: return result.as_expr() else: return result @public def cofactors(f, g, *gens, **args): """ Compute GCD and cofactors of ``f`` and ``g``. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import cofactors >>> from sympy.abc import x >>> cofactors(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: h, cff, cfg = domain.cofactors(a, b) except NotImplementedError: raise ComputationFailed('cofactors', 2, exc) else: return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg) h, cff, cfg = F.cofactors(G) if not opt.polys: return h.as_expr(), cff.as_expr(), cfg.as_expr() else: return h, cff, cfg @public def gcd_list(seq, *gens, **args): """ Compute GCD of a list of polynomials. Examples ======== >>> from sympy import gcd_list >>> from sympy.abc import x >>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x - 1 """ seq = sympify(seq) def try_non_polynomial_gcd(seq): if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.zero elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.gcd(result, number) if domain.is_one(result): break return domain.to_sympy(result) return None result = try_non_polynomial_gcd(seq) if result is not None: return result options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) # gcd for domain Q[irrational] (purely algebraic irrational) if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq): a = seq[-1] lst = [ (a/elt).ratsimp() for elt in seq[:-1] ] if all(frc.is_rational for frc in lst): lc = 1 for frc in lst: lc = lcm(lc, frc.as_numer_denom()[0]) # abs ensures that the gcd is always non-negative return abs(a/lc) except PolificationFailed as exc: result = try_non_polynomial_gcd(exc.exprs) if result is not None: return result else: raise ComputationFailed('gcd_list', len(seq), exc) if not polys: if not opt.polys: return S.Zero else: return Poly(0, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.gcd(poly) if result.is_one: break if not opt.polys: return result.as_expr() else: return result @public def gcd(f, g=None, *gens, **args): """ Compute GCD of ``f`` and ``g``. Examples ======== >>> from sympy import gcd >>> from sympy.abc import x >>> gcd(x**2 - 1, x**2 - 3*x + 2) x - 1 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return gcd_list(f, *gens, **args) elif g is None: raise TypeError("gcd() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) # gcd for domain Q[irrational] (purely algebraic irrational) a, b = map(sympify, (f, g)) if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational: frc = (a/b).ratsimp() if frc.is_rational: # abs ensures that the returned gcd is always non-negative return abs(a/frc.as_numer_denom()[0]) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.gcd(a, b)) except NotImplementedError: raise ComputationFailed('gcd', 2, exc) result = F.gcd(G) if not opt.polys: return result.as_expr() else: return result @public def lcm_list(seq, *gens, **args): """ Compute LCM of a list of polynomials. Examples ======== >>> from sympy import lcm_list >>> from sympy.abc import x >>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x**5 - x**4 - 2*x**3 - x**2 + x + 2 """ seq = sympify(seq) def try_non_polynomial_lcm(seq) -> Optional[Expr]: if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.to_sympy(domain.one) elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.lcm(result, number) return domain.to_sympy(result) return None result = try_non_polynomial_lcm(seq) if result is not None: return result options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) # lcm for domain Q[irrational] (purely algebraic irrational) if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq): a = seq[-1] lst = [ (a/elt).ratsimp() for elt in seq[:-1] ] if all(frc.is_rational for frc in lst): lc = 1 for frc in lst: lc = lcm(lc, frc.as_numer_denom()[1]) return a*lc except PolificationFailed as exc: result = try_non_polynomial_lcm(exc.exprs) if result is not None: return result else: raise ComputationFailed('lcm_list', len(seq), exc) if not polys: if not opt.polys: return S.One else: return Poly(1, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.lcm(poly) if not opt.polys: return result.as_expr() else: return result @public def lcm(f, g=None, *gens, **args): """ Compute LCM of ``f`` and ``g``. Examples ======== >>> from sympy import lcm >>> from sympy.abc import x >>> lcm(x**2 - 1, x**2 - 3*x + 2) x**3 - 2*x**2 - x + 2 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return lcm_list(f, *gens, **args) elif g is None: raise TypeError("lcm() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) # lcm for domain Q[irrational] (purely algebraic irrational) a, b = map(sympify, (f, g)) if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational: frc = (a/b).ratsimp() if frc.is_rational: return a*frc.as_numer_denom()[1] except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.lcm(a, b)) except NotImplementedError: raise ComputationFailed('lcm', 2, exc) result = F.lcm(G) if not opt.polys: return result.as_expr() else: return result @public def terms_gcd(f, *gens, **args): """ Remove GCD of terms from ``f``. If the ``deep`` flag is True, then the arguments of ``f`` will have terms_gcd applied to them. If a fraction is factored out of ``f`` and ``f`` is an Add, then an unevaluated Mul will be returned so that automatic simplification does not redistribute it. The hint ``clear``, when set to False, can be used to prevent such factoring when all coefficients are not fractions. Examples ======== >>> from sympy import terms_gcd, cos >>> from sympy.abc import x, y >>> terms_gcd(x**6*y**2 + x**3*y, x, y) x**3*y*(x**3*y + 1) The default action of polys routines is to expand the expression given to them. terms_gcd follows this behavior: >>> terms_gcd((3+3*x)*(x+x*y)) 3*x*(x*y + x + y + 1) If this is not desired then the hint ``expand`` can be set to False. In this case the expression will be treated as though it were comprised of one or more terms: >>> terms_gcd((3+3*x)*(x+x*y), expand=False) (3*x + 3)*(x*y + x) In order to traverse factors of a Mul or the arguments of other functions, the ``deep`` hint can be used: >>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True) 3*x*(x + 1)*(y + 1) >>> terms_gcd(cos(x + x*y), deep=True) cos(x*(y + 1)) Rationals are factored out by default: >>> terms_gcd(x + y/2) (2*x + y)/2 Only the y-term had a coefficient that was a fraction; if one does not want to factor out the 1/2 in cases like this, the flag ``clear`` can be set to False: >>> terms_gcd(x + y/2, clear=False) x + y/2 >>> terms_gcd(x*y/2 + y**2, clear=False) y*(x/2 + y) The ``clear`` flag is ignored if all coefficients are fractions: >>> terms_gcd(x/3 + y/2, clear=False) (2*x + 3*y)/6 See Also ======== sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms """ orig = sympify(f) if isinstance(f, Equality): return Equality(*(terms_gcd(s, *gens, **args) for s in [f.lhs, f.rhs])) elif isinstance(f, Relational): raise TypeError("Inequalities cannot be used with terms_gcd. Found: %s" %(f,)) if not isinstance(f, Expr) or f.is_Atom: return orig if args.get('deep', False): new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args]) args.pop('deep') args['expand'] = False return terms_gcd(new, *gens, **args) clear = args.pop('clear', True) options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: return exc.expr J, f = F.terms_gcd() if opt.domain.is_Ring: if opt.domain.is_Field: denom, f = f.clear_denoms(convert=True) coeff, f = f.primitive() if opt.domain.is_Field: coeff /= denom else: coeff = S.One term = Mul(*[x**j for x, j in zip(f.gens, J)]) if coeff == 1: coeff = S.One if term == 1: return orig if clear: return _keep_coeff(coeff, term*f.as_expr()) # base the clearing on the form of the original expression, not # the (perhaps) Mul that we have now coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul() return _keep_coeff(coeff, term*f, clear=False) @public def trunc(f, p, *gens, **args): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import trunc >>> from sympy.abc import x >>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3) -x**3 - x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('trunc', 1, exc) result = F.trunc(sympify(p)) if not opt.polys: return result.as_expr() else: return result @public def monic(f, *gens, **args): """ Divide all coefficients of ``f`` by ``LC(f)``. Examples ======== >>> from sympy import monic >>> from sympy.abc import x >>> monic(3*x**2 + 4*x + 2) x**2 + 4*x/3 + 2/3 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('monic', 1, exc) result = F.monic(auto=opt.auto) if not opt.polys: return result.as_expr() else: return result @public def content(f, *gens, **args): """ Compute GCD of coefficients of ``f``. Examples ======== >>> from sympy import content >>> from sympy.abc import x >>> content(6*x**2 + 8*x + 12) 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('content', 1, exc) return F.content() @public def primitive(f, *gens, **args): """ Compute content and the primitive form of ``f``. Examples ======== >>> from sympy.polys.polytools import primitive >>> from sympy.abc import x >>> primitive(6*x**2 + 8*x + 12) (2, 3*x**2 + 4*x + 6) >>> eq = (2 + 2*x)*x + 2 Expansion is performed by default: >>> primitive(eq) (2, x**2 + x + 1) Set ``expand`` to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction. >>> primitive(eq, expand=False) (1, x*(2*x + 2) + 2) >>> eq.as_content_primitive() (2, x*(x + 1) + 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('primitive', 1, exc) cont, result = F.primitive() if not opt.polys: return cont, result.as_expr() else: return cont, result @public def compose(f, g, *gens, **args): """ Compute functional composition ``f(g)``. Examples ======== >>> from sympy import compose >>> from sympy.abc import x >>> compose(x**2 + x, x - 1) x**2 - x """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('compose', 2, exc) result = F.compose(G) if not opt.polys: return result.as_expr() else: return result @public def decompose(f, *gens, **args): """ Compute functional decomposition of ``f``. Examples ======== >>> from sympy import decompose >>> from sympy.abc import x >>> decompose(x**4 + 2*x**3 - x - 1) [x**2 - x - 1, x**2 + x] """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('decompose', 1, exc) result = F.decompose() if not opt.polys: return [r.as_expr() for r in result] else: return result @public def sturm(f, *gens, **args): """ Compute Sturm sequence of ``f``. Examples ======== >>> from sympy import sturm >>> from sympy.abc import x >>> sturm(x**3 - 2*x**2 + x - 3) [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4] """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('sturm', 1, exc) result = F.sturm(auto=opt.auto) if not opt.polys: return [r.as_expr() for r in result] else: return result @public def gff_list(f, *gens, **args): """ Compute a list of greatest factorial factors of ``f``. Note that the input to ff() and rf() should be Poly instances to use the definitions here. Examples ======== >>> from sympy import gff_list, ff, Poly >>> from sympy.abc import x >>> f = Poly(x**5 + 2*x**4 - x**3 - 2*x**2, x) >>> gff_list(f) [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] >>> (ff(Poly(x), 1)*ff(Poly(x + 2), 4)) == f True >>> f = Poly(x**12 + 6*x**11 - 11*x**10 - 56*x**9 + 220*x**8 + 208*x**7 - \ 1401*x**6 + 1090*x**5 + 2715*x**4 - 6720*x**3 - 1092*x**2 + 5040*x, x) >>> gff_list(f) [(Poly(x**3 + 7, x, domain='ZZ'), 2), (Poly(x**2 + 5*x, x, domain='ZZ'), 3)] >>> ff(Poly(x**3 + 7, x), 2)*ff(Poly(x**2 + 5*x, x), 3) == f True """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('gff_list', 1, exc) factors = F.gff_list() if not opt.polys: return [(g.as_expr(), k) for g, k in factors] else: return factors @public def gff(f, *gens, **args): """Compute greatest factorial factorization of ``f``. """ raise NotImplementedError('symbolic falling factorial') @public def sqf_norm(f, *gens, **args): """ Compute square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import sqf_norm, sqrt >>> from sympy.abc import x >>> sqf_norm(x**2 + 1, extension=[sqrt(3)]) (1, x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('sqf_norm', 1, exc) s, g, r = F.sqf_norm() if not opt.polys: return Integer(s), g.as_expr(), r.as_expr() else: return Integer(s), g, r @public def sqf_part(f, *gens, **args): """ Compute square-free part of ``f``. Examples ======== >>> from sympy import sqf_part >>> from sympy.abc import x >>> sqf_part(x**3 - 3*x - 2) x**2 - x - 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('sqf_part', 1, exc) result = F.sqf_part() if not opt.polys: return result.as_expr() else: return result def _sorted_factors(factors, method): """Sort a list of ``(expr, exp)`` pairs. """ if method == 'sqf': def key(obj): poly, exp = obj rep = poly.rep.rep return (exp, len(rep), len(poly.gens), str(poly.domain), rep) else: def key(obj): poly, exp = obj rep = poly.rep.rep return (len(rep), len(poly.gens), exp, str(poly.domain), rep) return sorted(factors, key=key) def _factors_product(factors): """Multiply a list of ``(expr, exp)`` pairs. """ return Mul(*[f.as_expr()**k for f, k in factors]) def _symbolic_factor_list(expr, opt, method): """Helper function for :func:`_symbolic_factor`. """ coeff, factors = S.One, [] args = [i._eval_factor() if hasattr(i, '_eval_factor') else i for i in Mul.make_args(expr)] for arg in args: if arg.is_Number or (isinstance(arg, Expr) and pure_complex(arg)): coeff *= arg continue elif arg.is_Pow and arg.base != S.Exp1: base, exp = arg.args if base.is_Number and exp.is_Number: coeff *= arg continue if base.is_Number: factors.append((base, exp)) continue else: base, exp = arg, S.One try: poly, _ = _poly_from_expr(base, opt) except PolificationFailed as exc: factors.append((exc.expr, exp)) else: func = getattr(poly, method + '_list') _coeff, _factors = func() if _coeff is not S.One: if exp.is_Integer: coeff *= _coeff**exp elif _coeff.is_positive: factors.append((_coeff, exp)) else: _factors.append((_coeff, S.One)) if exp is S.One: factors.extend(_factors) elif exp.is_integer: factors.extend([(f, k*exp) for f, k in _factors]) else: other = [] for f, k in _factors: if f.as_expr().is_positive: factors.append((f, k*exp)) else: other.append((f, k)) factors.append((_factors_product(other), exp)) if method == 'sqf': factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k) for k in {i for _, i in factors}] return coeff, factors def _symbolic_factor(expr, opt, method): """Helper function for :func:`_factor`. """ if isinstance(expr, Expr): if hasattr(expr,'_eval_factor'): return expr._eval_factor() coeff, factors = _symbolic_factor_list(together(expr, fraction=opt['fraction']), opt, method) return _keep_coeff(coeff, _factors_product(factors)) elif hasattr(expr, 'args'): return expr.func(*[_symbolic_factor(arg, opt, method) for arg in expr.args]) elif hasattr(expr, '__iter__'): return expr.__class__([_symbolic_factor(arg, opt, method) for arg in expr]) else: return expr def _generic_factor_list(expr, gens, args, method): """Helper function for :func:`sqf_list` and :func:`factor_list`. """ options.allowed_flags(args, ['frac', 'polys']) opt = options.build_options(gens, args) expr = sympify(expr) if isinstance(expr, (Expr, Poly)): if isinstance(expr, Poly): numer, denom = expr, 1 else: numer, denom = together(expr).as_numer_denom() cp, fp = _symbolic_factor_list(numer, opt, method) cq, fq = _symbolic_factor_list(denom, opt, method) if fq and not opt.frac: raise PolynomialError("a polynomial expected, got %s" % expr) _opt = opt.clone(dict(expand=True)) for factors in (fp, fq): for i, (f, k) in enumerate(factors): if not f.is_Poly: f, _ = _poly_from_expr(f, _opt) factors[i] = (f, k) fp = _sorted_factors(fp, method) fq = _sorted_factors(fq, method) if not opt.polys: fp = [(f.as_expr(), k) for f, k in fp] fq = [(f.as_expr(), k) for f, k in fq] coeff = cp/cq if not opt.frac: return coeff, fp else: return coeff, fp, fq else: raise PolynomialError("a polynomial expected, got %s" % expr) def _generic_factor(expr, gens, args, method): """Helper function for :func:`sqf` and :func:`factor`. """ fraction = args.pop('fraction', True) options.allowed_flags(args, []) opt = options.build_options(gens, args) opt['fraction'] = fraction return _symbolic_factor(sympify(expr), opt, method) def to_rational_coeffs(f): """ try to transform a polynomial to have rational coefficients try to find a transformation ``x = alpha*y`` ``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with rational coefficients, ``lc`` the leading coefficient. If this fails, try ``x = y + beta`` ``f(x) = g(y)`` Returns ``None`` if ``g`` not found; ``(lc, alpha, None, g)`` in case of rescaling ``(None, None, beta, g)`` in case of translation Notes ===== Currently it transforms only polynomials without roots larger than 2. Examples ======== >>> from sympy import sqrt, Poly, simplify >>> from sympy.polys.polytools import to_rational_coeffs >>> from sympy.abc import x >>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX') >>> lc, r, _, g = to_rational_coeffs(p) >>> lc, r (7 + 5*sqrt(2), 2 - 2*sqrt(2)) >>> g Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ') >>> r1 = simplify(1/r) >>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p True """ from sympy.simplify.simplify import simplify def _try_rescale(f, f1=None): """ try rescaling ``x -> alpha*x`` to convert f to a polynomial with rational coefficients. Returns ``alpha, f``; if the rescaling is successful, ``alpha`` is the rescaling factor, and ``f`` is the rescaled polynomial; else ``alpha`` is ``None``. """ if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: return None, f n = f.degree() lc = f.LC() f1 = f1 or f1.monic() coeffs = f1.all_coeffs()[1:] coeffs = [simplify(coeffx) for coeffx in coeffs] if len(coeffs) > 1 and coeffs[-2]: rescale1_x = simplify(coeffs[-2]/coeffs[-1]) coeffs1 = [] for i in range(len(coeffs)): coeffx = simplify(coeffs[i]*rescale1_x**(i + 1)) if not coeffx.is_rational: break coeffs1.append(coeffx) else: rescale_x = simplify(1/rescale1_x) x = f.gens[0] v = [x**n] for i in range(1, n + 1): v.append(coeffs1[i - 1]*x**(n - i)) f = Add(*v) f = Poly(f) return lc, rescale_x, f return None def _try_translate(f, f1=None): """ try translating ``x -> x + alpha`` to convert f to a polynomial with rational coefficients. Returns ``alpha, f``; if the translating is successful, ``alpha`` is the translating factor, and ``f`` is the shifted polynomial; else ``alpha`` is ``None``. """ if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: return None, f n = f.degree() f1 = f1 or f1.monic() coeffs = f1.all_coeffs()[1:] c = simplify(coeffs[0]) if c.is_Add and not c.is_rational: rat, nonrat = sift(c.args, lambda z: z.is_rational is True, binary=True) alpha = -c.func(*nonrat)/n f2 = f1.shift(alpha) return alpha, f2 return None def _has_square_roots(p): """ Return True if ``f`` is a sum with square roots but no other root """ coeffs = p.coeffs() has_sq = False for y in coeffs: for x in Add.make_args(y): f = Factors(x).factors r = [wx.q for b, wx in f.items() if b.is_number and wx.is_Rational and wx.q >= 2] if not r: continue if min(r) == 2: has_sq = True if max(r) > 2: return False return has_sq if f.get_domain().is_EX and _has_square_roots(f): f1 = f.monic() r = _try_rescale(f, f1) if r: return r[0], r[1], None, r[2] else: r = _try_translate(f, f1) if r: return None, None, r[0], r[1] return None def _torational_factor_list(p, x): """ helper function to factor polynomial using to_rational_coeffs Examples ======== >>> from sympy.polys.polytools import _torational_factor_list >>> from sympy.abc import x >>> from sympy import sqrt, expand, Mul >>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) >>> factors = _torational_factor_list(p, x); factors (-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p True >>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)})) >>> factors = _torational_factor_list(p, x); factors (1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)]) >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p True """ from sympy.simplify.simplify import simplify p1 = Poly(p, x, domain='EX') n = p1.degree() res = to_rational_coeffs(p1) if not res: return None lc, r, t, g = res factors = factor_list(g.as_expr()) if lc: c = simplify(factors[0]*lc*r**n) r1 = simplify(1/r) a = [] for z in factors[1:][0]: a.append((simplify(z[0].subs({x: x*r1})), z[1])) else: c = factors[0] a = [] for z in factors[1:][0]: a.append((z[0].subs({x: x - t}), z[1])) return (c, a) @public def sqf_list(f, *gens, **args): """ Compute a list of square-free factors of ``f``. Examples ======== >>> from sympy import sqf_list >>> from sympy.abc import x >>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) (2, [(x + 1, 2), (x + 2, 3)]) """ return _generic_factor_list(f, gens, args, method='sqf') @public def sqf(f, *gens, **args): """ Compute square-free factorization of ``f``. Examples ======== >>> from sympy import sqf >>> from sympy.abc import x >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) 2*(x + 1)**2*(x + 2)**3 """ return _generic_factor(f, gens, args, method='sqf') @public def factor_list(f, *gens, **args): """ Compute a list of irreducible factors of ``f``. Examples ======== >>> from sympy import factor_list >>> from sympy.abc import x, y >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) (2, [(x + y, 1), (x**2 + 1, 2)]) """ return _generic_factor_list(f, gens, args, method='factor') @public def factor(f, *gens, deep=False, **args): """ Compute the factorization of expression, ``f``, into irreducibles. (To factor an integer into primes, use ``factorint``.) There two modes implemented: symbolic and formal. If ``f`` is not an instance of :class:`Poly` and generators are not specified, then the former mode is used. Otherwise, the formal mode is used. In symbolic mode, :func:`factor` will traverse the expression tree and factor its components without any prior expansion, unless an instance of :class:`~.Add` is encountered (in this case formal factorization is used). This way :func:`factor` can handle large or symbolic exponents. By default, the factorization is computed over the rationals. To factor over other domain, e.g. an algebraic or finite field, use appropriate options: ``extension``, ``modulus`` or ``domain``. Examples ======== >>> from sympy import factor, sqrt, exp >>> from sympy.abc import x, y >>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) 2*(x + y)*(x**2 + 1)**2 >>> factor(x**2 + 1) x**2 + 1 >>> factor(x**2 + 1, modulus=2) (x + 1)**2 >>> factor(x**2 + 1, gaussian=True) (x - I)*(x + I) >>> factor(x**2 - 2, extension=sqrt(2)) (x - sqrt(2))*(x + sqrt(2)) >>> factor((x**2 - 1)/(x**2 + 4*x + 4)) (x - 1)*(x + 1)/(x + 2)**2 >>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1)) (x + 2)**20000000*(x**2 + 1) By default, factor deals with an expression as a whole: >>> eq = 2**(x**2 + 2*x + 1) >>> factor(eq) 2**(x**2 + 2*x + 1) If the ``deep`` flag is True then subexpressions will be factored: >>> factor(eq, deep=True) 2**((x + 1)**2) If the ``fraction`` flag is False then rational expressions will not be combined. By default it is True. >>> factor(5*x + 3*exp(2 - 7*x), deep=True) (5*x*exp(7*x) + 3*exp(2))*exp(-7*x) >>> factor(5*x + 3*exp(2 - 7*x), deep=True, fraction=False) 5*x + 3*exp(2)*exp(-7*x) See Also ======== sympy.ntheory.factor_.factorint """ f = sympify(f) if deep: def _try_factor(expr): """ Factor, but avoid changing the expression when unable to. """ fac = factor(expr, *gens, **args) if fac.is_Mul or fac.is_Pow: return fac return expr f = bottom_up(f, _try_factor) # clean up any subexpressions that may have been expanded # while factoring out a larger expression partials = {} muladd = f.atoms(Mul, Add) for p in muladd: fac = factor(p, *gens, **args) if (fac.is_Mul or fac.is_Pow) and fac != p: partials[p] = fac return f.xreplace(partials) try: return _generic_factor(f, gens, args, method='factor') except PolynomialError as msg: if not f.is_commutative: return factor_nc(f) else: raise PolynomialError(msg) @public def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. Examples ======== >>> from sympy import intervals >>> from sympy.abc import x >>> intervals(x**2 - 3) [((-2, -1), 1), ((1, 2), 1)] >>> intervals(x**2 - 3, eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if not hasattr(F, '__iter__'): try: F = Poly(F) except GeneratorsNeeded: return [] return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: polys, opt = parallel_poly_from_expr(F, domain='QQ') if len(opt.gens) > 1: raise MultivariatePolynomialError for i, poly in enumerate(polys): polys[i] = poly.rep.rep if eps is not None: eps = opt.domain.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = opt.domain.convert(inf) if sup is not None: sup = opt.domain.convert(sup) intervals = dup_isolate_real_roots_list(polys, opt.domain, eps=eps, inf=inf, sup=sup, strict=strict, fast=fast) result = [] for (s, t), indices in intervals: s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t) result.append(((s, t), indices)) return result @public def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import refine_root >>> from sympy.abc import x >>> refine_root(x**2 - 3, 1, 2, eps=1e-2) (19/11, 26/15) """ try: F = Poly(f) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError( "Cannot refine a root of %s, not a polynomial" % f) return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf) @public def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. If one of ``inf`` or ``sup`` is complex, it will return the number of roots in the complex rectangle with corners at ``inf`` and ``sup``. Examples ======== >>> from sympy import count_roots, I >>> from sympy.abc import x >>> count_roots(x**4 - 4, -3, 3) 2 >>> count_roots(x**4 - 4, 0, 1 + 3*I) 1 """ try: F = Poly(f, greedy=False) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError("Cannot count roots of %s, not a polynomial" % f) return F.count_roots(inf=inf, sup=sup) @public def real_roots(f, multiple=True): """ Return a list of real roots with multiplicities of ``f``. Examples ======== >>> from sympy import real_roots >>> from sympy.abc import x >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4) [-1/2, 2, 2] """ try: F = Poly(f, greedy=False) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError( "Cannot compute real roots of %s, not a polynomial" % f) return F.real_roots(multiple=multiple) @public def nroots(f, n=15, maxsteps=50, cleanup=True): """ Compute numerical approximations of roots of ``f``. Examples ======== >>> from sympy import nroots >>> from sympy.abc import x >>> nroots(x**2 - 3, n=15) [-1.73205080756888, 1.73205080756888] >>> nroots(x**2 - 3, n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ try: F = Poly(f, greedy=False) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError( "Cannot compute numerical roots of %s, not a polynomial" % f) return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup) @public def ground_roots(f, *gens, **args): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import ground_roots >>> from sympy.abc import x >>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2) {0: 2, 1: 2} """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except PolificationFailed as exc: raise ComputationFailed('ground_roots', 1, exc) return F.ground_roots() @public def nth_power_roots_poly(f, n, *gens, **args): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import nth_power_roots_poly, factor, roots >>> from sympy.abc import x >>> f = x**4 - x**2 + 1 >>> g = factor(nth_power_roots_poly(f, 2)) >>> g (x**2 - x + 1)**2 >>> R_f = [ (r**2).expand() for r in roots(f) ] >>> R_g = roots(g).keys() >>> set(R_f) == set(R_g) True """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except PolificationFailed as exc: raise ComputationFailed('nth_power_roots_poly', 1, exc) result = F.nth_power_roots_poly(n) if not opt.polys: return result.as_expr() else: return result @public def cancel(f, *gens, _signsimp=True, **args): """ Cancel common factors in a rational function ``f``. Examples ======== >>> from sympy import cancel, sqrt, Symbol, together >>> from sympy.abc import x >>> A = Symbol('A', commutative=False) >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) (2*x + 2)/(x - 1) >>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A)) sqrt(6)/2 Note: due to automatic distribution of Rationals, a sum divided by an integer will appear as a sum. To recover a rational form use `together` on the result: >>> cancel(x/2 + 1) x/2 + 1 >>> together(_) (x + 2)/2 """ from sympy.simplify.simplify import signsimp from sympy.polys.rings import sring options.allowed_flags(args, ['polys']) f = sympify(f) if _signsimp: f = signsimp(f) opt = {} if 'polys' in args: opt['polys'] = args['polys'] if not isinstance(f, (tuple, Tuple)): if f.is_Number or isinstance(f, Relational) or not isinstance(f, Expr): return f f = factor_terms(f, radical=True) p, q = f.as_numer_denom() elif len(f) == 2: p, q = f if isinstance(p, Poly) and isinstance(q, Poly): opt['gens'] = p.gens opt['domain'] = p.domain opt['polys'] = opt.get('polys', True) p, q = p.as_expr(), q.as_expr() elif isinstance(f, Tuple): return factor_terms(f) else: raise ValueError('unexpected argument: %s' % f) from sympy.functions.elementary.piecewise import Piecewise try: if f.has(Piecewise): raise PolynomialError() R, (F, G) = sring((p, q), *gens, **args) if not R.ngens: if not isinstance(f, (tuple, Tuple)): return f.expand() else: return S.One, p, q except PolynomialError as msg: if f.is_commutative and not f.has(Piecewise): raise PolynomialError(msg) # Handling of noncommutative and/or piecewise expressions if f.is_Add or f.is_Mul: c, nc = sift(f.args, lambda x: x.is_commutative is True and not x.has(Piecewise), binary=True) nc = [cancel(i) for i in nc] return f.func(cancel(f.func(*c)), *nc) else: reps = [] pot = preorder_traversal(f) next(pot) for e in pot: # XXX: This should really skip anything that's not Expr. if isinstance(e, (tuple, Tuple, BooleanAtom)): continue try: reps.append((e, cancel(e))) pot.skip() # this was handled successfully except NotImplementedError: pass return f.xreplace(dict(reps)) c, (P, Q) = 1, F.cancel(G) if opt.get('polys', False) and 'gens' not in opt: opt['gens'] = R.symbols if not isinstance(f, (tuple, Tuple)): return c*(P.as_expr()/Q.as_expr()) else: P, Q = P.as_expr(), Q.as_expr() if not opt.get('polys', False): return c, P, Q else: return c, Poly(P, *gens, **opt), Poly(Q, *gens, **opt) @public def reduced(f, G, *gens, **args): """ Reduces a polynomial ``f`` modulo a set of polynomials ``G``. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*g_1 + ... + q_n*g_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import reduced >>> from sympy.abc import x, y >>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y]) ([2*x, 1], x**2 + y**2 + y) """ options.allowed_flags(args, ['polys', 'auto']) try: polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('reduced', 0, exc) domain = opt.domain retract = False if opt.auto and domain.is_Ring and not domain.is_Field: opt = opt.clone(dict(domain=domain.get_field())) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [Poly._from_dict(dict(q), opt) for q in Q] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [q.to_ring() for q in Q], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [q.as_expr() for q in Q], r.as_expr() else: return Q, r @public def groebner(F, *gens, **args): """ Computes the reduced Groebner basis for a set of polynomials. Use the ``order`` argument to set the monomial ordering that will be used to compute the basis. Allowed orders are ``lex``, ``grlex`` and ``grevlex``. If no order is specified, it defaults to ``lex``. For more information on Groebner bases, see the references and the docstring of :func:`~.solve_poly_system`. Examples ======== Example taken from [1]. >>> from sympy import groebner >>> from sympy.abc import x, y >>> F = [x*y - 2*y, 2*y**2 - x**2] >>> groebner(F, x, y, order='lex') GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, order='grlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grlex') >>> groebner(F, x, y, order='grevlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grevlex') By default, an improved implementation of the Buchberger algorithm is used. Optionally, an implementation of the F5B algorithm can be used. The algorithm can be set using the ``method`` flag or with the :func:`sympy.polys.polyconfig.setup` function. >>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)] >>> groebner(F, x, y, method='buchberger') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, method='f5b') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') References ========== 1. [Buchberger01]_ 2. [Cox97]_ """ return GroebnerBasis(F, *gens, **args) @public def is_zero_dimensional(F, *gens, **args): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ return GroebnerBasis(F, *gens, **args).is_zero_dimensional @public class GroebnerBasis(Basic): """Represents a reduced Groebner basis. """ def __new__(cls, F, *gens, **args): """Compute a reduced Groebner basis for a system of polynomials. """ options.allowed_flags(args, ['polys', 'method']) try: polys, opt = parallel_poly_from_expr(F, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('groebner', len(F), exc) from sympy.polys.rings import PolyRing ring = PolyRing(opt.gens, opt.domain, opt.order) polys = [ring.from_dict(poly.rep.to_dict()) for poly in polys if poly] G = _groebner(polys, ring, method=opt.method) G = [Poly._from_dict(g, opt) for g in G] return cls._new(G, opt) @classmethod def _new(cls, basis, options): obj = Basic.__new__(cls) obj._basis = tuple(basis) obj._options = options return obj @property def args(self): basis = (p.as_expr() for p in self._basis) return (Tuple(*basis), Tuple(*self._options.gens)) @property def exprs(self): return [poly.as_expr() for poly in self._basis] @property def polys(self): return list(self._basis) @property def gens(self): return self._options.gens @property def domain(self): return self._options.domain @property def order(self): return self._options.order def __len__(self): return len(self._basis) def __iter__(self): if self._options.polys: return iter(self.polys) else: return iter(self.exprs) def __getitem__(self, item): if self._options.polys: basis = self.polys else: basis = self.exprs return basis[item] def __hash__(self): return hash((self._basis, tuple(self._options.items()))) def __eq__(self, other): if isinstance(other, self.__class__): return self._basis == other._basis and self._options == other._options elif iterable(other): return self.polys == list(other) or self.exprs == list(other) else: return False def __ne__(self, other): return not self == other @property def is_zero_dimensional(self): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ def single_var(monomial): return sum(map(bool, monomial)) == 1 exponents = Monomial([0]*len(self.gens)) order = self._options.order for poly in self.polys: monomial = poly.LM(order=order) if single_var(monomial): exponents *= monomial # If any element of the exponents vector is zero, then there's # a variable for which there's no degree bound and the ideal # generated by this Groebner basis isn't zero-dimensional. return all(exponents) def fglm(self, order): """ Convert a Groebner basis from one ordering to another. The FGLM algorithm converts reduced Groebner bases of zero-dimensional ideals from one ordering to another. This method is often used when it is infeasible to compute a Groebner basis with respect to a particular ordering directly. Examples ======== >>> from sympy.abc import x, y >>> from sympy import groebner >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] >>> G = groebner(F, x, y, order='grlex') >>> list(G.fglm('lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] >>> list(groebner(F, x, y, order='lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] References ========== .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient Computation of Zero-dimensional Groebner Bases by Change of Ordering """ opt = self._options src_order = opt.order dst_order = monomial_key(order) if src_order == dst_order: return self if not self.is_zero_dimensional: raise NotImplementedError("Cannot convert Groebner bases of ideals with positive dimension") polys = list(self._basis) domain = opt.domain opt = opt.clone(dict( domain=domain.get_field(), order=dst_order, )) from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, src_order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) G = matrix_fglm(polys, _ring, dst_order) G = [Poly._from_dict(dict(g), opt) for g in G] if not domain.is_Field: G = [g.clear_denoms(convert=True)[1] for g in G] opt.domain = domain return self._new(G, opt) def reduce(self, expr, auto=True): """ Reduces a polynomial modulo a Groebner basis. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import groebner, expand >>> from sympy.abc import x, y >>> f = 2*x**4 - x**2 + y**3 + y**2 >>> G = groebner([x**3 - x, y**3 - y]) >>> G.reduce(f) ([2*x, 1], x**2 + y**2 + y) >>> Q, r = _ >>> expand(sum(q*g for q, g in zip(Q, G)) + r) 2*x**4 - x**2 + y**3 + y**2 >>> _ == f True """ poly = Poly._from_expr(expr, self._options) polys = [poly] + list(self._basis) opt = self._options domain = opt.domain retract = False if auto and domain.is_Ring and not domain.is_Field: opt = opt.clone(dict(domain=domain.get_field())) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [Poly._from_dict(dict(q), opt) for q in Q] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [q.to_ring() for q in Q], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [q.as_expr() for q in Q], r.as_expr() else: return Q, r def contains(self, poly): """ Check if ``poly`` belongs the ideal generated by ``self``. Examples ======== >>> from sympy import groebner >>> from sympy.abc import x, y >>> f = 2*x**3 + y**3 + 3*y >>> G = groebner([x**2 + y**2 - 1, x*y - 2]) >>> G.contains(f) True >>> G.contains(f + 1) False """ return self.reduce(poly)[1] == 0 @public def poly(expr, *gens, **args): """ Efficiently transform an expression into a polynomial. Examples ======== >>> from sympy import poly >>> from sympy.abc import x >>> poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') """ options.allowed_flags(args, []) def _poly(expr, opt): terms, poly_terms = [], [] for term in Add.make_args(expr): factors, poly_factors = [], [] for factor in Mul.make_args(term): if factor.is_Add: poly_factors.append(_poly(factor, opt)) elif factor.is_Pow and factor.base.is_Add and \ factor.exp.is_Integer and factor.exp >= 0: poly_factors.append( _poly(factor.base, opt).pow(factor.exp)) else: factors.append(factor) if not poly_factors: terms.append(term) else: product = poly_factors[0] for factor in poly_factors[1:]: product = product.mul(factor) if factors: factor = Mul(*factors) if factor.is_Number: product = product.mul(factor) else: product = product.mul(Poly._from_expr(factor, opt)) poly_terms.append(product) if not poly_terms: result = Poly._from_expr(expr, opt) else: result = poly_terms[0] for term in poly_terms[1:]: result = result.add(term) if terms: term = Add(*terms) if term.is_Number: result = result.add(term) else: result = result.add(Poly._from_expr(term, opt)) return result.reorder(*opt.get('gens', ()), **args) expr = sympify(expr) if expr.is_Poly: return Poly(expr, *gens, **args) if 'expand' not in args: args['expand'] = False opt = options.build_options(gens, args) return _poly(expr, opt)
12c039fe831e4a48d2c0bb476287ffcc73e330042b299b5fba066447bd3dc73b
"""Functions for generating interesting polynomials, e.g. for benchmarking. """ from sympy.core import Add, Mul, Symbol, sympify, Dummy, symbols from sympy.core.containers import Tuple from sympy.core.singleton import S from sympy.ntheory import nextprime from sympy.polys.densearith import ( dmp_add_term, dmp_neg, dmp_mul, dmp_sqr ) from sympy.polys.densebasic import ( dmp_zero, dmp_one, dmp_ground, dup_from_raw_dict, dmp_raise, dup_random ) from sympy.polys.domains import ZZ from sympy.polys.factortools import dup_zz_cyclotomic_poly from sympy.polys.polyclasses import DMP from sympy.polys.polytools import Poly, PurePoly from sympy.polys.polyutils import _analyze_gens from sympy.utilities import subsets, public, filldedent @public def swinnerton_dyer_poly(n, x=None, polys=False): """Generates n-th Swinnerton-Dyer polynomial in `x`. Parameters ---------- n : int `n` decides the order of polynomial x : optional polys : bool, optional ``polys=True`` returns an expression, otherwise (default) returns an expression. """ if n <= 0: raise ValueError( "Cannot generate Swinnerton-Dyer polynomial of order %s" % n) if x is not None: sympify(x) else: x = Dummy('x') if n > 3: from sympy.functions.elementary.miscellaneous import sqrt from .numberfields import minimal_polynomial p = 2 a = [sqrt(2)] for i in range(2, n + 1): p = nextprime(p) a.append(sqrt(p)) return minimal_polynomial(Add(*a), x, polys=polys) if n == 1: ex = x**2 - 2 elif n == 2: ex = x**4 - 10*x**2 + 1 elif n == 3: ex = x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576 return PurePoly(ex, x) if polys else ex @public def cyclotomic_poly(n, x=None, polys=False): """Generates cyclotomic polynomial of order `n` in `x`. Parameters ---------- n : int `n` decides the order of polynomial x : optional polys : bool, optional ``polys=True`` returns an expression, otherwise (default) returns an expression. """ if n <= 0: raise ValueError( "Cannot generate cyclotomic polynomial of order %s" % n) poly = DMP(dup_zz_cyclotomic_poly(int(n), ZZ), ZZ) if x is not None: poly = Poly.new(poly, x) else: poly = PurePoly.new(poly, Dummy('x')) return poly if polys else poly.as_expr() @public def symmetric_poly(n, *gens, **args): """Generates symmetric polynomial of order `n`. Returns a Poly object when ``polys=True``, otherwise (default) returns an expression. """ # TODO: use an explicit keyword argument gens = _analyze_gens(gens) if n < 0 or n > len(gens) or not gens: raise ValueError("Cannot generate symmetric polynomial of order %s for %s" % (n, gens)) elif not n: poly = S.One else: poly = Add(*[Mul(*s) for s in subsets(gens, int(n))]) if not args.get('polys', False): return poly else: return Poly(poly, *gens) @public def random_poly(x, n, inf, sup, domain=ZZ, polys=False): """Generates a polynomial of degree ``n`` with coefficients in ``[inf, sup]``. Parameters ---------- x `x` is the independent term of polynomial n : int `n` decides the order of polynomial inf Lower limit of range in which coefficients lie sup Upper limit of range in which coefficients lie domain : optional Decides what ring the coefficients are supposed to belong. Default is set to Integers. polys : bool, optional ``polys=True`` returns an expression, otherwise (default) returns an expression. """ poly = Poly(dup_random(n, inf, sup, domain), x, domain=domain) return poly if polys else poly.as_expr() @public def interpolating_poly(n, x, X='x', Y='y'): """Construct Lagrange interpolating polynomial for ``n`` data points. If a sequence of values are given for ``X`` and ``Y`` then the first ``n`` values will be used. """ ok = getattr(x, 'free_symbols', None) if isinstance(X, str): X = symbols("%s:%s" % (X, n)) elif ok and ok & Tuple(*X).free_symbols: ok = False if isinstance(Y, str): Y = symbols("%s:%s" % (Y, n)) elif ok and ok & Tuple(*Y).free_symbols: ok = False if not ok: raise ValueError(filldedent(''' Expecting symbol for x that does not appear in X or Y. Use `interpolate(list(zip(X, Y)), x)` instead.''')) coeffs = [] numert = Mul(*[x - X[i] for i in range(n)]) for i in range(n): numer = numert/(x - X[i]) denom = Mul(*[(X[i] - X[j]) for j in range(n) if i != j]) coeffs.append(numer/denom) return Add(*[coeff*y for coeff, y in zip(coeffs, Y)]) def fateman_poly_F_1(n): """Fateman's GCD benchmark: trivial GCD """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0, y_1 = Y[0], Y[1] u = y_0 + Add(*[y for y in Y[1:]]) v = y_0**2 + Add(*[y**2 for y in Y[1:]]) F = ((u + 1)*(u + 2)).as_poly(*Y) G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 - 1)).as_poly(*Y) H = Poly(1, *Y) return F, G, H def dmp_fateman_poly_F_1(n, K): """Fateman's GCD benchmark: trivial GCD """ u = [K(1), K(0)] for i in range(n): u = [dmp_one(i, K), u] v = [K(1), K(0), K(0)] for i in range(0, n): v = [dmp_one(i, K), dmp_zero(i), v] m = n - 1 U = dmp_add_term(u, dmp_ground(K(1), m), 0, n, K) V = dmp_add_term(u, dmp_ground(K(2), m), 0, n, K) f = [[-K(3), K(0)], [], [K(1), K(0), -K(1)]] W = dmp_add_term(v, dmp_ground(K(1), m), 0, n, K) Y = dmp_raise(f, m, 1, K) F = dmp_mul(U, V, n, K) G = dmp_mul(W, Y, n, K) H = dmp_one(n, K) return F, G, H def fateman_poly_F_2(n): """Fateman's GCD benchmark: linearly dense quartic inputs """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0 = Y[0] u = Add(*[y for y in Y[1:]]) H = Poly((y_0 + u + 1)**2, *Y) F = Poly((y_0 - u - 2)**2, *Y) G = Poly((y_0 + u + 2)**2, *Y) return H*F, H*G, H def dmp_fateman_poly_F_2(n, K): """Fateman's GCD benchmark: linearly dense quartic inputs """ u = [K(1), K(0)] for i in range(n - 1): u = [dmp_one(i, K), u] m = n - 1 v = dmp_add_term(u, dmp_ground(K(2), m - 1), 0, n, K) f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K) g = dmp_sqr([dmp_one(m, K), v], n, K) v = dmp_add_term(u, dmp_one(m - 1, K), 0, n, K) h = dmp_sqr([dmp_one(m, K), v], n, K) return dmp_mul(f, h, n, K), dmp_mul(g, h, n, K), h def fateman_poly_F_3(n): """Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0 = Y[0] u = Add(*[y**(n + 1) for y in Y[1:]]) H = Poly((y_0**(n + 1) + u + 1)**2, *Y) F = Poly((y_0**(n + 1) - u - 2)**2, *Y) G = Poly((y_0**(n + 1) + u + 2)**2, *Y) return H*F, H*G, H def dmp_fateman_poly_F_3(n, K): """Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ u = dup_from_raw_dict({n + 1: K.one}, K) for i in range(0, n - 1): u = dmp_add_term([u], dmp_one(i, K), n + 1, i + 1, K) v = dmp_add_term(u, dmp_ground(K(2), n - 2), 0, n, K) f = dmp_sqr( dmp_add_term([dmp_neg(v, n - 1, K)], dmp_one(n - 1, K), n + 1, n, K), n, K) g = dmp_sqr(dmp_add_term([v], dmp_one(n - 1, K), n + 1, n, K), n, K) v = dmp_add_term(u, dmp_one(n - 2, K), 0, n - 1, K) h = dmp_sqr(dmp_add_term([v], dmp_one(n - 1, K), n + 1, n, K), n, K) return dmp_mul(f, h, n, K), dmp_mul(g, h, n, K), h # A few useful polynomials from Wang's paper ('78). from sympy.polys.rings import ring def _f_0(): R, x, y, z = ring("x,y,z", ZZ) return x**2*y*z**2 + 2*x**2*y*z + 3*x**2*y + 2*x**2 + 3*x + 4*y**2*z**2 + 5*y**2*z + 6*y**2 + y*z**2 + 2*y*z + y + 1 def _f_1(): R, x, y, z = ring("x,y,z", ZZ) return x**3*y*z + x**2*y**2*z**2 + x**2*y**2 + 20*x**2*y*z + 30*x**2*y + x**2*z**2 + 10*x**2*z + x*y**3*z + 30*x*y**2*z + 20*x*y**2 + x*y*z**3 + 10*x*y*z**2 + x*y*z + 610*x*y + 20*x*z**2 + 230*x*z + 300*x + y**2*z**2 + 10*y**2*z + 30*y*z**2 + 320*y*z + 200*y + 600*z + 6000 def _f_2(): R, x, y, z = ring("x,y,z", ZZ) return x**5*y**3 + x**5*y**2*z + x**5*y*z**2 + x**5*z**3 + x**3*y**2 + x**3*y*z + 90*x**3*y + 90*x**3*z + x**2*y**2*z - 11*x**2*y**2 + x**2*z**3 - 11*x**2*z**2 + y*z - 11*y + 90*z - 990 def _f_3(): R, x, y, z = ring("x,y,z", ZZ) return x**5*y**2 + x**4*z**4 + x**4 + x**3*y**3*z + x**3*z + x**2*y**4 + x**2*y**3*z**3 + x**2*y*z**5 + x**2*y*z + x*y**2*z**4 + x*y**2 + x*y*z**7 + x*y*z**3 + x*y*z**2 + y**2*z + y*z**4 def _f_4(): R, x, y, z = ring("x,y,z", ZZ) return -x**9*y**8*z - x**8*y**5*z**3 - x**7*y**12*z**2 - 5*x**7*y**8 - x**6*y**9*z**4 + x**6*y**7*z**3 + 3*x**6*y**7*z - 5*x**6*y**5*z**2 - x**6*y**4*z**3 + x**5*y**4*z**5 + 3*x**5*y**4*z**3 - x**5*y*z**5 + x**4*y**11*z**4 + 3*x**4*y**11*z**2 - x**4*y**8*z**4 + 5*x**4*y**7*z**2 + 15*x**4*y**7 - 5*x**4*y**4*z**2 + x**3*y**8*z**6 + 3*x**3*y**8*z**4 - x**3*y**5*z**6 + 5*x**3*y**4*z**4 + 15*x**3*y**4*z**2 + x**3*y**3*z**5 + 3*x**3*y**3*z**3 - 5*x**3*y*z**4 + x**2*z**7 + 3*x**2*z**5 + x*y**7*z**6 + 3*x*y**7*z**4 + 5*x*y**3*z**4 + 15*x*y**3*z**2 + y**4*z**8 + 3*y**4*z**6 + 5*z**6 + 15*z**4 def _f_5(): R, x, y, z = ring("x,y,z", ZZ) return -x**3 - 3*x**2*y + 3*x**2*z - 3*x*y**2 + 6*x*y*z - 3*x*z**2 - y**3 + 3*y**2*z - 3*y*z**2 + z**3 def _f_6(): R, x, y, z, t = ring("x,y,z,t", ZZ) return 2115*x**4*y + 45*x**3*z**3*t**2 - 45*x**3*t**2 - 423*x*y**4 - 47*x*y**3 + 141*x*y*z**3 + 94*x*y*z*t - 9*y**3*z**3*t**2 + 9*y**3*t**2 - y**2*z**3*t**2 + y**2*t**2 + 3*z**6*t**2 + 2*z**4*t**3 - 3*z**3*t**2 - 2*z*t**3 def _w_1(): R, x, y, z = ring("x,y,z", ZZ) return 4*x**6*y**4*z**2 + 4*x**6*y**3*z**3 - 4*x**6*y**2*z**4 - 4*x**6*y*z**5 + x**5*y**4*z**3 + 12*x**5*y**3*z - x**5*y**2*z**5 + 12*x**5*y**2*z**2 - 12*x**5*y*z**3 - 12*x**5*z**4 + 8*x**4*y**4 + 6*x**4*y**3*z**2 + 8*x**4*y**3*z - 4*x**4*y**2*z**4 + 4*x**4*y**2*z**3 - 8*x**4*y**2*z**2 - 4*x**4*y*z**5 - 2*x**4*y*z**4 - 8*x**4*y*z**3 + 2*x**3*y**4*z + x**3*y**3*z**3 - x**3*y**2*z**5 - 2*x**3*y**2*z**3 + 9*x**3*y**2*z - 12*x**3*y*z**3 + 12*x**3*y*z**2 - 12*x**3*z**4 + 3*x**3*z**3 + 6*x**2*y**3 - 6*x**2*y**2*z**2 + 8*x**2*y**2*z - 2*x**2*y*z**4 - 8*x**2*y*z**3 + 2*x**2*y*z**2 + 2*x*y**3*z - 2*x*y**2*z**3 - 3*x*y*z + 3*x*z**3 - 2*y**2 + 2*y*z**2 def _w_2(): R, x, y = ring("x,y", ZZ) return 24*x**8*y**3 + 48*x**8*y**2 + 24*x**7*y**5 - 72*x**7*y**2 + 25*x**6*y**4 + 2*x**6*y**3 + 4*x**6*y + 8*x**6 + x**5*y**6 + x**5*y**3 - 12*x**5 + x**4*y**5 - x**4*y**4 - 2*x**4*y**3 + 292*x**4*y**2 - x**3*y**6 + 3*x**3*y**3 - x**2*y**5 + 12*x**2*y**3 + 48*x**2 - 12*y**3 def f_polys(): return _f_0(), _f_1(), _f_2(), _f_3(), _f_4(), _f_5(), _f_6() def w_polys(): return _w_1(), _w_2()
bf04769fa0cd2af531f8abb4007afd9fad34fa31eb5a9bda51bf265a3dd470a0
"""Algorithms for computing symbolic roots of polynomials. """ import math from functools import reduce from sympy.core import S, I, pi from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.logic import fuzzy_not from sympy.core.mul import expand_2arg, Mul from sympy.core.numbers import Rational, igcd, comp from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol, symbols from sympy.core.sympify import sympify from sympy.functions import exp, im, cos, acos, Piecewise from sympy.functions.elementary.miscellaneous import root, sqrt from sympy.ntheory import divisors, isprime, nextprime from sympy.polys.domains import EX from sympy.polys.polyerrors import (PolynomialError, GeneratorsNeeded, DomainError) from sympy.polys.polyquinticconst import PolyQuintic from sympy.polys.polytools import Poly, cancel, factor, gcd_list, discriminant from sympy.polys.rationaltools import together from sympy.polys.specialpolys import cyclotomic_poly from sympy.utilities import public def roots_linear(f): """Returns a list of roots of a linear polynomial.""" r = -f.nth(0)/f.nth(1) dom = f.get_domain() if not dom.is_Numerical: if dom.is_Composite: r = factor(r) else: from sympy.simplify.simplify import simplify r = simplify(r) return [r] def roots_quadratic(f): """Returns a list of roots of a quadratic polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise the ordering will not be sorted (but will be canonical). """ a, b, c = f.all_coeffs() dom = f.get_domain() def _sqrt(d): # remove squares from square root since both will be represented # in the results; a similar thing is happening in roots() but # must be duplicated here because not all quadratics are binomials co = [] other = [] for di in Mul.make_args(d): if di.is_Pow and di.exp.is_Integer and di.exp % 2 == 0: co.append(Pow(di.base, di.exp//2)) else: other.append(di) if co: d = Mul(*other) co = Mul(*co) return co*sqrt(d) return sqrt(d) def _simplify(expr): if dom.is_Composite: return factor(expr) else: from sympy.simplify.simplify import simplify return simplify(expr) if c is S.Zero: r0, r1 = S.Zero, -b/a if not dom.is_Numerical: r1 = _simplify(r1) elif r1.is_negative: r0, r1 = r1, r0 elif b is S.Zero: r = -c/a if not dom.is_Numerical: r = _simplify(r) R = _sqrt(r) r0 = -R r1 = R else: d = b**2 - 4*a*c A = 2*a B = -b/A if not dom.is_Numerical: d = _simplify(d) B = _simplify(B) D = factor_terms(_sqrt(d)/A) r0 = B - D r1 = B + D if a.is_negative: r0, r1 = r1, r0 elif not dom.is_Numerical: r0, r1 = [expand_2arg(i) for i in (r0, r1)] return [r0, r1] def roots_cubic(f, trig=False): """Returns a list of roots of a cubic polynomial. References ========== [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots, (accessed November 17, 2014). """ if trig: a, b, c, d = f.all_coeffs() p = (3*a*c - b**2)/(3*a**2) q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 if (D > 0) == True: rv = [] for k in range(3): rv.append(2*sqrt(-p/3)*cos(acos(q/p*sqrt(-3/p)*Rational(3, 2))/3 - k*pi*Rational(2, 3))) return [i - b/3/a for i in rv] # a*x**3 + b*x**2 + c*x + d -> x**3 + a*x**2 + b*x + c _, a, b, c = f.monic().all_coeffs() if c is S.Zero: x1, x2 = roots([1, a, b], multiple=True) return [x1, S.Zero, x2] # x**3 + a*x**2 + b*x + c -> u**3 + p*u + q p = b - a**2/3 q = c - a*b/3 + 2*a**3/27 pon3 = p/3 aon3 = a/3 u1 = None if p is S.Zero: if q is S.Zero: return [-aon3]*3 u1 = -root(q, 3) if q.is_positive else root(-q, 3) elif q is S.Zero: y1, y2 = roots([1, 0, p], multiple=True) return [tmp - aon3 for tmp in [y1, S.Zero, y2]] elif q.is_real and q.is_negative: u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) coeff = I*sqrt(3)/2 if u1 is None: u1 = S.One u2 = Rational(-1, 2) + coeff u3 = Rational(-1, 2) - coeff b, c, d = a, b, c # a, b, c, d = S.One, a, b, c D0 = b**2 - 3*c # b**2 - 3*a*c D1 = 2*b**3 - 9*b*c + 27*d # 2*b**3 - 9*a*b*c + 27*a**2*d C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3) return [-(b + uk*C + D0/C/uk)/3 for uk in [u1, u2, u3]] # -(b + uk*C + D0/C/uk)/3/a u2 = u1*(Rational(-1, 2) + coeff) u3 = u1*(Rational(-1, 2) - coeff) if p is S.Zero: return [u1 - aon3, u2 - aon3, u3 - aon3] soln = [ -u1 + pon3/u1 - aon3, -u2 + pon3/u2 - aon3, -u3 + pon3/u3 - aon3 ] return soln def _roots_quartic_euler(p, q, r, a): """ Descartes-Euler solution of the quartic equation Parameters ========== p, q, r: coefficients of ``x**4 + p*x**2 + q*x + r`` a: shift of the roots Notes ===== This is a helper function for ``roots_quartic``. Look for solutions of the form :: ``x1 = sqrt(R) - sqrt(A + B*sqrt(R))`` ``x2 = -sqrt(R) - sqrt(A - B*sqrt(R))`` ``x3 = -sqrt(R) + sqrt(A - B*sqrt(R))`` ``x4 = sqrt(R) + sqrt(A + B*sqrt(R))`` To satisfy the quartic equation one must have ``p = -2*(R + A); q = -4*B*R; r = (R - A)**2 - B**2*R`` so that ``R`` must satisfy the Descartes-Euler resolvent equation ``64*R**3 + 32*p*R**2 + (4*p**2 - 16*r)*R - q**2 = 0`` If the resolvent does not have a rational solution, return None; in that case it is likely that the Ferrari method gives a simpler solution. Examples ======== >>> from sympy import S >>> from sympy.polys.polyroots import _roots_quartic_euler >>> p, q, r = -S(64)/5, -S(512)/125, -S(1024)/3125 >>> _roots_quartic_euler(p, q, r, S(0))[0] -sqrt(32*sqrt(5)/125 + 16/5) + 4*sqrt(5)/5 """ # solve the resolvent equation x = Dummy('x') eq = 64*x**3 + 32*p*x**2 + (4*p**2 - 16*r)*x - q**2 xsols = list(roots(Poly(eq, x), cubics=False).keys()) xsols = [sol for sol in xsols if sol.is_rational and sol.is_nonzero] if not xsols: return None R = max(xsols) c1 = sqrt(R) B = -q*c1/(4*R) A = -R - p/2 c2 = sqrt(A + B) c3 = sqrt(A - B) return [c1 - c2 - a, -c1 - c3 - a, -c1 + c3 - a, c1 + c2 - a] def roots_quartic(f): r""" Returns a list of roots of a quartic polynomial. There are many references for solving quartic expressions available [1-5]. This reviewer has found that many of them require one to select from among 2 or more possible sets of solutions and that some solutions work when one is searching for real roots but do not work when searching for complex roots (though this is not always stated clearly). The following routine has been tested and found to be correct for 0, 2 or 4 complex roots. The quasisymmetric case solution [6] looks for quartics that have the form `x**4 + A*x**3 + B*x**2 + C*x + D = 0` where `(C/A)**2 = D`. Although no general solution that is always applicable for all coefficients is known to this reviewer, certain conditions are tested to determine the simplest 4 expressions that can be returned: 1) `f = c + a*(a**2/8 - b/2) == 0` 2) `g = d - a*(a*(3*a**2/256 - b/16) + c/4) = 0` 3) if `f != 0` and `g != 0` and `p = -d + a*c/4 - b**2/12` then a) `p == 0` b) `p != 0` Examples ======== >>> from sympy import Poly >>> from sympy.polys.polyroots import roots_quartic >>> r = roots_quartic(Poly('x**4-6*x**3+17*x**2-26*x+20')) >>> # 4 complex roots: 1+-I*sqrt(3), 2+-I >>> sorted(str(tmp.evalf(n=2)) for tmp in r) ['1.0 + 1.7*I', '1.0 - 1.7*I', '2.0 + 1.0*I', '2.0 - 1.0*I'] References ========== 1. http://mathforum.org/dr.math/faq/faq.cubic.equations.html 2. https://en.wikipedia.org/wiki/Quartic_function#Summary_of_Ferrari.27s_method 3. http://planetmath.org/encyclopedia/GaloisTheoreticDerivationOfTheQuarticFormula.html 4. http://staff.bath.ac.uk/masjhd/JHD-CA.pdf 5. http://www.albmath.org/files/Math_5713.pdf 6. http://www.statemaster.com/encyclopedia/Quartic-equation 7. eqworld.ipmnet.ru/en/solutions/ae/ae0108.pdf """ _, a, b, c, d = f.monic().all_coeffs() if not d: return [S.Zero] + roots([1, a, b, c], multiple=True) elif (c/a)**2 == d: x, m = f.gen, c/a g = Poly(x**2 + a*x + b - 2*m, x) z1, z2 = roots_quadratic(g) h1 = Poly(x**2 - z1*x + m, x) h2 = Poly(x**2 - z2*x + m, x) r1 = roots_quadratic(h1) r2 = roots_quadratic(h2) return r1 + r2 else: a2 = a**2 e = b - 3*a2/8 f = _mexpand(c + a*(a2/8 - b/2)) aon4 = a/4 g = _mexpand(d - aon4*(a*(3*a2/64 - b/4) + c)) if f.is_zero: y1, y2 = [sqrt(tmp) for tmp in roots([1, e, g], multiple=True)] return [tmp - aon4 for tmp in [-y1, -y2, y1, y2]] if g.is_zero: y = [S.Zero] + roots([1, 0, e, f], multiple=True) return [tmp - aon4 for tmp in y] else: # Descartes-Euler method, see [7] sols = _roots_quartic_euler(e, f, g, aon4) if sols: return sols # Ferrari method, see [1, 2] p = -e**2/12 - g q = -e**3/108 + e*g/3 - f**2/8 TH = Rational(1, 3) def _ans(y): w = sqrt(e + 2*y) arg1 = 3*e + 2*y arg2 = 2*f/w ans = [] for s in [-1, 1]: root = sqrt(-(arg1 + s*arg2)) for t in [-1, 1]: ans.append((s*w - t*root)/2 - aon4) return ans # whether a Piecewise is returned or not # depends on knowing p, so try to put # in a simple form p = _mexpand(p) # p == 0 case y1 = e*Rational(-5, 6) - q**TH if p.is_zero: return _ans(y1) # if p != 0 then u below is not 0 root = sqrt(q**2/4 + p**3/27) r = -q/2 + root # or -q/2 - root u = r**TH # primary root of solve(x**3 - r, x) y2 = e*Rational(-5, 6) + u - p/u/3 if fuzzy_not(p.is_zero): return _ans(y2) # sort it out once they know the values of the coefficients return [Piecewise((a1, Eq(p, 0)), (a2, True)) for a1, a2 in zip(_ans(y1), _ans(y2))] def roots_binomial(f): """Returns a list of roots of a binomial polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise the ordering will not be sorted (but will be canonical). """ n = f.degree() a, b = f.nth(n), f.nth(0) base = -cancel(b/a) alpha = root(base, n) if alpha.is_number: alpha = alpha.expand(complex=True) # define some parameters that will allow us to order the roots. # If the domain is ZZ this is guaranteed to return roots sorted # with reals before non-real roots and non-real sorted according # to real part and imaginary part, e.g. -1, 1, -1 + I, 2 - I neg = base.is_negative even = n % 2 == 0 if neg: if even == True and (base + 1).is_positive: big = True else: big = False # get the indices in the right order so the computed # roots will be sorted when the domain is ZZ ks = [] imax = n//2 if even: ks.append(imax) imax -= 1 if not neg: ks.append(0) for i in range(imax, 0, -1): if neg: ks.extend([i, -i]) else: ks.extend([-i, i]) if neg: ks.append(0) if big: for i in range(0, len(ks), 2): pair = ks[i: i + 2] pair = list(reversed(pair)) # compute the roots roots, d = [], 2*I*pi/n for k in ks: zeta = exp(k*d).expand(complex=True) roots.append((alpha*zeta).expand(power_base=False)) return roots def _inv_totient_estimate(m): """ Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``. Examples ======== >>> from sympy.polys.polyroots import _inv_totient_estimate >>> _inv_totient_estimate(192) (192, 840) >>> _inv_totient_estimate(400) (400, 1750) """ primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ] a, b = 1, 1 for p in primes: a *= p b *= p - 1 L = m U = int(math.ceil(m*(float(a)/b))) P = p = 2 primes = [] while P <= U: p = nextprime(p) primes.append(p) P *= p P //= p b = 1 for p in primes[:-1]: b *= p - 1 U = int(math.ceil(m*(float(P)/b))) return L, U def roots_cyclotomic(f, factor=False): """Compute roots of cyclotomic polynomials. """ L, U = _inv_totient_estimate(f.degree()) for n in range(L, U + 1): g = cyclotomic_poly(n, f.gen, polys=True) if f.expr == g.expr: break else: # pragma: no cover raise RuntimeError("failed to find index of a cyclotomic polynomial") roots = [] if not factor: # get the indices in the right order so the computed # roots will be sorted h = n//2 ks = [i for i in range(1, n + 1) if igcd(i, n) == 1] ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1)) d = 2*I*pi/n for k in reversed(ks): roots.append(exp(k*d).expand(complex=True)) else: g = Poly(f, extension=root(-1, n)) for h, _ in ordered(g.factor_list()[1]): roots.append(-h.TC()) return roots def roots_quintic(f): """ Calculate exact roots of a solvable quintic """ result = [] coeff_5, coeff_4, p, q, r, s = f.all_coeffs() # Eqn must be of the form x^5 + px^3 + qx^2 + rx + s if coeff_4: return result if coeff_5 != 1: l = [p/coeff_5, q/coeff_5, r/coeff_5, s/coeff_5] if not all(coeff.is_Rational for coeff in l): return result f = Poly(f/coeff_5) elif not all(coeff.is_Rational for coeff in (p, q, r, s)): return result quintic = PolyQuintic(f) # Eqn standardized. Algo for solving starts here if not f.is_irreducible: return result f20 = quintic.f20 # Check if f20 has linear factors over domain Z if f20.is_irreducible: return result # Now, we know that f is solvable for _factor in f20.factor_list()[1]: if _factor[0].is_linear: theta = _factor[0].root(0) break d = discriminant(f) delta = sqrt(d) # zeta = a fifth root of unity zeta1, zeta2, zeta3, zeta4 = quintic.zeta T = quintic.T(theta, d) tol = S(1e-10) alpha = T[1] + T[2]*delta alpha_bar = T[1] - T[2]*delta beta = T[3] + T[4]*delta beta_bar = T[3] - T[4]*delta disc = alpha**2 - 4*beta disc_bar = alpha_bar**2 - 4*beta_bar l0 = quintic.l0(theta) Stwo = S(2) l1 = _quintic_simplify((-alpha + sqrt(disc)) / Stwo) l4 = _quintic_simplify((-alpha - sqrt(disc)) / Stwo) l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / Stwo) l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / Stwo) order = quintic.order(theta, d) test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) ) # Comparing floats if not comp(test, 0, tol): l2, l3 = l3, l2 # Now we have correct order of l's R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4 R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4 R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4 R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4 Res = [None, [None]*5, [None]*5, [None]*5, [None]*5] Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5] sol = Symbol('sol') # Simplifying improves performance a lot for exact expressions R1 = _quintic_simplify(R1) R2 = _quintic_simplify(R2) R3 = _quintic_simplify(R3) R4 = _quintic_simplify(R4) # Solve imported here. Causing problems if imported as 'solve' # and hence the changed name from sympy.solvers.solvers import solve as _solve a, b = symbols('a b', cls=Dummy) _sol = _solve( sol**5 - a - I*b, sol) for i in range(5): _sol[i] = factor(_sol[i]) R1 = R1.as_real_imag() R2 = R2.as_real_imag() R3 = R3.as_real_imag() R4 = R4.as_real_imag() for i, currentroot in enumerate(_sol): Res[1][i] = _quintic_simplify(currentroot.subs({ a: R1[0], b: R1[1] })) Res[2][i] = _quintic_simplify(currentroot.subs({ a: R2[0], b: R2[1] })) Res[3][i] = _quintic_simplify(currentroot.subs({ a: R3[0], b: R3[1] })) Res[4][i] = _quintic_simplify(currentroot.subs({ a: R4[0], b: R4[1] })) for i in range(1, 5): for j in range(5): Res_n[i][j] = Res[i][j].n() Res[i][j] = _quintic_simplify(Res[i][j]) r1 = Res[1][0] r1_n = Res_n[1][0] for i in range(5): if comp(im(r1_n*Res_n[4][i]), 0, tol): r4 = Res[4][i] break # Now we have various Res values. Each will be a list of five # values. We have to pick one r value from those five for each Res u, v = quintic.uv(theta, d) testplus = (u + v*delta*sqrt(5)).n() testminus = (u - v*delta*sqrt(5)).n() # Evaluated numbers suffixed with _n # We will use evaluated numbers for calculation. Much faster. r4_n = r4.n() r2 = r3 = None for i in range(5): r2temp_n = Res_n[2][i] for j in range(5): # Again storing away the exact number and using # evaluated numbers in computations r3temp_n = Res_n[3][j] if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)): r2 = Res[2][i] r3 = Res[3][j] break if r2: break else: return [] # fall back to normal solve # Now, we have r's so we can get roots x1 = (r1 + r2 + r3 + r4)/5 x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5 x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5 x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5 x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5 result = [x1, x2, x3, x4, x5] # Now check if solutions are distinct saw = set() for r in result: r = r.n(2) if r in saw: # Roots were identical. Abort, return [] # and fall back to usual solve return [] saw.add(r) return result def _quintic_simplify(expr): from sympy.simplify.simplify import powsimp expr = powsimp(expr) expr = cancel(expr) return together(expr) def _integer_basis(poly): """Compute coefficient basis for a polynomial over integers. Returns the integer ``div`` such that substituting ``x = div*y`` ``p(x) = m*q(y)`` where the coefficients of ``q`` are smaller than those of ``p``. For example ``x**5 + 512*x + 1024 = 0`` with ``div = 4`` becomes ``y**5 + 2*y + 1 = 0`` Returns the integer ``div`` or ``None`` if there is no possible scaling. Examples ======== >>> from sympy.polys import Poly >>> from sympy.abc import x >>> from sympy.polys.polyroots import _integer_basis >>> p = Poly(x**5 + 512*x + 1024, x, domain='ZZ') >>> _integer_basis(p) 4 """ monoms, coeffs = list(zip(*poly.terms())) monoms, = list(zip(*monoms)) coeffs = list(map(abs, coeffs)) if coeffs[0] < coeffs[-1]: coeffs = list(reversed(coeffs)) n = monoms[0] monoms = [n - i for i in reversed(monoms)] else: return None monoms = monoms[:-1] coeffs = coeffs[:-1] # Special case for two-term polynominals if len(monoms) == 1: r = Pow(coeffs[0], S.One/monoms[0]) if r.is_Integer: return int(r) else: return None divs = reversed(divisors(gcd_list(coeffs))[1:]) try: div = next(divs) except StopIteration: return None while True: for monom, coeff in zip(monoms, coeffs): if coeff % div**monom != 0: try: div = next(divs) except StopIteration: return None else: break else: return div def preprocess_roots(poly): """Try to get rid of symbolic coefficients from ``poly``. """ coeff = S.One poly_func = poly.func try: _, poly = poly.clear_denoms(convert=True) except DomainError: return coeff, poly poly = poly.primitive()[1] poly = poly.retract() # TODO: This is fragile. Figure out how to make this independent of construct_domain(). if poly.get_domain().is_Poly and all(c.is_term for c in poly.rep.coeffs()): poly = poly.inject() strips = list(zip(*poly.monoms())) gens = list(poly.gens[1:]) base, strips = strips[0], strips[1:] for gen, strip in zip(list(gens), strips): reverse = False if strip[0] < strip[-1]: strip = reversed(strip) reverse = True ratio = None for a, b in zip(base, strip): if not a and not b: continue elif not a or not b: break elif b % a != 0: break else: _ratio = b // a if ratio is None: ratio = _ratio elif ratio != _ratio: break else: if reverse: ratio = -ratio poly = poly.eval(gen, 1) coeff *= gen**(-ratio) gens.remove(gen) if gens: poly = poly.eject(*gens) if poly.is_univariate and poly.get_domain().is_ZZ: basis = _integer_basis(poly) if basis is not None: n = poly.degree() def func(k, coeff): return coeff//basis**(n - k[0]) poly = poly.termwise(func) coeff *= basis if not isinstance(poly, poly_func): poly = poly_func(poly) return coeff, poly @public def roots(f, *gens, auto=True, cubics=True, trig=False, quartics=True, quintics=False, multiple=False, filter=None, predicate=None, **flags): """ Computes symbolic roots of a univariate polynomial. Given a univariate polynomial f with symbolic coefficients (or a list of the polynomial's coefficients), returns a dictionary with its roots and their multiplicities. Only roots expressible via radicals will be returned. To get a complete set of roots use RootOf class or numerical methods instead. By default cubic and quartic formulas are used in the algorithm. To disable them because of unreadable output set ``cubics=False`` or ``quartics=False`` respectively. If cubic roots are real but are expressed in terms of complex numbers (casus irreducibilis [1]) the ``trig`` flag can be set to True to have the solutions returned in terms of cosine and inverse cosine functions. To get roots from a specific domain set the ``filter`` flag with one of the following specifiers: Z, Q, R, I, C. By default all roots are returned (this is equivalent to setting ``filter='C'``). By default a dictionary is returned giving a compact result in case of multiple roots. However to get a list containing all those roots set the ``multiple`` flag to True; the list will have identical roots appearing next to each other in the result. (For a given Poly, the all_roots method will give the roots in sorted numerical order.) Examples ======== >>> from sympy import Poly, roots >>> from sympy.abc import x, y >>> roots(x**2 - 1, x) {-1: 1, 1: 1} >>> p = Poly(x**2-1, x) >>> roots(p) {-1: 1, 1: 1} >>> p = Poly(x**2-y, x, y) >>> roots(Poly(p, x)) {-sqrt(y): 1, sqrt(y): 1} >>> roots(x**2 - y, x) {-sqrt(y): 1, sqrt(y): 1} >>> roots([1, 0, -1]) {-1: 1, 1: 1} References ========== .. [1] https://en.wikipedia.org/wiki/Cubic_function#Trigonometric_.28and_hyperbolic.29_method """ from sympy.polys.polytools import to_rational_coeffs flags = dict(flags) if isinstance(f, list): if gens: raise ValueError('redundant generators given') x = Dummy('x') poly, i = {}, len(f) - 1 for coeff in f: poly[i], i = sympify(coeff), i - 1 f = Poly(poly, x, field=True) else: try: F = Poly(f, *gens, **flags) if not isinstance(f, Poly) and not F.gen.is_Symbol: raise PolynomialError("generator must be a Symbol") else: f = F if f.length == 2 and f.degree() != 1: # check for foo**n factors in the constant n = f.degree() npow_bases = [] others = [] expr = f.as_expr() con = expr.as_independent(*gens)[0] for p in Mul.make_args(con): if p.is_Pow and not p.exp % n: npow_bases.append(p.base**(p.exp/n)) else: others.append(p) if npow_bases: b = Mul(*npow_bases) B = Dummy() d = roots(Poly(expr - con + B**n*Mul(*others), *gens, **flags), *gens, **flags) rv = {} for k, v in d.items(): rv[k.subs(B, b)] = v return rv except GeneratorsNeeded: if multiple: return [] else: return {} if f.is_multivariate: raise PolynomialError('multivariate polynomials are not supported') def _update_dict(result, zeros, currentroot, k): if currentroot == S.Zero: if S.Zero in zeros: zeros[S.Zero] += k else: zeros[S.Zero] = k if currentroot in result: result[currentroot] += k else: result[currentroot] = k def _try_decompose(f): """Find roots using functional decomposition. """ factors, roots = f.decompose(), [] for currentroot in _try_heuristics(factors[0]): roots.append(currentroot) for currentfactor in factors[1:]: previous, roots = list(roots), [] for currentroot in previous: g = currentfactor - Poly(currentroot, f.gen) for currentroot in _try_heuristics(g): roots.append(currentroot) return roots def _try_heuristics(f): """Find roots using formulas and some tricks. """ if f.is_ground: return [] if f.is_monomial: return [S.Zero]*f.degree() if f.length() == 2: if f.degree() == 1: return list(map(cancel, roots_linear(f))) else: return roots_binomial(f) result = [] for i in [-1, 1]: if not f.eval(i): f = f.quo(Poly(f.gen - i, f.gen)) result.append(i) break n = f.degree() if n == 1: result += list(map(cancel, roots_linear(f))) elif n == 2: result += list(map(cancel, roots_quadratic(f))) elif f.is_cyclotomic: result += roots_cyclotomic(f) elif n == 3 and cubics: result += roots_cubic(f, trig=trig) elif n == 4 and quartics: result += roots_quartic(f) elif n == 5 and quintics: result += roots_quintic(f) return result # Convert the generators to symbols dumgens = symbols('x:%d' % len(f.gens), cls=Dummy) f = f.per(f.rep, dumgens) (k,), f = f.terms_gcd() if not k: zeros = {} else: zeros = {S.Zero: k} coeff, f = preprocess_roots(f) if auto and f.get_domain().is_Ring: f = f.to_field() # Use EX instead of ZZ_I or QQ_I if f.get_domain().is_QQ_I: f = f.per(f.rep.convert(EX)) rescale_x = None translate_x = None result = {} if not f.is_ground: dom = f.get_domain() if not dom.is_Exact and dom.is_Numerical: for r in f.nroots(): _update_dict(result, zeros, r, 1) elif f.degree() == 1: _update_dict(result, zeros, roots_linear(f)[0], 1) elif f.length() == 2: roots_fun = roots_quadratic if f.degree() == 2 else roots_binomial for r in roots_fun(f): _update_dict(result, zeros, r, 1) else: _, factors = Poly(f.as_expr()).factor_list() if len(factors) == 1 and f.degree() == 2: for r in roots_quadratic(f): _update_dict(result, zeros, r, 1) else: if len(factors) == 1 and factors[0][1] == 1: if f.get_domain().is_EX: res = to_rational_coeffs(f) if res: if res[0] is None: translate_x, f = res[2:] else: rescale_x, f = res[1], res[-1] result = roots(f) if not result: for currentroot in _try_decompose(f): _update_dict(result, zeros, currentroot, 1) else: for r in _try_heuristics(f): _update_dict(result, zeros, r, 1) else: for currentroot in _try_decompose(f): _update_dict(result, zeros, currentroot, 1) else: for currentfactor, k in factors: for r in _try_heuristics(Poly(currentfactor, f.gen, field=True)): _update_dict(result, zeros, r, k) if coeff is not S.One: _result, result, = result, {} for currentroot, k in _result.items(): result[coeff*currentroot] = k if filter not in [None, 'C']: handlers = { 'Z': lambda r: r.is_Integer, 'Q': lambda r: r.is_Rational, 'R': lambda r: all(a.is_real for a in r.as_numer_denom()), 'I': lambda r: r.is_imaginary, } try: query = handlers[filter] except KeyError: raise ValueError("Invalid filter: %s" % filter) for zero in dict(result).keys(): if not query(zero): del result[zero] if predicate is not None: for zero in dict(result).keys(): if not predicate(zero): del result[zero] if rescale_x: result1 = {} for k, v in result.items(): result1[k*rescale_x] = v result = result1 if translate_x: result1 = {} for k, v in result.items(): result1[k + translate_x] = v result = result1 # adding zero roots after non-trivial roots have been translated result.update(zeros) if not multiple: return result else: zeros = [] for zero in ordered(result): zeros.extend([zero]*result[zero]) return zeros def root_factors(f, *gens, filter=None, **args): """ Returns all factors of a univariate polynomial. Examples ======== >>> from sympy.abc import x, y >>> from sympy.polys.polyroots import root_factors >>> root_factors(x**2 - y, x) [x - sqrt(y), x + sqrt(y)] """ args = dict(args) F = Poly(f, *gens, **args) if not F.is_Poly: return [f] if F.is_multivariate: raise ValueError('multivariate polynomials are not supported') x = F.gens[0] zeros = roots(F, filter=filter) if not zeros: factors = [F] else: factors, N = [], 0 for r, n in ordered(zeros.items()): factors, N = factors + [Poly(x - r, x)]*n, N + n if N < F.degree(): G = reduce(lambda p, q: p*q, factors) factors.append(F.quo(G)) if not isinstance(f, Poly): factors = [ f.as_expr() for f in factors ] return factors
ea59181cda533e9daaabca8a04d88af55fb136a2e0d0c61ca22fe4b0a68d05c8
"""Arithmetics for dense recursive polynomials in ``K[x]`` or ``K[X]``. """ from sympy.polys.densebasic import ( dup_slice, dup_LC, dmp_LC, dup_degree, dmp_degree, dup_strip, dmp_strip, dmp_zero_p, dmp_zero, dmp_one_p, dmp_one, dmp_ground, dmp_zeros) from sympy.polys.polyerrors import (ExactQuotientFailed, PolynomialDivisionFailed) def dup_add_term(f, c, i, K): """ Add ``c*x**i`` to ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_add_term(x**2 - 1, ZZ(2), 4) 2*x**4 + x**2 - 1 """ if not c: return f n = len(f) m = n - i - 1 if i == n - 1: return dup_strip([f[0] + c] + f[1:]) else: if i >= n: return [c] + [K.zero]*(i - n) + f else: return f[:m] + [f[m] + c] + f[m + 1:] def dmp_add_term(f, c, i, u, K): """ Add ``c(x_2..x_u)*x_0**i`` to ``f`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_add_term(x*y + 1, 2, 2) 2*x**2 + x*y + 1 """ if not u: return dup_add_term(f, c, i, K) v = u - 1 if dmp_zero_p(c, v): return f n = len(f) m = n - i - 1 if i == n - 1: return dmp_strip([dmp_add(f[0], c, v, K)] + f[1:], u) else: if i >= n: return [c] + dmp_zeros(i - n, v, K) + f else: return f[:m] + [dmp_add(f[m], c, v, K)] + f[m + 1:] def dup_sub_term(f, c, i, K): """ Subtract ``c*x**i`` from ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_sub_term(2*x**4 + x**2 - 1, ZZ(2), 4) x**2 - 1 """ if not c: return f n = len(f) m = n - i - 1 if i == n - 1: return dup_strip([f[0] - c] + f[1:]) else: if i >= n: return [-c] + [K.zero]*(i - n) + f else: return f[:m] + [f[m] - c] + f[m + 1:] def dmp_sub_term(f, c, i, u, K): """ Subtract ``c(x_2..x_u)*x_0**i`` from ``f`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_sub_term(2*x**2 + x*y + 1, 2, 2) x*y + 1 """ if not u: return dup_add_term(f, -c, i, K) v = u - 1 if dmp_zero_p(c, v): return f n = len(f) m = n - i - 1 if i == n - 1: return dmp_strip([dmp_sub(f[0], c, v, K)] + f[1:], u) else: if i >= n: return [dmp_neg(c, v, K)] + dmp_zeros(i - n, v, K) + f else: return f[:m] + [dmp_sub(f[m], c, v, K)] + f[m + 1:] def dup_mul_term(f, c, i, K): """ Multiply ``f`` by ``c*x**i`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_mul_term(x**2 - 1, ZZ(3), 2) 3*x**4 - 3*x**2 """ if not c or not f: return [] else: return [ cf * c for cf in f ] + [K.zero]*i def dmp_mul_term(f, c, i, u, K): """ Multiply ``f`` by ``c(x_2..x_u)*x_0**i`` in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_mul_term(x**2*y + x, 3*y, 2) 3*x**4*y**2 + 3*x**3*y """ if not u: return dup_mul_term(f, c, i, K) v = u - 1 if dmp_zero_p(f, u): return f if dmp_zero_p(c, v): return dmp_zero(u) else: return [ dmp_mul(cf, c, v, K) for cf in f ] + dmp_zeros(i, v, K) def dup_add_ground(f, c, K): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_add_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) x**3 + 2*x**2 + 3*x + 8 """ return dup_add_term(f, c, 0, K) def dmp_add_ground(f, c, u, K): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_add_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) x**3 + 2*x**2 + 3*x + 8 """ return dmp_add_term(f, dmp_ground(c, u - 1), 0, u, K) def dup_sub_ground(f, c, K): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_sub_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) x**3 + 2*x**2 + 3*x """ return dup_sub_term(f, c, 0, K) def dmp_sub_ground(f, c, u, K): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_sub_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) x**3 + 2*x**2 + 3*x """ return dmp_sub_term(f, dmp_ground(c, u - 1), 0, u, K) def dup_mul_ground(f, c, K): """ Multiply ``f`` by a constant value in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_mul_ground(x**2 + 2*x - 1, ZZ(3)) 3*x**2 + 6*x - 3 """ if not c or not f: return [] else: return [ cf * c for cf in f ] def dmp_mul_ground(f, c, u, K): """ Multiply ``f`` by a constant value in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_mul_ground(2*x + 2*y, ZZ(3)) 6*x + 6*y """ if not u: return dup_mul_ground(f, c, K) v = u - 1 return [ dmp_mul_ground(cf, c, v, K) for cf in f ] def dup_quo_ground(f, c, K): """ Quotient by a constant in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> R.dup_quo_ground(3*x**2 + 2, ZZ(2)) x**2 + 1 >>> R, x = ring("x", QQ) >>> R.dup_quo_ground(3*x**2 + 2, QQ(2)) 3/2*x**2 + 1 """ if not c: raise ZeroDivisionError('polynomial division') if not f: return f if K.is_Field: return [ K.quo(cf, c) for cf in f ] else: return [ cf // c for cf in f ] def dmp_quo_ground(f, c, u, K): """ Quotient by a constant in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_quo_ground(2*x**2*y + 3*x, ZZ(2)) x**2*y + x >>> R, x,y = ring("x,y", QQ) >>> R.dmp_quo_ground(2*x**2*y + 3*x, QQ(2)) x**2*y + 3/2*x """ if not u: return dup_quo_ground(f, c, K) v = u - 1 return [ dmp_quo_ground(cf, c, v, K) for cf in f ] def dup_exquo_ground(f, c, K): """ Exact quotient by a constant in ``K[x]``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> R.dup_exquo_ground(x**2 + 2, QQ(2)) 1/2*x**2 + 1 """ if not c: raise ZeroDivisionError('polynomial division') if not f: return f return [ K.exquo(cf, c) for cf in f ] def dmp_exquo_ground(f, c, u, K): """ Exact quotient by a constant in ``K[X]``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) >>> R.dmp_exquo_ground(x**2*y + 2*x, QQ(2)) 1/2*x**2*y + x """ if not u: return dup_exquo_ground(f, c, K) v = u - 1 return [ dmp_exquo_ground(cf, c, v, K) for cf in f ] def dup_lshift(f, n, K): """ Efficiently multiply ``f`` by ``x**n`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_lshift(x**2 + 1, 2) x**4 + x**2 """ if not f: return f else: return f + [K.zero]*n def dup_rshift(f, n, K): """ Efficiently divide ``f`` by ``x**n`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_rshift(x**4 + x**2, 2) x**2 + 1 >>> R.dup_rshift(x**4 + x**2 + 2, 2) x**2 + 1 """ return f[:-n] def dup_abs(f, K): """ Make all coefficients positive in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_abs(x**2 - 1) x**2 + 1 """ return [ K.abs(coeff) for coeff in f ] def dmp_abs(f, u, K): """ Make all coefficients positive in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_abs(x**2*y - x) x**2*y + x """ if not u: return dup_abs(f, K) v = u - 1 return [ dmp_abs(cf, v, K) for cf in f ] def dup_neg(f, K): """ Negate a polynomial in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_neg(x**2 - 1) -x**2 + 1 """ return [ -coeff for coeff in f ] def dmp_neg(f, u, K): """ Negate a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_neg(x**2*y - x) -x**2*y + x """ if not u: return dup_neg(f, K) v = u - 1 return [ dmp_neg(cf, v, K) for cf in f ] def dup_add(f, g, K): """ Add dense polynomials in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_add(x**2 - 1, x - 2) x**2 + x - 3 """ if not f: return g if not g: return f df = dup_degree(f) dg = dup_degree(g) if df == dg: return dup_strip([ a + b for a, b in zip(f, g) ]) else: k = abs(df - dg) if df > dg: h, f = f[:k], f[k:] else: h, g = g[:k], g[k:] return h + [ a + b for a, b in zip(f, g) ] def dmp_add(f, g, u, K): """ Add dense polynomials in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_add(x**2 + y, x**2*y + x) x**2*y + x**2 + x + y """ if not u: return dup_add(f, g, K) df = dmp_degree(f, u) if df < 0: return g dg = dmp_degree(g, u) if dg < 0: return f v = u - 1 if df == dg: return dmp_strip([ dmp_add(a, b, v, K) for a, b in zip(f, g) ], u) else: k = abs(df - dg) if df > dg: h, f = f[:k], f[k:] else: h, g = g[:k], g[k:] return h + [ dmp_add(a, b, v, K) for a, b in zip(f, g) ] def dup_sub(f, g, K): """ Subtract dense polynomials in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_sub(x**2 - 1, x - 2) x**2 - x + 1 """ if not f: return dup_neg(g, K) if not g: return f df = dup_degree(f) dg = dup_degree(g) if df == dg: return dup_strip([ a - b for a, b in zip(f, g) ]) else: k = abs(df - dg) if df > dg: h, f = f[:k], f[k:] else: h, g = dup_neg(g[:k], K), g[k:] return h + [ a - b for a, b in zip(f, g) ] def dmp_sub(f, g, u, K): """ Subtract dense polynomials in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_sub(x**2 + y, x**2*y + x) -x**2*y + x**2 - x + y """ if not u: return dup_sub(f, g, K) df = dmp_degree(f, u) if df < 0: return dmp_neg(g, u, K) dg = dmp_degree(g, u) if dg < 0: return f v = u - 1 if df == dg: return dmp_strip([ dmp_sub(a, b, v, K) for a, b in zip(f, g) ], u) else: k = abs(df - dg) if df > dg: h, f = f[:k], f[k:] else: h, g = dmp_neg(g[:k], u, K), g[k:] return h + [ dmp_sub(a, b, v, K) for a, b in zip(f, g) ] def dup_add_mul(f, g, h, K): """ Returns ``f + g*h`` where ``f, g, h`` are in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_add_mul(x**2 - 1, x - 2, x + 2) 2*x**2 - 5 """ return dup_add(f, dup_mul(g, h, K), K) def dmp_add_mul(f, g, h, u, K): """ Returns ``f + g*h`` where ``f, g, h`` are in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_add_mul(x**2 + y, x, x + 2) 2*x**2 + 2*x + y """ return dmp_add(f, dmp_mul(g, h, u, K), u, K) def dup_sub_mul(f, g, h, K): """ Returns ``f - g*h`` where ``f, g, h`` are in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_sub_mul(x**2 - 1, x - 2, x + 2) 3 """ return dup_sub(f, dup_mul(g, h, K), K) def dmp_sub_mul(f, g, h, u, K): """ Returns ``f - g*h`` where ``f, g, h`` are in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_sub_mul(x**2 + y, x, x + 2) -2*x + y """ return dmp_sub(f, dmp_mul(g, h, u, K), u, K) def dup_mul(f, g, K): """ Multiply dense polynomials in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_mul(x - 2, x + 2) x**2 - 4 """ if f == g: return dup_sqr(f, K) if not (f and g): return [] df = dup_degree(f) dg = dup_degree(g) n = max(df, dg) + 1 if n < 100: h = [] for i in range(0, df + dg + 1): coeff = K.zero for j in range(max(0, i - dg), min(df, i) + 1): coeff += f[j]*g[i - j] h.append(coeff) return dup_strip(h) else: # Use Karatsuba's algorithm (divide and conquer), see e.g.: # Joris van der Hoeven, Relax But Don't Be Too Lazy, # J. Symbolic Computation, 11 (2002), section 3.1.1. n2 = n//2 fl, gl = dup_slice(f, 0, n2, K), dup_slice(g, 0, n2, K) fh = dup_rshift(dup_slice(f, n2, n, K), n2, K) gh = dup_rshift(dup_slice(g, n2, n, K), n2, K) lo, hi = dup_mul(fl, gl, K), dup_mul(fh, gh, K) mid = dup_mul(dup_add(fl, fh, K), dup_add(gl, gh, K), K) mid = dup_sub(mid, dup_add(lo, hi, K), K) return dup_add(dup_add(lo, dup_lshift(mid, n2, K), K), dup_lshift(hi, 2*n2, K), K) def dmp_mul(f, g, u, K): """ Multiply dense polynomials in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_mul(x*y + 1, x) x**2*y + x """ if not u: return dup_mul(f, g, K) if f == g: return dmp_sqr(f, u, K) df = dmp_degree(f, u) if df < 0: return f dg = dmp_degree(g, u) if dg < 0: return g h, v = [], u - 1 for i in range(0, df + dg + 1): coeff = dmp_zero(v) for j in range(max(0, i - dg), min(df, i) + 1): coeff = dmp_add(coeff, dmp_mul(f[j], g[i - j], v, K), v, K) h.append(coeff) return dmp_strip(h, u) def dup_sqr(f, K): """ Square dense polynomials in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_sqr(x**2 + 1) x**4 + 2*x**2 + 1 """ df, h = len(f) - 1, [] for i in range(0, 2*df + 1): c = K.zero jmin = max(0, i - df) jmax = min(i, df) n = jmax - jmin + 1 jmax = jmin + n // 2 - 1 for j in range(jmin, jmax + 1): c += f[j]*f[i - j] c += c if n & 1: elem = f[jmax + 1] c += elem**2 h.append(c) return dup_strip(h) def dmp_sqr(f, u, K): """ Square dense polynomials in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_sqr(x**2 + x*y + y**2) x**4 + 2*x**3*y + 3*x**2*y**2 + 2*x*y**3 + y**4 """ if not u: return dup_sqr(f, K) df = dmp_degree(f, u) if df < 0: return f h, v = [], u - 1 for i in range(0, 2*df + 1): c = dmp_zero(v) jmin = max(0, i - df) jmax = min(i, df) n = jmax - jmin + 1 jmax = jmin + n // 2 - 1 for j in range(jmin, jmax + 1): c = dmp_add(c, dmp_mul(f[j], f[i - j], v, K), v, K) c = dmp_mul_ground(c, K(2), v, K) if n & 1: elem = dmp_sqr(f[jmax + 1], v, K) c = dmp_add(c, elem, v, K) h.append(c) return dmp_strip(h, u) def dup_pow(f, n, K): """ Raise ``f`` to the ``n``-th power in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_pow(x - 2, 3) x**3 - 6*x**2 + 12*x - 8 """ if not n: return [K.one] if n < 0: raise ValueError("Cannot raise polynomial to a negative power") if n == 1 or not f or f == [K.one]: return f g = [K.one] while True: n, m = n//2, n if m % 2: g = dup_mul(g, f, K) if not n: break f = dup_sqr(f, K) return g def dmp_pow(f, n, u, K): """ Raise ``f`` to the ``n``-th power in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_pow(x*y + 1, 3) x**3*y**3 + 3*x**2*y**2 + 3*x*y + 1 """ if not u: return dup_pow(f, n, K) if not n: return dmp_one(u, K) if n < 0: raise ValueError("Cannot raise polynomial to a negative power") if n == 1 or dmp_zero_p(f, u) or dmp_one_p(f, u, K): return f g = dmp_one(u, K) while True: n, m = n//2, n if m & 1: g = dmp_mul(g, f, u, K) if not n: break f = dmp_sqr(f, u, K) return g def dup_pdiv(f, g, K): """ Polynomial pseudo-division in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_pdiv(x**2 + 1, 2*x - 4) (2*x + 4, 20) """ df = dup_degree(f) dg = dup_degree(g) q, r, dr = [], f, df if not g: raise ZeroDivisionError("polynomial division") elif df < dg: return q, r N = df - dg + 1 lc_g = dup_LC(g, K) while True: lc_r = dup_LC(r, K) j, N = dr - dg, N - 1 Q = dup_mul_ground(q, lc_g, K) q = dup_add_term(Q, lc_r, j, K) R = dup_mul_ground(r, lc_g, K) G = dup_mul_term(g, lc_r, j, K) r = dup_sub(R, G, K) _dr, dr = dr, dup_degree(r) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) c = lc_g**N q = dup_mul_ground(q, c, K) r = dup_mul_ground(r, c, K) return q, r def dup_prem(f, g, K): """ Polynomial pseudo-remainder in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_prem(x**2 + 1, 2*x - 4) 20 """ df = dup_degree(f) dg = dup_degree(g) r, dr = f, df if not g: raise ZeroDivisionError("polynomial division") elif df < dg: return r N = df - dg + 1 lc_g = dup_LC(g, K) while True: lc_r = dup_LC(r, K) j, N = dr - dg, N - 1 R = dup_mul_ground(r, lc_g, K) G = dup_mul_term(g, lc_r, j, K) r = dup_sub(R, G, K) _dr, dr = dr, dup_degree(r) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) return dup_mul_ground(r, lc_g**N, K) def dup_pquo(f, g, K): """ Polynomial exact pseudo-quotient in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_pquo(x**2 - 1, 2*x - 2) 2*x + 2 >>> R.dup_pquo(x**2 + 1, 2*x - 4) 2*x + 4 """ return dup_pdiv(f, g, K)[0] def dup_pexquo(f, g, K): """ Polynomial pseudo-quotient in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_pexquo(x**2 - 1, 2*x - 2) 2*x + 2 >>> R.dup_pexquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: [2, -4] does not divide [1, 0, 1] """ q, r = dup_pdiv(f, g, K) if not r: return q else: raise ExactQuotientFailed(f, g) def dmp_pdiv(f, g, u, K): """ Polynomial pseudo-division in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_pdiv(x**2 + x*y, 2*x + 2) (2*x + 2*y - 2, -4*y + 4) """ if not u: return dup_pdiv(f, g, K) df = dmp_degree(f, u) dg = dmp_degree(g, u) if dg < 0: raise ZeroDivisionError("polynomial division") q, r, dr = dmp_zero(u), f, df if df < dg: return q, r N = df - dg + 1 lc_g = dmp_LC(g, K) while True: lc_r = dmp_LC(r, K) j, N = dr - dg, N - 1 Q = dmp_mul_term(q, lc_g, 0, u, K) q = dmp_add_term(Q, lc_r, j, u, K) R = dmp_mul_term(r, lc_g, 0, u, K) G = dmp_mul_term(g, lc_r, j, u, K) r = dmp_sub(R, G, u, K) _dr, dr = dr, dmp_degree(r, u) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) c = dmp_pow(lc_g, N, u - 1, K) q = dmp_mul_term(q, c, 0, u, K) r = dmp_mul_term(r, c, 0, u, K) return q, r def dmp_prem(f, g, u, K): """ Polynomial pseudo-remainder in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_prem(x**2 + x*y, 2*x + 2) -4*y + 4 """ if not u: return dup_prem(f, g, K) df = dmp_degree(f, u) dg = dmp_degree(g, u) if dg < 0: raise ZeroDivisionError("polynomial division") r, dr = f, df if df < dg: return r N = df - dg + 1 lc_g = dmp_LC(g, K) while True: lc_r = dmp_LC(r, K) j, N = dr - dg, N - 1 R = dmp_mul_term(r, lc_g, 0, u, K) G = dmp_mul_term(g, lc_r, j, u, K) r = dmp_sub(R, G, u, K) _dr, dr = dr, dmp_degree(r, u) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) c = dmp_pow(lc_g, N, u - 1, K) return dmp_mul_term(r, c, 0, u, K) def dmp_pquo(f, g, u, K): """ Polynomial exact pseudo-quotient in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x**2 + x*y >>> g = 2*x + 2*y >>> h = 2*x + 2 >>> R.dmp_pquo(f, g) 2*x >>> R.dmp_pquo(f, h) 2*x + 2*y - 2 """ return dmp_pdiv(f, g, u, K)[0] def dmp_pexquo(f, g, u, K): """ Polynomial pseudo-quotient in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x**2 + x*y >>> g = 2*x + 2*y >>> h = 2*x + 2 >>> R.dmp_pexquo(f, g) 2*x >>> R.dmp_pexquo(f, h) Traceback (most recent call last): ... ExactQuotientFailed: [[2], [2]] does not divide [[1], [1, 0], []] """ q, r = dmp_pdiv(f, g, u, K) if dmp_zero_p(r, u): return q else: raise ExactQuotientFailed(f, g) def dup_rr_div(f, g, K): """ Univariate division with remainder over a ring. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_rr_div(x**2 + 1, 2*x - 4) (0, x**2 + 1) """ df = dup_degree(f) dg = dup_degree(g) q, r, dr = [], f, df if not g: raise ZeroDivisionError("polynomial division") elif df < dg: return q, r lc_g = dup_LC(g, K) while True: lc_r = dup_LC(r, K) if lc_r % lc_g: break c = K.exquo(lc_r, lc_g) j = dr - dg q = dup_add_term(q, c, j, K) h = dup_mul_term(g, c, j, K) r = dup_sub(r, h, K) _dr, dr = dr, dup_degree(r) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) return q, r def dmp_rr_div(f, g, u, K): """ Multivariate division with remainder over a ring. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_rr_div(x**2 + x*y, 2*x + 2) (0, x**2 + x*y) """ if not u: return dup_rr_div(f, g, K) df = dmp_degree(f, u) dg = dmp_degree(g, u) if dg < 0: raise ZeroDivisionError("polynomial division") q, r, dr = dmp_zero(u), f, df if df < dg: return q, r lc_g, v = dmp_LC(g, K), u - 1 while True: lc_r = dmp_LC(r, K) c, R = dmp_rr_div(lc_r, lc_g, v, K) if not dmp_zero_p(R, v): break j = dr - dg q = dmp_add_term(q, c, j, u, K) h = dmp_mul_term(g, c, j, u, K) r = dmp_sub(r, h, u, K) _dr, dr = dr, dmp_degree(r, u) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) return q, r def dup_ff_div(f, g, K): """ Polynomial division with remainder over a field. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> R.dup_ff_div(x**2 + 1, 2*x - 4) (1/2*x + 1, 5) """ df = dup_degree(f) dg = dup_degree(g) q, r, dr = [], f, df if not g: raise ZeroDivisionError("polynomial division") elif df < dg: return q, r lc_g = dup_LC(g, K) while True: lc_r = dup_LC(r, K) c = K.exquo(lc_r, lc_g) j = dr - dg q = dup_add_term(q, c, j, K) h = dup_mul_term(g, c, j, K) r = dup_sub(r, h, K) _dr, dr = dr, dup_degree(r) if dr < dg: break elif dr == _dr and not K.is_Exact: # remove leading term created by rounding error r = dup_strip(r[1:]) dr = dup_degree(r) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) return q, r def dmp_ff_div(f, g, u, K): """ Polynomial division with remainder over a field. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) >>> R.dmp_ff_div(x**2 + x*y, 2*x + 2) (1/2*x + 1/2*y - 1/2, -y + 1) """ if not u: return dup_ff_div(f, g, K) df = dmp_degree(f, u) dg = dmp_degree(g, u) if dg < 0: raise ZeroDivisionError("polynomial division") q, r, dr = dmp_zero(u), f, df if df < dg: return q, r lc_g, v = dmp_LC(g, K), u - 1 while True: lc_r = dmp_LC(r, K) c, R = dmp_ff_div(lc_r, lc_g, v, K) if not dmp_zero_p(R, v): break j = dr - dg q = dmp_add_term(q, c, j, u, K) h = dmp_mul_term(g, c, j, u, K) r = dmp_sub(r, h, u, K) _dr, dr = dr, dmp_degree(r, u) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) return q, r def dup_div(f, g, K): """ Polynomial division with remainder in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> R.dup_div(x**2 + 1, 2*x - 4) (0, x**2 + 1) >>> R, x = ring("x", QQ) >>> R.dup_div(x**2 + 1, 2*x - 4) (1/2*x + 1, 5) """ if K.is_Field: return dup_ff_div(f, g, K) else: return dup_rr_div(f, g, K) def dup_rem(f, g, K): """ Returns polynomial remainder in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> R.dup_rem(x**2 + 1, 2*x - 4) x**2 + 1 >>> R, x = ring("x", QQ) >>> R.dup_rem(x**2 + 1, 2*x - 4) 5 """ return dup_div(f, g, K)[1] def dup_quo(f, g, K): """ Returns exact polynomial quotient in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> R.dup_quo(x**2 + 1, 2*x - 4) 0 >>> R, x = ring("x", QQ) >>> R.dup_quo(x**2 + 1, 2*x - 4) 1/2*x + 1 """ return dup_div(f, g, K)[0] def dup_exquo(f, g, K): """ Returns polynomial quotient in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_exquo(x**2 - 1, x - 1) x + 1 >>> R.dup_exquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: [2, -4] does not divide [1, 0, 1] """ q, r = dup_div(f, g, K) if not r: return q else: raise ExactQuotientFailed(f, g) def dmp_div(f, g, u, K): """ Polynomial division with remainder in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_div(x**2 + x*y, 2*x + 2) (0, x**2 + x*y) >>> R, x,y = ring("x,y", QQ) >>> R.dmp_div(x**2 + x*y, 2*x + 2) (1/2*x + 1/2*y - 1/2, -y + 1) """ if K.is_Field: return dmp_ff_div(f, g, u, K) else: return dmp_rr_div(f, g, u, K) def dmp_rem(f, g, u, K): """ Returns polynomial remainder in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_rem(x**2 + x*y, 2*x + 2) x**2 + x*y >>> R, x,y = ring("x,y", QQ) >>> R.dmp_rem(x**2 + x*y, 2*x + 2) -y + 1 """ return dmp_div(f, g, u, K)[1] def dmp_quo(f, g, u, K): """ Returns exact polynomial quotient in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_quo(x**2 + x*y, 2*x + 2) 0 >>> R, x,y = ring("x,y", QQ) >>> R.dmp_quo(x**2 + x*y, 2*x + 2) 1/2*x + 1/2*y - 1/2 """ return dmp_div(f, g, u, K)[0] def dmp_exquo(f, g, u, K): """ Returns polynomial quotient in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x**2 + x*y >>> g = x + y >>> h = 2*x + 2 >>> R.dmp_exquo(f, g) x >>> R.dmp_exquo(f, h) Traceback (most recent call last): ... ExactQuotientFailed: [[2], [2]] does not divide [[1], [1, 0], []] """ q, r = dmp_div(f, g, u, K) if dmp_zero_p(r, u): return q else: raise ExactQuotientFailed(f, g) def dup_max_norm(f, K): """ Returns maximum norm of a polynomial in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_max_norm(-x**2 + 2*x - 3) 3 """ if not f: return K.zero else: return max(dup_abs(f, K)) def dmp_max_norm(f, u, K): """ Returns maximum norm of a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_max_norm(2*x*y - x - 3) 3 """ if not u: return dup_max_norm(f, K) v = u - 1 return max([ dmp_max_norm(c, v, K) for c in f ]) def dup_l1_norm(f, K): """ Returns l1 norm of a polynomial in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_l1_norm(2*x**3 - 3*x**2 + 1) 6 """ if not f: return K.zero else: return sum(dup_abs(f, K)) def dmp_l1_norm(f, u, K): """ Returns l1 norm of a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_l1_norm(2*x*y - x - 3) 6 """ if not u: return dup_l1_norm(f, K) v = u - 1 return sum([ dmp_l1_norm(c, v, K) for c in f ]) def dup_l2_norm_squared(f, K): """ Returns squared l2 norm of a polynomial in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_l2_norm_squared(2*x**3 - 3*x**2 + 1) 14 """ return sum([coeff**2 for coeff in f], K.zero) def dmp_l2_norm_squared(f, u, K): """ Returns squared l2 norm of a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_l2_norm_squared(2*x*y - x - 3) 14 """ if not u: return dup_l2_norm_squared(f, K) v = u - 1 return sum([ dmp_l2_norm_squared(c, v, K) for c in f ]) def dup_expand(polys, K): """ Multiply together several polynomials in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_expand([x**2 - 1, x, 2]) 2*x**3 - 2*x """ if not polys: return [K.one] f = polys[0] for g in polys[1:]: f = dup_mul(f, g, K) return f def dmp_expand(polys, u, K): """ Multiply together several polynomials in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_expand([x**2 + y**2, x + 1]) x**3 + x**2 + x*y**2 + y**2 """ if not polys: return dmp_one(u, K) f = polys[0] for g in polys[1:]: f = dmp_mul(f, g, u, K) return f
b0828fc4d29501630d24c15ff1232502c870a0dc16786cd8a9480b670e54ca6b
"""Dense univariate polynomials with coefficients in Galois fields. """ from sympy.core.random import uniform from math import ceil as _ceil, sqrt as _sqrt from sympy.core.mul import prod from sympy.external.gmpy import SYMPY_INTS from sympy.polys.polyconfig import query from sympy.polys.polyerrors import ExactQuotientFailed from sympy.polys.polyutils import _sort_factors def gf_crt(U, M, K=None): """ Chinese Remainder Theorem. Given a set of integer residues ``u_0,...,u_n`` and a set of co-prime integer moduli ``m_0,...,m_n``, returns an integer ``u``, such that ``u = u_i mod m_i`` for ``i = ``0,...,n``. Examples ======== Consider a set of residues ``U = [49, 76, 65]`` and a set of moduli ``M = [99, 97, 95]``. Then we have:: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_crt >>> gf_crt([49, 76, 65], [99, 97, 95], ZZ) 639985 This is the correct result because:: >>> [639985 % m for m in [99, 97, 95]] [49, 76, 65] Note: this is a low-level routine with no error checking. See Also ======== sympy.ntheory.modular.crt : a higher level crt routine sympy.ntheory.modular.solve_congruence """ p = prod(M, start=K.one) v = K.zero for u, m in zip(U, M): e = p // m s, _, _ = K.gcdex(e, m) v += e*(u*s % m) return v % p def gf_crt1(M, K): """ First part of the Chinese Remainder Theorem. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_crt1 >>> gf_crt1([99, 97, 95], ZZ) (912285, [9215, 9405, 9603], [62, 24, 12]) """ E, S = [], [] p = prod(M, start=K.one) for m in M: E.append(p // m) S.append(K.gcdex(E[-1], m)[0] % m) return p, E, S def gf_crt2(U, M, p, E, S, K): """ Second part of the Chinese Remainder Theorem. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_crt2 >>> U = [49, 76, 65] >>> M = [99, 97, 95] >>> p = 912285 >>> E = [9215, 9405, 9603] >>> S = [62, 24, 12] >>> gf_crt2(U, M, p, E, S, ZZ) 639985 """ v = K.zero for u, m, e, s in zip(U, M, E, S): v += e*(u*s % m) return v % p def gf_int(a, p): """ Coerce ``a mod p`` to an integer in the range ``[-p/2, p/2]``. Examples ======== >>> from sympy.polys.galoistools import gf_int >>> gf_int(2, 7) 2 >>> gf_int(5, 7) -2 """ if a <= p // 2: return a else: return a - p def gf_degree(f): """ Return the leading degree of ``f``. Examples ======== >>> from sympy.polys.galoistools import gf_degree >>> gf_degree([1, 1, 2, 0]) 3 >>> gf_degree([]) -1 """ return len(f) - 1 def gf_LC(f, K): """ Return the leading coefficient of ``f``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_LC >>> gf_LC([3, 0, 1], ZZ) 3 """ if not f: return K.zero else: return f[0] def gf_TC(f, K): """ Return the trailing coefficient of ``f``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_TC >>> gf_TC([3, 0, 1], ZZ) 1 """ if not f: return K.zero else: return f[-1] def gf_strip(f): """ Remove leading zeros from ``f``. Examples ======== >>> from sympy.polys.galoistools import gf_strip >>> gf_strip([0, 0, 0, 3, 0, 1]) [3, 0, 1] """ if not f or f[0]: return f k = 0 for coeff in f: if coeff: break else: k += 1 return f[k:] def gf_trunc(f, p): """ Reduce all coefficients modulo ``p``. Examples ======== >>> from sympy.polys.galoistools import gf_trunc >>> gf_trunc([7, -2, 3], 5) [2, 3, 3] """ return gf_strip([ a % p for a in f ]) def gf_normal(f, p, K): """ Normalize all coefficients in ``K``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_normal >>> gf_normal([5, 10, 21, -3], 5, ZZ) [1, 2] """ return gf_trunc(list(map(K, f)), p) def gf_from_dict(f, p, K): """ Create a ``GF(p)[x]`` polynomial from a dict. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_from_dict >>> gf_from_dict({10: ZZ(4), 4: ZZ(33), 0: ZZ(-1)}, 5, ZZ) [4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4] """ n, h = max(f.keys()), [] if isinstance(n, SYMPY_INTS): for k in range(n, -1, -1): h.append(f.get(k, K.zero) % p) else: (n,) = n for k in range(n, -1, -1): h.append(f.get((k,), K.zero) % p) return gf_trunc(h, p) def gf_to_dict(f, p, symmetric=True): """ Convert a ``GF(p)[x]`` polynomial to a dict. Examples ======== >>> from sympy.polys.galoistools import gf_to_dict >>> gf_to_dict([4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4], 5) {0: -1, 4: -2, 10: -1} >>> gf_to_dict([4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4], 5, symmetric=False) {0: 4, 4: 3, 10: 4} """ n, result = gf_degree(f), {} for k in range(0, n + 1): if symmetric: a = gf_int(f[n - k], p) else: a = f[n - k] if a: result[k] = a return result def gf_from_int_poly(f, p): """ Create a ``GF(p)[x]`` polynomial from ``Z[x]``. Examples ======== >>> from sympy.polys.galoistools import gf_from_int_poly >>> gf_from_int_poly([7, -2, 3], 5) [2, 3, 3] """ return gf_trunc(f, p) def gf_to_int_poly(f, p, symmetric=True): """ Convert a ``GF(p)[x]`` polynomial to ``Z[x]``. Examples ======== >>> from sympy.polys.galoistools import gf_to_int_poly >>> gf_to_int_poly([2, 3, 3], 5) [2, -2, -2] >>> gf_to_int_poly([2, 3, 3], 5, symmetric=False) [2, 3, 3] """ if symmetric: return [ gf_int(c, p) for c in f ] else: return f def gf_neg(f, p, K): """ Negate a polynomial in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_neg >>> gf_neg([3, 2, 1, 0], 5, ZZ) [2, 3, 4, 0] """ return [ -coeff % p for coeff in f ] def gf_add_ground(f, a, p, K): """ Compute ``f + a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_add_ground >>> gf_add_ground([3, 2, 4], 2, 5, ZZ) [3, 2, 1] """ if not f: a = a % p else: a = (f[-1] + a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a] def gf_sub_ground(f, a, p, K): """ Compute ``f - a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sub_ground >>> gf_sub_ground([3, 2, 4], 2, 5, ZZ) [3, 2, 2] """ if not f: a = -a % p else: a = (f[-1] - a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a] def gf_mul_ground(f, a, p, K): """ Compute ``f * a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_mul_ground >>> gf_mul_ground([3, 2, 4], 2, 5, ZZ) [1, 4, 3] """ if not a: return [] else: return [ (a*b) % p for b in f ] def gf_quo_ground(f, a, p, K): """ Compute ``f/a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_quo_ground >>> gf_quo_ground(ZZ.map([3, 2, 4]), ZZ(2), 5, ZZ) [4, 1, 2] """ return gf_mul_ground(f, K.invert(a, p), p, K) def gf_add(f, g, p, K): """ Add polynomials in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_add >>> gf_add([3, 2, 4], [2, 2, 2], 5, ZZ) [4, 1] """ if not f: return g if not g: return f df = gf_degree(f) dg = gf_degree(g) if df == dg: return gf_strip([ (a + b) % p for a, b in zip(f, g) ]) else: k = abs(df - dg) if df > dg: h, f = f[:k], f[k:] else: h, g = g[:k], g[k:] return h + [ (a + b) % p for a, b in zip(f, g) ] def gf_sub(f, g, p, K): """ Subtract polynomials in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sub >>> gf_sub([3, 2, 4], [2, 2, 2], 5, ZZ) [1, 0, 2] """ if not g: return f if not f: return gf_neg(g, p, K) df = gf_degree(f) dg = gf_degree(g) if df == dg: return gf_strip([ (a - b) % p for a, b in zip(f, g) ]) else: k = abs(df - dg) if df > dg: h, f = f[:k], f[k:] else: h, g = gf_neg(g[:k], p, K), g[k:] return h + [ (a - b) % p for a, b in zip(f, g) ] def gf_mul(f, g, p, K): """ Multiply polynomials in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_mul >>> gf_mul([3, 2, 4], [2, 2, 2], 5, ZZ) [1, 0, 3, 2, 3] """ df = gf_degree(f) dg = gf_degree(g) dh = df + dg h = [0]*(dh + 1) for i in range(0, dh + 1): coeff = K.zero for j in range(max(0, i - dg), min(i, df) + 1): coeff += f[j]*g[i - j] h[i] = coeff % p return gf_strip(h) def gf_sqr(f, p, K): """ Square polynomials in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sqr >>> gf_sqr([3, 2, 4], 5, ZZ) [4, 2, 3, 1, 1] """ df = gf_degree(f) dh = 2*df h = [0]*(dh + 1) for i in range(0, dh + 1): coeff = K.zero jmin = max(0, i - df) jmax = min(i, df) n = jmax - jmin + 1 jmax = jmin + n // 2 - 1 for j in range(jmin, jmax + 1): coeff += f[j]*f[i - j] coeff += coeff if n & 1: elem = f[jmax + 1] coeff += elem**2 h[i] = coeff % p return gf_strip(h) def gf_add_mul(f, g, h, p, K): """ Returns ``f + g*h`` where ``f``, ``g``, ``h`` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_add_mul >>> gf_add_mul([3, 2, 4], [2, 2, 2], [1, 4], 5, ZZ) [2, 3, 2, 2] """ return gf_add(f, gf_mul(g, h, p, K), p, K) def gf_sub_mul(f, g, h, p, K): """ Compute ``f - g*h`` where ``f``, ``g``, ``h`` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sub_mul >>> gf_sub_mul([3, 2, 4], [2, 2, 2], [1, 4], 5, ZZ) [3, 3, 2, 1] """ return gf_sub(f, gf_mul(g, h, p, K), p, K) def gf_expand(F, p, K): """ Expand results of :func:`~.factor` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_expand >>> gf_expand([([3, 2, 4], 1), ([2, 2], 2), ([3, 1], 3)], 5, ZZ) [4, 3, 0, 3, 0, 1, 4, 1] """ if isinstance(F, tuple): lc, F = F else: lc = K.one g = [lc] for f, k in F: f = gf_pow(f, k, p, K) g = gf_mul(g, f, p, K) return g def gf_div(f, g, p, K): """ Division with remainder in ``GF(p)[x]``. Given univariate polynomials ``f`` and ``g`` with coefficients in a finite field with ``p`` elements, returns polynomials ``q`` and ``r`` (quotient and remainder) such that ``f = q*g + r``. Consider polynomials ``x**3 + x + 1`` and ``x**2 + x`` in GF(2):: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_div, gf_add_mul >>> gf_div(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) ([1, 1], [1]) As result we obtained quotient ``x + 1`` and remainder ``1``, thus:: >>> gf_add_mul(ZZ.map([1]), ZZ.map([1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) [1, 0, 1, 1] References ========== .. [1] [Monagan93]_ .. [2] [Gathen99]_ """ df = gf_degree(f) dg = gf_degree(g) if not g: raise ZeroDivisionError("polynomial division") elif df < dg: return [], f inv = K.invert(g[0], p) h, dq, dr = list(f), df - dg, dg - 1 for i in range(0, df + 1): coeff = h[i] for j in range(max(0, dg - i), min(df - i, dr) + 1): coeff -= h[i + j - dg] * g[dg - j] if i <= dq: coeff *= inv h[i] = coeff % p return h[:dq + 1], gf_strip(h[dq + 1:]) def gf_rem(f, g, p, K): """ Compute polynomial remainder in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_rem >>> gf_rem(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) [1] """ return gf_div(f, g, p, K)[1] def gf_quo(f, g, p, K): """ Compute exact quotient in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_quo >>> gf_quo(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) [1, 1] >>> gf_quo(ZZ.map([1, 0, 3, 2, 3]), ZZ.map([2, 2, 2]), 5, ZZ) [3, 2, 4] """ df = gf_degree(f) dg = gf_degree(g) if not g: raise ZeroDivisionError("polynomial division") elif df < dg: return [] inv = K.invert(g[0], p) h, dq, dr = f[:], df - dg, dg - 1 for i in range(0, dq + 1): coeff = h[i] for j in range(max(0, dg - i), min(df - i, dr) + 1): coeff -= h[i + j - dg] * g[dg - j] h[i] = (coeff * inv) % p return h[:dq + 1] def gf_exquo(f, g, p, K): """ Compute polynomial quotient in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_exquo >>> gf_exquo(ZZ.map([1, 0, 3, 2, 3]), ZZ.map([2, 2, 2]), 5, ZZ) [3, 2, 4] >>> gf_exquo(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) Traceback (most recent call last): ... ExactQuotientFailed: [1, 1, 0] does not divide [1, 0, 1, 1] """ q, r = gf_div(f, g, p, K) if not r: return q else: raise ExactQuotientFailed(f, g) def gf_lshift(f, n, K): """ Efficiently multiply ``f`` by ``x**n``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_lshift >>> gf_lshift([3, 2, 4], 4, ZZ) [3, 2, 4, 0, 0, 0, 0] """ if not f: return f else: return f + [K.zero]*n def gf_rshift(f, n, K): """ Efficiently divide ``f`` by ``x**n``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_rshift >>> gf_rshift([1, 2, 3, 4, 0], 3, ZZ) ([1, 2], [3, 4, 0]) """ if not n: return f, [] else: return f[:-n], f[-n:] def gf_pow(f, n, p, K): """ Compute ``f**n`` in ``GF(p)[x]`` using repeated squaring. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_pow >>> gf_pow([3, 2, 4], 3, 5, ZZ) [2, 4, 4, 2, 2, 1, 4] """ if not n: return [K.one] elif n == 1: return f elif n == 2: return gf_sqr(f, p, K) h = [K.one] while True: if n & 1: h = gf_mul(h, f, p, K) n -= 1 n >>= 1 if not n: break f = gf_sqr(f, p, K) return h def gf_frobenius_monomial_base(g, p, K): """ return the list of ``x**(i*p) mod g in Z_p`` for ``i = 0, .., n - 1`` where ``n = gf_degree(g)`` Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_frobenius_monomial_base >>> g = ZZ.map([1, 0, 2, 1]) >>> gf_frobenius_monomial_base(g, 5, ZZ) [[1], [4, 4, 2], [1, 2]] """ n = gf_degree(g) if n == 0: return [] b = [0]*n b[0] = [1] if p < n: for i in range(1, n): mon = gf_lshift(b[i - 1], p, K) b[i] = gf_rem(mon, g, p, K) elif n > 1: b[1] = gf_pow_mod([K.one, K.zero], p, g, p, K) for i in range(2, n): b[i] = gf_mul(b[i - 1], b[1], p, K) b[i] = gf_rem(b[i], g, p, K) return b def gf_frobenius_map(f, g, b, p, K): """ compute gf_pow_mod(f, p, g, p, K) using the Frobenius map Parameters ========== f, g : polynomials in ``GF(p)[x]`` b : frobenius monomial base p : prime number K : domain Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_frobenius_monomial_base, gf_frobenius_map >>> f = ZZ.map([2, 1, 0, 1]) >>> g = ZZ.map([1, 0, 2, 1]) >>> p = 5 >>> b = gf_frobenius_monomial_base(g, p, ZZ) >>> r = gf_frobenius_map(f, g, b, p, ZZ) >>> gf_frobenius_map(f, g, b, p, ZZ) [4, 0, 3] """ m = gf_degree(g) if gf_degree(f) >= m: f = gf_rem(f, g, p, K) if not f: return [] n = gf_degree(f) sf = [f[-1]] for i in range(1, n + 1): v = gf_mul_ground(b[i], f[n - i], p, K) sf = gf_add(sf, v, p, K) return sf def _gf_pow_pnm1d2(f, n, g, b, p, K): """ utility function for ``gf_edf_zassenhaus`` Compute ``f**((p**n - 1) // 2)`` in ``GF(p)[x]/(g)`` ``f**((p**n - 1) // 2) = (f*f**p*...*f**(p**n - 1))**((p - 1) // 2)`` """ f = gf_rem(f, g, p, K) h = f r = f for i in range(1, n): h = gf_frobenius_map(h, g, b, p, K) r = gf_mul(r, h, p, K) r = gf_rem(r, g, p, K) res = gf_pow_mod(r, (p - 1)//2, g, p, K) return res def gf_pow_mod(f, n, g, p, K): """ Compute ``f**n`` in ``GF(p)[x]/(g)`` using repeated squaring. Given polynomials ``f`` and ``g`` in ``GF(p)[x]`` and a non-negative integer ``n``, efficiently computes ``f**n (mod g)`` i.e. the remainder of ``f**n`` from division by ``g``, using the repeated squaring algorithm. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_pow_mod >>> gf_pow_mod(ZZ.map([3, 2, 4]), 3, ZZ.map([1, 1]), 5, ZZ) [] References ========== .. [1] [Gathen99]_ """ if not n: return [K.one] elif n == 1: return gf_rem(f, g, p, K) elif n == 2: return gf_rem(gf_sqr(f, p, K), g, p, K) h = [K.one] while True: if n & 1: h = gf_mul(h, f, p, K) h = gf_rem(h, g, p, K) n -= 1 n >>= 1 if not n: break f = gf_sqr(f, p, K) f = gf_rem(f, g, p, K) return h def gf_gcd(f, g, p, K): """ Euclidean Algorithm in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_gcd >>> gf_gcd(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ) [1, 3] """ while g: f, g = g, gf_rem(f, g, p, K) return gf_monic(f, p, K)[1] def gf_lcm(f, g, p, K): """ Compute polynomial LCM in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_lcm >>> gf_lcm(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ) [1, 2, 0, 4] """ if not f or not g: return [] h = gf_quo(gf_mul(f, g, p, K), gf_gcd(f, g, p, K), p, K) return gf_monic(h, p, K)[1] def gf_cofactors(f, g, p, K): """ Compute polynomial GCD and cofactors in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_cofactors >>> gf_cofactors(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ) ([1, 3], [3, 3], [2, 1]) """ if not f and not g: return ([], [], []) h = gf_gcd(f, g, p, K) return (h, gf_quo(f, h, p, K), gf_quo(g, h, p, K)) def gf_gcdex(f, g, p, K): """ Extended Euclidean Algorithm in ``GF(p)[x]``. Given polynomials ``f`` and ``g`` in ``GF(p)[x]``, computes polynomials ``s``, ``t`` and ``h``, such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. The typical application of EEA is solving polynomial diophantine equations. Consider polynomials ``f = (x + 7) (x + 1)``, ``g = (x + 7) (x**2 + 1)`` in ``GF(11)[x]``. Application of Extended Euclidean Algorithm gives:: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_gcdex, gf_mul, gf_add >>> s, t, g = gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) >>> s, t, g ([5, 6], [6], [1, 7]) As result we obtained polynomials ``s = 5*x + 6`` and ``t = 6``, and additionally ``gcd(f, g) = x + 7``. This is correct because:: >>> S = gf_mul(s, ZZ.map([1, 8, 7]), 11, ZZ) >>> T = gf_mul(t, ZZ.map([1, 7, 1, 7]), 11, ZZ) >>> gf_add(S, T, 11, ZZ) == [1, 7] True References ========== .. [1] [Gathen99]_ """ if not (f or g): return [K.one], [], [] p0, r0 = gf_monic(f, p, K) p1, r1 = gf_monic(g, p, K) if not f: return [], [K.invert(p1, p)], r1 if not g: return [K.invert(p0, p)], [], r0 s0, s1 = [K.invert(p0, p)], [] t0, t1 = [], [K.invert(p1, p)] while True: Q, R = gf_div(r0, r1, p, K) if not R: break (lc, r1), r0 = gf_monic(R, p, K), r1 inv = K.invert(lc, p) s = gf_sub_mul(s0, s1, Q, p, K) t = gf_sub_mul(t0, t1, Q, p, K) s1, s0 = gf_mul_ground(s, inv, p, K), s1 t1, t0 = gf_mul_ground(t, inv, p, K), t1 return s1, t1, r1 def gf_monic(f, p, K): """ Compute LC and a monic polynomial in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_monic >>> gf_monic(ZZ.map([3, 2, 4]), 5, ZZ) (3, [1, 4, 3]) """ if not f: return K.zero, [] else: lc = f[0] if K.is_one(lc): return lc, list(f) else: return lc, gf_quo_ground(f, lc, p, K) def gf_diff(f, p, K): """ Differentiate polynomial in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_diff >>> gf_diff([3, 2, 4], 5, ZZ) [1, 2] """ df = gf_degree(f) h, n = [K.zero]*df, df for coeff in f[:-1]: coeff *= K(n) coeff %= p if coeff: h[df - n] = coeff n -= 1 return gf_strip(h) def gf_eval(f, a, p, K): """ Evaluate ``f(a)`` in ``GF(p)`` using Horner scheme. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_eval >>> gf_eval([3, 2, 4], 2, 5, ZZ) 0 """ result = K.zero for c in f: result *= a result += c result %= p return result def gf_multi_eval(f, A, p, K): """ Evaluate ``f(a)`` for ``a`` in ``[a_1, ..., a_n]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_multi_eval >>> gf_multi_eval([3, 2, 4], [0, 1, 2, 3, 4], 5, ZZ) [4, 4, 0, 2, 0] """ return [ gf_eval(f, a, p, K) for a in A ] def gf_compose(f, g, p, K): """ Compute polynomial composition ``f(g)`` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_compose >>> gf_compose([3, 2, 4], [2, 2, 2], 5, ZZ) [2, 4, 0, 3, 0] """ if len(g) <= 1: return gf_strip([gf_eval(f, gf_LC(g, K), p, K)]) if not f: return [] h = [f[0]] for c in f[1:]: h = gf_mul(h, g, p, K) h = gf_add_ground(h, c, p, K) return h def gf_compose_mod(g, h, f, p, K): """ Compute polynomial composition ``g(h)`` in ``GF(p)[x]/(f)``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_compose_mod >>> gf_compose_mod(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 2]), ZZ.map([4, 3]), 5, ZZ) [4] """ if not g: return [] comp = [g[0]] for a in g[1:]: comp = gf_mul(comp, h, p, K) comp = gf_add_ground(comp, a, p, K) comp = gf_rem(comp, f, p, K) return comp def gf_trace_map(a, b, c, n, f, p, K): """ Compute polynomial trace map in ``GF(p)[x]/(f)``. Given a polynomial ``f`` in ``GF(p)[x]``, polynomials ``a``, ``b``, ``c`` in the quotient ring ``GF(p)[x]/(f)`` such that ``b = c**t (mod f)`` for some positive power ``t`` of ``p``, and a positive integer ``n``, returns a mapping:: a -> a**t**n, a + a**t + a**t**2 + ... + a**t**n (mod f) In factorization context, ``b = x**p mod f`` and ``c = x mod f``. This way we can efficiently compute trace polynomials in equal degree factorization routine, much faster than with other methods, like iterated Frobenius algorithm, for large degrees. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_trace_map >>> gf_trace_map([1, 2], [4, 4], [1, 1], 4, [3, 2, 4], 5, ZZ) ([1, 3], [1, 3]) References ========== .. [1] [Gathen92]_ """ u = gf_compose_mod(a, b, f, p, K) v = b if n & 1: U = gf_add(a, u, p, K) V = b else: U = a V = c n >>= 1 while n: u = gf_add(u, gf_compose_mod(u, v, f, p, K), p, K) v = gf_compose_mod(v, v, f, p, K) if n & 1: U = gf_add(U, gf_compose_mod(u, V, f, p, K), p, K) V = gf_compose_mod(v, V, f, p, K) n >>= 1 return gf_compose_mod(a, V, f, p, K), U def _gf_trace_map(f, n, g, b, p, K): """ utility for ``gf_edf_shoup`` """ f = gf_rem(f, g, p, K) h = f r = f for i in range(1, n): h = gf_frobenius_map(h, g, b, p, K) r = gf_add(r, h, p, K) r = gf_rem(r, g, p, K) return r def gf_random(n, p, K): """ Generate a random polynomial in ``GF(p)[x]`` of degree ``n``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_random >>> gf_random(10, 5, ZZ) #doctest: +SKIP [1, 2, 3, 2, 1, 1, 1, 2, 0, 4, 2] """ return [K.one] + [ K(int(uniform(0, p))) for i in range(0, n) ] def gf_irreducible(n, p, K): """ Generate random irreducible polynomial of degree ``n`` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_irreducible >>> gf_irreducible(10, 5, ZZ) #doctest: +SKIP [1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4] """ while True: f = gf_random(n, p, K) if gf_irreducible_p(f, p, K): return f def gf_irred_p_ben_or(f, p, K): """ Ben-Or's polynomial irreducibility test over finite fields. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_irred_p_ben_or >>> gf_irred_p_ben_or(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ) True >>> gf_irred_p_ben_or(ZZ.map([3, 2, 4]), 5, ZZ) False """ n = gf_degree(f) if n <= 1: return True _, f = gf_monic(f, p, K) if n < 5: H = h = gf_pow_mod([K.one, K.zero], p, f, p, K) for i in range(0, n//2): g = gf_sub(h, [K.one, K.zero], p, K) if gf_gcd(f, g, p, K) == [K.one]: h = gf_compose_mod(h, H, f, p, K) else: return False else: b = gf_frobenius_monomial_base(f, p, K) H = h = gf_frobenius_map([K.one, K.zero], f, b, p, K) for i in range(0, n//2): g = gf_sub(h, [K.one, K.zero], p, K) if gf_gcd(f, g, p, K) == [K.one]: h = gf_frobenius_map(h, f, b, p, K) else: return False return True def gf_irred_p_rabin(f, p, K): """ Rabin's polynomial irreducibility test over finite fields. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_irred_p_rabin >>> gf_irred_p_rabin(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ) True >>> gf_irred_p_rabin(ZZ.map([3, 2, 4]), 5, ZZ) False """ n = gf_degree(f) if n <= 1: return True _, f = gf_monic(f, p, K) x = [K.one, K.zero] from sympy.ntheory import factorint indices = { n//d for d in factorint(n) } b = gf_frobenius_monomial_base(f, p, K) h = b[1] for i in range(1, n): if i in indices: g = gf_sub(h, x, p, K) if gf_gcd(f, g, p, K) != [K.one]: return False h = gf_frobenius_map(h, f, b, p, K) return h == x _irred_methods = { 'ben-or': gf_irred_p_ben_or, 'rabin': gf_irred_p_rabin, } def gf_irreducible_p(f, p, K): """ Test irreducibility of a polynomial ``f`` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_irreducible_p >>> gf_irreducible_p(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ) True >>> gf_irreducible_p(ZZ.map([3, 2, 4]), 5, ZZ) False """ method = query('GF_IRRED_METHOD') if method is not None: irred = _irred_methods[method](f, p, K) else: irred = gf_irred_p_rabin(f, p, K) return irred def gf_sqf_p(f, p, K): """ Return ``True`` if ``f`` is square-free in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sqf_p >>> gf_sqf_p(ZZ.map([3, 2, 4]), 5, ZZ) True >>> gf_sqf_p(ZZ.map([2, 4, 4, 2, 2, 1, 4]), 5, ZZ) False """ _, f = gf_monic(f, p, K) if not f: return True else: return gf_gcd(f, gf_diff(f, p, K), p, K) == [K.one] def gf_sqf_part(f, p, K): """ Return square-free part of a ``GF(p)[x]`` polynomial. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sqf_part >>> gf_sqf_part(ZZ.map([1, 1, 3, 0, 1, 0, 2, 2, 1]), 5, ZZ) [1, 4, 3] """ _, sqf = gf_sqf_list(f, p, K) g = [K.one] for f, _ in sqf: g = gf_mul(g, f, p, K) return g def gf_sqf_list(f, p, K, all=False): """ Return the square-free decomposition of a ``GF(p)[x]`` polynomial. Given a polynomial ``f`` in ``GF(p)[x]``, returns the leading coefficient of ``f`` and a square-free decomposition ``f_1**e_1 f_2**e_2 ... f_k**e_k`` such that all ``f_i`` are monic polynomials and ``(f_i, f_j)`` for ``i != j`` are co-prime and ``e_1 ... e_k`` are given in increasing order. All trivial terms (i.e. ``f_i = 1``) are not included in the output. Consider polynomial ``f = x**11 + 1`` over ``GF(11)[x]``:: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import ( ... gf_from_dict, gf_diff, gf_sqf_list, gf_pow, ... ) ... # doctest: +NORMALIZE_WHITESPACE >>> f = gf_from_dict({11: ZZ(1), 0: ZZ(1)}, 11, ZZ) Note that ``f'(x) = 0``:: >>> gf_diff(f, 11, ZZ) [] This phenomenon does not happen in characteristic zero. However we can still compute square-free decomposition of ``f`` using ``gf_sqf()``:: >>> gf_sqf_list(f, 11, ZZ) (1, [([1, 1], 11)]) We obtained factorization ``f = (x + 1)**11``. This is correct because:: >>> gf_pow([1, 1], 11, 11, ZZ) == f True References ========== .. [1] [Geddes92]_ """ n, sqf, factors, r = 1, False, [], int(p) lc, f = gf_monic(f, p, K) if gf_degree(f) < 1: return lc, [] while True: F = gf_diff(f, p, K) if F != []: g = gf_gcd(f, F, p, K) h = gf_quo(f, g, p, K) i = 1 while h != [K.one]: G = gf_gcd(g, h, p, K) H = gf_quo(h, G, p, K) if gf_degree(H) > 0: factors.append((H, i*n)) g, h, i = gf_quo(g, G, p, K), G, i + 1 if g == [K.one]: sqf = True else: f = g if not sqf: d = gf_degree(f) // r for i in range(0, d + 1): f[i] = f[i*r] f, n = f[:d + 1], n*r else: break if all: raise ValueError("'all=True' is not supported yet") return lc, factors def gf_Qmatrix(f, p, K): """ Calculate Berlekamp's ``Q`` matrix. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_Qmatrix >>> gf_Qmatrix([3, 2, 4], 5, ZZ) [[1, 0], [3, 4]] >>> gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ) [[1, 0, 0, 0], [0, 4, 0, 0], [0, 0, 1, 0], [0, 0, 0, 4]] """ n, r = gf_degree(f), int(p) q = [K.one] + [K.zero]*(n - 1) Q = [list(q)] + [[]]*(n - 1) for i in range(1, (n - 1)*r + 1): qq, c = [(-q[-1]*f[-1]) % p], q[-1] for j in range(1, n): qq.append((q[j - 1] - c*f[-j - 1]) % p) if not (i % r): Q[i//r] = list(qq) q = qq return Q def gf_Qbasis(Q, p, K): """ Compute a basis of the kernel of ``Q``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_Qmatrix, gf_Qbasis >>> gf_Qbasis(gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ), 5, ZZ) [[1, 0, 0, 0], [0, 0, 1, 0]] >>> gf_Qbasis(gf_Qmatrix([3, 2, 4], 5, ZZ), 5, ZZ) [[1, 0]] """ Q, n = [ list(q) for q in Q ], len(Q) for k in range(0, n): Q[k][k] = (Q[k][k] - K.one) % p for k in range(0, n): for i in range(k, n): if Q[k][i]: break else: continue inv = K.invert(Q[k][i], p) for j in range(0, n): Q[j][i] = (Q[j][i]*inv) % p for j in range(0, n): t = Q[j][k] Q[j][k] = Q[j][i] Q[j][i] = t for i in range(0, n): if i != k: q = Q[k][i] for j in range(0, n): Q[j][i] = (Q[j][i] - Q[j][k]*q) % p for i in range(0, n): for j in range(0, n): if i == j: Q[i][j] = (K.one - Q[i][j]) % p else: Q[i][j] = (-Q[i][j]) % p basis = [] for q in Q: if any(q): basis.append(q) return basis def gf_berlekamp(f, p, K): """ Factor a square-free ``f`` in ``GF(p)[x]`` for small ``p``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_berlekamp >>> gf_berlekamp([1, 0, 0, 0, 1], 5, ZZ) [[1, 0, 2], [1, 0, 3]] """ Q = gf_Qmatrix(f, p, K) V = gf_Qbasis(Q, p, K) for i, v in enumerate(V): V[i] = gf_strip(list(reversed(v))) factors = [f] for k in range(1, len(V)): for f in list(factors): s = K.zero while s < p: g = gf_sub_ground(V[k], s, p, K) h = gf_gcd(f, g, p, K) if h != [K.one] and h != f: factors.remove(f) f = gf_quo(f, h, p, K) factors.extend([f, h]) if len(factors) == len(V): return _sort_factors(factors, multiple=False) s += K.one return _sort_factors(factors, multiple=False) def gf_ddf_zassenhaus(f, p, K): """ Cantor-Zassenhaus: Deterministic Distinct Degree Factorization Given a monic square-free polynomial ``f`` in ``GF(p)[x]``, computes partial distinct degree factorization ``f_1 ... f_d`` of ``f`` where ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0`` is an argument to the equal degree factorization routine. Consider the polynomial ``x**15 - 1`` in ``GF(11)[x]``:: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_from_dict >>> f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ) Distinct degree factorization gives:: >>> from sympy.polys.galoistools import gf_ddf_zassenhaus >>> gf_ddf_zassenhaus(f, 11, ZZ) [([1, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)] which means ``x**15 - 1 = (x**5 - 1) (x**10 + x**5 + 1)``. To obtain factorization into irreducibles, use equal degree factorization procedure (EDF) with each of the factors. References ========== .. [1] [Gathen99]_ .. [2] [Geddes92]_ """ i, g, factors = 1, [K.one, K.zero], [] b = gf_frobenius_monomial_base(f, p, K) while 2*i <= gf_degree(f): g = gf_frobenius_map(g, f, b, p, K) h = gf_gcd(f, gf_sub(g, [K.one, K.zero], p, K), p, K) if h != [K.one]: factors.append((h, i)) f = gf_quo(f, h, p, K) g = gf_rem(g, f, p, K) b = gf_frobenius_monomial_base(f, p, K) i += 1 if f != [K.one]: return factors + [(f, gf_degree(f))] else: return factors def gf_edf_zassenhaus(f, n, p, K): """ Cantor-Zassenhaus: Probabilistic Equal Degree Factorization Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and an integer ``n``, such that ``n`` divides ``deg(f)``, returns all irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``. EDF procedure gives complete factorization over Galois fields. Consider the square-free polynomial ``f = x**3 + x**2 + x + 1`` in ``GF(5)[x]``. Let's compute its irreducible factors of degree one:: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_edf_zassenhaus >>> gf_edf_zassenhaus([1,1,1,1], 1, 5, ZZ) [[1, 1], [1, 2], [1, 3]] Notes ===== The case p == 2 is handled by Cohen's Algorithm 3.4.8. The case p odd is as in Geddes Algorithm 8.9 (or Cohen's Algorithm 3.4.6). References ========== .. [1] [Gathen99]_ .. [2] [Geddes92]_ Algorithm 8.9 .. [3] [Cohen93]_ Algorithm 3.4.8 """ factors = [f] if gf_degree(f) <= n: return factors N = gf_degree(f) // n if p != 2: b = gf_frobenius_monomial_base(f, p, K) t = [K.one, K.zero] while len(factors) < N: if p == 2: h = r = t for i in range(n - 1): r = gf_pow_mod(r, 2, f, p, K) h = gf_add(h, r, p, K) g = gf_gcd(f, h, p, K) t += [K.zero, K.zero] else: r = gf_random(2 * n - 1, p, K) h = _gf_pow_pnm1d2(r, n, f, b, p, K) g = gf_gcd(f, gf_sub_ground(h, K.one, p, K), p, K) if g != [K.one] and g != f: factors = gf_edf_zassenhaus(g, n, p, K) \ + gf_edf_zassenhaus(gf_quo(f, g, p, K), n, p, K) return _sort_factors(factors, multiple=False) def gf_ddf_shoup(f, p, K): """ Kaltofen-Shoup: Deterministic Distinct Degree Factorization Given a monic square-free polynomial ``f`` in ``GF(p)[x]``, computes partial distinct degree factorization ``f_1,...,f_d`` of ``f`` where ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0`` is an argument to the equal degree factorization routine. This algorithm is an improved version of Zassenhaus algorithm for large ``deg(f)`` and modulus ``p`` (especially for ``deg(f) ~ lg(p)``). Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_ddf_shoup, gf_from_dict >>> f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ) >>> gf_ddf_shoup(f, 3, ZZ) [([1, 1, 0], 1), ([1, 1, 0, 1, 2], 2)] References ========== .. [1] [Kaltofen98]_ .. [2] [Shoup95]_ .. [3] [Gathen92]_ """ n = gf_degree(f) k = int(_ceil(_sqrt(n//2))) b = gf_frobenius_monomial_base(f, p, K) h = gf_frobenius_map([K.one, K.zero], f, b, p, K) # U[i] = x**(p**i) U = [[K.one, K.zero], h] + [K.zero]*(k - 1) for i in range(2, k + 1): U[i] = gf_frobenius_map(U[i-1], f, b, p, K) h, U = U[k], U[:k] # V[i] = x**(p**(k*(i+1))) V = [h] + [K.zero]*(k - 1) for i in range(1, k): V[i] = gf_compose_mod(V[i - 1], h, f, p, K) factors = [] for i, v in enumerate(V): h, j = [K.one], k - 1 for u in U: g = gf_sub(v, u, p, K) h = gf_mul(h, g, p, K) h = gf_rem(h, f, p, K) g = gf_gcd(f, h, p, K) f = gf_quo(f, g, p, K) for u in reversed(U): h = gf_sub(v, u, p, K) F = gf_gcd(g, h, p, K) if F != [K.one]: factors.append((F, k*(i + 1) - j)) g, j = gf_quo(g, F, p, K), j - 1 if f != [K.one]: factors.append((f, gf_degree(f))) return factors def gf_edf_shoup(f, n, p, K): """ Gathen-Shoup: Probabilistic Equal Degree Factorization Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and integer ``n`` such that ``n`` divides ``deg(f)``, returns all irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``. This is a complete factorization over Galois fields. This algorithm is an improved version of Zassenhaus algorithm for large ``deg(f)`` and modulus ``p`` (especially for ``deg(f) ~ lg(p)``). Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_edf_shoup >>> gf_edf_shoup(ZZ.map([1, 2837, 2277]), 1, 2917, ZZ) [[1, 852], [1, 1985]] References ========== .. [1] [Shoup91]_ .. [2] [Gathen92]_ """ N, q = gf_degree(f), int(p) if not N: return [] if N <= n: return [f] factors, x = [f], [K.one, K.zero] r = gf_random(N - 1, p, K) if p == 2: h = gf_pow_mod(x, q, f, p, K) H = gf_trace_map(r, h, x, n - 1, f, p, K)[1] h1 = gf_gcd(f, H, p, K) h2 = gf_quo(f, h1, p, K) factors = gf_edf_shoup(h1, n, p, K) \ + gf_edf_shoup(h2, n, p, K) else: b = gf_frobenius_monomial_base(f, p, K) H = _gf_trace_map(r, n, f, b, p, K) h = gf_pow_mod(H, (q - 1)//2, f, p, K) h1 = gf_gcd(f, h, p, K) h2 = gf_gcd(f, gf_sub_ground(h, K.one, p, K), p, K) h3 = gf_quo(f, gf_mul(h1, h2, p, K), p, K) factors = gf_edf_shoup(h1, n, p, K) \ + gf_edf_shoup(h2, n, p, K) \ + gf_edf_shoup(h3, n, p, K) return _sort_factors(factors, multiple=False) def gf_zassenhaus(f, p, K): """ Factor a square-free ``f`` in ``GF(p)[x]`` for medium ``p``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_zassenhaus >>> gf_zassenhaus(ZZ.map([1, 4, 3]), 5, ZZ) [[1, 1], [1, 3]] """ factors = [] for factor, n in gf_ddf_zassenhaus(f, p, K): factors += gf_edf_zassenhaus(factor, n, p, K) return _sort_factors(factors, multiple=False) def gf_shoup(f, p, K): """ Factor a square-free ``f`` in ``GF(p)[x]`` for large ``p``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_shoup >>> gf_shoup(ZZ.map([1, 4, 3]), 5, ZZ) [[1, 1], [1, 3]] """ factors = [] for factor, n in gf_ddf_shoup(f, p, K): factors += gf_edf_shoup(factor, n, p, K) return _sort_factors(factors, multiple=False) _factor_methods = { 'berlekamp': gf_berlekamp, # ``p`` : small 'zassenhaus': gf_zassenhaus, # ``p`` : medium 'shoup': gf_shoup, # ``p`` : large } def gf_factor_sqf(f, p, K, method=None): """ Factor a square-free polynomial ``f`` in ``GF(p)[x]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_factor_sqf >>> gf_factor_sqf(ZZ.map([3, 2, 4]), 5, ZZ) (3, [[1, 1], [1, 3]]) """ lc, f = gf_monic(f, p, K) if gf_degree(f) < 1: return lc, [] method = method or query('GF_FACTOR_METHOD') if method is not None: factors = _factor_methods[method](f, p, K) else: factors = gf_zassenhaus(f, p, K) return lc, factors def gf_factor(f, p, K): """ Factor (non square-free) polynomials in ``GF(p)[x]``. Given a possibly non square-free polynomial ``f`` in ``GF(p)[x]``, returns its complete factorization into irreducibles:: f_1(x)**e_1 f_2(x)**e_2 ... f_d(x)**e_d where each ``f_i`` is a monic polynomial and ``gcd(f_i, f_j) == 1``, for ``i != j``. The result is given as a tuple consisting of the leading coefficient of ``f`` and a list of factors of ``f`` with their multiplicities. The algorithm proceeds by first computing square-free decomposition of ``f`` and then iteratively factoring each of square-free factors. Consider a non square-free polynomial ``f = (7*x + 1) (x + 2)**2`` in ``GF(11)[x]``. We obtain its factorization into irreducibles as follows:: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_factor >>> gf_factor(ZZ.map([5, 2, 7, 2]), 11, ZZ) (5, [([1, 2], 1), ([1, 8], 2)]) We arrived with factorization ``f = 5 (x + 2) (x + 8)**2``. We did not recover the exact form of the input polynomial because we requested to get monic factors of ``f`` and its leading coefficient separately. Square-free factors of ``f`` can be factored into irreducibles over ``GF(p)`` using three very different methods: Berlekamp efficient for very small values of ``p`` (usually ``p < 25``) Cantor-Zassenhaus efficient on average input and with "typical" ``p`` Shoup-Kaltofen-Gathen efficient with very large inputs and modulus If you want to use a specific factorization method, instead of the default one, set ``GF_FACTOR_METHOD`` with one of ``berlekamp``, ``zassenhaus`` or ``shoup`` values. References ========== .. [1] [Gathen99]_ """ lc, f = gf_monic(f, p, K) if gf_degree(f) < 1: return lc, [] factors = [] for g, n in gf_sqf_list(f, p, K)[1]: for h in gf_factor_sqf(g, p, K)[1]: factors.append((h, n)) return lc, _sort_factors(factors) def gf_value(f, a): """ Value of polynomial 'f' at 'a' in field R. Examples ======== >>> from sympy.polys.galoistools import gf_value >>> gf_value([1, 7, 2, 4], 11) 2204 """ result = 0 for c in f: result *= a result += c return result def linear_congruence(a, b, m): """ Returns the values of x satisfying a*x congruent b mod(m) Here m is positive integer and a, b are natural numbers. This function returns only those values of x which are distinct mod(m). Examples ======== >>> from sympy.polys.galoistools import linear_congruence >>> linear_congruence(3, 12, 15) [4, 9, 14] There are 3 solutions distinct mod(15) since gcd(a, m) = gcd(3, 15) = 3. References ========== .. [1] https://en.wikipedia.org/wiki/Linear_congruence_theorem """ from sympy.polys.polytools import gcdex if a % m == 0: if b % m == 0: return list(range(m)) else: return [] r, _, g = gcdex(a, m) if b % g != 0: return [] return [(r * b // g + t * m // g) % m for t in range(g)] def _raise_mod_power(x, s, p, f): """ Used in gf_csolve to generate solutions of f(x) cong 0 mod(p**(s + 1)) from the solutions of f(x) cong 0 mod(p**s). Examples ======== >>> from sympy.polys.galoistools import _raise_mod_power >>> from sympy.polys.galoistools import csolve_prime These is the solutions of f(x) = x**2 + x + 7 cong 0 mod(3) >>> f = [1, 1, 7] >>> csolve_prime(f, 3) [1] >>> [ i for i in range(3) if not (i**2 + i + 7) % 3] [1] The solutions of f(x) cong 0 mod(9) are constructed from the values returned from _raise_mod_power: >>> x, s, p = 1, 1, 3 >>> V = _raise_mod_power(x, s, p, f) >>> [x + v * p**s for v in V] [1, 4, 7] And these are confirmed with the following: >>> [ i for i in range(3**2) if not (i**2 + i + 7) % 3**2] [1, 4, 7] """ from sympy.polys.domains import ZZ f_f = gf_diff(f, p, ZZ) alpha = gf_value(f_f, x) beta = - gf_value(f, x) // p**s return linear_congruence(alpha, beta, p) def csolve_prime(f, p, e=1): """ Solutions of f(x) congruent 0 mod(p**e). Examples ======== >>> from sympy.polys.galoistools import csolve_prime >>> csolve_prime([1, 1, 7], 3, 1) [1] >>> csolve_prime([1, 1, 7], 3, 2) [1, 4, 7] Solutions [7, 4, 1] (mod 3**2) are generated by ``_raise_mod_power()`` from solution [1] (mod 3). """ from sympy.polys.domains import ZZ X1 = [i for i in range(p) if gf_eval(f, i, p, ZZ) == 0] if e == 1: return X1 X = [] S = list(zip(X1, [1]*len(X1))) while S: x, s = S.pop() if s == e: X.append(x) else: s1 = s + 1 ps = p**s S.extend([(x + v*ps, s1) for v in _raise_mod_power(x, s, p, f)]) return sorted(X) def gf_csolve(f, n): """ To solve f(x) congruent 0 mod(n). n is divided into canonical factors and f(x) cong 0 mod(p**e) will be solved for each factor. Applying the Chinese Remainder Theorem to the results returns the final answers. Examples ======== Solve [1, 1, 7] congruent 0 mod(189): >>> from sympy.polys.galoistools import gf_csolve >>> gf_csolve([1, 1, 7], 189) [13, 49, 76, 112, 139, 175] References ========== .. [1] 'An introduction to the Theory of Numbers' 5th Edition by Ivan Niven, Zuckerman and Montgomery. """ from sympy.polys.domains import ZZ from sympy.ntheory import factorint P = factorint(n) X = [csolve_prime(f, p, e) for p, e in P.items()] pools = list(map(tuple, X)) perms = [[]] for pool in pools: perms = [x + [y] for x in perms for y in pool] dist_factors = [pow(p, e) for p, e in P.items()] return sorted([gf_crt(per, dist_factors, ZZ) for per in perms])
3e735f67d570416564f4fbea635f243bae8a8bbdc9a15f8031273f330c8cbf59
"""Groebner bases algorithms. """ from sympy.core.symbol import Dummy from sympy.polys.monomials import monomial_mul, monomial_lcm, monomial_divides, term_div from sympy.polys.orderings import lex from sympy.polys.polyerrors import DomainError from sympy.polys.polyconfig import query def groebner(seq, ring, method=None): """ Computes Groebner basis for a set of polynomials in `K[X]`. Wrapper around the (default) improved Buchberger and the other algorithms for computing Groebner bases. The choice of algorithm can be changed via ``method`` argument or :func:`sympy.polys.polyconfig.setup`, where ``method`` can be either ``buchberger`` or ``f5b``. """ if method is None: method = query('groebner') _groebner_methods = { 'buchberger': _buchberger, 'f5b': _f5b, } try: _groebner = _groebner_methods[method] except KeyError: raise ValueError("'%s' is not a valid Groebner bases algorithm (valid are 'buchberger' and 'f5b')" % method) domain, orig = ring.domain, None if not domain.is_Field or not domain.has_assoc_Field: try: orig, ring = ring, ring.clone(domain=domain.get_field()) except DomainError: raise DomainError("Cannot compute a Groebner basis over %s" % domain) else: seq = [ s.set_ring(ring) for s in seq ] G = _groebner(seq, ring) if orig is not None: G = [ g.clear_denoms()[1].set_ring(orig) for g in G ] return G def _buchberger(f, ring): """ Computes Groebner basis for a set of polynomials in `K[X]`. Given a set of multivariate polynomials `F`, finds another set `G`, such that Ideal `F = Ideal G` and `G` is a reduced Groebner basis. The resulting basis is unique and has monic generators if the ground domains is a field. Otherwise the result is non-unique but Groebner bases over e.g. integers can be computed (if the input polynomials are monic). Groebner bases can be used to choose specific generators for a polynomial ideal. Because these bases are unique you can check for ideal equality by comparing the Groebner bases. To see if one polynomial lies in an ideal, divide by the elements in the base and see if the remainder vanishes. They can also be used to solve systems of polynomial equations as, by choosing lexicographic ordering, you can eliminate one variable at a time, provided that the ideal is zero-dimensional (finite number of solutions). Notes ===== Algorithm used: an improved version of Buchberger's algorithm as presented in T. Becker, V. Weispfenning, Groebner Bases: A Computational Approach to Commutative Algebra, Springer, 1993, page 232. References ========== .. [1] [Bose03]_ .. [2] [Giovini91]_ .. [3] [Ajwa95]_ .. [4] [Cox97]_ """ order = ring.order monomial_mul = ring.monomial_mul monomial_div = ring.monomial_div monomial_lcm = ring.monomial_lcm def select(P): # normal selection strategy # select the pair with minimum LCM(LM(f), LM(g)) pr = min(P, key=lambda pair: order(monomial_lcm(f[pair[0]].LM, f[pair[1]].LM))) return pr def normal(g, J): h = g.rem([ f[j] for j in J ]) if not h: return None else: h = h.monic() if h not in I: I[h] = len(f) f.append(h) return h.LM, I[h] def update(G, B, ih): # update G using the set of critical pairs B and h # [BW] page 230 h = f[ih] mh = h.LM # filter new pairs (h, g), g in G C = G.copy() D = set() while C: # select a pair (h, g) by popping an element from C ig = C.pop() g = f[ig] mg = g.LM LCMhg = monomial_lcm(mh, mg) def lcm_divides(ip): # LCM(LM(h), LM(p)) divides LCM(LM(h), LM(g)) m = monomial_lcm(mh, f[ip].LM) return monomial_div(LCMhg, m) # HT(h) and HT(g) disjoint: mh*mg == LCMhg if monomial_mul(mh, mg) == LCMhg or ( not any(lcm_divides(ipx) for ipx in C) and not any(lcm_divides(pr[1]) for pr in D)): D.add((ih, ig)) E = set() while D: # select h, g from D (h the same as above) ih, ig = D.pop() mg = f[ig].LM LCMhg = monomial_lcm(mh, mg) if not monomial_mul(mh, mg) == LCMhg: E.add((ih, ig)) # filter old pairs B_new = set() while B: # select g1, g2 from B (-> CP) ig1, ig2 = B.pop() mg1 = f[ig1].LM mg2 = f[ig2].LM LCM12 = monomial_lcm(mg1, mg2) # if HT(h) does not divide lcm(HT(g1), HT(g2)) if not monomial_div(LCM12, mh) or \ monomial_lcm(mg1, mh) == LCM12 or \ monomial_lcm(mg2, mh) == LCM12: B_new.add((ig1, ig2)) B_new |= E # filter polynomials G_new = set() while G: ig = G.pop() mg = f[ig].LM if not monomial_div(mg, mh): G_new.add(ig) G_new.add(ih) return G_new, B_new # end of update ################################ if not f: return [] # replace f with a reduced list of initial polynomials; see [BW] page 203 f1 = f[:] while True: f = f1[:] f1 = [] for i in range(len(f)): p = f[i] r = p.rem(f[:i]) if r: f1.append(r.monic()) if f == f1: break I = {} # ip = I[p]; p = f[ip] F = set() # set of indices of polynomials G = set() # set of indices of intermediate would-be Groebner basis CP = set() # set of pairs of indices of critical pairs for i, h in enumerate(f): I[h] = i F.add(i) ##################################### # algorithm GROEBNERNEWS2 in [BW] page 232 while F: # select p with minimum monomial according to the monomial ordering h = min([f[x] for x in F], key=lambda f: order(f.LM)) ih = I[h] F.remove(ih) G, CP = update(G, CP, ih) # count the number of critical pairs which reduce to zero reductions_to_zero = 0 while CP: ig1, ig2 = select(CP) CP.remove((ig1, ig2)) h = spoly(f[ig1], f[ig2], ring) # ordering divisors is on average more efficient [Cox] page 111 G1 = sorted(G, key=lambda g: order(f[g].LM)) ht = normal(h, G1) if ht: G, CP = update(G, CP, ht[1]) else: reductions_to_zero += 1 ###################################### # now G is a Groebner basis; reduce it Gr = set() for ig in G: ht = normal(f[ig], G - {ig}) if ht: Gr.add(ht[1]) Gr = [f[ig] for ig in Gr] # order according to the monomial ordering Gr = sorted(Gr, key=lambda f: order(f.LM), reverse=True) return Gr def spoly(p1, p2, ring): """ Compute LCM(LM(p1), LM(p2))/LM(p1)*p1 - LCM(LM(p1), LM(p2))/LM(p2)*p2 This is the S-poly provided p1 and p2 are monic """ LM1 = p1.LM LM2 = p2.LM LCM12 = ring.monomial_lcm(LM1, LM2) m1 = ring.monomial_div(LCM12, LM1) m2 = ring.monomial_div(LCM12, LM2) s1 = p1.mul_monom(m1) s2 = p2.mul_monom(m2) s = s1 - s2 return s # F5B # convenience functions def Sign(f): return f[0] def Polyn(f): return f[1] def Num(f): return f[2] def sig(monomial, index): return (monomial, index) def lbp(signature, polynomial, number): return (signature, polynomial, number) # signature functions def sig_cmp(u, v, order): """ Compare two signatures by extending the term order to K[X]^n. u < v iff - the index of v is greater than the index of u or - the index of v is equal to the index of u and u[0] < v[0] w.r.t. order u > v otherwise """ if u[1] > v[1]: return -1 if u[1] == v[1]: #if u[0] == v[0]: # return 0 if order(u[0]) < order(v[0]): return -1 return 1 def sig_key(s, order): """ Key for comparing two signatures. s = (m, k), t = (n, l) s < t iff [k > l] or [k == l and m < n] s > t otherwise """ return (-s[1], order(s[0])) def sig_mult(s, m): """ Multiply a signature by a monomial. The product of a signature (m, i) and a monomial n is defined as (m * t, i). """ return sig(monomial_mul(s[0], m), s[1]) # labeled polynomial functions def lbp_sub(f, g): """ Subtract labeled polynomial g from f. The signature and number of the difference of f and g are signature and number of the maximum of f and g, w.r.t. lbp_cmp. """ if sig_cmp(Sign(f), Sign(g), Polyn(f).ring.order) < 0: max_poly = g else: max_poly = f ret = Polyn(f) - Polyn(g) return lbp(Sign(max_poly), ret, Num(max_poly)) def lbp_mul_term(f, cx): """ Multiply a labeled polynomial with a term. The product of a labeled polynomial (s, p, k) by a monomial is defined as (m * s, m * p, k). """ return lbp(sig_mult(Sign(f), cx[0]), Polyn(f).mul_term(cx), Num(f)) def lbp_cmp(f, g): """ Compare two labeled polynomials. f < g iff - Sign(f) < Sign(g) or - Sign(f) == Sign(g) and Num(f) > Num(g) f > g otherwise """ if sig_cmp(Sign(f), Sign(g), Polyn(f).ring.order) == -1: return -1 if Sign(f) == Sign(g): if Num(f) > Num(g): return -1 #if Num(f) == Num(g): # return 0 return 1 def lbp_key(f): """ Key for comparing two labeled polynomials. """ return (sig_key(Sign(f), Polyn(f).ring.order), -Num(f)) # algorithm and helper functions def critical_pair(f, g, ring): """ Compute the critical pair corresponding to two labeled polynomials. A critical pair is a tuple (um, f, vm, g), where um and vm are terms such that um * f - vm * g is the S-polynomial of f and g (so, wlog assume um * f > vm * g). For performance sake, a critical pair is represented as a tuple (Sign(um * f), um, f, Sign(vm * g), vm, g), since um * f creates a new, relatively expensive object in memory, whereas Sign(um * f) and um are lightweight and f (in the tuple) is a reference to an already existing object in memory. """ domain = ring.domain ltf = Polyn(f).LT ltg = Polyn(g).LT lt = (monomial_lcm(ltf[0], ltg[0]), domain.one) um = term_div(lt, ltf, domain) vm = term_div(lt, ltg, domain) # The full information is not needed (now), so only the product # with the leading term is considered: fr = lbp_mul_term(lbp(Sign(f), Polyn(f).leading_term(), Num(f)), um) gr = lbp_mul_term(lbp(Sign(g), Polyn(g).leading_term(), Num(g)), vm) # return in proper order, such that the S-polynomial is just # u_first * f_first - u_second * f_second: if lbp_cmp(fr, gr) == -1: return (Sign(gr), vm, g, Sign(fr), um, f) else: return (Sign(fr), um, f, Sign(gr), vm, g) def cp_cmp(c, d): """ Compare two critical pairs c and d. c < d iff - lbp(c[0], _, Num(c[2]) < lbp(d[0], _, Num(d[2])) (this corresponds to um_c * f_c and um_d * f_d) or - lbp(c[0], _, Num(c[2]) >< lbp(d[0], _, Num(d[2])) and lbp(c[3], _, Num(c[5])) < lbp(d[3], _, Num(d[5])) (this corresponds to vm_c * g_c and vm_d * g_d) c > d otherwise """ zero = Polyn(c[2]).ring.zero c0 = lbp(c[0], zero, Num(c[2])) d0 = lbp(d[0], zero, Num(d[2])) r = lbp_cmp(c0, d0) if r == -1: return -1 if r == 0: c1 = lbp(c[3], zero, Num(c[5])) d1 = lbp(d[3], zero, Num(d[5])) r = lbp_cmp(c1, d1) if r == -1: return -1 #if r == 0: # return 0 return 1 def cp_key(c, ring): """ Key for comparing critical pairs. """ return (lbp_key(lbp(c[0], ring.zero, Num(c[2]))), lbp_key(lbp(c[3], ring.zero, Num(c[5])))) def s_poly(cp): """ Compute the S-polynomial of a critical pair. The S-polynomial of a critical pair cp is cp[1] * cp[2] - cp[4] * cp[5]. """ return lbp_sub(lbp_mul_term(cp[2], cp[1]), lbp_mul_term(cp[5], cp[4])) def is_rewritable_or_comparable(sign, num, B): """ Check if a labeled polynomial is redundant by checking if its signature and number imply rewritability or comparability. (sign, num) is comparable if there exists a labeled polynomial h in B, such that sign[1] (the index) is less than Sign(h)[1] and sign[0] is divisible by the leading monomial of h. (sign, num) is rewritable if there exists a labeled polynomial h in B, such thatsign[1] is equal to Sign(h)[1], num < Num(h) and sign[0] is divisible by Sign(h)[0]. """ for h in B: # comparable if sign[1] < Sign(h)[1]: if monomial_divides(Polyn(h).LM, sign[0]): return True # rewritable if sign[1] == Sign(h)[1]: if num < Num(h): if monomial_divides(Sign(h)[0], sign[0]): return True return False def f5_reduce(f, B): """ F5-reduce a labeled polynomial f by B. Continuously searches for non-zero labeled polynomial h in B, such that the leading term lt_h of h divides the leading term lt_f of f and Sign(lt_h * h) < Sign(f). If such a labeled polynomial h is found, f gets replaced by f - lt_f / lt_h * h. If no such h can be found or f is 0, f is no further F5-reducible and f gets returned. A polynomial that is reducible in the usual sense need not be F5-reducible, e.g.: >>> from sympy.polys.groebnertools import lbp, sig, f5_reduce, Polyn >>> from sympy.polys import ring, QQ, lex >>> R, x,y,z = ring("x,y,z", QQ, lex) >>> f = lbp(sig((1, 1, 1), 4), x, 3) >>> g = lbp(sig((0, 0, 0), 2), x, 2) >>> Polyn(f).rem([Polyn(g)]) 0 >>> f5_reduce(f, [g]) (((1, 1, 1), 4), x, 3) """ order = Polyn(f).ring.order domain = Polyn(f).ring.domain if not Polyn(f): return f while True: g = f for h in B: if Polyn(h): if monomial_divides(Polyn(h).LM, Polyn(f).LM): t = term_div(Polyn(f).LT, Polyn(h).LT, domain) if sig_cmp(sig_mult(Sign(h), t[0]), Sign(f), order) < 0: # The following check need not be done and is in general slower than without. #if not is_rewritable_or_comparable(Sign(gp), Num(gp), B): hp = lbp_mul_term(h, t) f = lbp_sub(f, hp) break if g == f or not Polyn(f): return f def _f5b(F, ring): """ Computes a reduced Groebner basis for the ideal generated by F. f5b is an implementation of the F5B algorithm by Yao Sun and Dingkang Wang. Similarly to Buchberger's algorithm, the algorithm proceeds by computing critical pairs, computing the S-polynomial, reducing it and adjoining the reduced S-polynomial if it is not 0. Unlike Buchberger's algorithm, each polynomial contains additional information, namely a signature and a number. The signature specifies the path of computation (i.e. from which polynomial in the original basis was it derived and how), the number says when the polynomial was added to the basis. With this information it is (often) possible to decide if an S-polynomial will reduce to 0 and can be discarded. Optimizations include: Reducing the generators before computing a Groebner basis, removing redundant critical pairs when a new polynomial enters the basis and sorting the critical pairs and the current basis. Once a Groebner basis has been found, it gets reduced. References ========== .. [1] Yao Sun, Dingkang Wang: "A New Proof for the Correctness of F5 (F5-Like) Algorithm", http://arxiv.org/abs/1004.0084 (specifically v4) .. [2] Thomas Becker, Volker Weispfenning, Groebner bases: A computational approach to commutative algebra, 1993, p. 203, 216 """ order = ring.order # reduce polynomials (like in Mario Pernici's implementation) (Becker, Weispfenning, p. 203) B = F while True: F = B B = [] for i in range(len(F)): p = F[i] r = p.rem(F[:i]) if r: B.append(r) if F == B: break # basis B = [lbp(sig(ring.zero_monom, i + 1), F[i], i + 1) for i in range(len(F))] B.sort(key=lambda f: order(Polyn(f).LM), reverse=True) # critical pairs CP = [critical_pair(B[i], B[j], ring) for i in range(len(B)) for j in range(i + 1, len(B))] CP.sort(key=lambda cp: cp_key(cp, ring), reverse=True) k = len(B) reductions_to_zero = 0 while len(CP): cp = CP.pop() # discard redundant critical pairs: if is_rewritable_or_comparable(cp[0], Num(cp[2]), B): continue if is_rewritable_or_comparable(cp[3], Num(cp[5]), B): continue s = s_poly(cp) p = f5_reduce(s, B) p = lbp(Sign(p), Polyn(p).monic(), k + 1) if Polyn(p): # remove old critical pairs, that become redundant when adding p: indices = [] for i, cp in enumerate(CP): if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p]): indices.append(i) elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p]): indices.append(i) for i in reversed(indices): del CP[i] # only add new critical pairs that are not made redundant by p: for g in B: if Polyn(g): cp = critical_pair(p, g, ring) if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p]): continue elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p]): continue CP.append(cp) # sort (other sorting methods/selection strategies were not as successful) CP.sort(key=lambda cp: cp_key(cp, ring), reverse=True) # insert p into B: m = Polyn(p).LM if order(m) <= order(Polyn(B[-1]).LM): B.append(p) else: for i, q in enumerate(B): if order(m) > order(Polyn(q).LM): B.insert(i, p) break k += 1 #print(len(B), len(CP), "%d critical pairs removed" % len(indices)) else: reductions_to_zero += 1 # reduce Groebner basis: H = [Polyn(g).monic() for g in B] H = red_groebner(H, ring) return sorted(H, key=lambda f: order(f.LM), reverse=True) def red_groebner(G, ring): """ Compute reduced Groebner basis, from BeckerWeispfenning93, p. 216 Selects a subset of generators, that already generate the ideal and computes a reduced Groebner basis for them. """ def reduction(P): """ The actual reduction algorithm. """ Q = [] for i, p in enumerate(P): h = p.rem(P[:i] + P[i + 1:]) if h: Q.append(h) return [p.monic() for p in Q] F = G H = [] while F: f0 = F.pop() if not any(monomial_divides(f.LM, f0.LM) for f in F + H): H.append(f0) # Becker, Weispfenning, p. 217: H is Groebner basis of the ideal generated by G. return reduction(H) def is_groebner(G, ring): """ Check if G is a Groebner basis. """ for i in range(len(G)): for j in range(i + 1, len(G)): s = spoly(G[i], G[j], ring) s = s.rem(G) if s: return False return True def is_minimal(G, ring): """ Checks if G is a minimal Groebner basis. """ order = ring.order domain = ring.domain G.sort(key=lambda g: order(g.LM)) for i, g in enumerate(G): if g.LC != domain.one: return False for h in G[:i] + G[i + 1:]: if monomial_divides(h.LM, g.LM): return False return True def is_reduced(G, ring): """ Checks if G is a reduced Groebner basis. """ order = ring.order domain = ring.domain G.sort(key=lambda g: order(g.LM)) for i, g in enumerate(G): if g.LC != domain.one: return False for term in g.terms(): for h in G[:i] + G[i + 1:]: if monomial_divides(h.LM, term[0]): return False return True def groebner_lcm(f, g): """ Computes LCM of two polynomials using Groebner bases. The LCM is computed as the unique generator of the intersection of the two ideals generated by `f` and `g`. The approach is to compute a Groebner basis with respect to lexicographic ordering of `t*f` and `(1 - t)*g`, where `t` is an unrelated variable and then filtering out the solution that does not contain `t`. References ========== .. [1] [Cox97]_ """ if f.ring != g.ring: raise ValueError("Values should be equal") ring = f.ring domain = ring.domain if not f or not g: return ring.zero if len(f) <= 1 and len(g) <= 1: monom = monomial_lcm(f.LM, g.LM) coeff = domain.lcm(f.LC, g.LC) return ring.term_new(monom, coeff) fc, f = f.primitive() gc, g = g.primitive() lcm = domain.lcm(fc, gc) f_terms = [ ((1,) + monom, coeff) for monom, coeff in f.terms() ] g_terms = [ ((0,) + monom, coeff) for monom, coeff in g.terms() ] \ + [ ((1,) + monom,-coeff) for monom, coeff in g.terms() ] t = Dummy("t") t_ring = ring.clone(symbols=(t,) + ring.symbols, order=lex) F = t_ring.from_terms(f_terms) G = t_ring.from_terms(g_terms) basis = groebner([F, G], t_ring) def is_independent(h, j): return not any(monom[j] for monom in h.monoms()) H = [ h for h in basis if is_independent(h, 0) ] h_terms = [ (monom[1:], coeff*lcm) for monom, coeff in H[0].terms() ] h = ring.from_terms(h_terms) return h def groebner_gcd(f, g): """Computes GCD of two polynomials using Groebner bases. """ if f.ring != g.ring: raise ValueError("Values should be equal") domain = f.ring.domain if not domain.is_Field: fc, f = f.primitive() gc, g = g.primitive() gcd = domain.gcd(fc, gc) H = (f*g).quo([groebner_lcm(f, g)]) if len(H) != 1: raise ValueError("Length should be 1") h = H[0] if not domain.is_Field: return gcd*h else: return h.monic()
c4d6e402f6191af3896ac333b93f2aef15569793711235b3cb96ab417290ee13
"""Sparse rational function fields. """ from typing import Any, Dict as tDict from functools import reduce from operator import add, mul, lt, le, gt, ge from sympy.core.expr import Expr from sympy.core.mod import Mod from sympy.core.numbers import Exp1 from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import CantSympify, sympify from sympy.functions.elementary.exponential import ExpBase from sympy.polys.domains.domainelement import DomainElement from sympy.polys.domains.fractionfield import FractionField from sympy.polys.domains.polynomialring import PolynomialRing from sympy.polys.constructor import construct_domain from sympy.polys.orderings import lex from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polyoptions import build_options from sympy.polys.polyutils import _parallel_dict_from_expr from sympy.polys.rings import PolyElement from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public from sympy.utilities.iterables import is_sequence from sympy.utilities.magic import pollute @public def field(symbols, domain, order=lex): """Construct new rational function field returning (field, x1, ..., xn). """ _field = FracField(symbols, domain, order) return (_field,) + _field.gens @public def xfield(symbols, domain, order=lex): """Construct new rational function field returning (field, (x1, ..., xn)). """ _field = FracField(symbols, domain, order) return (_field, _field.gens) @public def vfield(symbols, domain, order=lex): """Construct new rational function field and inject generators into global namespace. """ _field = FracField(symbols, domain, order) pollute([ sym.name for sym in _field.symbols ], _field.gens) return _field @public def sfield(exprs, *symbols, **options): """Construct a field deriving generators and domain from options and input expressions. Parameters ========== exprs : py:class:`~.Expr` or sequence of :py:class:`~.Expr` (sympifiable) symbols : sequence of :py:class:`~.Symbol`/:py:class:`~.Expr` options : keyword arguments understood by :py:class:`~.Options` Examples ======== >>> from sympy import exp, log, symbols, sfield >>> x = symbols("x") >>> K, f = sfield((x*log(x) + 4*x**2)*exp(1/x + log(x)/3)/x**2) >>> K Rational function field in x, exp(1/x), log(x), x**(1/3) over ZZ with lex order >>> f (4*x**2*(exp(1/x)) + x*(exp(1/x))*(log(x)))/((x**(1/3))**5) """ single = False if not is_sequence(exprs): exprs, single = [exprs], True exprs = list(map(sympify, exprs)) opt = build_options(symbols, options) numdens = [] for expr in exprs: numdens.extend(expr.as_numer_denom()) reps, opt = _parallel_dict_from_expr(numdens, opt) if opt.domain is None: # NOTE: this is inefficient because construct_domain() automatically # performs conversion to the target domain. It shouldn't do this. coeffs = sum([list(rep.values()) for rep in reps], []) opt.domain, _ = construct_domain(coeffs, opt=opt) _field = FracField(opt.gens, opt.domain, opt.order) fracs = [] for i in range(0, len(reps), 2): fracs.append(_field(tuple(reps[i:i+2]))) if single: return (_field, fracs[0]) else: return (_field, fracs) _field_cache = {} # type: tDict[Any, Any] class FracField(DefaultPrinting): """Multivariate distributed rational function field. """ def __new__(cls, symbols, domain, order=lex): from sympy.polys.rings import PolyRing ring = PolyRing(symbols, domain, order) symbols = ring.symbols ngens = ring.ngens domain = ring.domain order = ring.order _hash_tuple = (cls.__name__, symbols, ngens, domain, order) obj = _field_cache.get(_hash_tuple) if obj is None: obj = object.__new__(cls) obj._hash_tuple = _hash_tuple obj._hash = hash(_hash_tuple) obj.ring = ring obj.dtype = type("FracElement", (FracElement,), {"field": obj}) obj.symbols = symbols obj.ngens = ngens obj.domain = domain obj.order = order obj.zero = obj.dtype(ring.zero) obj.one = obj.dtype(ring.one) obj.gens = obj._gens() for symbol, generator in zip(obj.symbols, obj.gens): if isinstance(symbol, Symbol): name = symbol.name if not hasattr(obj, name): setattr(obj, name, generator) _field_cache[_hash_tuple] = obj return obj def _gens(self): """Return a list of polynomial generators. """ return tuple([ self.dtype(gen) for gen in self.ring.gens ]) def __getnewargs__(self): return (self.symbols, self.domain, self.order) def __hash__(self): return self._hash def index(self, gen): if isinstance(gen, self.dtype): return self.ring.index(gen.to_poly()) else: raise ValueError("expected a %s, got %s instead" % (self.dtype,gen)) def __eq__(self, other): return isinstance(other, FracField) and \ (self.symbols, self.ngens, self.domain, self.order) == \ (other.symbols, other.ngens, other.domain, other.order) def __ne__(self, other): return not self == other def raw_new(self, numer, denom=None): return self.dtype(numer, denom) def new(self, numer, denom=None): if denom is None: denom = self.ring.one numer, denom = numer.cancel(denom) return self.raw_new(numer, denom) def domain_new(self, element): return self.domain.convert(element) def ground_new(self, element): try: return self.new(self.ring.ground_new(element)) except CoercionFailed: domain = self.domain if not domain.is_Field and domain.has_assoc_Field: ring = self.ring ground_field = domain.get_field() element = ground_field.convert(element) numer = ring.ground_new(ground_field.numer(element)) denom = ring.ground_new(ground_field.denom(element)) return self.raw_new(numer, denom) else: raise def field_new(self, element): if isinstance(element, FracElement): if self == element.field: return element if isinstance(self.domain, FractionField) and \ self.domain.field == element.field: return self.ground_new(element) elif isinstance(self.domain, PolynomialRing) and \ self.domain.ring.to_field() == element.field: return self.ground_new(element) else: raise NotImplementedError("conversion") elif isinstance(element, PolyElement): denom, numer = element.clear_denoms() if isinstance(self.domain, PolynomialRing) and \ numer.ring == self.domain.ring: numer = self.ring.ground_new(numer) elif isinstance(self.domain, FractionField) and \ numer.ring == self.domain.field.to_ring(): numer = self.ring.ground_new(numer) else: numer = numer.set_ring(self.ring) denom = self.ring.ground_new(denom) return self.raw_new(numer, denom) elif isinstance(element, tuple) and len(element) == 2: numer, denom = list(map(self.ring.ring_new, element)) return self.new(numer, denom) elif isinstance(element, str): raise NotImplementedError("parsing") elif isinstance(element, Expr): return self.from_expr(element) else: return self.ground_new(element) __call__ = field_new def _rebuild_expr(self, expr, mapping): domain = self.domain powers = tuple((gen, gen.as_base_exp()) for gen in mapping.keys() if gen.is_Pow or isinstance(gen, ExpBase)) def _rebuild(expr): generator = mapping.get(expr) if generator is not None: return generator elif expr.is_Add: return reduce(add, list(map(_rebuild, expr.args))) elif expr.is_Mul: return reduce(mul, list(map(_rebuild, expr.args))) elif expr.is_Pow or isinstance(expr, (ExpBase, Exp1)): b, e = expr.as_base_exp() # look for bg**eg whose integer power may be b**e for gen, (bg, eg) in powers: if bg == b and Mod(e, eg) == 0: return mapping.get(gen)**int(e/eg) if e.is_Integer and e is not S.One: return _rebuild(b)**int(e) elif mapping.get(1/expr) is not None: return 1/mapping.get(1/expr) try: return domain.convert(expr) except CoercionFailed: if not domain.is_Field and domain.has_assoc_Field: return domain.get_field().convert(expr) else: raise return _rebuild(sympify(expr)) def from_expr(self, expr): mapping = dict(list(zip(self.symbols, self.gens))) try: frac = self._rebuild_expr(expr, mapping) except CoercionFailed: raise ValueError("expected an expression convertible to a rational function in %s, got %s" % (self, expr)) else: return self.field_new(frac) def to_domain(self): return FractionField(self) def to_ring(self): from sympy.polys.rings import PolyRing return PolyRing(self.symbols, self.domain, self.order) class FracElement(DomainElement, DefaultPrinting, CantSympify): """Element of multivariate distributed rational function field. """ def __init__(self, numer, denom=None): if denom is None: denom = self.field.ring.one elif not denom: raise ZeroDivisionError("zero denominator") self.numer = numer self.denom = denom def raw_new(f, numer, denom): return f.__class__(numer, denom) def new(f, numer, denom): return f.raw_new(*numer.cancel(denom)) def to_poly(f): if f.denom != 1: raise ValueError("f.denom should be 1") return f.numer def parent(self): return self.field.to_domain() def __getnewargs__(self): return (self.field, self.numer, self.denom) _hash = None def __hash__(self): _hash = self._hash if _hash is None: self._hash = _hash = hash((self.field, self.numer, self.denom)) return _hash def copy(self): return self.raw_new(self.numer.copy(), self.denom.copy()) def set_field(self, new_field): if self.field == new_field: return self else: new_ring = new_field.ring numer = self.numer.set_ring(new_ring) denom = self.denom.set_ring(new_ring) return new_field.new(numer, denom) def as_expr(self, *symbols): return self.numer.as_expr(*symbols)/self.denom.as_expr(*symbols) def __eq__(f, g): if isinstance(g, FracElement) and f.field == g.field: return f.numer == g.numer and f.denom == g.denom else: return f.numer == g and f.denom == f.field.ring.one def __ne__(f, g): return not f == g def __bool__(f): return bool(f.numer) def sort_key(self): return (self.denom.sort_key(), self.numer.sort_key()) def _cmp(f1, f2, op): if isinstance(f2, f1.field.dtype): return op(f1.sort_key(), f2.sort_key()) else: return NotImplemented def __lt__(f1, f2): return f1._cmp(f2, lt) def __le__(f1, f2): return f1._cmp(f2, le) def __gt__(f1, f2): return f1._cmp(f2, gt) def __ge__(f1, f2): return f1._cmp(f2, ge) def __pos__(f): """Negate all coefficients in ``f``. """ return f.raw_new(f.numer, f.denom) def __neg__(f): """Negate all coefficients in ``f``. """ return f.raw_new(-f.numer, f.denom) def _extract_ground(self, element): domain = self.field.domain try: element = domain.convert(element) except CoercionFailed: if not domain.is_Field and domain.has_assoc_Field: ground_field = domain.get_field() try: element = ground_field.convert(element) except CoercionFailed: pass else: return -1, ground_field.numer(element), ground_field.denom(element) return 0, None, None else: return 1, element, None def __add__(f, g): """Add rational functions ``f`` and ``g``. """ field = f.field if not g: return f elif not f: return g elif isinstance(g, field.dtype): if f.denom == g.denom: return f.new(f.numer + g.numer, f.denom) else: return f.new(f.numer*g.denom + f.denom*g.numer, f.denom*g.denom) elif isinstance(g, field.ring.dtype): return f.new(f.numer + f.denom*g, f.denom) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__radd__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__radd__(f) return f.__radd__(g) def __radd__(f, c): if isinstance(c, f.field.ring.dtype): return f.new(f.numer + f.denom*c, f.denom) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(f.numer + f.denom*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(f.numer*g_denom + f.denom*g_numer, f.denom*g_denom) def __sub__(f, g): """Subtract rational functions ``f`` and ``g``. """ field = f.field if not g: return f elif not f: return -g elif isinstance(g, field.dtype): if f.denom == g.denom: return f.new(f.numer - g.numer, f.denom) else: return f.new(f.numer*g.denom - f.denom*g.numer, f.denom*g.denom) elif isinstance(g, field.ring.dtype): return f.new(f.numer - f.denom*g, f.denom) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__rsub__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__rsub__(f) op, g_numer, g_denom = f._extract_ground(g) if op == 1: return f.new(f.numer - f.denom*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(f.numer*g_denom - f.denom*g_numer, f.denom*g_denom) def __rsub__(f, c): if isinstance(c, f.field.ring.dtype): return f.new(-f.numer + f.denom*c, f.denom) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(-f.numer + f.denom*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(-f.numer*g_denom + f.denom*g_numer, f.denom*g_denom) def __mul__(f, g): """Multiply rational functions ``f`` and ``g``. """ field = f.field if not f or not g: return field.zero elif isinstance(g, field.dtype): return f.new(f.numer*g.numer, f.denom*g.denom) elif isinstance(g, field.ring.dtype): return f.new(f.numer*g, f.denom) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__rmul__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__rmul__(f) return f.__rmul__(g) def __rmul__(f, c): if isinstance(c, f.field.ring.dtype): return f.new(f.numer*c, f.denom) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(f.numer*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(f.numer*g_numer, f.denom*g_denom) def __truediv__(f, g): """Computes quotient of fractions ``f`` and ``g``. """ field = f.field if not g: raise ZeroDivisionError elif isinstance(g, field.dtype): return f.new(f.numer*g.denom, f.denom*g.numer) elif isinstance(g, field.ring.dtype): return f.new(f.numer, f.denom*g) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__rtruediv__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__rtruediv__(f) op, g_numer, g_denom = f._extract_ground(g) if op == 1: return f.new(f.numer, f.denom*g_numer) elif not op: return NotImplemented else: return f.new(f.numer*g_denom, f.denom*g_numer) def __rtruediv__(f, c): if not f: raise ZeroDivisionError elif isinstance(c, f.field.ring.dtype): return f.new(f.denom*c, f.numer) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(f.denom*g_numer, f.numer) elif not op: return NotImplemented else: return f.new(f.denom*g_numer, f.numer*g_denom) def __pow__(f, n): """Raise ``f`` to a non-negative power ``n``. """ if n >= 0: return f.raw_new(f.numer**n, f.denom**n) elif not f: raise ZeroDivisionError else: return f.raw_new(f.denom**-n, f.numer**-n) def diff(f, x): """Computes partial derivative in ``x``. Examples ======== >>> from sympy.polys.fields import field >>> from sympy.polys.domains import ZZ >>> _, x, y, z = field("x,y,z", ZZ) >>> ((x**2 + y)/(z + 1)).diff(x) 2*x/(z + 1) """ x = x.to_poly() return f.new(f.numer.diff(x)*f.denom - f.numer*f.denom.diff(x), f.denom**2) def __call__(f, *values): if 0 < len(values) <= f.field.ngens: return f.evaluate(list(zip(f.field.gens, values))) else: raise ValueError("expected at least 1 and at most %s values, got %s" % (f.field.ngens, len(values))) def evaluate(f, x, a=None): if isinstance(x, list) and a is None: x = [ (X.to_poly(), a) for X, a in x ] numer, denom = f.numer.evaluate(x), f.denom.evaluate(x) else: x = x.to_poly() numer, denom = f.numer.evaluate(x, a), f.denom.evaluate(x, a) field = numer.ring.to_field() return field.new(numer, denom) def subs(f, x, a=None): if isinstance(x, list) and a is None: x = [ (X.to_poly(), a) for X, a in x ] numer, denom = f.numer.subs(x), f.denom.subs(x) else: x = x.to_poly() numer, denom = f.numer.subs(x, a), f.denom.subs(x, a) return f.new(numer, denom) def compose(f, x, a=None): raise NotImplementedError
4c2584fab9bfba43d6c579e6a91c0ffcdd9ce88321ed5ae41c95d6d7b101e733
"""Low-level linear systems solver. """ from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import connected_components from sympy.core.sympify import sympify from sympy.core.numbers import Integer, Rational from sympy.matrices.dense import MutableDenseMatrix from sympy.polys.domains import ZZ, QQ from sympy.polys.domains import EX from sympy.polys.rings import sring from sympy.polys.polyerrors import NotInvertible from sympy.polys.domainmatrix import DomainMatrix class PolyNonlinearError(Exception): """Raised by solve_lin_sys for nonlinear equations""" pass class RawMatrix(MutableDenseMatrix): """ .. deprecated:: 1.9 This class fundamentally is broken by design. Use ``DomainMatrix`` if you want a matrix over the polys domains or ``Matrix`` for a matrix with ``Expr`` elements. The ``RawMatrix`` class will be removed/broken in future in order to reestablish the invariant that the elements of a Matrix should be of type ``Expr``. """ _sympify = staticmethod(lambda x: x) def __init__(self, *args, **kwargs): sympy_deprecation_warning( """ The RawMatrix class is deprecated. Use either DomainMatrix or Matrix instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-rawmatrix", ) domain = ZZ for i in range(self.rows): for j in range(self.cols): val = self[i,j] if getattr(val, 'is_Poly', False): K = val.domain[val.gens] val_sympy = val.as_expr() elif hasattr(val, 'parent'): K = val.parent() val_sympy = K.to_sympy(val) elif isinstance(val, (int, Integer)): K = ZZ val_sympy = sympify(val) elif isinstance(val, Rational): K = QQ val_sympy = val else: for K in ZZ, QQ: if K.of_type(val): val_sympy = K.to_sympy(val) break else: raise TypeError domain = domain.unify(K) self[i,j] = val_sympy self.ring = domain def eqs_to_matrix(eqs_coeffs, eqs_rhs, gens, domain): """Get matrix from linear equations in dict format. Explanation =========== Get the matrix representation of a system of linear equations represented as dicts with low-level DomainElement coefficients. This is an *internal* function that is used by solve_lin_sys. Parameters ========== eqs_coeffs: list[dict[Symbol, DomainElement]] The left hand sides of the equations as dicts mapping from symbols to coefficients where the coefficients are instances of DomainElement. eqs_rhs: list[DomainElements] The right hand sides of the equations as instances of DomainElement. gens: list[Symbol] The unknowns in the system of equations. domain: Domain The domain for coefficients of both lhs and rhs. Returns ======= The augmented matrix representation of the system as a DomainMatrix. Examples ======== >>> from sympy import symbols, ZZ >>> from sympy.polys.solvers import eqs_to_matrix >>> x, y = symbols('x, y') >>> eqs_coeff = [{x:ZZ(1), y:ZZ(1)}, {x:ZZ(1), y:ZZ(-1)}] >>> eqs_rhs = [ZZ(0), ZZ(-1)] >>> eqs_to_matrix(eqs_coeff, eqs_rhs, [x, y], ZZ) DomainMatrix([[1, 1, 0], [1, -1, 1]], (2, 3), ZZ) See also ======== solve_lin_sys: Uses :func:`~eqs_to_matrix` internally """ sym2index = {x: n for n, x in enumerate(gens)} nrows = len(eqs_coeffs) ncols = len(gens) + 1 rows = [[domain.zero] * ncols for _ in range(nrows)] for row, eq_coeff, eq_rhs in zip(rows, eqs_coeffs, eqs_rhs): for sym, coeff in eq_coeff.items(): row[sym2index[sym]] = domain.convert(coeff) row[-1] = -domain.convert(eq_rhs) return DomainMatrix(rows, (nrows, ncols), domain) def sympy_eqs_to_ring(eqs, symbols): """Convert a system of equations from Expr to a PolyRing Explanation =========== High-level functions like ``solve`` expect Expr as inputs but can use ``solve_lin_sys`` internally. This function converts equations from ``Expr`` to the low-level poly types used by the ``solve_lin_sys`` function. Parameters ========== eqs: List of Expr A list of equations as Expr instances symbols: List of Symbol A list of the symbols that are the unknowns in the system of equations. Returns ======= Tuple[List[PolyElement], Ring]: The equations as PolyElement instances and the ring of polynomials within which each equation is represented. Examples ======== >>> from sympy import symbols >>> from sympy.polys.solvers import sympy_eqs_to_ring >>> a, x, y = symbols('a, x, y') >>> eqs = [x-y, x+a*y] >>> eqs_ring, ring = sympy_eqs_to_ring(eqs, [x, y]) >>> eqs_ring [x - y, x + a*y] >>> type(eqs_ring[0]) <class 'sympy.polys.rings.PolyElement'> >>> ring ZZ(a)[x,y] With the equations in this form they can be passed to ``solve_lin_sys``: >>> from sympy.polys.solvers import solve_lin_sys >>> solve_lin_sys(eqs_ring, ring) {y: 0, x: 0} """ try: K, eqs_K = sring(eqs, symbols, field=True, extension=True) except NotInvertible: # https://github.com/sympy/sympy/issues/18874 K, eqs_K = sring(eqs, symbols, domain=EX) return eqs_K, K.to_domain() def solve_lin_sys(eqs, ring, _raw=True): """Solve a system of linear equations from a PolynomialRing Explanation =========== Solves a system of linear equations given as PolyElement instances of a PolynomialRing. The basic arithmetic is carried out using instance of DomainElement which is more efficient than :class:`~sympy.core.expr.Expr` for the most common inputs. While this is a public function it is intended primarily for internal use so its interface is not necessarily convenient. Users are suggested to use the :func:`sympy.solvers.solveset.linsolve` function (which uses this function internally) instead. Parameters ========== eqs: list[PolyElement] The linear equations to be solved as elements of a PolynomialRing (assumed equal to zero). ring: PolynomialRing The polynomial ring from which eqs are drawn. The generators of this ring are the unkowns to be solved for and the domain of the ring is the domain of the coefficients of the system of equations. _raw: bool If *_raw* is False, the keys and values in the returned dictionary will be of type Expr (and the unit of the field will be removed from the keys) otherwise the low-level polys types will be returned, e.g. PolyElement: PythonRational. Returns ======= ``None`` if the system has no solution. dict[Symbol, Expr] if _raw=False dict[Symbol, DomainElement] if _raw=True. Examples ======== >>> from sympy import symbols >>> from sympy.polys.solvers import solve_lin_sys, sympy_eqs_to_ring >>> x, y = symbols('x, y') >>> eqs = [x - y, x + y - 2] >>> eqs_ring, ring = sympy_eqs_to_ring(eqs, [x, y]) >>> solve_lin_sys(eqs_ring, ring) {y: 1, x: 1} Passing ``_raw=False`` returns the same result except that the keys are ``Expr`` rather than low-level poly types. >>> solve_lin_sys(eqs_ring, ring, _raw=False) {x: 1, y: 1} See also ======== sympy_eqs_to_ring: prepares the inputs to ``solve_lin_sys``. linsolve: ``linsolve`` uses ``solve_lin_sys`` internally. sympy.solvers.solvers.solve: ``solve`` uses ``solve_lin_sys`` internally. """ as_expr = not _raw assert ring.domain.is_Field eqs_dict = [dict(eq) for eq in eqs] one_monom = ring.one.monoms()[0] zero = ring.domain.zero eqs_rhs = [] eqs_coeffs = [] for eq_dict in eqs_dict: eq_rhs = eq_dict.pop(one_monom, zero) eq_coeffs = {} for monom, coeff in eq_dict.items(): if sum(monom) != 1: msg = "Nonlinear term encountered in solve_lin_sys" raise PolyNonlinearError(msg) eq_coeffs[ring.gens[monom.index(1)]] = coeff if not eq_coeffs: if not eq_rhs: continue else: return None eqs_rhs.append(eq_rhs) eqs_coeffs.append(eq_coeffs) result = _solve_lin_sys(eqs_coeffs, eqs_rhs, ring) if result is not None and as_expr: def to_sympy(x): as_expr = getattr(x, 'as_expr', None) if as_expr: return as_expr() else: return ring.domain.to_sympy(x) tresult = {to_sympy(sym): to_sympy(val) for sym, val in result.items()} # Remove 1.0x result = {} for k, v in tresult.items(): if k.is_Mul: c, s = k.as_coeff_Mul() result[s] = v/c else: result[k] = v return result def _solve_lin_sys(eqs_coeffs, eqs_rhs, ring): """Solve a linear system from dict of PolynomialRing coefficients Explanation =========== This is an **internal** function used by :func:`solve_lin_sys` after the equations have been preprocessed. The role of this function is to split the system into connected components and pass those to :func:`_solve_lin_sys_component`. Examples ======== Setup a system for $x-y=0$ and $x+y=2$ and solve: >>> from sympy import symbols, sring >>> from sympy.polys.solvers import _solve_lin_sys >>> x, y = symbols('x, y') >>> R, (xr, yr) = sring([x, y], [x, y]) >>> eqs = [{xr:R.one, yr:-R.one}, {xr:R.one, yr:R.one}] >>> eqs_rhs = [R.zero, -2*R.one] >>> _solve_lin_sys(eqs, eqs_rhs, R) {y: 1, x: 1} See also ======== solve_lin_sys: This function is used internally by :func:`solve_lin_sys`. """ V = ring.gens E = [] for eq_coeffs in eqs_coeffs: syms = list(eq_coeffs) E.extend(zip(syms[:-1], syms[1:])) G = V, E components = connected_components(G) sym2comp = {} for n, component in enumerate(components): for sym in component: sym2comp[sym] = n subsystems = [([], []) for _ in range(len(components))] for eq_coeff, eq_rhs in zip(eqs_coeffs, eqs_rhs): sym = next(iter(eq_coeff), None) sub_coeff, sub_rhs = subsystems[sym2comp[sym]] sub_coeff.append(eq_coeff) sub_rhs.append(eq_rhs) sol = {} for subsystem in subsystems: subsol = _solve_lin_sys_component(subsystem[0], subsystem[1], ring) if subsol is None: return None sol.update(subsol) return sol def _solve_lin_sys_component(eqs_coeffs, eqs_rhs, ring): """Solve a linear system from dict of PolynomialRing coefficients Explanation =========== This is an **internal** function used by :func:`solve_lin_sys` after the equations have been preprocessed. After :func:`_solve_lin_sys` splits the system into connected components this function is called for each component. The system of equations is solved using Gauss-Jordan elimination with division followed by back-substitution. Examples ======== Setup a system for $x-y=0$ and $x+y=2$ and solve: >>> from sympy import symbols, sring >>> from sympy.polys.solvers import _solve_lin_sys_component >>> x, y = symbols('x, y') >>> R, (xr, yr) = sring([x, y], [x, y]) >>> eqs = [{xr:R.one, yr:-R.one}, {xr:R.one, yr:R.one}] >>> eqs_rhs = [R.zero, -2*R.one] >>> _solve_lin_sys_component(eqs, eqs_rhs, R) {y: 1, x: 1} See also ======== solve_lin_sys: This function is used internally by :func:`solve_lin_sys`. """ # transform from equations to matrix form matrix = eqs_to_matrix(eqs_coeffs, eqs_rhs, ring.gens, ring.domain) # convert to a field for rref if not matrix.domain.is_Field: matrix = matrix.to_field() # solve by row-reduction echelon, pivots = matrix.rref() # construct the returnable form of the solutions keys = ring.gens if pivots and pivots[-1] == len(keys): return None if len(pivots) == len(keys): sol = [] for s in [row[-1] for row in echelon.rep.to_ddm()]: a = s sol.append(a) sols = dict(zip(keys, sol)) else: sols = {} g = ring.gens # Extract ground domain coefficients and convert to the ring: if hasattr(ring, 'ring'): convert = ring.ring.ground_new else: convert = ring.ground_new echelon = echelon.rep.to_ddm() vals_set = {v for row in echelon for v in row} vals_map = {v: convert(v) for v in vals_set} echelon = [[vals_map[eij] for eij in ei] for ei in echelon] for i, p in enumerate(pivots): v = echelon[i][-1] - sum(echelon[i][j]*g[j] for j in range(p+1, len(g)) if echelon[i][j]) sols[keys[p]] = v return sols
2ce5db25e96e51f3d1e37f6e91378a3bbebf57aa94e31f9f5d01b977f00049d4
"""Real and complex root isolation and refinement algorithms. """ from sympy.polys.densearith import ( dup_neg, dup_rshift, dup_rem, dup_l2_norm_squared) from sympy.polys.densebasic import ( dup_LC, dup_TC, dup_degree, dup_strip, dup_reverse, dup_convert, dup_terms_gcd) from sympy.polys.densetools import ( dup_clear_denoms, dup_mirror, dup_scale, dup_shift, dup_transform, dup_diff, dup_eval, dmp_eval_in, dup_sign_variations, dup_real_imag) from sympy.polys.euclidtools import ( dup_discriminant) from sympy.polys.factortools import ( dup_factor_list) from sympy.polys.polyerrors import ( RefinementFailed, DomainError, PolynomialError) from sympy.polys.sqfreetools import ( dup_sqf_part, dup_sqf_list) def dup_sturm(f, K): """ Computes the Sturm sequence of ``f`` in ``F[x]``. Given a univariate, square-free polynomial ``f(x)`` returns the associated Sturm sequence ``f_0(x), ..., f_n(x)`` defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> R.dup_sturm(x**3 - 2*x**2 + x - 3) [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2/9*x + 25/9, -2079/4] References ========== .. [1] [Davenport88]_ """ if not K.is_Field: raise DomainError("Cannot compute Sturm sequence over %s" % K) f = dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] def dup_root_upper_bound(f, K): """Compute the LMQ upper bound for the positive roots of `f`; LMQ (Local Max Quadratic) was developed by Akritas-Strzebonski-Vigklas. References ========== .. [1] Alkiviadis G. Akritas: "Linear and Quadratic Complexity Bounds on the Values of the Positive Roots of Polynomials" Journal of Universal Computer Science, Vol. 15, No. 3, 523-537, 2009. """ n, P = len(f), [] t = n * [K.one] if dup_LC(f, K) < 0: f = dup_neg(f, K) f = list(reversed(f)) for i in range(0, n): if f[i] >= 0: continue a, QL = K.log(-f[i], 2), [] for j in range(i + 1, n): if f[j] <= 0: continue q = t[j] + a - K.log(f[j], 2) QL.append([q // (j - i), j]) if not QL: continue q = min(QL) t[q[1]] = t[q[1]] + 1 P.append(q[0]) if not P: return None else: return K.get_field()(2)**(max(P) + 1) def dup_root_lower_bound(f, K): """Compute the LMQ lower bound for the positive roots of `f`; LMQ (Local Max Quadratic) was developed by Akritas-Strzebonski-Vigklas. References ========== .. [1] Alkiviadis G. Akritas: "Linear and Quadratic Complexity Bounds on the Values of the Positive Roots of Polynomials" Journal of Universal Computer Science, Vol. 15, No. 3, 523-537, 2009. """ bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return 1/bound else: return None def dup_cauchy_upper_bound(f, K): """ Compute the Cauchy upper bound on the absolute value of all roots of f, real or complex. References ========== .. [1] https://en.wikipedia.org/wiki/Geometrical_properties_of_polynomial_roots#Lagrange's_and_Cauchy's_bounds """ n = dup_degree(f) if n < 1: raise PolynomialError('Polynomial has no roots.') if K.is_ZZ: L = K.get_field() f, K = dup_convert(f, K, L), L elif not K.is_QQ or K.is_RR or K.is_CC: # We need to compute absolute value, and we are not supporting cases # where this would take us outside the domain (or its quotient field). raise DomainError('Cauchy bound not supported over %s' % K) else: f = f[:] while K.is_zero(f[-1]): f.pop() if len(f) == 1: # Monomial. All roots are zero. return K.zero lc = f[0] return K.one + max(abs(n / lc) for n in f[1:]) def dup_cauchy_lower_bound(f, K): """Compute the Cauchy lower bound on the absolute value of all non-zero roots of f, real or complex.""" g = dup_reverse(f) if len(g) < 2: raise PolynomialError('Polynomial has no non-zero roots.') if K.is_ZZ: K = K.get_field() b = dup_cauchy_upper_bound(g, K) return K.one / b def dup_mignotte_sep_bound_squared(f, K): """ Return the square of the Mignotte lower bound on separation between distinct roots of f. The square is returned so that the bound lies in K or its quotient field. References ========== .. [1] Mignotte, Maurice. "Some useful bounds." Computer algebra. Springer, Vienna, 1982. 259-263. http://people.dm.unipi.it/gianni/AC-EAG/Mignotte.pdf """ n = dup_degree(f) if n < 2: raise PolynomialError('Polynomials of degree < 2 have no distinct roots.') if K.is_ZZ: L = K.get_field() f, K = dup_convert(f, K, L), L elif not K.is_QQ or K.is_RR or K.is_CC: # We need to compute absolute value, and we are not supporting cases # where this would take us outside the domain (or its quotient field). raise DomainError('Mignotte bound not supported over %s' % K) D = dup_discriminant(f, K) l2sq = dup_l2_norm_squared(f, K) return K(3)*K.abs(D) / ( K(n)**(n+1) * l2sq**(n-1) ) def _mobius_from_interval(I, field): """Convert an open interval to a Mobius transform. """ s, t = I a, c = field.numer(s), field.denom(s) b, d = field.numer(t), field.denom(t) return a, b, c, d def _mobius_to_interval(M, field): """Convert a Mobius transform to an open interval. """ a, b, c, d = M s, t = field(a, c), field(b, d) if s <= t: return (s, t) else: return (t, s) def dup_step_refine_real_root(f, M, K, fast=False): """One step of positive real root refinement algorithm. """ a, b, c, d = M if a == b and c == d: return f, (a, b, c, d) A = dup_root_lower_bound(f, K) if A is not None: A = K(int(A)) else: A = K.zero if fast and A > 16: f = dup_scale(f, A, K) a, c, A = A*a, A*c, K.one if A >= K.one: f = dup_shift(f, A, K) b, d = A*a + b, A*c + d if not dup_eval(f, K.zero, K): return f, (b, b, d, d) f, g = dup_shift(f, K.one, K), f a1, b1, c1, d1 = a, a + b, c, c + d if not dup_eval(f, K.zero, K): return f, (b1, b1, d1, d1) k = dup_sign_variations(f, K) if k == 1: a, b, c, d = a1, b1, c1, d1 else: f = dup_shift(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K) a, b, c, d = b, a + b, d, c + d return f, (a, b, c, d) def dup_inner_refine_real_root(f, M, K, eps=None, steps=None, disjoint=None, fast=False, mobius=False): """Refine a positive root of `f` given a Mobius transform or an interval. """ F = K.get_field() if len(M) == 2: a, b, c, d = _mobius_from_interval(M, F) else: a, b, c, d = M while not c: f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) if eps is not None and steps is not None: for i in range(0, steps): if abs(F(a, c) - F(b, d)) >= eps: f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) else: break else: if eps is not None: while abs(F(a, c) - F(b, d)) >= eps: f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) if steps is not None: for i in range(0, steps): f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) if disjoint is not None: while True: u, v = _mobius_to_interval((a, b, c, d), F) if v <= disjoint or disjoint <= u: break else: f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) if not mobius: return _mobius_to_interval((a, b, c, d), F) else: return f, (a, b, c, d) def dup_outer_refine_real_root(f, s, t, K, eps=None, steps=None, disjoint=None, fast=False): """Refine a positive root of `f` given an interval `(s, t)`. """ a, b, c, d = _mobius_from_interval((s, t), K.get_field()) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1: raise RefinementFailed("there should be exactly one root in (%s, %s) interval" % (s, t)) return dup_inner_refine_real_root(f, (a, b, c, d), K, eps=eps, steps=steps, disjoint=disjoint, fast=fast) def dup_refine_real_root(f, s, t, K, eps=None, steps=None, disjoint=None, fast=False): """Refine real root's approximating interval to the given precision. """ if K.is_QQ: (_, f), K = dup_clear_denoms(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError("real root refinement not supported over %s" % K) if s == t: return (s, t) if s > t: s, t = t, s negative = False if s < 0: if t <= 0: f, s, t, negative = dup_mirror(f, K), -t, -s, True else: raise ValueError("Cannot refine a real root in (%s, %s)" % (s, t)) if negative and disjoint is not None: if disjoint < 0: disjoint = -disjoint else: disjoint = None s, t = dup_outer_refine_real_root( f, s, t, K, eps=eps, steps=steps, disjoint=disjoint, fast=fast) if negative: return (-t, -s) else: return ( s, t) def dup_inner_isolate_real_roots(f, K, eps=None, fast=False): """Internal function for isolation positive roots up to given precision. References ========== 1. Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. 2. Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. """ a, b, c, d = K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K) if k == 0: return [] if k == 1: roots = [dup_inner_refine_real_root( f, (a, b, c, d), K, eps=eps, fast=fast, mobius=True)] else: roots, stack = [], [(a, b, c, d, f, k)] while stack: a, b, c, d, f, k = stack.pop() A = dup_root_lower_bound(f, K) if A is not None: A = K(int(A)) else: A = K.zero if fast and A > 16: f = dup_scale(f, A, K) a, c, A = A*a, A*c, K.one if A >= K.one: f = dup_shift(f, A, K) b, d = A*a + b, A*c + d if not dup_TC(f, K): roots.append((f, (b, b, d, d))) f = dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if k == 0: continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), K, eps=eps, fast=fast, mobius=True)) continue f1 = dup_shift(f, K.one, K) a1, b1, c1, d1, r = a, a + b, c, c + d, 0 if not dup_TC(f1, K): roots.append((f1, (b1, b1, d1, d1))) f1, r = dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K) k2 = k - k1 - r a2, b2, c2, d2 = b, a + b, d, c + d if k2 > 1: f2 = dup_shift(dup_reverse(f), K.one, K) if not dup_TC(f2, K): f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) else: f2 = None if k1 < k2: a1, a2, b1, b2 = a2, a1, b2, b1 c1, c2, d1, d2 = c2, c1, d2, d1 f1, f2, k1, k2 = f2, f1, k2, k1 if not k1: continue if f1 is None: f1 = dup_shift(dup_reverse(f), K.one, K) if not dup_TC(f1, K): f1 = dup_rshift(f1, 1, K) if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), K, eps=eps, fast=fast, mobius=True)) else: stack.append((a1, b1, c1, d1, f1, k1)) if not k2: continue if f2 is None: f2 = dup_shift(dup_reverse(f), K.one, K) if not dup_TC(f2, K): f2 = dup_rshift(f2, 1, K) if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), K, eps=eps, fast=fast, mobius=True)) else: stack.append((a2, b2, c2, d2, f2, k2)) return roots def _discard_if_outside_interval(f, M, inf, sup, K, negative, fast, mobius): """Discard an isolating interval if outside ``(inf, sup)``. """ F = K.get_field() while True: u, v = _mobius_to_interval(M, F) if negative: u, v = -v, -u if (inf is None or u >= inf) and (sup is None or v <= sup): if not mobius: return u, v else: return f, M elif (sup is not None and u > sup) or (inf is not None and v < inf): return None else: f, M = dup_step_refine_real_root(f, M, K, fast=fast) def dup_inner_isolate_positive_roots(f, K, eps=None, inf=None, sup=None, fast=False, mobius=False): """Iteratively compute disjoint positive root isolation intervals. """ if sup is not None and sup < 0: return [] roots = dup_inner_isolate_real_roots(f, K, eps=eps, fast=fast) F, results = K.get_field(), [] if inf is not None or sup is not None: for f, M in roots: result = _discard_if_outside_interval(f, M, inf, sup, K, False, fast, mobius) if result is not None: results.append(result) elif not mobius: for f, M in roots: u, v = _mobius_to_interval(M, F) results.append((u, v)) else: results = roots return results def dup_inner_isolate_negative_roots(f, K, inf=None, sup=None, eps=None, fast=False, mobius=False): """Iteratively compute disjoint negative root isolation intervals. """ if inf is not None and inf >= 0: return [] roots = dup_inner_isolate_real_roots(dup_mirror(f, K), K, eps=eps, fast=fast) F, results = K.get_field(), [] if inf is not None or sup is not None: for f, M in roots: result = _discard_if_outside_interval(f, M, inf, sup, K, True, fast, mobius) if result is not None: results.append(result) elif not mobius: for f, M in roots: u, v = _mobius_to_interval(M, F) results.append((-v, -u)) else: results = roots return results def _isolate_zero(f, K, inf, sup, basis=False, sqf=False): """Handle special case of CF algorithm when ``f`` is homogeneous. """ j, f = dup_terms_gcd(f, K) if j > 0: F = K.get_field() if (inf is None or inf <= 0) and (sup is None or 0 <= sup): if not sqf: if not basis: return [((F.zero, F.zero), j)], f else: return [((F.zero, F.zero), j, [K.one, K.zero])], f else: return [(F.zero, F.zero)], f return [], f def dup_isolate_real_roots_sqf(f, K, eps=None, inf=None, sup=None, fast=False, blackbox=False): """Isolate real roots of a square-free polynomial using the Vincent-Akritas-Strzebonski (VAS) CF approach. References ========== .. [1] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods. Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. .. [2] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using New Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. """ if K.is_QQ: (_, f), K = dup_clear_denoms(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError("isolation of real roots not supported over %s" % K) if dup_degree(f) <= 0: return [] I_zero, f = _isolate_zero(f, K, inf, sup, basis=False, sqf=True) I_neg = dup_inner_isolate_negative_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) I_pos = dup_inner_isolate_positive_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) roots = sorted(I_neg + I_zero + I_pos) if not blackbox: return roots else: return [ RealInterval((a, b), f, K) for (a, b) in roots ] def dup_isolate_real_roots(f, K, eps=None, inf=None, sup=None, basis=False, fast=False): """Isolate real roots using Vincent-Akritas-Strzebonski (VAS) continued fractions approach. References ========== .. [1] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods. Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. .. [2] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using New Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. """ if K.is_QQ: (_, f), K = dup_clear_denoms(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError("isolation of real roots not supported over %s" % K) if dup_degree(f) <= 0: return [] I_zero, f = _isolate_zero(f, K, inf, sup, basis=basis, sqf=False) _, factors = dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) = factors I_neg = dup_inner_isolate_negative_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) I_pos = dup_inner_isolate_positive_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) I_neg = [ ((u, v), k) for u, v in I_neg ] I_pos = [ ((u, v), k) for u, v in I_pos ] else: I_neg, I_pos = _real_isolate_and_disjoin(factors, K, eps=eps, inf=inf, sup=sup, basis=basis, fast=fast) return sorted(I_neg + I_zero + I_pos) def dup_isolate_real_roots_list(polys, K, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): """Isolate real roots of a list of square-free polynomial using Vincent-Akritas-Strzebonski (VAS) CF approach. References ========== .. [1] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods. Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. .. [2] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using New Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. """ if K.is_QQ: K, F, polys = K.get_ring(), K, polys[:] for i, p in enumerate(polys): polys[i] = dup_clear_denoms(p, F, K, convert=True)[1] elif not K.is_ZZ: raise DomainError("isolation of real roots not supported over %s" % K) zeros, factors_dict = False, {} if (inf is None or inf <= 0) and (sup is None or 0 <= sup): zeros, zero_indices = True, {} for i, p in enumerate(polys): j, p = dup_terms_gcd(p, K) if zeros and j > 0: zero_indices[i] = j for f, k in dup_factor_list(p, K)[1]: f = tuple(f) if f not in factors_dict: factors_dict[f] = {i: k} else: factors_dict[f][i] = k factors_list = [] for f, indices in factors_dict.items(): factors_list.append((list(f), indices)) I_neg, I_pos = _real_isolate_and_disjoin(factors_list, K, eps=eps, inf=inf, sup=sup, strict=strict, basis=basis, fast=fast) F = K.get_field() if not zeros or not zero_indices: I_zero = [] else: if not basis: I_zero = [((F.zero, F.zero), zero_indices)] else: I_zero = [((F.zero, F.zero), zero_indices, [K.one, K.zero])] return sorted(I_neg + I_zero + I_pos) def _disjoint_p(M, N, strict=False): """Check if Mobius transforms define disjoint intervals. """ a1, b1, c1, d1 = M a2, b2, c2, d2 = N a1d1, b1c1 = a1*d1, b1*c1 a2d2, b2c2 = a2*d2, b2*c2 if a1d1 == b1c1 and a2d2 == b2c2: return True if a1d1 > b1c1: a1, c1, b1, d1 = b1, d1, a1, c1 if a2d2 > b2c2: a2, c2, b2, d2 = b2, d2, a2, c2 if not strict: return a2*d1 >= c2*b1 or b2*c1 <= d2*a1 else: return a2*d1 > c2*b1 or b2*c1 < d2*a1 def _real_isolate_and_disjoin(factors, K, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): """Isolate real roots of a list of polynomials and disjoin intervals. """ I_pos, I_neg = [], [] for i, (f, k) in enumerate(factors): for F, M in dup_inner_isolate_positive_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast, mobius=True): I_pos.append((F, M, k, f)) for G, N in dup_inner_isolate_negative_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast, mobius=True): I_neg.append((G, N, k, f)) for i, (f, M, k, F) in enumerate(I_pos): for j, (g, N, m, G) in enumerate(I_pos[i + 1:]): while not _disjoint_p(M, N, strict=strict): f, M = dup_inner_refine_real_root(f, M, K, steps=1, fast=fast, mobius=True) g, N = dup_inner_refine_real_root(g, N, K, steps=1, fast=fast, mobius=True) I_pos[i + j + 1] = (g, N, m, G) I_pos[i] = (f, M, k, F) for i, (f, M, k, F) in enumerate(I_neg): for j, (g, N, m, G) in enumerate(I_neg[i + 1:]): while not _disjoint_p(M, N, strict=strict): f, M = dup_inner_refine_real_root(f, M, K, steps=1, fast=fast, mobius=True) g, N = dup_inner_refine_real_root(g, N, K, steps=1, fast=fast, mobius=True) I_neg[i + j + 1] = (g, N, m, G) I_neg[i] = (f, M, k, F) if strict: for i, (f, M, k, F) in enumerate(I_neg): if not M[0]: while not M[0]: f, M = dup_inner_refine_real_root(f, M, K, steps=1, fast=fast, mobius=True) I_neg[i] = (f, M, k, F) break for j, (g, N, m, G) in enumerate(I_pos): if not N[0]: while not N[0]: g, N = dup_inner_refine_real_root(g, N, K, steps=1, fast=fast, mobius=True) I_pos[j] = (g, N, m, G) break field = K.get_field() I_neg = [ (_mobius_to_interval(M, field), k, f) for (_, M, k, f) in I_neg ] I_pos = [ (_mobius_to_interval(M, field), k, f) for (_, M, k, f) in I_pos ] if not basis: I_neg = [ ((-v, -u), k) for ((u, v), k, _) in I_neg ] I_pos = [ (( u, v), k) for ((u, v), k, _) in I_pos ] else: I_neg = [ ((-v, -u), k, f) for ((u, v), k, f) in I_neg ] I_pos = [ (( u, v), k, f) for ((u, v), k, f) in I_pos ] return I_neg, I_pos def dup_count_real_roots(f, K, inf=None, sup=None): """Returns the number of distinct real roots of ``f`` in ``[inf, sup]``. """ if dup_degree(f) <= 0: return 0 if not K.is_Field: R, K = K, K.get_field() f = dup_convert(f, R, K) sturm = dup_sturm(f, K) if inf is None: signs_inf = dup_sign_variations([ dup_LC(s, K)*(-1)**dup_degree(s) for s in sturm ], K) else: signs_inf = dup_sign_variations([ dup_eval(s, inf, K) for s in sturm ], K) if sup is None: signs_sup = dup_sign_variations([ dup_LC(s, K) for s in sturm ], K) else: signs_sup = dup_sign_variations([ dup_eval(s, sup, K) for s in sturm ], K) count = abs(signs_inf - signs_sup) if inf is not None and not dup_eval(f, inf, K): count += 1 return count OO = 'OO' # Origin of (re, im) coordinate system Q1 = 'Q1' # Quadrant #1 (++): re > 0 and im > 0 Q2 = 'Q2' # Quadrant #2 (-+): re < 0 and im > 0 Q3 = 'Q3' # Quadrant #3 (--): re < 0 and im < 0 Q4 = 'Q4' # Quadrant #4 (+-): re > 0 and im < 0 A1 = 'A1' # Axis #1 (+0): re > 0 and im = 0 A2 = 'A2' # Axis #2 (0+): re = 0 and im > 0 A3 = 'A3' # Axis #3 (-0): re < 0 and im = 0 A4 = 'A4' # Axis #4 (0-): re = 0 and im < 0 _rules_simple = { # Q --> Q (same) => no change (Q1, Q1): 0, (Q2, Q2): 0, (Q3, Q3): 0, (Q4, Q4): 0, # A -- CCW --> Q => +1/4 (CCW) (A1, Q1): 1, (A2, Q2): 1, (A3, Q3): 1, (A4, Q4): 1, # A -- CW --> Q => -1/4 (CCW) (A1, Q4): 2, (A2, Q1): 2, (A3, Q2): 2, (A4, Q3): 2, # Q -- CCW --> A => +1/4 (CCW) (Q1, A2): 3, (Q2, A3): 3, (Q3, A4): 3, (Q4, A1): 3, # Q -- CW --> A => -1/4 (CCW) (Q1, A1): 4, (Q2, A2): 4, (Q3, A3): 4, (Q4, A4): 4, # Q -- CCW --> Q => +1/2 (CCW) (Q1, Q2): +5, (Q2, Q3): +5, (Q3, Q4): +5, (Q4, Q1): +5, # Q -- CW --> Q => -1/2 (CW) (Q1, Q4): -5, (Q2, Q1): -5, (Q3, Q2): -5, (Q4, Q3): -5, } _rules_ambiguous = { # A -- CCW --> Q => { +1/4 (CCW), -9/4 (CW) } (A1, OO, Q1): -1, (A2, OO, Q2): -1, (A3, OO, Q3): -1, (A4, OO, Q4): -1, # A -- CW --> Q => { -1/4 (CCW), +7/4 (CW) } (A1, OO, Q4): -2, (A2, OO, Q1): -2, (A3, OO, Q2): -2, (A4, OO, Q3): -2, # Q -- CCW --> A => { +1/4 (CCW), -9/4 (CW) } (Q1, OO, A2): -3, (Q2, OO, A3): -3, (Q3, OO, A4): -3, (Q4, OO, A1): -3, # Q -- CW --> A => { -1/4 (CCW), +7/4 (CW) } (Q1, OO, A1): -4, (Q2, OO, A2): -4, (Q3, OO, A3): -4, (Q4, OO, A4): -4, # A -- OO --> A => { +1 (CCW), -1 (CW) } (A1, A3): 7, (A2, A4): 7, (A3, A1): 7, (A4, A2): 7, (A1, OO, A3): 7, (A2, OO, A4): 7, (A3, OO, A1): 7, (A4, OO, A2): 7, # Q -- DIA --> Q => { +1 (CCW), -1 (CW) } (Q1, Q3): 8, (Q2, Q4): 8, (Q3, Q1): 8, (Q4, Q2): 8, (Q1, OO, Q3): 8, (Q2, OO, Q4): 8, (Q3, OO, Q1): 8, (Q4, OO, Q2): 8, # A --- R ---> A => { +1/2 (CCW), -3/2 (CW) } (A1, A2): 9, (A2, A3): 9, (A3, A4): 9, (A4, A1): 9, (A1, OO, A2): 9, (A2, OO, A3): 9, (A3, OO, A4): 9, (A4, OO, A1): 9, # A --- L ---> A => { +3/2 (CCW), -1/2 (CW) } (A1, A4): 10, (A2, A1): 10, (A3, A2): 10, (A4, A3): 10, (A1, OO, A4): 10, (A2, OO, A1): 10, (A3, OO, A2): 10, (A4, OO, A3): 10, # Q --- 1 ---> A => { +3/4 (CCW), -5/4 (CW) } (Q1, A3): 11, (Q2, A4): 11, (Q3, A1): 11, (Q4, A2): 11, (Q1, OO, A3): 11, (Q2, OO, A4): 11, (Q3, OO, A1): 11, (Q4, OO, A2): 11, # Q --- 2 ---> A => { +5/4 (CCW), -3/4 (CW) } (Q1, A4): 12, (Q2, A1): 12, (Q3, A2): 12, (Q4, A3): 12, (Q1, OO, A4): 12, (Q2, OO, A1): 12, (Q3, OO, A2): 12, (Q4, OO, A3): 12, # A --- 1 ---> Q => { +5/4 (CCW), -3/4 (CW) } (A1, Q3): 13, (A2, Q4): 13, (A3, Q1): 13, (A4, Q2): 13, (A1, OO, Q3): 13, (A2, OO, Q4): 13, (A3, OO, Q1): 13, (A4, OO, Q2): 13, # A --- 2 ---> Q => { +3/4 (CCW), -5/4 (CW) } (A1, Q2): 14, (A2, Q3): 14, (A3, Q4): 14, (A4, Q1): 14, (A1, OO, Q2): 14, (A2, OO, Q3): 14, (A3, OO, Q4): 14, (A4, OO, Q1): 14, # Q --> OO --> Q => { +1/2 (CCW), -3/2 (CW) } (Q1, OO, Q2): 15, (Q2, OO, Q3): 15, (Q3, OO, Q4): 15, (Q4, OO, Q1): 15, # Q --> OO --> Q => { +3/2 (CCW), -1/2 (CW) } (Q1, OO, Q4): 16, (Q2, OO, Q1): 16, (Q3, OO, Q2): 16, (Q4, OO, Q3): 16, # A --> OO --> A => { +2 (CCW), 0 (CW) } (A1, OO, A1): 17, (A2, OO, A2): 17, (A3, OO, A3): 17, (A4, OO, A4): 17, # Q --> OO --> Q => { +2 (CCW), 0 (CW) } (Q1, OO, Q1): 18, (Q2, OO, Q2): 18, (Q3, OO, Q3): 18, (Q4, OO, Q4): 18, } _values = { 0: [( 0, 1)], 1: [(+1, 4)], 2: [(-1, 4)], 3: [(+1, 4)], 4: [(-1, 4)], -1: [(+9, 4), (+1, 4)], -2: [(+7, 4), (-1, 4)], -3: [(+9, 4), (+1, 4)], -4: [(+7, 4), (-1, 4)], +5: [(+1, 2)], -5: [(-1, 2)], 7: [(+1, 1), (-1, 1)], 8: [(+1, 1), (-1, 1)], 9: [(+1, 2), (-3, 2)], 10: [(+3, 2), (-1, 2)], 11: [(+3, 4), (-5, 4)], 12: [(+5, 4), (-3, 4)], 13: [(+5, 4), (-3, 4)], 14: [(+3, 4), (-5, 4)], 15: [(+1, 2), (-3, 2)], 16: [(+3, 2), (-1, 2)], 17: [(+2, 1), ( 0, 1)], 18: [(+2, 1), ( 0, 1)], } def _classify_point(re, im): """Return the half-axis (or origin) on which (re, im) point is located. """ if not re and not im: return OO if not re: if im > 0: return A2 else: return A4 elif not im: if re > 0: return A1 else: return A3 def _intervals_to_quadrants(intervals, f1, f2, s, t, F): """Generate a sequence of extended quadrants from a list of critical points. """ if not intervals: return [] Q = [] if not f1: (a, b), _, _ = intervals[0] if a == b == s: if len(intervals) == 1: if dup_eval(f2, t, F) > 0: return [OO, A2] else: return [OO, A4] else: (a, _), _, _ = intervals[1] if dup_eval(f2, (s + a)/2, F) > 0: Q.extend([OO, A2]) f2_sgn = +1 else: Q.extend([OO, A4]) f2_sgn = -1 intervals = intervals[1:] else: if dup_eval(f2, s, F) > 0: Q.append(A2) f2_sgn = +1 else: Q.append(A4) f2_sgn = -1 for (a, _), indices, _ in intervals: Q.append(OO) if indices[1] % 2 == 1: f2_sgn = -f2_sgn if a != t: if f2_sgn > 0: Q.append(A2) else: Q.append(A4) return Q if not f2: (a, b), _, _ = intervals[0] if a == b == s: if len(intervals) == 1: if dup_eval(f1, t, F) > 0: return [OO, A1] else: return [OO, A3] else: (a, _), _, _ = intervals[1] if dup_eval(f1, (s + a)/2, F) > 0: Q.extend([OO, A1]) f1_sgn = +1 else: Q.extend([OO, A3]) f1_sgn = -1 intervals = intervals[1:] else: if dup_eval(f1, s, F) > 0: Q.append(A1) f1_sgn = +1 else: Q.append(A3) f1_sgn = -1 for (a, _), indices, _ in intervals: Q.append(OO) if indices[0] % 2 == 1: f1_sgn = -f1_sgn if a != t: if f1_sgn > 0: Q.append(A1) else: Q.append(A3) return Q re = dup_eval(f1, s, F) im = dup_eval(f2, s, F) if not re or not im: Q.append(_classify_point(re, im)) if len(intervals) == 1: re = dup_eval(f1, t, F) im = dup_eval(f2, t, F) else: (a, _), _, _ = intervals[1] re = dup_eval(f1, (s + a)/2, F) im = dup_eval(f2, (s + a)/2, F) intervals = intervals[1:] if re > 0: f1_sgn = +1 else: f1_sgn = -1 if im > 0: f2_sgn = +1 else: f2_sgn = -1 sgn = { (+1, +1): Q1, (-1, +1): Q2, (-1, -1): Q3, (+1, -1): Q4, } Q.append(sgn[(f1_sgn, f2_sgn)]) for (a, b), indices, _ in intervals: if a == b: re = dup_eval(f1, a, F) im = dup_eval(f2, a, F) cls = _classify_point(re, im) if cls is not None: Q.append(cls) if 0 in indices: if indices[0] % 2 == 1: f1_sgn = -f1_sgn if 1 in indices: if indices[1] % 2 == 1: f2_sgn = -f2_sgn if not (a == b and b == t): Q.append(sgn[(f1_sgn, f2_sgn)]) return Q def _traverse_quadrants(Q_L1, Q_L2, Q_L3, Q_L4, exclude=None): """Transform sequences of quadrants to a sequence of rules. """ if exclude is True: edges = [1, 1, 0, 0] corners = { (0, 1): 1, (1, 2): 1, (2, 3): 0, (3, 0): 1, } else: edges = [0, 0, 0, 0] corners = { (0, 1): 0, (1, 2): 0, (2, 3): 0, (3, 0): 0, } if exclude is not None and exclude is not True: exclude = set(exclude) for i, edge in enumerate(['S', 'E', 'N', 'W']): if edge in exclude: edges[i] = 1 for i, corner in enumerate(['SW', 'SE', 'NE', 'NW']): if corner in exclude: corners[((i - 1) % 4, i)] = 1 QQ, rules = [Q_L1, Q_L2, Q_L3, Q_L4], [] for i, Q in enumerate(QQ): if not Q: continue if Q[-1] == OO: Q = Q[:-1] if Q[0] == OO: j, Q = (i - 1) % 4, Q[1:] qq = (QQ[j][-2], OO, Q[0]) if qq in _rules_ambiguous: rules.append((_rules_ambiguous[qq], corners[(j, i)])) else: raise NotImplementedError("3 element rule (corner): " + str(qq)) q1, k = Q[0], 1 while k < len(Q): q2, k = Q[k], k + 1 if q2 != OO: qq = (q1, q2) if qq in _rules_simple: rules.append((_rules_simple[qq], 0)) elif qq in _rules_ambiguous: rules.append((_rules_ambiguous[qq], edges[i])) else: raise NotImplementedError("2 element rule (inside): " + str(qq)) else: qq, k = (q1, q2, Q[k]), k + 1 if qq in _rules_ambiguous: rules.append((_rules_ambiguous[qq], edges[i])) else: raise NotImplementedError("3 element rule (edge): " + str(qq)) q1 = qq[-1] return rules def _reverse_intervals(intervals): """Reverse intervals for traversal from right to left and from top to bottom. """ return [ ((b, a), indices, f) for (a, b), indices, f in reversed(intervals) ] def _winding_number(T, field): """Compute the winding number of the input polynomial, i.e. the number of roots. """ return int(sum([ field(*_values[t][i]) for t, i in T ]) / field(2)) def dup_count_complex_roots(f, K, inf=None, sup=None, exclude=None): """Count all roots in [u + v*I, s + t*I] rectangle using Collins-Krandick algorithm. """ if not K.is_ZZ and not K.is_QQ: raise DomainError("complex root counting is not supported over %s" % K) if K.is_ZZ: R, F = K, K.get_field() else: R, F = K.get_ring(), K f = dup_convert(f, K, F) if inf is None or sup is None: _, lc = dup_degree(f), abs(dup_LC(f, F)) B = 2*max([ F.quo(abs(c), lc) for c in f ]) if inf is None: (u, v) = (-B, -B) else: (u, v) = inf if sup is None: (s, t) = (+B, +B) else: (s, t) = sup f1, f2 = dup_real_imag(f, F) f1L1F = dmp_eval_in(f1, v, 1, 1, F) f2L1F = dmp_eval_in(f2, v, 1, 1, F) _, f1L1R = dup_clear_denoms(f1L1F, F, R, convert=True) _, f2L1R = dup_clear_denoms(f2L1F, F, R, convert=True) f1L2F = dmp_eval_in(f1, s, 0, 1, F) f2L2F = dmp_eval_in(f2, s, 0, 1, F) _, f1L2R = dup_clear_denoms(f1L2F, F, R, convert=True) _, f2L2R = dup_clear_denoms(f2L2F, F, R, convert=True) f1L3F = dmp_eval_in(f1, t, 1, 1, F) f2L3F = dmp_eval_in(f2, t, 1, 1, F) _, f1L3R = dup_clear_denoms(f1L3F, F, R, convert=True) _, f2L3R = dup_clear_denoms(f2L3F, F, R, convert=True) f1L4F = dmp_eval_in(f1, u, 0, 1, F) f2L4F = dmp_eval_in(f2, u, 0, 1, F) _, f1L4R = dup_clear_denoms(f1L4F, F, R, convert=True) _, f2L4R = dup_clear_denoms(f2L4F, F, R, convert=True) S_L1 = [f1L1R, f2L1R] S_L2 = [f1L2R, f2L2R] S_L3 = [f1L3R, f2L3R] S_L4 = [f1L4R, f2L4R] I_L1 = dup_isolate_real_roots_list(S_L1, R, inf=u, sup=s, fast=True, basis=True, strict=True) I_L2 = dup_isolate_real_roots_list(S_L2, R, inf=v, sup=t, fast=True, basis=True, strict=True) I_L3 = dup_isolate_real_roots_list(S_L3, R, inf=u, sup=s, fast=True, basis=True, strict=True) I_L4 = dup_isolate_real_roots_list(S_L4, R, inf=v, sup=t, fast=True, basis=True, strict=True) I_L3 = _reverse_intervals(I_L3) I_L4 = _reverse_intervals(I_L4) Q_L1 = _intervals_to_quadrants(I_L1, f1L1F, f2L1F, u, s, F) Q_L2 = _intervals_to_quadrants(I_L2, f1L2F, f2L2F, v, t, F) Q_L3 = _intervals_to_quadrants(I_L3, f1L3F, f2L3F, s, u, F) Q_L4 = _intervals_to_quadrants(I_L4, f1L4F, f2L4F, t, v, F) T = _traverse_quadrants(Q_L1, Q_L2, Q_L3, Q_L4, exclude=exclude) return _winding_number(T, F) def _vertical_bisection(N, a, b, I, Q, F1, F2, f1, f2, F): """Vertical bisection step in Collins-Krandick root isolation algorithm. """ (u, v), (s, t) = a, b I_L1, I_L2, I_L3, I_L4 = I Q_L1, Q_L2, Q_L3, Q_L4 = Q f1L1F, f1L2F, f1L3F, f1L4F = F1 f2L1F, f2L2F, f2L3F, f2L4F = F2 x = (u + s) / 2 f1V = dmp_eval_in(f1, x, 0, 1, F) f2V = dmp_eval_in(f2, x, 0, 1, F) I_V = dup_isolate_real_roots_list([f1V, f2V], F, inf=v, sup=t, fast=True, strict=True, basis=True) I_L1_L, I_L1_R = [], [] I_L2_L, I_L2_R = I_V, I_L2 I_L3_L, I_L3_R = [], [] I_L4_L, I_L4_R = I_L4, _reverse_intervals(I_V) for I in I_L1: (a, b), indices, h = I if a == b: if a == x: I_L1_L.append(I) I_L1_R.append(I) elif a < x: I_L1_L.append(I) else: I_L1_R.append(I) else: if b <= x: I_L1_L.append(I) elif a >= x: I_L1_R.append(I) else: a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=x, fast=True) if b <= x: I_L1_L.append(((a, b), indices, h)) if a >= x: I_L1_R.append(((a, b), indices, h)) for I in I_L3: (b, a), indices, h = I if a == b: if a == x: I_L3_L.append(I) I_L3_R.append(I) elif a < x: I_L3_L.append(I) else: I_L3_R.append(I) else: if b <= x: I_L3_L.append(I) elif a >= x: I_L3_R.append(I) else: a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=x, fast=True) if b <= x: I_L3_L.append(((b, a), indices, h)) if a >= x: I_L3_R.append(((b, a), indices, h)) Q_L1_L = _intervals_to_quadrants(I_L1_L, f1L1F, f2L1F, u, x, F) Q_L2_L = _intervals_to_quadrants(I_L2_L, f1V, f2V, v, t, F) Q_L3_L = _intervals_to_quadrants(I_L3_L, f1L3F, f2L3F, x, u, F) Q_L4_L = Q_L4 Q_L1_R = _intervals_to_quadrants(I_L1_R, f1L1F, f2L1F, x, s, F) Q_L2_R = Q_L2 Q_L3_R = _intervals_to_quadrants(I_L3_R, f1L3F, f2L3F, s, x, F) Q_L4_R = _intervals_to_quadrants(I_L4_R, f1V, f2V, t, v, F) T_L = _traverse_quadrants(Q_L1_L, Q_L2_L, Q_L3_L, Q_L4_L, exclude=True) T_R = _traverse_quadrants(Q_L1_R, Q_L2_R, Q_L3_R, Q_L4_R, exclude=True) N_L = _winding_number(T_L, F) N_R = _winding_number(T_R, F) I_L = (I_L1_L, I_L2_L, I_L3_L, I_L4_L) Q_L = (Q_L1_L, Q_L2_L, Q_L3_L, Q_L4_L) I_R = (I_L1_R, I_L2_R, I_L3_R, I_L4_R) Q_R = (Q_L1_R, Q_L2_R, Q_L3_R, Q_L4_R) F1_L = (f1L1F, f1V, f1L3F, f1L4F) F2_L = (f2L1F, f2V, f2L3F, f2L4F) F1_R = (f1L1F, f1L2F, f1L3F, f1V) F2_R = (f2L1F, f2L2F, f2L3F, f2V) a, b = (u, v), (x, t) c, d = (x, v), (s, t) D_L = (N_L, a, b, I_L, Q_L, F1_L, F2_L) D_R = (N_R, c, d, I_R, Q_R, F1_R, F2_R) return D_L, D_R def _horizontal_bisection(N, a, b, I, Q, F1, F2, f1, f2, F): """Horizontal bisection step in Collins-Krandick root isolation algorithm. """ (u, v), (s, t) = a, b I_L1, I_L2, I_L3, I_L4 = I Q_L1, Q_L2, Q_L3, Q_L4 = Q f1L1F, f1L2F, f1L3F, f1L4F = F1 f2L1F, f2L2F, f2L3F, f2L4F = F2 y = (v + t) / 2 f1H = dmp_eval_in(f1, y, 1, 1, F) f2H = dmp_eval_in(f2, y, 1, 1, F) I_H = dup_isolate_real_roots_list([f1H, f2H], F, inf=u, sup=s, fast=True, strict=True, basis=True) I_L1_B, I_L1_U = I_L1, I_H I_L2_B, I_L2_U = [], [] I_L3_B, I_L3_U = _reverse_intervals(I_H), I_L3 I_L4_B, I_L4_U = [], [] for I in I_L2: (a, b), indices, h = I if a == b: if a == y: I_L2_B.append(I) I_L2_U.append(I) elif a < y: I_L2_B.append(I) else: I_L2_U.append(I) else: if b <= y: I_L2_B.append(I) elif a >= y: I_L2_U.append(I) else: a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=y, fast=True) if b <= y: I_L2_B.append(((a, b), indices, h)) if a >= y: I_L2_U.append(((a, b), indices, h)) for I in I_L4: (b, a), indices, h = I if a == b: if a == y: I_L4_B.append(I) I_L4_U.append(I) elif a < y: I_L4_B.append(I) else: I_L4_U.append(I) else: if b <= y: I_L4_B.append(I) elif a >= y: I_L4_U.append(I) else: a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=y, fast=True) if b <= y: I_L4_B.append(((b, a), indices, h)) if a >= y: I_L4_U.append(((b, a), indices, h)) Q_L1_B = Q_L1 Q_L2_B = _intervals_to_quadrants(I_L2_B, f1L2F, f2L2F, v, y, F) Q_L3_B = _intervals_to_quadrants(I_L3_B, f1H, f2H, s, u, F) Q_L4_B = _intervals_to_quadrants(I_L4_B, f1L4F, f2L4F, y, v, F) Q_L1_U = _intervals_to_quadrants(I_L1_U, f1H, f2H, u, s, F) Q_L2_U = _intervals_to_quadrants(I_L2_U, f1L2F, f2L2F, y, t, F) Q_L3_U = Q_L3 Q_L4_U = _intervals_to_quadrants(I_L4_U, f1L4F, f2L4F, t, y, F) T_B = _traverse_quadrants(Q_L1_B, Q_L2_B, Q_L3_B, Q_L4_B, exclude=True) T_U = _traverse_quadrants(Q_L1_U, Q_L2_U, Q_L3_U, Q_L4_U, exclude=True) N_B = _winding_number(T_B, F) N_U = _winding_number(T_U, F) I_B = (I_L1_B, I_L2_B, I_L3_B, I_L4_B) Q_B = (Q_L1_B, Q_L2_B, Q_L3_B, Q_L4_B) I_U = (I_L1_U, I_L2_U, I_L3_U, I_L4_U) Q_U = (Q_L1_U, Q_L2_U, Q_L3_U, Q_L4_U) F1_B = (f1L1F, f1L2F, f1H, f1L4F) F2_B = (f2L1F, f2L2F, f2H, f2L4F) F1_U = (f1H, f1L2F, f1L3F, f1L4F) F2_U = (f2H, f2L2F, f2L3F, f2L4F) a, b = (u, v), (s, y) c, d = (u, y), (s, t) D_B = (N_B, a, b, I_B, Q_B, F1_B, F2_B) D_U = (N_U, c, d, I_U, Q_U, F1_U, F2_U) return D_B, D_U def _depth_first_select(rectangles): """Find a rectangle of minimum area for bisection. """ min_area, j = None, None for i, (_, (u, v), (s, t), _, _, _, _) in enumerate(rectangles): area = (s - u)*(t - v) if min_area is None or area < min_area: min_area, j = area, i return rectangles.pop(j) def _rectangle_small_p(a, b, eps): """Return ``True`` if the given rectangle is small enough. """ (u, v), (s, t) = a, b if eps is not None: return s - u < eps and t - v < eps else: return True def dup_isolate_complex_roots_sqf(f, K, eps=None, inf=None, sup=None, blackbox=False): """Isolate complex roots of a square-free polynomial using Collins-Krandick algorithm. """ if not K.is_ZZ and not K.is_QQ: raise DomainError("isolation of complex roots is not supported over %s" % K) if dup_degree(f) <= 0: return [] if K.is_ZZ: F = K.get_field() else: F = K f = dup_convert(f, K, F) lc = abs(dup_LC(f, F)) B = 2*max([ F.quo(abs(c), lc) for c in f ]) (u, v), (s, t) = (-B, F.zero), (B, B) if inf is not None: u = inf if sup is not None: s = sup if v < 0 or t <= v or s <= u: raise ValueError("not a valid complex isolation rectangle") f1, f2 = dup_real_imag(f, F) f1L1 = dmp_eval_in(f1, v, 1, 1, F) f2L1 = dmp_eval_in(f2, v, 1, 1, F) f1L2 = dmp_eval_in(f1, s, 0, 1, F) f2L2 = dmp_eval_in(f2, s, 0, 1, F) f1L3 = dmp_eval_in(f1, t, 1, 1, F) f2L3 = dmp_eval_in(f2, t, 1, 1, F) f1L4 = dmp_eval_in(f1, u, 0, 1, F) f2L4 = dmp_eval_in(f2, u, 0, 1, F) S_L1 = [f1L1, f2L1] S_L2 = [f1L2, f2L2] S_L3 = [f1L3, f2L3] S_L4 = [f1L4, f2L4] I_L1 = dup_isolate_real_roots_list(S_L1, F, inf=u, sup=s, fast=True, strict=True, basis=True) I_L2 = dup_isolate_real_roots_list(S_L2, F, inf=v, sup=t, fast=True, strict=True, basis=True) I_L3 = dup_isolate_real_roots_list(S_L3, F, inf=u, sup=s, fast=True, strict=True, basis=True) I_L4 = dup_isolate_real_roots_list(S_L4, F, inf=v, sup=t, fast=True, strict=True, basis=True) I_L3 = _reverse_intervals(I_L3) I_L4 = _reverse_intervals(I_L4) Q_L1 = _intervals_to_quadrants(I_L1, f1L1, f2L1, u, s, F) Q_L2 = _intervals_to_quadrants(I_L2, f1L2, f2L2, v, t, F) Q_L3 = _intervals_to_quadrants(I_L3, f1L3, f2L3, s, u, F) Q_L4 = _intervals_to_quadrants(I_L4, f1L4, f2L4, t, v, F) T = _traverse_quadrants(Q_L1, Q_L2, Q_L3, Q_L4) N = _winding_number(T, F) if not N: return [] I = (I_L1, I_L2, I_L3, I_L4) Q = (Q_L1, Q_L2, Q_L3, Q_L4) F1 = (f1L1, f1L2, f1L3, f1L4) F2 = (f2L1, f2L2, f2L3, f2L4) rectangles, roots = [(N, (u, v), (s, t), I, Q, F1, F2)], [] while rectangles: N, (u, v), (s, t), I, Q, F1, F2 = _depth_first_select(rectangles) if s - u > t - v: D_L, D_R = _vertical_bisection(N, (u, v), (s, t), I, Q, F1, F2, f1, f2, F) N_L, a, b, I_L, Q_L, F1_L, F2_L = D_L N_R, c, d, I_R, Q_R, F1_R, F2_R = D_R if N_L >= 1: if N_L == 1 and _rectangle_small_p(a, b, eps): roots.append(ComplexInterval(a, b, I_L, Q_L, F1_L, F2_L, f1, f2, F)) else: rectangles.append(D_L) if N_R >= 1: if N_R == 1 and _rectangle_small_p(c, d, eps): roots.append(ComplexInterval(c, d, I_R, Q_R, F1_R, F2_R, f1, f2, F)) else: rectangles.append(D_R) else: D_B, D_U = _horizontal_bisection(N, (u, v), (s, t), I, Q, F1, F2, f1, f2, F) N_B, a, b, I_B, Q_B, F1_B, F2_B = D_B N_U, c, d, I_U, Q_U, F1_U, F2_U = D_U if N_B >= 1: if N_B == 1 and _rectangle_small_p(a, b, eps): roots.append(ComplexInterval( a, b, I_B, Q_B, F1_B, F2_B, f1, f2, F)) else: rectangles.append(D_B) if N_U >= 1: if N_U == 1 and _rectangle_small_p(c, d, eps): roots.append(ComplexInterval( c, d, I_U, Q_U, F1_U, F2_U, f1, f2, F)) else: rectangles.append(D_U) _roots, roots = sorted(roots, key=lambda r: (r.ax, r.ay)), [] for root in _roots: roots.extend([root.conjugate(), root]) if blackbox: return roots else: return [ r.as_tuple() for r in roots ] def dup_isolate_all_roots_sqf(f, K, eps=None, inf=None, sup=None, fast=False, blackbox=False): """Isolate real and complex roots of a square-free polynomial ``f``. """ return ( dup_isolate_real_roots_sqf( f, K, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox), dup_isolate_complex_roots_sqf(f, K, eps=eps, inf=inf, sup=sup, blackbox=blackbox)) def dup_isolate_all_roots(f, K, eps=None, inf=None, sup=None, fast=False): """Isolate real and complex roots of a non-square-free polynomial ``f``. """ if not K.is_ZZ and not K.is_QQ: raise DomainError("isolation of real and complex roots is not supported over %s" % K) _, factors = dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) = factors real_part, complex_part = dup_isolate_all_roots_sqf( f, K, eps=eps, inf=inf, sup=sup, fast=fast) real_part = [ ((a, b), k) for (a, b) in real_part ] complex_part = [ ((a, b), k) for (a, b) in complex_part ] return real_part, complex_part else: raise NotImplementedError( "only trivial square-free polynomials are supported") class RealInterval: """A fully qualified representation of a real isolation interval. """ def __init__(self, data, f, dom): """Initialize new real interval with complete information. """ if len(data) == 2: s, t = data self.neg = False if s < 0: if t <= 0: f, s, t, self.neg = dup_mirror(f, dom), -t, -s, True else: raise ValueError("Cannot refine a real root in (%s, %s)" % (s, t)) a, b, c, d = _mobius_from_interval((s, t), dom.get_field()) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), dom) self.mobius = a, b, c, d else: self.mobius = data[:-1] self.neg = data[-1] self.f, self.dom = f, dom @property def func(self): return RealInterval @property def args(self): i = self return (i.mobius + (i.neg,), i.f, i.dom) def __eq__(self, other): if type(other) is not type(self): return False return self.args == other.args @property def a(self): """Return the position of the left end. """ field = self.dom.get_field() a, b, c, d = self.mobius if not self.neg: if a*d < b*c: return field(a, c) return field(b, d) else: if a*d > b*c: return -field(a, c) return -field(b, d) @property def b(self): """Return the position of the right end. """ was = self.neg self.neg = not was rv = -self.a self.neg = was return rv @property def dx(self): """Return width of the real isolating interval. """ return self.b - self.a @property def center(self): """Return the center of the real isolating interval. """ return (self.a + self.b)/2 @property def max_denom(self): """Return the largest denominator occurring in either endpoint. """ return max(self.a.denominator, self.b.denominator) def as_tuple(self): """Return tuple representation of real isolating interval. """ return (self.a, self.b) def __repr__(self): return "(%s, %s)" % (self.a, self.b) def __contains__(self, item): """ Say whether a complex number belongs to this real interval. Parameters ========== item : pair (re, im) or number re Either a pair giving the real and imaginary parts of the number, or else a real number. """ if isinstance(item, tuple): re, im = item else: re, im = item, 0 return im == 0 and self.a <= re <= self.b def is_disjoint(self, other): """Return ``True`` if two isolation intervals are disjoint. """ if isinstance(other, RealInterval): return (self.b < other.a or other.b < self.a) assert isinstance(other, ComplexInterval) return (self.b < other.ax or other.bx < self.a or other.ay*other.by > 0) def _inner_refine(self): """Internal one step real root refinement procedure. """ if self.mobius is None: return self f, mobius = dup_inner_refine_real_root( self.f, self.mobius, self.dom, steps=1, mobius=True) return RealInterval(mobius + (self.neg,), f, self.dom) def refine_disjoint(self, other): """Refine an isolating interval until it is disjoint with another one. """ expr = self while not expr.is_disjoint(other): expr, other = expr._inner_refine(), other._inner_refine() return expr, other def refine_size(self, dx): """Refine an isolating interval until it is of sufficiently small size. """ expr = self while not (expr.dx < dx): expr = expr._inner_refine() return expr def refine_step(self, steps=1): """Perform several steps of real root refinement algorithm. """ expr = self for _ in range(steps): expr = expr._inner_refine() return expr def refine(self): """Perform one step of real root refinement algorithm. """ return self._inner_refine() class ComplexInterval: """A fully qualified representation of a complex isolation interval. The printed form is shown as (ax, bx) x (ay, by) where (ax, ay) and (bx, by) are the coordinates of the southwest and northeast corners of the interval's rectangle, respectively. Examples ======== >>> from sympy import CRootOf, S >>> from sympy.abc import x >>> CRootOf.clear_cache() # for doctest reproducibility >>> root = CRootOf(x**10 - 2*x + 3, 9) >>> i = root._get_interval(); i (3/64, 3/32) x (9/8, 75/64) The real part of the root lies within the range [0, 3/4] while the imaginary part lies within the range [9/8, 3/2]: >>> root.n(3) 0.0766 + 1.14*I The width of the ranges in the x and y directions on the complex plane are: >>> i.dx, i.dy (3/64, 3/64) The center of the range is >>> i.center (9/128, 147/128) The northeast coordinate of the rectangle bounding the root in the complex plane is given by attribute b and the x and y components are accessed by bx and by: >>> i.b, i.bx, i.by ((3/32, 75/64), 3/32, 75/64) The southwest coordinate is similarly given by i.a >>> i.a, i.ax, i.ay ((3/64, 9/8), 3/64, 9/8) Although the interval prints to show only the real and imaginary range of the root, all the information of the underlying root is contained as properties of the interval. For example, an interval with a nonpositive imaginary range is considered to be the conjugate. Since the y values of y are in the range [0, 1/4] it is not the conjugate: >>> i.conj False The conjugate's interval is >>> ic = i.conjugate(); ic (3/64, 3/32) x (-75/64, -9/8) NOTE: the values printed still represent the x and y range in which the root -- conjugate, in this case -- is located, but the underlying a and b values of a root and its conjugate are the same: >>> assert i.a == ic.a and i.b == ic.b What changes are the reported coordinates of the bounding rectangle: >>> (i.ax, i.ay), (i.bx, i.by) ((3/64, 9/8), (3/32, 75/64)) >>> (ic.ax, ic.ay), (ic.bx, ic.by) ((3/64, -75/64), (3/32, -9/8)) The interval can be refined once: >>> i # for reference, this is the current interval (3/64, 3/32) x (9/8, 75/64) >>> i.refine() (3/64, 3/32) x (9/8, 147/128) Several refinement steps can be taken: >>> i.refine_step(2) # 2 steps (9/128, 3/32) x (9/8, 147/128) It is also possible to refine to a given tolerance: >>> tol = min(i.dx, i.dy)/2 >>> i.refine_size(tol) (9/128, 21/256) x (9/8, 291/256) A disjoint interval is one whose bounding rectangle does not overlap with another. An interval, necessarily, is not disjoint with itself, but any interval is disjoint with a conjugate since the conjugate rectangle will always be in the lower half of the complex plane and the non-conjugate in the upper half: >>> i.is_disjoint(i), i.is_disjoint(i.conjugate()) (False, True) The following interval j is not disjoint from i: >>> close = CRootOf(x**10 - 2*x + 300/S(101), 9) >>> j = close._get_interval(); j (75/1616, 75/808) x (225/202, 1875/1616) >>> i.is_disjoint(j) False The two can be made disjoint, however: >>> newi, newj = i.refine_disjoint(j) >>> newi (39/512, 159/2048) x (2325/2048, 4653/4096) >>> newj (3975/51712, 2025/25856) x (29325/25856, 117375/103424) Even though the real ranges overlap, the imaginary do not, so the roots have been resolved as distinct. Intervals are disjoint when either the real or imaginary component of the intervals is distinct. In the case above, the real components have not been resolved (so we do not know, yet, which root has the smaller real part) but the imaginary part of ``close`` is larger than ``root``: >>> close.n(3) 0.0771 + 1.13*I >>> root.n(3) 0.0766 + 1.14*I """ def __init__(self, a, b, I, Q, F1, F2, f1, f2, dom, conj=False): """Initialize new complex interval with complete information. """ # a and b are the SW and NE corner of the bounding interval, # (ax, ay) and (bx, by), respectively, for the NON-CONJUGATE # root (the one with the positive imaginary part); when working # with the conjugate, the a and b value are still non-negative # but the ay, by are reversed and have oppositite sign self.a, self.b = a, b self.I, self.Q = I, Q self.f1, self.F1 = f1, F1 self.f2, self.F2 = f2, F2 self.dom = dom self.conj = conj @property def func(self): return ComplexInterval @property def args(self): i = self return (i.a, i.b, i.I, i.Q, i.F1, i.F2, i.f1, i.f2, i.dom, i.conj) def __eq__(self, other): if type(other) is not type(self): return False return self.args == other.args @property def ax(self): """Return ``x`` coordinate of south-western corner. """ return self.a[0] @property def ay(self): """Return ``y`` coordinate of south-western corner. """ if not self.conj: return self.a[1] else: return -self.b[1] @property def bx(self): """Return ``x`` coordinate of north-eastern corner. """ return self.b[0] @property def by(self): """Return ``y`` coordinate of north-eastern corner. """ if not self.conj: return self.b[1] else: return -self.a[1] @property def dx(self): """Return width of the complex isolating interval. """ return self.b[0] - self.a[0] @property def dy(self): """Return height of the complex isolating interval. """ return self.b[1] - self.a[1] @property def center(self): """Return the center of the complex isolating interval. """ return ((self.ax + self.bx)/2, (self.ay + self.by)/2) @property def max_denom(self): """Return the largest denominator occurring in either endpoint. """ return max(self.ax.denominator, self.bx.denominator, self.ay.denominator, self.by.denominator) def as_tuple(self): """Return tuple representation of the complex isolating interval's SW and NE corners, respectively. """ return ((self.ax, self.ay), (self.bx, self.by)) def __repr__(self): return "(%s, %s) x (%s, %s)" % (self.ax, self.bx, self.ay, self.by) def conjugate(self): """This complex interval really is located in lower half-plane. """ return ComplexInterval(self.a, self.b, self.I, self.Q, self.F1, self.F2, self.f1, self.f2, self.dom, conj=True) def __contains__(self, item): """ Say whether a complex number belongs to this complex rectangular region. Parameters ========== item : pair (re, im) or number re Either a pair giving the real and imaginary parts of the number, or else a real number. """ if isinstance(item, tuple): re, im = item else: re, im = item, 0 return self.ax <= re <= self.bx and self.ay <= im <= self.by def is_disjoint(self, other): """Return ``True`` if two isolation intervals are disjoint. """ if isinstance(other, RealInterval): return other.is_disjoint(self) if self.conj != other.conj: # above and below real axis return True re_distinct = (self.bx < other.ax or other.bx < self.ax) if re_distinct: return True im_distinct = (self.by < other.ay or other.by < self.ay) return im_distinct def _inner_refine(self): """Internal one step complex root refinement procedure. """ (u, v), (s, t) = self.a, self.b I, Q = self.I, self.Q f1, F1 = self.f1, self.F1 f2, F2 = self.f2, self.F2 dom = self.dom if s - u > t - v: D_L, D_R = _vertical_bisection(1, (u, v), (s, t), I, Q, F1, F2, f1, f2, dom) if D_L[0] == 1: _, a, b, I, Q, F1, F2 = D_L else: _, a, b, I, Q, F1, F2 = D_R else: D_B, D_U = _horizontal_bisection(1, (u, v), (s, t), I, Q, F1, F2, f1, f2, dom) if D_B[0] == 1: _, a, b, I, Q, F1, F2 = D_B else: _, a, b, I, Q, F1, F2 = D_U return ComplexInterval(a, b, I, Q, F1, F2, f1, f2, dom, self.conj) def refine_disjoint(self, other): """Refine an isolating interval until it is disjoint with another one. """ expr = self while not expr.is_disjoint(other): expr, other = expr._inner_refine(), other._inner_refine() return expr, other def refine_size(self, dx, dy=None): """Refine an isolating interval until it is of sufficiently small size. """ if dy is None: dy = dx expr = self while not (expr.dx < dx and expr.dy < dy): expr = expr._inner_refine() return expr def refine_step(self, steps=1): """Perform several steps of complex root refinement algorithm. """ expr = self for _ in range(steps): expr = expr._inner_refine() return expr def refine(self): """Perform one step of complex root refinement algorithm. """ return self._inner_refine()
3a4a59888ac3daeff5601edd1363499a1a6dd5466804da17d89058dead548b1a
"""Compatibility interface between dense and sparse polys. """ from sympy.polys.densearith import dup_add_term from sympy.polys.densearith import dmp_add_term from sympy.polys.densearith import dup_sub_term from sympy.polys.densearith import dmp_sub_term from sympy.polys.densearith import dup_mul_term from sympy.polys.densearith import dmp_mul_term from sympy.polys.densearith import dup_add_ground from sympy.polys.densearith import dmp_add_ground from sympy.polys.densearith import dup_sub_ground from sympy.polys.densearith import dmp_sub_ground from sympy.polys.densearith import dup_mul_ground from sympy.polys.densearith import dmp_mul_ground from sympy.polys.densearith import dup_quo_ground from sympy.polys.densearith import dmp_quo_ground from sympy.polys.densearith import dup_exquo_ground from sympy.polys.densearith import dmp_exquo_ground from sympy.polys.densearith import dup_lshift from sympy.polys.densearith import dup_rshift from sympy.polys.densearith import dup_abs from sympy.polys.densearith import dmp_abs from sympy.polys.densearith import dup_neg from sympy.polys.densearith import dmp_neg from sympy.polys.densearith import dup_add from sympy.polys.densearith import dmp_add from sympy.polys.densearith import dup_sub from sympy.polys.densearith import dmp_sub from sympy.polys.densearith import dup_add_mul from sympy.polys.densearith import dmp_add_mul from sympy.polys.densearith import dup_sub_mul from sympy.polys.densearith import dmp_sub_mul from sympy.polys.densearith import dup_mul from sympy.polys.densearith import dmp_mul from sympy.polys.densearith import dup_sqr from sympy.polys.densearith import dmp_sqr from sympy.polys.densearith import dup_pow from sympy.polys.densearith import dmp_pow from sympy.polys.densearith import dup_pdiv from sympy.polys.densearith import dup_prem from sympy.polys.densearith import dup_pquo from sympy.polys.densearith import dup_pexquo from sympy.polys.densearith import dmp_pdiv from sympy.polys.densearith import dmp_prem from sympy.polys.densearith import dmp_pquo from sympy.polys.densearith import dmp_pexquo from sympy.polys.densearith import dup_rr_div from sympy.polys.densearith import dmp_rr_div from sympy.polys.densearith import dup_ff_div from sympy.polys.densearith import dmp_ff_div from sympy.polys.densearith import dup_div from sympy.polys.densearith import dup_rem from sympy.polys.densearith import dup_quo from sympy.polys.densearith import dup_exquo from sympy.polys.densearith import dmp_div from sympy.polys.densearith import dmp_rem from sympy.polys.densearith import dmp_quo from sympy.polys.densearith import dmp_exquo from sympy.polys.densearith import dup_max_norm from sympy.polys.densearith import dmp_max_norm from sympy.polys.densearith import dup_l1_norm from sympy.polys.densearith import dmp_l1_norm from sympy.polys.densearith import dup_l2_norm_squared from sympy.polys.densearith import dmp_l2_norm_squared from sympy.polys.densearith import dup_expand from sympy.polys.densearith import dmp_expand from sympy.polys.densebasic import dup_LC from sympy.polys.densebasic import dmp_LC from sympy.polys.densebasic import dup_TC from sympy.polys.densebasic import dmp_TC from sympy.polys.densebasic import dmp_ground_LC from sympy.polys.densebasic import dmp_ground_TC from sympy.polys.densebasic import dup_degree from sympy.polys.densebasic import dmp_degree from sympy.polys.densebasic import dmp_degree_in from sympy.polys.densebasic import dmp_to_dict from sympy.polys.densetools import dup_integrate from sympy.polys.densetools import dmp_integrate from sympy.polys.densetools import dmp_integrate_in from sympy.polys.densetools import dup_diff from sympy.polys.densetools import dmp_diff from sympy.polys.densetools import dmp_diff_in from sympy.polys.densetools import dup_eval from sympy.polys.densetools import dmp_eval from sympy.polys.densetools import dmp_eval_in from sympy.polys.densetools import dmp_eval_tail from sympy.polys.densetools import dmp_diff_eval_in from sympy.polys.densetools import dup_trunc from sympy.polys.densetools import dmp_trunc from sympy.polys.densetools import dmp_ground_trunc from sympy.polys.densetools import dup_monic from sympy.polys.densetools import dmp_ground_monic from sympy.polys.densetools import dup_content from sympy.polys.densetools import dmp_ground_content from sympy.polys.densetools import dup_primitive from sympy.polys.densetools import dmp_ground_primitive from sympy.polys.densetools import dup_extract from sympy.polys.densetools import dmp_ground_extract from sympy.polys.densetools import dup_real_imag from sympy.polys.densetools import dup_mirror from sympy.polys.densetools import dup_scale from sympy.polys.densetools import dup_shift from sympy.polys.densetools import dup_transform from sympy.polys.densetools import dup_compose from sympy.polys.densetools import dmp_compose from sympy.polys.densetools import dup_decompose from sympy.polys.densetools import dmp_lift from sympy.polys.densetools import dup_sign_variations from sympy.polys.densetools import dup_clear_denoms from sympy.polys.densetools import dmp_clear_denoms from sympy.polys.densetools import dup_revert from sympy.polys.euclidtools import dup_half_gcdex from sympy.polys.euclidtools import dmp_half_gcdex from sympy.polys.euclidtools import dup_gcdex from sympy.polys.euclidtools import dmp_gcdex from sympy.polys.euclidtools import dup_invert from sympy.polys.euclidtools import dmp_invert from sympy.polys.euclidtools import dup_euclidean_prs from sympy.polys.euclidtools import dmp_euclidean_prs from sympy.polys.euclidtools import dup_primitive_prs from sympy.polys.euclidtools import dmp_primitive_prs from sympy.polys.euclidtools import dup_inner_subresultants from sympy.polys.euclidtools import dup_subresultants from sympy.polys.euclidtools import dup_prs_resultant from sympy.polys.euclidtools import dup_resultant from sympy.polys.euclidtools import dmp_inner_subresultants from sympy.polys.euclidtools import dmp_subresultants from sympy.polys.euclidtools import dmp_prs_resultant from sympy.polys.euclidtools import dmp_zz_modular_resultant from sympy.polys.euclidtools import dmp_zz_collins_resultant from sympy.polys.euclidtools import dmp_qq_collins_resultant from sympy.polys.euclidtools import dmp_resultant from sympy.polys.euclidtools import dup_discriminant from sympy.polys.euclidtools import dmp_discriminant from sympy.polys.euclidtools import dup_rr_prs_gcd from sympy.polys.euclidtools import dup_ff_prs_gcd from sympy.polys.euclidtools import dmp_rr_prs_gcd from sympy.polys.euclidtools import dmp_ff_prs_gcd from sympy.polys.euclidtools import dup_zz_heu_gcd from sympy.polys.euclidtools import dmp_zz_heu_gcd from sympy.polys.euclidtools import dup_qq_heu_gcd from sympy.polys.euclidtools import dmp_qq_heu_gcd from sympy.polys.euclidtools import dup_inner_gcd from sympy.polys.euclidtools import dmp_inner_gcd from sympy.polys.euclidtools import dup_gcd from sympy.polys.euclidtools import dmp_gcd from sympy.polys.euclidtools import dup_rr_lcm from sympy.polys.euclidtools import dup_ff_lcm from sympy.polys.euclidtools import dup_lcm from sympy.polys.euclidtools import dmp_rr_lcm from sympy.polys.euclidtools import dmp_ff_lcm from sympy.polys.euclidtools import dmp_lcm from sympy.polys.euclidtools import dmp_content from sympy.polys.euclidtools import dmp_primitive from sympy.polys.euclidtools import dup_cancel from sympy.polys.euclidtools import dmp_cancel from sympy.polys.factortools import dup_trial_division from sympy.polys.factortools import dmp_trial_division from sympy.polys.factortools import dup_zz_mignotte_bound from sympy.polys.factortools import dmp_zz_mignotte_bound from sympy.polys.factortools import dup_zz_hensel_step from sympy.polys.factortools import dup_zz_hensel_lift from sympy.polys.factortools import dup_zz_zassenhaus from sympy.polys.factortools import dup_zz_irreducible_p from sympy.polys.factortools import dup_cyclotomic_p from sympy.polys.factortools import dup_zz_cyclotomic_poly from sympy.polys.factortools import dup_zz_cyclotomic_factor from sympy.polys.factortools import dup_zz_factor_sqf from sympy.polys.factortools import dup_zz_factor from sympy.polys.factortools import dmp_zz_wang_non_divisors from sympy.polys.factortools import dmp_zz_wang_lead_coeffs from sympy.polys.factortools import dup_zz_diophantine from sympy.polys.factortools import dmp_zz_diophantine from sympy.polys.factortools import dmp_zz_wang_hensel_lifting from sympy.polys.factortools import dmp_zz_wang from sympy.polys.factortools import dmp_zz_factor from sympy.polys.factortools import dup_qq_i_factor from sympy.polys.factortools import dup_zz_i_factor from sympy.polys.factortools import dmp_qq_i_factor from sympy.polys.factortools import dmp_zz_i_factor from sympy.polys.factortools import dup_ext_factor from sympy.polys.factortools import dmp_ext_factor from sympy.polys.factortools import dup_gf_factor from sympy.polys.factortools import dmp_gf_factor from sympy.polys.factortools import dup_factor_list from sympy.polys.factortools import dup_factor_list_include from sympy.polys.factortools import dmp_factor_list from sympy.polys.factortools import dmp_factor_list_include from sympy.polys.factortools import dup_irreducible_p from sympy.polys.factortools import dmp_irreducible_p from sympy.polys.rootisolation import dup_sturm from sympy.polys.rootisolation import dup_root_upper_bound from sympy.polys.rootisolation import dup_root_lower_bound from sympy.polys.rootisolation import dup_step_refine_real_root from sympy.polys.rootisolation import dup_inner_refine_real_root from sympy.polys.rootisolation import dup_outer_refine_real_root from sympy.polys.rootisolation import dup_refine_real_root from sympy.polys.rootisolation import dup_inner_isolate_real_roots from sympy.polys.rootisolation import dup_inner_isolate_positive_roots from sympy.polys.rootisolation import dup_inner_isolate_negative_roots from sympy.polys.rootisolation import dup_isolate_real_roots_sqf from sympy.polys.rootisolation import dup_isolate_real_roots from sympy.polys.rootisolation import dup_isolate_real_roots_list from sympy.polys.rootisolation import dup_count_real_roots from sympy.polys.rootisolation import dup_count_complex_roots from sympy.polys.rootisolation import dup_isolate_complex_roots_sqf from sympy.polys.rootisolation import dup_isolate_all_roots_sqf from sympy.polys.rootisolation import dup_isolate_all_roots from sympy.polys.sqfreetools import ( dup_sqf_p, dmp_sqf_p, dup_sqf_norm, dmp_sqf_norm, dup_gf_sqf_part, dmp_gf_sqf_part, dup_sqf_part, dmp_sqf_part, dup_gf_sqf_list, dmp_gf_sqf_list, dup_sqf_list, dup_sqf_list_include, dmp_sqf_list, dmp_sqf_list_include, dup_gff_list, dmp_gff_list) from sympy.polys.galoistools import ( gf_degree, gf_LC, gf_TC, gf_strip, gf_from_dict, gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, gf_mul_ground, gf_quo_ground, gf_add, gf_sub, gf_mul, gf_sqr, gf_add_mul, gf_sub_mul, gf_expand, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_pow, gf_pow_mod, gf_gcd, gf_lcm, gf_cofactors, gf_gcdex, gf_monic, gf_diff, gf_eval, gf_multi_eval, gf_compose, gf_compose_mod, gf_trace_map, gf_random, gf_irreducible, gf_irred_p_ben_or, gf_irred_p_rabin, gf_irreducible_p, gf_sqf_p, gf_sqf_part, gf_Qmatrix, gf_berlekamp, gf_ddf_zassenhaus, gf_edf_zassenhaus, gf_ddf_shoup, gf_edf_shoup, gf_zassenhaus, gf_shoup, gf_factor_sqf, gf_factor) from sympy.utilities import public @public class IPolys: symbols = None ngens = None domain = None order = None gens = None def drop(self, gen): pass def clone(self, symbols=None, domain=None, order=None): pass def to_ground(self): pass def ground_new(self, element): pass def domain_new(self, element): pass def from_dict(self, d): pass def wrap(self, element): from sympy.polys.rings import PolyElement if isinstance(element, PolyElement): if element.ring == self: return element else: raise NotImplementedError("domain conversions") else: return self.ground_new(element) def to_dense(self, element): return self.wrap(element).to_dense() def from_dense(self, element): return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) def dup_add_term(self, f, c, i): return self.from_dense(dup_add_term(self.to_dense(f), c, i, self.domain)) def dmp_add_term(self, f, c, i): return self.from_dense(dmp_add_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) def dup_sub_term(self, f, c, i): return self.from_dense(dup_sub_term(self.to_dense(f), c, i, self.domain)) def dmp_sub_term(self, f, c, i): return self.from_dense(dmp_sub_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) def dup_mul_term(self, f, c, i): return self.from_dense(dup_mul_term(self.to_dense(f), c, i, self.domain)) def dmp_mul_term(self, f, c, i): return self.from_dense(dmp_mul_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) def dup_add_ground(self, f, c): return self.from_dense(dup_add_ground(self.to_dense(f), c, self.domain)) def dmp_add_ground(self, f, c): return self.from_dense(dmp_add_ground(self.to_dense(f), c, self.ngens-1, self.domain)) def dup_sub_ground(self, f, c): return self.from_dense(dup_sub_ground(self.to_dense(f), c, self.domain)) def dmp_sub_ground(self, f, c): return self.from_dense(dmp_sub_ground(self.to_dense(f), c, self.ngens-1, self.domain)) def dup_mul_ground(self, f, c): return self.from_dense(dup_mul_ground(self.to_dense(f), c, self.domain)) def dmp_mul_ground(self, f, c): return self.from_dense(dmp_mul_ground(self.to_dense(f), c, self.ngens-1, self.domain)) def dup_quo_ground(self, f, c): return self.from_dense(dup_quo_ground(self.to_dense(f), c, self.domain)) def dmp_quo_ground(self, f, c): return self.from_dense(dmp_quo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) def dup_exquo_ground(self, f, c): return self.from_dense(dup_exquo_ground(self.to_dense(f), c, self.domain)) def dmp_exquo_ground(self, f, c): return self.from_dense(dmp_exquo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) def dup_lshift(self, f, n): return self.from_dense(dup_lshift(self.to_dense(f), n, self.domain)) def dup_rshift(self, f, n): return self.from_dense(dup_rshift(self.to_dense(f), n, self.domain)) def dup_abs(self, f): return self.from_dense(dup_abs(self.to_dense(f), self.domain)) def dmp_abs(self, f): return self.from_dense(dmp_abs(self.to_dense(f), self.ngens-1, self.domain)) def dup_neg(self, f): return self.from_dense(dup_neg(self.to_dense(f), self.domain)) def dmp_neg(self, f): return self.from_dense(dmp_neg(self.to_dense(f), self.ngens-1, self.domain)) def dup_add(self, f, g): return self.from_dense(dup_add(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_add(self, f, g): return self.from_dense(dmp_add(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_sub(self, f, g): return self.from_dense(dup_sub(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_sub(self, f, g): return self.from_dense(dmp_sub(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_add_mul(self, f, g, h): return self.from_dense(dup_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) def dmp_add_mul(self, f, g, h): return self.from_dense(dmp_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) def dup_sub_mul(self, f, g, h): return self.from_dense(dup_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) def dmp_sub_mul(self, f, g, h): return self.from_dense(dmp_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) def dup_mul(self, f, g): return self.from_dense(dup_mul(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_mul(self, f, g): return self.from_dense(dmp_mul(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_sqr(self, f): return self.from_dense(dup_sqr(self.to_dense(f), self.domain)) def dmp_sqr(self, f): return self.from_dense(dmp_sqr(self.to_dense(f), self.ngens-1, self.domain)) def dup_pow(self, f, n): return self.from_dense(dup_pow(self.to_dense(f), n, self.domain)) def dmp_pow(self, f, n): return self.from_dense(dmp_pow(self.to_dense(f), n, self.ngens-1, self.domain)) def dup_pdiv(self, f, g): q, r = dup_pdiv(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(q), self.from_dense(r)) def dup_prem(self, f, g): return self.from_dense(dup_prem(self.to_dense(f), self.to_dense(g), self.domain)) def dup_pquo(self, f, g): return self.from_dense(dup_pquo(self.to_dense(f), self.to_dense(g), self.domain)) def dup_pexquo(self, f, g): return self.from_dense(dup_pexquo(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_pdiv(self, f, g): q, r = dmp_pdiv(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(q), self.from_dense(r)) def dmp_prem(self, f, g): return self.from_dense(dmp_prem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dmp_pquo(self, f, g): return self.from_dense(dmp_pquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dmp_pexquo(self, f, g): return self.from_dense(dmp_pexquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_rr_div(self, f, g): q, r = dup_rr_div(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(q), self.from_dense(r)) def dmp_rr_div(self, f, g): q, r = dmp_rr_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(q), self.from_dense(r)) def dup_ff_div(self, f, g): q, r = dup_ff_div(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(q), self.from_dense(r)) def dmp_ff_div(self, f, g): q, r = dmp_ff_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(q), self.from_dense(r)) def dup_div(self, f, g): q, r = dup_div(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(q), self.from_dense(r)) def dup_rem(self, f, g): return self.from_dense(dup_rem(self.to_dense(f), self.to_dense(g), self.domain)) def dup_quo(self, f, g): return self.from_dense(dup_quo(self.to_dense(f), self.to_dense(g), self.domain)) def dup_exquo(self, f, g): return self.from_dense(dup_exquo(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_div(self, f, g): q, r = dmp_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(q), self.from_dense(r)) def dmp_rem(self, f, g): return self.from_dense(dmp_rem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dmp_quo(self, f, g): return self.from_dense(dmp_quo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dmp_exquo(self, f, g): return self.from_dense(dmp_exquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_max_norm(self, f): return dup_max_norm(self.to_dense(f), self.domain) def dmp_max_norm(self, f): return dmp_max_norm(self.to_dense(f), self.ngens-1, self.domain) def dup_l1_norm(self, f): return dup_l1_norm(self.to_dense(f), self.domain) def dmp_l1_norm(self, f): return dmp_l1_norm(self.to_dense(f), self.ngens-1, self.domain) def dup_l2_norm_squared(self, f): return dup_l2_norm_squared(self.to_dense(f), self.domain) def dmp_l2_norm_squared(self, f): return dmp_l2_norm_squared(self.to_dense(f), self.ngens-1, self.domain) def dup_expand(self, polys): return self.from_dense(dup_expand(list(map(self.to_dense, polys)), self.domain)) def dmp_expand(self, polys): return self.from_dense(dmp_expand(list(map(self.to_dense, polys)), self.ngens-1, self.domain)) def dup_LC(self, f): return dup_LC(self.to_dense(f), self.domain) def dmp_LC(self, f): LC = dmp_LC(self.to_dense(f), self.domain) if isinstance(LC, list): return self[1:].from_dense(LC) else: return LC def dup_TC(self, f): return dup_TC(self.to_dense(f), self.domain) def dmp_TC(self, f): TC = dmp_TC(self.to_dense(f), self.domain) if isinstance(TC, list): return self[1:].from_dense(TC) else: return TC def dmp_ground_LC(self, f): return dmp_ground_LC(self.to_dense(f), self.ngens-1, self.domain) def dmp_ground_TC(self, f): return dmp_ground_TC(self.to_dense(f), self.ngens-1, self.domain) def dup_degree(self, f): return dup_degree(self.to_dense(f)) def dmp_degree(self, f): return dmp_degree(self.to_dense(f), self.ngens-1) def dmp_degree_in(self, f, j): return dmp_degree_in(self.to_dense(f), j, self.ngens-1) def dup_integrate(self, f, m): return self.from_dense(dup_integrate(self.to_dense(f), m, self.domain)) def dmp_integrate(self, f, m): return self.from_dense(dmp_integrate(self.to_dense(f), m, self.ngens-1, self.domain)) def dup_diff(self, f, m): return self.from_dense(dup_diff(self.to_dense(f), m, self.domain)) def dmp_diff(self, f, m): return self.from_dense(dmp_diff(self.to_dense(f), m, self.ngens-1, self.domain)) def dmp_diff_in(self, f, m, j): return self.from_dense(dmp_diff_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) def dmp_integrate_in(self, f, m, j): return self.from_dense(dmp_integrate_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) def dup_eval(self, f, a): return dup_eval(self.to_dense(f), a, self.domain) def dmp_eval(self, f, a): result = dmp_eval(self.to_dense(f), a, self.ngens-1, self.domain) return self[1:].from_dense(result) def dmp_eval_in(self, f, a, j): result = dmp_eval_in(self.to_dense(f), a, j, self.ngens-1, self.domain) return self.drop(j).from_dense(result) def dmp_diff_eval_in(self, f, m, a, j): result = dmp_diff_eval_in(self.to_dense(f), m, a, j, self.ngens-1, self.domain) return self.drop(j).from_dense(result) def dmp_eval_tail(self, f, A): result = dmp_eval_tail(self.to_dense(f), A, self.ngens-1, self.domain) if isinstance(result, list): return self[:-len(A)].from_dense(result) else: return result def dup_trunc(self, f, p): return self.from_dense(dup_trunc(self.to_dense(f), p, self.domain)) def dmp_trunc(self, f, g): return self.from_dense(dmp_trunc(self.to_dense(f), self[1:].to_dense(g), self.ngens-1, self.domain)) def dmp_ground_trunc(self, f, p): return self.from_dense(dmp_ground_trunc(self.to_dense(f), p, self.ngens-1, self.domain)) def dup_monic(self, f): return self.from_dense(dup_monic(self.to_dense(f), self.domain)) def dmp_ground_monic(self, f): return self.from_dense(dmp_ground_monic(self.to_dense(f), self.ngens-1, self.domain)) def dup_extract(self, f, g): c, F, G = dup_extract(self.to_dense(f), self.to_dense(g), self.domain) return (c, self.from_dense(F), self.from_dense(G)) def dmp_ground_extract(self, f, g): c, F, G = dmp_ground_extract(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (c, self.from_dense(F), self.from_dense(G)) def dup_real_imag(self, f): p, q = dup_real_imag(self.wrap(f).drop(1).to_dense(), self.domain) return (self.from_dense(p), self.from_dense(q)) def dup_mirror(self, f): return self.from_dense(dup_mirror(self.to_dense(f), self.domain)) def dup_scale(self, f, a): return self.from_dense(dup_scale(self.to_dense(f), a, self.domain)) def dup_shift(self, f, a): return self.from_dense(dup_shift(self.to_dense(f), a, self.domain)) def dup_transform(self, f, p, q): return self.from_dense(dup_transform(self.to_dense(f), self.to_dense(p), self.to_dense(q), self.domain)) def dup_compose(self, f, g): return self.from_dense(dup_compose(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_compose(self, f, g): return self.from_dense(dmp_compose(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_decompose(self, f): components = dup_decompose(self.to_dense(f), self.domain) return list(map(self.from_dense, components)) def dmp_lift(self, f): result = dmp_lift(self.to_dense(f), self.ngens-1, self.domain) return self.to_ground().from_dense(result) def dup_sign_variations(self, f): return dup_sign_variations(self.to_dense(f), self.domain) def dup_clear_denoms(self, f, convert=False): c, F = dup_clear_denoms(self.to_dense(f), self.domain, convert=convert) if convert: ring = self.clone(domain=self.domain.get_ring()) else: ring = self return (c, ring.from_dense(F)) def dmp_clear_denoms(self, f, convert=False): c, F = dmp_clear_denoms(self.to_dense(f), self.ngens-1, self.domain, convert=convert) if convert: ring = self.clone(domain=self.domain.get_ring()) else: ring = self return (c, ring.from_dense(F)) def dup_revert(self, f, n): return self.from_dense(dup_revert(self.to_dense(f), n, self.domain)) def dup_half_gcdex(self, f, g): s, h = dup_half_gcdex(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(s), self.from_dense(h)) def dmp_half_gcdex(self, f, g): s, h = dmp_half_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(s), self.from_dense(h)) def dup_gcdex(self, f, g): s, t, h = dup_gcdex(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) def dmp_gcdex(self, f, g): s, t, h = dmp_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) def dup_invert(self, f, g): return self.from_dense(dup_invert(self.to_dense(f), self.to_dense(g), self.domain)) def dmp_invert(self, f, g): return self.from_dense(dmp_invert(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) def dup_euclidean_prs(self, f, g): prs = dup_euclidean_prs(self.to_dense(f), self.to_dense(g), self.domain) return list(map(self.from_dense, prs)) def dmp_euclidean_prs(self, f, g): prs = dmp_euclidean_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return list(map(self.from_dense, prs)) def dup_primitive_prs(self, f, g): prs = dup_primitive_prs(self.to_dense(f), self.to_dense(g), self.domain) return list(map(self.from_dense, prs)) def dmp_primitive_prs(self, f, g): prs = dmp_primitive_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return list(map(self.from_dense, prs)) def dup_inner_subresultants(self, f, g): prs, sres = dup_inner_subresultants(self.to_dense(f), self.to_dense(g), self.domain) return (list(map(self.from_dense, prs)), sres) def dmp_inner_subresultants(self, f, g): prs, sres = dmp_inner_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (list(map(self.from_dense, prs)), sres) def dup_subresultants(self, f, g): prs = dup_subresultants(self.to_dense(f), self.to_dense(g), self.domain) return list(map(self.from_dense, prs)) def dmp_subresultants(self, f, g): prs = dmp_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return list(map(self.from_dense, prs)) def dup_prs_resultant(self, f, g): res, prs = dup_prs_resultant(self.to_dense(f), self.to_dense(g), self.domain) return (res, list(map(self.from_dense, prs))) def dmp_prs_resultant(self, f, g): res, prs = dmp_prs_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self[1:].from_dense(res), list(map(self.from_dense, prs))) def dmp_zz_modular_resultant(self, f, g, p): res = dmp_zz_modular_resultant(self.to_dense(f), self.to_dense(g), self.domain_new(p), self.ngens-1, self.domain) return self[1:].from_dense(res) def dmp_zz_collins_resultant(self, f, g): res = dmp_zz_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self[1:].from_dense(res) def dmp_qq_collins_resultant(self, f, g): res = dmp_qq_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self[1:].from_dense(res) def dup_resultant(self, f, g): #, includePRS=False): return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) #, includePRS=includePRS) def dmp_resultant(self, f, g): #, includePRS=False): res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) #, includePRS=includePRS) if isinstance(res, list): return self[1:].from_dense(res) else: return res def dup_discriminant(self, f): return dup_discriminant(self.to_dense(f), self.domain) def dmp_discriminant(self, f): disc = dmp_discriminant(self.to_dense(f), self.ngens-1, self.domain) if isinstance(disc, list): return self[1:].from_dense(disc) else: return disc def dup_rr_prs_gcd(self, f, g): H, F, G = dup_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dup_ff_prs_gcd(self, f, g): H, F, G = dup_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dmp_rr_prs_gcd(self, f, g): H, F, G = dmp_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dmp_ff_prs_gcd(self, f, g): H, F, G = dmp_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dup_zz_heu_gcd(self, f, g): H, F, G = dup_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dmp_zz_heu_gcd(self, f, g): H, F, G = dmp_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dup_qq_heu_gcd(self, f, g): H, F, G = dup_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dmp_qq_heu_gcd(self, f, g): H, F, G = dmp_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dup_inner_gcd(self, f, g): H, F, G = dup_inner_gcd(self.to_dense(f), self.to_dense(g), self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dmp_inner_gcd(self, f, g): H, F, G = dmp_inner_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) def dup_gcd(self, f, g): H = dup_gcd(self.to_dense(f), self.to_dense(g), self.domain) return self.from_dense(H) def dmp_gcd(self, f, g): H = dmp_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self.from_dense(H) def dup_rr_lcm(self, f, g): H = dup_rr_lcm(self.to_dense(f), self.to_dense(g), self.domain) return self.from_dense(H) def dup_ff_lcm(self, f, g): H = dup_ff_lcm(self.to_dense(f), self.to_dense(g), self.domain) return self.from_dense(H) def dup_lcm(self, f, g): H = dup_lcm(self.to_dense(f), self.to_dense(g), self.domain) return self.from_dense(H) def dmp_rr_lcm(self, f, g): H = dmp_rr_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self.from_dense(H) def dmp_ff_lcm(self, f, g): H = dmp_ff_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self.from_dense(H) def dmp_lcm(self, f, g): H = dmp_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self.from_dense(H) def dup_content(self, f): cont = dup_content(self.to_dense(f), self.domain) return cont def dup_primitive(self, f): cont, prim = dup_primitive(self.to_dense(f), self.domain) return cont, self.from_dense(prim) def dmp_content(self, f): cont = dmp_content(self.to_dense(f), self.ngens-1, self.domain) if isinstance(cont, list): return self[1:].from_dense(cont) else: return cont def dmp_primitive(self, f): cont, prim = dmp_primitive(self.to_dense(f), self.ngens-1, self.domain) if isinstance(cont, list): return (self[1:].from_dense(cont), self.from_dense(prim)) else: return (cont, self.from_dense(prim)) def dmp_ground_content(self, f): cont = dmp_ground_content(self.to_dense(f), self.ngens-1, self.domain) return cont def dmp_ground_primitive(self, f): cont, prim = dmp_ground_primitive(self.to_dense(f), self.ngens-1, self.domain) return (cont, self.from_dense(prim)) def dup_cancel(self, f, g, include=True): result = dup_cancel(self.to_dense(f), self.to_dense(g), self.domain, include=include) if not include: cf, cg, F, G = result return (cf, cg, self.from_dense(F), self.from_dense(G)) else: F, G = result return (self.from_dense(F), self.from_dense(G)) def dmp_cancel(self, f, g, include=True): result = dmp_cancel(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain, include=include) if not include: cf, cg, F, G = result return (cf, cg, self.from_dense(F), self.from_dense(G)) else: F, G = result return (self.from_dense(F), self.from_dense(G)) def dup_trial_division(self, f, factors): factors = dup_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dmp_trial_division(self, f, factors): factors = dmp_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.ngens-1, self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dup_zz_mignotte_bound(self, f): return dup_zz_mignotte_bound(self.to_dense(f), self.domain) def dmp_zz_mignotte_bound(self, f): return dmp_zz_mignotte_bound(self.to_dense(f), self.ngens-1, self.domain) def dup_zz_hensel_step(self, m, f, g, h, s, t): D = self.to_dense G, H, S, T = dup_zz_hensel_step(m, D(f), D(g), D(h), D(s), D(t), self.domain) return (self.from_dense(G), self.from_dense(H), self.from_dense(S), self.from_dense(T)) def dup_zz_hensel_lift(self, p, f, f_list, l): D = self.to_dense polys = dup_zz_hensel_lift(p, D(f), list(map(D, f_list)), l, self.domain) return list(map(self.from_dense, polys)) def dup_zz_zassenhaus(self, f): factors = dup_zz_zassenhaus(self.to_dense(f), self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dup_zz_irreducible_p(self, f): return dup_zz_irreducible_p(self.to_dense(f), self.domain) def dup_cyclotomic_p(self, f, irreducible=False): return dup_cyclotomic_p(self.to_dense(f), self.domain, irreducible=irreducible) def dup_zz_cyclotomic_poly(self, n): F = dup_zz_cyclotomic_poly(n, self.domain) return self.from_dense(F) def dup_zz_cyclotomic_factor(self, f): result = dup_zz_cyclotomic_factor(self.to_dense(f), self.domain) if result is None: return result else: return list(map(self.from_dense, result)) # E: List[ZZ], cs: ZZ, ct: ZZ def dmp_zz_wang_non_divisors(self, E, cs, ct): return dmp_zz_wang_non_divisors(E, cs, ct, self.domain) # f: Poly, T: List[(Poly, int)], ct: ZZ, A: List[ZZ] #def dmp_zz_wang_test_points(f, T, ct, A): # dmp_zz_wang_test_points(self.to_dense(f), T, ct, A, self.ngens-1, self.domain) # f: Poly, T: List[(Poly, int)], cs: ZZ, E: List[ZZ], H: List[Poly], A: List[ZZ] def dmp_zz_wang_lead_coeffs(self, f, T, cs, E, H, A): mv = self[1:] T = [ (mv.to_dense(t), k) for t, k in T ] uv = self[:1] H = list(map(uv.to_dense, H)) f, HH, CC = dmp_zz_wang_lead_coeffs(self.to_dense(f), T, cs, E, H, A, self.ngens-1, self.domain) return self.from_dense(f), list(map(uv.from_dense, HH)), list(map(mv.from_dense, CC)) # f: List[Poly], m: int, p: ZZ def dup_zz_diophantine(self, F, m, p): result = dup_zz_diophantine(list(map(self.to_dense, F)), m, p, self.domain) return list(map(self.from_dense, result)) # f: List[Poly], c: List[Poly], A: List[ZZ], d: int, p: ZZ def dmp_zz_diophantine(self, F, c, A, d, p): result = dmp_zz_diophantine(list(map(self.to_dense, F)), self.to_dense(c), A, d, p, self.ngens-1, self.domain) return list(map(self.from_dense, result)) # f: Poly, H: List[Poly], LC: List[Poly], A: List[ZZ], p: ZZ def dmp_zz_wang_hensel_lifting(self, f, H, LC, A, p): uv = self[:1] mv = self[1:] H = list(map(uv.to_dense, H)) LC = list(map(mv.to_dense, LC)) result = dmp_zz_wang_hensel_lifting(self.to_dense(f), H, LC, A, p, self.ngens-1, self.domain) return list(map(self.from_dense, result)) def dmp_zz_wang(self, f, mod=None, seed=None): factors = dmp_zz_wang(self.to_dense(f), self.ngens-1, self.domain, mod=mod, seed=seed) return [ self.from_dense(g) for g in factors ] def dup_zz_factor_sqf(self, f): coeff, factors = dup_zz_factor_sqf(self.to_dense(f), self.domain) return (coeff, [ self.from_dense(g) for g in factors ]) def dup_zz_factor(self, f): coeff, factors = dup_zz_factor(self.to_dense(f), self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_zz_factor(self, f): coeff, factors = dmp_zz_factor(self.to_dense(f), self.ngens-1, self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_qq_i_factor(self, f): coeff, factors = dup_qq_i_factor(self.to_dense(f), self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_qq_i_factor(self, f): coeff, factors = dmp_qq_i_factor(self.to_dense(f), self.ngens-1, self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_zz_i_factor(self, f): coeff, factors = dup_zz_i_factor(self.to_dense(f), self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_zz_i_factor(self, f): coeff, factors = dmp_zz_i_factor(self.to_dense(f), self.ngens-1, self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_ext_factor(self, f): coeff, factors = dup_ext_factor(self.to_dense(f), self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_ext_factor(self, f): coeff, factors = dmp_ext_factor(self.to_dense(f), self.ngens-1, self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_gf_factor(self, f): coeff, factors = dup_gf_factor(self.to_dense(f), self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_gf_factor(self, f): coeff, factors = dmp_gf_factor(self.to_dense(f), self.ngens-1, self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_factor_list(self, f): coeff, factors = dup_factor_list(self.to_dense(f), self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_factor_list_include(self, f): factors = dup_factor_list_include(self.to_dense(f), self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dmp_factor_list(self, f): coeff, factors = dmp_factor_list(self.to_dense(f), self.ngens-1, self.domain) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_factor_list_include(self, f): factors = dmp_factor_list_include(self.to_dense(f), self.ngens-1, self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dup_irreducible_p(self, f): return dup_irreducible_p(self.to_dense(f), self.domain) def dmp_irreducible_p(self, f): return dmp_irreducible_p(self.to_dense(f), self.ngens-1, self.domain) def dup_sturm(self, f): seq = dup_sturm(self.to_dense(f), self.domain) return list(map(self.from_dense, seq)) def dup_sqf_p(self, f): return dup_sqf_p(self.to_dense(f), self.domain) def dmp_sqf_p(self, f): return dmp_sqf_p(self.to_dense(f), self.ngens-1, self.domain) def dup_sqf_norm(self, f): s, F, R = dup_sqf_norm(self.to_dense(f), self.domain) return (s, self.from_dense(F), self.to_ground().from_dense(R)) def dmp_sqf_norm(self, f): s, F, R = dmp_sqf_norm(self.to_dense(f), self.ngens-1, self.domain) return (s, self.from_dense(F), self.to_ground().from_dense(R)) def dup_gf_sqf_part(self, f): return self.from_dense(dup_gf_sqf_part(self.to_dense(f), self.domain)) def dmp_gf_sqf_part(self, f): return self.from_dense(dmp_gf_sqf_part(self.to_dense(f), self.domain)) def dup_sqf_part(self, f): return self.from_dense(dup_sqf_part(self.to_dense(f), self.domain)) def dmp_sqf_part(self, f): return self.from_dense(dmp_sqf_part(self.to_dense(f), self.ngens-1, self.domain)) def dup_gf_sqf_list(self, f, all=False): coeff, factors = dup_gf_sqf_list(self.to_dense(f), self.domain, all=all) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_gf_sqf_list(self, f, all=False): coeff, factors = dmp_gf_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_sqf_list(self, f, all=False): coeff, factors = dup_sqf_list(self.to_dense(f), self.domain, all=all) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dup_sqf_list_include(self, f, all=False): factors = dup_sqf_list_include(self.to_dense(f), self.domain, all=all) return [ (self.from_dense(g), k) for g, k in factors ] def dmp_sqf_list(self, f, all=False): coeff, factors = dmp_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) def dmp_sqf_list_include(self, f, all=False): factors = dmp_sqf_list_include(self.to_dense(f), self.ngens-1, self.domain, all=all) return [ (self.from_dense(g), k) for g, k in factors ] def dup_gff_list(self, f): factors = dup_gff_list(self.to_dense(f), self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dmp_gff_list(self, f): factors = dmp_gff_list(self.to_dense(f), self.ngens-1, self.domain) return [ (self.from_dense(g), k) for g, k in factors ] def dup_root_upper_bound(self, f): return dup_root_upper_bound(self.to_dense(f), self.domain) def dup_root_lower_bound(self, f): return dup_root_lower_bound(self.to_dense(f), self.domain) def dup_step_refine_real_root(self, f, M, fast=False): return dup_step_refine_real_root(self.to_dense(f), M, self.domain, fast=fast) def dup_inner_refine_real_root(self, f, M, eps=None, steps=None, disjoint=None, fast=False, mobius=False): return dup_inner_refine_real_root(self.to_dense(f), M, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast, mobius=mobius) def dup_outer_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): return dup_outer_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) def dup_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): return dup_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) def dup_inner_isolate_real_roots(self, f, eps=None, fast=False): return dup_inner_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, fast=fast) def dup_inner_isolate_positive_roots(self, f, eps=None, inf=None, sup=None, fast=False, mobius=False): return dup_inner_isolate_positive_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, mobius=mobius) def dup_inner_isolate_negative_roots(self, f, inf=None, sup=None, eps=None, fast=False, mobius=False): return dup_inner_isolate_negative_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, eps=eps, fast=fast, mobius=mobius) def dup_isolate_real_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): return dup_isolate_real_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) def dup_isolate_real_roots(self, f, eps=None, inf=None, sup=None, basis=False, fast=False): return dup_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, basis=basis, fast=fast) def dup_isolate_real_roots_list(self, polys, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): return dup_isolate_real_roots_list(list(map(self.to_dense, polys)), self.domain, eps=eps, inf=inf, sup=sup, strict=strict, basis=basis, fast=fast) def dup_count_real_roots(self, f, inf=None, sup=None): return dup_count_real_roots(self.to_dense(f), self.domain, inf=inf, sup=sup) def dup_count_complex_roots(self, f, inf=None, sup=None, exclude=None): return dup_count_complex_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, exclude=exclude) def dup_isolate_complex_roots_sqf(self, f, eps=None, inf=None, sup=None, blackbox=False): return dup_isolate_complex_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, blackbox=blackbox) def dup_isolate_all_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): return dup_isolate_all_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) def dup_isolate_all_roots(self, f, eps=None, inf=None, sup=None, fast=False): return dup_isolate_all_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast) def fateman_poly_F_1(self): from sympy.polys.specialpolys import dmp_fateman_poly_F_1 return tuple(map(self.from_dense, dmp_fateman_poly_F_1(self.ngens-1, self.domain))) def fateman_poly_F_2(self): from sympy.polys.specialpolys import dmp_fateman_poly_F_2 return tuple(map(self.from_dense, dmp_fateman_poly_F_2(self.ngens-1, self.domain))) def fateman_poly_F_3(self): from sympy.polys.specialpolys import dmp_fateman_poly_F_3 return tuple(map(self.from_dense, dmp_fateman_poly_F_3(self.ngens-1, self.domain))) def to_gf_dense(self, element): return gf_strip([ self.domain.dom.convert(c, self.domain) for c in self.wrap(element).to_dense() ]) def from_gf_dense(self, element): return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain.dom)) def gf_degree(self, f): return gf_degree(self.to_gf_dense(f)) def gf_LC(self, f): return gf_LC(self.to_gf_dense(f), self.domain.dom) def gf_TC(self, f): return gf_TC(self.to_gf_dense(f), self.domain.dom) def gf_strip(self, f): return self.from_gf_dense(gf_strip(self.to_gf_dense(f))) def gf_trunc(self, f): return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod)) def gf_normal(self, f): return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_from_dict(self, f): return self.from_gf_dense(gf_from_dict(f, self.domain.mod, self.domain.dom)) def gf_to_dict(self, f, symmetric=True): return gf_to_dict(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) def gf_from_int_poly(self, f): return self.from_gf_dense(gf_from_int_poly(f, self.domain.mod)) def gf_to_int_poly(self, f, symmetric=True): return gf_to_int_poly(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) def gf_neg(self, f): return self.from_gf_dense(gf_neg(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_add_ground(self, f, a): return self.from_gf_dense(gf_add_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) def gf_sub_ground(self, f, a): return self.from_gf_dense(gf_sub_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) def gf_mul_ground(self, f, a): return self.from_gf_dense(gf_mul_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) def gf_quo_ground(self, f, a): return self.from_gf_dense(gf_quo_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) def gf_add(self, f, g): return self.from_gf_dense(gf_add(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_sub(self, f, g): return self.from_gf_dense(gf_sub(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_mul(self, f, g): return self.from_gf_dense(gf_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_sqr(self, f): return self.from_gf_dense(gf_sqr(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_add_mul(self, f, g, h): return self.from_gf_dense(gf_add_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) def gf_sub_mul(self, f, g, h): return self.from_gf_dense(gf_sub_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) def gf_expand(self, F): return self.from_gf_dense(gf_expand(list(map(self.to_gf_dense, F)), self.domain.mod, self.domain.dom)) def gf_div(self, f, g): q, r = gf_div(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) return self.from_gf_dense(q), self.from_gf_dense(r) def gf_rem(self, f, g): return self.from_gf_dense(gf_rem(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_quo(self, f, g): return self.from_gf_dense(gf_quo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_exquo(self, f, g): return self.from_gf_dense(gf_exquo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_lshift(self, f, n): return self.from_gf_dense(gf_lshift(self.to_gf_dense(f), n, self.domain.dom)) def gf_rshift(self, f, n): return self.from_gf_dense(gf_rshift(self.to_gf_dense(f), n, self.domain.dom)) def gf_pow(self, f, n): return self.from_gf_dense(gf_pow(self.to_gf_dense(f), n, self.domain.mod, self.domain.dom)) def gf_pow_mod(self, f, n, g): return self.from_gf_dense(gf_pow_mod(self.to_gf_dense(f), n, self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_cofactors(self, f, g): h, cff, cfg = gf_cofactors(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) return self.from_gf_dense(h), self.from_gf_dense(cff), self.from_gf_dense(cfg) def gf_gcd(self, f, g): return self.from_gf_dense(gf_gcd(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_lcm(self, f, g): return self.from_gf_dense(gf_lcm(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_gcdex(self, f, g): return self.from_gf_dense(gf_gcdex(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_monic(self, f): return self.from_gf_dense(gf_monic(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_diff(self, f): return self.from_gf_dense(gf_diff(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_eval(self, f, a): return gf_eval(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom) def gf_multi_eval(self, f, A): return gf_multi_eval(self.to_gf_dense(f), A, self.domain.mod, self.domain.dom) def gf_compose(self, f, g): return self.from_gf_dense(gf_compose(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) def gf_compose_mod(self, g, h, f): return self.from_gf_dense(gf_compose_mod(self.to_gf_dense(g), self.to_gf_dense(h), self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_trace_map(self, a, b, c, n, f): a = self.to_gf_dense(a) b = self.to_gf_dense(b) c = self.to_gf_dense(c) f = self.to_gf_dense(f) U, V = gf_trace_map(a, b, c, n, f, self.domain.mod, self.domain.dom) return self.from_gf_dense(U), self.from_gf_dense(V) def gf_random(self, n): return self.from_gf_dense(gf_random(n, self.domain.mod, self.domain.dom)) def gf_irreducible(self, n): return self.from_gf_dense(gf_irreducible(n, self.domain.mod, self.domain.dom)) def gf_irred_p_ben_or(self, f): return gf_irred_p_ben_or(self.to_gf_dense(f), self.domain.mod, self.domain.dom) def gf_irred_p_rabin(self, f): return gf_irred_p_rabin(self.to_gf_dense(f), self.domain.mod, self.domain.dom) def gf_irreducible_p(self, f): return gf_irreducible_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) def gf_sqf_p(self, f): return gf_sqf_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) def gf_sqf_part(self, f): return self.from_gf_dense(gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) def gf_sqf_list(self, f, all=False): coeff, factors = gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] def gf_Qmatrix(self, f): return gf_Qmatrix(self.to_gf_dense(f), self.domain.mod, self.domain.dom) def gf_berlekamp(self, f): factors = gf_berlekamp(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ self.from_gf_dense(g) for g in factors ] def gf_ddf_zassenhaus(self, f): factors = gf_ddf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ (self.from_gf_dense(g), k) for g, k in factors ] def gf_edf_zassenhaus(self, f, n): factors = gf_edf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ self.from_gf_dense(g) for g in factors ] def gf_ddf_shoup(self, f): factors = gf_ddf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ (self.from_gf_dense(g), k) for g, k in factors ] def gf_edf_shoup(self, f, n): factors = gf_edf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ self.from_gf_dense(g) for g in factors ] def gf_zassenhaus(self, f): factors = gf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ self.from_gf_dense(g) for g in factors ] def gf_shoup(self, f): factors = gf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return [ self.from_gf_dense(g) for g in factors ] def gf_factor_sqf(self, f, method=None): coeff, factors = gf_factor_sqf(self.to_gf_dense(f), self.domain.mod, self.domain.dom, method=method) return coeff, [ self.from_gf_dense(g) for g in factors ] def gf_factor(self, f): coeff, factors = gf_factor(self.to_gf_dense(f), self.domain.mod, self.domain.dom) return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ]
d2c656a59e062c1aa3b7cabbaf3de9f1d89a7f202811cb6ddb8119d19a902414
""" This module contains functions for two multivariate resultants. These are: - Dixon's resultant. - Macaulay's resultant. Multivariate resultants are used to identify whether a multivariate system has common roots. That is when the resultant is equal to zero. """ from sympy.core.mul import (Mul, prod) from sympy.matrices.dense import (Matrix, diag) from sympy.polys.polytools import (Poly, degree_list, rem) from sympy.simplify.simplify import simplify from sympy.tensor.indexed import IndexedBase from sympy.polys.monomials import itermonomials, monomial_deg from sympy.polys.orderings import monomial_key from sympy.polys.polytools import poly_from_expr, total_degree from sympy.functions.combinatorial.factorials import binomial from itertools import combinations_with_replacement from sympy.utilities.exceptions import sympy_deprecation_warning class DixonResultant(): """ A class for retrieving the Dixon's resultant of a multivariate system. Examples ======== >>> from sympy import symbols >>> from sympy.polys.multivariate_resultants import DixonResultant >>> x, y = symbols('x, y') >>> p = x + y >>> q = x ** 2 + y ** 3 >>> h = x ** 2 + y >>> dixon = DixonResultant(variables=[x, y], polynomials=[p, q, h]) >>> poly = dixon.get_dixon_polynomial() >>> matrix = dixon.get_dixon_matrix(polynomial=poly) >>> matrix Matrix([ [ 0, 0, -1, 0, -1], [ 0, -1, 0, -1, 0], [-1, 0, 1, 0, 0], [ 0, -1, 0, 0, 1], [-1, 0, 0, 1, 0]]) >>> matrix.det() 0 See Also ======== Notebook in examples: sympy/example/notebooks. References ========== .. [1] [Kapur1994]_ .. [2] [Palancz08]_ """ def __init__(self, polynomials, variables): """ A class that takes two lists, a list of polynomials and list of variables. Returns the Dixon matrix of the multivariate system. Parameters ---------- polynomials : list of polynomials A list of m n-degree polynomials variables: list A list of all n variables """ self.polynomials = polynomials self.variables = variables self.n = len(self.variables) self.m = len(self.polynomials) a = IndexedBase("alpha") # A list of n alpha variables (the replacing variables) self.dummy_variables = [a[i] for i in range(self.n)] # A list of the d_max of each variable. self._max_degrees = [max(degree_list(poly)[i] for poly in self.polynomials) for i in range(self.n)] @property def max_degrees(self): sympy_deprecation_warning( """ The max_degrees property of DixonResultant is deprecated. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-dixonresultant-properties", ) return self._max_degrees def get_dixon_polynomial(self): r""" Returns ======= dixon_polynomial: polynomial Dixon's polynomial is calculated as: delta = Delta(A) / ((x_1 - a_1) ... (x_n - a_n)) where, A = |p_1(x_1,... x_n), ..., p_n(x_1,... x_n)| |p_1(a_1,... x_n), ..., p_n(a_1,... x_n)| |... , ..., ...| |p_1(a_1,... a_n), ..., p_n(a_1,... a_n)| """ if self.m != (self.n + 1): raise ValueError('Method invalid for given combination.') # First row rows = [self.polynomials] temp = list(self.variables) for idx in range(self.n): temp[idx] = self.dummy_variables[idx] substitution = {var: t for var, t in zip(self.variables, temp)} rows.append([f.subs(substitution) for f in self.polynomials]) A = Matrix(rows) terms = zip(self.variables, self.dummy_variables) product_of_differences = Mul(*[a - b for a, b in terms]) dixon_polynomial = (A.det() / product_of_differences).factor() return poly_from_expr(dixon_polynomial, self.dummy_variables)[0] def get_upper_degree(self): sympy_deprecation_warning( """ The get_upper_degree() method of DixonResultant is deprecated. Use get_max_degrees() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-dixonresultant-properties" ) list_of_products = [self.variables[i] ** self._max_degrees[i] for i in range(self.n)] product = prod(list_of_products) product = Poly(product).monoms() return monomial_deg(*product) def get_max_degrees(self, polynomial): r""" Returns a list of the maximum degree of each variable appearing in the coefficients of the Dixon polynomial. The coefficients are viewed as polys in $x_1, x_2, \dots, x_n$. """ deg_lists = [degree_list(Poly(poly, self.variables)) for poly in polynomial.coeffs()] max_degrees = [max(degs) for degs in zip(*deg_lists)] return max_degrees def get_dixon_matrix(self, polynomial): r""" Construct the Dixon matrix from the coefficients of polynomial \alpha. Each coefficient is viewed as a polynomial of x_1, ..., x_n. """ max_degrees = self.get_max_degrees(polynomial) # list of column headers of the Dixon matrix. monomials = itermonomials(self.variables, max_degrees) monomials = sorted(monomials, reverse=True, key=monomial_key('lex', self.variables)) dixon_matrix = Matrix([[Poly(c, *self.variables).coeff_monomial(m) for m in monomials] for c in polynomial.coeffs()]) # remove columns if needed if dixon_matrix.shape[0] != dixon_matrix.shape[1]: keep = [column for column in range(dixon_matrix.shape[-1]) if any(element != 0 for element in dixon_matrix[:, column])] dixon_matrix = dixon_matrix[:, keep] return dixon_matrix def KSY_precondition(self, matrix): """ Test for the validity of the Kapur-Saxena-Yang precondition. The precondition requires that the column corresponding to the monomial 1 = x_1 ^ 0 * x_2 ^ 0 * ... * x_n ^ 0 is not a linear combination of the remaining ones. In SymPy notation this is the last column. For the precondition to hold the last non-zero row of the rref matrix should be of the form [0, 0, ..., 1]. """ if matrix.is_zero_matrix: return False m, n = matrix.shape # simplify the matrix and keep only its non-zero rows matrix = simplify(matrix.rref()[0]) rows = [i for i in range(m) if any(matrix[i, j] != 0 for j in range(n))] matrix = matrix[rows,:] condition = Matrix([[0]*(n-1) + [1]]) if matrix[-1,:] == condition: return True else: return False def delete_zero_rows_and_columns(self, matrix): """Remove the zero rows and columns of the matrix.""" rows = [ i for i in range(matrix.rows) if not matrix.row(i).is_zero_matrix] cols = [ j for j in range(matrix.cols) if not matrix.col(j).is_zero_matrix] return matrix[rows, cols] def product_leading_entries(self, matrix): """Calculate the product of the leading entries of the matrix.""" res = 1 for row in range(matrix.rows): for el in matrix.row(row): if el != 0: res = res * el break return res def get_KSY_Dixon_resultant(self, matrix): """Calculate the Kapur-Saxena-Yang approach to the Dixon Resultant.""" matrix = self.delete_zero_rows_and_columns(matrix) _, U, _ = matrix.LUdecomposition() matrix = self.delete_zero_rows_and_columns(simplify(U)) return self.product_leading_entries(matrix) class MacaulayResultant(): """ A class for calculating the Macaulay resultant. Note that the polynomials must be homogenized and their coefficients must be given as symbols. Examples ======== >>> from sympy import symbols >>> from sympy.polys.multivariate_resultants import MacaulayResultant >>> x, y, z = symbols('x, y, z') >>> a_0, a_1, a_2 = symbols('a_0, a_1, a_2') >>> b_0, b_1, b_2 = symbols('b_0, b_1, b_2') >>> c_0, c_1, c_2,c_3, c_4 = symbols('c_0, c_1, c_2, c_3, c_4') >>> f = a_0 * y - a_1 * x + a_2 * z >>> g = b_1 * x ** 2 + b_0 * y ** 2 - b_2 * z ** 2 >>> h = c_0 * y * z ** 2 - c_1 * x ** 3 + c_2 * x ** 2 * z - c_3 * x * z ** 2 + c_4 * z ** 3 >>> mac = MacaulayResultant(polynomials=[f, g, h], variables=[x, y, z]) >>> mac.monomial_set [x**4, x**3*y, x**3*z, x**2*y**2, x**2*y*z, x**2*z**2, x*y**3, x*y**2*z, x*y*z**2, x*z**3, y**4, y**3*z, y**2*z**2, y*z**3, z**4] >>> matrix = mac.get_matrix() >>> submatrix = mac.get_submatrix(matrix) >>> submatrix Matrix([ [-a_1, a_0, a_2, 0], [ 0, -a_1, 0, 0], [ 0, 0, -a_1, 0], [ 0, 0, 0, -a_1]]) See Also ======== Notebook in examples: sympy/example/notebooks. References ========== .. [1] [Bruce97]_ .. [2] [Stiller96]_ """ def __init__(self, polynomials, variables): """ Parameters ========== variables: list A list of all n variables polynomials : list of SymPy polynomials A list of m n-degree polynomials """ self.polynomials = polynomials self.variables = variables self.n = len(variables) # A list of the d_max of each polynomial. self.degrees = [total_degree(poly, *self.variables) for poly in self.polynomials] self.degree_m = self._get_degree_m() self.monomials_size = self.get_size() # The set T of all possible monomials of degree degree_m self.monomial_set = self.get_monomials_of_certain_degree(self.degree_m) def _get_degree_m(self): r""" Returns ======= degree_m: int The degree_m is calculated as 1 + \sum_1 ^ n (d_i - 1), where d_i is the degree of the i polynomial """ return 1 + sum(d - 1 for d in self.degrees) def get_size(self): r""" Returns ======= size: int The size of set T. Set T is the set of all possible monomials of the n variables for degree equal to the degree_m """ return binomial(self.degree_m + self.n - 1, self.n - 1) def get_monomials_of_certain_degree(self, degree): """ Returns ======= monomials: list A list of monomials of a certain degree. """ monomials = [Mul(*monomial) for monomial in combinations_with_replacement(self.variables, degree)] return sorted(monomials, reverse=True, key=monomial_key('lex', self.variables)) def get_row_coefficients(self): """ Returns ======= row_coefficients: list The row coefficients of Macaulay's matrix """ row_coefficients = [] divisible = [] for i in range(self.n): if i == 0: degree = self.degree_m - self.degrees[i] monomial = self.get_monomials_of_certain_degree(degree) row_coefficients.append(monomial) else: divisible.append(self.variables[i - 1] ** self.degrees[i - 1]) degree = self.degree_m - self.degrees[i] poss_rows = self.get_monomials_of_certain_degree(degree) for div in divisible: for p in poss_rows: if rem(p, div) == 0: poss_rows = [item for item in poss_rows if item != p] row_coefficients.append(poss_rows) return row_coefficients def get_matrix(self): """ Returns ======= macaulay_matrix: Matrix The Macaulay numerator matrix """ rows = [] row_coefficients = self.get_row_coefficients() for i in range(self.n): for multiplier in row_coefficients[i]: coefficients = [] poly = Poly(self.polynomials[i] * multiplier, *self.variables) for mono in self.monomial_set: coefficients.append(poly.coeff_monomial(mono)) rows.append(coefficients) macaulay_matrix = Matrix(rows) return macaulay_matrix def get_reduced_nonreduced(self): r""" Returns ======= reduced: list A list of the reduced monomials non_reduced: list A list of the monomials that are not reduced Definition ========== A polynomial is said to be reduced in x_i, if its degree (the maximum degree of its monomials) in x_i is less than d_i. A polynomial that is reduced in all variables but one is said simply to be reduced. """ divisible = [] for m in self.monomial_set: temp = [] for i, v in enumerate(self.variables): temp.append(bool(total_degree(m, v) >= self.degrees[i])) divisible.append(temp) reduced = [i for i, r in enumerate(divisible) if sum(r) < self.n - 1] non_reduced = [i for i, r in enumerate(divisible) if sum(r) >= self.n -1] return reduced, non_reduced def get_submatrix(self, matrix): r""" Returns ======= macaulay_submatrix: Matrix The Macaulay denominator matrix. Columns that are non reduced are kept. The row which contains one of the a_{i}s is dropped. a_{i}s are the coefficients of x_i ^ {d_i}. """ reduced, non_reduced = self.get_reduced_nonreduced() # if reduced == [], then det(matrix) should be 1 if reduced == []: return diag([1]) # reduced != [] reduction_set = [v ** self.degrees[i] for i, v in enumerate(self.variables)] ais = list([self.polynomials[i].coeff(reduction_set[i]) for i in range(self.n)]) reduced_matrix = matrix[:, reduced] keep = [] for row in range(reduced_matrix.rows): check = [ai in reduced_matrix[row, :] for ai in ais] if True not in check: keep.append(row) return matrix[keep, non_reduced]
9125b3143a82d7fc18cbb46346b5a04a1988269dc79b2a4bf93a81539e8bf4c3
"""Useful utilities for higher level polynomial classes. """ from sympy.core import (S, Add, Mul, Pow, Eq, Expr, expand_mul, expand_multinomial) from sympy.core.exprtools import decompose_power, decompose_power_rat from sympy.core.numbers import _illegal from sympy.polys.polyerrors import PolynomialError, GeneratorsError from sympy.polys.polyoptions import build_options import re _gens_order = { 'a': 301, 'b': 302, 'c': 303, 'd': 304, 'e': 305, 'f': 306, 'g': 307, 'h': 308, 'i': 309, 'j': 310, 'k': 311, 'l': 312, 'm': 313, 'n': 314, 'o': 315, 'p': 216, 'q': 217, 'r': 218, 's': 219, 't': 220, 'u': 221, 'v': 222, 'w': 223, 'x': 124, 'y': 125, 'z': 126, } _max_order = 1000 _re_gen = re.compile(r"^(.*?)(\d*)$", re.MULTILINE) def _nsort(roots, separated=False): """Sort the numerical roots putting the real roots first, then sorting according to real and imaginary parts. If ``separated`` is True, then the real and imaginary roots will be returned in two lists, respectively. This routine tries to avoid issue 6137 by separating the roots into real and imaginary parts before evaluation. In addition, the sorting will raise an error if any computation cannot be done with precision. """ if not all(r.is_number for r in roots): raise NotImplementedError # see issue 6137: # get the real part of the evaluated real and imaginary parts of each root key = [[i.n(2).as_real_imag()[0] for i in r.as_real_imag()] for r in roots] # make sure the parts were computed with precision if len(roots) > 1 and any(i._prec == 1 for k in key for i in k): raise NotImplementedError("could not compute root with precision") # insert a key to indicate if the root has an imaginary part key = [(1 if i else 0, r, i) for r, i in key] key = sorted(zip(key, roots)) # return the real and imaginary roots separately if desired if separated: r = [] i = [] for (im, _, _), v in key: if im: i.append(v) else: r.append(v) return r, i _, roots = zip(*key) return list(roots) def _sort_gens(gens, **args): """Sort generators in a reasonably intelligent way. """ opt = build_options(args) gens_order, wrt = {}, None if opt is not None: gens_order, wrt = {}, opt.wrt for i, gen in enumerate(opt.sort): gens_order[gen] = i + 1 def order_key(gen): gen = str(gen) if wrt is not None: try: return (-len(wrt) + wrt.index(gen), gen, 0) except ValueError: pass name, index = _re_gen.match(gen).groups() if index: index = int(index) else: index = 0 try: return ( gens_order[name], name, index) except KeyError: pass try: return (_gens_order[name], name, index) except KeyError: pass return (_max_order, name, index) try: gens = sorted(gens, key=order_key) except TypeError: # pragma: no cover pass return tuple(gens) def _unify_gens(f_gens, g_gens): """Unify generators in a reasonably intelligent way. """ f_gens = list(f_gens) g_gens = list(g_gens) if f_gens == g_gens: return tuple(f_gens) gens, common, k = [], [], 0 for gen in f_gens: if gen in g_gens: common.append(gen) for i, gen in enumerate(g_gens): if gen in common: g_gens[i], k = common[k], k + 1 for gen in common: i = f_gens.index(gen) gens.extend(f_gens[:i]) f_gens = f_gens[i + 1:] i = g_gens.index(gen) gens.extend(g_gens[:i]) g_gens = g_gens[i + 1:] gens.append(gen) gens.extend(f_gens) gens.extend(g_gens) return tuple(gens) def _analyze_gens(gens): """Support for passing generators as `*gens` and `[gens]`. """ if len(gens) == 1 and hasattr(gens[0], '__iter__'): return tuple(gens[0]) else: return tuple(gens) def _sort_factors(factors, **args): """Sort low-level factors in increasing 'complexity' order. """ def order_if_multiple_key(factor): (f, n) = factor return (len(f), n, f) def order_no_multiple_key(f): return (len(f), f) if args.get('multiple', True): return sorted(factors, key=order_if_multiple_key) else: return sorted(factors, key=order_no_multiple_key) illegal_types = [type(obj) for obj in _illegal] finf = [float(i) for i in _illegal[1:3]] def _not_a_coeff(expr): """Do not treat NaN and infinities as valid polynomial coefficients. """ if type(expr) in illegal_types or expr in finf: return True if isinstance(expr, float) and float(expr) != expr: return True # nan return # could be def _parallel_dict_from_expr_if_gens(exprs, opt): """Transform expressions into a multinomial form given generators. """ k, indices = len(opt.gens), {} for i, g in enumerate(opt.gens): indices[g] = i polys = [] for expr in exprs: poly = {} if expr.is_Equality: expr = expr.lhs - expr.rhs for term in Add.make_args(expr): coeff, monom = [], [0]*k for factor in Mul.make_args(term): if not _not_a_coeff(factor) and factor.is_Number: coeff.append(factor) else: try: if opt.series is False: base, exp = decompose_power(factor) if exp < 0: exp, base = -exp, Pow(base, -S.One) else: base, exp = decompose_power_rat(factor) monom[indices[base]] = exp except KeyError: if not factor.has_free(*opt.gens): coeff.append(factor) else: raise PolynomialError("%s contains an element of " "the set of generators." % factor) monom = tuple(monom) if monom in poly: poly[monom] += Mul(*coeff) else: poly[monom] = Mul(*coeff) polys.append(poly) return polys, opt.gens def _parallel_dict_from_expr_no_gens(exprs, opt): """Transform expressions into a multinomial form and figure out generators. """ if opt.domain is not None: def _is_coeff(factor): return factor in opt.domain elif opt.extension is True: def _is_coeff(factor): return factor.is_algebraic elif opt.greedy is not False: def _is_coeff(factor): return factor is S.ImaginaryUnit else: def _is_coeff(factor): return factor.is_number gens, reprs = set(), [] for expr in exprs: terms = [] if expr.is_Equality: expr = expr.lhs - expr.rhs for term in Add.make_args(expr): coeff, elements = [], {} for factor in Mul.make_args(term): if not _not_a_coeff(factor) and (factor.is_Number or _is_coeff(factor)): coeff.append(factor) else: if opt.series is False: base, exp = decompose_power(factor) if exp < 0: exp, base = -exp, Pow(base, -S.One) else: base, exp = decompose_power_rat(factor) elements[base] = elements.setdefault(base, 0) + exp gens.add(base) terms.append((coeff, elements)) reprs.append(terms) gens = _sort_gens(gens, opt=opt) k, indices = len(gens), {} for i, g in enumerate(gens): indices[g] = i polys = [] for terms in reprs: poly = {} for coeff, term in terms: monom = [0]*k for base, exp in term.items(): monom[indices[base]] = exp monom = tuple(monom) if monom in poly: poly[monom] += Mul(*coeff) else: poly[monom] = Mul(*coeff) polys.append(poly) return polys, tuple(gens) def _dict_from_expr_if_gens(expr, opt): """Transform an expression into a multinomial form given generators. """ (poly,), gens = _parallel_dict_from_expr_if_gens((expr,), opt) return poly, gens def _dict_from_expr_no_gens(expr, opt): """Transform an expression into a multinomial form and figure out generators. """ (poly,), gens = _parallel_dict_from_expr_no_gens((expr,), opt) return poly, gens def parallel_dict_from_expr(exprs, **args): """Transform expressions into a multinomial form. """ reps, opt = _parallel_dict_from_expr(exprs, build_options(args)) return reps, opt.gens def _parallel_dict_from_expr(exprs, opt): """Transform expressions into a multinomial form. """ if opt.expand is not False: exprs = [ expr.expand() for expr in exprs ] if any(expr.is_commutative is False for expr in exprs): raise PolynomialError('non-commutative expressions are not supported') if opt.gens: reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt) else: reps, gens = _parallel_dict_from_expr_no_gens(exprs, opt) return reps, opt.clone({'gens': gens}) def dict_from_expr(expr, **args): """Transform an expression into a multinomial form. """ rep, opt = _dict_from_expr(expr, build_options(args)) return rep, opt.gens def _dict_from_expr(expr, opt): """Transform an expression into a multinomial form. """ if expr.is_commutative is False: raise PolynomialError('non-commutative expressions are not supported') def _is_expandable_pow(expr): return (expr.is_Pow and expr.exp.is_positive and expr.exp.is_Integer and expr.base.is_Add) if opt.expand is not False: if not isinstance(expr, (Expr, Eq)): raise PolynomialError('expression must be of type Expr') expr = expr.expand() # TODO: Integrate this into expand() itself while any(_is_expandable_pow(i) or i.is_Mul and any(_is_expandable_pow(j) for j in i.args) for i in Add.make_args(expr)): expr = expand_multinomial(expr) while any(i.is_Mul and any(j.is_Add for j in i.args) for i in Add.make_args(expr)): expr = expand_mul(expr) if opt.gens: rep, gens = _dict_from_expr_if_gens(expr, opt) else: rep, gens = _dict_from_expr_no_gens(expr, opt) return rep, opt.clone({'gens': gens}) def expr_from_dict(rep, *gens): """Convert a multinomial form into an expression. """ result = [] for monom, coeff in rep.items(): term = [coeff] for g, m in zip(gens, monom): if m: term.append(Pow(g, m)) result.append(Mul(*term)) return Add(*result) parallel_dict_from_basic = parallel_dict_from_expr dict_from_basic = dict_from_expr basic_from_dict = expr_from_dict def _dict_reorder(rep, gens, new_gens): """Reorder levels using dict representation. """ gens = list(gens) monoms = rep.keys() coeffs = rep.values() new_monoms = [ [] for _ in range(len(rep)) ] used_indices = set() for gen in new_gens: try: j = gens.index(gen) used_indices.add(j) for M, new_M in zip(monoms, new_monoms): new_M.append(M[j]) except ValueError: for new_M in new_monoms: new_M.append(0) for i, _ in enumerate(gens): if i not in used_indices: for monom in monoms: if monom[i]: raise GeneratorsError("unable to drop generators") return map(tuple, new_monoms), coeffs class PicklableWithSlots: """ Mixin class that allows to pickle objects with ``__slots__``. Examples ======== First define a class that mixes :class:`PicklableWithSlots` in:: >>> from sympy.polys.polyutils import PicklableWithSlots >>> class Some(PicklableWithSlots): ... __slots__ = ('foo', 'bar') ... ... def __init__(self, foo, bar): ... self.foo = foo ... self.bar = bar To make :mod:`pickle` happy in doctest we have to use these hacks:: >>> import builtins >>> builtins.Some = Some >>> from sympy.polys import polyutils >>> polyutils.Some = Some Next lets see if we can create an instance, pickle it and unpickle:: >>> some = Some('abc', 10) >>> some.foo, some.bar ('abc', 10) >>> from pickle import dumps, loads >>> some2 = loads(dumps(some)) >>> some2.foo, some2.bar ('abc', 10) """ __slots__ = () def __getstate__(self, cls=None): if cls is None: # This is the case for the instance that gets pickled cls = self.__class__ d = {} # Get all data that should be stored from super classes for c in cls.__bases__: if hasattr(c, "__getstate__"): d.update(c.__getstate__(self, c)) # Get all information that should be stored from cls and return the dict for name in cls.__slots__: if hasattr(self, name): d[name] = getattr(self, name) return d def __setstate__(self, d): # All values that were pickled are now assigned to a fresh instance for name, value in d.items(): try: setattr(self, name, value) except AttributeError: # This is needed in cases like Rational :> Half pass class IntegerPowerable: r""" Mixin class for classes that define a `__mul__` method, and want to be raised to integer powers in the natural way that follows. Implements powering via binary expansion, for efficiency. By default, only integer powers $\geq 2$ are supported. To support the first, zeroth, or negative powers, override the corresponding methods, `_first_power`, `_zeroth_power`, `_negative_power`, below. """ def __pow__(self, e, modulo=None): if e < 2: try: if e == 1: return self._first_power() elif e == 0: return self._zeroth_power() else: return self._negative_power(e, modulo=modulo) except NotImplementedError: return NotImplemented else: bits = [int(d) for d in reversed(bin(e)[2:])] n = len(bits) p = self first = True for i in range(n): if bits[i]: if first: r = p first = False else: r *= p if modulo is not None: r %= modulo if i < n - 1: p *= p if modulo is not None: p %= modulo return r def _negative_power(self, e, modulo=None): """ Compute inverse of self, then raise that to the abs(e) power. For example, if the class has an `inv()` method, return self.inv() ** abs(e) % modulo """ raise NotImplementedError def _zeroth_power(self): """Return unity element of algebraic struct to which self belongs.""" raise NotImplementedError def _first_power(self): """Return a copy of self.""" raise NotImplementedError
87ca82d19b177fe64a3cb20c05a2d5d9a4821c3b972d005ccca65c53e27605a1
"""Euclidean algorithms, GCDs, LCMs and polynomial remainder sequences. """ from sympy.polys.densearith import ( dup_sub_mul, dup_neg, dmp_neg, dmp_add, dmp_sub, dup_mul, dmp_mul, dmp_pow, dup_div, dmp_div, dup_rem, dup_quo, dmp_quo, dup_prem, dmp_prem, dup_mul_ground, dmp_mul_ground, dmp_mul_term, dup_quo_ground, dmp_quo_ground, dup_max_norm, dmp_max_norm) from sympy.polys.densebasic import ( dup_strip, dmp_raise, dmp_zero, dmp_one, dmp_ground, dmp_one_p, dmp_zero_p, dmp_zeros, dup_degree, dmp_degree, dmp_degree_in, dup_LC, dmp_LC, dmp_ground_LC, dmp_multi_deflate, dmp_inflate, dup_convert, dmp_convert, dmp_apply_pairs) from sympy.polys.densetools import ( dup_clear_denoms, dmp_clear_denoms, dup_diff, dmp_diff, dup_eval, dmp_eval, dmp_eval_in, dup_trunc, dmp_ground_trunc, dup_monic, dmp_ground_monic, dup_primitive, dmp_ground_primitive, dup_extract, dmp_ground_extract) from sympy.polys.galoistools import ( gf_int, gf_crt) from sympy.polys.polyconfig import query from sympy.polys.polyerrors import ( MultivariatePolynomialError, HeuristicGCDFailed, HomomorphismFailed, NotInvertible, DomainError) def dup_half_gcdex(f, g, K): """ Half extended Euclidean algorithm in `F[x]`. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> R.dup_half_gcdex(f, g) (-1/5*x + 3/5, x + 1) """ if not K.is_Field: raise DomainError("Cannot compute half extended GCD over %s" % K) a, b = [K.one], [] while g: q, r = dup_div(f, g, K) f, g = g, r a, b = b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K) return a, f def dmp_half_gcdex(f, g, u, K): """ Half extended Euclidean algorithm in `F[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) """ if not u: return dup_half_gcdex(f, g, K) else: raise MultivariatePolynomialError(f, g) def dup_gcdex(f, g, K): """ Extended Euclidean algorithm in `F[x]`. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> R.dup_gcdex(f, g) (-1/5*x + 3/5, 1/5*x**2 - 6/5*x + 2, x + 1) """ s, h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f, K) t = dup_quo(F, g, K) return s, t, h def dmp_gcdex(f, g, u, K): """ Extended Euclidean algorithm in `F[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) """ if not u: return dup_gcdex(f, g, K) else: raise MultivariatePolynomialError(f, g) def dup_invert(f, g, K): """ Compute multiplicative inverse of `f` modulo `g` in `F[x]`. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = x**2 - 1 >>> g = 2*x - 1 >>> h = x - 1 >>> R.dup_invert(f, g) -4/3 >>> R.dup_invert(f, h) Traceback (most recent call last): ... NotInvertible: zero divisor """ s, h = dup_half_gcdex(f, g, K) if h == [K.one]: return dup_rem(s, g, K) else: raise NotInvertible("zero divisor") def dmp_invert(f, g, u, K): """ Compute multiplicative inverse of `f` modulo `g` in `F[X]`. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) """ if not u: return dup_invert(f, g, K) else: raise MultivariatePolynomialError(f, g) def dup_euclidean_prs(f, g, K): """ Euclidean polynomial remainder sequence (PRS) in `K[x]`. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 >>> g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 >>> prs = R.dup_euclidean_prs(f, g) >>> prs[0] x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 >>> prs[1] 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 >>> prs[2] -5/9*x**4 + 1/9*x**2 - 1/3 >>> prs[3] -117/25*x**2 - 9*x + 441/25 >>> prs[4] 233150/19773*x - 102500/6591 >>> prs[5] -1288744821/543589225 """ prs = [f, g] h = dup_rem(f, g, K) while h: prs.append(h) f, g = g, h h = dup_rem(f, g, K) return prs def dmp_euclidean_prs(f, g, u, K): """ Euclidean polynomial remainder sequence (PRS) in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) """ if not u: return dup_euclidean_prs(f, g, K) else: raise MultivariatePolynomialError(f, g) def dup_primitive_prs(f, g, K): """ Primitive polynomial remainder sequence (PRS) in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 >>> g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 >>> prs = R.dup_primitive_prs(f, g) >>> prs[0] x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 >>> prs[1] 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 >>> prs[2] -5*x**4 + x**2 - 3 >>> prs[3] 13*x**2 + 25*x - 49 >>> prs[4] 4663*x - 6150 >>> prs[5] 1 """ prs = [f, g] _, h = dup_primitive(dup_prem(f, g, K), K) while h: prs.append(h) f, g = g, h _, h = dup_primitive(dup_prem(f, g, K), K) return prs def dmp_primitive_prs(f, g, u, K): """ Primitive polynomial remainder sequence (PRS) in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) """ if not u: return dup_primitive_prs(f, g, K) else: raise MultivariatePolynomialError(f, g) def dup_inner_subresultants(f, g, K): """ Subresultant PRS algorithm in `K[x]`. Computes the subresultant polynomial remainder sequence (PRS) and the non-zero scalar subresultants of `f` and `g`. By [1] Thm. 3, these are the constants '-c' (- to optimize computation of sign). The first subdeterminant is set to 1 by convention to match the polynomial and the scalar subdeterminants. If 'deg(f) < deg(g)', the subresultants of '(g,f)' are computed. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_inner_subresultants(x**2 + 1, x**2 - 1) ([x**2 + 1, x**2 - 1, -2], [1, 1, 4]) References ========== .. [1] W.S. Brown, The Subresultant PRS Algorithm. ACM Transaction of Mathematical Software 4 (1978) 237-249 """ n = dup_degree(f) m = dup_degree(g) if n < m: f, g = g, f n, m = m, n if not f: return [], [] if not g: return [f], [K.one] R = [f, g] d = n - m b = (-K.one)**(d + 1) h = dup_prem(f, g, K) h = dup_mul_ground(h, b, K) lc = dup_LC(g, K) c = lc**d # Conventional first scalar subdeterminant is 1 S = [K.one, c] c = -c while h: k = dup_degree(h) R.append(h) f, g, m, d = g, h, k, m - k b = -lc * c**d h = dup_prem(f, g, K) h = dup_quo_ground(h, b, K) lc = dup_LC(g, K) if d > 1: # abnormal case q = c**(d - 1) c = K.quo((-lc)**d, q) else: c = -lc S.append(-c) return R, S def dup_subresultants(f, g, K): """ Computes subresultant PRS of two polynomials in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_subresultants(x**2 + 1, x**2 - 1) [x**2 + 1, x**2 - 1, -2] """ return dup_inner_subresultants(f, g, K)[0] def dup_prs_resultant(f, g, K): """ Resultant algorithm in `K[x]` using subresultant PRS. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_prs_resultant(x**2 + 1, x**2 - 1) (4, [x**2 + 1, x**2 - 1, -2]) """ if not f or not g: return (K.zero, []) R, S = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return (K.zero, R) return S[-1], R def dup_resultant(f, g, K, includePRS=False): """ Computes resultant of two polynomials in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_resultant(x**2 + 1, x**2 - 1) 4 """ if includePRS: return dup_prs_resultant(f, g, K) return dup_prs_resultant(f, g, K)[0] def dmp_inner_subresultants(f, g, u, K): """ Subresultant PRS algorithm in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y - y**3 - 4 >>> g = x**2 + x*y**3 - 9 >>> a = 3*x*y**4 + y**3 - 27*y + 4 >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 >>> prs = [f, g, a, b] >>> sres = [[1], [1], [3, 0, 0, 0, 0], [-3, 0, 0, -12, 1, 0, -54, 8, 729, -216, 16]] >>> R.dmp_inner_subresultants(f, g) == (prs, sres) True """ if not u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m = dmp_degree(g, u) if n < m: f, g = g, f n, m = m, n if dmp_zero_p(f, u): return [], [] v = u - 1 if dmp_zero_p(g, u): return [f], [dmp_ground(K.one, v)] R = [f, g] d = n - m b = dmp_pow(dmp_ground(-K.one, v), d + 1, v, K) h = dmp_prem(f, g, u, K) h = dmp_mul_term(h, b, 0, u, K) lc = dmp_LC(g, K) c = dmp_pow(lc, d, v, K) S = [dmp_ground(K.one, v), c] c = dmp_neg(c, v, K) while not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) f, g, m, d = g, h, k, m - k b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, d, v, K), v, K) h = dmp_prem(f, g, u, K) h = [ dmp_quo(ch, b, v, K) for ch in h ] lc = dmp_LC(g, K) if d > 1: p = dmp_pow(dmp_neg(lc, v, K), d, v, K) q = dmp_pow(c, d - 1, v, K) c = dmp_quo(p, q, v, K) else: c = dmp_neg(lc, v, K) S.append(dmp_neg(c, v, K)) return R, S def dmp_subresultants(f, g, u, K): """ Computes subresultant PRS of two polynomials in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y - y**3 - 4 >>> g = x**2 + x*y**3 - 9 >>> a = 3*x*y**4 + y**3 - 27*y + 4 >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 >>> R.dmp_subresultants(f, g) == [f, g, a, b] True """ return dmp_inner_subresultants(f, g, u, K)[0] def dmp_prs_resultant(f, g, u, K): """ Resultant algorithm in `K[X]` using subresultant PRS. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y - y**3 - 4 >>> g = x**2 + x*y**3 - 9 >>> a = 3*x*y**4 + y**3 - 27*y + 4 >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 >>> res, prs = R.dmp_prs_resultant(f, g) >>> res == b # resultant has n-1 variables False >>> res == b.drop(x) True >>> prs == [f, g, a, b] True """ if not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u - 1), []) R, S = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u - 1), R) return S[-1], R def dmp_zz_modular_resultant(f, g, p, u, K): """ Compute resultant of `f` and `g` modulo a prime `p`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x + y + 2 >>> g = 2*x*y + x + 3 >>> R.dmp_zz_modular_resultant(f, g, 5) -2*y**2 + 1 """ if not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v = u - 1 n = dmp_degree(f, u) m = dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u) B = n*M + m*N D, a = [K.one], -K.one r = dmp_zero(v) while dup_degree(D) <= B: while True: a += K.one if a == p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r, a, v, K) if not v: R = dup_strip([R]) e = dup_strip([e]) else: R = [R] e = [e] d = K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R, e, v, K), v, K) r = dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p, K) return r def _collins_crt(r, R, P, p, K): """Wrapper of CRT for Collins's resultant algorithm. """ return gf_int(gf_crt([r, R], [P, p], K), P*p) def dmp_zz_collins_resultant(f, g, u, K): """ Collins's modular resultant algorithm in `Z[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = x + y + 2 >>> g = 2*x*y + x + 3 >>> R.dmp_zz_collins_resultant(f, g) -2*y**2 - 5*y + 1 """ n = dmp_degree(f, u) m = dmp_degree(g, u) if n < 0 or m < 0: return dmp_zero(u - 1) A = dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K) v = u - 1 B = K(2)*K.factorial(K(n + m))*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one from sympy.ntheory import nextprime while P <= B: p = K(nextprime(p)) while not (a % p) or not (b % p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue if K.is_one(P): r = R else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) P *= p return r def dmp_qq_collins_resultant(f, g, u, K0): """ Collins's modular resultant algorithm in `Q[X]`. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y = ring("x,y", QQ) >>> f = QQ(1,2)*x + y + QQ(2,3) >>> g = 2*x*y + x + 3 >>> R.dmp_qq_collins_resultant(f, g) -2*y**2 - 7/3*y + 5/6 """ n = dmp_degree(f, u) m = dmp_degree(g, u) if n < 0 or m < 0: return dmp_zero(u - 1) K1 = K0.get_ring() cf, f = dmp_clear_denoms(f, u, K0, K1) cg, g = dmp_clear_denoms(g, u, K0, K1) f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u - 1, K1, K0) c = K0.convert(cf**m * cg**n, K1) return dmp_quo_ground(r, c, u - 1, K0) def dmp_resultant(f, g, u, K, includePRS=False): """ Computes resultant of two polynomials in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> f = 3*x**2*y - y**3 - 4 >>> g = x**2 + x*y**3 - 9 >>> R.dmp_resultant(f, g) -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 """ if not u: return dup_resultant(f, g, K, includePRS=includePRS) if includePRS: return dmp_prs_resultant(f, g, u, K) if K.is_Field: if K.is_QQ and query('USE_COLLINS_RESULTANT'): return dmp_qq_collins_resultant(f, g, u, K) else: if K.is_ZZ and query('USE_COLLINS_RESULTANT'): return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u, K)[0] def dup_discriminant(f, K): """ Computes discriminant of a polynomial in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_discriminant(x**2 + 2*x + 3) -8 """ d = dup_degree(f) if d <= 0: return K.zero else: s = (-1)**((d*(d - 1)) // 2) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) def dmp_discriminant(f, u, K): """ Computes discriminant of a polynomial in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y,z,t = ring("x,y,z,t", ZZ) >>> R.dmp_discriminant(x**2*y + x*z + t) -4*y*t + z**2 """ if not u: return dup_discriminant(f, K) d, v = dmp_degree(f, u), u - 1 if d <= 0: return dmp_zero(v) else: s = (-1)**((d*(d - 1)) // 2) c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K): """Handle trivial cases in GCD algorithm over a ring. """ if not (f or g): return [], [], [] elif not f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return dup_neg(g, K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K): """Handle trivial cases in GCD algorithm over a field. """ if not (f or g): return [], [], [] elif not f: return dup_monic(g, K), [], [dup_LC(g, K)] elif not g: return dup_monic(f, K), [dup_LC(f, K)], [] else: return None def _dmp_rr_trivial_gcd(f, g, u, K): """Handle trivial cases in GCD algorithm over a ring. """ zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if_contain_one = dmp_one_p(f, u, K) or dmp_one_p(g, u, K) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif if_contain_one: return dmp_one(u, K), f, g elif query('USE_SIMPLIFY_GCD'): return _dmp_simplify_gcd(f, g, u, K) else: return None def _dmp_ff_trivial_gcd(f, g, u, K): """Handle trivial cases in GCD algorithm over a field. """ zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif query('USE_SIMPLIFY_GCD'): return _dmp_simplify_gcd(f, g, u, K) else: return None def _dmp_simplify_gcd(f, g, u, K): """Try to eliminate `x_0` from GCD computation in `K[X]`. """ df = dmp_degree(f, u) dg = dmp_degree(g, u) if df > 0 and dg > 0: return None if not (df or dg): F = dmp_LC(f, K) G = dmp_LC(g, K) else: if not df: F = dmp_LC(f, K) G = dmp_content(g, u, K) else: F = dmp_content(f, u, K) G = dmp_LC(g, K) v = u - 1 h = dmp_gcd(F, G, v, K) cff = [ dmp_quo(cf, h, v, K) for cf in f ] cfg = [ dmp_quo(cg, h, v, K) for cg in g ] return [h], cff, cfg def dup_rr_prs_gcd(f, g, K): """ Computes polynomial GCD using subresultants over a ring. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_rr_prs_gcd(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return result fc, F = dup_primitive(f, K) gc, G = dup_primitive(g, K) c = K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K) c *= K.canonical_unit(dup_LC(h, K)) h = dup_mul_ground(h, c, K) cff = dup_quo(f, h, K) cfg = dup_quo(g, h, K) return h, cff, cfg def dup_ff_prs_gcd(f, g, K): """ Computes polynomial GCD using subresultants over a field. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> R.dup_ff_prs_gcd(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ result = _dup_ff_trivial_gcd(f, g, K) if result is not None: return result h = dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff = dup_quo(f, h, K) cfg = dup_quo(g, h, K) return h, cff, cfg def dmp_rr_prs_gcd(f, g, u, K): """ Computes polynomial GCD using subresultants over a ring. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_rr_prs_gcd(f, g) (x + y, x + y, x) """ if not u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result fc, F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u - 1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) cff = dmp_quo(f, h, u, K) cfg = dmp_quo(g, h, u, K) return h, cff, cfg def dmp_ff_prs_gcd(f, g, u, K): """ Computes polynomial GCD using subresultants over a field. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y, = ring("x,y", QQ) >>> f = QQ(1,2)*x**2 + x*y + QQ(1,2)*y**2 >>> g = x**2 + x*y >>> R.dmp_ff_prs_gcd(f, g) (x + y, 1/2*x + 1/2*y, x) """ if not u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u, K) if result is not None: return result fc, F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u - 1, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h, u, K) cff = dmp_quo(f, h, u, K) cfg = dmp_quo(g, h, u, K) return h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): """Interpolate polynomial GCD from integer GCD. """ f = [] while h: g = h % x if g > x // 2: g -= x f.insert(0, g) h = (h - g) // x return f def dup_zz_heu_gcd(f, g, K): """ Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials `f` and `g` in `Z[x]`, returns their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg`` such that:: h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) The algorithm is purely heuristic which means it may fail to compute the GCD. This will be signaled by raising an exception. In this case you will need to switch to another GCD method. The algorithm computes the polynomial GCD by evaluating polynomials f and g at certain points and computing (fast) integer GCD of those evaluations. The polynomial GCD is recovered from the integer image by interpolation. The final step is to verify if the result is the correct GCD. This gives cofactors as a side effect. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_zz_heu_gcd(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) References ========== .. [1] [Liao95]_ """ result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return result df = dup_degree(f) dg = dup_degree(g) gcd, f, g = dup_extract(f, g, K) if df == 0 or dg == 0: return [gcd], f, g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B = K(2*min(f_norm, g_norm) + 29) x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2) for i in range(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg = dup_eval(g, x, K) if ff and gg: h = K.gcd(ff, gg) cff = ff // h cfg = gg // h h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K) if not r: cfg_, r = dup_div(g, h, K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff, K) if not r: cfg_, r = dup_div(g, h, K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg, K) if not r: cff_, r = dup_div(f, h, K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def _dmp_zz_gcd_interpolate(h, x, v, K): """Interpolate polynomial GCD from integer GCD. """ f = [] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K) f.insert(0, g) h = dmp_sub(h, g, v, K) h = dmp_quo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v + 1, K)): return dmp_neg(f, v + 1, K) else: return f def dmp_zz_heu_gcd(f, g, u, K): """ Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials `f` and `g` in `Z[X]`, returns their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg`` such that:: h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) The algorithm is purely heuristic which means it may fail to compute the GCD. This will be signaled by raising an exception. In this case you will need to switch to another GCD method. The algorithm computes the polynomial GCD by evaluating polynomials f and g at certain points and computing (fast) integer GCD of those evaluations. The polynomial GCD is recovered from the integer image by interpolation. The evaluation process reduces f and g variable by variable into a large integer. The final step is to verify if the interpolated polynomial is the correct GCD. This gives cofactors of the input polynomials as a side effect. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_zz_heu_gcd(f, g) (x + y, x + y, x) References ========== .. [1] [Liao95]_ """ if not u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result gcd, f, g = dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K) B = K(2*min(f_norm, g_norm) + 29) x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for i in range(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg = dmp_eval(g, x, u, K) v = u - 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): """ Heuristic polynomial GCD in `Q[x]`. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = QQ(1,2)*x**2 + QQ(7,4)*x + QQ(3,2) >>> g = QQ(1,2)*x**2 + x >>> R.dup_qq_heu_gcd(f, g) (x + 2, 1/2*x + 3/4, 1/2*x) """ result = _dup_ff_trivial_gcd(f, g, K0) if result is not None: return result K1 = K0.get_ring() cf, f = dup_clear_denoms(f, K0, K1) cg, g = dup_clear_denoms(g, K0, K1) f = dup_convert(f, K0, K1) g = dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0) c = dup_LC(h, K0) h = dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg def dmp_qq_heu_gcd(f, g, u, K0): """ Heuristic polynomial GCD in `Q[X]`. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y, = ring("x,y", QQ) >>> f = QQ(1,4)*x**2 + x*y + y**2 >>> g = QQ(1,2)*x**2 + x*y >>> R.dmp_qq_heu_gcd(f, g) (x + 2*y, 1/4*x + 1/2*y, 1/2*x) """ result = _dmp_ff_trivial_gcd(f, g, u, K0) if result is not None: return result K1 = K0.get_ring() cf, f = dmp_clear_denoms(f, u, K0, K1) cg, g = dmp_clear_denoms(g, u, K0, K1) f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff, cfg def dup_inner_gcd(f, g, K): """ Computes polynomial GCD and cofactors of `f` and `g` in `K[x]`. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_inner_gcd(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ if not K.is_Exact: try: exact = K.get_exact() except DomainError: return [K.one], f, g f = dup_convert(f, K, exact) g = dup_convert(g, K, exact) h, cff, cfg = dup_inner_gcd(f, g, exact) h = dup_convert(h, exact, K) cff = dup_convert(cff, exact, K) cfg = dup_convert(cfg, exact, K) return h, cff, cfg elif K.is_Field: if K.is_QQ and query('USE_HEU_GCD'): try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if K.is_ZZ and query('USE_HEU_GCD'): try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) def _dmp_inner_gcd(f, g, u, K): """Helper function for `dmp_inner_gcd()`. """ if not K.is_Exact: try: exact = K.get_exact() except DomainError: return dmp_one(u, K), f, g f = dmp_convert(f, u, K, exact) g = dmp_convert(g, u, K, exact) h, cff, cfg = _dmp_inner_gcd(f, g, u, exact) h = dmp_convert(h, u, exact, K) cff = dmp_convert(cff, u, exact, K) cfg = dmp_convert(cfg, u, exact, K) return h, cff, cfg elif K.is_Field: if K.is_QQ and query('USE_HEU_GCD'): try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else: if K.is_ZZ and query('USE_HEU_GCD'): try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) def dmp_inner_gcd(f, g, u, K): """ Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`. Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_inner_gcd(f, g) (x + y, x + y, x) """ if not u: return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K): """ Computes polynomial GCD of `f` and `g` in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_gcd(x**2 - 1, x**2 - 3*x + 2) x - 1 """ return dup_inner_gcd(f, g, K)[0] def dmp_gcd(f, g, u, K): """ Computes polynomial GCD of `f` and `g` in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_gcd(f, g) x + y """ return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K): """ Computes polynomial LCM over a ring in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_rr_lcm(x**2 - 1, x**2 - 3*x + 2) x**3 - 2*x**2 - x + 2 """ fc, f = dup_primitive(f, K) gc, g = dup_primitive(g, K) c = K.lcm(fc, gc) h = dup_quo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): """ Computes polynomial LCM over a field in `K[x]`. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x = ring("x", QQ) >>> f = QQ(1,2)*x**2 + QQ(7,4)*x + QQ(3,2) >>> g = QQ(1,2)*x**2 + x >>> R.dup_ff_lcm(f, g) x**3 + 7/2*x**2 + 3*x """ h = dup_quo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_monic(h, K) def dup_lcm(f, g, K): """ Computes polynomial LCM of `f` and `g` in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_lcm(x**2 - 1, x**2 - 3*x + 2) x**3 - 2*x**2 - x + 2 """ if K.is_Field: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K) def dmp_rr_lcm(f, g, u, K): """ Computes polynomial LCM over a ring in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_rr_lcm(f, g) x**3 + 2*x**2*y + x*y**2 """ fc, f = dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c, u, K) def dmp_ff_lcm(f, g, u, K): """ Computes polynomial LCM over a field in `K[X]`. Examples ======== >>> from sympy.polys import ring, QQ >>> R, x,y, = ring("x,y", QQ) >>> f = QQ(1,4)*x**2 + x*y + y**2 >>> g = QQ(1,2)*x**2 + x*y >>> R.dmp_ff_lcm(f, g) x**3 + 4*x**2*y + 4*x*y**2 """ h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h, u, K) def dmp_lcm(f, g, u, K): """ Computes polynomial LCM of `f` and `g` in `K[X]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_lcm(f, g) x**3 + 2*x**2*y + x*y**2 """ if not u: return dup_lcm(f, g, K) if K.is_Field: return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g, u, K) def dmp_content(f, u, K): """ Returns GCD of multivariate coefficients. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> R.dmp_content(2*x*y + 6*x + 4*y + 12) 2*y + 6 """ cont, v = dmp_LC(f, K), u - 1 if dmp_zero_p(f, u): return cont for c in f[1:]: cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else: return cont def dmp_primitive(f, u, K): """ Returns multivariate content and a primitive polynomial. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y, = ring("x,y", ZZ) >>> R.dmp_primitive(2*x*y + 6*x + 4*y + 12) (2*y + 6, x + 2) """ cont, v = dmp_content(f, u, K), u - 1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont, f else: return cont, [ dmp_quo(c, cont, v, K) for c in f ] def dup_cancel(f, g, K, include=True): """ Cancel common factors in a rational function `f/g`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_cancel(2*x**2 - 2, x**2 - 2*x + 1) (2*x + 2, x - 1) """ return dmp_cancel(f, g, 0, K, include=include) def dmp_cancel(f, g, u, K, include=True): """ Cancel common factors in a rational function `f/g`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_cancel(2*x**2 - 2, x**2 - 2*x + 1) (2*x + 2, x - 1) """ K0 = None if K.is_Field and K.has_assoc_Ring: K0, K = K, K.get_ring() cq, f = dmp_clear_denoms(f, u, K0, K, convert=True) cp, g = dmp_clear_denoms(g, u, K0, K, convert=True) else: cp, cq = K.one, K.one _, p, q = dmp_inner_gcd(f, g, u, K) if K0 is not None: _, cp, cq = K.cofactors(cp, cq) p = dmp_convert(p, u, K, K0) q = dmp_convert(q, u, K, K0) K = K0 p_neg = K.is_negative(dmp_ground_LC(p, u, K)) q_neg = K.is_negative(dmp_ground_LC(q, u, K)) if p_neg and q_neg: p, q = dmp_neg(p, u, K), dmp_neg(q, u, K) elif p_neg: cp, p = -cp, dmp_neg(p, u, K) elif q_neg: cp, q = -cp, dmp_neg(q, u, K) if not include: return cp, cq, p, q p = dmp_mul_ground(p, cp, u, K) q = dmp_mul_ground(q, cq, u, K) return p, q
44ab712b293240e3702260eaa1d395185159bad6dcfa8d0c1e54f7ceaae7538e
"""Polynomial factorization routines in characteristic zero. """ from sympy.core.random import _randint from sympy.polys.galoistools import ( gf_from_int_poly, gf_to_int_poly, gf_lshift, gf_add_mul, gf_mul, gf_div, gf_rem, gf_gcdex, gf_sqf_p, gf_factor_sqf, gf_factor) from sympy.polys.densebasic import ( dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dmp_degree_list, dmp_from_dict, dmp_zero_p, dmp_one, dmp_nest, dmp_raise, dup_strip, dmp_ground, dup_inflate, dmp_exclude, dmp_include, dmp_inject, dmp_eject, dup_terms_gcd, dmp_terms_gcd) from sympy.polys.densearith import ( dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_sqr, dmp_pow, dup_div, dmp_div, dup_quo, dmp_quo, dmp_expand, dmp_add_mul, dup_sub_mul, dmp_sub_mul, dup_lshift, dup_max_norm, dmp_max_norm, dup_l1_norm, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground) from sympy.polys.densetools import ( dup_clear_denoms, dmp_clear_denoms, dup_trunc, dmp_ground_trunc, dup_content, dup_monic, dmp_ground_monic, dup_primitive, dmp_ground_primitive, dmp_eval_tail, dmp_eval_in, dmp_diff_eval_in, dmp_compose, dup_shift, dup_mirror) from sympy.polys.euclidtools import ( dmp_primitive, dup_inner_gcd, dmp_inner_gcd) from sympy.polys.sqfreetools import ( dup_sqf_p, dup_sqf_norm, dmp_sqf_norm, dup_sqf_part, dmp_sqf_part) from sympy.polys.polyutils import _sort_factors from sympy.polys.polyconfig import query from sympy.polys.polyerrors import ( ExtraneousFactors, DomainError, CoercionFailed, EvaluationFailed) from sympy.utilities import subsets from math import ceil as _ceil, log as _log def dup_trial_division(f, factors, K): """ Determine multiplicities of factors for a univariate polynomial using trial division. """ result = [] for factor in factors: k = 0 while True: q, r = dup_div(f, factor, K) if not r: f, k = q, k + 1 else: break result.append((factor, k)) return _sort_factors(result) def dmp_trial_division(f, factors, u, K): """ Determine multiplicities of factors for a multivariate polynomial using trial division. """ result = [] for factor in factors: k = 0 while True: q, r = dmp_div(f, factor, u, K) if dmp_zero_p(r, u): f, k = q, k + 1 else: break result.append((factor, k)) return _sort_factors(result) def dup_zz_mignotte_bound(f, K): """ The Knuth-Cohen variant of Mignotte bound for univariate polynomials in `K[x]`. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> f = x**3 + 14*x**2 + 56*x + 64 >>> R.dup_zz_mignotte_bound(f) 152 By checking `factor(f)` we can see that max coeff is 8 Also consider a case that `f` is irreducible for example `f = 2*x**2 + 3*x + 4` To avoid a bug for these cases, we return the bound plus the max coefficient of `f` >>> f = 2*x**2 + 3*x + 4 >>> R.dup_zz_mignotte_bound(f) 6 Lastly,To see the difference between the new and the old Mignotte bound consider the irreducible polynomial:: >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26 >>> R.dup_zz_mignotte_bound(f) 744 The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664. References ========== ..[1] [Abbott2013]_ """ from sympy.functions.combinatorial.factorials import binomial d = dup_degree(f) delta = _ceil(d / 2) delta2 = _ceil(delta / 2) # euclidean-norm eucl_norm = K.sqrt( sum( [cf**2 for cf in f] ) ) # biggest values of binomial coefficients (p. 538 of reference) t1 = binomial(delta - 1, delta2) t2 = binomial(delta - 1, delta2 - 1) lc = K.abs(dup_LC(f, K)) # leading coefficient bound = t1 * eucl_norm + t2 * lc # (p. 538 of reference) bound += dup_max_norm(f, K) # add max coeff for irreducible polys bound = _ceil(bound / 2) * 2 # round up to even integer return bound def dmp_zz_mignotte_bound(f, u, K): """Mignotte bound for multivariate polynomials in `K[X]`. """ a = dmp_max_norm(f, u, K) b = abs(dmp_ground_LC(f, u, K)) n = sum(dmp_degree_list(f, u)) return K.sqrt(K(n + 1))*2**n*a*b def dup_zz_hensel_step(m, f, g, h, s, t, K): """ One step in Hensel lifting in `Z[x]`. Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s` and `t` such that:: f = g*h (mod m) s*g + t*h = 1 (mod m) lc(f) is not a zero divisor (mod m) lc(h) = 1 deg(f) = deg(g) + deg(h) deg(s) < deg(h) deg(t) < deg(g) returns polynomials `G`, `H`, `S` and `T`, such that:: f = G*H (mod m**2) S*G + T*H = 1 (mod m**2) References ========== .. [1] [Gathen99]_ """ M = m**2 e = dup_sub_mul(f, g, h, K) e = dup_trunc(e, M, K) q, r = dup_div(dup_mul(s, e, K), h, K) q = dup_trunc(q, M, K) r = dup_trunc(r, M, K) u = dup_add(dup_mul(t, e, K), dup_mul(q, g, K), K) G = dup_trunc(dup_add(g, u, K), M, K) H = dup_trunc(dup_add(h, r, K), M, K) u = dup_add(dup_mul(s, G, K), dup_mul(t, H, K), K) b = dup_trunc(dup_sub(u, [K.one], K), M, K) c, d = dup_div(dup_mul(s, b, K), H, K) c = dup_trunc(c, M, K) d = dup_trunc(d, M, K) u = dup_add(dup_mul(t, b, K), dup_mul(c, G, K), K) S = dup_trunc(dup_sub(s, d, K), M, K) T = dup_trunc(dup_sub(t, u, K), M, K) return G, H, S, T def dup_zz_hensel_lift(p, f, f_list, l, K): r""" Multifactor Hensel lifting in `Z[x]`. Given a prime `p`, polynomial `f` over `Z[x]` such that `lc(f)` is a unit modulo `p`, monic pair-wise coprime polynomials `f_i` over `Z[x]` satisfying:: f = lc(f) f_1 ... f_r (mod p) and a positive integer `l`, returns a list of monic polynomials `F_1,\ F_2,\ \dots,\ F_r` satisfying:: f = lc(f) F_1 ... F_r (mod p**l) F_i = f_i (mod p), i = 1..r References ========== .. [1] [Gathen99]_ """ r = len(f_list) lc = dup_LC(f, K) if r == 1: F = dup_mul_ground(f, K.gcdex(lc, p**l)[0], K) return [ dup_trunc(F, p**l, K) ] m = p k = r // 2 d = int(_ceil(_log(l, 2))) g = gf_from_int_poly([lc], p) for f_i in f_list[:k]: g = gf_mul(g, gf_from_int_poly(f_i, p), p, K) h = gf_from_int_poly(f_list[k], p) for f_i in f_list[k + 1:]: h = gf_mul(h, gf_from_int_poly(f_i, p), p, K) s, t, _ = gf_gcdex(g, h, p, K) g = gf_to_int_poly(g, p) h = gf_to_int_poly(h, p) s = gf_to_int_poly(s, p) t = gf_to_int_poly(t, p) for _ in range(1, d + 1): (g, h, s, t), m = dup_zz_hensel_step(m, f, g, h, s, t, K), m**2 return dup_zz_hensel_lift(p, g, f_list[:k], l, K) \ + dup_zz_hensel_lift(p, h, f_list[k:], l, K) def _test_pl(fc, q, pl): if q > pl // 2: q = q - pl if not q: return True return fc % q == 0 def dup_zz_zassenhaus(f, K): """Factor primitive square-free polynomials in `Z[x]`. """ n = dup_degree(f) if n == 1: return [f] from sympy.ntheory import isprime fc = f[-1] A = dup_max_norm(f, K) b = dup_LC(f, K) B = int(abs(K.sqrt(K(n + 1))*2**n*A*b)) C = int((n + 1)**(2*n)*A**(2*n - 1)) gamma = int(_ceil(2*_log(C, 2))) bound = int(2*gamma*_log(gamma)) a = [] # choose a prime number `p` such that `f` be square free in Z_p # if there are many factors in Z_p, choose among a few different `p` # the one with fewer factors for px in range(3, bound + 1): if not isprime(px) or b % px == 0: continue px = K.convert(px) F = gf_from_int_poly(f, px) if not gf_sqf_p(F, px, K): continue fsqfx = gf_factor_sqf(F, px, K)[1] a.append((px, fsqfx)) if len(fsqfx) < 15 or len(a) > 4: break p, fsqf = min(a, key=lambda x: len(x[1])) l = int(_ceil(_log(2*B + 1, p))) modular = [gf_to_int_poly(ff, p) for ff in fsqf] g = dup_zz_hensel_lift(p, f, modular, l, K) sorted_T = range(len(g)) T = set(sorted_T) factors, s = [], 1 pl = p**l while 2*s <= len(T): for S in subsets(sorted_T, s): # lift the constant coefficient of the product `G` of the factors # in the subset `S`; if it is does not divide `fc`, `G` does # not divide the input polynomial if b == 1: q = 1 for i in S: q = q*g[i][-1] q = q % pl if not _test_pl(fc, q, pl): continue else: G = [b] for i in S: G = dup_mul(G, g[i], K) G = dup_trunc(G, pl, K) G = dup_primitive(G, K)[1] q = G[-1] if q and fc % q != 0: continue H = [b] S = set(S) T_S = T - S if b == 1: G = [b] for i in S: G = dup_mul(G, g[i], K) G = dup_trunc(G, pl, K) for i in T_S: H = dup_mul(H, g[i], K) H = dup_trunc(H, pl, K) G_norm = dup_l1_norm(G, K) H_norm = dup_l1_norm(H, K) if G_norm*H_norm <= B: T = T_S sorted_T = [i for i in sorted_T if i not in S] G = dup_primitive(G, K)[1] f = dup_primitive(H, K)[1] factors.append(G) b = dup_LC(f, K) break else: s += 1 return factors + [f] def dup_zz_irreducible_p(f, K): """Test irreducibility using Eisenstein's criterion. """ lc = dup_LC(f, K) tc = dup_TC(f, K) e_fc = dup_content(f[1:], K) if e_fc: from sympy.ntheory import factorint e_ff = factorint(int(e_fc)) for p in e_ff.keys(): if (lc % p) and (tc % p**2): return True def dup_cyclotomic_p(f, K, irreducible=False): """ Efficiently test if ``f`` is a cyclotomic polynomial. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 >>> R.dup_cyclotomic_p(f) False >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 >>> R.dup_cyclotomic_p(g) True """ if K.is_QQ: try: K0, K = K, K.get_ring() f = dup_convert(f, K0, K) except CoercionFailed: return False elif not K.is_ZZ: return False lc = dup_LC(f, K) tc = dup_TC(f, K) if lc != 1 or (tc != -1 and tc != 1): return False if not irreducible: coeff, factors = dup_factor_list(f, K) if coeff != K.one or factors != [(f, 1)]: return False n = dup_degree(f) g, h = [], [] for i in range(n, -1, -2): g.insert(0, f[i]) for i in range(n - 1, -1, -2): h.insert(0, f[i]) g = dup_sqr(dup_strip(g), K) h = dup_sqr(dup_strip(h), K) F = dup_sub(g, dup_lshift(h, 1, K), K) if K.is_negative(dup_LC(F, K)): F = dup_neg(F, K) if F == f: return True g = dup_mirror(f, K) if K.is_negative(dup_LC(g, K)): g = dup_neg(g, K) if F == g and dup_cyclotomic_p(g, K): return True G = dup_sqf_part(F, K) if dup_sqr(G, K) == F and dup_cyclotomic_p(G, K): return True return False def dup_zz_cyclotomic_poly(n, K): """Efficiently generate n-th cyclotomic polynomial. """ from sympy.ntheory import factorint h = [K.one, -K.one] for p, k in factorint(n).items(): h = dup_quo(dup_inflate(h, p, K), h, K) h = dup_inflate(h, p**(k - 1), K) return h def _dup_cyclotomic_decompose(n, K): from sympy.ntheory import factorint H = [[K.one, -K.one]] for p, k in factorint(n).items(): Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ] H.extend(Q) for i in range(1, k): Q = [ dup_inflate(q, p, K) for q in Q ] H.extend(Q) return H def dup_zz_cyclotomic_factor(f, K): """ Efficiently factor polynomials `x**n - 1` and `x**n + 1` in `Z[x]`. Given a univariate polynomial `f` in `Z[x]` returns a list of factors of `f`, provided that `f` is in the form `x**n - 1` or `x**n + 1` for `n >= 1`. Otherwise returns None. Factorization is performed using cyclotomic decomposition of `f`, which makes this method much faster that any other direct factorization approach (e.g. Zassenhaus's). References ========== .. [1] [Weisstein09]_ """ lc_f, tc_f = dup_LC(f, K), dup_TC(f, K) if dup_degree(f) <= 0: return None if lc_f != 1 or tc_f not in [-1, 1]: return None if any(bool(cf) for cf in f[1:-1]): return None n = dup_degree(f) F = _dup_cyclotomic_decompose(n, K) if not K.is_one(tc_f): return F else: H = [] for h in _dup_cyclotomic_decompose(2*n, K): if h not in F: H.append(h) return H def dup_zz_factor_sqf(f, K): """Factor square-free (non-primitive) polynomials in `Z[x]`. """ cont, g = dup_primitive(f, K) n = dup_degree(g) if dup_LC(g, K) < 0: cont, g = -cont, dup_neg(g, K) if n <= 0: return cont, [] elif n == 1: return cont, [g] if query('USE_IRREDUCIBLE_IN_FACTOR'): if dup_zz_irreducible_p(g, K): return cont, [g] factors = None if query('USE_CYCLOTOMIC_FACTOR'): factors = dup_zz_cyclotomic_factor(g, K) if factors is None: factors = dup_zz_zassenhaus(g, K) return cont, _sort_factors(factors, multiple=False) def dup_zz_factor(f, K): """ Factor (non square-free) polynomials in `Z[x]`. Given a univariate polynomial `f` in `Z[x]` computes its complete factorization `f_1, ..., f_n` into irreducibles over integers:: f = content(f) f_1**k_1 ... f_n**k_n The factorization is computed by reducing the input polynomial into a primitive square-free polynomial and factoring it using Zassenhaus algorithm. Trial division is used to recover the multiplicities of factors. The result is returned as a tuple consisting of:: (content(f), [(f_1, k_1), ..., (f_n, k_n)) Examples ======== Consider the polynomial `f = 2*x**4 - 2`:: >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_zz_factor(2*x**4 - 2) (2, [(x - 1, 1), (x + 1, 1), (x**2 + 1, 1)]) In result we got the following factorization:: f = 2 (x - 1) (x + 1) (x**2 + 1) Note that this is a complete factorization over integers, however over Gaussian integers we can factor the last term. By default, polynomials `x**n - 1` and `x**n + 1` are factored using cyclotomic decomposition to speedup computations. To disable this behaviour set cyclotomic=False. References ========== .. [1] [Gathen99]_ """ cont, g = dup_primitive(f, K) n = dup_degree(g) if dup_LC(g, K) < 0: cont, g = -cont, dup_neg(g, K) if n <= 0: return cont, [] elif n == 1: return cont, [(g, 1)] if query('USE_IRREDUCIBLE_IN_FACTOR'): if dup_zz_irreducible_p(g, K): return cont, [(g, 1)] g = dup_sqf_part(g, K) H = None if query('USE_CYCLOTOMIC_FACTOR'): H = dup_zz_cyclotomic_factor(g, K) if H is None: H = dup_zz_zassenhaus(g, K) factors = dup_trial_division(f, H, K) return cont, factors def dmp_zz_wang_non_divisors(E, cs, ct, K): """Wang/EEZ: Compute a set of valid divisors. """ result = [ cs*ct ] for q in E: q = abs(q) for r in reversed(result): while r != 1: r = K.gcd(r, q) q = q // r if K.is_one(q): return None result.append(q) return result[1:] def dmp_zz_wang_test_points(f, T, ct, A, u, K): """Wang/EEZ: Test evaluation points for suitability. """ if not dmp_eval_tail(dmp_LC(f, K), A, u - 1, K): raise EvaluationFailed('no luck') g = dmp_eval_tail(f, A, u, K) if not dup_sqf_p(g, K): raise EvaluationFailed('no luck') c, h = dup_primitive(g, K) if K.is_negative(dup_LC(h, K)): c, h = -c, dup_neg(h, K) v = u - 1 E = [ dmp_eval_tail(t, A, v, K) for t, _ in T ] D = dmp_zz_wang_non_divisors(E, c, ct, K) if D is not None: return c, h, E else: raise EvaluationFailed('no luck') def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K): """Wang/EEZ: Compute correct leading coefficients. """ C, J, v = [], [0]*len(E), u - 1 for h in H: c = dmp_one(v, K) d = dup_LC(h, K)*cs for i in reversed(range(len(E))): k, e, (t, _) = 0, E[i], T[i] while not (d % e): d, k = d//e, k + 1 if k != 0: c, J[i] = dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1 C.append(c) if not all(J): raise ExtraneousFactors # pragma: no cover CC, HH = [], [] for c, h in zip(C, H): d = dmp_eval_tail(c, A, v, K) lc = dup_LC(h, K) if K.is_one(cs): cc = lc//d else: g = K.gcd(lc, d) d, cc = d//g, lc//g h, cs = dup_mul_ground(h, d, K), cs//d c = dmp_mul_ground(c, cc, v, K) CC.append(c) HH.append(h) if K.is_one(cs): return f, HH, CC CCC, HHH = [], [] for c, h in zip(CC, HH): CCC.append(dmp_mul_ground(c, cs, v, K)) HHH.append(dmp_mul_ground(h, cs, 0, K)) f = dmp_mul_ground(f, cs**(len(H) - 1), u, K) return f, HHH, CCC def dup_zz_diophantine(F, m, p, K): """Wang/EEZ: Solve univariate Diophantine equations. """ if len(F) == 2: a, b = F f = gf_from_int_poly(a, p) g = gf_from_int_poly(b, p) s, t, G = gf_gcdex(g, f, p, K) s = gf_lshift(s, m, K) t = gf_lshift(t, m, K) q, s = gf_div(s, f, p, K) t = gf_add_mul(t, q, g, p, K) s = gf_to_int_poly(s, p) t = gf_to_int_poly(t, p) result = [s, t] else: G = [F[-1]] for f in reversed(F[1:-1]): G.insert(0, dup_mul(f, G[0], K)) S, T = [], [[1]] for f, g in zip(F, G): t, s = dmp_zz_diophantine([g, f], T[-1], [], 0, p, 1, K) T.append(t) S.append(s) result, S = [], S + [T[-1]] for s, f in zip(S, F): s = gf_from_int_poly(s, p) f = gf_from_int_poly(f, p) r = gf_rem(gf_lshift(s, m, K), f, p, K) s = gf_to_int_poly(r, p) result.append(s) return result def dmp_zz_diophantine(F, c, A, d, p, u, K): """Wang/EEZ: Solve multivariate Diophantine equations. """ if not A: S = [ [] for _ in F ] n = dup_degree(c) for i, coeff in enumerate(c): if not coeff: continue T = dup_zz_diophantine(F, n - i, p, K) for j, (s, t) in enumerate(zip(S, T)): t = dup_mul_ground(t, coeff, K) S[j] = dup_trunc(dup_add(s, t, K), p, K) else: n = len(A) e = dmp_expand(F, u, K) a, A = A[-1], A[:-1] B, G = [], [] for f in F: B.append(dmp_quo(e, f, u, K)) G.append(dmp_eval_in(f, a, n, u, K)) C = dmp_eval_in(c, a, n, u, K) v = u - 1 S = dmp_zz_diophantine(G, C, A, d, p, v, K) S = [ dmp_raise(s, 1, v, K) for s in S ] for s, b in zip(S, B): c = dmp_sub_mul(c, s, b, u, K) c = dmp_ground_trunc(c, p, u, K) m = dmp_nest([K.one, -a], n, K) M = dmp_one(n, K) for k in K.map(range(0, d)): if dmp_zero_p(c, u): break M = dmp_mul(M, m, u, K) C = dmp_diff_eval_in(c, k + 1, a, n, u, K) if not dmp_zero_p(C, v): C = dmp_quo_ground(C, K.factorial(k + 1), v, K) T = dmp_zz_diophantine(G, C, A, d, p, v, K) for i, t in enumerate(T): T[i] = dmp_mul(dmp_raise(t, 1, v, K), M, u, K) for i, (s, t) in enumerate(zip(S, T)): S[i] = dmp_add(s, t, u, K) for t, b in zip(T, B): c = dmp_sub_mul(c, t, b, u, K) c = dmp_ground_trunc(c, p, u, K) S = [ dmp_ground_trunc(s, p, u, K) for s in S ] return S def dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K): """Wang/EEZ: Parallel Hensel lifting algorithm. """ S, n, v = [f], len(A), u - 1 H = list(H) for i, a in enumerate(reversed(A[1:])): s = dmp_eval_in(S[0], a, n - i, u - i, K) S.insert(0, dmp_ground_trunc(s, p, v - i, K)) d = max(dmp_degree_list(f, u)[1:]) for j, s, a in zip(range(2, n + 2), S, A): G, w = list(H), j - 1 I, J = A[:j - 2], A[j - 1:] for i, (h, lc) in enumerate(zip(H, LC)): lc = dmp_ground_trunc(dmp_eval_tail(lc, J, v, K), p, w - 1, K) H[i] = [lc] + dmp_raise(h[1:], 1, w - 1, K) m = dmp_nest([K.one, -a], w, K) M = dmp_one(w, K) c = dmp_sub(s, dmp_expand(H, w, K), w, K) dj = dmp_degree_in(s, w, w) for k in K.map(range(0, dj)): if dmp_zero_p(c, w): break M = dmp_mul(M, m, w, K) C = dmp_diff_eval_in(c, k + 1, a, w, w, K) if not dmp_zero_p(C, w - 1): C = dmp_quo_ground(C, K.factorial(k + 1), w - 1, K) T = dmp_zz_diophantine(G, C, I, d, p, w - 1, K) for i, (h, t) in enumerate(zip(H, T)): h = dmp_add_mul(h, dmp_raise(t, 1, w - 1, K), M, w, K) H[i] = dmp_ground_trunc(h, p, w, K) h = dmp_sub(s, dmp_expand(H, w, K), w, K) c = dmp_ground_trunc(h, p, w, K) if dmp_expand(H, u, K) != f: raise ExtraneousFactors # pragma: no cover else: return H def dmp_zz_wang(f, u, K, mod=None, seed=None): r""" Factor primitive square-free polynomials in `Z[X]`. Given a multivariate polynomial `f` in `Z[x_1,...,x_n]`, which is primitive and square-free in `x_1`, computes factorization of `f` into irreducibles over integers. The procedure is based on Wang's Enhanced Extended Zassenhaus algorithm. The algorithm works by viewing `f` as a univariate polynomial in `Z[x_2,...,x_n][x_1]`, for which an evaluation mapping is computed:: x_2 -> a_2, ..., x_n -> a_n where `a_i`, for `i = 2, \dots, n`, are carefully chosen integers. The mapping is used to transform `f` into a univariate polynomial in `Z[x_1]`, which can be factored efficiently using Zassenhaus algorithm. The last step is to lift univariate factors to obtain true multivariate factors. For this purpose a parallel Hensel lifting procedure is used. The parameter ``seed`` is passed to _randint and can be used to seed randint (when an integer) or (for testing purposes) can be a sequence of numbers. References ========== .. [1] [Wang78]_ .. [2] [Geddes92]_ """ from sympy.ntheory import nextprime randint = _randint(seed) ct, T = dmp_zz_factor(dmp_LC(f, K), u - 1, K) b = dmp_zz_mignotte_bound(f, u, K) p = K(nextprime(b)) if mod is None: if u == 1: mod = 2 else: mod = 1 history, configs, A, r = set(), [], [K.zero]*u, None try: cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K) _, H = dup_zz_factor_sqf(s, K) r = len(H) if r == 1: return [f] configs = [(s, cs, E, H, A)] except EvaluationFailed: pass eez_num_configs = query('EEZ_NUMBER_OF_CONFIGS') eez_num_tries = query('EEZ_NUMBER_OF_TRIES') eez_mod_step = query('EEZ_MODULUS_STEP') while len(configs) < eez_num_configs: for _ in range(eez_num_tries): A = [ K(randint(-mod, mod)) for _ in range(u) ] if tuple(A) not in history: history.add(tuple(A)) else: continue try: cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K) except EvaluationFailed: continue _, H = dup_zz_factor_sqf(s, K) rr = len(H) if r is not None: if rr != r: # pragma: no cover if rr < r: configs, r = [], rr else: continue else: r = rr if r == 1: return [f] configs.append((s, cs, E, H, A)) if len(configs) == eez_num_configs: break else: mod += eez_mod_step s_norm, s_arg, i = None, 0, 0 for s, _, _, _, _ in configs: _s_norm = dup_max_norm(s, K) if s_norm is not None: if _s_norm < s_norm: s_norm = _s_norm s_arg = i else: s_norm = _s_norm i += 1 _, cs, E, H, A = configs[s_arg] orig_f = f try: f, H, LC = dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K) factors = dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K) except ExtraneousFactors: # pragma: no cover if query('EEZ_RESTART_IF_NEEDED'): return dmp_zz_wang(orig_f, u, K, mod + 1) else: raise ExtraneousFactors( "we need to restart algorithm with better parameters") result = [] for f in factors: _, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) result.append(f) return result def dmp_zz_factor(f, u, K): r""" Factor (non square-free) polynomials in `Z[X]`. Given a multivariate polynomial `f` in `Z[x]` computes its complete factorization `f_1, \dots, f_n` into irreducibles over integers:: f = content(f) f_1**k_1 ... f_n**k_n The factorization is computed by reducing the input polynomial into a primitive square-free polynomial and factoring it using Enhanced Extended Zassenhaus (EEZ) algorithm. Trial division is used to recover the multiplicities of factors. The result is returned as a tuple consisting of:: (content(f), [(f_1, k_1), ..., (f_n, k_n)) Consider polynomial `f = 2*(x**2 - y**2)`:: >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_zz_factor(2*x**2 - 2*y**2) (2, [(x - y, 1), (x + y, 1)]) In result we got the following factorization:: f = 2 (x - y) (x + y) References ========== .. [1] [Gathen99]_ """ if not u: return dup_zz_factor(f, K) if dmp_zero_p(f, u): return K.zero, [] cont, g = dmp_ground_primitive(f, u, K) if dmp_ground_LC(g, u, K) < 0: cont, g = -cont, dmp_neg(g, u, K) if all(d <= 0 for d in dmp_degree_list(g, u)): return cont, [] G, g = dmp_primitive(g, u, K) factors = [] if dmp_degree(g, u) > 0: g = dmp_sqf_part(g, u, K) H = dmp_zz_wang(g, u, K) factors = dmp_trial_division(f, H, u, K) for g, k in dmp_zz_factor(G, u - 1, K)[1]: factors.insert(0, ([g], k)) return cont, _sort_factors(factors) def dup_qq_i_factor(f, K0): """Factor univariate polynomials into irreducibles in `QQ_I[x]`. """ # Factor in QQ<I> K1 = K0.as_AlgebraicField() f = dup_convert(f, K0, K1) coeff, factors = dup_factor_list(f, K1) factors = [(dup_convert(fac, K1, K0), i) for fac, i in factors] coeff = K0.convert(coeff, K1) return coeff, factors def dup_zz_i_factor(f, K0): """Factor univariate polynomials into irreducibles in `ZZ_I[x]`. """ # First factor in QQ_I K1 = K0.get_field() f = dup_convert(f, K0, K1) coeff, factors = dup_qq_i_factor(f, K1) new_factors = [] for fac, i in factors: # Extract content fac_denom, fac_num = dup_clear_denoms(fac, K1) fac_num_ZZ_I = dup_convert(fac_num, K1, K0) content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, 0, K1) coeff = (coeff * content ** i) // fac_denom ** i new_factors.append((fac_prim, i)) factors = new_factors coeff = K0.convert(coeff, K1) return coeff, factors def dmp_qq_i_factor(f, u, K0): """Factor multivariate polynomials into irreducibles in `QQ_I[X]`. """ # Factor in QQ<I> K1 = K0.as_AlgebraicField() f = dmp_convert(f, u, K0, K1) coeff, factors = dmp_factor_list(f, u, K1) factors = [(dmp_convert(fac, u, K1, K0), i) for fac, i in factors] coeff = K0.convert(coeff, K1) return coeff, factors def dmp_zz_i_factor(f, u, K0): """Factor multivariate polynomials into irreducibles in `ZZ_I[X]`. """ # First factor in QQ_I K1 = K0.get_field() f = dmp_convert(f, u, K0, K1) coeff, factors = dmp_qq_i_factor(f, u, K1) new_factors = [] for fac, i in factors: # Extract content fac_denom, fac_num = dmp_clear_denoms(fac, u, K1) fac_num_ZZ_I = dmp_convert(fac_num, u, K1, K0) content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, u, K1) coeff = (coeff * content ** i) // fac_denom ** i new_factors.append((fac_prim, i)) factors = new_factors coeff = K0.convert(coeff, K1) return coeff, factors def dup_ext_factor(f, K): """Factor univariate polynomials over algebraic number fields. """ n, lc = dup_degree(f), dup_LC(f, K) f = dup_monic(f, K) if n <= 0: return lc, [] if n == 1: return lc, [(f, 1)] f, F = dup_sqf_part(f, K), f s, g, r = dup_sqf_norm(f, K) factors = dup_factor_list_include(r, K.dom) if len(factors) == 1: return lc, [(f, n//dup_degree(f))] H = s*K.unit for i, (factor, _) in enumerate(factors): h = dup_convert(factor, K.dom, K) h, _, g = dup_inner_gcd(h, g, K) h = dup_shift(h, H, K) factors[i] = h factors = dup_trial_division(F, factors, K) return lc, factors def dmp_ext_factor(f, u, K): """Factor multivariate polynomials over algebraic number fields. """ if not u: return dup_ext_factor(f, K) lc = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K) if all(d <= 0 for d in dmp_degree_list(f, u)): return lc, [] f, F = dmp_sqf_part(f, u, K), f s, g, r = dmp_sqf_norm(f, u, K) factors = dmp_factor_list_include(r, u, K.dom) if len(factors) == 1: factors = [f] else: H = dmp_raise([K.one, s*K.unit], u, 0, K) for i, (factor, _) in enumerate(factors): h = dmp_convert(factor, u, K.dom, K) h, _, g = dmp_inner_gcd(h, g, u, K) h = dmp_compose(h, H, u, K) factors[i] = h return lc, dmp_trial_division(F, factors, u, K) def dup_gf_factor(f, K): """Factor univariate polynomials over finite fields. """ f = dup_convert(f, K, K.dom) coeff, factors = gf_factor(f, K.mod, K.dom) for i, (f, k) in enumerate(factors): factors[i] = (dup_convert(f, K.dom, K), k) return K.convert(coeff, K.dom), factors def dmp_gf_factor(f, u, K): """Factor multivariate polynomials over finite fields. """ raise NotImplementedError('multivariate polynomials over finite fields') def dup_factor_list(f, K0): """Factor univariate polynomials into irreducibles in `K[x]`. """ j, f = dup_terms_gcd(f, K0) cont, f = dup_primitive(f, K0) if K0.is_FiniteField: coeff, factors = dup_gf_factor(f, K0) elif K0.is_Algebraic: coeff, factors = dup_ext_factor(f, K0) elif K0.is_GaussianRing: coeff, factors = dup_zz_i_factor(f, K0) elif K0.is_GaussianField: coeff, factors = dup_qq_i_factor(f, K0) else: if not K0.is_Exact: K0_inexact, K0 = K0, K0.get_exact() f = dup_convert(f, K0_inexact, K0) else: K0_inexact = None if K0.is_Field: K = K0.get_ring() denom, f = dup_clear_denoms(f, K0, K) f = dup_convert(f, K0, K) else: K = K0 if K.is_ZZ: coeff, factors = dup_zz_factor(f, K) elif K.is_Poly: f, u = dmp_inject(f, 0, K) coeff, factors = dmp_factor_list(f, u, K.dom) for i, (f, k) in enumerate(factors): factors[i] = (dmp_eject(f, u, K), k) coeff = K.convert(coeff, K.dom) else: # pragma: no cover raise DomainError('factorization not supported over %s' % K0) if K0.is_Field: for i, (f, k) in enumerate(factors): factors[i] = (dup_convert(f, K, K0), k) coeff = K0.convert(coeff, K) coeff = K0.quo(coeff, denom) if K0_inexact: for i, (f, k) in enumerate(factors): max_norm = dup_max_norm(f, K0) f = dup_quo_ground(f, max_norm, K0) f = dup_convert(f, K0, K0_inexact) factors[i] = (f, k) coeff = K0.mul(coeff, K0.pow(max_norm, k)) coeff = K0_inexact.convert(coeff, K0) K0 = K0_inexact if j: factors.insert(0, ([K0.one, K0.zero], j)) return coeff*cont, _sort_factors(factors) def dup_factor_list_include(f, K): """Factor univariate polynomials into irreducibles in `K[x]`. """ coeff, factors = dup_factor_list(f, K) if not factors: return [(dup_strip([coeff]), 1)] else: g = dup_mul_ground(factors[0][0], coeff, K) return [(g, factors[0][1])] + factors[1:] def dmp_factor_list(f, u, K0): """Factor multivariate polynomials into irreducibles in `K[X]`. """ if not u: return dup_factor_list(f, K0) J, f = dmp_terms_gcd(f, u, K0) cont, f = dmp_ground_primitive(f, u, K0) if K0.is_FiniteField: # pragma: no cover coeff, factors = dmp_gf_factor(f, u, K0) elif K0.is_Algebraic: coeff, factors = dmp_ext_factor(f, u, K0) elif K0.is_GaussianRing: coeff, factors = dmp_zz_i_factor(f, u, K0) elif K0.is_GaussianField: coeff, factors = dmp_qq_i_factor(f, u, K0) else: if not K0.is_Exact: K0_inexact, K0 = K0, K0.get_exact() f = dmp_convert(f, u, K0_inexact, K0) else: K0_inexact = None if K0.is_Field: K = K0.get_ring() denom, f = dmp_clear_denoms(f, u, K0, K) f = dmp_convert(f, u, K0, K) else: K = K0 if K.is_ZZ: levels, f, v = dmp_exclude(f, u, K) coeff, factors = dmp_zz_factor(f, v, K) for i, (f, k) in enumerate(factors): factors[i] = (dmp_include(f, levels, v, K), k) elif K.is_Poly: f, v = dmp_inject(f, u, K) coeff, factors = dmp_factor_list(f, v, K.dom) for i, (f, k) in enumerate(factors): factors[i] = (dmp_eject(f, v, K), k) coeff = K.convert(coeff, K.dom) else: # pragma: no cover raise DomainError('factorization not supported over %s' % K0) if K0.is_Field: for i, (f, k) in enumerate(factors): factors[i] = (dmp_convert(f, u, K, K0), k) coeff = K0.convert(coeff, K) coeff = K0.quo(coeff, denom) if K0_inexact: for i, (f, k) in enumerate(factors): max_norm = dmp_max_norm(f, u, K0) f = dmp_quo_ground(f, max_norm, u, K0) f = dmp_convert(f, u, K0, K0_inexact) factors[i] = (f, k) coeff = K0.mul(coeff, K0.pow(max_norm, k)) coeff = K0_inexact.convert(coeff, K0) K0 = K0_inexact for i, j in enumerate(reversed(J)): if not j: continue term = {(0,)*(u - i) + (1,) + (0,)*i: K0.one} factors.insert(0, (dmp_from_dict(term, u, K0), j)) return coeff*cont, _sort_factors(factors) def dmp_factor_list_include(f, u, K): """Factor multivariate polynomials into irreducibles in `K[X]`. """ if not u: return dup_factor_list_include(f, K) coeff, factors = dmp_factor_list(f, u, K) if not factors: return [(dmp_ground(coeff, u), 1)] else: g = dmp_mul_ground(factors[0][0], coeff, u, K) return [(g, factors[0][1])] + factors[1:] def dup_irreducible_p(f, K): """ Returns ``True`` if a univariate polynomial ``f`` has no factors over its domain. """ return dmp_irreducible_p(f, 0, K) def dmp_irreducible_p(f, u, K): """ Returns ``True`` if a multivariate polynomial ``f`` has no factors over its domain. """ _, factors = dmp_factor_list(f, u, K) if not factors: return True elif len(factors) > 1: return False else: _, k = factors[0] return k == 1
e4040e9ca8e519844011df7d83d166544ce3a3360f1ba4adaf1e8c40db465a4b
"""py.test hacks to support XFAIL/XPASS""" import sys import re import functools import os import contextlib import warnings import inspect import pathlib from typing import Any, Callable from sympy.utilities.exceptions import SymPyDeprecationWarning # Imported here for backwards compatibility. Note: do not import this from # here in library code (importing sympy.pytest in library code will break the # pytest integration). from sympy.utilities.exceptions import ignore_warnings # noqa:F401 ON_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None) try: import pytest USE_PYTEST = getattr(sys, '_running_pytest', False) except ImportError: USE_PYTEST = False raises: Callable[[Any, Any], Any] XFAIL: Callable[[Any], Any] skip: Callable[[Any], Any] SKIP: Callable[[Any], Any] slow: Callable[[Any], Any] nocache_fail: Callable[[Any], Any] if USE_PYTEST: raises = pytest.raises skip = pytest.skip XFAIL = pytest.mark.xfail SKIP = pytest.mark.skip slow = pytest.mark.slow nocache_fail = pytest.mark.nocache_fail from _pytest.outcomes import Failed else: # Not using pytest so define the things that would have been imported from # there. # _pytest._code.code.ExceptionInfo class ExceptionInfo: def __init__(self, value): self.value = value def __repr__(self): return "<ExceptionInfo {!r}>".format(self.value) def raises(expectedException, code=None): """ Tests that ``code`` raises the exception ``expectedException``. ``code`` may be a callable, such as a lambda expression or function name. If ``code`` is not given or None, ``raises`` will return a context manager for use in ``with`` statements; the code to execute then comes from the scope of the ``with``. ``raises()`` does nothing if the callable raises the expected exception, otherwise it raises an AssertionError. Examples ======== >>> from sympy.testing.pytest import raises >>> raises(ZeroDivisionError, lambda: 1/0) <ExceptionInfo ZeroDivisionError(...)> >>> raises(ZeroDivisionError, lambda: 1/2) Traceback (most recent call last): ... Failed: DID NOT RAISE >>> with raises(ZeroDivisionError): ... n = 1/0 >>> with raises(ZeroDivisionError): ... n = 1/2 Traceback (most recent call last): ... Failed: DID NOT RAISE Note that you cannot test multiple statements via ``with raises``: >>> with raises(ZeroDivisionError): ... n = 1/0 # will execute and raise, aborting the ``with`` ... n = 9999/0 # never executed This is just what ``with`` is supposed to do: abort the contained statement sequence at the first exception and let the context manager deal with the exception. To test multiple statements, you'll need a separate ``with`` for each: >>> with raises(ZeroDivisionError): ... n = 1/0 # will execute and raise >>> with raises(ZeroDivisionError): ... n = 9999/0 # will also execute and raise """ if code is None: return RaisesContext(expectedException) elif callable(code): try: code() except expectedException as e: return ExceptionInfo(e) raise Failed("DID NOT RAISE") elif isinstance(code, str): raise TypeError( '\'raises(xxx, "code")\' has been phased out; ' 'change \'raises(xxx, "expression")\' ' 'to \'raises(xxx, lambda: expression)\', ' '\'raises(xxx, "statement")\' ' 'to \'with raises(xxx): statement\'') else: raise TypeError( 'raises() expects a callable for the 2nd argument.') class RaisesContext: def __init__(self, expectedException): self.expectedException = expectedException def __enter__(self): return None def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: raise Failed("DID NOT RAISE") return issubclass(exc_type, self.expectedException) class XFail(Exception): pass class XPass(Exception): pass class Skipped(Exception): pass class Failed(Exception): # type: ignore pass def XFAIL(func): def wrapper(): try: func() except Exception as e: message = str(e) if message != "Timeout": raise XFail(func.__name__) else: raise Skipped("Timeout") raise XPass(func.__name__) wrapper = functools.update_wrapper(wrapper, func) return wrapper def skip(str): raise Skipped(str) def SKIP(reason): """Similar to ``skip()``, but this is a decorator. """ def wrapper(func): def func_wrapper(): raise Skipped(reason) func_wrapper = functools.update_wrapper(func_wrapper, func) return func_wrapper return wrapper def slow(func): func._slow = True def func_wrapper(): func() func_wrapper = functools.update_wrapper(func_wrapper, func) func_wrapper.__wrapped__ = func return func_wrapper def nocache_fail(func): "Dummy decorator for marking tests that fail when cache is disabled" return func @contextlib.contextmanager def warns(warningcls, *, match='', test_stacklevel=True): ''' Like raises but tests that warnings are emitted. >>> from sympy.testing.pytest import warns >>> import warnings >>> with warns(UserWarning): ... warnings.warn('deprecated', UserWarning, stacklevel=2) >>> with warns(UserWarning): ... pass Traceback (most recent call last): ... Failed: DID NOT WARN. No warnings of type UserWarning\ was emitted. The list of emitted warnings is: []. ``test_stacklevel`` makes it check that the ``stacklevel`` parameter to ``warn()`` is set so that the warning shows the user line of code (the code under the warns() context manager). Set this to False if this is ambiguous or if the context manager does not test the direct user code that emits the warning. If the warning is a ``SymPyDeprecationWarning``, this additionally tests that the ``active_deprecations_target`` is a real target in the ``active-deprecations.md`` file. ''' # Absorbs all warnings in warnrec with warnings.catch_warnings(record=True) as warnrec: # Any warning other than the one we are looking for is an error warnings.simplefilter("error") warnings.filterwarnings("always", category=warningcls) # Now run the test yield warnrec # Raise if expected warning not found if not any(issubclass(w.category, warningcls) for w in warnrec): msg = ('Failed: DID NOT WARN.' ' No warnings of type %s was emitted.' ' The list of emitted warnings is: %s.' ) % (warningcls, [w.message for w in warnrec]) raise Failed(msg) # We don't include the match in the filter above because it would then # fall to the error filter, so we instead manually check that it matches # here for w in warnrec: # Should always be true due to the filters above assert issubclass(w.category, warningcls) if not re.compile(match, re.I).match(str(w.message)): raise Failed(f"Failed: WRONG MESSAGE. A warning with of the correct category ({warningcls.__name__}) was issued, but it did not match the given match regex ({match!r})") if test_stacklevel: for f in inspect.stack(): thisfile = f.filename file = os.path.split(thisfile)[1] if file.startswith('test_'): break elif file == 'doctest.py': # skip the stacklevel testing in the doctests of this # function return else: raise RuntimeError("Could not find the file for the given warning to test the stacklevel") for w in warnrec: if w.filename != thisfile: msg = f'''\ Failed: Warning has the wrong stacklevel. The warning stacklevel needs to be set so that the line of code shown in the warning message is user code that calls the deprecated code (the current stacklevel is showing code from {w.filename} (line {w.lineno}), expected {thisfile})'''.replace('\n', ' ') raise Failed(msg) if warningcls == SymPyDeprecationWarning: this_file = pathlib.Path(__file__) active_deprecations_file = (this_file.parent.parent.parent / 'doc' / 'src' / 'explanation' / 'active-deprecations.md') if not active_deprecations_file.exists(): # We can only test that the active_deprecations_target works if we are # in the git repo. return targets = [] for w in warnrec: targets.append(w.message.active_deprecations_target) with open(active_deprecations_file, encoding="utf-8") as f: text = f.read() for target in targets: if f'({target})=' not in text: raise Failed(f"The active deprecations target {target!r} does not appear to be a valid target in the active-deprecations.md file ({active_deprecations_file}).") def _both_exp_pow(func): """ Decorator used to run the test twice: the first time `e^x` is represented as ``Pow(E, x)``, the second time as ``exp(x)`` (exponential object is not a power). This is a temporary trick helping to manage the elimination of the class ``exp`` in favor of a replacement by ``Pow(E, ...)``. """ from sympy.core.parameters import _exp_is_pow def func_wrap(): with _exp_is_pow(True): func() with _exp_is_pow(False): func() wrapper = functools.update_wrapper(func_wrap, func) return wrapper @contextlib.contextmanager def warns_deprecated_sympy(): ''' Shorthand for ``warns(SymPyDeprecationWarning)`` This is the recommended way to test that ``SymPyDeprecationWarning`` is emitted for deprecated features in SymPy. To test for other warnings use ``warns``. To suppress warnings without asserting that they are emitted use ``ignore_warnings``. .. note:: ``warns_deprecated_sympy()`` is only intended for internal use in the SymPy test suite to test that a deprecation warning triggers properly. All other code in the SymPy codebase, including documentation examples, should not use deprecated behavior. If you are a user of SymPy and you want to disable SymPyDeprecationWarnings, use ``warnings`` filters (see :ref:`silencing-sympy-deprecation-warnings`). >>> from sympy.testing.pytest import warns_deprecated_sympy >>> from sympy.utilities.exceptions import sympy_deprecation_warning >>> with warns_deprecated_sympy(): ... sympy_deprecation_warning("Don't use", ... deprecated_since_version="1.0", ... active_deprecations_target="active-deprecations") >>> with warns_deprecated_sympy(): ... pass Traceback (most recent call last): ... Failed: DID NOT WARN. No warnings of type \ SymPyDeprecationWarning was emitted. The list of emitted warnings is: []. .. note:: Sometimes the stacklevel test will fail because the same warning is emitted multiple times. In this case, you can use :func:`sympy.utilities.exceptions.ignore_warnings` in the code to prevent the ``SymPyDeprecationWarning`` from being emitted again recursively. In rare cases it is impossible to have a consistent ``stacklevel`` for deprecation warnings because different ways of calling a function will produce different call stacks.. In those cases, use ``warns(SymPyDeprecationWarning)`` instead. See Also ======== sympy.utilities.exceptions.SymPyDeprecationWarning sympy.utilities.exceptions.sympy_deprecation_warning sympy.utilities.decorator.deprecated ''' with warns(SymPyDeprecationWarning): yield
6499f4a824063b133f14a124f0bd1b3fa30780588d52ca47f1cd00e0909e575f
""" This is our testing framework. Goals: * it should be compatible with py.test and operate very similarly (or identically) * does not require any external dependencies * preferably all the functionality should be in this file only * no magic, just import the test file and execute the test functions, that's it * portable """ import os import sys import platform import inspect import traceback import pdb import re import linecache import time from fnmatch import fnmatch from timeit import default_timer as clock import doctest as pdoctest # avoid clashing with our doctest() function from doctest import DocTestFinder, DocTestRunner import random import subprocess import shutil import signal import stat import tempfile import warnings from contextlib import contextmanager from inspect import unwrap from sympy.core.cache import clear_cache from sympy.external import import_module from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY IS_WINDOWS = (os.name == 'nt') ON_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None) # emperically generated list of the proportion of time spent running # an even split of tests. This should periodically be regenerated. # A list of [.6, .1, .3] would mean that if the tests are evenly split # into '1/3', '2/3', '3/3', the first split would take 60% of the time, # the second 10% and the third 30%. These lists are normalized to sum # to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3]. # # This list can be generated with the code: # from time import time # import sympy # import os # os.environ["TRAVIS_BUILD_NUMBER"] = '2' # Mock travis to get more correct densities # delays, num_splits = [], 30 # for i in range(1, num_splits + 1): # tic = time() # sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests # delays.append(time() - tic) # tot = sum(delays) # print([round(x / tot, 4) for x in delays]) SPLIT_DENSITY = [ 0.0059, 0.0027, 0.0068, 0.0011, 0.0006, 0.0058, 0.0047, 0.0046, 0.004, 0.0257, 0.0017, 0.0026, 0.004, 0.0032, 0.0016, 0.0015, 0.0004, 0.0011, 0.0016, 0.0014, 0.0077, 0.0137, 0.0217, 0.0074, 0.0043, 0.0067, 0.0236, 0.0004, 0.1189, 0.0142, 0.0234, 0.0003, 0.0003, 0.0047, 0.0006, 0.0013, 0.0004, 0.0008, 0.0007, 0.0006, 0.0139, 0.0013, 0.0007, 0.0051, 0.002, 0.0004, 0.0005, 0.0213, 0.0048, 0.0016, 0.0012, 0.0014, 0.0024, 0.0015, 0.0004, 0.0005, 0.0007, 0.011, 0.0062, 0.0015, 0.0021, 0.0049, 0.0006, 0.0006, 0.0011, 0.0006, 0.0019, 0.003, 0.0044, 0.0054, 0.0057, 0.0049, 0.0016, 0.0006, 0.0009, 0.0006, 0.0012, 0.0006, 0.0149, 0.0532, 0.0076, 0.0041, 0.0024, 0.0135, 0.0081, 0.2209, 0.0459, 0.0438, 0.0488, 0.0137, 0.002, 0.0003, 0.0008, 0.0039, 0.0024, 0.0005, 0.0004, 0.003, 0.056, 0.0026] SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483] class Skipped(Exception): pass class TimeOutError(Exception): pass class DependencyError(Exception): pass def _indent(s, indent=4): """ Add the given number of space characters to the beginning of every non-blank line in ``s``, and return the result. If the string ``s`` is Unicode, it is encoded using the stdout encoding and the ``backslashreplace`` error handler. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) pdoctest._indent = _indent # type: ignore # override reporter to maintain windows and python3 def _report_failure(self, out, test, example, got): """ Report that the given example failed. """ s = self._checker.output_difference(example, got, self.optionflags) s = s.encode('raw_unicode_escape').decode('utf8', 'ignore') out(self._failure_header(test, example) + s) if IS_WINDOWS: DocTestRunner.report_failure = _report_failure # type: ignore def convert_to_native_paths(lst): """ Converts a list of '/' separated paths into a list of native (os.sep separated) paths and converts to lowercase if the system is case insensitive. """ newlst = [] for i, rv in enumerate(lst): rv = os.path.join(*rv.split("/")) # on windows the slash after the colon is dropped if sys.platform == "win32": pos = rv.find(':') if pos != -1: if rv[pos + 1] != '\\': rv = rv[:pos + 1] + '\\' + rv[pos + 1:] newlst.append(os.path.normcase(rv)) return newlst def get_sympy_dir(): """ Returns the root SymPy directory and set the global value indicating whether the system is case sensitive or not. """ this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") sympy_dir = os.path.normpath(sympy_dir) return os.path.normcase(sympy_dir) def setup_pprint(): from sympy.interactive.printing import init_printing from sympy.printing.pretty.pretty import pprint_use_unicode import sympy.interactive.printing as interactive_printing # force pprint to be in ascii mode in doctests use_unicode_prev = pprint_use_unicode(False) # hook our nice, hash-stable strprinter init_printing(pretty_print=False) # Prevent init_printing() in doctests from affecting other doctests interactive_printing.NO_GLOBAL = True return use_unicode_prev @contextmanager def raise_on_deprecated(): """Context manager to make DeprecationWarning raise an error This is to catch SymPyDeprecationWarning from library code while running tests and doctests. It is important to use this context manager around each individual test/doctest in case some tests modify the warning filters. """ with warnings.catch_warnings(): warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*') yield def run_in_subprocess_with_hash_randomization( function, function_args=(), function_kwargs=None, command=sys.executable, module='sympy.testing.runtests', force=False): """ Run a function in a Python subprocess with hash randomization enabled. If hash randomization is not supported by the version of Python given, it returns False. Otherwise, it returns the exit value of the command. The function is passed to sys.exit(), so the return value of the function will be the return value. The environment variable PYTHONHASHSEED is used to seed Python's hash randomization. If it is set, this function will return False, because starting a new subprocess is unnecessary in that case. If it is not set, one is set at random, and the tests are run. Note that if this environment variable is set when Python starts, hash randomization is automatically enabled. To force a subprocess to be created even if PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a subprocess in Python versions that do not support hash randomization (see below), because those versions of Python do not support the ``-R`` flag. ``function`` should be a string name of a function that is importable from the module ``module``, like "_test". The default for ``module`` is "sympy.testing.runtests". ``function_args`` and ``function_kwargs`` should be a repr-able tuple and dict, respectively. The default Python command is sys.executable, which is the currently running Python command. This function is necessary because the seed for hash randomization must be set by the environment variable before Python starts. Hence, in order to use a predetermined seed for tests, we must start Python in a separate subprocess. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. Examples ======== >>> from sympy.testing.runtests import ( ... run_in_subprocess_with_hash_randomization) >>> # run the core tests in verbose mode >>> run_in_subprocess_with_hash_randomization("_test", ... function_args=("core",), ... function_kwargs={'verbose': True}) # doctest: +SKIP # Will return 0 if sys.executable supports hash randomization and tests # pass, 1 if they fail, and False if it does not support hash # randomization. """ cwd = get_sympy_dir() # Note, we must return False everywhere, not None, as subprocess.call will # sometimes return None. # First check if the Python version supports hash randomization # If it does not have this support, it won't recognize the -R flag p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) p.communicate() if p.returncode != 0: return False hash_seed = os.getenv("PYTHONHASHSEED") if not hash_seed: os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32)) else: if not force: return False function_kwargs = function_kwargs or {} # Now run the command commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" % (module, function, function, repr(function_args), repr(function_kwargs))) try: p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd) p.communicate() except KeyboardInterrupt: p.wait() finally: # Put the environment variable back, so that it reads correctly for # the current Python process. if hash_seed is None: del os.environ["PYTHONHASHSEED"] else: os.environ["PYTHONHASHSEED"] = hash_seed return p.returncode def run_all_tests(test_args=(), test_kwargs=None, doctest_args=(), doctest_kwargs=None, examples_args=(), examples_kwargs=None): """ Run all tests. Right now, this runs the regular tests (bin/test), the doctests (bin/doctest), and the examples (examples/all.py). This is what ``setup.py test`` uses. You can pass arguments and keyword arguments to the test functions that support them (for now, test, doctest, and the examples). See the docstrings of those functions for a description of the available options. For example, to run the solvers tests with colors turned off: >>> from sympy.testing.runtests import run_all_tests >>> run_all_tests(test_args=("solvers",), ... test_kwargs={"colors:False"}) # doctest: +SKIP """ tests_successful = True test_kwargs = test_kwargs or {} doctest_kwargs = doctest_kwargs or {} examples_kwargs = examples_kwargs or {'quiet': True} try: # Regular tests if not test(*test_args, **test_kwargs): # some regular test fails, so set the tests_successful # flag to false and continue running the doctests tests_successful = False # Doctests print() if not doctest(*doctest_args, **doctest_kwargs): tests_successful = False # Examples print() sys.path.append("examples") # examples/all.py from all import run_examples # type: ignore if not run_examples(*examples_args, **examples_kwargs): tests_successful = False if tests_successful: return else: # Return nonzero exit code sys.exit(1) except KeyboardInterrupt: print() print("DO *NOT* COMMIT!") sys.exit(1) def test(*paths, subprocess=True, rerun=0, **kwargs): """ Run tests in the specified test_*.py files. Tests in a particular test_*.py file are run if any of the given strings in ``paths`` matches a part of the test file's path. If ``paths=[]``, tests in all test_*.py files are run. Notes: - If sort=False, tests are run in random order (not default). - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. **Explanation of test results** ====== =============================================================== Output Meaning ====== =============================================================== . passed F failed X XPassed (expected to fail but passed) f XFAILed (expected to fail and indeed failed) s skipped w slow T timeout (e.g., when ``--timeout`` is used) K KeyboardInterrupt (when running the slow tests with ``--slow``, you can interrupt one of them without killing the test runner) ====== =============================================================== Colors have no additional meaning and are used just to facilitate interpreting the output. Examples ======== >>> import sympy Run all tests: >>> sympy.test() # doctest: +SKIP Run one file: >>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP >>> sympy.test("_basic") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.test("sympy/core/tests/test_basic.py", ... "sympy/functions") # doctest: +SKIP Run all tests in sympy/core and sympy/utilities: >>> sympy.test("/core", "/util") # doctest: +SKIP Run specific test from a file: >>> sympy.test("sympy/core/tests/test_basic.py", ... kw="test_equality") # doctest: +SKIP Run specific test from any file: >>> sympy.test(kw="subs") # doctest: +SKIP Run the tests with verbose mode on: >>> sympy.test(verbose=True) # doctest: +SKIP Do not sort the test output: >>> sympy.test(sort=False) # doctest: +SKIP Turn on post-mortem pdb: >>> sympy.test(pdb=True) # doctest: +SKIP Turn off colors: >>> sympy.test(colors=False) # doctest: +SKIP Force colors, even when the output is not to a terminal (this is useful, e.g., if you are piping to ``less -r`` and you still want colors) >>> sympy.test(force_colors=False) # doctest: +SKIP The traceback verboseness can be set to "short" or "no" (default is "short") >>> sympy.test(tb='no') # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. For instance, to run the first half of the test suite: >>> sympy.test(split='1/2') # doctest: +SKIP The ``time_balance`` option can be passed in conjunction with ``split``. If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt to split the tests such that each split takes equal time. This heuristic for balancing is based on pre-recorded test data. >>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP You can disable running the tests in a separate subprocess using ``subprocess=False``. This is done to support seeding hash randomization, which is enabled by default in the Python versions where it is supported. If subprocess=False, hash randomization is enabled/disabled according to whether it has been enabled or not in the calling Python process. However, even if it is enabled, the seed cannot be printed unless it is called from a new Python process. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. If hash randomization is not supported ``subprocess=False`` is used automatically. >>> sympy.test(subprocess=False) # doctest: +SKIP To set the hash randomization seed, set the environment variable ``PYTHONHASHSEED`` before running the tests. This can be done from within Python using >>> import os >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP Or from the command line using $ PYTHONHASHSEED=42 ./bin/test If the seed is not set, a random seed will be chosen. Note that to reproduce the same hash values, you must use both the same seed as well as the same architecture (32-bit vs. 64-bit). """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_test", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_test(*paths, **kwargs)) if not val or i == 0: return val def _test(*paths, verbose=False, tb="short", kw=None, pdb=False, colors=True, force_colors=False, sort=True, seed=None, timeout=False, fail_on_timeout=False, slow=False, enhance_asserts=False, split=None, time_balance=True, blacklist=('sympy/integrals/rubi/rubi_tests/tests',), fast_threshold=None, slow_threshold=None): """ Internal function that actually runs the tests. All keyword arguments from ``test()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstring of ``test()`` for more information. """ kw = kw or () # ensure that kw is a tuple if isinstance(kw, str): kw = (kw,) post_mortem = pdb if seed is None: seed = random.randrange(100000000) if ON_TRAVIS and timeout is False: # Travis times out if no activity is seen for 10 minutes. timeout = 595 fail_on_timeout = True if ON_TRAVIS: # pyglet does not work on Travis blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests'] blacklist = convert_to_native_paths(blacklist) r = PyTestReporter(verbose=verbose, tb=tb, colors=colors, force_colors=force_colors, split=split) t = SymPyTests(r, kw, post_mortem, seed, fast_threshold=fast_threshold, slow_threshold=slow_threshold) test_files = t.get_test_files('sympy') not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break density = None if time_balance: if slow: density = SPLIT_DENSITY_SLOW else: density = SPLIT_DENSITY if split: matched = split_list(matched, split, density=density) t._testfiles.extend(matched) return int(not t.test(sort=sort, timeout=timeout, slow=slow, enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout)) def doctest(*paths, subprocess=True, rerun=0, **kwargs): r""" Runs doctests in all \*.py files in the SymPy directory which match any of the given strings in ``paths`` or all tests if paths=[]. Notes: - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. Examples ======== >>> import sympy Run all tests: >>> sympy.doctest() # doctest: +SKIP Run one file: >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP >>> sympy.doctest("polynomial.rst") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP Run any file having polynomial in its name, doc/src/modules/polynomial.rst, sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py: >>> sympy.doctest("polynomial") # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. Note that the regular doctests and the Sphinx doctests are split independently. For instance, to run the first half of the test suite: >>> sympy.doctest(split='1/2') # doctest: +SKIP The ``subprocess`` and ``verbose`` options are the same as with the function ``test()``. See the docstring of that function for more information. """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_doctest", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_doctest(*paths, **kwargs)) if not val or i == 0: return val def _get_doctest_blacklist(): '''Get the default blacklist for the doctests''' blacklist = [] blacklist.extend([ "doc/src/modules/plotting.rst", # generates live plots "doc/src/modules/physics/mechanics/autolev_parser.rst", "sympy/codegen/array_utils.py", # raises deprecation warning "sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/galgebra.py", # no longer part of SymPy "sympy/integrals/rubi/rubi.py", "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code "sympy/parsing/latex/_antlr/latexlexer.py", # generated code "sympy/parsing/latex/_antlr/latexparser.py", # generated code "sympy/plotting/pygletplot/__init__.py", # crashes on some systems "sympy/plotting/pygletplot/plot.py", # crashes on some systems "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/this.py", # prints text ]) # autolev parser tests num = 12 for i in range (1, num+1): blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py") blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"]) if import_module('numpy') is None: blacklist.extend([ "sympy/plotting/experimental_lambdify.py", "sympy/plotting/plot_implicit.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py", "examples/intermediate/sample.py", "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py", "doc/src/modules/numeric-computation.rst" ]) else: if import_module('matplotlib') is None: blacklist.extend([ "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py" ]) else: # Use a non-windowed backend, so that the tests work on Travis import matplotlib matplotlib.use('Agg') if ON_TRAVIS or import_module('pyglet') is None: blacklist.extend(["sympy/plotting/pygletplot"]) if import_module('aesara') is None: blacklist.extend([ "sympy/printing/aesaracode.py", "doc/src/modules/numeric-computation.rst", ]) if import_module('cupy') is None: blacklist.extend([ "doc/src/modules/numeric-computation.rst", ]) if import_module('antlr4') is None: blacklist.extend([ "sympy/parsing/autolev/__init__.py", "sympy/parsing/latex/_parse_latex_antlr.py", ]) if import_module('lfortran') is None: #throws ImportError when lfortran not installed blacklist.extend([ "sympy/parsing/sym_expr.py", ]) # disabled because of doctest failures in asmeurer's bot blacklist.extend([ "sympy/utilities/autowrap.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py" ]) # blacklist these modules until issue 4840 is resolved blacklist.extend([ "sympy/conftest.py", # Depends on pytest "sympy/testing/benchmarking.py", ]) # These are deprecated stubs to be removed: blacklist.extend([ "sympy/utilities/benchmarking.py", "sympy/utilities/tmpfiles.py", "sympy/utilities/pytest.py", "sympy/utilities/runtests.py", "sympy/utilities/quality_unicode.py", "sympy/utilities/randtest.py", ]) blacklist = convert_to_native_paths(blacklist) return blacklist def _doctest(*paths, **kwargs): """ Internal function that actually runs the doctests. All keyword arguments from ``doctest()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstrings of ``doctest()`` and ``test()`` for more information. """ from sympy.printing.pretty.pretty import pprint_use_unicode normal = kwargs.get("normal", False) verbose = kwargs.get("verbose", False) colors = kwargs.get("colors", True) force_colors = kwargs.get("force_colors", False) blacklist = kwargs.get("blacklist", []) split = kwargs.get('split', None) blacklist.extend(_get_doctest_blacklist()) # Use a non-windowed backend, so that the tests work on Travis if import_module('matplotlib') is not None: import matplotlib matplotlib.use('Agg') # Disable warnings for external modules import sympy.external sympy.external.importtools.WARN_OLD_VERSION = False sympy.external.importtools.WARN_NOT_INSTALLED = False # Disable showing up of plots from sympy.plotting.plot import unset_show unset_show() r = PyTestReporter(verbose, split=split, colors=colors,\ force_colors=force_colors) t = SymPyDocTests(r, normal) test_files = t.get_test_files('sympy') test_files.extend(t.get_test_files('examples', init_only=False)) not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # take only what was requested...but not blacklisted items # and allow for partial match anywhere or fnmatch of name paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break matched.sort() if split: matched = split_list(matched, split) t._testfiles.extend(matched) # run the tests and record the result for this *py portion of the tests if t._testfiles: failed = not t.test() else: failed = False # N.B. # -------------------------------------------------------------------- # Here we test *.rst and *.md files at or below doc/src. Code from these # must be self supporting in terms of imports since there is no importing # of necessary modules by doctest.testfile. If you try to pass *.py files # through this they might fail because they will lack the needed imports # and smarter parsing that can be done with source code. # test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False) test_files_md = t.get_test_files('doc/src', '*.md', init_only=False) test_files = test_files_rst + test_files_md test_files.sort() not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # Take only what was requested as long as it's not on the blacklist. # Paths were already made native in *py tests so don't repeat here. # There's no chance of having a *py file slip through since we # only have *rst files in test_files. matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break if split: matched = split_list(matched, split) first_report = True for rst_file in matched: if not os.path.isfile(rst_file): continue old_displayhook = sys.displayhook try: use_unicode_prev = setup_pprint() out = sympytestfile( rst_file, module_relative=False, encoding='utf-8', optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) finally: # make sure we return to the original displayhook in case some # doctest has changed that sys.displayhook = old_displayhook # The NO_GLOBAL flag overrides the no_global flag to init_printing # if True import sympy.interactive.printing as interactive_printing interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) rstfailed, tested = out if tested: failed = rstfailed or failed if first_report: first_report = False msg = 'rst/md doctests start' if not t._testfiles: r.start(msg=msg) else: r.write_center(msg) print() # use as the id, everything past the first 'sympy' file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:] print(file_id, end=" ") # get at least the name out so it is know who is being tested wid = r.terminal_width - len(file_id) - 1 # update width test_file = '[%s]' % (tested) report = '[%s]' % (rstfailed or 'OK') print(''.join( [test_file, ' '*(wid - len(test_file) - len(report)), report]) ) # the doctests for *py will have printed this message already if there was # a failure, so now only print it if there was intervening reporting by # testing the *rst as evidenced by first_report no longer being True. if not first_report and failed: print() print("DO *NOT* COMMIT!") return int(failed) sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') def split_list(l, split, density=None): """ Splits a list into part a of b split should be a string of the form 'a/b'. For instance, '1/3' would give the split one of three. If the length of the list is not divisible by the number of splits, the last split will have more items. `density` may be specified as a list. If specified, tests will be balanced so that each split has as equal-as-possible amount of mass according to `density`. >>> from sympy.testing.runtests import split_list >>> a = list(range(10)) >>> split_list(a, '1/3') [0, 1, 2] >>> split_list(a, '2/3') [3, 4, 5] >>> split_list(a, '3/3') [6, 7, 8, 9] """ m = sp.match(split) if not m: raise ValueError("split must be a string of the form a/b where a and b are ints") i, t = map(int, m.groups()) if not density: return l[(i - 1)*len(l)//t : i*len(l)//t] # normalize density tot = sum(density) density = [x / tot for x in density] def density_inv(x): """Interpolate the inverse to the cumulative distribution function given by density""" if x <= 0: return 0 if x >= sum(density): return 1 # find the first time the cumulative sum surpasses x # and linearly interpolate cumm = 0 for i, d in enumerate(density): cumm += d if cumm >= x: break frac = (d - (cumm - x)) / d return (i + frac) / len(density) lower_frac = density_inv((i - 1) / t) higher_frac = density_inv(i / t) return l[int(lower_frac*len(l)) : int(higher_frac*len(l))] from collections import namedtuple SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted') def sympytestfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=pdoctest.DocTestParser(), encoding=None): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg ``module_relative`` specifies how filenames should be interpreted: - If ``module_relative`` is True (the default), then ``filename`` specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the ``package`` argument is specified, then it is relative to that package. To ensure os-independence, ``filename`` should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If ``module_relative`` is False, then ``filename`` specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg ``name`` gives the name of the test; by default use the file's basename. Optional keyword argument ``package`` is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify ``package`` if ``module_relative`` is False. Optional keyword arg ``globs`` gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg ``extraglobs`` gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg ``verbose`` prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg ``report`` prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg ``optionflags`` or's together module constants, and defaults to 0. Possible values (see the docs for details): - DONT_ACCEPT_TRUE_FOR_1 - DONT_ACCEPT_BLANKLINE - NORMALIZE_WHITESPACE - ELLIPSIS - SKIP - IGNORE_EXCEPTION_DETAIL - REPORT_UDIFF - REPORT_CDIFF - REPORT_NDIFF - REPORT_ONLY_FIRST_FAILURE Optional keyword arg ``raise_on_error`` raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg ``parser`` specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Optional keyword arg ``encoding`` specifies an encoding that should be used to convert the file to unicode. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path text, filename = pdoctest._load_testfile( filename, package, module_relative, encoding) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' if raise_on_error: runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags) runner._checker = SymPyOutputChecker() # Read the file, convert it to a test, and run it. test = parser.get_doctest(text, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if pdoctest.master is None: pdoctest.master = runner else: pdoctest.master.merge(runner) return SymPyTestResults(runner.failures, runner.tries) class SymPyTests: def __init__(self, reporter, kw="", post_mortem=False, seed=None, fast_threshold=None, slow_threshold=None): self._post_mortem = post_mortem self._kw = kw self._count = 0 self._root_dir = get_sympy_dir() self._reporter = reporter self._reporter.root_dir(self._root_dir) self._testfiles = [] self._seed = seed if seed is not None else random.random() # Defaults in seconds, from human / UX design limits # http://www.nngroup.com/articles/response-times-3-important-limits/ # # These defaults are *NOT* set in stone as we are measuring different # things, so others feel free to come up with a better yardstick :) if fast_threshold: self._fast_threshold = float(fast_threshold) else: self._fast_threshold = 8 if slow_threshold: self._slow_threshold = float(slow_threshold) else: self._slow_threshold = 10 def test(self, sort=False, timeout=False, slow=False, enhance_asserts=False, fail_on_timeout=False): """ Runs the tests returning True if all tests pass, otherwise False. If sort=False run tests in random order. """ if sort: self._testfiles.sort() elif slow: pass else: random.seed(self._seed) random.shuffle(self._testfiles) self._reporter.start(self._seed) for f in self._testfiles: try: self.test_file(f, sort, timeout, slow, enhance_asserts, fail_on_timeout) except KeyboardInterrupt: print(" interrupted by user") self._reporter.finish() raise return self._reporter.finish() def _enhance_asserts(self, source): from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple, Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations) ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=', "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not', "In": 'in', "NotIn": 'not in'} class Transform(NodeTransformer): def visit_Assert(self, stmt): if isinstance(stmt.test, Compare): compare = stmt.test values = [compare.left] + compare.comparators names = [ "_%s" % i for i, _ in enumerate(values) ] names_store = [ Name(n, Store()) for n in names ] names_load = [ Name(n, Load()) for n in names ] target = Tuple(names_store, Store()) value = Tuple(values, Load()) assign = Assign([target], value) new_compare = Compare(names_load[0], compare.ops, names_load[1:]) msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s" msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load())) test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset) return [assign, test] else: return stmt tree = parse(source) new_tree = Transform().visit(tree) return fix_missing_locations(new_tree) def test_file(self, filename, sort=True, timeout=False, slow=False, enhance_asserts=False, fail_on_timeout=False): reporter = self._reporter funcs = [] try: gl = {'__file__': filename} try: open_file = lambda: open(filename, encoding="utf8") with open_file() as f: source = f.read() if self._kw: for l in source.splitlines(): if l.lstrip().startswith('def '): if any(l.lower().find(k.lower()) != -1 for k in self._kw): break else: return if enhance_asserts: try: source = self._enhance_asserts(source) except ImportError: pass code = compile(source, filename, "exec", flags=0, dont_inherit=True) exec(code, gl) except (SystemExit, KeyboardInterrupt): raise except ImportError: reporter.import_error(filename, sys.exc_info()) return except Exception: reporter.test_exception(sys.exc_info()) clear_cache() self._count += 1 random.seed(self._seed) disabled = gl.get("disabled", False) if not disabled: # we need to filter only those functions that begin with 'test_' # We have to be careful about decorated functions. As long as # the decorator uses functools.wraps, we can detect it. funcs = [] for f in gl: if (f.startswith("test_") and (inspect.isfunction(gl[f]) or inspect.ismethod(gl[f]))): func = gl[f] # Handle multiple decorators while hasattr(func, '__wrapped__'): func = func.__wrapped__ if inspect.getsourcefile(func) == filename: funcs.append(gl[f]) if slow: funcs = [f for f in funcs if getattr(f, '_slow', False)] # Sorting of XFAILed functions isn't fixed yet :-( funcs.sort(key=lambda x: inspect.getsourcelines(x)[1]) i = 0 while i < len(funcs): if inspect.isgeneratorfunction(funcs[i]): # some tests can be generators, that return the actual # test functions. We unpack it below: f = funcs.pop(i) for fg in f(): func = fg[0] args = fg[1:] fgw = lambda: func(*args) funcs.insert(i, fgw) i += 1 else: i += 1 # drop functions that are not selected with the keyword expression: funcs = [x for x in funcs if self.matches(x)] if not funcs: return except Exception: reporter.entering_filename(filename, len(funcs)) raise reporter.entering_filename(filename, len(funcs)) if not sort: random.shuffle(funcs) for f in funcs: start = time.time() reporter.entering_test(f) try: if getattr(f, '_slow', False) and not slow: raise Skipped("Slow") with raise_on_deprecated(): if timeout: self._timeout(f, timeout, fail_on_timeout) else: random.seed(self._seed) f() except KeyboardInterrupt: if getattr(f, '_slow', False): reporter.test_skip("KeyboardInterrupt") else: raise except Exception: if timeout: signal.alarm(0) # Disable the alarm. It could not be handled before. t, v, tr = sys.exc_info() if t is AssertionError: reporter.test_fail((t, v, tr)) if self._post_mortem: pdb.post_mortem(tr) elif t.__name__ == "Skipped": reporter.test_skip(v) elif t.__name__ == "XFail": reporter.test_xfail() elif t.__name__ == "XPass": reporter.test_xpass(v) else: reporter.test_exception((t, v, tr)) if self._post_mortem: pdb.post_mortem(tr) else: reporter.test_pass() taken = time.time() - start if taken > self._slow_threshold: filename = os.path.relpath(filename, reporter._root_dir) reporter.slow_test_functions.append( (filename + "::" + f.__name__, taken)) if getattr(f, '_slow', False) and slow: if taken < self._fast_threshold: filename = os.path.relpath(filename, reporter._root_dir) reporter.fast_test_functions.append( (filename + "::" + f.__name__, taken)) reporter.leaving_filename() def _timeout(self, function, timeout, fail_on_timeout): def callback(x, y): signal.alarm(0) if fail_on_timeout: raise TimeOutError("Timed out after %d seconds" % timeout) else: raise Skipped("Timeout") signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) # Set an alarm with a given timeout function() signal.alarm(0) # Disable the alarm def matches(self, x): """ Does the keyword expression self._kw match "x"? Returns True/False. Always returns True if self._kw is "". """ if not self._kw: return True for kw in self._kw: if x.__name__.lower().find(kw.lower()) != -1: return True return False def get_test_files(self, dir, pat='test_*.py'): """ Returns the list of test_*.py (default) files at or below directory ``dir`` relative to the SymPy home directory. """ dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) g = [] for path, folders, files in os.walk(dir): g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)]) return sorted([os.path.normcase(gi) for gi in g]) class SymPyDocTests: def __init__(self, reporter, normal): self._count = 0 self._root_dir = get_sympy_dir() self._reporter = reporter self._reporter.root_dir(self._root_dir) self._normal = normal self._testfiles = [] def test(self): """ Runs the tests and returns True if all tests pass, otherwise False. """ self._reporter.start() for f in self._testfiles: try: self.test_file(f) except KeyboardInterrupt: print(" interrupted by user") self._reporter.finish() raise return self._reporter.finish() def test_file(self, filename): clear_cache() from io import StringIO import sympy.interactive.printing as interactive_printing from sympy.printing.pretty.pretty import pprint_use_unicode rel_name = filename[len(self._root_dir) + 1:] dirname, file = os.path.split(filename) module = rel_name.replace(os.sep, '.')[:-3] if rel_name.startswith("examples"): # Examples files do not have __init__.py files, # So we have to temporarily extend sys.path to import them sys.path.insert(0, dirname) module = file[:-3] # remove ".py" try: module = pdoctest._normalize_module(module) tests = SymPyDocTestFinder().find(module) except (SystemExit, KeyboardInterrupt): raise except ImportError: self._reporter.import_error(filename, sys.exc_info()) return finally: if rel_name.startswith("examples"): del sys.path[0] tests = [test for test in tests if len(test.examples) > 0] # By default tests are sorted by alphabetical order by function name. # We sort by line number so one can edit the file sequentially from # bottom to top. However, if there are decorated functions, their line # numbers will be too large and for now one must just search for these # by text and function name. tests.sort(key=lambda x: -x.lineno) if not tests: return self._reporter.entering_filename(filename, len(tests)) for test in tests: assert len(test.examples) != 0 if self._reporter._verbose: self._reporter.write("\n{} ".format(test.name)) # check if there are external dependencies which need to be met if '_doctest_depends_on' in test.globs: try: self._check_dependencies(**test.globs['_doctest_depends_on']) except DependencyError as e: self._reporter.test_skip(v=str(e)) continue runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) runner._checker = SymPyOutputChecker() old = sys.stdout new = StringIO() sys.stdout = new # If the testing is normal, the doctests get importing magic to # provide the global namespace. If not normal (the default) then # then must run on their own; all imports must be explicit within # a function's docstring. Once imported that import will be # available to the rest of the tests in a given function's # docstring (unless clear_globs=True below). if not self._normal: test.globs = {} # if this is uncommented then all the test would get is what # comes by default with a "from sympy import *" #exec('from sympy import *') in test.globs old_displayhook = sys.displayhook use_unicode_prev = setup_pprint() try: f, t = runner.run(test, out=new.write, clear_globs=False) except KeyboardInterrupt: raise finally: sys.stdout = old if f > 0: self._reporter.doctest_fail(test.name, new.getvalue()) else: self._reporter.test_pass() sys.displayhook = old_displayhook interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) self._reporter.leaving_filename() def get_test_files(self, dir, pat='*.py', init_only=True): r""" Returns the list of \*.py files (default) from which docstrings will be tested which are at or below directory ``dir``. By default, only those that have an __init__.py in their parent directory and do not start with ``test_`` will be included. """ def importable(x): """ Checks if given pathname x is an importable module by checking for __init__.py file. Returns True/False. Currently we only test if the __init__.py file exists in the directory with the file "x" (in theory we should also test all the parent dirs). """ init_py = os.path.join(os.path.dirname(x), "__init__.py") return os.path.exists(init_py) dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) g = [] for path, folders, files in os.walk(dir): g.extend([os.path.join(path, f) for f in files if not f.startswith('test_') and fnmatch(f, pat)]) if init_only: # skip files that are not importable (i.e. missing __init__.py) g = [x for x in g if importable(x)] return [os.path.normcase(gi) for gi in g] def _check_dependencies(self, executables=(), modules=(), disable_viewers=(), python_version=(3, 5)): """ Checks if the dependencies for the test are installed. Raises ``DependencyError`` it at least one dependency is not installed. """ for executable in executables: if not shutil.which(executable): raise DependencyError("Could not find %s" % executable) for module in modules: if module == 'matplotlib': matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']}, min_module_version='1.0.0', catch=(RuntimeError,)) if matplotlib is None: raise DependencyError("Could not import matplotlib") else: if not import_module(module): raise DependencyError("Could not import %s" % module) if disable_viewers: tempdir = tempfile.mkdtemp() os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH']) vw = ('#!/usr/bin/env python3\n' 'import sys\n' 'if len(sys.argv) <= 1:\n' ' exit("wrong number of args")\n') for viewer in disable_viewers: with open(os.path.join(tempdir, viewer), 'w') as fh: fh.write(vw) # make the file executable os.chmod(os.path.join(tempdir, viewer), stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR) if python_version: if sys.version_info < python_version: raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version))) if 'pyglet' in modules: # monkey-patch pyglet s.t. it does not open a window during # doctesting import pyglet class DummyWindow: def __init__(self, *args, **kwargs): self.has_exit = True self.width = 600 self.height = 400 def set_vsync(self, x): pass def switch_to(self): pass def push_handlers(self, x): pass def close(self): pass pyglet.window.Window = DummyWindow class SymPyDocTestFinder(DocTestFinder): """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. Modified from doctest's version to look harder for code that appears comes from a different module. For example, the @vectorize decorator makes it look like functions come from multidimensional.py even though their code exists elsewhere. """ def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to ``tests``. """ if self._verbose: print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Make sure we don't run doctests for classes outside of sympy, such # as in numpy or scipy. if inspect.isclass(obj): if obj.__module__.split('.')[0] != 'sympy': return # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) if not self._recurse: return # Look for tests in a module's contained objects. if inspect.ismodule(obj): for rawname, val in obj.__dict__.items(): # Recurse to functions & classes. if inspect.isfunction(val) or inspect.isclass(val): # Make sure we don't run doctests functions or classes # from different modules if val.__module__ != module.__name__: continue assert self._from_module(module, val), \ "%s is not in module %s (rawname %s)" % (val, module, rawname) try: valname = '%s.%s' % (name, rawname) self._find(tests, val, valname, module, source_lines, globs, seen) except KeyboardInterrupt: raise # Look for tests in a module's __test__ dictionary. for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, str): raise ValueError("SymPyDocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, str)): raise ValueError("SymPyDocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj): for valname, val in obj.__dict__.items(): # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).__func__ # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(unwrap(val)) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): # Make sure we don't run doctests functions or classes # from different modules if isinstance(val, property): if hasattr(val.fget, '__module__'): if val.fget.__module__ != module.__name__: continue else: if val.__module__ != module.__name__: continue assert self._from_module(module, val), \ "%s is not in module %s (valname %s)" % ( val, module, valname) valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ lineno = None # Extract the object's docstring. If it does not have one, # then return None (no test for this object). if isinstance(obj, str): # obj is a string in the case for objects in the polys package. # Note that source_lines is a binary string (compiled polys # modules), which can't be handled by _find_lineno so determine # the line number here. docstring = obj matches = re.findall(r"line \d+", name) assert len(matches) == 1, \ "string '%s' does not contain lineno " % name # NOTE: this is not the exact linenumber but its better than no # lineno ;) lineno = int(matches[0][5:]) else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, str): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # check that properties have a docstring because _find_lineno # assumes it if isinstance(obj, property): if obj.fget.__doc__ is None: return None # Find the docstring's location in the file. if lineno is None: obj = unwrap(obj) # handling of properties is not implemented in _find_lineno so do # it here if hasattr(obj, 'func_closure') and obj.func_closure is not None: tobj = obj.func_closure[0].cell_contents elif isinstance(obj, property): tobj = obj.fget else: tobj = obj lineno = self._find_lineno(tobj, source_lines) if lineno is None: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {}) return self._parser.get_doctest(docstring, globs, name, filename, lineno) class SymPyDocTestRunner(DocTestRunner): """ A class used to run DocTest test cases, and accumulate statistics. The ``run`` method is used to process a single DocTest case. It returns a tuple ``(f, t)``, where ``t`` is the number of test cases tried, and ``f`` is the number of test cases that failed. Modified from the doctest version to not reset the sys.displayhook (see issue 5140). See the docstring of the original DocTestRunner for more information. """ def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in ``test``, and display the results using the writer function ``out``. The examples are run in the namespace ``test.globs``. If ``clear_globs`` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use ``clear_globs=False``. ``compileflags`` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to ``globs``. The output of each example is checked using ``SymPyDocTestRunner.check_output``, and the results are formatted by the ``SymPyDocTestRunner.report_*`` methods. """ self.test = test # Remove ``` from the end of example, which may appear in Markdown # files for example in test.examples: example.want = example.want.replace('```\n', '') example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '') if compileflags is None: compileflags = pdoctest._extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: out = save_stdout.write sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_set_trace = pdb.set_trace self.debugger = pdoctest._OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = pdoctest.linecache.getlines linecache.getlines = self.__patched_linecache_getlines # Fail for deprecation warnings with raise_on_deprecated(): try: return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace linecache.getlines = self.save_linecache_getlines if clear_globs: test.globs.clear() # We have to override the name mangled methods. monkeypatched_methods = [ 'patched_linecache_getlines', 'run', 'record_outcome' ] for method in monkeypatched_methods: oldname = '_DocTestRunner__' + method newname = '_SymPyDocTestRunner__' + method setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname)) class SymPyOutputChecker(pdoctest.OutputChecker): """ Compared to the OutputChecker from the stdlib our OutputChecker class supports numerical comparison of floats occurring in the output of the doctest examples """ def __init__(self): # NOTE OutputChecker is an old-style class with no __init__ method, # so we can't call the base class version of __init__ here got_floats = r'(\d+\.\d*|\.\d+)' # floats in the 'want' string may contain ellipses want_floats = got_floats + r'(\.{3})?' front_sep = r'\s|\+|\-|\*|,' back_sep = front_sep + r'|j|e' fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep) fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep) self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep) fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep) self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # TODO parse integers as well ? # Parse floats and compare them. If some of the parsed floats contain # ellipses, skip the comparison. matches = self.num_got_rgx.finditer(got) numbers_got = [match.group(1) for match in matches] # list of strs matches = self.num_want_rgx.finditer(want) numbers_want = [match.group(1) for match in matches] # list of strs if len(numbers_got) != len(numbers_want): return False if len(numbers_got) > 0: nw_ = [] for ng, nw in zip(numbers_got, numbers_want): if '...' in nw: nw_.append(ng) continue else: nw_.append(nw) if abs(float(ng)-float(nw)) > 1e-5: return False got = self.num_got_rgx.sub(r'%s', got) got = got % tuple(nw_) # <BLANKLINE> can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE): # Replace <BLANKLINE> in want with a blank line. want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub(r'(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & pdoctest.NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & pdoctest.ELLIPSIS: if pdoctest._ellipsis_match(want, got): return True # We didn't find any match; return false. return False class Reporter: """ Parent class for all reporters. """ pass class PyTestReporter(Reporter): """ Py.test like reporter. Should produce output identical to py.test. """ def __init__(self, verbose=False, tb="short", colors=True, force_colors=False, split=None): self._verbose = verbose self._tb_style = tb self._colors = colors self._force_colors = force_colors self._xfailed = 0 self._xpassed = [] self._failed = [] self._failed_doctest = [] self._passed = 0 self._skipped = 0 self._exceptions = [] self._terminal_width = None self._default_width = 80 self._split = split self._active_file = '' self._active_f = None # TODO: Should these be protected? self.slow_test_functions = [] self.fast_test_functions = [] # this tracks the x-position of the cursor (useful for positioning # things on the screen), without the need for any readline library: self._write_pos = 0 self._line_wrap = False def root_dir(self, dir): self._root_dir = dir @property def terminal_width(self): if self._terminal_width is not None: return self._terminal_width def findout_terminal_width(): if sys.platform == "win32": # Windows support is based on: # # http://code.activestate.com/recipes/ # 440694-determine-size-of-console-window-on-windows/ from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (_, _, _, _, _, left, _, right, _, _, _) = \ struct.unpack("hhhhHhhhhhh", csbi.raw) return right - left else: return self._default_width if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty(): return self._default_width # leave PIPEs alone try: process = subprocess.Popen(['stty', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = process.stdout.read() stdout = stdout.decode("utf-8") except OSError: pass else: # We support the following output formats from stty: # # 1) Linux -> columns 80 # 2) OS X -> 80 columns # 3) Solaris -> columns = 80 re_linux = r"columns\s+(?P<columns>\d+);" re_osx = r"(?P<columns>\d+)\s*columns;" re_solaris = r"columns\s+=\s+(?P<columns>\d+);" for regex in (re_linux, re_osx, re_solaris): match = re.search(regex, stdout) if match is not None: columns = match.group('columns') try: width = int(columns) except ValueError: pass if width != 0: return width return self._default_width width = findout_terminal_width() self._terminal_width = width return width def write(self, text, color="", align="left", width=None, force_colors=False): """ Prints a text on the screen. It uses sys.stdout.write(), so no readline library is necessary. Parameters ========== color : choose from the colors below, "" means default color align : "left"/"right", "left" is a normal print, "right" is aligned on the right-hand side of the screen, filled with spaces if necessary width : the screen width """ color_templates = ( ("Black", "0;30"), ("Red", "0;31"), ("Green", "0;32"), ("Brown", "0;33"), ("Blue", "0;34"), ("Purple", "0;35"), ("Cyan", "0;36"), ("LightGray", "0;37"), ("DarkGray", "1;30"), ("LightRed", "1;31"), ("LightGreen", "1;32"), ("Yellow", "1;33"), ("LightBlue", "1;34"), ("LightPurple", "1;35"), ("LightCyan", "1;36"), ("White", "1;37"), ) colors = {} for name, value in color_templates: colors[name] = value c_normal = '\033[0m' c_color = '\033[%sm' if width is None: width = self.terminal_width if align == "right": if self._write_pos + len(text) > width: # we don't fit on the current line, create a new line self.write("\n") self.write(" "*(width - self._write_pos - len(text))) if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \ sys.stdout.isatty(): # the stdout is not a terminal, this for example happens if the # output is piped to less, e.g. "bin/test | less". In this case, # the terminal control sequences would be printed verbatim, so # don't use any colors. color = "" elif sys.platform == "win32": # Windows consoles don't support ANSI escape sequences color = "" elif not self._colors: color = "" if self._line_wrap: if text[0] != "\n": sys.stdout.write("\n") # Avoid UnicodeEncodeError when printing out test failures if IS_WINDOWS: text = text.encode('raw_unicode_escape').decode('utf8', 'ignore') elif not sys.stdout.encoding.lower().startswith('utf'): text = text.encode(sys.stdout.encoding, 'backslashreplace' ).decode(sys.stdout.encoding) if color == "": sys.stdout.write(text) else: sys.stdout.write("%s%s%s" % (c_color % colors[color], text, c_normal)) sys.stdout.flush() l = text.rfind("\n") if l == -1: self._write_pos += len(text) else: self._write_pos = len(text) - l - 1 self._line_wrap = self._write_pos >= width self._write_pos %= width def write_center(self, text, delim="="): width = self.terminal_width if text != "": text = " %s " % text idx = (width - len(text)) // 2 t = delim*idx + text + delim*(width - idx - len(text)) self.write(t + "\n") def write_exception(self, e, val, tb): # remove the first item, as that is always runtests.py tb = tb.tb_next t = traceback.format_exception(e, val, tb) self.write("".join(t)) def start(self, seed=None, msg="test process starts"): self.write_center(msg) executable = sys.executable v = tuple(sys.version_info) python_version = "%s.%s.%s-%s-%s" % v implementation = platform.python_implementation() if implementation == 'PyPy': implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info self.write("executable: %s (%s) [%s]\n" % (executable, python_version, implementation)) from sympy.utilities.misc import ARCH self.write("architecture: %s\n" % ARCH) from sympy.core.cache import USE_CACHE self.write("cache: %s\n" % USE_CACHE) version = '' if GROUND_TYPES =='gmpy': if HAS_GMPY == 1: import gmpy elif HAS_GMPY == 2: import gmpy2 as gmpy version = gmpy.version() self.write("ground types: %s %s\n" % (GROUND_TYPES, version)) numpy = import_module('numpy') self.write("numpy: %s\n" % (None if not numpy else numpy.__version__)) if seed is not None: self.write("random seed: %d\n" % seed) from sympy.utilities.misc import HASH_RANDOMIZATION self.write("hash randomization: ") hash_seed = os.getenv("PYTHONHASHSEED") or '0' if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)): self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed) else: self.write("off\n") if self._split: self.write("split: %s\n" % self._split) self.write('\n') self._t_start = clock() def finish(self): self._t_end = clock() self.write("\n") global text, linelen text = "tests finished: %d passed, " % self._passed linelen = len(text) def add_text(mytext): global text, linelen """Break new text if too long.""" if linelen + len(mytext) > self.terminal_width: text += '\n' linelen = 0 text += mytext linelen += len(mytext) if len(self._failed) > 0: add_text("%d failed, " % len(self._failed)) if len(self._failed_doctest) > 0: add_text("%d failed, " % len(self._failed_doctest)) if self._skipped > 0: add_text("%d skipped, " % self._skipped) if self._xfailed > 0: add_text("%d expected to fail, " % self._xfailed) if len(self._xpassed) > 0: add_text("%d expected to fail but passed, " % len(self._xpassed)) if len(self._exceptions) > 0: add_text("%d exceptions, " % len(self._exceptions)) add_text("in %.2f seconds" % (self._t_end - self._t_start)) if self.slow_test_functions: self.write_center('slowest tests', '_') sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1]) for slow_func_name, taken in sorted_slow: print('%s - Took %.3f seconds' % (slow_func_name, taken)) if self.fast_test_functions: self.write_center('unexpectedly fast tests', '_') sorted_fast = sorted(self.fast_test_functions, key=lambda r: r[1]) for fast_func_name, taken in sorted_fast: print('%s - Took %.3f seconds' % (fast_func_name, taken)) if len(self._xpassed) > 0: self.write_center("xpassed tests", "_") for e in self._xpassed: self.write("%s: %s\n" % (e[0], e[1])) self.write("\n") if self._tb_style != "no" and len(self._exceptions) > 0: for e in self._exceptions: filename, f, (t, val, tb) = e self.write_center("", "_") if f is None: s = "%s" % filename else: s = "%s:%s" % (filename, f.__name__) self.write_center(s, "_") self.write_exception(t, val, tb) self.write("\n") if self._tb_style != "no" and len(self._failed) > 0: for e in self._failed: filename, f, (t, val, tb) = e self.write_center("", "_") self.write_center("%s:%s" % (filename, f.__name__), "_") self.write_exception(t, val, tb) self.write("\n") if self._tb_style != "no" and len(self._failed_doctest) > 0: for e in self._failed_doctest: filename, msg = e self.write_center("", "_") self.write_center("%s" % filename, "_") self.write(msg) self.write("\n") self.write_center(text) ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \ len(self._failed_doctest) == 0 if not ok: self.write("DO *NOT* COMMIT!\n") return ok def entering_filename(self, filename, n): rel_name = filename[len(self._root_dir) + 1:] self._active_file = rel_name self._active_file_error = False self.write(rel_name) self.write("[%d] " % n) def leaving_filename(self): self.write(" ") if self._active_file_error: self.write("[FAIL]", "Red", align="right") else: self.write("[OK]", "Green", align="right") self.write("\n") if self._verbose: self.write("\n") def entering_test(self, f): self._active_f = f if self._verbose: self.write("\n" + f.__name__ + " ") def test_xfail(self): self._xfailed += 1 self.write("f", "Green") def test_xpass(self, v): message = str(v) self._xpassed.append((self._active_file, message)) self.write("X", "Green") def test_fail(self, exc_info): self._failed.append((self._active_file, self._active_f, exc_info)) self.write("F", "Red") self._active_file_error = True def doctest_fail(self, name, error_msg): # the first line contains "******", remove it: error_msg = "\n".join(error_msg.split("\n")[1:]) self._failed_doctest.append((name, error_msg)) self.write("F", "Red") self._active_file_error = True def test_pass(self, char="."): self._passed += 1 if self._verbose: self.write("ok", "Green") else: self.write(char, "Green") def test_skip(self, v=None): char = "s" self._skipped += 1 if v is not None: message = str(v) if message == "KeyboardInterrupt": char = "K" elif message == "Timeout": char = "T" elif message == "Slow": char = "w" if self._verbose: if v is not None: self.write(message + ' ', "Blue") else: self.write(" - ", "Blue") self.write(char, "Blue") def test_exception(self, exc_info): self._exceptions.append((self._active_file, self._active_f, exc_info)) if exc_info[0] is TimeOutError: self.write("T", "Red") else: self.write("E", "Red") self._active_file_error = True def import_error(self, filename, exc_info): self._exceptions.append((filename, None, exc_info)) rel_name = filename[len(self._root_dir) + 1:] self.write(rel_name) self.write("[?] Failed to import", "Red") self.write(" ") self.write("[FAIL]", "Red", align="right") self.write("\n")
20a0c5026f1bef66753a44fbbe9827663696e4bb1253fc1fea0df9b0292af48d
""" .. deprecated:: 1.10 ``sympy.testing.randtest`` functions have been moved to :mod:`sympy.core.random`. """ from sympy.utilities.exceptions import sympy_deprecation_warning sympy_deprecation_warning("The sympy.testing.randtest submodule is deprecated. Use sympy.core.random instead.", deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-testing-randtest") from sympy.core.random import ( # noqa:F401 random_complex_number, verify_numerically, test_derivative_numerically, _randrange, _randint)
3b394007ab2cf7d7511c50c0dd0adaf1afa6175609e92b0dec0c263a386fa8df
from collections.abc import Callable from sympy.core.basic import Basic from sympy.core.cache import cacheit from sympy.core import S, Dummy, Lambda from sympy.core.symbol import Str from sympy.core.symbol import symbols from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.matrices.matrices import MatrixBase from sympy.solvers import solve from sympy.vector.scalar import BaseScalar from sympy.core.containers import Tuple from sympy.core.function import diff from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin) from sympy.matrices.dense import eye from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.simplify.simplify import simplify from sympy.simplify.trigsimp import trigsimp import sympy.vector from sympy.vector.orienters import (Orienter, AxisOrienter, BodyOrienter, SpaceOrienter, QuaternionOrienter) class CoordSys3D(Basic): """ Represents a coordinate system in 3-D space. """ def __new__(cls, name, transformation=None, parent=None, location=None, rotation_matrix=None, vector_names=None, variable_names=None): """ The orientation/location parameters are necessary if this system is being defined at a certain orientation or location wrt another. Parameters ========== name : str The name of the new CoordSys3D instance. transformation : Lambda, Tuple, str Transformation defined by transformation equations or chosen from predefined ones. location : Vector The position vector of the new system's origin wrt the parent instance. rotation_matrix : SymPy ImmutableMatrix The rotation matrix of the new coordinate system with respect to the parent. In other words, the output of new_system.rotation_matrix(parent). parent : CoordSys3D The coordinate system wrt which the orientation/location (or both) is being defined. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. """ name = str(name) Vector = sympy.vector.Vector Point = sympy.vector.Point if not isinstance(name, str): raise TypeError("name should be a string") if transformation is not None: if (location is not None) or (rotation_matrix is not None): raise ValueError("specify either `transformation` or " "`location`/`rotation_matrix`") if isinstance(transformation, (Tuple, tuple, list)): if isinstance(transformation[0], MatrixBase): rotation_matrix = transformation[0] location = transformation[1] else: transformation = Lambda(transformation[0], transformation[1]) elif isinstance(transformation, Callable): x1, x2, x3 = symbols('x1 x2 x3', cls=Dummy) transformation = Lambda((x1, x2, x3), transformation(x1, x2, x3)) elif isinstance(transformation, str): transformation = Str(transformation) elif isinstance(transformation, (Str, Lambda)): pass else: raise TypeError("transformation: " "wrong type {}".format(type(transformation))) # If orientation information has been provided, store # the rotation matrix accordingly if rotation_matrix is None: rotation_matrix = ImmutableDenseMatrix(eye(3)) else: if not isinstance(rotation_matrix, MatrixBase): raise TypeError("rotation_matrix should be an Immutable" + "Matrix instance") rotation_matrix = rotation_matrix.as_immutable() # If location information is not given, adjust the default # location as Vector.zero if parent is not None: if not isinstance(parent, CoordSys3D): raise TypeError("parent should be a " + "CoordSys3D/None") if location is None: location = Vector.zero else: if not isinstance(location, Vector): raise TypeError("location should be a Vector") # Check that location does not contain base # scalars for x in location.free_symbols: if isinstance(x, BaseScalar): raise ValueError("location should not contain" + " BaseScalars") origin = parent.origin.locate_new(name + '.origin', location) else: location = Vector.zero origin = Point(name + '.origin') if transformation is None: transformation = Tuple(rotation_matrix, location) if isinstance(transformation, Tuple): lambda_transformation = CoordSys3D._compose_rotation_and_translation( transformation[0], transformation[1], parent ) r, l = transformation l = l._projections lambda_lame = CoordSys3D._get_lame_coeff('cartesian') lambda_inverse = lambda x, y, z: r.inv()*Matrix( [x-l[0], y-l[1], z-l[2]]) elif isinstance(transformation, Str): trname = transformation.name lambda_transformation = CoordSys3D._get_transformation_lambdas(trname) if parent is not None: if parent.lame_coefficients() != (S.One, S.One, S.One): raise ValueError('Parent for pre-defined coordinate ' 'system should be Cartesian.') lambda_lame = CoordSys3D._get_lame_coeff(trname) lambda_inverse = CoordSys3D._set_inv_trans_equations(trname) elif isinstance(transformation, Lambda): if not CoordSys3D._check_orthogonality(transformation): raise ValueError("The transformation equation does not " "create orthogonal coordinate system") lambda_transformation = transformation lambda_lame = CoordSys3D._calculate_lame_coeff(lambda_transformation) lambda_inverse = None else: lambda_transformation = lambda x, y, z: transformation(x, y, z) lambda_lame = CoordSys3D._get_lame_coeff(transformation) lambda_inverse = None if variable_names is None: if isinstance(transformation, Lambda): variable_names = ["x1", "x2", "x3"] elif isinstance(transformation, Str): if transformation.name == 'spherical': variable_names = ["r", "theta", "phi"] elif transformation.name == 'cylindrical': variable_names = ["r", "theta", "z"] else: variable_names = ["x", "y", "z"] else: variable_names = ["x", "y", "z"] if vector_names is None: vector_names = ["i", "j", "k"] # All systems that are defined as 'roots' are unequal, unless # they have the same name. # Systems defined at same orientation/position wrt the same # 'parent' are equal, irrespective of the name. # This is true even if the same orientation is provided via # different methods like Axis/Body/Space/Quaternion. # However, coincident systems may be seen as unequal if # positioned/oriented wrt different parents, even though # they may actually be 'coincident' wrt the root system. if parent is not None: obj = super().__new__( cls, Str(name), transformation, parent) else: obj = super().__new__( cls, Str(name), transformation) obj._name = name # Initialize the base vectors _check_strings('vector_names', vector_names) vector_names = list(vector_names) latex_vects = [(r'\mathbf{\hat{%s}_{%s}}' % (x, name)) for x in vector_names] pretty_vects = ['%s_%s' % (x, name) for x in vector_names] obj._vector_names = vector_names v1 = BaseVector(0, obj, pretty_vects[0], latex_vects[0]) v2 = BaseVector(1, obj, pretty_vects[1], latex_vects[1]) v3 = BaseVector(2, obj, pretty_vects[2], latex_vects[2]) obj._base_vectors = (v1, v2, v3) # Initialize the base scalars _check_strings('variable_names', vector_names) variable_names = list(variable_names) latex_scalars = [(r"\mathbf{{%s}_{%s}}" % (x, name)) for x in variable_names] pretty_scalars = ['%s_%s' % (x, name) for x in variable_names] obj._variable_names = variable_names obj._vector_names = vector_names x1 = BaseScalar(0, obj, pretty_scalars[0], latex_scalars[0]) x2 = BaseScalar(1, obj, pretty_scalars[1], latex_scalars[1]) x3 = BaseScalar(2, obj, pretty_scalars[2], latex_scalars[2]) obj._base_scalars = (x1, x2, x3) obj._transformation = transformation obj._transformation_lambda = lambda_transformation obj._lame_coefficients = lambda_lame(x1, x2, x3) obj._transformation_from_parent_lambda = lambda_inverse setattr(obj, variable_names[0], x1) setattr(obj, variable_names[1], x2) setattr(obj, variable_names[2], x3) setattr(obj, vector_names[0], v1) setattr(obj, vector_names[1], v2) setattr(obj, vector_names[2], v3) # Assign params obj._parent = parent if obj._parent is not None: obj._root = obj._parent._root else: obj._root = obj obj._parent_rotation_matrix = rotation_matrix obj._origin = origin # Return the instance return obj def _sympystr(self, printer): return self._name def __iter__(self): return iter(self.base_vectors()) @staticmethod def _check_orthogonality(equations): """ Helper method for _connect_to_cartesian. It checks if set of transformation equations create orthogonal curvilinear coordinate system Parameters ========== equations : Lambda Lambda of transformation equations """ x1, x2, x3 = symbols("x1, x2, x3", cls=Dummy) equations = equations(x1, x2, x3) v1 = Matrix([diff(equations[0], x1), diff(equations[1], x1), diff(equations[2], x1)]) v2 = Matrix([diff(equations[0], x2), diff(equations[1], x2), diff(equations[2], x2)]) v3 = Matrix([diff(equations[0], x3), diff(equations[1], x3), diff(equations[2], x3)]) if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)): return False else: if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 \ and simplify(v3.dot(v1)) == 0: return True else: return False @staticmethod def _set_inv_trans_equations(curv_coord_name): """ Store information about inverse transformation equations for pre-defined coordinate systems. Parameters ========== curv_coord_name : str Name of coordinate system """ if curv_coord_name == 'cartesian': return lambda x, y, z: (x, y, z) if curv_coord_name == 'spherical': return lambda x, y, z: ( sqrt(x**2 + y**2 + z**2), acos(z/sqrt(x**2 + y**2 + z**2)), atan2(y, x) ) if curv_coord_name == 'cylindrical': return lambda x, y, z: ( sqrt(x**2 + y**2), atan2(y, x), z ) raise ValueError('Wrong set of parameters.' 'Type of coordinate system is defined') def _calculate_inv_trans_equations(self): """ Helper method for set_coordinate_type. It calculates inverse transformation equations for given transformations equations. """ x1, x2, x3 = symbols("x1, x2, x3", cls=Dummy, reals=True) x, y, z = symbols("x, y, z", cls=Dummy) equations = self._transformation(x1, x2, x3) solved = solve([equations[0] - x, equations[1] - y, equations[2] - z], (x1, x2, x3), dict=True)[0] solved = solved[x1], solved[x2], solved[x3] self._transformation_from_parent_lambda = \ lambda x1, x2, x3: tuple(i.subs(list(zip((x, y, z), (x1, x2, x3)))) for i in solved) @staticmethod def _get_lame_coeff(curv_coord_name): """ Store information about Lame coefficients for pre-defined coordinate systems. Parameters ========== curv_coord_name : str Name of coordinate system """ if isinstance(curv_coord_name, str): if curv_coord_name == 'cartesian': return lambda x, y, z: (S.One, S.One, S.One) if curv_coord_name == 'spherical': return lambda r, theta, phi: (S.One, r, r*sin(theta)) if curv_coord_name == 'cylindrical': return lambda r, theta, h: (S.One, r, S.One) raise ValueError('Wrong set of parameters.' ' Type of coordinate system is not defined') return CoordSys3D._calculate_lame_coefficients(curv_coord_name) @staticmethod def _calculate_lame_coeff(equations): """ It calculates Lame coefficients for given transformations equations. Parameters ========== equations : Lambda Lambda of transformation equations. """ return lambda x1, x2, x3: ( sqrt(diff(equations(x1, x2, x3)[0], x1)**2 + diff(equations(x1, x2, x3)[1], x1)**2 + diff(equations(x1, x2, x3)[2], x1)**2), sqrt(diff(equations(x1, x2, x3)[0], x2)**2 + diff(equations(x1, x2, x3)[1], x2)**2 + diff(equations(x1, x2, x3)[2], x2)**2), sqrt(diff(equations(x1, x2, x3)[0], x3)**2 + diff(equations(x1, x2, x3)[1], x3)**2 + diff(equations(x1, x2, x3)[2], x3)**2) ) def _inverse_rotation_matrix(self): """ Returns inverse rotation matrix. """ return simplify(self._parent_rotation_matrix**-1) @staticmethod def _get_transformation_lambdas(curv_coord_name): """ Store information about transformation equations for pre-defined coordinate systems. Parameters ========== curv_coord_name : str Name of coordinate system """ if isinstance(curv_coord_name, str): if curv_coord_name == 'cartesian': return lambda x, y, z: (x, y, z) if curv_coord_name == 'spherical': return lambda r, theta, phi: ( r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta) ) if curv_coord_name == 'cylindrical': return lambda r, theta, h: ( r*cos(theta), r*sin(theta), h ) raise ValueError('Wrong set of parameters.' 'Type of coordinate system is defined') @classmethod def _rotation_trans_equations(cls, matrix, equations): """ Returns the transformation equations obtained from rotation matrix. Parameters ========== matrix : Matrix Rotation matrix equations : tuple Transformation equations """ return tuple(matrix * Matrix(equations)) @property def origin(self): return self._origin def base_vectors(self): return self._base_vectors def base_scalars(self): return self._base_scalars def lame_coefficients(self): return self._lame_coefficients def transformation_to_parent(self): return self._transformation_lambda(*self.base_scalars()) def transformation_from_parent(self): if self._parent is None: raise ValueError("no parent coordinate system, use " "`transformation_from_parent_function()`") return self._transformation_from_parent_lambda( *self._parent.base_scalars()) def transformation_from_parent_function(self): return self._transformation_from_parent_lambda def rotation_matrix(self, other): """ Returns the direction cosine matrix(DCM), also known as the 'rotation matrix' of this coordinate system with respect to another system. If v_a is a vector defined in system 'A' (in matrix format) and v_b is the same vector defined in system 'B', then v_a = A.rotation_matrix(B) * v_b. A SymPy Matrix is returned. Parameters ========== other : CoordSys3D The system which the DCM is generated to. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import symbols >>> q1 = symbols('q1') >>> N = CoordSys3D('N') >>> A = N.orient_new_axis('A', q1, N.i) >>> N.rotation_matrix(A) Matrix([ [1, 0, 0], [0, cos(q1), -sin(q1)], [0, sin(q1), cos(q1)]]) """ from sympy.vector.functions import _path if not isinstance(other, CoordSys3D): raise TypeError(str(other) + " is not a CoordSys3D") # Handle special cases if other == self: return eye(3) elif other == self._parent: return self._parent_rotation_matrix elif other._parent == self: return other._parent_rotation_matrix.T # Else, use tree to calculate position rootindex, path = _path(self, other) result = eye(3) i = -1 for i in range(rootindex): result *= path[i]._parent_rotation_matrix i += 2 while i < len(path): result *= path[i]._parent_rotation_matrix.T i += 1 return result @cacheit def position_wrt(self, other): """ Returns the position vector of the origin of this coordinate system with respect to another Point/CoordSys3D. Parameters ========== other : Point/CoordSys3D If other is a Point, the position of this system's origin wrt it is returned. If its an instance of CoordSyRect, the position wrt its origin is returned. Examples ======== >>> from sympy.vector import CoordSys3D >>> N = CoordSys3D('N') >>> N1 = N.locate_new('N1', 10 * N.i) >>> N.position_wrt(N1) (-10)*N.i """ return self.origin.position_wrt(other) def scalar_map(self, other): """ Returns a dictionary which expresses the coordinate variables (base scalars) of this frame in terms of the variables of otherframe. Parameters ========== otherframe : CoordSys3D The other system to map the variables to. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import Symbol >>> A = CoordSys3D('A') >>> q = Symbol('q') >>> B = A.orient_new_axis('B', q, A.k) >>> A.scalar_map(B) {A.x: B.x*cos(q) - B.y*sin(q), A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} """ relocated_scalars = [] origin_coords = tuple(self.position_wrt(other).to_matrix(other)) for i, x in enumerate(other.base_scalars()): relocated_scalars.append(x - origin_coords[i]) vars_matrix = (self.rotation_matrix(other) * Matrix(relocated_scalars)) mapping = {} for i, x in enumerate(self.base_scalars()): mapping[x] = trigsimp(vars_matrix[i]) return mapping def locate_new(self, name, position, vector_names=None, variable_names=None): """ Returns a CoordSys3D with its origin located at the given position wrt this coordinate system's origin. Parameters ========== name : str The name of the new CoordSys3D instance. position : Vector The position vector of the new system's origin wrt this one. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. Examples ======== >>> from sympy.vector import CoordSys3D >>> A = CoordSys3D('A') >>> B = A.locate_new('B', 10 * A.i) >>> B.origin.position_wrt(A.origin) 10*A.i """ if variable_names is None: variable_names = self._variable_names if vector_names is None: vector_names = self._vector_names return CoordSys3D(name, location=position, vector_names=vector_names, variable_names=variable_names, parent=self) def orient_new(self, name, orienters, location=None, vector_names=None, variable_names=None): """ Creates a new CoordSys3D oriented in the user-specified way with respect to this system. Please refer to the documentation of the orienter classes for more information about the orientation procedure. Parameters ========== name : str The name of the new CoordSys3D instance. orienters : iterable/Orienter An Orienter or an iterable of Orienters for orienting the new coordinate system. If an Orienter is provided, it is applied to get the new system. If an iterable is provided, the orienters will be applied in the order in which they appear in the iterable. location : Vector(optional) The location of the new coordinate system's origin wrt this system's origin. If not specified, the origins are taken to be coincident. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import symbols >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = CoordSys3D('N') Using an AxisOrienter >>> from sympy.vector import AxisOrienter >>> axis_orienter = AxisOrienter(q1, N.i + 2 * N.j) >>> A = N.orient_new('A', (axis_orienter, )) Using a BodyOrienter >>> from sympy.vector import BodyOrienter >>> body_orienter = BodyOrienter(q1, q2, q3, '123') >>> B = N.orient_new('B', (body_orienter, )) Using a SpaceOrienter >>> from sympy.vector import SpaceOrienter >>> space_orienter = SpaceOrienter(q1, q2, q3, '312') >>> C = N.orient_new('C', (space_orienter, )) Using a QuaternionOrienter >>> from sympy.vector import QuaternionOrienter >>> q_orienter = QuaternionOrienter(q0, q1, q2, q3) >>> D = N.orient_new('D', (q_orienter, )) """ if variable_names is None: variable_names = self._variable_names if vector_names is None: vector_names = self._vector_names if isinstance(orienters, Orienter): if isinstance(orienters, AxisOrienter): final_matrix = orienters.rotation_matrix(self) else: final_matrix = orienters.rotation_matrix() # TODO: trigsimp is needed here so that the matrix becomes # canonical (scalar_map also calls trigsimp; without this, you can # end up with the same CoordinateSystem that compares differently # due to a differently formatted matrix). However, this is # probably not so good for performance. final_matrix = trigsimp(final_matrix) else: final_matrix = Matrix(eye(3)) for orienter in orienters: if isinstance(orienter, AxisOrienter): final_matrix *= orienter.rotation_matrix(self) else: final_matrix *= orienter.rotation_matrix() return CoordSys3D(name, rotation_matrix=final_matrix, vector_names=vector_names, variable_names=variable_names, location=location, parent=self) def orient_new_axis(self, name, angle, axis, location=None, vector_names=None, variable_names=None): """ Axis rotation is a rotation about an arbitrary axis by some angle. The angle is supplied as a SymPy expr scalar, and the axis is supplied as a Vector. Parameters ========== name : string The name of the new coordinate system angle : Expr The angle by which the new system is to be rotated axis : Vector The axis around which the rotation has to be performed location : Vector(optional) The location of the new coordinate system's origin wrt this system's origin. If not specified, the origins are taken to be coincident. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import symbols >>> q1 = symbols('q1') >>> N = CoordSys3D('N') >>> B = N.orient_new_axis('B', q1, N.i + 2 * N.j) """ if variable_names is None: variable_names = self._variable_names if vector_names is None: vector_names = self._vector_names orienter = AxisOrienter(angle, axis) return self.orient_new(name, orienter, location=location, vector_names=vector_names, variable_names=variable_names) def orient_new_body(self, name, angle1, angle2, angle3, rotation_order, location=None, vector_names=None, variable_names=None): """ Body orientation takes this coordinate system through three successive simple rotations. Body fixed rotations include both Euler Angles and Tait-Bryan Angles, see https://en.wikipedia.org/wiki/Euler_angles. Parameters ========== name : string The name of the new coordinate system angle1, angle2, angle3 : Expr Three successive angles to rotate the coordinate system by rotation_order : string String defining the order of axes for rotation location : Vector(optional) The location of the new coordinate system's origin wrt this system's origin. If not specified, the origins are taken to be coincident. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import symbols >>> q1, q2, q3 = symbols('q1 q2 q3') >>> N = CoordSys3D('N') A 'Body' fixed rotation is described by three angles and three body-fixed rotation axes. To orient a coordinate system D with respect to N, each sequential rotation is always about the orthogonal unit vectors fixed to D. For example, a '123' rotation will specify rotations about N.i, then D.j, then D.k. (Initially, D.i is same as N.i) Therefore, >>> D = N.orient_new_body('D', q1, q2, q3, '123') is same as >>> D = N.orient_new_axis('D', q1, N.i) >>> D = D.orient_new_axis('D', q2, D.j) >>> D = D.orient_new_axis('D', q3, D.k) Acceptable rotation orders are of length 3, expressed in XYZ or 123, and cannot have a rotation about about an axis twice in a row. >>> B = N.orient_new_body('B', q1, q2, q3, '123') >>> B = N.orient_new_body('B', q1, q2, 0, 'ZXZ') >>> B = N.orient_new_body('B', 0, 0, 0, 'XYX') """ orienter = BodyOrienter(angle1, angle2, angle3, rotation_order) return self.orient_new(name, orienter, location=location, vector_names=vector_names, variable_names=variable_names) def orient_new_space(self, name, angle1, angle2, angle3, rotation_order, location=None, vector_names=None, variable_names=None): """ Space rotation is similar to Body rotation, but the rotations are applied in the opposite order. Parameters ========== name : string The name of the new coordinate system angle1, angle2, angle3 : Expr Three successive angles to rotate the coordinate system by rotation_order : string String defining the order of axes for rotation location : Vector(optional) The location of the new coordinate system's origin wrt this system's origin. If not specified, the origins are taken to be coincident. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. See Also ======== CoordSys3D.orient_new_body : method to orient via Euler angles Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import symbols >>> q1, q2, q3 = symbols('q1 q2 q3') >>> N = CoordSys3D('N') To orient a coordinate system D with respect to N, each sequential rotation is always about N's orthogonal unit vectors. For example, a '123' rotation will specify rotations about N.i, then N.j, then N.k. Therefore, >>> D = N.orient_new_space('D', q1, q2, q3, '312') is same as >>> B = N.orient_new_axis('B', q1, N.i) >>> C = B.orient_new_axis('C', q2, N.j) >>> D = C.orient_new_axis('D', q3, N.k) """ orienter = SpaceOrienter(angle1, angle2, angle3, rotation_order) return self.orient_new(name, orienter, location=location, vector_names=vector_names, variable_names=variable_names) def orient_new_quaternion(self, name, q0, q1, q2, q3, location=None, vector_names=None, variable_names=None): """ Quaternion orientation orients the new CoordSys3D with Quaternions, defined as a finite rotation about lambda, a unit vector, by some amount theta. This orientation is described by four parameters: q0 = cos(theta/2) q1 = lambda_x sin(theta/2) q2 = lambda_y sin(theta/2) q3 = lambda_z sin(theta/2) Quaternion does not take in a rotation order. Parameters ========== name : string The name of the new coordinate system q0, q1, q2, q3 : Expr The quaternions to rotate the coordinate system by location : Vector(optional) The location of the new coordinate system's origin wrt this system's origin. If not specified, the origins are taken to be coincident. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import symbols >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = CoordSys3D('N') >>> B = N.orient_new_quaternion('B', q0, q1, q2, q3) """ orienter = QuaternionOrienter(q0, q1, q2, q3) return self.orient_new(name, orienter, location=location, vector_names=vector_names, variable_names=variable_names) def create_new(self, name, transformation, variable_names=None, vector_names=None): """ Returns a CoordSys3D which is connected to self by transformation. Parameters ========== name : str The name of the new CoordSys3D instance. transformation : Lambda, Tuple, str Transformation defined by transformation equations or chosen from predefined ones. vector_names, variable_names : iterable(optional) Iterables of 3 strings each, with custom names for base vectors and base scalars of the new system respectively. Used for simple str printing. Examples ======== >>> from sympy.vector import CoordSys3D >>> a = CoordSys3D('a') >>> b = a.create_new('b', transformation='spherical') >>> b.transformation_to_parent() (b.r*sin(b.theta)*cos(b.phi), b.r*sin(b.phi)*sin(b.theta), b.r*cos(b.theta)) >>> b.transformation_from_parent() (sqrt(a.x**2 + a.y**2 + a.z**2), acos(a.z/sqrt(a.x**2 + a.y**2 + a.z**2)), atan2(a.y, a.x)) """ return CoordSys3D(name, parent=self, transformation=transformation, variable_names=variable_names, vector_names=vector_names) def __init__(self, name, location=None, rotation_matrix=None, parent=None, vector_names=None, variable_names=None, latex_vects=None, pretty_vects=None, latex_scalars=None, pretty_scalars=None, transformation=None): # Dummy initializer for setting docstring pass __init__.__doc__ = __new__.__doc__ @staticmethod def _compose_rotation_and_translation(rot, translation, parent): r = lambda x, y, z: CoordSys3D._rotation_trans_equations(rot, (x, y, z)) if parent is None: return r dx, dy, dz = [translation.dot(i) for i in parent.base_vectors()] t = lambda x, y, z: ( x + dx, y + dy, z + dz, ) return lambda x, y, z: t(*r(x, y, z)) def _check_strings(arg_name, arg): errorstr = arg_name + " must be an iterable of 3 string-types" if len(arg) != 3: raise ValueError(errorstr) for s in arg: if not isinstance(s, str): raise TypeError(errorstr) # Delayed import to avoid cyclic import problems: from sympy.vector.vector import BaseVector
e0124d8e6237e361e455199e424a9abaabe26cab1fd873aece49d04df40c9298
from sympy.core import Basic from sympy.vector.operators import gradient, divergence, curl class Del(Basic): """ Represents the vector differential operator, usually represented in mathematical expressions as the 'nabla' symbol. """ def __new__(cls): obj = super().__new__(cls) obj._name = "delop" return obj def gradient(self, scalar_field, doit=False): """ Returns the gradient of the given scalar field, as a Vector instance. Parameters ========== scalar_field : SymPy expression The scalar field to calculate the gradient of. doit : bool If True, the result is returned after calling .doit() on each component. Else, the returned expression contains Derivative instances Examples ======== >>> from sympy.vector import CoordSys3D, Del >>> C = CoordSys3D('C') >>> delop = Del() >>> delop.gradient(9) 0 >>> delop(C.x*C.y*C.z).doit() C.y*C.z*C.i + C.x*C.z*C.j + C.x*C.y*C.k """ return gradient(scalar_field, doit=doit) __call__ = gradient __call__.__doc__ = gradient.__doc__ def dot(self, vect, doit=False): """ Represents the dot product between this operator and a given vector - equal to the divergence of the vector field. Parameters ========== vect : Vector The vector whose divergence is to be calculated. doit : bool If True, the result is returned after calling .doit() on each component. Else, the returned expression contains Derivative instances Examples ======== >>> from sympy.vector import CoordSys3D, Del >>> delop = Del() >>> C = CoordSys3D('C') >>> delop.dot(C.x*C.i) Derivative(C.x, C.x) >>> v = C.x*C.y*C.z * (C.i + C.j + C.k) >>> (delop & v).doit() C.x*C.y + C.x*C.z + C.y*C.z """ return divergence(vect, doit=doit) __and__ = dot __and__.__doc__ = dot.__doc__ def cross(self, vect, doit=False): """ Represents the cross product between this operator and a given vector - equal to the curl of the vector field. Parameters ========== vect : Vector The vector whose curl is to be calculated. doit : bool If True, the result is returned after calling .doit() on each component. Else, the returned expression contains Derivative instances Examples ======== >>> from sympy.vector import CoordSys3D, Del >>> C = CoordSys3D('C') >>> delop = Del() >>> v = C.x*C.y*C.z * (C.i + C.j + C.k) >>> delop.cross(v, doit = True) (-C.x*C.y + C.x*C.z)*C.i + (C.x*C.y - C.y*C.z)*C.j + (-C.x*C.z + C.y*C.z)*C.k >>> (delop ^ C.i).doit() 0 """ return curl(vect, doit=doit) __xor__ = cross __xor__.__doc__ = cross.__doc__ def _sympystr(self, printer): return self._name
f1ae1c490d6c279ba2add3281e757b4965d4df324f2adff4a23a276bc0bea756
from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.vector import (Vector, VectorAdd, VectorMul, BaseVector, VectorZero, Cross, Dot, cross, dot) from sympy.vector.dyadic import (Dyadic, DyadicAdd, DyadicMul, BaseDyadic, DyadicZero) from sympy.vector.scalar import BaseScalar from sympy.vector.deloperator import Del from sympy.vector.functions import (express, matrix_to_vector, laplacian, is_conservative, is_solenoidal, scalar_potential, directional_derivative, scalar_potential_difference) from sympy.vector.point import Point from sympy.vector.orienters import (AxisOrienter, BodyOrienter, SpaceOrienter, QuaternionOrienter) from sympy.vector.operators import Gradient, Divergence, Curl, Laplacian, gradient, curl, divergence from sympy.vector.implicitregion import ImplicitRegion from sympy.vector.parametricregion import (ParametricRegion, parametric_region_list) from sympy.vector.integrals import (ParametricIntegral, vector_integrate) __all__ = [ 'Vector', 'VectorAdd', 'VectorMul', 'BaseVector', 'VectorZero', 'Cross', 'Dot', 'cross', 'dot', 'Dyadic', 'DyadicAdd', 'DyadicMul', 'BaseDyadic', 'DyadicZero', 'BaseScalar', 'Del', 'CoordSys3D', 'express', 'matrix_to_vector', 'laplacian', 'is_conservative', 'is_solenoidal', 'scalar_potential', 'directional_derivative', 'scalar_potential_difference', 'Point', 'AxisOrienter', 'BodyOrienter', 'SpaceOrienter', 'QuaternionOrienter', 'Gradient', 'Divergence', 'Curl', 'Laplacian', 'gradient', 'curl', 'divergence', 'ParametricRegion', 'parametric_region_list', 'ImplicitRegion', 'ParametricIntegral', 'vector_integrate', ]
19fa757e2a9e54e992e34c1505e33ea2b548fed179acba29d642a50308b55465
from typing import Type from sympy.core.add import Add from sympy.core.assumptions import StdFactKB from sympy.core.expr import AtomicExpr, Expr from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.sorting import default_sort_key from sympy.core.sympify import sympify from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.vector.basisdependent import (BasisDependentZero, BasisDependent, BasisDependentMul, BasisDependentAdd) from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.dyadic import Dyadic, BaseDyadic, DyadicAdd class Vector(BasisDependent): """ Super class for all Vector classes. Ideally, neither this class nor any of its subclasses should be instantiated by the user. """ is_scalar = False is_Vector = True _op_priority = 12.0 _expr_type = None # type: Type[Vector] _mul_func = None # type: Type[Vector] _add_func = None # type: Type[Vector] _zero_func = None # type: Type[Vector] _base_func = None # type: Type[Vector] zero = None # type: VectorZero @property def components(self): """ Returns the components of this vector in the form of a Python dictionary mapping BaseVector instances to the corresponding measure numbers. Examples ======== >>> from sympy.vector import CoordSys3D >>> C = CoordSys3D('C') >>> v = 3*C.i + 4*C.j + 5*C.k >>> v.components {C.i: 3, C.j: 4, C.k: 5} """ # The '_components' attribute is defined according to the # subclass of Vector the instance belongs to. return self._components def magnitude(self): """ Returns the magnitude of this vector. """ return sqrt(self & self) def normalize(self): """ Returns the normalized version of this vector. """ return self / self.magnitude() def dot(self, other): """ Returns the dot product of this Vector, either with another Vector, or a Dyadic, or a Del operator. If 'other' is a Vector, returns the dot product scalar (SymPy expression). If 'other' is a Dyadic, the dot product is returned as a Vector. If 'other' is an instance of Del, returns the directional derivative operator as a Python function. If this function is applied to a scalar expression, it returns the directional derivative of the scalar field wrt this Vector. Parameters ========== other: Vector/Dyadic/Del The Vector or Dyadic we are dotting with, or a Del operator . Examples ======== >>> from sympy.vector import CoordSys3D, Del >>> C = CoordSys3D('C') >>> delop = Del() >>> C.i.dot(C.j) 0 >>> C.i & C.i 1 >>> v = 3*C.i + 4*C.j + 5*C.k >>> v.dot(C.k) 5 >>> (C.i & delop)(C.x*C.y*C.z) C.y*C.z >>> d = C.i.outer(C.i) >>> C.i.dot(d) C.i """ # Check special cases if isinstance(other, Dyadic): if isinstance(self, VectorZero): return Vector.zero outvec = Vector.zero for k, v in other.components.items(): vect_dot = k.args[0].dot(self) outvec += vect_dot * v * k.args[1] return outvec from sympy.vector.deloperator import Del if not isinstance(other, (Del, Vector)): raise TypeError(str(other) + " is not a vector, dyadic or " + "del operator") # Check if the other is a del operator if isinstance(other, Del): def directional_derivative(field): from sympy.vector.functions import directional_derivative return directional_derivative(field, self) return directional_derivative return dot(self, other) def __and__(self, other): return self.dot(other) __and__.__doc__ = dot.__doc__ def cross(self, other): """ Returns the cross product of this Vector with another Vector or Dyadic instance. The cross product is a Vector, if 'other' is a Vector. If 'other' is a Dyadic, this returns a Dyadic instance. Parameters ========== other: Vector/Dyadic The Vector or Dyadic we are crossing with. Examples ======== >>> from sympy.vector import CoordSys3D >>> C = CoordSys3D('C') >>> C.i.cross(C.j) C.k >>> C.i ^ C.i 0 >>> v = 3*C.i + 4*C.j + 5*C.k >>> v ^ C.i 5*C.j + (-4)*C.k >>> d = C.i.outer(C.i) >>> C.j.cross(d) (-1)*(C.k|C.i) """ # Check special cases if isinstance(other, Dyadic): if isinstance(self, VectorZero): return Dyadic.zero outdyad = Dyadic.zero for k, v in other.components.items(): cross_product = self.cross(k.args[0]) outer = cross_product.outer(k.args[1]) outdyad += v * outer return outdyad return cross(self, other) def __xor__(self, other): return self.cross(other) __xor__.__doc__ = cross.__doc__ def outer(self, other): """ Returns the outer product of this vector with another, in the form of a Dyadic instance. Parameters ========== other : Vector The Vector with respect to which the outer product is to be computed. Examples ======== >>> from sympy.vector import CoordSys3D >>> N = CoordSys3D('N') >>> N.i.outer(N.j) (N.i|N.j) """ # Handle the special cases if not isinstance(other, Vector): raise TypeError("Invalid operand for outer product") elif (isinstance(self, VectorZero) or isinstance(other, VectorZero)): return Dyadic.zero # Iterate over components of both the vectors to generate # the required Dyadic instance args = [] for k1, v1 in self.components.items(): for k2, v2 in other.components.items(): args.append((v1 * v2) * BaseDyadic(k1, k2)) return DyadicAdd(*args) def projection(self, other, scalar=False): """ Returns the vector or scalar projection of the 'other' on 'self'. Examples ======== >>> from sympy.vector.coordsysrect import CoordSys3D >>> C = CoordSys3D('C') >>> i, j, k = C.base_vectors() >>> v1 = i + j + k >>> v2 = 3*i + 4*j >>> v1.projection(v2) 7/3*C.i + 7/3*C.j + 7/3*C.k >>> v1.projection(v2, scalar=True) 7/3 """ if self.equals(Vector.zero): return S.Zero if scalar else Vector.zero if scalar: return self.dot(other) / self.dot(self) else: return self.dot(other) / self.dot(self) * self @property def _projections(self): """ Returns the components of this vector but the output includes also zero values components. Examples ======== >>> from sympy.vector import CoordSys3D, Vector >>> C = CoordSys3D('C') >>> v1 = 3*C.i + 4*C.j + 5*C.k >>> v1._projections (3, 4, 5) >>> v2 = C.x*C.y*C.z*C.i >>> v2._projections (C.x*C.y*C.z, 0, 0) >>> v3 = Vector.zero >>> v3._projections (0, 0, 0) """ from sympy.vector.operators import _get_coord_systems if isinstance(self, VectorZero): return (S.Zero, S.Zero, S.Zero) base_vec = next(iter(_get_coord_systems(self))).base_vectors() return tuple([self.dot(i) for i in base_vec]) def __or__(self, other): return self.outer(other) __or__.__doc__ = outer.__doc__ def to_matrix(self, system): """ Returns the matrix form of this vector with respect to the specified coordinate system. Parameters ========== system : CoordSys3D The system wrt which the matrix form is to be computed Examples ======== >>> from sympy.vector import CoordSys3D >>> C = CoordSys3D('C') >>> from sympy.abc import a, b, c >>> v = a*C.i + b*C.j + c*C.k >>> v.to_matrix(C) Matrix([ [a], [b], [c]]) """ return Matrix([self.dot(unit_vec) for unit_vec in system.base_vectors()]) def separate(self): """ The constituents of this vector in different coordinate systems, as per its definition. Returns a dict mapping each CoordSys3D to the corresponding constituent Vector. Examples ======== >>> from sympy.vector import CoordSys3D >>> R1 = CoordSys3D('R1') >>> R2 = CoordSys3D('R2') >>> v = R1.i + R2.i >>> v.separate() == {R1: R1.i, R2: R2.i} True """ parts = {} for vect, measure in self.components.items(): parts[vect.system] = (parts.get(vect.system, Vector.zero) + vect * measure) return parts def _div_helper(one, other): """ Helper for division involving vectors. """ if isinstance(one, Vector) and isinstance(other, Vector): raise TypeError("Cannot divide two vectors") elif isinstance(one, Vector): if other == S.Zero: raise ValueError("Cannot divide a vector by zero") return VectorMul(one, Pow(other, S.NegativeOne)) else: raise TypeError("Invalid division involving a vector") class BaseVector(Vector, AtomicExpr): """ Class to denote a base vector. """ def __new__(cls, index, system, pretty_str=None, latex_str=None): if pretty_str is None: pretty_str = "x{}".format(index) if latex_str is None: latex_str = "x_{}".format(index) pretty_str = str(pretty_str) latex_str = str(latex_str) # Verify arguments if index not in range(0, 3): raise ValueError("index must be 0, 1 or 2") if not isinstance(system, CoordSys3D): raise TypeError("system should be a CoordSys3D") name = system._vector_names[index] # Initialize an object obj = super().__new__(cls, S(index), system) # Assign important attributes obj._base_instance = obj obj._components = {obj: S.One} obj._measure_number = S.One obj._name = system._name + '.' + name obj._pretty_form = '' + pretty_str obj._latex_form = latex_str obj._system = system # The _id is used for printing purposes obj._id = (index, system) assumptions = {'commutative': True} obj._assumptions = StdFactKB(assumptions) # This attr is used for re-expression to one of the systems # involved in the definition of the Vector. Applies to # VectorMul and VectorAdd too. obj._sys = system return obj @property def system(self): return self._system def _sympystr(self, printer): return self._name def _sympyrepr(self, printer): index, system = self._id return printer._print(system) + '.' + system._vector_names[index] @property def free_symbols(self): return {self} class VectorAdd(BasisDependentAdd, Vector): """ Class to denote sum of Vector instances. """ def __new__(cls, *args, **options): obj = BasisDependentAdd.__new__(cls, *args, **options) return obj def _sympystr(self, printer): ret_str = '' items = list(self.separate().items()) items.sort(key=lambda x: x[0].__str__()) for system, vect in items: base_vects = system.base_vectors() for x in base_vects: if x in vect.components: temp_vect = self.components[x] * x ret_str += printer._print(temp_vect) + " + " return ret_str[:-3] class VectorMul(BasisDependentMul, Vector): """ Class to denote products of scalars and BaseVectors. """ def __new__(cls, *args, **options): obj = BasisDependentMul.__new__(cls, *args, **options) return obj @property def base_vector(self): """ The BaseVector involved in the product. """ return self._base_instance @property def measure_number(self): """ The scalar expression involved in the definition of this VectorMul. """ return self._measure_number class VectorZero(BasisDependentZero, Vector): """ Class to denote a zero vector """ _op_priority = 12.1 _pretty_form = '0' _latex_form = r'\mathbf{\hat{0}}' def __new__(cls): obj = BasisDependentZero.__new__(cls) return obj class Cross(Vector): """ Represents unevaluated Cross product. Examples ======== >>> from sympy.vector import CoordSys3D, Cross >>> R = CoordSys3D('R') >>> v1 = R.i + R.j + R.k >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k >>> Cross(v1, v2) Cross(R.i + R.j + R.k, R.x*R.i + R.y*R.j + R.z*R.k) >>> Cross(v1, v2).doit() (-R.y + R.z)*R.i + (R.x - R.z)*R.j + (-R.x + R.y)*R.k """ def __new__(cls, expr1, expr2): expr1 = sympify(expr1) expr2 = sympify(expr2) if default_sort_key(expr1) > default_sort_key(expr2): return -Cross(expr2, expr1) obj = Expr.__new__(cls, expr1, expr2) obj._expr1 = expr1 obj._expr2 = expr2 return obj def doit(self, **kwargs): return cross(self._expr1, self._expr2) class Dot(Expr): """ Represents unevaluated Dot product. Examples ======== >>> from sympy.vector import CoordSys3D, Dot >>> from sympy import symbols >>> R = CoordSys3D('R') >>> a, b, c = symbols('a b c') >>> v1 = R.i + R.j + R.k >>> v2 = a * R.i + b * R.j + c * R.k >>> Dot(v1, v2) Dot(R.i + R.j + R.k, a*R.i + b*R.j + c*R.k) >>> Dot(v1, v2).doit() a + b + c """ def __new__(cls, expr1, expr2): expr1 = sympify(expr1) expr2 = sympify(expr2) expr1, expr2 = sorted([expr1, expr2], key=default_sort_key) obj = Expr.__new__(cls, expr1, expr2) obj._expr1 = expr1 obj._expr2 = expr2 return obj def doit(self, **kwargs): return dot(self._expr1, self._expr2) def cross(vect1, vect2): """ Returns cross product of two vectors. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector.vector import cross >>> R = CoordSys3D('R') >>> v1 = R.i + R.j + R.k >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k >>> cross(v1, v2) (-R.y + R.z)*R.i + (R.x - R.z)*R.j + (-R.x + R.y)*R.k """ if isinstance(vect1, Add): return VectorAdd.fromiter(cross(i, vect2) for i in vect1.args) if isinstance(vect2, Add): return VectorAdd.fromiter(cross(vect1, i) for i in vect2.args) if isinstance(vect1, BaseVector) and isinstance(vect2, BaseVector): if vect1._sys == vect2._sys: n1 = vect1.args[0] n2 = vect2.args[0] if n1 == n2: return Vector.zero n3 = ({0,1,2}.difference({n1, n2})).pop() sign = 1 if ((n1 + 1) % 3 == n2) else -1 return sign*vect1._sys.base_vectors()[n3] from .functions import express try: v = express(vect1, vect2._sys) except ValueError: return Cross(vect1, vect2) else: return cross(v, vect2) if isinstance(vect1, VectorZero) or isinstance(vect2, VectorZero): return Vector.zero if isinstance(vect1, VectorMul): v1, m1 = next(iter(vect1.components.items())) return m1*cross(v1, vect2) if isinstance(vect2, VectorMul): v2, m2 = next(iter(vect2.components.items())) return m2*cross(vect1, v2) return Cross(vect1, vect2) def dot(vect1, vect2): """ Returns dot product of two vectors. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector.vector import dot >>> R = CoordSys3D('R') >>> v1 = R.i + R.j + R.k >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k >>> dot(v1, v2) R.x + R.y + R.z """ if isinstance(vect1, Add): return Add.fromiter(dot(i, vect2) for i in vect1.args) if isinstance(vect2, Add): return Add.fromiter(dot(vect1, i) for i in vect2.args) if isinstance(vect1, BaseVector) and isinstance(vect2, BaseVector): if vect1._sys == vect2._sys: return S.One if vect1 == vect2 else S.Zero from .functions import express try: v = express(vect2, vect1._sys) except ValueError: return Dot(vect1, vect2) else: return dot(vect1, v) if isinstance(vect1, VectorZero) or isinstance(vect2, VectorZero): return S.Zero if isinstance(vect1, VectorMul): v1, m1 = next(iter(vect1.components.items())) return m1*dot(v1, vect2) if isinstance(vect2, VectorMul): v2, m2 = next(iter(vect2.components.items())) return m2*dot(vect1, v2) return Dot(vect1, vect2) Vector._expr_type = Vector Vector._mul_func = VectorMul Vector._add_func = VectorAdd Vector._zero_func = VectorZero Vector._base_func = BaseVector Vector.zero = VectorZero()
3ddb3fec9479c981326b089e674bd502c2214dcdeb5af68dd3c82cb110c00aef
import collections from sympy.core.expr import Expr from sympy.core import sympify, S, preorder_traversal from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.vector import Vector, VectorMul, VectorAdd, Cross, Dot from sympy.core.function import Derivative from sympy.core.add import Add from sympy.core.mul import Mul def _get_coord_systems(expr): g = preorder_traversal(expr) ret = set() for i in g: if isinstance(i, CoordSys3D): ret.add(i) g.skip() return frozenset(ret) def _split_mul_args_wrt_coordsys(expr): d = collections.defaultdict(lambda: S.One) for i in expr.args: d[_get_coord_systems(i)] *= i return list(d.values()) class Gradient(Expr): """ Represents unevaluated Gradient. Examples ======== >>> from sympy.vector import CoordSys3D, Gradient >>> R = CoordSys3D('R') >>> s = R.x*R.y*R.z >>> Gradient(s) Gradient(R.x*R.y*R.z) """ def __new__(cls, expr): expr = sympify(expr) obj = Expr.__new__(cls, expr) obj._expr = expr return obj def doit(self, **kwargs): return gradient(self._expr, doit=True) class Divergence(Expr): """ Represents unevaluated Divergence. Examples ======== >>> from sympy.vector import CoordSys3D, Divergence >>> R = CoordSys3D('R') >>> v = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k >>> Divergence(v) Divergence(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) """ def __new__(cls, expr): expr = sympify(expr) obj = Expr.__new__(cls, expr) obj._expr = expr return obj def doit(self, **kwargs): return divergence(self._expr, doit=True) class Curl(Expr): """ Represents unevaluated Curl. Examples ======== >>> from sympy.vector import CoordSys3D, Curl >>> R = CoordSys3D('R') >>> v = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k >>> Curl(v) Curl(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) """ def __new__(cls, expr): expr = sympify(expr) obj = Expr.__new__(cls, expr) obj._expr = expr return obj def doit(self, **kwargs): return curl(self._expr, doit=True) def curl(vect, doit=True): """ Returns the curl of a vector field computed wrt the base scalars of the given coordinate system. Parameters ========== vect : Vector The vector operand doit : bool If True, the result is returned after calling .doit() on each component. Else, the returned expression contains Derivative instances Examples ======== >>> from sympy.vector import CoordSys3D, curl >>> R = CoordSys3D('R') >>> v1 = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k >>> curl(v1) 0 >>> v2 = R.x*R.y*R.z*R.i >>> curl(v2) R.x*R.y*R.j + (-R.x*R.z)*R.k """ coord_sys = _get_coord_systems(vect) if len(coord_sys) == 0: return Vector.zero elif len(coord_sys) == 1: coord_sys = next(iter(coord_sys)) i, j, k = coord_sys.base_vectors() x, y, z = coord_sys.base_scalars() h1, h2, h3 = coord_sys.lame_coefficients() vectx = vect.dot(i) vecty = vect.dot(j) vectz = vect.dot(k) outvec = Vector.zero outvec += (Derivative(vectz * h3, y) - Derivative(vecty * h2, z)) * i / (h2 * h3) outvec += (Derivative(vectx * h1, z) - Derivative(vectz * h3, x)) * j / (h1 * h3) outvec += (Derivative(vecty * h2, x) - Derivative(vectx * h1, y)) * k / (h2 * h1) if doit: return outvec.doit() return outvec else: if isinstance(vect, (Add, VectorAdd)): from sympy.vector import express try: cs = next(iter(coord_sys)) args = [express(i, cs, variables=True) for i in vect.args] except ValueError: args = vect.args return VectorAdd.fromiter(curl(i, doit=doit) for i in args) elif isinstance(vect, (Mul, VectorMul)): vector = [i for i in vect.args if isinstance(i, (Vector, Cross, Gradient))][0] scalar = Mul.fromiter(i for i in vect.args if not isinstance(i, (Vector, Cross, Gradient))) res = Cross(gradient(scalar), vector).doit() + scalar*curl(vector, doit=doit) if doit: return res.doit() return res elif isinstance(vect, (Cross, Curl, Gradient)): return Curl(vect) else: raise Curl(vect) def divergence(vect, doit=True): """ Returns the divergence of a vector field computed wrt the base scalars of the given coordinate system. Parameters ========== vector : Vector The vector operand doit : bool If True, the result is returned after calling .doit() on each component. Else, the returned expression contains Derivative instances Examples ======== >>> from sympy.vector import CoordSys3D, divergence >>> R = CoordSys3D('R') >>> v1 = R.x*R.y*R.z * (R.i+R.j+R.k) >>> divergence(v1) R.x*R.y + R.x*R.z + R.y*R.z >>> v2 = 2*R.y*R.z*R.j >>> divergence(v2) 2*R.z """ coord_sys = _get_coord_systems(vect) if len(coord_sys) == 0: return S.Zero elif len(coord_sys) == 1: if isinstance(vect, (Cross, Curl, Gradient)): return Divergence(vect) # TODO: is case of many coord systems, this gets a random one: coord_sys = next(iter(coord_sys)) i, j, k = coord_sys.base_vectors() x, y, z = coord_sys.base_scalars() h1, h2, h3 = coord_sys.lame_coefficients() vx = _diff_conditional(vect.dot(i), x, h2, h3) \ / (h1 * h2 * h3) vy = _diff_conditional(vect.dot(j), y, h3, h1) \ / (h1 * h2 * h3) vz = _diff_conditional(vect.dot(k), z, h1, h2) \ / (h1 * h2 * h3) res = vx + vy + vz if doit: return res.doit() return res else: if isinstance(vect, (Add, VectorAdd)): return Add.fromiter(divergence(i, doit=doit) for i in vect.args) elif isinstance(vect, (Mul, VectorMul)): vector = [i for i in vect.args if isinstance(i, (Vector, Cross, Gradient))][0] scalar = Mul.fromiter(i for i in vect.args if not isinstance(i, (Vector, Cross, Gradient))) res = Dot(vector, gradient(scalar)) + scalar*divergence(vector, doit=doit) if doit: return res.doit() return res elif isinstance(vect, (Cross, Curl, Gradient)): return Divergence(vect) else: raise Divergence(vect) def gradient(scalar_field, doit=True): """ Returns the vector gradient of a scalar field computed wrt the base scalars of the given coordinate system. Parameters ========== scalar_field : SymPy Expr The scalar field to compute the gradient of doit : bool If True, the result is returned after calling .doit() on each component. Else, the returned expression contains Derivative instances Examples ======== >>> from sympy.vector import CoordSys3D, gradient >>> R = CoordSys3D('R') >>> s1 = R.x*R.y*R.z >>> gradient(s1) R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k >>> s2 = 5*R.x**2*R.z >>> gradient(s2) 10*R.x*R.z*R.i + 5*R.x**2*R.k """ coord_sys = _get_coord_systems(scalar_field) if len(coord_sys) == 0: return Vector.zero elif len(coord_sys) == 1: coord_sys = next(iter(coord_sys)) h1, h2, h3 = coord_sys.lame_coefficients() i, j, k = coord_sys.base_vectors() x, y, z = coord_sys.base_scalars() vx = Derivative(scalar_field, x) / h1 vy = Derivative(scalar_field, y) / h2 vz = Derivative(scalar_field, z) / h3 if doit: return (vx * i + vy * j + vz * k).doit() return vx * i + vy * j + vz * k else: if isinstance(scalar_field, (Add, VectorAdd)): return VectorAdd.fromiter(gradient(i) for i in scalar_field.args) if isinstance(scalar_field, (Mul, VectorMul)): s = _split_mul_args_wrt_coordsys(scalar_field) return VectorAdd.fromiter(scalar_field / i * gradient(i) for i in s) return Gradient(scalar_field) class Laplacian(Expr): """ Represents unevaluated Laplacian. Examples ======== >>> from sympy.vector import CoordSys3D, Laplacian >>> R = CoordSys3D('R') >>> v = 3*R.x**3*R.y**2*R.z**3 >>> Laplacian(v) Laplacian(3*R.x**3*R.y**2*R.z**3) """ def __new__(cls, expr): expr = sympify(expr) obj = Expr.__new__(cls, expr) obj._expr = expr return obj def doit(self, **kwargs): from sympy.vector.functions import laplacian return laplacian(self._expr) def _diff_conditional(expr, base_scalar, coeff_1, coeff_2): """ First re-expresses expr in the system that base_scalar belongs to. If base_scalar appears in the re-expressed form, differentiates it wrt base_scalar. Else, returns 0 """ from sympy.vector.functions import express new_expr = express(expr, base_scalar.system, variables=True) arg = coeff_1 * coeff_2 * new_expr return Derivative(arg, base_scalar) if arg else S.Zero
6909943fe667ad649fa646ad2b22cecbae12dd5c04bb0abe70b18b993317182b
from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.deloperator import Del from sympy.vector.scalar import BaseScalar from sympy.vector.vector import Vector, BaseVector from sympy.vector.operators import gradient, curl, divergence from sympy.core.function import diff from sympy.core.singleton import S from sympy.integrals.integrals import integrate from sympy.simplify.simplify import simplify from sympy.core import sympify from sympy.vector.dyadic import Dyadic def express(expr, system, system2=None, variables=False): """ Global function for 'express' functionality. Re-expresses a Vector, Dyadic or scalar(sympyfiable) in the given coordinate system. If 'variables' is True, then the coordinate variables (base scalars) of other coordinate systems present in the vector/scalar field or dyadic are also substituted in terms of the base scalars of the given system. Parameters ========== expr : Vector/Dyadic/scalar(sympyfiable) The expression to re-express in CoordSys3D 'system' system: CoordSys3D The coordinate system the expr is to be expressed in system2: CoordSys3D The other coordinate system required for re-expression (only for a Dyadic Expr) variables : boolean Specifies whether to substitute the coordinate variables present in expr, in terms of those of parameter system Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy import Symbol, cos, sin >>> N = CoordSys3D('N') >>> q = Symbol('q') >>> B = N.orient_new_axis('B', q, N.k) >>> from sympy.vector import express >>> express(B.i, N) (cos(q))*N.i + (sin(q))*N.j >>> express(N.x, B, variables=True) B.x*cos(q) - B.y*sin(q) >>> d = N.i.outer(N.i) >>> express(d, B, N) == (cos(q))*(B.i|N.i) + (-sin(q))*(B.j|N.i) True """ if expr in (0, Vector.zero): return expr if not isinstance(system, CoordSys3D): raise TypeError("system should be a CoordSys3D \ instance") if isinstance(expr, Vector): if system2 is not None: raise ValueError("system2 should not be provided for \ Vectors") # Given expr is a Vector if variables: # If variables attribute is True, substitute # the coordinate variables in the Vector system_list = [] for x in expr.atoms(BaseScalar, BaseVector): if x.system != system: system_list.append(x.system) system_list = set(system_list) subs_dict = {} for f in system_list: subs_dict.update(f.scalar_map(system)) expr = expr.subs(subs_dict) # Re-express in this coordinate system outvec = Vector.zero parts = expr.separate() for x in parts: if x != system: temp = system.rotation_matrix(x) * parts[x].to_matrix(x) outvec += matrix_to_vector(temp, system) else: outvec += parts[x] return outvec elif isinstance(expr, Dyadic): if system2 is None: system2 = system if not isinstance(system2, CoordSys3D): raise TypeError("system2 should be a CoordSys3D \ instance") outdyad = Dyadic.zero var = variables for k, v in expr.components.items(): outdyad += (express(v, system, variables=var) * (express(k.args[0], system, variables=var) | express(k.args[1], system2, variables=var))) return outdyad else: if system2 is not None: raise ValueError("system2 should not be provided for \ Vectors") if variables: # Given expr is a scalar field system_set = set() expr = sympify(expr) # Substitute all the coordinate variables for x in expr.atoms(BaseScalar): if x.system != system: system_set.add(x.system) subs_dict = {} for f in system_set: subs_dict.update(f.scalar_map(system)) return expr.subs(subs_dict) return expr def directional_derivative(field, direction_vector): """ Returns the directional derivative of a scalar or vector field computed along a given vector in coordinate system which parameters are expressed. Parameters ========== field : Vector or Scalar The scalar or vector field to compute the directional derivative of direction_vector : Vector The vector to calculated directional derivative along them. Examples ======== >>> from sympy.vector import CoordSys3D, directional_derivative >>> R = CoordSys3D('R') >>> f1 = R.x*R.y*R.z >>> v1 = 3*R.i + 4*R.j + R.k >>> directional_derivative(f1, v1) R.x*R.y + 4*R.x*R.z + 3*R.y*R.z >>> f2 = 5*R.x**2*R.z >>> directional_derivative(f2, v1) 5*R.x**2 + 30*R.x*R.z """ from sympy.vector.operators import _get_coord_systems coord_sys = _get_coord_systems(field) if len(coord_sys) > 0: # TODO: This gets a random coordinate system in case of multiple ones: coord_sys = next(iter(coord_sys)) field = express(field, coord_sys, variables=True) i, j, k = coord_sys.base_vectors() x, y, z = coord_sys.base_scalars() out = Vector.dot(direction_vector, i) * diff(field, x) out += Vector.dot(direction_vector, j) * diff(field, y) out += Vector.dot(direction_vector, k) * diff(field, z) if out == 0 and isinstance(field, Vector): out = Vector.zero return out elif isinstance(field, Vector): return Vector.zero else: return S.Zero def laplacian(expr): """ Return the laplacian of the given field computed in terms of the base scalars of the given coordinate system. Parameters ========== expr : SymPy Expr or Vector expr denotes a scalar or vector field. Examples ======== >>> from sympy.vector import CoordSys3D, laplacian >>> R = CoordSys3D('R') >>> f = R.x**2*R.y**5*R.z >>> laplacian(f) 20*R.x**2*R.y**3*R.z + 2*R.y**5*R.z >>> f = R.x**2*R.i + R.y**3*R.j + R.z**4*R.k >>> laplacian(f) 2*R.i + 6*R.y*R.j + 12*R.z**2*R.k """ delop = Del() if expr.is_Vector: return (gradient(divergence(expr)) - curl(curl(expr))).doit() return delop.dot(delop(expr)).doit() def is_conservative(field): """ Checks if a field is conservative. Parameters ========== field : Vector The field to check for conservative property Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector import is_conservative >>> R = CoordSys3D('R') >>> is_conservative(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) True >>> is_conservative(R.z*R.j) False """ # Field is conservative irrespective of system # Take the first coordinate system in the result of the # separate method of Vector if not isinstance(field, Vector): raise TypeError("field should be a Vector") if field == Vector.zero: return True return curl(field).simplify() == Vector.zero def is_solenoidal(field): """ Checks if a field is solenoidal. Parameters ========== field : Vector The field to check for solenoidal property Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector import is_solenoidal >>> R = CoordSys3D('R') >>> is_solenoidal(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) True >>> is_solenoidal(R.y * R.j) False """ # Field is solenoidal irrespective of system # Take the first coordinate system in the result of the # separate method in Vector if not isinstance(field, Vector): raise TypeError("field should be a Vector") if field == Vector.zero: return True return divergence(field).simplify() is S.Zero def scalar_potential(field, coord_sys): """ Returns the scalar potential function of a field in a given coordinate system (without the added integration constant). Parameters ========== field : Vector The vector field whose scalar potential function is to be calculated coord_sys : CoordSys3D The coordinate system to do the calculation in Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector import scalar_potential, gradient >>> R = CoordSys3D('R') >>> scalar_potential(R.k, R) == R.z True >>> scalar_field = 2*R.x**2*R.y*R.z >>> grad_field = gradient(scalar_field) >>> scalar_potential(grad_field, R) 2*R.x**2*R.y*R.z """ # Check whether field is conservative if not is_conservative(field): raise ValueError("Field is not conservative") if field == Vector.zero: return S.Zero # Express the field exntirely in coord_sys # Substitute coordinate variables also if not isinstance(coord_sys, CoordSys3D): raise TypeError("coord_sys must be a CoordSys3D") field = express(field, coord_sys, variables=True) dimensions = coord_sys.base_vectors() scalars = coord_sys.base_scalars() # Calculate scalar potential function temp_function = integrate(field.dot(dimensions[0]), scalars[0]) for i, dim in enumerate(dimensions[1:]): partial_diff = diff(temp_function, scalars[i + 1]) partial_diff = field.dot(dim) - partial_diff temp_function += integrate(partial_diff, scalars[i + 1]) return temp_function def scalar_potential_difference(field, coord_sys, point1, point2): """ Returns the scalar potential difference between two points in a certain coordinate system, wrt a given field. If a scalar field is provided, its values at the two points are considered. If a conservative vector field is provided, the values of its scalar potential function at the two points are used. Returns (potential at point2) - (potential at point1) The position vectors of the two Points are calculated wrt the origin of the coordinate system provided. Parameters ========== field : Vector/Expr The field to calculate wrt coord_sys : CoordSys3D The coordinate system to do the calculations in point1 : Point The initial Point in given coordinate system position2 : Point The second Point in the given coordinate system Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector import scalar_potential_difference >>> R = CoordSys3D('R') >>> P = R.origin.locate_new('P', R.x*R.i + R.y*R.j + R.z*R.k) >>> vectfield = 4*R.x*R.y*R.i + 2*R.x**2*R.j >>> scalar_potential_difference(vectfield, R, R.origin, P) 2*R.x**2*R.y >>> Q = R.origin.locate_new('O', 3*R.i + R.j + 2*R.k) >>> scalar_potential_difference(vectfield, R, P, Q) -2*R.x**2*R.y + 18 """ if not isinstance(coord_sys, CoordSys3D): raise TypeError("coord_sys must be a CoordSys3D") if isinstance(field, Vector): # Get the scalar potential function scalar_fn = scalar_potential(field, coord_sys) else: # Field is a scalar scalar_fn = field # Express positions in required coordinate system origin = coord_sys.origin position1 = express(point1.position_wrt(origin), coord_sys, variables=True) position2 = express(point2.position_wrt(origin), coord_sys, variables=True) # Get the two positions as substitution dicts for coordinate variables subs_dict1 = {} subs_dict2 = {} scalars = coord_sys.base_scalars() for i, x in enumerate(coord_sys.base_vectors()): subs_dict1[scalars[i]] = x.dot(position1) subs_dict2[scalars[i]] = x.dot(position2) return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1) def matrix_to_vector(matrix, system): """ Converts a vector in matrix form to a Vector instance. It is assumed that the elements of the Matrix represent the measure numbers of the components of the vector along basis vectors of 'system'. Parameters ========== matrix : SymPy Matrix, Dimensions: (3, 1) The matrix to be converted to a vector system : CoordSys3D The coordinate system the vector is to be defined in Examples ======== >>> from sympy import ImmutableMatrix as Matrix >>> m = Matrix([1, 2, 3]) >>> from sympy.vector import CoordSys3D, matrix_to_vector >>> C = CoordSys3D('C') >>> v = matrix_to_vector(m, C) >>> v C.i + 2*C.j + 3*C.k >>> v.to_matrix(C) == m True """ outvec = Vector.zero vects = system.base_vectors() for i, x in enumerate(matrix): outvec += x * vects[i] return outvec def _path(from_object, to_object): """ Calculates the 'path' of objects starting from 'from_object' to 'to_object', along with the index of the first common ancestor in the tree. Returns (index, list) tuple. """ if from_object._root != to_object._root: raise ValueError("No connecting path found between " + str(from_object) + " and " + str(to_object)) other_path = [] obj = to_object while obj._parent is not None: other_path.append(obj) obj = obj._parent other_path.append(obj) object_set = set(other_path) from_path = [] obj = from_object while obj not in object_set: from_path.append(obj) obj = obj._parent index = len(from_path) i = other_path.index(obj) while i >= 0: from_path.append(other_path[i]) i -= 1 return index, from_path def orthogonalize(*vlist, orthonormal=False): """ Takes a sequence of independent vectors and orthogonalizes them using the Gram - Schmidt process. Returns a list of orthogonal or orthonormal vectors. Parameters ========== vlist : sequence of independent vectors to be made orthogonal. orthonormal : Optional parameter Set to True if the vectors returned should be orthonormal. Default: False Examples ======== >>> from sympy.vector.coordsysrect import CoordSys3D >>> from sympy.vector.functions import orthogonalize >>> C = CoordSys3D('C') >>> i, j, k = C.base_vectors() >>> v1 = i + 2*j >>> v2 = 2*i + 3*j >>> orthogonalize(v1, v2) [C.i + 2*C.j, 2/5*C.i + (-1/5)*C.j] References ========== .. [1] https://en.wikipedia.org/wiki/Gram-Schmidt_process """ if not all(isinstance(vec, Vector) for vec in vlist): raise TypeError('Each element must be of Type Vector') ortho_vlist = [] for i, term in enumerate(vlist): for j in range(i): term -= ortho_vlist[j].projection(vlist[i]) # TODO : The following line introduces a performance issue # and needs to be changed once a good solution for issue #10279 is # found. if simplify(term).equals(Vector.zero): raise ValueError("Vector set not linearly independent") ortho_vlist.append(term) if orthonormal: ortho_vlist = [vec.normalize() for vec in ortho_vlist] return ortho_vlist
8554f16856c512480babb4ad175093c8f6a73b6364c5fe84ff41115755f4cc30
from sympy.core.singleton import S from sympy.simplify.simplify import simplify from sympy.core import Basic, diff from sympy.core.sorting import default_sort_key from sympy.matrices import Matrix from sympy.vector import (CoordSys3D, Vector, ParametricRegion, parametric_region_list, ImplicitRegion) from sympy.vector.operators import _get_coord_systems from sympy.integrals import Integral, integrate from sympy.utilities.iterables import topological_sort from sympy.geometry.entity import GeometryEntity class ParametricIntegral(Basic): """ Represents integral of a scalar or vector field over a Parametric Region Examples ======== >>> from sympy import cos, sin, pi >>> from sympy.vector import CoordSys3D, ParametricRegion, ParametricIntegral >>> from sympy.abc import r, t, theta, phi >>> C = CoordSys3D('C') >>> curve = ParametricRegion((3*t - 2, t + 1), (t, 1, 2)) >>> ParametricIntegral(C.x, curve) 5*sqrt(10)/2 >>> length = ParametricIntegral(1, curve) >>> length sqrt(10) >>> semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\ (theta, 0, 2*pi), (phi, 0, pi/2)) >>> ParametricIntegral(C.z, semisphere) 8*pi >>> ParametricIntegral(C.j + C.k, ParametricRegion((r*cos(theta), r*sin(theta)), r, theta)) 0 """ def __new__(cls, field, parametricregion): coord_set = _get_coord_systems(field) if len(coord_set) == 0: coord_sys = CoordSys3D('C') elif len(coord_set) > 1: raise ValueError else: coord_sys = next(iter(coord_set)) if parametricregion.dimensions == 0: return S.Zero base_vectors = coord_sys.base_vectors() base_scalars = coord_sys.base_scalars() parametricfield = field r = Vector.zero for i in range(len(parametricregion.definition)): r += base_vectors[i]*parametricregion.definition[i] if len(coord_set) != 0: for i in range(len(parametricregion.definition)): parametricfield = parametricfield.subs(base_scalars[i], parametricregion.definition[i]) if parametricregion.dimensions == 1: parameter = parametricregion.parameters[0] r_diff = diff(r, parameter) lower, upper = parametricregion.limits[parameter][0], parametricregion.limits[parameter][1] if isinstance(parametricfield, Vector): integrand = simplify(r_diff.dot(parametricfield)) else: integrand = simplify(r_diff.magnitude()*parametricfield) result = integrate(integrand, (parameter, lower, upper)) elif parametricregion.dimensions == 2: u, v = cls._bounds_case(parametricregion.parameters, parametricregion.limits) r_u = diff(r, u) r_v = diff(r, v) normal_vector = simplify(r_u.cross(r_v)) if isinstance(parametricfield, Vector): integrand = parametricfield.dot(normal_vector) else: integrand = parametricfield*normal_vector.magnitude() integrand = simplify(integrand) lower_u, upper_u = parametricregion.limits[u][0], parametricregion.limits[u][1] lower_v, upper_v = parametricregion.limits[v][0], parametricregion.limits[v][1] result = integrate(integrand, (u, lower_u, upper_u), (v, lower_v, upper_v)) else: variables = cls._bounds_case(parametricregion.parameters, parametricregion.limits) coeff = Matrix(parametricregion.definition).jacobian(variables).det() integrand = simplify(parametricfield*coeff) l = [(var, parametricregion.limits[var][0], parametricregion.limits[var][1]) for var in variables] result = integrate(integrand, *l) if not isinstance(result, Integral): return result else: return super().__new__(cls, field, parametricregion) @classmethod def _bounds_case(cls, parameters, limits): V = list(limits.keys()) E = list() for p in V: lower_p = limits[p][0] upper_p = limits[p][1] lower_p = lower_p.atoms() upper_p = upper_p.atoms() for q in V: if p == q: continue if lower_p.issuperset({q}) or upper_p.issuperset({q}): E.append((p, q)) if not E: return parameters else: return topological_sort((V, E), key=default_sort_key) @property def field(self): return self.args[0] @property def parametricregion(self): return self.args[1] def vector_integrate(field, *region): """ Compute the integral of a vector/scalar field over a a region or a set of parameters. Examples ======== >>> from sympy.vector import CoordSys3D, ParametricRegion, vector_integrate >>> from sympy.abc import x, y, t >>> C = CoordSys3D('C') >>> region = ParametricRegion((t, t**2), (t, 1, 5)) >>> vector_integrate(C.x*C.i, region) 12 Integrals over some objects of geometry module can also be calculated. >>> from sympy.geometry import Point, Circle, Triangle >>> c = Circle(Point(0, 2), 5) >>> vector_integrate(C.x**2 + C.y**2, c) 290*pi >>> triangle = Triangle(Point(-2, 3), Point(2, 3), Point(0, 5)) >>> vector_integrate(3*C.x**2*C.y*C.i + C.j, triangle) -8 Integrals over some simple implicit regions can be computed. But in most cases, it takes too long to compute over them. This is due to the expressions of parametric representation becoming large. >>> from sympy.vector import ImplicitRegion >>> c2 = ImplicitRegion((x, y), (x - 2)**2 + (y - 1)**2 - 9) >>> vector_integrate(1, c2) 6*pi Integral of fields with respect to base scalars: >>> vector_integrate(12*C.y**3, (C.y, 1, 3)) 240 >>> vector_integrate(C.x**2*C.z, C.x) C.x**3*C.z/3 >>> vector_integrate(C.x*C.i - C.y*C.k, C.x) (Integral(C.x, C.x))*C.i + (Integral(-C.y, C.x))*C.k >>> _.doit() C.x**2/2*C.i + (-C.x*C.y)*C.k """ if len(region) == 1: if isinstance(region[0], ParametricRegion): return ParametricIntegral(field, region[0]) if isinstance(region[0], ImplicitRegion): region = parametric_region_list(region[0])[0] return vector_integrate(field, region) if isinstance(region[0], GeometryEntity): regions_list = parametric_region_list(region[0]) result = 0 for reg in regions_list: result += vector_integrate(field, reg) return result return integrate(field, *region)
3ec4752328ba254cf386590b00b3e84dab52a0276b03bf39e5fbaf6c7653e2ed
"""Parabolic geometrical entity. Contains * Parabola """ from sympy.core import S from sympy.core.sorting import ordered from sympy.core.symbol import _symbol, symbols from sympy.geometry.entity import GeometryEntity, GeometrySet from sympy.geometry.point import Point, Point2D from sympy.geometry.line import Line, Line2D, Ray2D, Segment2D, LinearEntity3D from sympy.geometry.ellipse import Ellipse from sympy.functions import sign from sympy.simplify import simplify from sympy.solvers.solvers import solve class Parabola(GeometrySet): """A parabolic GeometryEntity. A parabola is declared with a point, that is called 'focus', and a line, that is called 'directrix'. Only vertical or horizontal parabolas are currently supported. Parameters ========== focus : Point Default value is Point(0, 0) directrix : Line Attributes ========== focus directrix axis of symmetry focal length p parameter vertex eccentricity Raises ====== ValueError When `focus` is not a two dimensional point. When `focus` is a point of directrix. NotImplementedError When `directrix` is neither horizontal nor vertical. Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8))) >>> p1.focus Point2D(0, 0) >>> p1.directrix Line2D(Point2D(5, 8), Point2D(7, 8)) """ def __new__(cls, focus=None, directrix=None, **kwargs): if focus: focus = Point(focus, dim=2) else: focus = Point(0, 0) directrix = Line(directrix) if directrix.contains(focus): raise ValueError('The focus must not be a point of directrix') return GeometryEntity.__new__(cls, focus, directrix, **kwargs) @property def ambient_dimension(self): """Returns the ambient dimension of parabola. Returns ======= ambient_dimension : integer Examples ======== >>> from sympy import Parabola, Point, Line >>> f1 = Point(0, 0) >>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8))) >>> p1.ambient_dimension 2 """ return 2 @property def axis_of_symmetry(self): """Return the axis of symmetry of the parabola: a line perpendicular to the directrix passing through the focus. Returns ======= axis_of_symmetry : Line See Also ======== sympy.geometry.line.Line Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8))) >>> p1.axis_of_symmetry Line2D(Point2D(0, 0), Point2D(0, 1)) """ return self.directrix.perpendicular_line(self.focus) @property def directrix(self): """The directrix of the parabola. Returns ======= directrix : Line See Also ======== sympy.geometry.line.Line Examples ======== >>> from sympy import Parabola, Point, Line >>> l1 = Line(Point(5, 8), Point(7, 8)) >>> p1 = Parabola(Point(0, 0), l1) >>> p1.directrix Line2D(Point2D(5, 8), Point2D(7, 8)) """ return self.args[1] @property def eccentricity(self): """The eccentricity of the parabola. Returns ======= eccentricity : number A parabola may also be characterized as a conic section with an eccentricity of 1. As a consequence of this, all parabolas are similar, meaning that while they can be different sizes, they are all the same shape. See Also ======== https://en.wikipedia.org/wiki/Parabola Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8))) >>> p1.eccentricity 1 Notes ----- The eccentricity for every Parabola is 1 by definition. """ return S.One def equation(self, x='x', y='y'): """The equation of the parabola. Parameters ========== x : str, optional Label for the x-axis. Default value is 'x'. y : str, optional Label for the y-axis. Default value is 'y'. Returns ======= equation : SymPy expression Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8))) >>> p1.equation() -x**2 - 16*y + 64 >>> p1.equation('f') -f**2 - 16*y + 64 >>> p1.equation(y='z') -x**2 - 16*z + 64 """ x = _symbol(x, real=True) y = _symbol(y, real=True) m = self.directrix.slope if m is S.Infinity: t1 = 4 * (self.p_parameter) * (x - self.vertex.x) t2 = (y - self.vertex.y)**2 elif m == 0: t1 = 4 * (self.p_parameter) * (y - self.vertex.y) t2 = (x - self.vertex.x)**2 else: a, b = self.focus c, d = self.directrix.coefficients[:2] t1 = (x - a)**2 + (y - b)**2 t2 = self.directrix.equation(x, y)**2/(c**2 + d**2) return t1 - t2 @property def focal_length(self): """The focal length of the parabola. Returns ======= focal_lenght : number or symbolic expression Notes ===== The distance between the vertex and the focus (or the vertex and directrix), measured along the axis of symmetry, is the "focal length". See Also ======== https://en.wikipedia.org/wiki/Parabola Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8))) >>> p1.focal_length 4 """ distance = self.directrix.distance(self.focus) focal_length = distance/2 return focal_length @property def focus(self): """The focus of the parabola. Returns ======= focus : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Parabola, Point, Line >>> f1 = Point(0, 0) >>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8))) >>> p1.focus Point2D(0, 0) """ return self.args[0] def intersection(self, o): """The intersection of the parabola and another geometrical entity `o`. Parameters ========== o : GeometryEntity, LinearEntity Returns ======= intersection : list of GeometryEntity objects Examples ======== >>> from sympy import Parabola, Point, Ellipse, Line, Segment >>> p1 = Point(0,0) >>> l1 = Line(Point(1, -2), Point(-1,-2)) >>> parabola1 = Parabola(p1, l1) >>> parabola1.intersection(Ellipse(Point(0, 0), 2, 5)) [Point2D(-2, 0), Point2D(2, 0)] >>> parabola1.intersection(Line(Point(-7, 3), Point(12, 3))) [Point2D(-4, 3), Point2D(4, 3)] >>> parabola1.intersection(Segment((-12, -65), (14, -68))) [] """ x, y = symbols('x y', real=True) parabola_eq = self.equation() if isinstance(o, Parabola): if o in self: return [o] else: return list(ordered([Point(i) for i in solve([parabola_eq, o.equation()], [x, y])])) elif isinstance(o, Point2D): if simplify(parabola_eq.subs([(x, o._args[0]), (y, o._args[1])])) == 0: return [o] else: return [] elif isinstance(o, (Segment2D, Ray2D)): result = solve([parabola_eq, Line2D(o.points[0], o.points[1]).equation()], [x, y]) return list(ordered([Point2D(i) for i in result if i in o])) elif isinstance(o, (Line2D, Ellipse)): return list(ordered([Point2D(i) for i in solve([parabola_eq, o.equation()], [x, y])])) elif isinstance(o, LinearEntity3D): raise TypeError('Entity must be two dimensional, not three dimensional') else: raise TypeError('Wrong type of argument were put') @property def p_parameter(self): """P is a parameter of parabola. Returns ======= p : number or symbolic expression Notes ===== The absolute value of p is the focal length. The sign on p tells which way the parabola faces. Vertical parabolas that open up and horizontal that open right, give a positive value for p. Vertical parabolas that open down and horizontal that open left, give a negative value for p. See Also ======== http://www.sparknotes.com/math/precalc/conicsections/section2.rhtml Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8))) >>> p1.p_parameter -4 """ m = self.directrix.slope if m is S.Infinity: x = self.directrix.coefficients[2] p = sign(self.focus.args[0] + x) elif m == 0: y = self.directrix.coefficients[2] p = sign(self.focus.args[1] + y) else: d = self.directrix.projection(self.focus) p = sign(self.focus.x - d.x) return p * self.focal_length @property def vertex(self): """The vertex of the parabola. Returns ======= vertex : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Parabola, Point, Line >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8))) >>> p1.vertex Point2D(0, 4) """ focus = self.focus m = self.directrix.slope if m is S.Infinity: vertex = Point(focus.args[0] - self.p_parameter, focus.args[1]) elif m == 0: vertex = Point(focus.args[0], focus.args[1] - self.p_parameter) else: vertex = self.axis_of_symmetry.intersection(self)[0] return vertex
58ec8b7c9ff2efb303f37308e05c9d2cb86ccff0c7280056a52a9952708e20e1
"""Curves in 2-dimensional Euclidean space. Contains ======== Curve """ from sympy.functions.elementary.miscellaneous import sqrt from sympy.core import sympify, diff from sympy.core.containers import Tuple from sympy.core.symbol import _symbol from sympy.geometry.entity import GeometryEntity, GeometrySet from sympy.geometry.point import Point from sympy.integrals import integrate from sympy.matrices import Matrix, rot_axis3 from sympy.utilities.iterables import is_sequence from mpmath.libmp.libmpf import prec_to_dps class Curve(GeometrySet): """A curve in space. A curve is defined by parametric functions for the coordinates, a parameter and the lower and upper bounds for the parameter value. Parameters ========== function : list of functions limits : 3-tuple Function parameter and lower and upper bounds. Attributes ========== functions parameter limits Raises ====== ValueError When `functions` are specified incorrectly. When `limits` are specified incorrectly. Examples ======== >>> from sympy import Curve, sin, cos, interpolate >>> from sympy.abc import t, a >>> C = Curve((sin(t), cos(t)), (t, 0, 2)) >>> C.functions (sin(t), cos(t)) >>> C.limits (t, 0, 2) >>> C.parameter t >>> C = Curve((t, interpolate([1, 4, 9, 16], t)), (t, 0, 1)); C Curve((t, t**2), (t, 0, 1)) >>> C.subs(t, 4) Point2D(4, 16) >>> C.arbitrary_point(a) Point2D(a, a**2) See Also ======== sympy.core.function.Function sympy.polys.polyfuncs.interpolate """ def __new__(cls, function, limits): fun = sympify(function) if not is_sequence(fun) or len(fun) != 2: raise ValueError("Function argument should be (x(t), y(t)) " "but got %s" % str(function)) if not is_sequence(limits) or len(limits) != 3: raise ValueError("Limit argument should be (t, tmin, tmax) " "but got %s" % str(limits)) return GeometryEntity.__new__(cls, Tuple(*fun), Tuple(*limits)) def __call__(self, f): return self.subs(self.parameter, f) def _eval_subs(self, old, new): if old == self.parameter: return Point(*[f.subs(old, new) for f in self.functions]) def _eval_evalf(self, prec=15, **options): f, (t, a, b) = self.args dps = prec_to_dps(prec) f = tuple([i.evalf(n=dps, **options) for i in f]) a, b = [i.evalf(n=dps, **options) for i in (a, b)] return self.func(f, (t, a, b)) def arbitrary_point(self, parameter='t'): """A parameterized point on the curve. Parameters ========== parameter : str or Symbol, optional Default value is 't'. The Curve's parameter is selected with None or self.parameter otherwise the provided symbol is used. Returns ======= Point : Returns a point in parametric form. Raises ====== ValueError When `parameter` already appears in the functions. Examples ======== >>> from sympy import Curve, Symbol >>> from sympy.abc import s >>> C = Curve([2*s, s**2], (s, 0, 2)) >>> C.arbitrary_point() Point2D(2*t, t**2) >>> C.arbitrary_point(C.parameter) Point2D(2*s, s**2) >>> C.arbitrary_point(None) Point2D(2*s, s**2) >>> C.arbitrary_point(Symbol('a')) Point2D(2*a, a**2) See Also ======== sympy.geometry.point.Point """ if parameter is None: return Point(*self.functions) tnew = _symbol(parameter, self.parameter, real=True) t = self.parameter if (tnew.name != t.name and tnew.name in (f.name for f in self.free_symbols)): raise ValueError('Symbol %s already appears in object ' 'and cannot be used as a parameter.' % tnew.name) return Point(*[w.subs(t, tnew) for w in self.functions]) @property def free_symbols(self): """Return a set of symbols other than the bound symbols used to parametrically define the Curve. Returns ======= set : Set of all non-parameterized symbols. Examples ======== >>> from sympy.abc import t, a >>> from sympy import Curve >>> Curve((t, t**2), (t, 0, 2)).free_symbols set() >>> Curve((t, t**2), (t, a, 2)).free_symbols {a} """ free = set() for a in self.functions + self.limits[1:]: free |= a.free_symbols free = free.difference({self.parameter}) return free @property def ambient_dimension(self): """The dimension of the curve. Returns ======= int : the dimension of curve. Examples ======== >>> from sympy.abc import t >>> from sympy import Curve >>> C = Curve((t, t**2), (t, 0, 2)) >>> C.ambient_dimension 2 """ return len(self.args[0]) @property def functions(self): """The functions specifying the curve. Returns ======= functions : list of parameterized coordinate functions. Examples ======== >>> from sympy.abc import t >>> from sympy import Curve >>> C = Curve((t, t**2), (t, 0, 2)) >>> C.functions (t, t**2) See Also ======== parameter """ return self.args[0] @property def limits(self): """The limits for the curve. Returns ======= limits : tuple Contains parameter and lower and upper limits. Examples ======== >>> from sympy.abc import t >>> from sympy import Curve >>> C = Curve([t, t**3], (t, -2, 2)) >>> C.limits (t, -2, 2) See Also ======== plot_interval """ return self.args[1] @property def parameter(self): """The curve function variable. Returns ======= Symbol : returns a bound symbol. Examples ======== >>> from sympy.abc import t >>> from sympy import Curve >>> C = Curve([t, t**2], (t, 0, 2)) >>> C.parameter t See Also ======== functions """ return self.args[1][0] @property def length(self): """The curve length. Examples ======== >>> from sympy import Curve >>> from sympy.abc import t >>> Curve((t, t), (t, 0, 1)).length sqrt(2) """ integrand = sqrt(sum(diff(func, self.limits[0])**2 for func in self.functions)) return integrate(integrand, self.limits) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the curve. Parameters ========== parameter : str or Symbol, optional Default value is 't'; otherwise the provided symbol is used. Returns ======= List : the plot interval as below: [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Curve, sin >>> from sympy.abc import x, s >>> Curve((x, sin(x)), (x, 1, 2)).plot_interval() [t, 1, 2] >>> Curve((x, sin(x)), (x, 1, 2)).plot_interval(s) [s, 1, 2] See Also ======== limits : Returns limits of the parameter interval """ t = _symbol(parameter, self.parameter, real=True) return [t] + list(self.limits[1:]) def rotate(self, angle=0, pt=None): """This function is used to rotate a curve along given point ``pt`` at given angle(in radian). Parameters ========== angle : the angle at which the curve will be rotated(in radian) in counterclockwise direction. default value of angle is 0. pt : Point the point along which the curve will be rotated. If no point given, the curve will be rotated around origin. Returns ======= Curve : returns a curve rotated at given angle along given point. Examples ======== >>> from sympy import Curve, pi >>> from sympy.abc import x >>> Curve((x, x), (x, 0, 1)).rotate(pi/2) Curve((-x, x), (x, 0, 1)) """ if pt: pt = -Point(pt, dim=2) else: pt = Point(0,0) rv = self.translate(*pt.args) f = list(rv.functions) f.append(0) f = Matrix(1, 3, f) f *= rot_axis3(angle) rv = self.func(f[0, :2].tolist()[0], self.limits) pt = -pt return rv.translate(*pt.args) def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since Curve is not made up of Points. Returns ======= Curve : returns scaled curve. Examples ======== >>> from sympy import Curve >>> from sympy.abc import x >>> Curve((x, x), (x, 0, 1)).scale(2) Curve((2*x, x), (x, 0, 1)) """ if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) fx, fy = self.functions return self.func((fx*x, fy*y), self.limits) def translate(self, x=0, y=0): """Translate the Curve by (x, y). Returns ======= Curve : returns a translated curve. Examples ======== >>> from sympy import Curve >>> from sympy.abc import x >>> Curve((x, x), (x, 0, 1)).translate(1, 2) Curve((x + 1, x + 2), (x, 0, 1)) """ fx, fy = self.functions return self.func((fx + x, fy + y), self.limits)
e0cd9e4eb0198cd5ffe91704ec19a1bfe1c989eb576e857a93f6e75e56f59921
"""Geometrical Points. Contains ======== Point Point2D Point3D When methods of Point require 1 or more points as arguments, they can be passed as a sequence of coordinates or Points: >>> from sympy import Point >>> Point(1, 1).is_collinear((2, 2), (3, 4)) False >>> Point(1, 1).is_collinear(Point(2, 2), Point(3, 4)) False """ import warnings from sympy.core import S, sympify, Expr from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.numbers import Float from sympy.core.parameters import global_parameters from sympy.simplify import nsimplify, simplify from sympy.geometry.exceptions import GeometryError from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.complexes import im from sympy.functions.elementary.trigonometric import cos, sin from sympy.matrices import Matrix from sympy.matrices.expressions import Transpose from sympy.utilities.iterables import uniq, is_sequence from sympy.utilities.misc import filldedent, func_name, Undecidable from .entity import GeometryEntity from mpmath.libmp.libmpf import prec_to_dps class Point(GeometryEntity): """A point in a n-dimensional Euclidean space. Parameters ========== coords : sequence of n-coordinate values. In the special case where n=2 or 3, a Point2D or Point3D will be created as appropriate. evaluate : if `True` (default), all floats are turn into exact types. dim : number of coordinates the point should have. If coordinates are unspecified, they are padded with zeros. on_morph : indicates what should happen when the number of coordinates of a point need to be changed by adding or removing zeros. Possible values are `'warn'`, `'error'`, or `ignore` (default). No warning or error is given when `*args` is empty and `dim` is given. An error is always raised when trying to remove nonzero coordinates. Attributes ========== length origin: A `Point` representing the origin of the appropriately-dimensioned space. Raises ====== TypeError : When instantiating with anything but a Point or sequence ValueError : when instantiating with a sequence with length < 2 or when trying to reduce dimensions if keyword `on_morph='error'` is set. See Also ======== sympy.geometry.line.Segment : Connects two Points Examples ======== >>> from sympy import Point >>> from sympy.abc import x >>> Point(1, 2, 3) Point3D(1, 2, 3) >>> Point([1, 2]) Point2D(1, 2) >>> Point(0, x) Point2D(0, x) >>> Point(dim=4) Point(0, 0, 0, 0) Floats are automatically converted to Rational unless the evaluate flag is False: >>> Point(0.5, 0.25) Point2D(1/2, 1/4) >>> Point(0.5, 0.25, evaluate=False) Point2D(0.5, 0.25) """ is_Point = True def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) on_morph = kwargs.get('on_morph', 'ignore') # unpack into coords coords = args[0] if len(args) == 1 else args # check args and handle quickly handle Point instances if isinstance(coords, Point): # even if we're mutating the dimension of a point, we # don't reevaluate its coordinates evaluate = False if len(coords) == kwargs.get('dim', len(coords)): return coords if not is_sequence(coords): raise TypeError(filldedent(''' Expecting sequence of coordinates, not `{}`''' .format(func_name(coords)))) # A point where only `dim` is specified is initialized # to zeros. if len(coords) == 0 and kwargs.get('dim', None): coords = (S.Zero,)*kwargs.get('dim') coords = Tuple(*coords) dim = kwargs.get('dim', len(coords)) if len(coords) < 2: raise ValueError(filldedent(''' Point requires 2 or more coordinates or keyword `dim` > 1.''')) if len(coords) != dim: message = ("Dimension of {} needs to be changed " "from {} to {}.").format(coords, len(coords), dim) if on_morph == 'ignore': pass elif on_morph == "error": raise ValueError(message) elif on_morph == 'warn': warnings.warn(message, stacklevel=2) else: raise ValueError(filldedent(''' on_morph value should be 'error', 'warn' or 'ignore'.''')) if any(coords[dim:]): raise ValueError('Nonzero coordinates cannot be removed.') if any(a.is_number and im(a).is_zero is False for a in coords): raise ValueError('Imaginary coordinates are not permitted.') if not all(isinstance(a, Expr) for a in coords): raise TypeError('Coordinates must be valid SymPy expressions.') # pad with zeros appropriately coords = coords[:dim] + (S.Zero,)*(dim - len(coords)) # Turn any Floats into rationals and simplify # any expressions before we instantiate if evaluate: coords = coords.xreplace({ f: simplify(nsimplify(f, rational=True)) for f in coords.atoms(Float)}) # return 2D or 3D instances if len(coords) == 2: kwargs['_nocheck'] = True return Point2D(*coords, **kwargs) elif len(coords) == 3: kwargs['_nocheck'] = True return Point3D(*coords, **kwargs) # the general Point return GeometryEntity.__new__(cls, *coords) def __abs__(self): """Returns the distance between this point and the origin.""" origin = Point([0]*len(self)) return Point.distance(origin, self) def __add__(self, other): """Add other to self by incrementing self's coordinates by those of other. Notes ===== >>> from sympy import Point When sequences of coordinates are passed to Point methods, they are converted to a Point internally. This __add__ method does not do that so if floating point values are used, a floating point result (in terms of SymPy Floats) will be returned. >>> Point(1, 2) + (.1, .2) Point2D(1.1, 2.2) If this is not desired, the `translate` method can be used or another Point can be added: >>> Point(1, 2).translate(.1, .2) Point2D(11/10, 11/5) >>> Point(1, 2) + Point(.1, .2) Point2D(11/10, 11/5) See Also ======== sympy.geometry.point.Point.translate """ try: s, o = Point._normalize_dimension(self, Point(other, evaluate=False)) except TypeError: raise GeometryError("Don't know how to add {} and a Point object".format(other)) coords = [simplify(a + b) for a, b in zip(s, o)] return Point(coords, evaluate=False) def __contains__(self, item): return item in self.args def __truediv__(self, divisor): """Divide point's coordinates by a factor.""" divisor = sympify(divisor) coords = [simplify(x/divisor) for x in self.args] return Point(coords, evaluate=False) def __eq__(self, other): if not isinstance(other, Point) or len(self.args) != len(other.args): return False return self.args == other.args def __getitem__(self, key): return self.args[key] def __hash__(self): return hash(self.args) def __iter__(self): return self.args.__iter__() def __len__(self): return len(self.args) def __mul__(self, factor): """Multiply point's coordinates by a factor. Notes ===== >>> from sympy import Point When multiplying a Point by a floating point number, the coordinates of the Point will be changed to Floats: >>> Point(1, 2)*0.1 Point2D(0.1, 0.2) If this is not desired, the `scale` method can be used or else only multiply or divide by integers: >>> Point(1, 2).scale(1.1, 1.1) Point2D(11/10, 11/5) >>> Point(1, 2)*11/10 Point2D(11/10, 11/5) See Also ======== sympy.geometry.point.Point.scale """ factor = sympify(factor) coords = [simplify(x*factor) for x in self.args] return Point(coords, evaluate=False) def __rmul__(self, factor): """Multiply a factor by point's coordinates.""" return self.__mul__(factor) def __neg__(self): """Negate the point.""" coords = [-x for x in self.args] return Point(coords, evaluate=False) def __sub__(self, other): """Subtract two points, or subtract a factor from this point's coordinates.""" return self + [-x for x in other] @classmethod def _normalize_dimension(cls, *points, **kwargs): """Ensure that points have the same dimension. By default `on_morph='warn'` is passed to the `Point` constructor.""" # if we have a built-in ambient dimension, use it dim = getattr(cls, '_ambient_dimension', None) # override if we specified it dim = kwargs.get('dim', dim) # if no dim was given, use the highest dimensional point if dim is None: dim = max(i.ambient_dimension for i in points) if all(i.ambient_dimension == dim for i in points): return list(points) kwargs['dim'] = dim kwargs['on_morph'] = kwargs.get('on_morph', 'warn') return [Point(i, **kwargs) for i in points] @staticmethod def affine_rank(*args): """The affine rank of a set of points is the dimension of the smallest affine space containing all the points. For example, if the points lie on a line (and are not all the same) their affine rank is 1. If the points lie on a plane but not a line, their affine rank is 2. By convention, the empty set has affine rank -1.""" if len(args) == 0: return -1 # make sure we're genuinely points # and translate every point to the origin points = Point._normalize_dimension(*[Point(i) for i in args]) origin = points[0] points = [i - origin for i in points[1:]] m = Matrix([i.args for i in points]) # XXX fragile -- what is a better way? return m.rank(iszerofunc = lambda x: abs(x.n(2)) < 1e-12 if x.is_number else x.is_zero) @property def ambient_dimension(self): """Number of components this point has.""" return getattr(self, '_ambient_dimension', len(self)) @classmethod def are_coplanar(cls, *points): """Return True if there exists a plane in which all the points lie. A trivial True value is returned if `len(points) < 3` or all Points are 2-dimensional. Parameters ========== A set of points Raises ====== ValueError : if less than 3 unique points are given Returns ======= boolean Examples ======== >>> from sympy import Point3D >>> p1 = Point3D(1, 2, 2) >>> p2 = Point3D(2, 7, 2) >>> p3 = Point3D(0, 0, 2) >>> p4 = Point3D(1, 1, 2) >>> Point3D.are_coplanar(p1, p2, p3, p4) True >>> p5 = Point3D(0, 1, 3) >>> Point3D.are_coplanar(p1, p2, p3, p5) False """ if len(points) <= 1: return True points = cls._normalize_dimension(*[Point(i) for i in points]) # quick exit if we are in 2D if points[0].ambient_dimension == 2: return True points = list(uniq(points)) return Point.affine_rank(*points) <= 2 def distance(self, other): """The Euclidean distance between self and another GeometricEntity. Returns ======= distance : number or symbolic expression. Raises ====== TypeError : if other is not recognized as a GeometricEntity or is a GeometricEntity for which distance is not defined. See Also ======== sympy.geometry.line.Segment.length sympy.geometry.point.Point.taxicab_distance Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(1, 1), Point(4, 5) >>> l = Line((3, 1), (2, 2)) >>> p1.distance(p2) 5 >>> p1.distance(l) sqrt(2) The computed distance may be symbolic, too: >>> from sympy.abc import x, y >>> p3 = Point(x, y) >>> p3.distance((0, 0)) sqrt(x**2 + y**2) """ if not isinstance(other, GeometryEntity): try: other = Point(other, dim=self.ambient_dimension) except TypeError: raise TypeError("not recognized as a GeometricEntity: %s" % type(other)) if isinstance(other, Point): s, p = Point._normalize_dimension(self, Point(other)) return sqrt(Add(*((a - b)**2 for a, b in zip(s, p)))) distance = getattr(other, 'distance', None) if distance is None: raise TypeError("distance between Point and %s is not defined" % type(other)) return distance(self) def dot(self, p): """Return dot product of self with another Point.""" if not is_sequence(p): p = Point(p) # raise the error via Point return Add(*(a*b for a, b in zip(self, p))) def equals(self, other): """Returns whether the coordinates of self and other agree.""" # a point is equal to another point if all its components are equal if not isinstance(other, Point) or len(self) != len(other): return False return all(a.equals(b) for a, b in zip(self, other)) def _eval_evalf(self, prec=15, **options): """Evaluate the coordinates of the point. This method will, where possible, create and return a new Point where the coordinates are evaluated as floating point numbers to the precision indicated (default=15). Parameters ========== prec : int Returns ======= point : Point Examples ======== >>> from sympy import Point, Rational >>> p1 = Point(Rational(1, 2), Rational(3, 2)) >>> p1 Point2D(1/2, 3/2) >>> p1.evalf() Point2D(0.5, 1.5) """ dps = prec_to_dps(prec) coords = [x.evalf(n=dps, **options) for x in self.args] return Point(*coords, evaluate=False) def intersection(self, other): """The intersection between this point and another GeometryEntity. Parameters ========== other : GeometryEntity or sequence of coordinates Returns ======= intersection : list of Points Notes ===== The return value will either be an empty list if there is no intersection, otherwise it will contain this point. Examples ======== >>> from sympy import Point >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 0) >>> p1.intersection(p2) [] >>> p1.intersection(p3) [Point2D(0, 0)] """ if not isinstance(other, GeometryEntity): other = Point(other) if isinstance(other, Point): if self == other: return [self] p1, p2 = Point._normalize_dimension(self, other) if p1 == self and p1 == p2: return [self] return [] return other.intersection(self) def is_collinear(self, *args): """Returns `True` if there exists a line that contains `self` and `points`. Returns `False` otherwise. A trivially True value is returned if no points are given. Parameters ========== args : sequence of Points Returns ======= is_collinear : boolean See Also ======== sympy.geometry.line.Line Examples ======== >>> from sympy import Point >>> from sympy.abc import x >>> p1, p2 = Point(0, 0), Point(1, 1) >>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2) >>> Point.is_collinear(p1, p2, p3, p4) True >>> Point.is_collinear(p1, p2, p3, p5) False """ points = (self,) + args points = Point._normalize_dimension(*[Point(i) for i in points]) points = list(uniq(points)) return Point.affine_rank(*points) <= 1 def is_concyclic(self, *args): """Do `self` and the given sequence of points lie in a circle? Returns True if the set of points are concyclic and False otherwise. A trivial value of True is returned if there are fewer than 2 other points. Parameters ========== args : sequence of Points Returns ======= is_concyclic : boolean Examples ======== >>> from sympy import Point Define 4 points that are on the unit circle: >>> p1, p2, p3, p4 = Point(1, 0), (0, 1), (-1, 0), (0, -1) >>> p1.is_concyclic() == p1.is_concyclic(p2, p3, p4) == True True Define a point not on that circle: >>> p = Point(1, 1) >>> p.is_concyclic(p1, p2, p3) False """ points = (self,) + args points = Point._normalize_dimension(*[Point(i) for i in points]) points = list(uniq(points)) if not Point.affine_rank(*points) <= 2: return False origin = points[0] points = [p - origin for p in points] # points are concyclic if they are coplanar and # there is a point c so that ||p_i-c|| == ||p_j-c|| for all # i and j. Rearranging this equation gives us the following # condition: the matrix `mat` must not a pivot in the last # column. mat = Matrix([list(i) + [i.dot(i)] for i in points]) rref, pivots = mat.rref() if len(origin) not in pivots: return True return False @property def is_nonzero(self): """True if any coordinate is nonzero, False if every coordinate is zero, and None if it cannot be determined.""" is_zero = self.is_zero if is_zero is None: return None return not is_zero def is_scalar_multiple(self, p): """Returns whether each coordinate of `self` is a scalar multiple of the corresponding coordinate in point p. """ s, o = Point._normalize_dimension(self, Point(p)) # 2d points happen a lot, so optimize this function call if s.ambient_dimension == 2: (x1, y1), (x2, y2) = s.args, o.args rv = (x1*y2 - x2*y1).equals(0) if rv is None: raise Undecidable(filldedent( '''Cannot determine if %s is a scalar multiple of %s''' % (s, o))) # if the vectors p1 and p2 are linearly dependent, then they must # be scalar multiples of each other m = Matrix([s.args, o.args]) return m.rank() < 2 @property def is_zero(self): """True if every coordinate is zero, False if any coordinate is not zero, and None if it cannot be determined.""" nonzero = [x.is_nonzero for x in self.args] if any(nonzero): return False if any(x is None for x in nonzero): return None return True @property def length(self): """ Treating a Point as a Line, this returns 0 for the length of a Point. Examples ======== >>> from sympy import Point >>> p = Point(0, 1) >>> p.length 0 """ return S.Zero def midpoint(self, p): """The midpoint between self and point p. Parameters ========== p : Point Returns ======= midpoint : Point See Also ======== sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy import Point >>> p1, p2 = Point(1, 1), Point(13, 5) >>> p1.midpoint(p2) Point2D(7, 3) """ s, p = Point._normalize_dimension(self, Point(p)) return Point([simplify((a + b)*S.Half) for a, b in zip(s, p)]) @property def origin(self): """A point of all zeros of the same ambient dimension as the current point""" return Point([0]*len(self), evaluate=False) @property def orthogonal_direction(self): """Returns a non-zero point that is orthogonal to the line containing `self` and the origin. Examples ======== >>> from sympy import Line, Point >>> a = Point(1, 2, 3) >>> a.orthogonal_direction Point3D(-2, 1, 0) >>> b = _ >>> Line(b, b.origin).is_perpendicular(Line(a, a.origin)) True """ dim = self.ambient_dimension # if a coordinate is zero, we can put a 1 there and zeros elsewhere if self[0].is_zero: return Point([1] + (dim - 1)*[0]) if self[1].is_zero: return Point([0,1] + (dim - 2)*[0]) # if the first two coordinates aren't zero, we can create a non-zero # orthogonal vector by swapping them, negating one, and padding with zeros return Point([-self[1], self[0]] + (dim - 2)*[0]) @staticmethod def project(a, b): """Project the point `a` onto the line between the origin and point `b` along the normal direction. Parameters ========== a : Point b : Point Returns ======= p : Point See Also ======== sympy.geometry.line.LinearEntity.projection Examples ======== >>> from sympy import Line, Point >>> a = Point(1, 2) >>> b = Point(2, 5) >>> z = a.origin >>> p = Point.project(a, b) >>> Line(p, a).is_perpendicular(Line(p, b)) True >>> Point.is_collinear(z, p, b) True """ a, b = Point._normalize_dimension(Point(a), Point(b)) if b.is_zero: raise ValueError("Cannot project to the zero vector.") return b*(a.dot(b) / b.dot(b)) def taxicab_distance(self, p): """The Taxicab Distance from self to point p. Returns the sum of the horizontal and vertical distances to point p. Parameters ========== p : Point Returns ======= taxicab_distance : The sum of the horizontal and vertical distances to point p. See Also ======== sympy.geometry.point.Point.distance Examples ======== >>> from sympy import Point >>> p1, p2 = Point(1, 1), Point(4, 5) >>> p1.taxicab_distance(p2) 7 """ s, p = Point._normalize_dimension(self, Point(p)) return Add(*(abs(a - b) for a, b in zip(s, p))) def canberra_distance(self, p): """The Canberra Distance from self to point p. Returns the weighted sum of horizontal and vertical distances to point p. Parameters ========== p : Point Returns ======= canberra_distance : The weighted sum of horizontal and vertical distances to point p. The weight used is the sum of absolute values of the coordinates. Examples ======== >>> from sympy import Point >>> p1, p2 = Point(1, 1), Point(3, 3) >>> p1.canberra_distance(p2) 1 >>> p1, p2 = Point(0, 0), Point(3, 3) >>> p1.canberra_distance(p2) 2 Raises ====== ValueError when both vectors are zero. See Also ======== sympy.geometry.point.Point.distance """ s, p = Point._normalize_dimension(self, Point(p)) if self.is_zero and p.is_zero: raise ValueError("Cannot project to the zero vector.") return Add(*((abs(a - b)/(abs(a) + abs(b))) for a, b in zip(s, p))) @property def unit(self): """Return the Point that is in the same direction as `self` and a distance of 1 from the origin""" return self / abs(self) class Point2D(Point): """A point in a 2-dimensional Euclidean space. Parameters ========== coords : sequence of 2 coordinate values. Attributes ========== x y length Raises ====== TypeError When trying to add or subtract points with different dimensions. When trying to create a point with more than two dimensions. When `intersection` is called with object other than a Point. See Also ======== sympy.geometry.line.Segment : Connects two Points Examples ======== >>> from sympy import Point2D >>> from sympy.abc import x >>> Point2D(1, 2) Point2D(1, 2) >>> Point2D([1, 2]) Point2D(1, 2) >>> Point2D(0, x) Point2D(0, x) Floats are automatically converted to Rational unless the evaluate flag is False: >>> Point2D(0.5, 0.25) Point2D(1/2, 1/4) >>> Point2D(0.5, 0.25, evaluate=False) Point2D(0.5, 0.25) """ _ambient_dimension = 2 def __new__(cls, *args, _nocheck=False, **kwargs): if not _nocheck: kwargs['dim'] = 2 args = Point(*args, **kwargs) return GeometryEntity.__new__(cls, *args) def __contains__(self, item): return item == self @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ return (self.x, self.y, self.x, self.y) def rotate(self, angle, pt=None): """Rotate ``angle`` radians counterclockwise about Point ``pt``. See Also ======== translate, scale Examples ======== >>> from sympy import Point2D, pi >>> t = Point2D(1, 0) >>> t.rotate(pi/2) Point2D(0, 1) >>> t.rotate(pi/2, (2, 0)) Point2D(2, -1) """ c = cos(angle) s = sin(angle) rv = self if pt is not None: pt = Point(pt, dim=2) rv -= pt x, y = rv.args rv = Point(c*x - s*y, s*x + c*y) if pt is not None: rv += pt return rv def scale(self, x=1, y=1, pt=None): """Scale the coordinates of the Point by multiplying by ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) -- and then adding ``pt`` back again (i.e. ``pt`` is the point of reference for the scaling). See Also ======== rotate, translate Examples ======== >>> from sympy import Point2D >>> t = Point2D(1, 1) >>> t.scale(2) Point2D(2, 1) >>> t.scale(2, 2) Point2D(2, 2) """ if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) return Point(self.x*x, self.y*y) def transform(self, matrix): """Return the point after applying the transformation described by the 3x3 Matrix, ``matrix``. See Also ======== sympy.geometry.point.Point2D.rotate sympy.geometry.point.Point2D.scale sympy.geometry.point.Point2D.translate """ if not (matrix.is_Matrix and matrix.shape == (3, 3)): raise ValueError("matrix must be a 3x3 matrix") x, y = self.args return Point(*(Matrix(1, 3, [x, y, 1])*matrix).tolist()[0][:2]) def translate(self, x=0, y=0): """Shift the Point by adding x and y to the coordinates of the Point. See Also ======== sympy.geometry.point.Point2D.rotate, scale Examples ======== >>> from sympy import Point2D >>> t = Point2D(0, 1) >>> t.translate(2) Point2D(2, 1) >>> t.translate(2, 2) Point2D(2, 3) >>> t + Point2D(2, 2) Point2D(2, 3) """ return Point(self.x + x, self.y + y) @property def coordinates(self): """ Returns the two coordinates of the Point. Examples ======== >>> from sympy import Point2D >>> p = Point2D(0, 1) >>> p.coordinates (0, 1) """ return self.args @property def x(self): """ Returns the X coordinate of the Point. Examples ======== >>> from sympy import Point2D >>> p = Point2D(0, 1) >>> p.x 0 """ return self.args[0] @property def y(self): """ Returns the Y coordinate of the Point. Examples ======== >>> from sympy import Point2D >>> p = Point2D(0, 1) >>> p.y 1 """ return self.args[1] class Point3D(Point): """A point in a 3-dimensional Euclidean space. Parameters ========== coords : sequence of 3 coordinate values. Attributes ========== x y z length Raises ====== TypeError When trying to add or subtract points with different dimensions. When `intersection` is called with object other than a Point. Examples ======== >>> from sympy import Point3D >>> from sympy.abc import x >>> Point3D(1, 2, 3) Point3D(1, 2, 3) >>> Point3D([1, 2, 3]) Point3D(1, 2, 3) >>> Point3D(0, x, 3) Point3D(0, x, 3) Floats are automatically converted to Rational unless the evaluate flag is False: >>> Point3D(0.5, 0.25, 2) Point3D(1/2, 1/4, 2) >>> Point3D(0.5, 0.25, 3, evaluate=False) Point3D(0.5, 0.25, 3) """ _ambient_dimension = 3 def __new__(cls, *args, _nocheck=False, **kwargs): if not _nocheck: kwargs['dim'] = 3 args = Point(*args, **kwargs) return GeometryEntity.__new__(cls, *args) def __contains__(self, item): return item == self @staticmethod def are_collinear(*points): """Is a sequence of points collinear? Test whether or not a set of points are collinear. Returns True if the set of points are collinear, or False otherwise. Parameters ========== points : sequence of Point Returns ======= are_collinear : boolean See Also ======== sympy.geometry.line.Line3D Examples ======== >>> from sympy import Point3D >>> from sympy.abc import x >>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1) >>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6) >>> Point3D.are_collinear(p1, p2, p3, p4) True >>> Point3D.are_collinear(p1, p2, p3, p5) False """ return Point.is_collinear(*points) def direction_cosine(self, point): """ Gives the direction cosine between 2 points Parameters ========== p : Point3D Returns ======= list Examples ======== >>> from sympy import Point3D >>> p1 = Point3D(1, 2, 3) >>> p1.direction_cosine(Point3D(2, 3, 5)) [sqrt(6)/6, sqrt(6)/6, sqrt(6)/3] """ a = self.direction_ratio(point) b = sqrt(Add(*(i**2 for i in a))) return [(point.x - self.x) / b,(point.y - self.y) / b, (point.z - self.z) / b] def direction_ratio(self, point): """ Gives the direction ratio between 2 points Parameters ========== p : Point3D Returns ======= list Examples ======== >>> from sympy import Point3D >>> p1 = Point3D(1, 2, 3) >>> p1.direction_ratio(Point3D(2, 3, 5)) [1, 1, 2] """ return [(point.x - self.x),(point.y - self.y),(point.z - self.z)] def intersection(self, other): """The intersection between this point and another GeometryEntity. Parameters ========== other : GeometryEntity or sequence of coordinates Returns ======= intersection : list of Points Notes ===== The return value will either be an empty list if there is no intersection, otherwise it will contain this point. Examples ======== >>> from sympy import Point3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 0, 0) >>> p1.intersection(p2) [] >>> p1.intersection(p3) [Point3D(0, 0, 0)] """ if not isinstance(other, GeometryEntity): other = Point(other, dim=3) if isinstance(other, Point3D): if self == other: return [self] return [] return other.intersection(self) def scale(self, x=1, y=1, z=1, pt=None): """Scale the coordinates of the Point by multiplying by ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) -- and then adding ``pt`` back again (i.e. ``pt`` is the point of reference for the scaling). See Also ======== translate Examples ======== >>> from sympy import Point3D >>> t = Point3D(1, 1, 1) >>> t.scale(2) Point3D(2, 1, 1) >>> t.scale(2, 2) Point3D(2, 2, 1) """ if pt: pt = Point3D(pt) return self.translate(*(-pt).args).scale(x, y, z).translate(*pt.args) return Point3D(self.x*x, self.y*y, self.z*z) def transform(self, matrix): """Return the point after applying the transformation described by the 4x4 Matrix, ``matrix``. See Also ======== sympy.geometry.point.Point3D.scale sympy.geometry.point.Point3D.translate """ if not (matrix.is_Matrix and matrix.shape == (4, 4)): raise ValueError("matrix must be a 4x4 matrix") x, y, z = self.args m = Transpose(matrix) return Point3D(*(Matrix(1, 4, [x, y, z, 1])*m).tolist()[0][:3]) def translate(self, x=0, y=0, z=0): """Shift the Point by adding x and y to the coordinates of the Point. See Also ======== scale Examples ======== >>> from sympy import Point3D >>> t = Point3D(0, 1, 1) >>> t.translate(2) Point3D(2, 1, 1) >>> t.translate(2, 2) Point3D(2, 3, 1) >>> t + Point3D(2, 2, 2) Point3D(2, 3, 3) """ return Point3D(self.x + x, self.y + y, self.z + z) @property def coordinates(self): """ Returns the three coordinates of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 2) >>> p.coordinates (0, 1, 2) """ return self.args @property def x(self): """ Returns the X coordinate of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 3) >>> p.x 0 """ return self.args[0] @property def y(self): """ Returns the Y coordinate of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 2) >>> p.y 1 """ return self.args[1] @property def z(self): """ Returns the Z coordinate of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 1) >>> p.z 1 """ return self.args[2]
4e05427bd085ef948af491dcf598d58143dfba0642b7705194117604e0482153
"""Geometrical Planes. Contains ======== Plane """ from sympy.core import Dummy, Rational, S, Symbol from sympy.core.symbol import _symbol from sympy.functions.elementary.trigonometric import cos, sin, acos, asin, sqrt from .entity import GeometryEntity from .line import (Line, Ray, Segment, Line3D, LinearEntity, LinearEntity3D, Ray3D, Segment3D) from .point import Point, Point3D from sympy.matrices import Matrix from sympy.polys.polytools import cancel from sympy.solvers import solve, linsolve from sympy.utilities.iterables import uniq, is_sequence from sympy.utilities.misc import filldedent, func_name, Undecidable from mpmath.libmp.libmpf import prec_to_dps import random class Plane(GeometryEntity): """ A plane is a flat, two-dimensional surface. A plane is the two-dimensional analogue of a point (zero-dimensions), a line (one-dimension) and a solid (three-dimensions). A plane can generally be constructed by two types of inputs. They are three non-collinear points and a point and the plane's normal vector. Attributes ========== p1 normal_vector Examples ======== >>> from sympy import Plane, Point3D >>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2)) Plane(Point3D(1, 1, 1), (-1, 2, -1)) >>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2)) Plane(Point3D(1, 1, 1), (-1, 2, -1)) >>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7)) Plane(Point3D(1, 1, 1), (1, 4, 7)) """ def __new__(cls, p1, a=None, b=None, **kwargs): p1 = Point3D(p1, dim=3) if a and b: p2 = Point(a, dim=3) p3 = Point(b, dim=3) if Point3D.are_collinear(p1, p2, p3): raise ValueError('Enter three non-collinear points') a = p1.direction_ratio(p2) b = p1.direction_ratio(p3) normal_vector = tuple(Matrix(a).cross(Matrix(b))) else: a = kwargs.pop('normal_vector', a) evaluate = kwargs.get('evaluate', True) if is_sequence(a) and len(a) == 3: normal_vector = Point3D(a).args if evaluate else a else: raise ValueError(filldedent(''' Either provide 3 3D points or a point with a normal vector expressed as a sequence of length 3''')) if all(coord.is_zero for coord in normal_vector): raise ValueError('Normal vector cannot be zero vector') return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs) def __contains__(self, o): x, y, z = map(Dummy, 'xyz') k = self.equation(x, y, z) if isinstance(o, (LinearEntity, LinearEntity3D)): t = Dummy() d = Point3D(o.arbitrary_point(t)) e = k.subs([(x, d.x), (y, d.y), (z, d.z)]) return e.equals(0) try: o = Point(o, dim=3, strict=True) d = k.xreplace(dict(zip((x, y, z), o.args))) return d.equals(0) except TypeError: return False def _eval_evalf(self, prec=15, **options): pt, tup = self.args dps = prec_to_dps(prec) pt = pt.evalf(n=dps, **options) tup = tuple([i.evalf(n=dps, **options) for i in tup]) return self.func(pt, normal_vector=tup, evaluate=False) def angle_between(self, o): """Angle between the plane and other geometric entity. Parameters ========== LinearEntity3D, Plane. Returns ======= angle : angle in radians Notes ===== This method accepts only 3D entities as it's parameter, but if you want to calculate the angle between a 2D entity and a plane you should first convert to a 3D entity by projecting onto a desired plane and then proceed to calculate the angle. Examples ======== >>> from sympy import Point3D, Line3D, Plane >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3)) >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2)) >>> a.angle_between(b) -asin(sqrt(21)/6) """ if isinstance(o, LinearEntity3D): a = Matrix(self.normal_vector) b = Matrix(o.direction_ratio) c = a.dot(b) d = sqrt(sum([i**2 for i in self.normal_vector])) e = sqrt(sum([i**2 for i in o.direction_ratio])) return asin(c/(d*e)) if isinstance(o, Plane): a = Matrix(self.normal_vector) b = Matrix(o.normal_vector) c = a.dot(b) d = sqrt(sum([i**2 for i in self.normal_vector])) e = sqrt(sum([i**2 for i in o.normal_vector])) return acos(c/(d*e)) def arbitrary_point(self, u=None, v=None): """ Returns an arbitrary point on the Plane. If given two parameters, the point ranges over the entire plane. If given 1 or no parameters, returns a point with one parameter which, when varying from 0 to 2*pi, moves the point in a circle of radius 1 about p1 of the Plane. Examples ======== >>> from sympy import Plane, Ray >>> from sympy.abc import u, v, t, r >>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0)) >>> p.arbitrary_point(u, v) Point3D(1, u + 1, v + 1) >>> p.arbitrary_point(t) Point3D(1, cos(t) + 1, sin(t) + 1) While arbitrary values of u and v can move the point anywhere in the plane, the single-parameter point can be used to construct a ray whose arbitrary point can be located at angle t and radius r from p.p1: >>> Ray(p.p1, _).arbitrary_point(r) Point3D(1, r*cos(t) + 1, r*sin(t) + 1) Returns ======= Point3D """ circle = v is None if circle: u = _symbol(u or 't', real=True) else: u = _symbol(u or 'u', real=True) v = _symbol(v or 'v', real=True) x, y, z = self.normal_vector a, b, c = self.p1.args # x1, y1, z1 is a nonzero vector parallel to the plane if x.is_zero and y.is_zero: x1, y1, z1 = S.One, S.Zero, S.Zero else: x1, y1, z1 = -y, x, S.Zero # x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1 x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1)))) if circle: x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1)) x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2)) p = Point3D(a + x1*cos(u) + x2*sin(u), \ b + y1*cos(u) + y2*sin(u), \ c + z1*cos(u) + z2*sin(u)) else: p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v) return p @staticmethod def are_concurrent(*planes): """Is a sequence of Planes concurrent? Two or more Planes are concurrent if their intersections are a common line. Parameters ========== planes: list Returns ======= Boolean Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1)) >>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1)) >>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9)) >>> Plane.are_concurrent(a, b) True >>> Plane.are_concurrent(a, b, c) False """ planes = list(uniq(planes)) for i in planes: if not isinstance(i, Plane): raise ValueError('All objects should be Planes but got %s' % i.func) if len(planes) < 2: return False planes = list(planes) first = planes.pop(0) sol = first.intersection(planes[0]) if sol == []: return False else: line = sol[0] for i in planes[1:]: l = first.intersection(i) if not l or l[0] not in line: return False return True def distance(self, o): """Distance between the plane and another geometric entity. Parameters ========== Point3D, LinearEntity3D, Plane. Returns ======= distance Notes ===== This method accepts only 3D entities as it's parameter, but if you want to calculate the distance between a 2D entity and a plane you should first convert to a 3D entity by projecting onto a desired plane and then proceed to calculate the distance. Examples ======== >>> from sympy import Point3D, Line3D, Plane >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1)) >>> b = Point3D(1, 2, 3) >>> a.distance(b) sqrt(3) >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2)) >>> a.distance(c) 0 """ if self.intersection(o) != []: return S.Zero if isinstance(o, (Segment3D, Ray3D)): a, b = o.p1, o.p2 pi, = self.intersection(Line3D(a, b)) if pi in o: return self.distance(pi) elif a in Segment3D(pi, b): return self.distance(a) else: assert isinstance(o, Segment3D) is True return self.distance(b) # following code handles `Point3D`, `LinearEntity3D`, `Plane` a = o if isinstance(o, Point3D) else o.p1 n = Point3D(self.normal_vector).unit d = (a - self.p1).dot(n) return abs(d) def equals(self, o): """ Returns True if self and o are the same mathematical entities. Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1)) >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2)) >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6)) >>> a.equals(a) True >>> a.equals(b) True >>> a.equals(c) False """ if isinstance(o, Plane): a = self.equation() b = o.equation() return cancel(a/b).is_constant() else: return False def equation(self, x=None, y=None, z=None): """The equation of the Plane. Examples ======== >>> from sympy import Point3D, Plane >>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1)) >>> a.equation() -23*x + 11*y - 2*z + 16 >>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6)) >>> a.equation() 6*x + 6*y + 6*z - 42 """ x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')] a = Point3D(x, y, z) b = self.p1.direction_ratio(a) c = self.normal_vector return (sum(i*j for i, j in zip(b, c))) def intersection(self, o): """ The intersection with other geometrical entity. Parameters ========== Point, Point3D, LinearEntity, LinearEntity3D, Plane Returns ======= List Examples ======== >>> from sympy import Point3D, Line3D, Plane >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1)) >>> b = Point3D(1, 2, 3) >>> a.intersection(b) [Point3D(1, 2, 3)] >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2)) >>> a.intersection(c) [Point3D(2, 2, 2)] >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3)) >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3)) >>> d.intersection(e) [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))] """ if not isinstance(o, GeometryEntity): o = Point(o, dim=3) if isinstance(o, Point): if o in self: return [o] else: return [] if isinstance(o, (LinearEntity, LinearEntity3D)): # recast to 3D p1, p2 = o.p1, o.p2 if isinstance(o, Segment): o = Segment3D(p1, p2) elif isinstance(o, Ray): o = Ray3D(p1, p2) elif isinstance(o, Line): o = Line3D(p1, p2) else: raise ValueError('unhandled linear entity: %s' % o.func) if o in self: return [o] else: t = Dummy() # unnamed else it may clash with a symbol in o a = Point3D(o.arbitrary_point(t)) p1, n = self.p1, Point3D(self.normal_vector) # TODO: Replace solve with solveset, when this line is tested c = solve((a - p1).dot(n), t) if not c: return [] else: c = [i for i in c if i.is_real is not False] if len(c) > 1: c = [i for i in c if i.is_real] if len(c) != 1: raise Undecidable("not sure which point is real") p = a.subs(t, c[0]) if p not in o: return [] # e.g. a segment might not intersect a plane return [p] if isinstance(o, Plane): if self.equals(o): return [self] if self.is_parallel(o): return [] else: x, y, z = map(Dummy, 'xyz') a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector]) c = list(a.cross(b)) d = self.equation(x, y, z) e = o.equation(x, y, z) result = list(linsolve([d, e], x, y, z))[0] for i in (x, y, z): result = result.subs(i, 0) return [Line3D(Point3D(result), direction_ratio=c)] def is_coplanar(self, o): """ Returns True if `o` is coplanar with self, else False. Examples ======== >>> from sympy import Plane >>> o = (0, 0, 0) >>> p = Plane(o, (1, 1, 1)) >>> p2 = Plane(o, (2, 2, 2)) >>> p == p2 False >>> p.is_coplanar(p2) True """ if isinstance(o, Plane): x, y, z = map(Dummy, 'xyz') return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z) if isinstance(o, Point3D): return o in self elif isinstance(o, LinearEntity3D): return all(i in self for i in self) elif isinstance(o, GeometryEntity): # XXX should only be handling 2D objects now return all(i == 0 for i in self.normal_vector[:2]) def is_parallel(self, l): """Is the given geometric entity parallel to the plane? Parameters ========== LinearEntity3D or Plane Returns ======= Boolean Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6)) >>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12)) >>> a.is_parallel(b) True """ if isinstance(l, LinearEntity3D): a = l.direction_ratio b = self.normal_vector c = sum([i*j for i, j in zip(a, b)]) if c == 0: return True else: return False elif isinstance(l, Plane): a = Matrix(l.normal_vector) b = Matrix(self.normal_vector) if a.cross(b).is_zero_matrix: return True else: return False def is_perpendicular(self, l): """is the given geometric entity perpendicualar to the given plane? Parameters ========== LinearEntity3D or Plane Returns ======= Boolean Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6)) >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1)) >>> a.is_perpendicular(b) True """ if isinstance(l, LinearEntity3D): a = Matrix(l.direction_ratio) b = Matrix(self.normal_vector) if a.cross(b).is_zero_matrix: return True else: return False elif isinstance(l, Plane): a = Matrix(l.normal_vector) b = Matrix(self.normal_vector) if a.dot(b) == 0: return True else: return False else: return False @property def normal_vector(self): """Normal vector of the given plane. Examples ======== >>> from sympy import Point3D, Plane >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2)) >>> a.normal_vector (-1, 2, -1) >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7)) >>> a.normal_vector (1, 4, 7) """ return self.args[1] @property def p1(self): """The only defining point of the plane. Others can be obtained from the arbitrary_point method. See Also ======== sympy.geometry.point.Point3D Examples ======== >>> from sympy import Point3D, Plane >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2)) >>> a.p1 Point3D(1, 1, 1) """ return self.args[0] def parallel_plane(self, pt): """ Plane parallel to the given plane and passing through the point pt. Parameters ========== pt: Point3D Returns ======= Plane Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6)) >>> a.parallel_plane(Point3D(2, 3, 5)) Plane(Point3D(2, 3, 5), (2, 4, 6)) """ a = self.normal_vector return Plane(pt, normal_vector=a) def perpendicular_line(self, pt): """A line perpendicular to the given plane. Parameters ========== pt: Point3D Returns ======= Line3D Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6)) >>> a.perpendicular_line(Point3D(9, 8, 7)) Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13)) """ a = self.normal_vector return Line3D(pt, direction_ratio=a) def perpendicular_plane(self, *pts): """ Return a perpendicular passing through the given points. If the direction ratio between the points is the same as the Plane's normal vector then, to select from the infinite number of possible planes, a third point will be chosen on the z-axis (or the y-axis if the normal vector is already parallel to the z-axis). If less than two points are given they will be supplied as follows: if no point is given then pt1 will be self.p1; if a second point is not given it will be a point through pt1 on a line parallel to the z-axis (if the normal is not already the z-axis, otherwise on the line parallel to the y-axis). Parameters ========== pts: 0, 1 or 2 Point3D Returns ======= Plane Examples ======== >>> from sympy import Plane, Point3D >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0) >>> Z = (0, 0, 1) >>> p = Plane(a, normal_vector=Z) >>> p.perpendicular_plane(a, b) Plane(Point3D(0, 0, 0), (1, 0, 0)) """ if len(pts) > 2: raise ValueError('No more than 2 pts should be provided.') pts = list(pts) if len(pts) == 0: pts.append(self.p1) if len(pts) == 1: x, y, z = self.normal_vector if x == y == 0: dir = (0, 1, 0) else: dir = (0, 0, 1) pts.append(pts[0] + Point3D(*dir)) p1, p2 = [Point(i, dim=3) for i in pts] l = Line3D(p1, p2) n = Line3D(p1, direction_ratio=self.normal_vector) if l in n: # XXX should an error be raised instead? # there are infinitely many perpendicular planes; x, y, z = self.normal_vector if x == y == 0: # the z axis is the normal so pick a pt on the y-axis p3 = Point3D(0, 1, 0) # case 1 else: # else pick a pt on the z axis p3 = Point3D(0, 0, 1) # case 2 # in case that point is already given, move it a bit if p3 in l: p3 *= 2 # case 3 else: p3 = p1 + Point3D(*self.normal_vector) # case 4 return Plane(p1, p2, p3) def projection_line(self, line): """Project the given line onto the plane through the normal plane containing the line. Parameters ========== LinearEntity or LinearEntity3D Returns ======= Point3D, Line3D, Ray3D or Segment3D Notes ===== For the interaction between 2D and 3D lines(segments, rays), you should convert the line to 3D by using this method. For example for finding the intersection between a 2D and a 3D line, convert the 2D line to a 3D line by projecting it on a required plane and then proceed to find the intersection between those lines. Examples ======== >>> from sympy import Plane, Line, Line3D, Point3D >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1)) >>> b = Line(Point3D(1, 1), Point3D(2, 2)) >>> a.projection_line(b) Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3)) >>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) >>> a.projection_line(c) Point3D(1, 1, 1) """ if not isinstance(line, (LinearEntity, LinearEntity3D)): raise NotImplementedError('Enter a linear entity only') a, b = self.projection(line.p1), self.projection(line.p2) if a == b: # projection does not imply intersection so for # this case (line parallel to plane's normal) we # return the projection point return a if isinstance(line, (Line, Line3D)): return Line3D(a, b) if isinstance(line, (Ray, Ray3D)): return Ray3D(a, b) if isinstance(line, (Segment, Segment3D)): return Segment3D(a, b) def projection(self, pt): """Project the given point onto the plane along the plane normal. Parameters ========== Point or Point3D Returns ======= Point3D Examples ======== >>> from sympy import Plane, Point3D >>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1)) The projection is along the normal vector direction, not the z axis, so (1, 1) does not project to (1, 1, 2) on the plane A: >>> b = Point3D(1, 1) >>> A.projection(b) Point3D(5/3, 5/3, 2/3) >>> _ in A True But the point (1, 1, 2) projects to (1, 1) on the XY-plane: >>> XY = Plane((0, 0, 0), (0, 0, 1)) >>> XY.projection((1, 1, 2)) Point3D(1, 1, 0) """ rv = Point(pt, dim=3) if rv in self: return rv return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0] def random_point(self, seed=None): """ Returns a random point on the Plane. Returns ======= Point3D Examples ======== >>> from sympy import Plane >>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0)) >>> r = p.random_point(seed=42) # seed value is optional >>> r.n(3) Point3D(2.29, 0, -1.35) The random point can be moved to lie on the circle of radius 1 centered on p1: >>> c = p.p1 + (r - p.p1).unit >>> c.distance(p.p1).equals(1) True """ if seed is not None: rng = random.Random(seed) else: rng = random u, v = Dummy('u'), Dummy('v') params = { u: 2*Rational(rng.gauss(0, 1)) - 1, v: 2*Rational(rng.gauss(0, 1)) - 1} return self.arbitrary_point(u, v).subs(params) def parameter_value(self, other, u, v=None): """Return the parameter(s) corresponding to the given point. Examples ======== >>> from sympy import pi, Plane >>> from sympy.abc import t, u, v >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0)) By default, the parameter value returned defines a point that is a distance of 1 from the Plane's p1 value and in line with the given point: >>> on_circle = p.arbitrary_point(t).subs(t, pi/4) >>> on_circle.distance(p.p1) 1 >>> p.parameter_value(on_circle, t) {t: pi/4} Moving the point twice as far from p1 does not change the parameter value: >>> off_circle = p.p1 + (on_circle - p.p1)*2 >>> off_circle.distance(p.p1) 2 >>> p.parameter_value(off_circle, t) {t: pi/4} If the 2-value parameter is desired, supply the two parameter symbols and a replacement dictionary will be returned: >>> p.parameter_value(on_circle, u, v) {u: sqrt(10)/10, v: sqrt(10)/30} >>> p.parameter_value(off_circle, u, v) {u: sqrt(10)/5, v: sqrt(10)/15} """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other, Point): raise ValueError("other must be a point") if other == self.p1: return other if isinstance(u, Symbol) and v is None: delta = self.arbitrary_point(u) - self.p1 eq = delta - (other - self.p1).unit sol = solve(eq, u, dict=True) elif isinstance(u, Symbol) and isinstance(v, Symbol): pt = self.arbitrary_point(u, v) sol = solve(pt - other, (u, v), dict=True) else: raise ValueError('expecting 1 or 2 symbols') if not sol: raise ValueError("Given point is not on %s" % func_name(self)) return sol[0] # {t: tval} or {u: uval, v: vval} @property def ambient_dimension(self): return self.p1.ambient_dimension
900f660569a46b1bffd44864cae9043e53b38b2839b58373084b4f0c40687805
"""Elliptical geometrical entities. Contains * Ellipse * Circle """ from sympy.core.expr import Expr from sympy.core.relational import Eq from sympy.core import S, pi, sympify from sympy.core.evalf import N from sympy.core.parameters import global_parameters from sympy.core.logic import fuzzy_bool from sympy.core.numbers import Rational, oo from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, uniquely_named_symbol, _symbol from sympy.simplify import simplify, trigsimp from sympy.functions.elementary.miscellaneous import sqrt, Max from sympy.functions.elementary.trigonometric import cos, sin from sympy.functions.special.elliptic_integrals import elliptic_e from .entity import GeometryEntity, GeometrySet from .exceptions import GeometryError from .line import Line, Segment, Ray2D, Segment2D, Line2D, LinearEntity3D from .point import Point, Point2D, Point3D from .util import idiff, find from sympy.polys import DomainError, Poly, PolynomialError from sympy.polys.polyutils import _not_a_coeff, _nsort from sympy.solvers import solve from sympy.solvers.solveset import linear_coeffs from sympy.utilities.misc import filldedent, func_name from mpmath.libmp.libmpf import prec_to_dps import random class Ellipse(GeometrySet): """An elliptical GeometryEntity. Parameters ========== center : Point, optional Default value is Point(0, 0) hradius : number or SymPy expression, optional vradius : number or SymPy expression, optional eccentricity : number or SymPy expression, optional Two of `hradius`, `vradius` and `eccentricity` must be supplied to create an Ellipse. The third is derived from the two supplied. Attributes ========== center hradius vradius area circumference eccentricity periapsis apoapsis focus_distance foci Raises ====== GeometryError When `hradius`, `vradius` and `eccentricity` are incorrectly supplied as parameters. TypeError When `center` is not a Point. See Also ======== Circle Notes ----- Constructed from a center and two radii, the first being the horizontal radius (along the x-axis) and the second being the vertical radius (along the y-axis). When symbolic value for hradius and vradius are used, any calculation that refers to the foci or the major or minor axis will assume that the ellipse has its major radius on the x-axis. If this is not true then a manual rotation is necessary. Examples ======== >>> from sympy import Ellipse, Point, Rational >>> e1 = Ellipse(Point(0, 0), 5, 1) >>> e1.hradius, e1.vradius (5, 1) >>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5)) >>> e2 Ellipse(Point2D(3, 1), 3, 9/5) """ def __contains__(self, o): if isinstance(o, Point): x = Dummy('x', real=True) y = Dummy('y', real=True) res = self.equation(x, y).subs({x: o.x, y: o.y}) return trigsimp(simplify(res)) is S.Zero elif isinstance(o, Ellipse): return self == o return False def __eq__(self, o): """Is the other GeometryEntity the same as this ellipse?""" return isinstance(o, Ellipse) and (self.center == o.center and self.hradius == o.hradius and self.vradius == o.vradius) def __hash__(self): return super().__hash__() def __new__( cls, center=None, hradius=None, vradius=None, eccentricity=None, **kwargs): hradius = sympify(hradius) vradius = sympify(vradius) eccentricity = sympify(eccentricity) if center is None: center = Point(0, 0) else: center = Point(center, dim=2) if len(center) != 2: raise ValueError('The center of "{}" must be a two dimensional point'.format(cls)) if len(list(filter(lambda x: x is not None, (hradius, vradius, eccentricity)))) != 2: raise ValueError(filldedent(''' Exactly two arguments of "hradius", "vradius", and "eccentricity" must not be None.''')) if eccentricity is not None: if eccentricity.is_negative: raise GeometryError("Eccentricity of ellipse/circle should lie between [0, 1)") elif hradius is None: hradius = vradius / sqrt(1 - eccentricity**2) elif vradius is None: vradius = hradius * sqrt(1 - eccentricity**2) if hradius == vradius: return Circle(center, hradius, **kwargs) if S.Zero in (hradius, vradius): return Segment(Point(center[0] - hradius, center[1] - vradius), Point(center[0] + hradius, center[1] + vradius)) if hradius.is_real is False or vradius.is_real is False: raise GeometryError("Invalid value encountered when computing hradius / vradius.") return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG ellipse element for the Ellipse. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ c = N(self.center) h, v = N(self.hradius), N(self.vradius) return ( '<ellipse fill="{1}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" cx="{2}" cy="{3}" rx="{4}" ry="{5}"/>' ).format(2. * scale_factor, fill_color, c.x, c.y, h, v) @property def ambient_dimension(self): return 2 @property def apoapsis(self): """The apoapsis of the ellipse. The greatest distance between the focus and the contour. Returns ======= apoapsis : number See Also ======== periapsis : Returns shortest distance between foci and contour Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.apoapsis 2*sqrt(2) + 3 """ return self.major * (1 + self.eccentricity) def arbitrary_point(self, parameter='t'): """A parameterized point on the ellipse. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= arbitrary_point : Point Raises ====== ValueError When `parameter` already appears in the functions. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.arbitrary_point() Point2D(3*cos(t), 2*sin(t)) """ t = _symbol(parameter, real=True) if t.name in (f.name for f in self.free_symbols): raise ValueError(filldedent('Symbol %s already appears in object ' 'and cannot be used as a parameter.' % t.name)) return Point(self.center.x + self.hradius*cos(t), self.center.y + self.vradius*sin(t)) @property def area(self): """The area of the ellipse. Returns ======= area : number Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.area 3*pi """ return simplify(S.Pi * self.hradius * self.vradius) @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ h, v = self.hradius, self.vradius return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v) @property def center(self): """The center of the ellipse. Returns ======= center : number See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.center Point2D(0, 0) """ return self.args[0] @property def circumference(self): """The circumference of the ellipse. Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.circumference 12*elliptic_e(8/9) """ if self.eccentricity == 1: # degenerate return 4*self.major elif self.eccentricity == 0: # circle return 2*pi*self.hradius else: return 4*self.major*elliptic_e(self.eccentricity**2) @property def eccentricity(self): """The eccentricity of the ellipse. Returns ======= eccentricity : number Examples ======== >>> from sympy import Point, Ellipse, sqrt >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, sqrt(2)) >>> e1.eccentricity sqrt(7)/3 """ return self.focus_distance / self.major def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ----- Being on the border of self is considered False. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Ellipse, S >>> from sympy.abc import t >>> e = Ellipse((0, 0), 3, 2) >>> e.encloses_point((0, 0)) True >>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half)) False >>> e.encloses_point((4, 0)) False """ p = Point(p, dim=2) if p in self: return False if len(self.foci) == 2: # if the combined distance from the foci to p (h1 + h2) is less # than the combined distance from the foci to the minor axis # (which is the same as the major axis length) then p is inside # the ellipse h1, h2 = [f.distance(p) for f in self.foci] test = 2*self.major - (h1 + h2) else: test = self.radius - self.center.distance(p) return fuzzy_bool(test.is_positive) def equation(self, x='x', y='y', _slope=None): """ Returns the equation of an ellipse aligned with the x and y axes; when slope is given, the equation returned corresponds to an ellipse with a major axis having that slope. Parameters ========== x : str, optional Label for the x-axis. Default value is 'x'. y : str, optional Label for the y-axis. Default value is 'y'. _slope : Expr, optional The slope of the major axis. Ignored when 'None'. Returns ======= equation : SymPy expression See Also ======== arbitrary_point : Returns parameterized point on ellipse Examples ======== >>> from sympy import Point, Ellipse, pi >>> from sympy.abc import x, y >>> e1 = Ellipse(Point(1, 0), 3, 2) >>> eq1 = e1.equation(x, y); eq1 y**2/4 + (x/3 - 1/3)**2 - 1 >>> eq2 = e1.equation(x, y, _slope=1); eq2 (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1 A point on e1 satisfies eq1. Let's use one on the x-axis: >>> p1 = e1.center + Point(e1.major, 0) >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0 When rotated the same as the rotated ellipse, about the center point of the ellipse, it will satisfy the rotated ellipse's equation, too: >>> r1 = p1.rotate(pi/4, e1.center) >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0 References ========== .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis .. [2] https://en.wikipedia.org/wiki/Ellipse#Equation_of_a_shifted_ellipse """ x = _symbol(x, real=True) y = _symbol(y, real=True) dx = x - self.center.x dy = y - self.center.y if _slope is not None: L = (dy - _slope*dx)**2 l = (_slope*dy + dx)**2 h = 1 + _slope**2 b = h*self.major**2 a = h*self.minor**2 return l/b + L/a - 1 else: t1 = (dx/self.hradius)**2 t2 = (dy/self.vradius)**2 return t1 + t2 - 1 def evolute(self, x='x', y='y'): """The equation of evolute of the ellipse. Parameters ========== x : str, optional Label for the x-axis. Default value is 'x'. y : str, optional Label for the y-axis. Default value is 'y'. Returns ======= equation : SymPy expression Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(1, 0), 3, 2) >>> e1.evolute() 2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3) """ if len(self.args) != 3: raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.') x = _symbol(x, real=True) y = _symbol(y, real=True) t1 = (self.hradius*(x - self.center.x))**Rational(2, 3) t2 = (self.vradius*(y - self.center.y))**Rational(2, 3) return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3) @property def foci(self): """The foci of the ellipse. Notes ----- The foci can only be calculated if the major/minor axes are known. Raises ====== ValueError When the major and minor axis cannot be determined. See Also ======== sympy.geometry.point.Point focus_distance : Returns the distance between focus and center Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.foci (Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0)) """ c = self.center hr, vr = self.hradius, self.vradius if hr == vr: return (c, c) # calculate focus distance manually, since focus_distance calls this # routine fd = sqrt(self.major**2 - self.minor**2) if hr == self.minor: # foci on the y-axis return (c + Point(0, -fd), c + Point(0, fd)) elif hr == self.major: # foci on the x-axis return (c + Point(-fd, 0), c + Point(fd, 0)) @property def focus_distance(self): """The focal distance of the ellipse. The distance between the center and one focus. Returns ======= focus_distance : number See Also ======== foci Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.focus_distance 2*sqrt(2) """ return Point.distance(self.center, self.foci[0]) @property def hradius(self): """The horizontal radius of the ellipse. Returns ======= hradius : number See Also ======== vradius, major, minor Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.hradius 3 """ return self.args[1] def intersection(self, o): """The intersection of this ellipse and another geometrical entity `o`. Parameters ========== o : GeometryEntity Returns ======= intersection : list of GeometryEntity objects Notes ----- Currently supports intersections with Point, Line, Segment, Ray, Circle and Ellipse types. See Also ======== sympy.geometry.entity.GeometryEntity Examples ======== >>> from sympy import Ellipse, Point, Line >>> e = Ellipse(Point(0, 0), 5, 7) >>> e.intersection(Point(0, 0)) [] >>> e.intersection(Point(5, 0)) [Point2D(5, 0)] >>> e.intersection(Line(Point(0,0), Point(0, 1))) [Point2D(0, -7), Point2D(0, 7)] >>> e.intersection(Line(Point(5,0), Point(5, 1))) [Point2D(5, 0)] >>> e.intersection(Line(Point(6,0), Point(6, 1))) [] >>> e = Ellipse(Point(-1, 0), 4, 3) >>> e.intersection(Ellipse(Point(1, 0), 4, 3)) [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)] >>> e.intersection(Ellipse(Point(5, 0), 4, 3)) [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)] >>> e.intersection(Ellipse(Point(100500, 0), 4, 3)) [] >>> e.intersection(Ellipse(Point(0, 0), 3, 4)) [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)] >>> e.intersection(Ellipse(Point(-1, 0), 3, 4)) [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)] """ # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain x = Dummy('x', real=True) y = Dummy('y', real=True) if isinstance(o, Point): if o in self: return [o] else: return [] elif isinstance(o, (Segment2D, Ray2D)): ellipse_equation = self.equation(x, y) result = solve([ellipse_equation, Line(o.points[0], o.points[1]).equation(x, y)], [x, y]) return list(ordered([Point(i) for i in result if i in o])) elif isinstance(o, Polygon): return o.intersection(self) elif isinstance(o, (Ellipse, Line2D)): if o == self: return self else: ellipse_equation = self.equation(x, y) return list(ordered([Point(i) for i in solve([ellipse_equation, o.equation(x, y)], [x, y])])) elif isinstance(o, LinearEntity3D): raise TypeError('Entity must be two dimensional, not three dimensional') else: raise TypeError('Intersection not handled for %s' % func_name(o)) def is_tangent(self, o): """Is `o` tangent to the ellipse? Parameters ========== o : GeometryEntity An Ellipse, LinearEntity or Polygon Raises ====== NotImplementedError When the wrong type of argument is supplied. Returns ======= is_tangent: boolean True if o is tangent to the ellipse, False otherwise. See Also ======== tangent_lines Examples ======== >>> from sympy import Point, Ellipse, Line >>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3) >>> e1 = Ellipse(p0, 3, 2) >>> l1 = Line(p1, p2) >>> e1.is_tangent(l1) True """ if isinstance(o, Point2D): return False elif isinstance(o, Ellipse): intersect = self.intersection(o) if isinstance(intersect, Ellipse): return True elif intersect: return all((self.tangent_lines(i)[0]).equals(o.tangent_lines(i)[0]) for i in intersect) else: return False elif isinstance(o, Line2D): hit = self.intersection(o) if not hit: return False if len(hit) == 1: return True # might return None if it can't decide return hit[0].equals(hit[1]) elif isinstance(o, Ray2D): intersect = self.intersection(o) if len(intersect) == 1: return intersect[0] != o.source and not self.encloses_point(o.source) else: return False elif isinstance(o, (Segment2D, Polygon)): all_tangents = False segments = o.sides if isinstance(o, Polygon) else [o] for segment in segments: intersect = self.intersection(segment) if len(intersect) == 1: if not any(intersect[0] in i for i in segment.points) \ and not any(self.encloses_point(i) for i in segment.points): all_tangents = True continue else: return False else: return all_tangents return all_tangents elif isinstance(o, (LinearEntity3D, Point3D)): raise TypeError('Entity must be two dimensional, not three dimensional') else: raise TypeError('Is_tangent not handled for %s' % func_name(o)) @property def major(self): """Longer axis of the ellipse (if it can be determined) else hradius. Returns ======= major : number or expression See Also ======== hradius, vradius, minor Examples ======== >>> from sympy import Point, Ellipse, Symbol >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.major 3 >>> a = Symbol('a') >>> b = Symbol('b') >>> Ellipse(p1, a, b).major a >>> Ellipse(p1, b, a).major b >>> m = Symbol('m') >>> M = m + 1 >>> Ellipse(p1, m, M).major m + 1 """ ab = self.args[1:3] if len(ab) == 1: return ab[0] a, b = ab o = b - a < 0 if o == True: return a elif o == False: return b return self.hradius @property def minor(self): """Shorter axis of the ellipse (if it can be determined) else vradius. Returns ======= minor : number or expression See Also ======== hradius, vradius, major Examples ======== >>> from sympy import Point, Ellipse, Symbol >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.minor 1 >>> a = Symbol('a') >>> b = Symbol('b') >>> Ellipse(p1, a, b).minor b >>> Ellipse(p1, b, a).minor a >>> m = Symbol('m') >>> M = m + 1 >>> Ellipse(p1, m, M).minor m """ ab = self.args[1:3] if len(ab) == 1: return ab[0] a, b = ab o = a - b < 0 if o == True: return a elif o == False: return b return self.vradius def normal_lines(self, p, prec=None): """Normal lines between `p` and the ellipse. Parameters ========== p : Point Returns ======= normal_lines : list with 1, 2 or 4 Lines Examples ======== >>> from sympy import Point, Ellipse >>> e = Ellipse((0, 0), 2, 3) >>> c = e.center >>> e.normal_lines(c + Point(1, 0)) [Line2D(Point2D(0, 0), Point2D(1, 0))] >>> e.normal_lines(c) [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))] Off-axis points require the solution of a quartic equation. This often leads to very large expressions that may be of little practical use. An approximate solution of `prec` digits can be obtained by passing in the desired value: >>> e.normal_lines((3, 3), prec=2) [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)), Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))] Whereas the above solution has an operation count of 12, the exact solution has an operation count of 2020. """ p = Point(p, dim=2) # XXX change True to something like self.angle == 0 if the arbitrarily # rotated ellipse is introduced. # https://github.com/sympy/sympy/issues/2815) if True: rv = [] if p.x == self.center.x: rv.append(Line(self.center, slope=oo)) if p.y == self.center.y: rv.append(Line(self.center, slope=0)) if rv: # at these special orientations of p either 1 or 2 normals # exist and we are done return rv # find the 4 normal points and construct lines through them with # the corresponding slope x, y = Dummy('x', real=True), Dummy('y', real=True) eq = self.equation(x, y) dydx = idiff(eq, y, x) norm = -1/dydx slope = Line(p, (x, y)).slope seq = slope - norm # TODO: Replace solve with solveset, when this line is tested yis = solve(seq, y)[0] xeq = eq.subs(y, yis).as_numer_denom()[0].expand() if len(xeq.free_symbols) == 1: try: # this is so much faster, it's worth a try xsol = Poly(xeq, x).real_roots() except (DomainError, PolynomialError, NotImplementedError): # TODO: Replace solve with solveset, when these lines are tested xsol = _nsort(solve(xeq, x), separated=True)[0] points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol] else: raise NotImplementedError( 'intersections for the general ellipse are not supported') slopes = [norm.subs(zip((x, y), pt.args)) for pt in points] if prec is not None: points = [pt.n(prec) for pt in points] slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes] return [Line(pt, slope=s) for pt, s in zip(points, slopes)] @property def periapsis(self): """The periapsis of the ellipse. The shortest distance between the focus and the contour. Returns ======= periapsis : number See Also ======== apoapsis : Returns greatest distance between focus and contour Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.periapsis 3 - 2*sqrt(2) """ return self.major * (1 - self.eccentricity) @property def semilatus_rectum(self): """ Calculates the semi-latus rectum of the Ellipse. Semi-latus rectum is defined as one half of the chord through a focus parallel to the conic section directrix of a conic section. Returns ======= semilatus_rectum : number See Also ======== apoapsis : Returns greatest distance between focus and contour periapsis : The shortest distance between the focus and the contour Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.semilatus_rectum 1/3 References ========== .. [1] http://mathworld.wolfram.com/SemilatusRectum.html .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum """ return self.major * (1 - self.eccentricity ** 2) def auxiliary_circle(self): """Returns a Circle whose diameter is the major axis of the ellipse. Examples ======== >>> from sympy import Ellipse, Point, symbols >>> c = Point(1, 2) >>> Ellipse(c, 8, 7).auxiliary_circle() Circle(Point2D(1, 2), 8) >>> a, b = symbols('a b') >>> Ellipse(c, a, b).auxiliary_circle() Circle(Point2D(1, 2), Max(a, b)) """ return Circle(self.center, Max(self.hradius, self.vradius)) def director_circle(self): """ Returns a Circle consisting of all points where two perpendicular tangent lines to the ellipse cross each other. Returns ======= Circle A director circle returned as a geometric object. Examples ======== >>> from sympy import Ellipse, Point, symbols >>> c = Point(3,8) >>> Ellipse(c, 7, 9).director_circle() Circle(Point2D(3, 8), sqrt(130)) >>> a, b = symbols('a b') >>> Ellipse(c, a, b).director_circle() Circle(Point2D(3, 8), sqrt(a**2 + b**2)) References ========== .. [1] https://en.wikipedia.org/wiki/Director_circle """ return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2)) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Ellipse. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.plot_interval() [t, -pi, pi] """ t = _symbol(parameter, real=True) return [t, -S.Pi, S.Pi] def random_point(self, seed=None): """A random point on the ellipse. Returns ======= point : Point Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.random_point() # gives some random point Point2D(...) >>> p1 = e1.random_point(seed=0); p1.n(2) Point2D(2.1, 1.4) Notes ===== When creating a random point, one may simply replace the parameter with a random number. When doing so, however, the random number should be made a Rational or else the point may not test as being in the ellipse: >>> from sympy.abc import t >>> from sympy import Rational >>> arb = e1.arbitrary_point(t); arb Point2D(3*cos(t), 2*sin(t)) >>> arb.subs(t, .1) in e1 False >>> arb.subs(t, Rational(.1)) in e1 True >>> arb.subs(t, Rational('.1')) in e1 True See Also ======== sympy.geometry.point.Point arbitrary_point : Returns parameterized point on ellipse """ t = _symbol('t', real=True) x, y = self.arbitrary_point(t).args # get a random value in [-1, 1) corresponding to cos(t) # and confirm that it will test as being in the ellipse if seed is not None: rng = random.Random(seed) else: rng = random # simplify this now or else the Float will turn s into a Float r = Rational(rng.random()) c = 2*r - 1 s = sqrt(1 - c**2) return Point(x.subs(cos(t), c), y.subs(sin(t), s)) def reflect(self, line): """Override GeometryEntity.reflect since the radius is not a GeometryEntity. Examples ======== >>> from sympy import Circle, Line >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) Circle(Point2D(1, 0), -1) >>> from sympy import Ellipse, Line, Point >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0))) Traceback (most recent call last): ... NotImplementedError: General Ellipse is not supported but the equation of the reflected Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 + 37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1 Notes ===== Until the general ellipse (with no axis parallel to the x-axis) is supported a NotImplemented error is raised and the equation whose zeros define the rotated ellipse is given. """ if line.slope in (0, oo): c = self.center c = c.reflect(line) return self.func(c, -self.hradius, self.vradius) else: x, y = [uniquely_named_symbol( name, (self, line), modify=lambda s: '_' + s, real=True) for name in 'xy'] expr = self.equation(x, y) p = Point(x, y).reflect(line) result = expr.subs(zip((x, y), p.args ), simultaneous=True) raise NotImplementedError(filldedent( 'General Ellipse is not supported but the equation ' 'of the reflected Ellipse is given by the zeros of: ' + "f(%s, %s) = %s" % (str(x), str(y), str(result)))) def rotate(self, angle=0, pt=None): """Rotate ``angle`` radians counterclockwise about Point ``pt``. Note: since the general ellipse is not supported, only rotations that are integer multiples of pi/2 are allowed. Examples ======== >>> from sympy import Ellipse, pi >>> Ellipse((1, 0), 2, 1).rotate(pi/2) Ellipse(Point2D(0, 1), 1, 2) >>> Ellipse((1, 0), 2, 1).rotate(pi) Ellipse(Point2D(-1, 0), 2, 1) """ if self.hradius == self.vradius: return self.func(self.center.rotate(angle, pt), self.hradius) if (angle/S.Pi).is_integer: return super().rotate(angle, pt) if (2*angle/S.Pi).is_integer: return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius) # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.') def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since it is the major and minor axes which must be scaled and they are not GeometryEntities. Examples ======== >>> from sympy import Ellipse >>> Ellipse((0, 0), 2, 1).scale(2, 4) Circle(Point2D(0, 0), 4) >>> Ellipse((0, 0), 2, 1).scale(2) Ellipse(Point2D(0, 0), 4, 1) """ c = self.center if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) h = self.hradius v = self.vradius return self.func(c.scale(x, y), hradius=h*x, vradius=v*y) def tangent_lines(self, p): """Tangent lines between `p` and the ellipse. If `p` is on the ellipse, returns the tangent line through point `p`. Otherwise, returns the tangent line(s) from `p` to the ellipse, or None if no tangent line is possible (e.g., `p` inside ellipse). Parameters ========== p : Point Returns ======= tangent_lines : list with 1 or 2 Lines Raises ====== NotImplementedError Can only find tangent lines for a point, `p`, on the ellipse. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Line Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.tangent_lines(Point(3, 0)) [Line2D(Point2D(3, 0), Point2D(3, -12))] """ p = Point(p, dim=2) if self.encloses_point(p): return [] if p in self: delta = self.center - p rise = (self.vradius**2)*delta.x run = -(self.hradius**2)*delta.y p2 = Point(simplify(p.x + run), simplify(p.y + rise)) return [Line(p, p2)] else: if len(self.foci) == 2: f1, f2 = self.foci maj = self.hradius test = (2*maj - Point.distance(f1, p) - Point.distance(f2, p)) else: test = self.radius - Point.distance(self.center, p) if test.is_number and test.is_positive: return [] # else p is outside the ellipse or we can't tell. In case of the # latter, the solutions returned will only be valid if # the point is not inside the ellipse; if it is, nan will result. x, y = Dummy('x'), Dummy('y') eq = self.equation(x, y) dydx = idiff(eq, y, x) slope = Line(p, Point(x, y)).slope # TODO: Replace solve with solveset, when this line is tested tangent_points = solve([slope - dydx, eq], [x, y]) # handle horizontal and vertical tangent lines if len(tangent_points) == 1: if tangent_points[0][ 0] == p.x or tangent_points[0][1] == p.y: return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))] else: return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])] # others return [Line(p, tangent_points[0]), Line(p, tangent_points[1])] @property def vradius(self): """The vertical radius of the ellipse. Returns ======= vradius : number See Also ======== hradius, major, minor Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.vradius 1 """ return self.args[2] def second_moment_of_area(self, point=None): """Returns the second moment and product moment area of an ellipse. Parameters ========== point : Point, two-tuple of sympifiable objects, or None(default=None) point is the point about which second moment of area is to be found. If "point=None" it will be calculated about the axis passing through the centroid of the ellipse. Returns ======= I_xx, I_yy, I_xy : number or SymPy expression I_xx, I_yy are second moment of area of an ellise. I_xy is product moment of area of an ellipse. Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.second_moment_of_area() (3*pi/4, 27*pi/4, 0) References ========== .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area """ I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4 I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4 I_xy = 0 if point is None: return I_xx, I_yy, I_xy # parallel axis theorem I_xx = I_xx + self.area*((point[1] - self.center.y)**2) I_yy = I_yy + self.area*((point[0] - self.center.x)**2) I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y) return I_xx, I_yy, I_xy def polar_second_moment_of_area(self): """Returns the polar second moment of area of an Ellipse It is a constituent of the second moment of area, linked through the perpendicular axis theorem. While the planar second moment of area describes an object's resistance to deflection (bending) when subjected to a force applied to a plane parallel to the central axis, the polar second moment of area describes an object's resistance to deflection when subjected to a moment applied in a plane perpendicular to the object's central axis (i.e. parallel to the cross-section) Examples ======== >>> from sympy import symbols, Circle, Ellipse >>> c = Circle((5, 5), 4) >>> c.polar_second_moment_of_area() 128*pi >>> a, b = symbols('a, b') >>> e = Ellipse((0, 0), a, b) >>> e.polar_second_moment_of_area() pi*a**3*b/4 + pi*a*b**3/4 References ========== .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia """ second_moment = self.second_moment_of_area() return second_moment[0] + second_moment[1] def section_modulus(self, point=None): """Returns a tuple with the section modulus of an ellipse Section modulus is a geometric property of an ellipse defined as the ratio of second moment of area to the distance of the extreme end of the ellipse from the centroidal axis. Parameters ========== point : Point, two-tuple of sympifyable objects, or None(default=None) point is the point at which section modulus is to be found. If "point=None" section modulus will be calculated for the point farthest from the centroidal axis of the ellipse. Returns ======= S_x, S_y: numbers or SymPy expressions S_x is the section modulus with respect to the x-axis S_y is the section modulus with respect to the y-axis A negative sign indicates that the section modulus is determined for a point below the centroidal axis. Examples ======== >>> from sympy import Symbol, Ellipse, Circle, Point2D >>> d = Symbol('d', positive=True) >>> c = Circle((0, 0), d/2) >>> c.section_modulus() (pi*d**3/32, pi*d**3/32) >>> e = Ellipse(Point2D(0, 0), 2, 4) >>> e.section_modulus() (8*pi, 4*pi) >>> e.section_modulus((2, 2)) (16*pi, 4*pi) References ========== .. [1] https://en.wikipedia.org/wiki/Section_modulus """ x_c, y_c = self.center if point is None: # taking x and y as maximum distances from centroid x_min, y_min, x_max, y_max = self.bounds y = max(y_c - y_min, y_max - y_c) x = max(x_c - x_min, x_max - x_c) else: # taking x and y as distances of the given point from the center point = Point2D(point) y = point.y - y_c x = point.x - x_c second_moment = self.second_moment_of_area() S_x = second_moment[0]/y S_y = second_moment[1]/x return S_x, S_y class Circle(Ellipse): """A circle in space. Constructed simply from a center and a radius, from three non-collinear points, or the equation of a circle. Parameters ========== center : Point radius : number or SymPy expression points : sequence of three Points equation : equation of a circle Attributes ========== radius (synonymous with hradius, vradius, major and minor) circumference equation Raises ====== GeometryError When the given equation is not that of a circle. When trying to construct circle from incorrect parameters. See Also ======== Ellipse, sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Circle, Eq >>> from sympy.abc import x, y, a, b A circle constructed from a center and radius: >>> c1 = Circle(Point(0, 0), 5) >>> c1.hradius, c1.vradius, c1.radius (5, 5, 5) A circle constructed from three points: >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0)) >>> c2.hradius, c2.vradius, c2.radius, c2.center (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2)) A circle can be constructed from an equation in the form `a*x**2 + by**2 + gx + hy + c = 0`, too: >>> Circle(x**2 + y**2 - 25) Circle(Point2D(0, 0), 5) If the variables corresponding to x and y are named something else, their name or symbol can be supplied: >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b) Circle(Point2D(0, 0), 5) """ def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) if len(args) == 1 and isinstance(args[0], (Expr, Eq)): x = kwargs.get('x', 'x') y = kwargs.get('y', 'y') equation = args[0] if isinstance(equation, Eq): equation = equation.lhs - equation.rhs x = find(x, equation) y = find(y, equation) try: a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y) except ValueError: raise GeometryError("The given equation is not that of a circle.") if S.Zero in (a, b) or a != b: raise GeometryError("The given equation is not that of a circle.") center_x = -c/a/2 center_y = -d/b/2 r2 = (center_x**2) + (center_y**2) - e return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate) else: c, r = None, None if len(args) == 3: args = [Point(a, dim=2, evaluate=evaluate) for a in args] t = Triangle(*args) if not isinstance(t, Triangle): return t c = t.circumcenter r = t.circumradius elif len(args) == 2: # Assume (center, radius) pair c = Point(args[0], dim=2, evaluate=evaluate) r = args[1] # this will prohibit imaginary radius try: r = Point(r, 0, evaluate=evaluate).x except ValueError: raise GeometryError("Circle with imaginary radius is not permitted") if not (c is None or r is None): if r == 0: return c return GeometryEntity.__new__(cls, c, r, **kwargs) raise GeometryError("Circle.__new__ received unknown arguments") def _eval_evalf(self, prec=15, **options): pt, r = self.args dps = prec_to_dps(prec) pt = pt.evalf(n=dps, **options) r = r.evalf(n=dps, **options) return self.func(pt, r, evaluate=False) @property def circumference(self): """The circumference of the circle. Returns ======= circumference : number or SymPy expression Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(3, 4), 6) >>> c1.circumference 12*pi """ return 2 * S.Pi * self.radius def equation(self, x='x', y='y'): """The equation of the circle. Parameters ========== x : str or Symbol, optional Default value is 'x'. y : str or Symbol, optional Default value is 'y'. Returns ======= equation : SymPy expression Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(0, 0), 5) >>> c1.equation() x**2 + y**2 - 25 """ x = _symbol(x, real=True) y = _symbol(y, real=True) t1 = (x - self.center.x)**2 t2 = (y - self.center.y)**2 return t1 + t2 - self.major**2 def intersection(self, o): """The intersection of this circle with another geometrical entity. Parameters ========== o : GeometryEntity Returns ======= intersection : list of GeometryEntities Examples ======== >>> from sympy import Point, Circle, Line, Ray >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0) >>> p4 = Point(5, 0) >>> c1 = Circle(p1, 5) >>> c1.intersection(p2) [] >>> c1.intersection(p4) [Point2D(5, 0)] >>> c1.intersection(Ray(p1, p2)) [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)] >>> c1.intersection(Line(p2, p3)) [] """ return Ellipse.intersection(self, o) @property def radius(self): """The radius of the circle. Returns ======= radius : number or SymPy expression See Also ======== Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(3, 4), 6) >>> c1.radius 6 """ return self.args[1] def reflect(self, line): """Override GeometryEntity.reflect since the radius is not a GeometryEntity. Examples ======== >>> from sympy import Circle, Line >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) Circle(Point2D(1, 0), -1) """ c = self.center c = c.reflect(line) return self.func(c, -self.radius) def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since the radius is not a GeometryEntity. Examples ======== >>> from sympy import Circle >>> Circle((0, 0), 1).scale(2, 2) Circle(Point2D(0, 0), 2) >>> Circle((0, 0), 1).scale(2, 4) Ellipse(Point2D(0, 0), 2, 4) """ c = self.center if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) c = c.scale(x, y) x, y = [abs(i) for i in (x, y)] if x == y: return self.func(c, x*self.radius) h = v = self.radius return Ellipse(c, hradius=h*x, vradius=v*y) @property def vradius(self): """ This Ellipse property is an alias for the Circle's radius. Whereas hradius, major and minor can use Ellipse's conventions, the vradius does not exist for a circle. It is always a positive value in order that the Circle, like Polygons, will have an area that can be positive or negative as determined by the sign of the hradius. Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(3, 4), 6) >>> c1.vradius 6 """ return abs(self.radius) from .polygon import Polygon, Triangle
155604eeb3eb045c3f0aa4a5b7af30839da9d3e90b1c358b5d43c1e7577a958a
"""The definition of the base geometrical entity with attributes common to all derived geometrical entities. Contains ======== GeometryEntity GeometricSet Notes ===== A GeometryEntity is any object that has special geometric properties. A GeometrySet is a superclass of any GeometryEntity that can also be viewed as a sympy.sets.Set. In particular, points are the only GeometryEntity not considered a Set. Rn is a GeometrySet representing n-dimensional Euclidean space. R2 and R3 are currently the only ambient spaces implemented. """ from typing import Tuple as tTuple from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.evalf import EvalfMixin, N from sympy.core.numbers import oo from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions.elementary.trigonometric import cos, sin, atan from sympy.matrices import eye from sympy.multipledispatch import dispatch from sympy.printing import sstr from sympy.sets import Set, Union, FiniteSet from sympy.sets.handlers.intersection import intersection_sets from sympy.sets.handlers.union import union_sets from sympy.solvers.solvers import solve from sympy.utilities.misc import func_name from sympy.utilities.iterables import is_sequence # How entities are ordered; used by __cmp__ in GeometryEntity ordering_of_classes = [ "Point2D", "Point3D", "Point", "Segment2D", "Ray2D", "Line2D", "Segment3D", "Line3D", "Ray3D", "Segment", "Ray", "Line", "Plane", "Triangle", "RegularPolygon", "Polygon", "Circle", "Ellipse", "Curve", "Parabola" ] class GeometryEntity(Basic, EvalfMixin): """The base class for all geometrical entities. This class does not represent any particular geometric entity, it only provides the implementation of some methods common to all subclasses. """ __slots__ = () # type: tTuple[str, ...] def __cmp__(self, other): """Comparison of two GeometryEntities.""" n1 = self.__class__.__name__ n2 = other.__class__.__name__ c = (n1 > n2) - (n1 < n2) if not c: return 0 i1 = -1 for cls in self.__class__.__mro__: try: i1 = ordering_of_classes.index(cls.__name__) break except ValueError: i1 = -1 if i1 == -1: return c i2 = -1 for cls in other.__class__.__mro__: try: i2 = ordering_of_classes.index(cls.__name__) break except ValueError: i2 = -1 if i2 == -1: return c return (i1 > i2) - (i1 < i2) def __contains__(self, other): """Subclasses should implement this method for anything more complex than equality.""" if type(self) is type(other): return self == other raise NotImplementedError() def __getnewargs__(self): """Returns a tuple that will be passed to __new__ on unpickling.""" return tuple(self.args) def __ne__(self, o): """Test inequality of two geometrical entities.""" return not self == o def __new__(cls, *args, **kwargs): # Points are sequences, but they should not # be converted to Tuples, so use this detection function instead. def is_seq_and_not_point(a): # we cannot use isinstance(a, Point) since we cannot import Point if hasattr(a, 'is_Point') and a.is_Point: return False return is_sequence(a) args = [Tuple(*a) if is_seq_and_not_point(a) else sympify(a) for a in args] return Basic.__new__(cls, *args) def __radd__(self, a): """Implementation of reverse add method.""" return a.__add__(self) def __rtruediv__(self, a): """Implementation of reverse division method.""" return a.__truediv__(self) def __repr__(self): """String representation of a GeometryEntity that can be evaluated by sympy.""" return type(self).__name__ + repr(self.args) def __rmul__(self, a): """Implementation of reverse multiplication method.""" return a.__mul__(self) def __rsub__(self, a): """Implementation of reverse subtraction method.""" return a.__sub__(self) def __str__(self): """String representation of a GeometryEntity.""" return type(self).__name__ + sstr(self.args) def _eval_subs(self, old, new): from sympy.geometry.point import Point, Point3D if is_sequence(old) or is_sequence(new): if isinstance(self, Point3D): old = Point3D(old) new = Point3D(new) else: old = Point(old) new = Point(new) return self._subs(old, new) def _repr_svg_(self): """SVG representation of a GeometryEntity suitable for IPython""" try: bounds = self.bounds except (NotImplementedError, TypeError): # if we have no SVG representation, return None so IPython # will fall back to the next representation return None if not all(x.is_number and x.is_finite for x in bounds): return None svg_top = '''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{1}" height="{2}" viewBox="{0}" preserveAspectRatio="xMinYMin meet"> <defs> <marker id="markerCircle" markerWidth="8" markerHeight="8" refx="5" refy="5" markerUnits="strokeWidth"> <circle cx="5" cy="5" r="1.5" style="stroke: none; fill:#000000;"/> </marker> <marker id="markerArrow" markerWidth="13" markerHeight="13" refx="2" refy="4" orient="auto" markerUnits="strokeWidth"> <path d="M2,2 L2,6 L6,4" style="fill: #000000;" /> </marker> <marker id="markerReverseArrow" markerWidth="13" markerHeight="13" refx="6" refy="4" orient="auto" markerUnits="strokeWidth"> <path d="M6,2 L6,6 L2,4" style="fill: #000000;" /> </marker> </defs>''' # Establish SVG canvas that will fit all the data + small space xmin, ymin, xmax, ymax = map(N, bounds) if xmin == xmax and ymin == ymax: # This is a point; buffer using an arbitrary size xmin, ymin, xmax, ymax = xmin - .5, ymin -.5, xmax + .5, ymax + .5 else: # Expand bounds by a fraction of the data ranges expand = 0.1 # or 10%; this keeps arrowheads in view (R plots use 4%) widest_part = max([xmax - xmin, ymax - ymin]) expand_amount = widest_part * expand xmin -= expand_amount ymin -= expand_amount xmax += expand_amount ymax += expand_amount dx = xmax - xmin dy = ymax - ymin width = min([max([100., dx]), 300]) height = min([max([100., dy]), 300]) scale_factor = 1. if max(width, height) == 0 else max(dx, dy) / max(width, height) try: svg = self._svg(scale_factor) except (NotImplementedError, TypeError): # if we have no SVG representation, return None so IPython # will fall back to the next representation return None view_box = "{} {} {} {}".format(xmin, ymin, dx, dy) transform = "matrix(1,0,0,-1,0,{})".format(ymax + ymin) svg_top = svg_top.format(view_box, width, height) return svg_top + ( '<g transform="{}">{}</g></svg>' ).format(transform, svg) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the GeometryEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ raise NotImplementedError() def _sympy_(self): return self @property def ambient_dimension(self): """What is the dimension of the space that the object is contained in?""" raise NotImplementedError() @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ raise NotImplementedError() def encloses(self, o): """ Return True if o is inside (not on or outside) the boundaries of self. The object will be decomposed into Points and individual Entities need only define an encloses_point method for their class. See Also ======== sympy.geometry.ellipse.Ellipse.encloses_point sympy.geometry.polygon.Polygon.encloses_point Examples ======== >>> from sympy import RegularPolygon, Point, Polygon >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices) >>> t2.encloses(t) True >>> t.encloses(t2) False """ from sympy.geometry.point import Point from sympy.geometry.line import Segment, Ray, Line from sympy.geometry.ellipse import Ellipse from sympy.geometry.polygon import Polygon, RegularPolygon if isinstance(o, Point): return self.encloses_point(o) elif isinstance(o, Segment): return all(self.encloses_point(x) for x in o.points) elif isinstance(o, (Ray, Line)): return False elif isinstance(o, Ellipse): return self.encloses_point(o.center) and \ self.encloses_point( Point(o.center.x + o.hradius, o.center.y)) and \ not self.intersection(o) elif isinstance(o, Polygon): if isinstance(o, RegularPolygon): if not self.encloses_point(o.center): return False return all(self.encloses_point(v) for v in o.vertices) raise NotImplementedError() def equals(self, o): return self == o def intersection(self, o): """ Returns a list of all of the intersections of self with o. Notes ===== An entity is not required to implement this method. If two different types of entities can intersect, the item with higher index in ordering_of_classes should implement intersections with anything having a lower index. See Also ======== sympy.geometry.util.intersection """ raise NotImplementedError() def is_similar(self, other): """Is this geometrical entity similar to another geometrical entity? Two entities are similar if a uniform scaling (enlarging or shrinking) of one of the entities will allow one to obtain the other. Notes ===== This method is not intended to be used directly but rather through the `are_similar` function found in util.py. An entity is not required to implement this method. If two different types of entities can be similar, it is only required that one of them be able to determine this. See Also ======== scale """ raise NotImplementedError() def reflect(self, line): """ Reflects an object across a line. Parameters ========== line: Line Examples ======== >>> from sympy import pi, sqrt, Line, RegularPolygon >>> l = Line((0, pi), slope=sqrt(2)) >>> pent = RegularPolygon((1, 2), 1, 5) >>> rpent = pent.reflect(l) >>> rpent RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5) >>> from sympy import pi, Line, Circle, Point >>> l = Line((0, pi), slope=1) >>> circ = Circle(Point(0, 0), 5) >>> rcirc = circ.reflect(l) >>> rcirc Circle(Point2D(-pi, pi), -5) """ from sympy.geometry.point import Point g = self l = line o = Point(0, 0) if l.slope.is_zero: y = l.args[0].y if not y: # x-axis return g.scale(y=-1) reps = [(p, p.translate(y=2*(y - p.y))) for p in g.atoms(Point)] elif l.slope is oo: x = l.args[0].x if not x: # y-axis return g.scale(x=-1) reps = [(p, p.translate(x=2*(x - p.x))) for p in g.atoms(Point)] else: if not hasattr(g, 'reflect') and not all( isinstance(arg, Point) for arg in g.args): raise NotImplementedError( 'reflect undefined or non-Point args in %s' % g) a = atan(l.slope) c = l.coefficients d = -c[-1]/c[1] # y-intercept # apply the transform to a single point x, y = Dummy(), Dummy() xf = Point(x, y) xf = xf.translate(y=-d).rotate(-a, o).scale(y=-1 ).rotate(a, o).translate(y=d) # replace every point using that transform reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)] return g.xreplace(dict(reps)) def rotate(self, angle, pt=None): """Rotate ``angle`` radians counterclockwise about Point ``pt``. The default pt is the origin, Point(0, 0) See Also ======== scale, translate Examples ======== >>> from sympy import Point, RegularPolygon, Polygon, pi >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t # vertex on x axis Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2)) >>> t.rotate(pi/2) # vertex on y axis now Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2)) """ newargs = [] for a in self.args: if isinstance(a, GeometryEntity): newargs.append(a.rotate(angle, pt)) else: newargs.append(a) return type(self)(*newargs) def scale(self, x=1, y=1, pt=None): """Scale the object by multiplying the x,y-coordinates by x and y. If pt is given, the scaling is done relative to that point; the object is shifted by -pt, scaled, and shifted by pt. See Also ======== rotate, translate Examples ======== >>> from sympy import RegularPolygon, Point, Polygon >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2)) >>> t.scale(2) Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2)) >>> t.scale(2, 2) Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3))) """ from sympy.geometry.point import Point if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) return type(self)(*[a.scale(x, y) for a in self.args]) # if this fails, override this class def translate(self, x=0, y=0): """Shift the object by adding to the x,y-coordinates the values x and y. See Also ======== rotate, scale Examples ======== >>> from sympy import RegularPolygon, Point, Polygon >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2)) >>> t.translate(2) Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2)) >>> t.translate(2, 2) Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2)) """ newargs = [] for a in self.args: if isinstance(a, GeometryEntity): newargs.append(a.translate(x, y)) else: newargs.append(a) return self.func(*newargs) def parameter_value(self, other, t): """Return the parameter corresponding to the given point. Evaluating an arbitrary point of the entity at this parameter value will return the given point. Examples ======== >>> from sympy import Line, Point >>> from sympy.abc import t >>> a = Point(0, 0) >>> b = Point(2, 2) >>> Line(a, b).parameter_value((1, 1), t) {t: 1/2} >>> Line(a, b).arbitrary_point(t).subs(_) Point2D(1, 1) """ from sympy.geometry.point import Point if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other, Point): raise ValueError("other must be a point") T = Dummy('t', real=True) sol = solve(self.arbitrary_point(T) - other, T, dict=True) if not sol: raise ValueError("Given point is not on %s" % func_name(self)) return {t: sol[0][T]} class GeometrySet(GeometryEntity, Set): """Parent class of all GeometryEntity that are also Sets (compatible with sympy.sets) """ __slots__ = () def _contains(self, other): """sympy.sets uses the _contains method, so include it for compatibility.""" if isinstance(other, Set) and other.is_FiniteSet: return all(self.__contains__(i) for i in other) return self.__contains__(other) @dispatch(GeometrySet, Set) # type:ignore # noqa:F811 def union_sets(self, o): # noqa:F811 """ Returns the union of self and o for use with sympy.sets.Set, if possible. """ # if its a FiniteSet, merge any points # we contain and return a union with the rest if o.is_FiniteSet: other_points = [p for p in o if not self._contains(p)] if len(other_points) == len(o): return None return Union(self, FiniteSet(*other_points)) if self._contains(o): return self return None @dispatch(GeometrySet, Set) # type: ignore # noqa:F811 def intersection_sets(self, o): # noqa:F811 """ Returns a sympy.sets.Set of intersection objects, if possible. """ from sympy.geometry.point import Point try: # if o is a FiniteSet, find the intersection directly # to avoid infinite recursion if o.is_FiniteSet: inter = FiniteSet(*(p for p in o if self.contains(p))) else: inter = self.intersection(o) except NotImplementedError: # sympy.sets.Set.reduce expects None if an object # doesn't know how to simplify return None # put the points in a FiniteSet points = FiniteSet(*[p for p in inter if isinstance(p, Point)]) non_points = [p for p in inter if not isinstance(p, Point)] return Union(*(non_points + [points])) def translate(x, y): """Return the matrix to translate a 2-D point by x and y.""" rv = eye(3) rv[2, 0] = x rv[2, 1] = y return rv def scale(x, y, pt=None): """Return the matrix to multiply a 2-D point's coordinates by x and y. If pt is given, the scaling is done relative to that point.""" rv = eye(3) rv[0, 0] = x rv[1, 1] = y if pt: from sympy.geometry.point import Point pt = Point(pt, dim=2) tr1 = translate(*(-pt).args) tr2 = translate(*pt.args) return tr1*rv*tr2 return rv def rotate(th): """Return the matrix to rotate a 2-D point about the origin by ``angle``. The angle is measured in radians. To Point a point about a point other then the origin, translate the Point, do the rotation, and translate it back: >>> from sympy.geometry.entity import rotate, translate >>> from sympy import Point, pi >>> rot_about_11 = translate(-1, -1)*rotate(pi/2)*translate(1, 1) >>> Point(1, 1).transform(rot_about_11) Point2D(1, 1) >>> Point(0, 0).transform(rot_about_11) Point2D(2, 0) """ s = sin(th) rv = eye(3)*cos(th) rv[0, 1] = s rv[1, 0] = -s rv[2, 2] = 1 return rv
d82b08c46c9b983e2304e462a14e68f80fc0a9e54acfbb5e6b36c351db3a97cd
"""Utility functions for geometrical entities. Contains ======== intersection convex_hull closest_points farthest_points are_coplanar are_similar """ from collections import deque from math import sqrt as _sqrt from .entity import GeometryEntity from .exceptions import GeometryError from .point import Point, Point2D, Point3D from sympy.core.containers import OrderedSet from sympy.core.function import Function from sympy.core.sorting import ordered from sympy.core.symbol import Symbol from sympy.functions.elementary.miscellaneous import sqrt from sympy.solvers.solvers import solve from sympy.utilities.iterables import is_sequence def find(x, equation): """ Checks whether a Symbol matching ``x`` is present in ``equation`` or not. If present, the matching symbol is returned, else a ValueError is raised. If ``x`` is a string the matching symbol will have the same name; if ``x`` is a Symbol then it will be returned if found. Examples ======== >>> from sympy.geometry.util import find >>> from sympy import Dummy >>> from sympy.abc import x >>> find('x', x) x >>> find('x', Dummy('x')) _x The dummy symbol is returned since it has a matching name: >>> _.name == 'x' True >>> find(x, Dummy('x')) Traceback (most recent call last): ... ValueError: could not find x """ free = equation.free_symbols xs = [i for i in free if (i.name if isinstance(x, str) else i) == x] if not xs: raise ValueError('could not find %s' % x) if len(xs) != 1: raise ValueError('ambiguous %s' % x) return xs[0] def _ordered_points(p): """Return the tuple of points sorted numerically according to args""" return tuple(sorted(p, key=lambda x: x.args)) def are_coplanar(*e): """ Returns True if the given entities are coplanar otherwise False Parameters ========== e: entities to be checked for being coplanar Returns ======= Boolean Examples ======== >>> from sympy import Point3D, Line3D >>> from sympy.geometry.util import are_coplanar >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1)) >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1)) >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9)) >>> are_coplanar(a, b, c) False """ from .line import LinearEntity3D from .plane import Plane # XXX update tests for coverage e = set(e) # first work with a Plane if present for i in list(e): if isinstance(i, Plane): e.remove(i) return all(p.is_coplanar(i) for p in e) if all(isinstance(i, Point3D) for i in e): if len(e) < 3: return False # remove pts that are collinear with 2 pts a, b = e.pop(), e.pop() for i in list(e): if Point3D.are_collinear(a, b, i): e.remove(i) if not e: return False else: # define a plane p = Plane(a, b, e.pop()) for i in e: if i not in p: return False return True else: pt3d = [] for i in e: if isinstance(i, Point3D): pt3d.append(i) elif isinstance(i, LinearEntity3D): pt3d.extend(i.args) elif isinstance(i, GeometryEntity): # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised # all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0 for p in i.args: if isinstance(p, Point): pt3d.append(Point3D(*(p.args + (0,)))) return are_coplanar(*pt3d) def are_similar(e1, e2): """Are two geometrical entities similar. Can one geometrical entity be uniformly scaled to the other? Parameters ========== e1 : GeometryEntity e2 : GeometryEntity Returns ======= are_similar : boolean Raises ====== GeometryError When `e1` and `e2` cannot be compared. Notes ===== If the two objects are equal then they are similar. See Also ======== sympy.geometry.entity.GeometryEntity.is_similar Examples ======== >>> from sympy import Point, Circle, Triangle, are_similar >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3) >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2)) >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1)) >>> are_similar(t1, t2) True >>> are_similar(t1, t3) False """ if e1 == e2: return True is_similar1 = getattr(e1, 'is_similar', None) if is_similar1: return is_similar1(e2) is_similar2 = getattr(e2, 'is_similar', None) if is_similar2: return is_similar2(e1) n1 = e1.__class__.__name__ n2 = e2.__class__.__name__ raise GeometryError( "Cannot test similarity between %s and %s" % (n1, n2)) def centroid(*args): """Find the centroid (center of mass) of the collection containing only Points, Segments or Polygons. The centroid is the weighted average of the individual centroid where the weights are the lengths (of segments) or areas (of polygons). Overlapping regions will add to the weight of that region. If there are no objects (or a mixture of objects) then None is returned. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment, sympy.geometry.polygon.Polygon Examples ======== >>> from sympy import Point, Segment, Polygon >>> from sympy.geometry.util import centroid >>> p = Polygon((0, 0), (10, 0), (10, 10)) >>> q = p.translate(0, 20) >>> p.centroid, q.centroid (Point2D(20/3, 10/3), Point2D(20/3, 70/3)) >>> centroid(p, q) Point2D(20/3, 40/3) >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2)) >>> centroid(p, q) Point2D(1, 2 - sqrt(2)) >>> centroid(Point(0, 0), Point(2, 0)) Point2D(1, 0) Stacking 3 polygons on top of each other effectively triples the weight of that polygon: >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1)) >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1)) >>> centroid(p, q) Point2D(3/2, 1/2) >>> centroid(p, p, p, q) # centroid x-coord shifts left Point2D(11/10, 1/2) Stacking the squares vertically above and below p has the same effect: >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q) Point2D(11/10, 1/2) """ from .line import Segment from .polygon import Polygon if args: if all(isinstance(g, Point) for g in args): c = Point(0, 0) for g in args: c += g den = len(args) elif all(isinstance(g, Segment) for g in args): c = Point(0, 0) L = 0 for g in args: l = g.length c += g.midpoint*l L += l den = L elif all(isinstance(g, Polygon) for g in args): c = Point(0, 0) A = 0 for g in args: a = g.area c += g.centroid*a A += a den = A c /= den return c.func(*[i.simplify() for i in c.args]) def closest_points(*args): """Return the subset of points from a set of points that were the closest to each other in the 2D plane. Parameters ========== args : a collection of Points on 2D plane. Notes ===== This can only be performed on a set of points whose coordinates can be ordered on the number line. If there are no ties then a single pair of Points will be in the set. Examples ======== >>> from sympy import closest_points, Triangle >>> Triangle(sss=(3, 4, 5)).args (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4)) >>> closest_points(*_) {(Point2D(0, 0), Point2D(3, 0))} References ========== .. [1] http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html .. [2] Sweep line algorithm https://en.wikipedia.org/wiki/Sweep_line_algorithm """ p = [Point2D(i) for i in set(args)] if len(p) < 2: raise ValueError('At least 2 distinct points must be given.') try: p.sort(key=lambda x: x.args) except TypeError: raise ValueError("The points could not be sorted.") if not all(i.is_Rational for j in p for i in j.args): def hypot(x, y): arg = x*x + y*y if arg.is_Rational: return _sqrt(arg) return sqrt(arg) else: from math import hypot rv = [(0, 1)] best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y) i = 2 left = 0 box = deque([0, 1]) while i < len(p): while left < i and p[i][0] - p[left][0] > best_dist: box.popleft() left += 1 for j in box: d = hypot(p[i].x - p[j].x, p[i].y - p[j].y) if d < best_dist: rv = [(j, i)] elif d == best_dist: rv.append((j, i)) else: continue best_dist = d box.append(i) i += 1 return {tuple([p[i] for i in pair]) for pair in rv} def convex_hull(*args, polygon=True): """The convex hull surrounding the Points contained in the list of entities. Parameters ========== args : a collection of Points, Segments and/or Polygons Optional parameters =================== polygon : Boolean. If True, returns a Polygon, if false a tuple, see below. Default is True. Returns ======= convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where ``L`` and ``U`` are the lower and upper hulls, respectively. Notes ===== This can only be performed on a set of points whose coordinates can be ordered on the number line. See Also ======== sympy.geometry.point.Point, sympy.geometry.polygon.Polygon Examples ======== >>> from sympy import convex_hull >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)] >>> convex_hull(*points) Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)) >>> convex_hull(*points, **dict(polygon=False)) ([Point2D(-5, 2), Point2D(15, 4)], [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)]) References ========== .. [1] https://en.wikipedia.org/wiki/Graham_scan .. [2] Andrew's Monotone Chain Algorithm (A.M. Andrew, "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979) http://geomalgorithms.com/a10-_hull-1.html """ from .line import Segment from .polygon import Polygon p = OrderedSet() for e in args: if not isinstance(e, GeometryEntity): try: e = Point(e) except NotImplementedError: raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e)) if isinstance(e, Point): p.add(e) elif isinstance(e, Segment): p.update(e.points) elif isinstance(e, Polygon): p.update(e.vertices) else: raise NotImplementedError( 'Convex hull for %s not implemented.' % type(e)) # make sure all our points are of the same dimension if any(len(x) != 2 for x in p): raise ValueError('Can only compute the convex hull in two dimensions') p = list(p) if len(p) == 1: return p[0] if polygon else (p[0], None) elif len(p) == 2: s = Segment(p[0], p[1]) return s if polygon else (s, None) def _orientation(p, q, r): '''Return positive if p-q-r are clockwise, neg if ccw, zero if collinear.''' return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y) # scan to find upper and lower convex hulls of a set of 2d points. U = [] L = [] try: p.sort(key=lambda x: x.args) except TypeError: raise ValueError("The points could not be sorted.") for p_i in p: while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0: U.pop() while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0: L.pop() U.append(p_i) L.append(p_i) U.reverse() convexHull = tuple(L + U[1:-1]) if len(convexHull) == 2: s = Segment(convexHull[0], convexHull[1]) return s if polygon else (s, None) if polygon: return Polygon(*convexHull) else: U.reverse() return (U, L) def farthest_points(*args): """Return the subset of points from a set of points that were the furthest apart from each other in the 2D plane. Parameters ========== args : a collection of Points on 2D plane. Notes ===== This can only be performed on a set of points whose coordinates can be ordered on the number line. If there are no ties then a single pair of Points will be in the set. Examples ======== >>> from sympy.geometry import farthest_points, Triangle >>> Triangle(sss=(3, 4, 5)).args (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4)) >>> farthest_points(*_) {(Point2D(0, 0), Point2D(3, 4))} References ========== .. [1] http://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/ .. [2] Rotating Callipers Technique https://en.wikipedia.org/wiki/Rotating_calipers """ def rotatingCalipers(Points): U, L = convex_hull(*Points, **dict(polygon=False)) if L is None: if isinstance(U, Point): raise ValueError('At least two distinct points must be given.') yield U.args else: i = 0 j = len(L) - 1 while i < len(U) - 1 or j > 0: yield U[i], L[j] # if all the way through one side of hull, advance the other side if i == len(U) - 1: j -= 1 elif j == 0: i += 1 # still points left on both lists, compare slopes of next hull edges # being careful to avoid divide-by-zero in slope calculation elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \ (L[j].y - L[j-1].y) * (U[i+1].x - U[i].x): i += 1 else: j -= 1 p = [Point2D(i) for i in set(args)] if not all(i.is_Rational for j in p for i in j.args): def hypot(x, y): arg = x*x + y*y if arg.is_Rational: return _sqrt(arg) return sqrt(arg) else: from math import hypot rv = [] diam = 0 for pair in rotatingCalipers(args): h, q = _ordered_points(pair) d = hypot(h.x - q.x, h.y - q.y) if d > diam: rv = [(h, q)] elif d == diam: rv.append((h, q)) else: continue diam = d return set(rv) def idiff(eq, y, x, n=1): """Return ``dy/dx`` assuming that ``eq == 0``. Parameters ========== y : the dependent variable or a list of dependent variables (with y first) x : the variable that the derivative is being taken with respect to n : the order of the derivative (default is 1) Examples ======== >>> from sympy.abc import x, y, a >>> from sympy.geometry.util import idiff >>> circ = x**2 + y**2 - 4 >>> idiff(circ, y, x) -x/y >>> idiff(circ, y, x, 2).simplify() (-x**2 - y**2)/y**3 Here, ``a`` is assumed to be independent of ``x``: >>> idiff(x + a + y, y, x) -1 Now the x-dependence of ``a`` is made explicit by listing ``a`` after ``y`` in a list. >>> idiff(x + a + y, [y, a], x) -Derivative(a, x) - 1 See Also ======== sympy.core.function.Derivative: represents unevaluated derivatives sympy.core.function.diff: explicitly differentiates wrt symbols """ if is_sequence(y): dep = set(y) y = y[0] elif isinstance(y, Symbol): dep = {y} elif isinstance(y, Function): pass else: raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y) f = {s: Function(s.name)(x) for s in eq.free_symbols if s != x and s in dep} if isinstance(y, Symbol): dydx = Function(y.name)(x).diff(x) else: dydx = y.diff(x) eq = eq.subs(f) derivs = {} for i in range(n): yp = solve(eq.diff(x), dydx)[0].subs(derivs) if i == n - 1: return yp.subs([(v, k) for k, v in f.items()]) derivs[dydx] = yp eq = dydx - yp dydx = dydx.diff(x) def intersection(*entities, pairwise=False, **kwargs): """The intersection of a collection of GeometryEntity instances. Parameters ========== entities : sequence of GeometryEntity pairwise (keyword argument) : Can be either True or False Returns ======= intersection : list of GeometryEntity Raises ====== NotImplementedError When unable to calculate intersection. Notes ===== The intersection of any geometrical entity with itself should return a list with one item: the entity in question. An intersection requires two or more entities. If only a single entity is given then the function will return an empty list. It is possible for `intersection` to miss intersections that one knows exists because the required quantities were not fully simplified internally. Reals should be converted to Rationals, e.g. Rational(str(real_num)) or else failures due to floating point issues may result. Case 1: When the keyword argument 'pairwise' is False (default value): In this case, the function returns a list of intersections common to all entities. Case 2: When the keyword argument 'pairwise' is True: In this case, the functions returns a list intersections that occur between any pair of entities. See Also ======== sympy.geometry.entity.GeometryEntity.intersection Examples ======== >>> from sympy import Ray, Circle, intersection >>> c = Circle((0, 1), 1) >>> intersection(c, c.center) [] >>> right = Ray((0, 0), (1, 0)) >>> up = Ray((0, 0), (0, 1)) >>> intersection(c, right, up) [Point2D(0, 0)] >>> intersection(c, right, up, pairwise=True) [Point2D(0, 0), Point2D(0, 2)] >>> left = Ray((1, 0), (0, 0)) >>> intersection(right, left) [Segment2D(Point2D(0, 0), Point2D(1, 0))] """ if len(entities) <= 1: return [] # entities may be an immutable tuple entities = list(entities) for i, e in enumerate(entities): if not isinstance(e, GeometryEntity): entities[i] = Point(e) if not pairwise: # find the intersection common to all objects res = entities[0].intersection(entities[1]) for entity in entities[2:]: newres = [] for x in res: newres.extend(x.intersection(entity)) res = newres return res # find all pairwise intersections ans = [] for j in range(0, len(entities)): for k in range(j + 1, len(entities)): ans.extend(intersection(entities[j], entities[k])) return list(ordered(set(ans)))
5c37e89ffce0c67990cbbe896b26316e4ba9fde9c544892434db90dc44e26771
"""Line-like geometrical entities. Contains ======== LinearEntity Line Ray Segment LinearEntity2D Line2D Ray2D Segment2D LinearEntity3D Line3D Ray3D Segment3D """ from sympy.core.containers import Tuple from sympy.core.evalf import N from sympy.core.expr import Expr from sympy.core.numbers import Rational, oo, Float from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import _symbol, Dummy, uniquely_named_symbol from sympy.core.sympify import sympify from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (_pi_coeff as pi_coeff, acos, tan, atan2) from .entity import GeometryEntity, GeometrySet from .exceptions import GeometryError from .point import Point, Point3D from .util import find, intersection from sympy.logic.boolalg import And from sympy.matrices import Matrix from sympy.sets.sets import Intersection from sympy.simplify.simplify import simplify from sympy.solvers.solvers import solve from sympy.solvers.solveset import linear_coeffs from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.misc import Undecidable, filldedent import random class LinearEntity(GeometrySet): """A base class for all linear entities (Line, Ray and Segment) in n-dimensional Euclidean space. Attributes ========== ambient_dimension direction length p1 p2 points Notes ===== This is an abstract class and is not meant to be instantiated. See Also ======== sympy.geometry.entity.GeometryEntity """ def __new__(cls, p1, p2=None, **kwargs): p1, p2 = Point._normalize_dimension(p1, p2) if p1 == p2: # sometimes we return a single point if we are not given two unique # points. This is done in the specific subclass raise ValueError( "%s.__new__ requires two unique Points." % cls.__name__) if len(p1) != len(p2): raise ValueError( "%s.__new__ requires two Points of equal dimension." % cls.__name__) return GeometryEntity.__new__(cls, p1, p2, **kwargs) def __contains__(self, other): """Return a definitive answer or else raise an error if it cannot be determined that other is on the boundaries of self.""" result = self.contains(other) if result is not None: return result else: raise Undecidable( "Cannot decide whether '%s' contains '%s'" % (self, other)) def _span_test(self, other): """Test whether the point `other` lies in the positive span of `self`. A point x is 'in front' of a point y if x.dot(y) >= 0. Return -1 if `other` is behind `self.p1`, 0 if `other` is `self.p1` and and 1 if `other` is in front of `self.p1`.""" if self.p1 == other: return 0 rel_pos = other - self.p1 d = self.direction if d.dot(rel_pos) > 0: return 1 return -1 @property def ambient_dimension(self): """A property method that returns the dimension of LinearEntity object. Parameters ========== p1 : LinearEntity Returns ======= dimension : integer Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> l1 = Line(p1, p2) >>> l1.ambient_dimension 2 >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1) >>> l1 = Line(p1, p2) >>> l1.ambient_dimension 3 """ return len(self.p1) def angle_between(l1, l2): """Return the non-reflex angle formed by rays emanating from the origin with directions the same as the direction vectors of the linear entities. Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= angle : angle in radians Notes ===== From the dot product of vectors v1 and v2 it is known that: ``dot(v1, v2) = |v1|*|v2|*cos(A)`` where A is the angle formed between the two vectors. We can get the directional vectors of the two lines and readily find the angle between the two using the above formula. See Also ======== is_perpendicular, Ray2D.closing_angle Examples ======== >>> from sympy import Line >>> e = Line((0, 0), (1, 0)) >>> ne = Line((0, 0), (1, 1)) >>> sw = Line((1, 1), (0, 0)) >>> ne.angle_between(e) pi/4 >>> sw.angle_between(e) 3*pi/4 To obtain the non-obtuse angle at the intersection of lines, use the ``smallest_angle_between`` method: >>> sw.smallest_angle_between(e) pi/4 >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0) >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3) >>> l1.angle_between(l2) acos(-sqrt(2)/3) >>> l1.smallest_angle_between(l2) acos(sqrt(2)/3) """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') v1, v2 = l1.direction, l2.direction return acos(v1.dot(v2)/(abs(v1)*abs(v2))) def smallest_angle_between(l1, l2): """Return the smallest angle formed at the intersection of the lines containing the linear entities. Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= angle : angle in radians See Also ======== angle_between, is_perpendicular, Ray2D.closing_angle Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2) >>> l1, l2 = Line(p1, p2), Line(p1, p3) >>> l1.smallest_angle_between(l2) pi/4 See Also ======== angle_between, Ray2D.closing_angle """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') v1, v2 = l1.direction, l2.direction return acos(abs(v1.dot(v2))/(abs(v1)*abs(v2))) def arbitrary_point(self, parameter='t'): """A parameterized point on the Line. Parameters ========== parameter : str, optional The name of the parameter which will be used for the parametric point. The default value is 't'. When this parameter is 0, the first point used to define the line will be returned, and when it is 1 the second point will be returned. Returns ======= point : Point Raises ====== ValueError When ``parameter`` already appears in the Line's definition. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(1, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.arbitrary_point() Point2D(4*t + 1, 3*t) >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1) >>> l1 = Line3D(p1, p2) >>> l1.arbitrary_point() Point3D(4*t + 1, 3*t, t) """ t = _symbol(parameter, real=True) if t.name in (f.name for f in self.free_symbols): raise ValueError(filldedent(''' Symbol %s already appears in object and cannot be used as a parameter. ''' % t.name)) # multiply on the right so the variable gets # combined with the coordinates of the point return self.p1 + (self.p2 - self.p1)*t @staticmethod def are_concurrent(*lines): """Is a sequence of linear entities concurrent? Two or more linear entities are concurrent if they all intersect at a single point. Parameters ========== lines : a sequence of linear entities. Returns ======= True : if the set of linear entities intersect in one point False : otherwise. See Also ======== sympy.geometry.util.intersection Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(3, 5) >>> p3, p4 = Point(-2, -2), Point(0, 2) >>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4) >>> Line.are_concurrent(l1, l2, l3) True >>> l4 = Line(p2, p3) >>> Line.are_concurrent(l2, l3, l4) False >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2) >>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1) >>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4) >>> Line3D.are_concurrent(l1, l2, l3) True >>> l4 = Line3D(p2, p3) >>> Line3D.are_concurrent(l2, l3, l4) False """ common_points = Intersection(*lines) if common_points.is_FiniteSet and len(common_points) == 1: return True return False def contains(self, other): """Subclasses should implement this method and should return True if other is on the boundaries of self; False if not on the boundaries of self; None if a determination cannot be made.""" raise NotImplementedError() @property def direction(self): """The direction vector of the LinearEntity. Returns ======= p : a Point; the ray from the origin to this point is the direction of `self` Examples ======== >>> from sympy import Line >>> a, b = (1, 1), (1, 3) >>> Line(a, b).direction Point2D(0, 2) >>> Line(b, a).direction Point2D(0, -2) This can be reported so the distance from the origin is 1: >>> Line(b, a).direction.unit Point2D(0, -1) See Also ======== sympy.geometry.point.Point.unit """ return self.p2 - self.p1 def intersection(self, other): """The intersection with another geometrical entity. Parameters ========== o : Point or LinearEntity Returns ======= intersection : list of geometrical entities See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line, Segment >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) >>> l1 = Line(p1, p2) >>> l1.intersection(p3) [Point2D(7, 7)] >>> p4, p5 = Point(5, 0), Point(0, 3) >>> l2 = Line(p4, p5) >>> l1.intersection(l2) [Point2D(15/8, 15/8)] >>> p6, p7 = Point(0, 5), Point(2, 6) >>> s1 = Segment(p6, p7) >>> l1.intersection(s1) [] >>> from sympy import Point3D, Line3D, Segment3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7) >>> l1 = Line3D(p1, p2) >>> l1.intersection(p3) [Point3D(7, 7, 7)] >>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17)) >>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8]) >>> l1.intersection(l2) [Point3D(1, 1, -3)] >>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3) >>> s1 = Segment3D(p6, p7) >>> l1.intersection(s1) [] """ def intersect_parallel_rays(ray1, ray2): if ray1.direction.dot(ray2.direction) > 0: # rays point in the same direction # so return the one that is "in front" return [ray2] if ray1._span_test(ray2.p1) >= 0 else [ray1] else: # rays point in opposite directions st = ray1._span_test(ray2.p1) if st < 0: return [] elif st == 0: return [ray2.p1] return [Segment(ray1.p1, ray2.p1)] def intersect_parallel_ray_and_segment(ray, seg): st1, st2 = ray._span_test(seg.p1), ray._span_test(seg.p2) if st1 < 0 and st2 < 0: return [] elif st1 >= 0 and st2 >= 0: return [seg] elif st1 >= 0: # st2 < 0: return [Segment(ray.p1, seg.p1)] else: # st1 < 0 and st2 >= 0: return [Segment(ray.p1, seg.p2)] def intersect_parallel_segments(seg1, seg2): if seg1.contains(seg2): return [seg2] if seg2.contains(seg1): return [seg1] # direct the segments so they're oriented the same way if seg1.direction.dot(seg2.direction) < 0: seg2 = Segment(seg2.p2, seg2.p1) # order the segments so seg1 is "behind" seg2 if seg1._span_test(seg2.p1) < 0: seg1, seg2 = seg2, seg1 if seg2._span_test(seg1.p2) < 0: return [] return [Segment(seg2.p1, seg1.p2)] if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if other.is_Point: if self.contains(other): return [other] else: return [] elif isinstance(other, LinearEntity): # break into cases based on whether # the lines are parallel, non-parallel intersecting, or skew pts = Point._normalize_dimension(self.p1, self.p2, other.p1, other.p2) rank = Point.affine_rank(*pts) if rank == 1: # we're collinear if isinstance(self, Line): return [other] if isinstance(other, Line): return [self] if isinstance(self, Ray) and isinstance(other, Ray): return intersect_parallel_rays(self, other) if isinstance(self, Ray) and isinstance(other, Segment): return intersect_parallel_ray_and_segment(self, other) if isinstance(self, Segment) and isinstance(other, Ray): return intersect_parallel_ray_and_segment(other, self) if isinstance(self, Segment) and isinstance(other, Segment): return intersect_parallel_segments(self, other) elif rank == 2: # we're in the same plane l1 = Line(*pts[:2]) l2 = Line(*pts[2:]) # check to see if we're parallel. If we are, we can't # be intersecting, since the collinear case was already # handled if l1.direction.is_scalar_multiple(l2.direction): return [] # find the intersection as if everything were lines # by solving the equation t*d + p1 == s*d' + p1' m = Matrix([l1.direction, -l2.direction]).transpose() v = Matrix([l2.p1 - l1.p1]).transpose() # we cannot use m.solve(v) because that only works for square matrices m_rref, pivots = m.col_insert(2, v).rref(simplify=True) # rank == 2 ensures we have 2 pivots, but let's check anyway if len(pivots) != 2: raise GeometryError("Failed when solving Mx=b when M={} and b={}".format(m, v)) coeff = m_rref[0, 2] line_intersection = l1.direction*coeff + self.p1 # if both are lines, skip a containment check if isinstance(self, Line) and isinstance(other, Line): return [line_intersection] if ((isinstance(self, Line) or self.contains(line_intersection)) and other.contains(line_intersection)): return [line_intersection] if not self.atoms(Float) and not other.atoms(Float): # if it can fail when there are no Floats then # maybe the following parametric check should be # done return [] # floats may fail exact containment so check that the # arbitrary points, when equal, both give a # non-negative parameter when the arbitrary point # coordinates are equated t, u = [Dummy(i) for i in 'tu'] tu = solve(self.arbitrary_point(t) - other.arbitrary_point(u), t, u, dict=True)[0] def ok(p, l): if isinstance(l, Line): # p > -oo return True if isinstance(l, Ray): # p >= 0 return p.is_nonnegative if isinstance(l, Segment): # 0 <= p <= 1 return p.is_nonnegative and (1 - p).is_nonnegative raise ValueError("unexpected line type") if ok(tu[t], self) and ok(tu[u], other): return [line_intersection] return [] else: # we're skew return [] return other.intersection(self) def is_parallel(l1, l2): """Are two linear entities parallel? Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= True : if l1 and l2 are parallel, False : otherwise. See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> p3, p4 = Point(3, 4), Point(6, 7) >>> l1, l2 = Line(p1, p2), Line(p3, p4) >>> Line.is_parallel(l1, l2) True >>> p5 = Point(6, 6) >>> l3 = Line(p3, p5) >>> Line.is_parallel(l1, l3) False >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5) >>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11) >>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4) >>> Line3D.is_parallel(l1, l2) True >>> p5 = Point3D(6, 6, 6) >>> l3 = Line3D(p3, p5) >>> Line3D.is_parallel(l1, l3) False """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') return l1.direction.is_scalar_multiple(l2.direction) def is_perpendicular(l1, l2): """Are two linear entities perpendicular? Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= True : if l1 and l2 are perpendicular, False : otherwise. See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1) >>> l1, l2 = Line(p1, p2), Line(p1, p3) >>> l1.is_perpendicular(l2) True >>> p4 = Point(5, 3) >>> l3 = Line(p1, p4) >>> l1.is_perpendicular(l3) False >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0) >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3) >>> l1.is_perpendicular(l2) False >>> p4 = Point3D(5, 3, 7) >>> l3 = Line3D(p1, p4) >>> l1.is_perpendicular(l3) False """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') return S.Zero.equals(l1.direction.dot(l2.direction)) def is_similar(self, other): """ Return True if self and other are contained in the same line. Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3) >>> l1 = Line(p1, p2) >>> l2 = Line(p1, p3) >>> l1.is_similar(l2) True """ l = Line(self.p1, self.p2) return l.contains(other) @property def length(self): """ The length of the line. Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(3, 5) >>> l1 = Line(p1, p2) >>> l1.length oo """ return S.Infinity @property def p1(self): """The first defining point of a linear entity. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.p1 Point2D(0, 0) """ return self.args[0] @property def p2(self): """The second defining point of a linear entity. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.p2 Point2D(5, 3) """ return self.args[1] def parallel_line(self, p): """Create a new Line parallel to this linear entity which passes through the point `p`. Parameters ========== p : Point Returns ======= line : Line See Also ======== is_parallel Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) >>> l1 = Line(p1, p2) >>> l2 = l1.parallel_line(p3) >>> p3 in l2 True >>> l1.is_parallel(l2) True >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0) >>> l1 = Line3D(p1, p2) >>> l2 = l1.parallel_line(p3) >>> p3 in l2 True >>> l1.is_parallel(l2) True """ p = Point(p, dim=self.ambient_dimension) return Line(p, p + self.direction) def perpendicular_line(self, p): """Create a new Line perpendicular to this linear entity which passes through the point `p`. Parameters ========== p : Point Returns ======= line : Line See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment Examples ======== >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0) >>> L = Line3D(p1, p2) >>> P = L.perpendicular_line(p3); P Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29)) >>> L.is_perpendicular(P) True In 3D the, the first point used to define the line is the point through which the perpendicular was required to pass; the second point is (arbitrarily) contained in the given line: >>> P.p2 in L True """ p = Point(p, dim=self.ambient_dimension) if p in self: p = p + self.direction.orthogonal_direction return Line(p, self.projection(p)) def perpendicular_segment(self, p): """Create a perpendicular line segment from `p` to this line. The enpoints of the segment are ``p`` and the closest point in the line containing self. (If self is not a line, the point might not be in self.) Parameters ========== p : Point Returns ======= segment : Segment Notes ===== Returns `p` itself if `p` is on this linear entity. See Also ======== perpendicular_line Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2) >>> l1 = Line(p1, p2) >>> s1 = l1.perpendicular_segment(p3) >>> l1.is_perpendicular(s1) True >>> p3 in s1 True >>> l1.perpendicular_segment(Point(4, 0)) Segment2D(Point2D(4, 0), Point2D(2, 2)) >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0) >>> l1 = Line3D(p1, p2) >>> s1 = l1.perpendicular_segment(p3) >>> l1.is_perpendicular(s1) True >>> p3 in s1 True >>> l1.perpendicular_segment(Point3D(4, 0, 0)) Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3)) """ p = Point(p, dim=self.ambient_dimension) if p in self: return p l = self.perpendicular_line(p) # The intersection should be unique, so unpack the singleton p2, = Intersection(Line(self.p1, self.p2), l) return Segment(p, p2) @property def points(self): """The two points used to define this linear entity. Returns ======= points : tuple of Points See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 11) >>> l1 = Line(p1, p2) >>> l1.points (Point2D(0, 0), Point2D(5, 11)) """ return (self.p1, self.p2) def projection(self, other): """Project a point, line, ray, or segment onto this linear entity. Parameters ========== other : Point or LinearEntity (Line, Ray, Segment) Returns ======= projection : Point or LinearEntity (Line, Ray, Segment) The return type matches the type of the parameter ``other``. Raises ====== GeometryError When method is unable to perform projection. Notes ===== A projection involves taking the two points that define the linear entity and projecting those points onto a Line and then reforming the linear entity using these projections. A point P is projected onto a line L by finding the point on L that is closest to P. This point is the intersection of L and the line perpendicular to L that passes through P. See Also ======== sympy.geometry.point.Point, perpendicular_line Examples ======== >>> from sympy import Point, Line, Segment, Rational >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0) >>> l1 = Line(p1, p2) >>> l1.projection(p3) Point2D(1/4, 1/4) >>> p4, p5 = Point(10, 0), Point(12, 1) >>> s1 = Segment(p4, p5) >>> l1.projection(s1) Segment2D(Point2D(5, 5), Point2D(13/2, 13/2)) >>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1) >>> l1 = Line(p1, p2) >>> l1.projection(p3) Point3D(2/3, 2/3, 5/3) >>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3) >>> s1 = Segment(p4, p5) >>> l1.projection(s1) Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6)) """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) def proj_point(p): return Point.project(p - self.p1, self.direction) + self.p1 if isinstance(other, Point): return proj_point(other) elif isinstance(other, LinearEntity): p1, p2 = proj_point(other.p1), proj_point(other.p2) # test to see if we're degenerate if p1 == p2: return p1 projected = other.__class__(p1, p2) projected = Intersection(self, projected) if projected.is_empty: return projected # if we happen to have intersected in only a point, return that if projected.is_FiniteSet and len(projected) == 1: # projected is a set of size 1, so unpack it in `a` a, = projected return a # order args so projection is in the same direction as self if self.direction.dot(projected.direction) < 0: p1, p2 = projected.args projected = projected.func(p2, p1) return projected raise GeometryError( "Do not know how to project %s onto %s" % (other, self)) def random_point(self, seed=None): """A random point on a LinearEntity. Returns ======= point : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line, Ray, Segment >>> p1, p2 = Point(0, 0), Point(5, 3) >>> line = Line(p1, p2) >>> r = line.random_point(seed=42) # seed value is optional >>> r.n(3) Point2D(-0.72, -0.432) >>> r in line True >>> Ray(p1, p2).random_point(seed=42).n(3) Point2D(0.72, 0.432) >>> Segment(p1, p2).random_point(seed=42).n(3) Point2D(3.2, 1.92) """ if seed is not None: rng = random.Random(seed) else: rng = random t = Dummy() pt = self.arbitrary_point(t) if isinstance(self, Ray): v = abs(rng.gauss(0, 1)) elif isinstance(self, Segment): v = rng.random() elif isinstance(self, Line): v = rng.gauss(0, 1) else: raise NotImplementedError('unhandled line type') return pt.subs(t, Rational(v)) def bisectors(self, other): """Returns the perpendicular lines which pass through the intersections of self and other that are in the same plane. Parameters ========== line : Line3D Returns ======= list: two Line instances Examples ======== >>> from sympy import Point3D, Line3D >>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) >>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0)) >>> r1.bisectors(r2) [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] """ if not isinstance(other, LinearEntity): raise GeometryError("Expecting LinearEntity, not %s" % other) l1, l2 = self, other # make sure dimensions match or else a warning will rise from # intersection calculation if l1.p1.ambient_dimension != l2.p1.ambient_dimension: if isinstance(l1, Line2D): l1, l2 = l2, l1 _, p1 = Point._normalize_dimension(l1.p1, l2.p1, on_morph='ignore') _, p2 = Point._normalize_dimension(l1.p2, l2.p2, on_morph='ignore') l2 = Line(p1, p2) point = intersection(l1, l2) # Three cases: Lines may intersect in a point, may be equal or may not intersect. if not point: raise GeometryError("The lines do not intersect") else: pt = point[0] if isinstance(pt, Line): # Intersection is a line because both lines are coincident return [self] d1 = l1.direction.unit d2 = l2.direction.unit bis1 = Line(pt, pt + d1 + d2) bis2 = Line(pt, pt + d1 - d2) return [bis1, bis2] class Line(LinearEntity): """An infinite line in space. A 2D line is declared with two distinct points, point and slope, or an equation. A 3D line may be defined with a point and a direction ratio. Parameters ========== p1 : Point p2 : Point slope : SymPy expression direction_ratio : list equation : equation of a line Notes ===== `Line` will automatically subclass to `Line2D` or `Line3D` based on the dimension of `p1`. The `slope` argument is only relevant for `Line2D` and the `direction_ratio` argument is only relevant for `Line3D`. The order of the points will define the direction of the line which is used when calculating the angle between lines. See Also ======== sympy.geometry.point.Point sympy.geometry.line.Line2D sympy.geometry.line.Line3D Examples ======== >>> from sympy import Line, Segment, Point, Eq >>> from sympy.abc import x, y, a, b >>> L = Line(Point(2,3), Point(3,5)) >>> L Line2D(Point2D(2, 3), Point2D(3, 5)) >>> L.points (Point2D(2, 3), Point2D(3, 5)) >>> L.equation() -2*x + y + 1 >>> L.coefficients (-2, 1, 1) Instantiate with keyword ``slope``: >>> Line(Point(0, 0), slope=0) Line2D(Point2D(0, 0), Point2D(1, 0)) Instantiate with another linear object >>> s = Segment((0, 0), (0, 1)) >>> Line(s).equation() x The line corresponding to an equation in the for `ax + by + c = 0`, can be entered: >>> Line(3*x + y + 18) Line2D(Point2D(0, -18), Point2D(1, -21)) If `x` or `y` has a different name, then they can be specified, too, as a string (to match the name) or symbol: >>> Line(Eq(3*a + b, -18), x='a', y=b) Line2D(Point2D(0, -18), Point2D(1, -21)) """ def __new__(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], (Expr, Eq)): missing = uniquely_named_symbol('?', args) if not kwargs: x = 'x' y = 'y' else: x = kwargs.pop('x', missing) y = kwargs.pop('y', missing) if kwargs: raise ValueError('expecting only x and y as keywords') equation = args[0] if isinstance(equation, Eq): equation = equation.lhs - equation.rhs def find_or_missing(x): try: return find(x, equation) except ValueError: return missing x = find_or_missing(x) y = find_or_missing(y) a, b, c = linear_coeffs(equation, x, y) if b: return Line((0, -c/b), slope=-a/b) if a: return Line((-c/a, 0), slope=oo) raise ValueError('not found in equation: %s' % (set('xy') - {x, y})) else: if len(args) > 0: p1 = args[0] if len(args) > 1: p2 = args[1] else: p2 = None if isinstance(p1, LinearEntity): if p2: raise ValueError('If p1 is a LinearEntity, p2 must be None.') dim = len(p1.p1) else: p1 = Point(p1) dim = len(p1) if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim: p2 = Point(p2) if dim == 2: return Line2D(p1, p2, **kwargs) elif dim == 3: return Line3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def contains(self, other): """ Return True if `other` is on this Line, or False otherwise. Examples ======== >>> from sympy import Line,Point >>> p1, p2 = Point(0, 1), Point(3, 4) >>> l = Line(p1, p2) >>> l.contains(p1) True >>> l.contains((0, 1)) True >>> l.contains((0, 0)) False >>> a = (0, 0, 0) >>> b = (1, 1, 1) >>> c = (2, 2, 2) >>> l1 = Line(a, b) >>> l2 = Line(b, a) >>> l1 == l2 False >>> l1 in l2 True """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): return Point.is_collinear(other, self.p1, self.p2) if isinstance(other, LinearEntity): return Point.is_collinear(self.p1, self.p2, other.p1, other.p2) return False def distance(self, other): """ Finds the shortest distance between a line and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> s = Line(p1, p2) >>> s.distance(Point(-1, 1)) sqrt(2) >>> s.distance((-1, 2)) 3*sqrt(2)/2 >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1) >>> s = Line(p1, p2) >>> s.distance(Point(-1, 1, 1)) 2*sqrt(6)/3 >>> s.distance((-1, 1, 1)) 2*sqrt(6)/3 """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if self.contains(other): return S.Zero return self.perpendicular_segment(other).length def equals(self, other): """Returns True if self and other are the same mathematical entities""" if not isinstance(other, Line): return False return Point.is_collinear(self.p1, other.p1, self.p2, other.p2) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of line. Gives values that will produce a line that is +/- 5 units long (where a unit is the distance between the two points that define the line). Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list (plot interval) [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.plot_interval() [t, -5, 5] """ t = _symbol(parameter, real=True) return [t, -5, 5] class Ray(LinearEntity): """A Ray is a semi-line in the space with a source point and a direction. Parameters ========== p1 : Point The source of the Ray p2 : Point or radian value This point determines the direction in which the Ray propagates. If given as an angle it is interpreted in radians with the positive direction being ccw. Attributes ========== source See Also ======== sympy.geometry.line.Ray2D sympy.geometry.line.Ray3D sympy.geometry.point.Point sympy.geometry.line.Line Notes ===== `Ray` will automatically subclass to `Ray2D` or `Ray3D` based on the dimension of `p1`. Examples ======== >>> from sympy import Ray, Point, pi >>> r = Ray(Point(2, 3), Point(3, 5)) >>> r Ray2D(Point2D(2, 3), Point2D(3, 5)) >>> r.points (Point2D(2, 3), Point2D(3, 5)) >>> r.source Point2D(2, 3) >>> r.xdirection oo >>> r.ydirection oo >>> r.slope 2 >>> Ray(Point(0, 0), angle=pi/4).slope 1 """ def __new__(cls, p1, p2=None, **kwargs): p1 = Point(p1) if p2 is not None: p1, p2 = Point._normalize_dimension(p1, Point(p2)) dim = len(p1) if dim == 2: return Ray2D(p1, p2, **kwargs) elif dim == 3: return Ray3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the LinearEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = (N(self.p1), N(self.p2)) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {}".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" ' 'marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>' ).format(2.*scale_factor, path, fill_color) def contains(self, other): """ Is other GeometryEntity contained in this Ray? Examples ======== >>> from sympy import Ray,Point,Segment >>> p1, p2 = Point(0, 0), Point(4, 4) >>> r = Ray(p1, p2) >>> r.contains(p1) True >>> r.contains((1, 1)) True >>> r.contains((1, 3)) False >>> s = Segment((1, 1), (2, 2)) >>> r.contains(s) True >>> s = Segment((1, 2), (2, 5)) >>> r.contains(s) False >>> r1 = Ray((2, 2), (3, 3)) >>> r.contains(r1) True >>> r1 = Ray((2, 2), (3, 5)) >>> r.contains(r1) False """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): if Point.is_collinear(self.p1, self.p2, other): # if we're in the direction of the ray, our # direction vector dot the ray's direction vector # should be non-negative return bool((self.p2 - self.p1).dot(other - self.p1) >= S.Zero) return False elif isinstance(other, Ray): if Point.is_collinear(self.p1, self.p2, other.p1, other.p2): return bool((self.p2 - self.p1).dot(other.p2 - other.p1) > S.Zero) return False elif isinstance(other, Segment): return other.p1 in self and other.p2 in self # No other known entity can be contained in a Ray return False def distance(self, other): """ Finds the shortest distance between the ray and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Ray >>> p1, p2 = Point(0, 0), Point(1, 1) >>> s = Ray(p1, p2) >>> s.distance(Point(-1, -1)) sqrt(2) >>> s.distance((-1, 2)) 3*sqrt(2)/2 >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2) >>> s = Ray(p1, p2) >>> s Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2)) >>> s.distance(Point(-1, -1, 2)) 4*sqrt(3)/3 >>> s.distance((-1, -1, 2)) 4*sqrt(3)/3 """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if self.contains(other): return S.Zero proj = Line(self.p1, self.p2).projection(other) if self.contains(proj): return abs(other - proj) else: return abs(other - self.source) def equals(self, other): """Returns True if self and other are the same mathematical entities""" if not isinstance(other, Ray): return False return self.source == other.source and other.p2 in self def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Ray. Gives values that will produce a ray that is 10 units long (where a unit is the distance between the two points that define the ray). Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Ray, pi >>> r = Ray((0, 0), angle=pi/4) >>> r.plot_interval() [t, 0, 10] """ t = _symbol(parameter, real=True) return [t, 0, 10] @property def source(self): """The point from which the ray emanates. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Ray >>> p1, p2 = Point(0, 0), Point(4, 1) >>> r1 = Ray(p1, p2) >>> r1.source Point2D(0, 0) >>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5) >>> r1 = Ray(p2, p1) >>> r1.source Point3D(4, 1, 5) """ return self.p1 class Segment(LinearEntity): """A line segment in space. Parameters ========== p1 : Point p2 : Point Attributes ========== length : number or SymPy expression midpoint : Point See Also ======== sympy.geometry.line.Segment2D sympy.geometry.line.Segment3D sympy.geometry.point.Point sympy.geometry.line.Line Notes ===== If 2D or 3D points are used to define `Segment`, it will be automatically subclassed to `Segment2D` or `Segment3D`. Examples ======== >>> from sympy import Point, Segment >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts Segment2D(Point2D(1, 0), Point2D(1, 1)) >>> s = Segment(Point(4, 3), Point(1, 1)) >>> s.points (Point2D(4, 3), Point2D(1, 1)) >>> s.slope 2/3 >>> s.length sqrt(13) >>> s.midpoint Point2D(5/2, 2) >>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1)) >>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.points (Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.length sqrt(17) >>> s.midpoint Point3D(5/2, 2, 8) """ def __new__(cls, p1, p2, **kwargs): p1, p2 = Point._normalize_dimension(Point(p1), Point(p2)) dim = len(p1) if dim == 2: return Segment2D(p1, p2, **kwargs) elif dim == 3: return Segment3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def contains(self, other): """ Is the other GeometryEntity contained within this Segment? Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 1), Point(3, 4) >>> s = Segment(p1, p2) >>> s2 = Segment(p2, p1) >>> s.contains(s2) True >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5) >>> s = Segment3D(p1, p2) >>> s2 = Segment3D(p2, p1) >>> s.contains(s2) True >>> s.contains((p1 + p2)/2) True """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): if Point.is_collinear(other, self.p1, self.p2): if isinstance(self, Segment2D): # if it is collinear and is in the bounding box of the # segment then it must be on the segment vert = (1/self.slope).equals(0) if vert is False: isin = (self.p1.x - other.x)*(self.p2.x - other.x) <= 0 if isin in (True, False): return isin if vert is True: isin = (self.p1.y - other.y)*(self.p2.y - other.y) <= 0 if isin in (True, False): return isin # use the triangle inequality d1, d2 = other - self.p1, other - self.p2 d = self.p2 - self.p1 # without the call to simplify, SymPy cannot tell that an expression # like (a+b)*(a/2+b/2) is always non-negative. If it cannot be # determined, raise an Undecidable error try: # the triangle inequality says that |d1|+|d2| >= |d| and is strict # only if other lies in the line segment return bool(simplify(Eq(abs(d1) + abs(d2) - abs(d), 0))) except TypeError: raise Undecidable("Cannot determine if {} is in {}".format(other, self)) if isinstance(other, Segment): return other.p1 in self and other.p2 in self return False def equals(self, other): """Returns True if self and other are the same mathematical entities""" return isinstance(other, self.func) and list( ordered(self.args)) == list(ordered(other.args)) def distance(self, other): """ Finds the shortest distance between a line segment and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 1), Point(3, 4) >>> s = Segment(p1, p2) >>> s.distance(Point(10, 15)) sqrt(170) >>> s.distance((0, 12)) sqrt(73) >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4) >>> s = Segment3D(p1, p2) >>> s.distance(Point3D(10, 15, 12)) sqrt(341) >>> s.distance((10, 15, 12)) sqrt(341) """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): vp1 = other - self.p1 vp2 = other - self.p2 dot_prod_sign_1 = self.direction.dot(vp1) >= 0 dot_prod_sign_2 = self.direction.dot(vp2) <= 0 if dot_prod_sign_1 and dot_prod_sign_2: return Line(self.p1, self.p2).distance(other) if dot_prod_sign_1 and not dot_prod_sign_2: return abs(vp2) if not dot_prod_sign_1 and dot_prod_sign_2: return abs(vp1) raise NotImplementedError() @property def length(self): """The length of the line segment. See Also ======== sympy.geometry.point.Point.distance Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 0), Point(4, 3) >>> s1 = Segment(p1, p2) >>> s1.length 5 >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3) >>> s1 = Segment3D(p1, p2) >>> s1.length sqrt(34) """ return Point.distance(self.p1, self.p2) @property def midpoint(self): """The midpoint of the line segment. See Also ======== sympy.geometry.point.Point.midpoint Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 0), Point(4, 3) >>> s1 = Segment(p1, p2) >>> s1.midpoint Point2D(2, 3/2) >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3) >>> s1 = Segment3D(p1, p2) >>> s1.midpoint Point3D(2, 3/2, 3/2) """ return Point.midpoint(self.p1, self.p2) def perpendicular_bisector(self, p=None): """The perpendicular bisector of this segment. If no point is specified or the point specified is not on the bisector then the bisector is returned as a Line. Otherwise a Segment is returned that joins the point specified and the intersection of the bisector and the segment. Parameters ========== p : Point Returns ======= bisector : Line or Segment See Also ======== LinearEntity.perpendicular_segment Examples ======== >>> from sympy import Point, Segment >>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1) >>> s1 = Segment(p1, p2) >>> s1.perpendicular_bisector() Line2D(Point2D(3, 3), Point2D(-3, 9)) >>> s1.perpendicular_bisector(p3) Segment2D(Point2D(5, 1), Point2D(3, 3)) """ l = self.perpendicular_line(self.midpoint) if p is not None: p2 = Point(p, dim=self.ambient_dimension) if p2 in l: return Segment(p2, self.midpoint) return l def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Segment gives values that will produce the full segment in a plot. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 0), Point(5, 3) >>> s1 = Segment(p1, p2) >>> s1.plot_interval() [t, 0, 1] """ t = _symbol(parameter, real=True) return [t, 0, 1] class LinearEntity2D(LinearEntity): """A base class for all linear entities (line, ray and segment) in a 2-dimensional Euclidean space. Attributes ========== p1 p2 coefficients slope points Notes ===== This is an abstract class and is not meant to be instantiated. See Also ======== sympy.geometry.entity.GeometryEntity """ @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ verts = self.points xs = [p.x for p in verts] ys = [p.y for p in verts] return (min(xs), min(ys), max(xs), max(ys)) def perpendicular_line(self, p): """Create a new Line perpendicular to this linear entity which passes through the point `p`. Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) >>> l1 = Line(p1, p2) >>> l2 = l1.perpendicular_line(p3) >>> p3 in l2 True >>> l1.is_perpendicular(l2) True Parameters ========== p : Point Returns ======= line : Line See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) >>> L = Line(p1, p2) >>> P = L.perpendicular_line(p3); P Line2D(Point2D(-2, 2), Point2D(-5, 4)) >>> L.is_perpendicular(P) True In 2D, the first point of the perpendicular line is the point through which was required to pass; the second point is arbitrarily chosen. To get a line that explicitly uses a point in the line, create a line from the perpendicular segment from the line to the point: >>> Line(L.perpendicular_segment(p3)) Line2D(Point2D(-2, 2), Point2D(4/13, 6/13)) """ p = Point(p, dim=self.ambient_dimension) # any two lines in R^2 intersect, so blindly making # a line through p in an orthogonal direction will work # and is faster than finding the projection point as in 3D return Line(p, p + self.direction.orthogonal_direction) @property def slope(self): """The slope of this linear entity, or infinity if vertical. Returns ======= slope : number or SymPy expression See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(3, 5) >>> l1 = Line(p1, p2) >>> l1.slope 5/3 >>> p3 = Point(0, 4) >>> l2 = Line(p1, p3) >>> l2.slope oo """ d1, d2 = (self.p1 - self.p2).args if d1 == 0: return S.Infinity return simplify(d2/d1) class Line2D(LinearEntity2D, Line): """An infinite line in space 2D. A line is declared with two distinct points or a point and slope as defined using keyword `slope`. Parameters ========== p1 : Point pt : Point slope : SymPy expression See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Line, Segment, Point >>> L = Line(Point(2,3), Point(3,5)) >>> L Line2D(Point2D(2, 3), Point2D(3, 5)) >>> L.points (Point2D(2, 3), Point2D(3, 5)) >>> L.equation() -2*x + y + 1 >>> L.coefficients (-2, 1, 1) Instantiate with keyword ``slope``: >>> Line(Point(0, 0), slope=0) Line2D(Point2D(0, 0), Point2D(1, 0)) Instantiate with another linear object >>> s = Segment((0, 0), (0, 1)) >>> Line(s).equation() x """ def __new__(cls, p1, pt=None, slope=None, **kwargs): if isinstance(p1, LinearEntity): if pt is not None: raise ValueError('When p1 is a LinearEntity, pt should be None') p1, pt = Point._normalize_dimension(*p1.args, dim=2) else: p1 = Point(p1, dim=2) if pt is not None and slope is None: try: p2 = Point(pt, dim=2) except (NotImplementedError, TypeError, ValueError): raise ValueError(filldedent(''' The 2nd argument was not a valid Point. If it was a slope, enter it with keyword "slope". ''')) elif slope is not None and pt is None: slope = sympify(slope) if slope.is_finite is False: # when infinite slope, don't change x dx = 0 dy = 1 else: # go over 1 up slope dx = 1 dy = slope # XXX avoiding simplification by adding to coords directly p2 = Point(p1.x + dx, p1.y + dy, evaluate=False) else: raise ValueError('A 2nd Point or keyword "slope" must be used.') return LinearEntity2D.__new__(cls, p1, p2, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the LinearEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = (N(self.p1), N(self.p2)) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {}".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" ' 'marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>' ).format(2.*scale_factor, path, fill_color) @property def coefficients(self): """The coefficients (`a`, `b`, `c`) for `ax + by + c = 0`. See Also ======== sympy.geometry.line.Line2D.equation Examples ======== >>> from sympy import Point, Line >>> from sympy.abc import x, y >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.coefficients (-3, 5, 0) >>> p3 = Point(x, y) >>> l2 = Line(p1, p3) >>> l2.coefficients (-y, x, 0) """ p1, p2 = self.points if p1.x == p2.x: return (S.One, S.Zero, -p1.x) elif p1.y == p2.y: return (S.Zero, S.One, -p1.y) return tuple([simplify(i) for i in (self.p1.y - self.p2.y, self.p2.x - self.p1.x, self.p1.x*self.p2.y - self.p1.y*self.p2.x)]) def equation(self, x='x', y='y'): """The equation of the line: ax + by + c. Parameters ========== x : str, optional The name to use for the x-axis, default value is 'x'. y : str, optional The name to use for the y-axis, default value is 'y'. Returns ======= equation : SymPy expression See Also ======== sympy.geometry.line.Line2D.coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(1, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.equation() -3*x + 4*y + 3 """ x = _symbol(x, real=True) y = _symbol(y, real=True) p1, p2 = self.points if p1.x == p2.x: return x - p1.x elif p1.y == p2.y: return y - p1.y a, b, c = self.coefficients return a*x + b*y + c class Ray2D(LinearEntity2D, Ray): """ A Ray is a semi-line in the space with a source point and a direction. Parameters ========== p1 : Point The source of the Ray p2 : Point or radian value This point determines the direction in which the Ray propagates. If given as an angle it is interpreted in radians with the positive direction being ccw. Attributes ========== source xdirection ydirection See Also ======== sympy.geometry.point.Point, Line Examples ======== >>> from sympy import Point, pi, Ray >>> r = Ray(Point(2, 3), Point(3, 5)) >>> r Ray2D(Point2D(2, 3), Point2D(3, 5)) >>> r.points (Point2D(2, 3), Point2D(3, 5)) >>> r.source Point2D(2, 3) >>> r.xdirection oo >>> r.ydirection oo >>> r.slope 2 >>> Ray(Point(0, 0), angle=pi/4).slope 1 """ def __new__(cls, p1, pt=None, angle=None, **kwargs): p1 = Point(p1, dim=2) if pt is not None and angle is None: try: p2 = Point(pt, dim=2) except (NotImplementedError, TypeError, ValueError): raise ValueError(filldedent(''' The 2nd argument was not a valid Point; if it was meant to be an angle it should be given with keyword "angle".''')) if p1 == p2: raise ValueError('A Ray requires two distinct points.') elif angle is not None and pt is None: # we need to know if the angle is an odd multiple of pi/2 c = pi_coeff(sympify(angle)) p2 = None if c is not None: if c.is_Rational: if c.q == 2: if c.p == 1: p2 = p1 + Point(0, 1) elif c.p == 3: p2 = p1 + Point(0, -1) elif c.q == 1: if c.p == 0: p2 = p1 + Point(1, 0) elif c.p == 1: p2 = p1 + Point(-1, 0) if p2 is None: c *= S.Pi else: c = angle % (2*S.Pi) if not p2: m = 2*c/S.Pi left = And(1 < m, m < 3) # is it in quadrant 2 or 3? x = Piecewise((-1, left), (Piecewise((0, Eq(m % 1, 0)), (1, True)), True)) y = Piecewise((-tan(c), left), (Piecewise((1, Eq(m, 1)), (-1, Eq(m, 3)), (tan(c), True)), True)) p2 = p1 + Point(x, y) else: raise ValueError('A 2nd point or keyword "angle" must be used.') return LinearEntity2D.__new__(cls, p1, p2, **kwargs) @property def xdirection(self): """The x direction of the ray. Positive infinity if the ray points in the positive x direction, negative infinity if the ray points in the negative x direction, or 0 if the ray is vertical. See Also ======== ydirection Examples ======== >>> from sympy import Point, Ray >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1) >>> r1, r2 = Ray(p1, p2), Ray(p1, p3) >>> r1.xdirection oo >>> r2.xdirection 0 """ if self.p1.x < self.p2.x: return S.Infinity elif self.p1.x == self.p2.x: return S.Zero else: return S.NegativeInfinity @property def ydirection(self): """The y direction of the ray. Positive infinity if the ray points in the positive y direction, negative infinity if the ray points in the negative y direction, or 0 if the ray is horizontal. See Also ======== xdirection Examples ======== >>> from sympy import Point, Ray >>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0) >>> r1, r2 = Ray(p1, p2), Ray(p1, p3) >>> r1.ydirection -oo >>> r2.ydirection 0 """ if self.p1.y < self.p2.y: return S.Infinity elif self.p1.y == self.p2.y: return S.Zero else: return S.NegativeInfinity def closing_angle(r1, r2): """Return the angle by which r2 must be rotated so it faces the same direction as r1. Parameters ========== r1 : Ray2D r2 : Ray2D Returns ======= angle : angle in radians (ccw angle is positive) See Also ======== LinearEntity.angle_between Examples ======== >>> from sympy import Ray, pi >>> r1 = Ray((0, 0), (1, 0)) >>> r2 = r1.rotate(-pi/2) >>> angle = r1.closing_angle(r2); angle pi/2 >>> r2.rotate(angle).direction.unit == r1.direction.unit True >>> r2.closing_angle(r1) -pi/2 """ if not all(isinstance(r, Ray2D) for r in (r1, r2)): # although the direction property is defined for # all linear entities, only the Ray is truly a # directed object raise TypeError('Both arguments must be Ray2D objects.') a1 = atan2(*list(reversed(r1.direction.args))) a2 = atan2(*list(reversed(r2.direction.args))) if a1*a2 < 0: a1 = 2*S.Pi + a1 if a1 < 0 else a1 a2 = 2*S.Pi + a2 if a2 < 0 else a2 return a1 - a2 class Segment2D(LinearEntity2D, Segment): """A line segment in 2D space. Parameters ========== p1 : Point p2 : Point Attributes ========== length : number or SymPy expression midpoint : Point See Also ======== sympy.geometry.point.Point, Line Examples ======== >>> from sympy import Point, Segment >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts Segment2D(Point2D(1, 0), Point2D(1, 1)) >>> s = Segment(Point(4, 3), Point(1, 1)); s Segment2D(Point2D(4, 3), Point2D(1, 1)) >>> s.points (Point2D(4, 3), Point2D(1, 1)) >>> s.slope 2/3 >>> s.length sqrt(13) >>> s.midpoint Point2D(5/2, 2) """ def __new__(cls, p1, p2, **kwargs): p1 = Point(p1, dim=2) p2 = Point(p2, dim=2) if p1 == p2: return p1 return LinearEntity2D.__new__(cls, p1, p2, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the LinearEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = (N(self.p1), N(self.p2)) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {}".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" />' ).format(2.*scale_factor, path, fill_color) class LinearEntity3D(LinearEntity): """An base class for all linear entities (line, ray and segment) in a 3-dimensional Euclidean space. Attributes ========== p1 p2 direction_ratio direction_cosine points Notes ===== This is a base class and is not meant to be instantiated. """ def __new__(cls, p1, p2, **kwargs): p1 = Point3D(p1, dim=3) p2 = Point3D(p2, dim=3) if p1 == p2: # if it makes sense to return a Point, handle in subclass raise ValueError( "%s.__new__ requires two unique Points." % cls.__name__) return GeometryEntity.__new__(cls, p1, p2, **kwargs) ambient_dimension = 3 @property def direction_ratio(self): """The direction ratio of a given line in 3D. See Also ======== sympy.geometry.line.Line3D.equation Examples ======== >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1) >>> l = Line3D(p1, p2) >>> l.direction_ratio [5, 3, 1] """ p1, p2 = self.points return p1.direction_ratio(p2) @property def direction_cosine(self): """The normalized direction ratio of a given line in 3D. See Also ======== sympy.geometry.line.Line3D.equation Examples ======== >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1) >>> l = Line3D(p1, p2) >>> l.direction_cosine [sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35] >>> sum(i**2 for i in _) 1 """ p1, p2 = self.points return p1.direction_cosine(p2) class Line3D(LinearEntity3D, Line): """An infinite 3D line in space. A line is declared with two distinct points or a point and direction_ratio as defined using keyword `direction_ratio`. Parameters ========== p1 : Point3D pt : Point3D direction_ratio : list See Also ======== sympy.geometry.point.Point3D sympy.geometry.line.Line sympy.geometry.line.Line2D Examples ======== >>> from sympy import Line3D, Point3D >>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1)) >>> L Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1)) >>> L.points (Point3D(2, 3, 4), Point3D(3, 5, 1)) """ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs): if isinstance(p1, LinearEntity3D): if pt is not None: raise ValueError('if p1 is a LinearEntity, pt must be None.') p1, pt = p1.args else: p1 = Point(p1, dim=3) if pt is not None and len(direction_ratio) == 0: pt = Point(pt, dim=3) elif len(direction_ratio) == 3 and pt is None: pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1], p1.z + direction_ratio[2]) else: raise ValueError('A 2nd Point or keyword "direction_ratio" must ' 'be used.') return LinearEntity3D.__new__(cls, p1, pt, **kwargs) def equation(self, x='x', y='y', z='z', k=None): """Return the equations that define the line in 3D. Parameters ========== x : str, optional The name to use for the x-axis, default value is 'x'. y : str, optional The name to use for the y-axis, default value is 'y'. z : str, optional The name to use for the z-axis, default value is 'z'. k : str, optional .. deprecated:: 1.2 The ``k`` flag is deprecated. It does nothing. Returns ======= equation : Tuple of simultaneous equations Examples ======== >>> from sympy import Point3D, Line3D, solve >>> from sympy.abc import x, y, z >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0) >>> l1 = Line3D(p1, p2) >>> eq = l1.equation(x, y, z); eq (-3*x + 4*y + 3, z) >>> solve(eq.subs(z, 0), (x, y, z)) {x: 4*y/3 + 1} """ if k is not None: sympy_deprecation_warning( """ The 'k' argument to Line3D.equation() is deprecated. Is currently has no effect, so it may be omitted. """, deprecated_since_version="1.2", active_deprecations_target='deprecated-line3d-equation-k', ) x, y, z, k = [_symbol(i, real=True) for i in (x, y, z, 'k')] p1, p2 = self.points d1, d2, d3 = p1.direction_ratio(p2) x1, y1, z1 = p1 eqs = [-d1*k + x - x1, -d2*k + y - y1, -d3*k + z - z1] # eliminate k from equations by solving first eq with k for k for i, e in enumerate(eqs): if e.has(k): kk = solve(eqs[i], k)[0] eqs.pop(i) break return Tuple(*[i.subs(k, kk).as_numer_denom()[0] for i in eqs]) class Ray3D(LinearEntity3D, Ray): """ A Ray is a semi-line in the space with a source point and a direction. Parameters ========== p1 : Point3D The source of the Ray p2 : Point or a direction vector direction_ratio: Determines the direction in which the Ray propagates. Attributes ========== source xdirection ydirection zdirection See Also ======== sympy.geometry.point.Point3D, Line3D Examples ======== >>> from sympy import Point3D, Ray3D >>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0)) >>> r Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0)) >>> r.points (Point3D(2, 3, 4), Point3D(3, 5, 0)) >>> r.source Point3D(2, 3, 4) >>> r.xdirection oo >>> r.ydirection oo >>> r.direction_ratio [1, 2, -4] """ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs): if isinstance(p1, LinearEntity3D): if pt is not None: raise ValueError('If p1 is a LinearEntity, pt must be None') p1, pt = p1.args else: p1 = Point(p1, dim=3) if pt is not None and len(direction_ratio) == 0: pt = Point(pt, dim=3) elif len(direction_ratio) == 3 and pt is None: pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1], p1.z + direction_ratio[2]) else: raise ValueError(filldedent(''' A 2nd Point or keyword "direction_ratio" must be used. ''')) return LinearEntity3D.__new__(cls, p1, pt, **kwargs) @property def xdirection(self): """The x direction of the ray. Positive infinity if the ray points in the positive x direction, negative infinity if the ray points in the negative x direction, or 0 if the ray is vertical. See Also ======== ydirection Examples ======== >>> from sympy import Point3D, Ray3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0) >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3) >>> r1.xdirection oo >>> r2.xdirection 0 """ if self.p1.x < self.p2.x: return S.Infinity elif self.p1.x == self.p2.x: return S.Zero else: return S.NegativeInfinity @property def ydirection(self): """The y direction of the ray. Positive infinity if the ray points in the positive y direction, negative infinity if the ray points in the negative y direction, or 0 if the ray is horizontal. See Also ======== xdirection Examples ======== >>> from sympy import Point3D, Ray3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0) >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3) >>> r1.ydirection -oo >>> r2.ydirection 0 """ if self.p1.y < self.p2.y: return S.Infinity elif self.p1.y == self.p2.y: return S.Zero else: return S.NegativeInfinity @property def zdirection(self): """The z direction of the ray. Positive infinity if the ray points in the positive z direction, negative infinity if the ray points in the negative z direction, or 0 if the ray is horizontal. See Also ======== xdirection Examples ======== >>> from sympy import Point3D, Ray3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0) >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3) >>> r1.ydirection -oo >>> r2.ydirection 0 >>> r2.zdirection 0 """ if self.p1.z < self.p2.z: return S.Infinity elif self.p1.z == self.p2.z: return S.Zero else: return S.NegativeInfinity class Segment3D(LinearEntity3D, Segment): """A line segment in a 3D space. Parameters ========== p1 : Point3D p2 : Point3D Attributes ========== length : number or SymPy expression midpoint : Point3D See Also ======== sympy.geometry.point.Point3D, Line3D Examples ======== >>> from sympy import Point3D, Segment3D >>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1)) >>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.points (Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.length sqrt(17) >>> s.midpoint Point3D(5/2, 2, 8) """ def __new__(cls, p1, p2, **kwargs): p1 = Point(p1, dim=3) p2 = Point(p2, dim=3) if p1 == p2: return p1 return LinearEntity3D.__new__(cls, p1, p2, **kwargs)
4de7fe470e9d839664cd30139ede95e2a3a582d774d3755fa72fc100354f40a0
from sympy.core import Expr, S, oo, pi, sympify from sympy.core.evalf import N from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import _symbol, Dummy, symbols, Symbol from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cos, sin, tan from .ellipse import Circle from .entity import GeometryEntity, GeometrySet from .exceptions import GeometryError from .line import Line, Segment, Ray from .point import Point from sympy.logic import And from sympy.matrices import Matrix from sympy.simplify.simplify import simplify from sympy.solvers.solvers import solve from sympy.utilities.iterables import has_dups, has_variety, uniq, rotate_left, least_rotation from sympy.utilities.misc import as_int, func_name from mpmath.libmp.libmpf import prec_to_dps import warnings class Polygon(GeometrySet): """A two-dimensional polygon. A simple polygon in space. Can be constructed from a sequence of points or from a center, radius, number of sides and rotation angle. Parameters ========== vertices : sequence of Points Optional parameters ========== n : If > 0, an n-sided RegularPolygon is created. See below. Default value is 0. Attributes ========== area angles perimeter vertices centroid sides Raises ====== GeometryError If all parameters are not Points. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle Notes ===== Polygons are treated as closed paths rather than 2D areas so some calculations can be be negative or positive (e.g., area) based on the orientation of the points. Any consecutive identical points are reduced to a single point and any points collinear and between two points will be removed unless they are needed to define an explicit intersection (see examples). A Triangle, Segment or Point will be returned when there are 3 or fewer points provided. Examples ======== >>> from sympy import Polygon, pi >>> p1, p2, p3, p4, p5 = [(0, 0), (1, 0), (5, 1), (0, 1), (3, 0)] >>> Polygon(p1, p2, p3, p4) Polygon(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)) >>> Polygon(p1, p2) Segment2D(Point2D(0, 0), Point2D(1, 0)) >>> Polygon(p1, p2, p5) Segment2D(Point2D(0, 0), Point2D(3, 0)) The area of a polygon is calculated as positive when vertices are traversed in a ccw direction. When the sides of a polygon cross the area will have positive and negative contributions. The following defines a Z shape where the bottom right connects back to the top left. >>> Polygon((0, 2), (2, 2), (0, 0), (2, 0)).area 0 When the keyword `n` is used to define the number of sides of the Polygon then a RegularPolygon is created and the other arguments are interpreted as center, radius and rotation. The unrotated RegularPolygon will always have a vertex at Point(r, 0) where `r` is the radius of the circle that circumscribes the RegularPolygon. Its method `spin` can be used to increment that angle. >>> p = Polygon((0,0), 1, n=3) >>> p RegularPolygon(Point2D(0, 0), 1, 3, 0) >>> p.vertices[0] Point2D(1, 0) >>> p.args[0] Point2D(0, 0) >>> p.spin(pi/2) >>> p.vertices[0] Point2D(0, 1) """ __slots__ = () def __new__(cls, *args, n = 0, **kwargs): if n: args = list(args) # return a virtual polygon with n sides if len(args) == 2: # center, radius args.append(n) elif len(args) == 3: # center, radius, rotation args.insert(2, n) return RegularPolygon(*args, **kwargs) vertices = [Point(a, dim=2, **kwargs) for a in args] # remove consecutive duplicates nodup = [] for p in vertices: if nodup and p == nodup[-1]: continue nodup.append(p) if len(nodup) > 1 and nodup[-1] == nodup[0]: nodup.pop() # last point was same as first # remove collinear points i = -3 while i < len(nodup) - 3 and len(nodup) > 2: a, b, c = nodup[i], nodup[i + 1], nodup[i + 2] if Point.is_collinear(a, b, c): nodup.pop(i + 1) if a == c: nodup.pop(i) else: i += 1 vertices = list(nodup) if len(vertices) > 3: return GeometryEntity.__new__(cls, *vertices, **kwargs) elif len(vertices) == 3: return Triangle(*vertices, **kwargs) elif len(vertices) == 2: return Segment(*vertices, **kwargs) else: return Point(*vertices, **kwargs) @property def area(self): """ The area of the polygon. Notes ===== The area calculation can be positive or negative based on the orientation of the points. If any side of the polygon crosses any other side, there will be areas having opposite signs. See Also ======== sympy.geometry.ellipse.Ellipse.area Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.area 3 In the Z shaped polygon (with the lower right connecting back to the upper left) the areas cancel out: >>> Z = Polygon((0, 1), (1, 1), (0, 0), (1, 0)) >>> Z.area 0 In the M shaped polygon, areas do not cancel because no side crosses any other (though there is a point of contact). >>> M = Polygon((0, 0), (0, 1), (2, 0), (3, 1), (3, 0)) >>> M.area -3/2 """ area = 0 args = self.args for i in range(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args area += x1*y2 - x2*y1 return simplify(area) / 2 @staticmethod def _isright(a, b, c): """Return True/False for cw/ccw orientation. Examples ======== >>> from sympy import Point, Polygon >>> a, b, c = [Point(i) for i in [(0, 0), (1, 1), (1, 0)]] >>> Polygon._isright(a, b, c) True >>> Polygon._isright(a, c, b) False """ ba = b - a ca = c - a t_area = simplify(ba.x*ca.y - ca.x*ba.y) res = t_area.is_nonpositive if res is None: raise ValueError("Can't determine orientation") return res @property def angles(self): """The internal angle at each vertex. Returns ======= angles : dict A dictionary where each key is a vertex and each value is the internal angle at that vertex. The vertices are represented as Points. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.angles[p1] pi/2 >>> poly.angles[p2] acos(-4*sqrt(17)/17) """ # Determine orientation of points args = self.vertices cw = self._isright(args[-1], args[0], args[1]) ret = {} for i in range(len(args)): a, b, c = args[i - 2], args[i - 1], args[i] ang = Ray(b, a).angle_between(Ray(b, c)) if cw ^ self._isright(a, b, c): ret[b] = 2*S.Pi - ang else: ret[b] = ang return ret @property def ambient_dimension(self): return self.vertices[0].ambient_dimension @property def perimeter(self): """The perimeter of the polygon. Returns ======= perimeter : number or Basic instance See Also ======== sympy.geometry.line.Segment.length Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.perimeter sqrt(17) + 7 """ p = 0 args = self.vertices for i in range(len(args)): p += args[i - 1].distance(args[i]) return simplify(p) @property def vertices(self): """The vertices of the polygon. Returns ======= vertices : list of Points Notes ===== When iterating over the vertices, it is more efficient to index self rather than to request the vertices and index them. Only use the vertices when you want to process all of them at once. This is even more important with RegularPolygons that calculate each vertex. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.vertices [Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)] >>> poly.vertices[0] Point2D(0, 0) """ return list(self.args) @property def centroid(self): """The centroid of the polygon. Returns ======= centroid : Point See Also ======== sympy.geometry.point.Point, sympy.geometry.util.centroid Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.centroid Point2D(31/18, 11/18) """ A = 1/(6*self.area) cx, cy = 0, 0 args = self.args for i in range(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args v = x1*y2 - x2*y1 cx += v*(x1 + x2) cy += v*(y1 + y2) return Point(simplify(A*cx), simplify(A*cy)) def second_moment_of_area(self, point=None): """Returns the second moment and product moment of area of a two dimensional polygon. Parameters ========== point : Point, two-tuple of sympifyable objects, or None(default=None) point is the point about which second moment of area is to be found. If "point=None" it will be calculated about the axis passing through the centroid of the polygon. Returns ======= I_xx, I_yy, I_xy : number or SymPy expression I_xx, I_yy are second moment of area of a two dimensional polygon. I_xy is product moment of area of a two dimensional polygon. Examples ======== >>> from sympy import Polygon, symbols >>> a, b = symbols('a, b') >>> p1, p2, p3, p4, p5 = [(0, 0), (a, 0), (a, b), (0, b), (a/3, b/3)] >>> rectangle = Polygon(p1, p2, p3, p4) >>> rectangle.second_moment_of_area() (a*b**3/12, a**3*b/12, 0) >>> rectangle.second_moment_of_area(p5) (a*b**3/9, a**3*b/9, a**2*b**2/36) References ========== .. [1] https://en.wikipedia.org/wiki/Second_moment_of_area """ I_xx, I_yy, I_xy = 0, 0, 0 args = self.vertices for i in range(len(args)): x1, y1 = args[i-1].args x2, y2 = args[i].args v = x1*y2 - x2*y1 I_xx += (y1**2 + y1*y2 + y2**2)*v I_yy += (x1**2 + x1*x2 + x2**2)*v I_xy += (x1*y2 + 2*x1*y1 + 2*x2*y2 + x2*y1)*v A = self.area c_x = self.centroid[0] c_y = self.centroid[1] # parallel axis theorem I_xx_c = (I_xx/12) - (A*(c_y**2)) I_yy_c = (I_yy/12) - (A*(c_x**2)) I_xy_c = (I_xy/24) - (A*(c_x*c_y)) if point is None: return I_xx_c, I_yy_c, I_xy_c I_xx = (I_xx_c + A*((point[1]-c_y)**2)) I_yy = (I_yy_c + A*((point[0]-c_x)**2)) I_xy = (I_xy_c + A*((point[0]-c_x)*(point[1]-c_y))) return I_xx, I_yy, I_xy def first_moment_of_area(self, point=None): """ Returns the first moment of area of a two-dimensional polygon with respect to a certain point of interest. First moment of area is a measure of the distribution of the area of a polygon in relation to an axis. The first moment of area of the entire polygon about its own centroid is always zero. Therefore, here it is calculated for an area, above or below a certain point of interest, that makes up a smaller portion of the polygon. This area is bounded by the point of interest and the extreme end (top or bottom) of the polygon. The first moment for this area is is then determined about the centroidal axis of the initial polygon. References ========== .. [1] https://skyciv.com/docs/tutorials/section-tutorials/calculating-the-statical-or-first-moment-of-area-of-beam-sections/?cc=BMD .. [2] https://mechanicalc.com/reference/cross-sections Parameters ========== point: Point, two-tuple of sympifyable objects, or None (default=None) point is the point above or below which the area of interest lies If ``point=None`` then the centroid acts as the point of interest. Returns ======= Q_x, Q_y: number or SymPy expressions Q_x is the first moment of area about the x-axis Q_y is the first moment of area about the y-axis A negative sign indicates that the section modulus is determined for a section below (or left of) the centroidal axis Examples ======== >>> from sympy import Point, Polygon >>> a, b = 50, 10 >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)] >>> p = Polygon(p1, p2, p3, p4) >>> p.first_moment_of_area() (625, 3125) >>> p.first_moment_of_area(point=Point(30, 7)) (525, 3000) """ if point: xc, yc = self.centroid else: point = self.centroid xc, yc = point h_line = Line(point, slope=0) v_line = Line(point, slope=S.Infinity) h_poly = self.cut_section(h_line) v_poly = self.cut_section(v_line) poly_1 = h_poly[0] if h_poly[0].area <= h_poly[1].area else h_poly[1] poly_2 = v_poly[0] if v_poly[0].area <= v_poly[1].area else v_poly[1] Q_x = (poly_1.centroid.y - yc)*poly_1.area Q_y = (poly_2.centroid.x - xc)*poly_2.area return Q_x, Q_y def polar_second_moment_of_area(self): """Returns the polar modulus of a two-dimensional polygon It is a constituent of the second moment of area, linked through the perpendicular axis theorem. While the planar second moment of area describes an object's resistance to deflection (bending) when subjected to a force applied to a plane parallel to the central axis, the polar second moment of area describes an object's resistance to deflection when subjected to a moment applied in a plane perpendicular to the object's central axis (i.e. parallel to the cross-section) Examples ======== >>> from sympy import Polygon, symbols >>> a, b = symbols('a, b') >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b)) >>> rectangle.polar_second_moment_of_area() a**3*b/12 + a*b**3/12 References ========== .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia """ second_moment = self.second_moment_of_area() return second_moment[0] + second_moment[1] def section_modulus(self, point=None): """Returns a tuple with the section modulus of a two-dimensional polygon. Section modulus is a geometric property of a polygon defined as the ratio of second moment of area to the distance of the extreme end of the polygon from the centroidal axis. Parameters ========== point : Point, two-tuple of sympifyable objects, or None(default=None) point is the point at which section modulus is to be found. If "point=None" it will be calculated for the point farthest from the centroidal axis of the polygon. Returns ======= S_x, S_y: numbers or SymPy expressions S_x is the section modulus with respect to the x-axis S_y is the section modulus with respect to the y-axis A negative sign indicates that the section modulus is determined for a point below the centroidal axis Examples ======== >>> from sympy import symbols, Polygon, Point >>> a, b = symbols('a, b', positive=True) >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b)) >>> rectangle.section_modulus() (a*b**2/6, a**2*b/6) >>> rectangle.section_modulus(Point(a/4, b/4)) (-a*b**2/3, -a**2*b/3) References ========== .. [1] https://en.wikipedia.org/wiki/Section_modulus """ x_c, y_c = self.centroid if point is None: # taking x and y as maximum distances from centroid x_min, y_min, x_max, y_max = self.bounds y = max(y_c - y_min, y_max - y_c) x = max(x_c - x_min, x_max - x_c) else: # taking x and y as distances of the given point from the centroid y = point.y - y_c x = point.x - x_c second_moment= self.second_moment_of_area() S_x = second_moment[0]/y S_y = second_moment[1]/x return S_x, S_y @property def sides(self): """The directed line segments that form the sides of the polygon. Returns ======= sides : list of sides Each side is a directed Segment. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.sides [Segment2D(Point2D(0, 0), Point2D(1, 0)), Segment2D(Point2D(1, 0), Point2D(5, 1)), Segment2D(Point2D(5, 1), Point2D(0, 1)), Segment2D(Point2D(0, 1), Point2D(0, 0))] """ res = [] args = self.vertices for i in range(-len(args), 0): res.append(Segment(args[i], args[i + 1])) return res @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ verts = self.vertices xs = [p.x for p in verts] ys = [p.y for p in verts] return (min(xs), min(ys), max(xs), max(ys)) def is_convex(self): """Is the polygon convex? A polygon is convex if all its interior angles are less than 180 degrees and there are no intersections between sides. Returns ======= is_convex : boolean True if this polygon is convex, False otherwise. See Also ======== sympy.geometry.util.convex_hull Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.is_convex() True """ # Determine orientation of points args = self.vertices cw = self._isright(args[-2], args[-1], args[0]) for i in range(1, len(args)): if cw ^ self._isright(args[i - 2], args[i - 1], args[i]): return False # check for intersecting sides sides = self.sides for i, si in enumerate(sides): pts = si.args # exclude the sides connected to si for j in range(1 if i == len(sides) - 1 else 0, i - 1): sj = sides[j] if sj.p1 not in pts and sj.p2 not in pts: hit = si.intersection(sj) if hit: return False return True def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ===== Being on the border of self is considered False. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.encloses_point Examples ======== >>> from sympy import Polygon, Point >>> p = Polygon((0, 0), (4, 0), (4, 4)) >>> p.encloses_point(Point(2, 1)) True >>> p.encloses_point(Point(2, 2)) False >>> p.encloses_point(Point(5, 5)) False References ========== .. [1] http://paulbourke.net/geometry/polygonmesh/#insidepoly """ p = Point(p, dim=2) if p in self.vertices or any(p in s for s in self.sides): return False # move to p, checking that the result is numeric lit = [] for v in self.vertices: lit.append(v - p) # the difference is simplified if lit[-1].free_symbols: return None poly = Polygon(*lit) # polygon closure is assumed in the following test but Polygon removes duplicate pts so # the last point has to be added so all sides are computed. Using Polygon.sides is # not good since Segments are unordered. args = poly.args indices = list(range(-len(args), 1)) if poly.is_convex(): orientation = None for i in indices: a = args[i] b = args[i + 1] test = ((-a.y)*(b.x - a.x) - (-a.x)*(b.y - a.y)).is_negative if orientation is None: orientation = test elif test is not orientation: return False return True hit_odd = False p1x, p1y = args[0].args for i in indices[1:]: p2x, p2y = args[i].args if 0 > min(p1y, p2y): if 0 <= max(p1y, p2y): if 0 <= max(p1x, p2x): if p1y != p2y: xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x if p1x == p2x or 0 <= xinters: hit_odd = not hit_odd p1x, p1y = p2x, p2y return hit_odd def arbitrary_point(self, parameter='t'): """A parameterized point on the polygon. The parameter, varying from 0 to 1, assigns points to the position on the perimeter that is that fraction of the total perimeter. So the point evaluated at t=1/2 would return the point from the first vertex that is 1/2 way around the polygon. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= arbitrary_point : Point Raises ====== ValueError When `parameter` already appears in the Polygon's definition. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Polygon, Symbol >>> t = Symbol('t', real=True) >>> tri = Polygon((0, 0), (1, 0), (1, 1)) >>> p = tri.arbitrary_point('t') >>> perimeter = tri.perimeter >>> s1, s2 = [s.length for s in tri.sides[:2]] >>> p.subs(t, (s1 + s2/2)/perimeter) Point2D(1, 1/2) """ t = _symbol(parameter, real=True) if t.name in (f.name for f in self.free_symbols): raise ValueError('Symbol %s already appears in object and cannot be used as a parameter.' % t.name) sides = [] perimeter = self.perimeter perim_fraction_start = 0 for s in self.sides: side_perim_fraction = s.length/perimeter perim_fraction_end = perim_fraction_start + side_perim_fraction pt = s.arbitrary_point(parameter).subs( t, (t - perim_fraction_start)/side_perim_fraction) sides.append( (pt, (And(perim_fraction_start <= t, t < perim_fraction_end)))) perim_fraction_start = perim_fraction_end return Piecewise(*sides) def parameter_value(self, other, t): if not isinstance(other,GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other,Point): raise ValueError("other must be a point") if other.free_symbols: raise NotImplementedError('non-numeric coordinates') unknown = False T = Dummy('t', real=True) p = self.arbitrary_point(T) for pt, cond in p.args: sol = solve(pt - other, T, dict=True) if not sol: continue value = sol[0][T] if simplify(cond.subs(T, value)) == True: return {t: value} unknown = True if unknown: raise ValueError("Given point may not be on %s" % func_name(self)) raise ValueError("Given point is not on %s" % func_name(self)) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the polygon. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list (plot interval) [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Polygon >>> p = Polygon((0, 0), (1, 0), (1, 1)) >>> p.plot_interval() [t, 0, 1] """ t = Symbol(parameter, real=True) return [t, 0, 1] def intersection(self, o): """The intersection of polygon and geometry entity. The intersection may be empty and can contain individual Points and complete Line Segments. Parameters ========== other: GeometryEntity Returns ======= intersection : list The list of Segments and Points See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Polygon, Line >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly1 = Polygon(p1, p2, p3, p4) >>> p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)]) >>> poly2 = Polygon(p5, p6, p7) >>> poly1.intersection(poly2) [Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)] >>> poly1.intersection(Line(p1, p2)) [Segment2D(Point2D(0, 0), Point2D(1, 0))] >>> poly1.intersection(p1) [Point2D(0, 0)] """ intersection_result = [] k = o.sides if isinstance(o, Polygon) else [o] for side in self.sides: for side1 in k: intersection_result.extend(side.intersection(side1)) intersection_result = list(uniq(intersection_result)) points = [entity for entity in intersection_result if isinstance(entity, Point)] segments = [entity for entity in intersection_result if isinstance(entity, Segment)] if points and segments: points_in_segments = list(uniq([point for point in points for segment in segments if point in segment])) if points_in_segments: for i in points_in_segments: points.remove(i) return list(ordered(segments + points)) else: return list(ordered(intersection_result)) def cut_section(self, line): """ Returns a tuple of two polygon segments that lie above and below the intersecting line respectively. Parameters ========== line: Line object of geometry module line which cuts the Polygon. The part of the Polygon that lies above and below this line is returned. Returns ======= upper_polygon, lower_polygon: Polygon objects or None upper_polygon is the polygon that lies above the given line. lower_polygon is the polygon that lies below the given line. upper_polygon and lower polygon are ``None`` when no polygon exists above the line or below the line. Raises ====== ValueError: When the line does not intersect the polygon Examples ======== >>> from sympy import Polygon, Line >>> a, b = 20, 10 >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)] >>> rectangle = Polygon(p1, p2, p3, p4) >>> t = rectangle.cut_section(Line((0, 5), slope=0)) >>> t (Polygon(Point2D(0, 10), Point2D(0, 5), Point2D(20, 5), Point2D(20, 10)), Polygon(Point2D(0, 5), Point2D(0, 0), Point2D(20, 0), Point2D(20, 5))) >>> upper_segment, lower_segment = t >>> upper_segment.area 100 >>> upper_segment.centroid Point2D(10, 15/2) >>> lower_segment.centroid Point2D(10, 5/2) References ========== .. [1] https://github.com/sympy/sympy/wiki/A-method-to-return-a-cut-section-of-any-polygon-geometry """ intersection_points = self.intersection(line) if not intersection_points: raise ValueError("This line does not intersect the polygon") points = list(self.vertices) points.append(points[0]) x, y = symbols('x, y', real=True, cls=Dummy) eq = line.equation(x, y) # considering equation of line to be `ax +by + c` a = eq.coeff(x) b = eq.coeff(y) upper_vertices = [] lower_vertices = [] # prev is true when previous point is above the line prev = True prev_point = None for point in points: # when coefficient of y is 0, right side of the line is # considered compare = eq.subs({x: point.x, y: point.y})/b if b \ else eq.subs(x, point.x)/a # if point lies above line if compare > 0: if not prev: # if previous point lies below the line, the intersection # point of the polygon egde and the line has to be included edge = Line(point, prev_point) new_point = edge.intersection(line) upper_vertices.append(new_point[0]) lower_vertices.append(new_point[0]) upper_vertices.append(point) prev = True else: if prev and prev_point: edge = Line(point, prev_point) new_point = edge.intersection(line) upper_vertices.append(new_point[0]) lower_vertices.append(new_point[0]) lower_vertices.append(point) prev = False prev_point = point upper_polygon, lower_polygon = None, None if upper_vertices and isinstance(Polygon(*upper_vertices), Polygon): upper_polygon = Polygon(*upper_vertices) if lower_vertices and isinstance(Polygon(*lower_vertices), Polygon): lower_polygon = Polygon(*lower_vertices) return upper_polygon, lower_polygon def distance(self, o): """ Returns the shortest distance between self and o. If o is a point, then self does not need to be convex. If o is another polygon self and o must be convex. Examples ======== >>> from sympy import Point, Polygon, RegularPolygon >>> p1, p2 = map(Point, [(0, 0), (7, 5)]) >>> poly = Polygon(*RegularPolygon(p1, 1, 3).vertices) >>> poly.distance(p2) sqrt(61) """ if isinstance(o, Point): dist = oo for side in self.sides: current = side.distance(o) if current == 0: return S.Zero elif current < dist: dist = current return dist elif isinstance(o, Polygon) and self.is_convex() and o.is_convex(): return self._do_poly_distance(o) raise NotImplementedError() def _do_poly_distance(self, e2): """ Calculates the least distance between the exteriors of two convex polygons e1 and e2. Does not check for the convexity of the polygons as this is checked by Polygon.distance. Notes ===== - Prints a warning if the two polygons possibly intersect as the return value will not be valid in such a case. For a more through test of intersection use intersection(). See Also ======== sympy.geometry.point.Point.distance Examples ======== >>> from sympy import Point, Polygon >>> square = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) >>> triangle = Polygon(Point(1, 2), Point(2, 2), Point(2, 1)) >>> square._do_poly_distance(triangle) sqrt(2)/2 Description of method used ========================== Method: [1] http://cgm.cs.mcgill.ca/~orm/mind2p.html Uses rotating calipers: [2] https://en.wikipedia.org/wiki/Rotating_calipers and antipodal points: [3] https://en.wikipedia.org/wiki/Antipodal_point """ e1 = self '''Tests for a possible intersection between the polygons and outputs a warning''' e1_center = e1.centroid e2_center = e2.centroid e1_max_radius = S.Zero e2_max_radius = S.Zero for vertex in e1.vertices: r = Point.distance(e1_center, vertex) if e1_max_radius < r: e1_max_radius = r for vertex in e2.vertices: r = Point.distance(e2_center, vertex) if e2_max_radius < r: e2_max_radius = r center_dist = Point.distance(e1_center, e2_center) if center_dist <= e1_max_radius + e2_max_radius: warnings.warn("Polygons may intersect producing erroneous output", stacklevel=3) ''' Find the upper rightmost vertex of e1 and the lowest leftmost vertex of e2 ''' e1_ymax = Point(0, -oo) e2_ymin = Point(0, oo) for vertex in e1.vertices: if vertex.y > e1_ymax.y or (vertex.y == e1_ymax.y and vertex.x > e1_ymax.x): e1_ymax = vertex for vertex in e2.vertices: if vertex.y < e2_ymin.y or (vertex.y == e2_ymin.y and vertex.x < e2_ymin.x): e2_ymin = vertex min_dist = Point.distance(e1_ymax, e2_ymin) ''' Produce a dictionary with vertices of e1 as the keys and, for each vertex, the points to which the vertex is connected as its value. The same is then done for e2. ''' e1_connections = {} e2_connections = {} for side in e1.sides: if side.p1 in e1_connections: e1_connections[side.p1].append(side.p2) else: e1_connections[side.p1] = [side.p2] if side.p2 in e1_connections: e1_connections[side.p2].append(side.p1) else: e1_connections[side.p2] = [side.p1] for side in e2.sides: if side.p1 in e2_connections: e2_connections[side.p1].append(side.p2) else: e2_connections[side.p1] = [side.p2] if side.p2 in e2_connections: e2_connections[side.p2].append(side.p1) else: e2_connections[side.p2] = [side.p1] e1_current = e1_ymax e2_current = e2_ymin support_line = Line(Point(S.Zero, S.Zero), Point(S.One, S.Zero)) ''' Determine which point in e1 and e2 will be selected after e2_ymin and e1_ymax, this information combined with the above produced dictionaries determines the path that will be taken around the polygons ''' point1 = e1_connections[e1_ymax][0] point2 = e1_connections[e1_ymax][1] angle1 = support_line.angle_between(Line(e1_ymax, point1)) angle2 = support_line.angle_between(Line(e1_ymax, point2)) if angle1 < angle2: e1_next = point1 elif angle2 < angle1: e1_next = point2 elif Point.distance(e1_ymax, point1) > Point.distance(e1_ymax, point2): e1_next = point2 else: e1_next = point1 point1 = e2_connections[e2_ymin][0] point2 = e2_connections[e2_ymin][1] angle1 = support_line.angle_between(Line(e2_ymin, point1)) angle2 = support_line.angle_between(Line(e2_ymin, point2)) if angle1 > angle2: e2_next = point1 elif angle2 > angle1: e2_next = point2 elif Point.distance(e2_ymin, point1) > Point.distance(e2_ymin, point2): e2_next = point2 else: e2_next = point1 ''' Loop which determines the distance between anti-podal pairs and updates the minimum distance accordingly. It repeats until it reaches the starting position. ''' while True: e1_angle = support_line.angle_between(Line(e1_current, e1_next)) e2_angle = pi - support_line.angle_between(Line( e2_current, e2_next)) if (e1_angle < e2_angle) is True: support_line = Line(e1_current, e1_next) e1_segment = Segment(e1_current, e1_next) min_dist_current = e1_segment.distance(e2_current) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e1_connections[e1_next][0] != e1_current: e1_current = e1_next e1_next = e1_connections[e1_next][0] else: e1_current = e1_next e1_next = e1_connections[e1_next][1] elif (e1_angle > e2_angle) is True: support_line = Line(e2_next, e2_current) e2_segment = Segment(e2_current, e2_next) min_dist_current = e2_segment.distance(e1_current) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e2_connections[e2_next][0] != e2_current: e2_current = e2_next e2_next = e2_connections[e2_next][0] else: e2_current = e2_next e2_next = e2_connections[e2_next][1] else: support_line = Line(e1_current, e1_next) e1_segment = Segment(e1_current, e1_next) e2_segment = Segment(e2_current, e2_next) min1 = e1_segment.distance(e2_next) min2 = e2_segment.distance(e1_next) min_dist_current = min(min1, min2) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e1_connections[e1_next][0] != e1_current: e1_current = e1_next e1_next = e1_connections[e1_next][0] else: e1_current = e1_next e1_next = e1_connections[e1_next][1] if e2_connections[e2_next][0] != e2_current: e2_current = e2_next e2_next = e2_connections[e2_next][0] else: e2_current = e2_next e2_next = e2_connections[e2_next][1] if e1_current == e1_ymax and e2_current == e2_ymin: break return min_dist def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the Polygon. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = map(N, self.vertices) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {} z".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" />' ).format(2. * scale_factor, path, fill_color) def _hashable_content(self): D = {} def ref_list(point_list): kee = {} for i, p in enumerate(ordered(set(point_list))): kee[p] = i D[i] = p return [kee[p] for p in point_list] S1 = ref_list(self.args) r_nor = rotate_left(S1, least_rotation(S1)) S2 = ref_list(list(reversed(self.args))) r_rev = rotate_left(S2, least_rotation(S2)) if r_nor < r_rev: r = r_nor else: r = r_rev canonical_args = [ D[order] for order in r ] return tuple(canonical_args) def __contains__(self, o): """ Return True if o is contained within the boundary lines of self.altitudes Parameters ========== other : GeometryEntity Returns ======= contained in : bool The points (and sides, if applicable) are contained in self. See Also ======== sympy.geometry.entity.GeometryEntity.encloses Examples ======== >>> from sympy import Line, Segment, Point >>> p = Point(0, 0) >>> q = Point(1, 1) >>> s = Segment(p, q*2) >>> l = Line(p, q) >>> p in q False >>> p in s True >>> q*3 in s False >>> s in l True """ if isinstance(o, Polygon): return self == o elif isinstance(o, Segment): return any(o in s for s in self.sides) elif isinstance(o, Point): if o in self.vertices: return True for side in self.sides: if o in side: return True return False def bisectors(p, prec=None): """Returns angle bisectors of a polygon. If prec is given then approximate the point defining the ray to that precision. The distance between the points defining the bisector ray is 1. Examples ======== >>> from sympy import Polygon, Point >>> p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3)) >>> p.bisectors(2) {Point2D(0, 0): Ray2D(Point2D(0, 0), Point2D(0.71, 0.71)), Point2D(0, 3): Ray2D(Point2D(0, 3), Point2D(0.23, 2.0)), Point2D(1, 1): Ray2D(Point2D(1, 1), Point2D(0.19, 0.42)), Point2D(2, 0): Ray2D(Point2D(2, 0), Point2D(1.1, 0.38))} """ b = {} pts = list(p.args) pts.append(pts[0]) # close it cw = Polygon._isright(*pts[:3]) if cw: pts = list(reversed(pts)) for v, a in p.angles.items(): i = pts.index(v) p1, p2 = Point._normalize_dimension(pts[i], pts[i + 1]) ray = Ray(p1, p2).rotate(a/2, v) dir = ray.direction ray = Ray(ray.p1, ray.p1 + dir/dir.distance((0, 0))) if prec is not None: ray = Ray(ray.p1, ray.p2.n(prec)) b[v] = ray return b class RegularPolygon(Polygon): """ A regular polygon. Such a polygon has all internal angles equal and all sides the same length. Parameters ========== center : Point radius : number or Basic instance The distance from the center to a vertex n : int The number of sides Attributes ========== vertices center radius rotation apothem interior_angle exterior_angle circumcircle incircle angles Raises ====== GeometryError If the `center` is not a Point, or the `radius` is not a number or Basic instance, or the number of sides, `n`, is less than three. Notes ===== A RegularPolygon can be instantiated with Polygon with the kwarg n. Regular polygons are instantiated with a center, radius, number of sides and a rotation angle. Whereas the arguments of a Polygon are vertices, the vertices of the RegularPolygon must be obtained with the vertices method. See Also ======== sympy.geometry.point.Point, Polygon Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r RegularPolygon(Point2D(0, 0), 5, 3, 0) >>> r.vertices[0] Point2D(5, 0) """ __slots__ = ('_n', '_center', '_radius', '_rot') def __new__(self, c, r, n, rot=0, **kwargs): r, n, rot = map(sympify, (r, n, rot)) c = Point(c, dim=2, **kwargs) if not isinstance(r, Expr): raise GeometryError("r must be an Expr object, not %s" % r) if n.is_Number: as_int(n) # let an error raise if necessary if n < 3: raise GeometryError("n must be a >= 3, not %s" % n) obj = GeometryEntity.__new__(self, c, r, n, **kwargs) obj._n = n obj._center = c obj._radius = r obj._rot = rot % (2*S.Pi/n) if rot.is_number else rot return obj def _eval_evalf(self, prec=15, **options): c, r, n, a = self.args dps = prec_to_dps(prec) c, r, a = [i.evalf(n=dps, **options) for i in (c, r, a)] return self.func(c, r, n, a) @property def args(self): """ Returns the center point, the radius, the number of sides, and the orientation angle. Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r.args (Point2D(0, 0), 5, 3, 0) """ return self._center, self._radius, self._n, self._rot def __str__(self): return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args) def __repr__(self): return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args) @property def area(self): """Returns the area. Examples ======== >>> from sympy import RegularPolygon >>> square = RegularPolygon((0, 0), 1, 4) >>> square.area 2 >>> _ == square.length**2 True """ c, r, n, rot = self.args return sign(r)*n*self.length**2/(4*tan(pi/n)) @property def length(self): """Returns the length of the sides. The half-length of the side and the apothem form two legs of a right triangle whose hypotenuse is the radius of the regular polygon. Examples ======== >>> from sympy import RegularPolygon >>> from sympy import sqrt >>> s = square_in_unit_circle = RegularPolygon((0, 0), 1, 4) >>> s.length sqrt(2) >>> sqrt((_/2)**2 + s.apothem**2) == s.radius True """ return self.radius*2*sin(pi/self._n) @property def center(self): """The center of the RegularPolygon This is also the center of the circumscribing circle. Returns ======= center : Point See Also ======== sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.center Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.center Point2D(0, 0) """ return self._center centroid = center @property def circumcenter(self): """ Alias for center. Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.circumcenter Point2D(0, 0) """ return self.center @property def radius(self): """Radius of the RegularPolygon This is also the radius of the circumscribing circle. Returns ======= radius : number or instance of Basic See Also ======== sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.radius r """ return self._radius @property def circumradius(self): """ Alias for radius. Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.circumradius r """ return self.radius @property def rotation(self): """CCW angle by which the RegularPolygon is rotated Returns ======= rotation : number or instance of Basic Examples ======== >>> from sympy import pi >>> from sympy.abc import a >>> from sympy import RegularPolygon, Point >>> RegularPolygon(Point(0, 0), 3, 4, pi/4).rotation pi/4 Numerical rotation angles are made canonical: >>> RegularPolygon(Point(0, 0), 3, 4, a).rotation a >>> RegularPolygon(Point(0, 0), 3, 4, pi).rotation 0 """ return self._rot @property def apothem(self): """The inradius of the RegularPolygon. The apothem/inradius is the radius of the inscribed circle. Returns ======= apothem : number or instance of Basic See Also ======== sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.apothem sqrt(2)*r/2 """ return self.radius * cos(S.Pi/self._n) @property def inradius(self): """ Alias for apothem. Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.inradius sqrt(2)*r/2 """ return self.apothem @property def interior_angle(self): """Measure of the interior angles. Returns ======= interior_angle : number See Also ======== sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.interior_angle 3*pi/4 """ return (self._n - 2)*S.Pi/self._n @property def exterior_angle(self): """Measure of the exterior angles. Returns ======= exterior_angle : number See Also ======== sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.exterior_angle pi/4 """ return 2*S.Pi/self._n @property def circumcircle(self): """The circumcircle of the RegularPolygon. Returns ======= circumcircle : Circle See Also ======== circumcenter, sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.circumcircle Circle(Point2D(0, 0), 4) """ return Circle(self.center, self.radius) @property def incircle(self): """The incircle of the RegularPolygon. Returns ======= incircle : Circle See Also ======== inradius, sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 7) >>> rp.incircle Circle(Point2D(0, 0), 4*cos(pi/7)) """ return Circle(self.center, self.apothem) @property def angles(self): """ Returns a dictionary with keys, the vertices of the Polygon, and values, the interior angle at each vertex. Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r.angles {Point2D(-5/2, -5*sqrt(3)/2): pi/3, Point2D(-5/2, 5*sqrt(3)/2): pi/3, Point2D(5, 0): pi/3} """ ret = {} ang = self.interior_angle for v in self.vertices: ret[v] = ang return ret def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ===== Being on the border of self is considered False. The general Polygon.encloses_point method is called only if a point is not within or beyond the incircle or circumcircle, respectively. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.ellipse.Ellipse.encloses_point Examples ======== >>> from sympy import RegularPolygon, S, Point, Symbol >>> p = RegularPolygon((0, 0), 3, 4) >>> p.encloses_point(Point(0, 0)) True >>> r, R = p.inradius, p.circumradius >>> p.encloses_point(Point((r + R)/2, 0)) True >>> p.encloses_point(Point(R/2, R/2 + (R - r)/10)) False >>> t = Symbol('t', real=True) >>> p.encloses_point(p.arbitrary_point().subs(t, S.Half)) False >>> p.encloses_point(Point(5, 5)) False """ c = self.center d = Segment(c, p).length if d >= self.radius: return False elif d < self.inradius: return True else: # now enumerate the RegularPolygon like a general polygon. return Polygon.encloses_point(self, p) def spin(self, angle): """Increment *in place* the virtual Polygon's rotation by ccw angle. See also: rotate method which moves the center. >>> from sympy import Polygon, Point, pi >>> r = Polygon(Point(0,0), 1, n=3) >>> r.vertices[0] Point2D(1, 0) >>> r.spin(pi/6) >>> r.vertices[0] Point2D(sqrt(3)/2, 1/2) See Also ======== rotation rotate : Creates a copy of the RegularPolygon rotated about a Point """ self._rot += angle def rotate(self, angle, pt=None): """Override GeometryEntity.rotate to first rotate the RegularPolygon about its center. >>> from sympy import Point, RegularPolygon, pi >>> t = RegularPolygon(Point(1, 0), 1, 3) >>> t.vertices[0] # vertex on x-axis Point2D(2, 0) >>> t.rotate(pi/2).vertices[0] # vertex on y axis now Point2D(0, 2) See Also ======== rotation spin : Rotates a RegularPolygon in place """ r = type(self)(*self.args) # need a copy or else changes are in-place r._rot += angle return GeometryEntity.rotate(r, angle, pt) def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since it is the radius that must be scaled (if x == y) or else a new Polygon must be returned. >>> from sympy import RegularPolygon Symmetric scaling returns a RegularPolygon: >>> RegularPolygon((0, 0), 1, 4).scale(2, 2) RegularPolygon(Point2D(0, 0), 2, 4, 0) Asymmetric scaling returns a kite as a Polygon: >>> RegularPolygon((0, 0), 1, 4).scale(2, 1) Polygon(Point2D(2, 0), Point2D(0, 1), Point2D(-2, 0), Point2D(0, -1)) """ if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) if x != y: return Polygon(*self.vertices).scale(x, y) c, r, n, rot = self.args r *= x return self.func(c, r, n, rot) def reflect(self, line): """Override GeometryEntity.reflect since this is not made of only points. Examples ======== >>> from sympy import RegularPolygon, Line >>> RegularPolygon((0, 0), 1, 4).reflect(Line((0, 1), slope=-2)) RegularPolygon(Point2D(4/5, 2/5), -1, 4, atan(4/3)) """ c, r, n, rot = self.args v = self.vertices[0] d = v - c cc = c.reflect(line) vv = v.reflect(line) dd = vv - cc # calculate rotation about the new center # which will align the vertices l1 = Ray((0, 0), dd) l2 = Ray((0, 0), d) ang = l1.closing_angle(l2) rot += ang # change sign of radius as point traversal is reversed return self.func(cc, -r, n, rot) @property def vertices(self): """The vertices of the RegularPolygon. Returns ======= vertices : list Each vertex is a Point. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.vertices [Point2D(5, 0), Point2D(0, 5), Point2D(-5, 0), Point2D(0, -5)] """ c = self._center r = abs(self._radius) rot = self._rot v = 2*S.Pi/self._n return [Point(c.x + r*cos(k*v + rot), c.y + r*sin(k*v + rot)) for k in range(self._n)] def __eq__(self, o): if not isinstance(o, Polygon): return False elif not isinstance(o, RegularPolygon): return Polygon.__eq__(o, self) return self.args == o.args def __hash__(self): return super().__hash__() class Triangle(Polygon): """ A polygon with three vertices and three sides. Parameters ========== points : sequence of Points keyword: asa, sas, or sss to specify sides/angles of the triangle Attributes ========== vertices altitudes orthocenter circumcenter circumradius circumcircle inradius incircle exradii medians medial nine_point_circle Raises ====== GeometryError If the number of vertices is not equal to three, or one of the vertices is not a Point, or a valid keyword is not given. See Also ======== sympy.geometry.point.Point, Polygon Examples ======== >>> from sympy import Triangle, Point >>> Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) Triangle(Point2D(0, 0), Point2D(4, 0), Point2D(4, 3)) Keywords sss, sas, or asa can be used to give the desired side lengths (in order) and interior angles (in degrees) that define the triangle: >>> Triangle(sss=(3, 4, 5)) Triangle(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4)) >>> Triangle(asa=(30, 1, 30)) Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(1/2, sqrt(3)/6)) >>> Triangle(sas=(1, 45, 2)) Triangle(Point2D(0, 0), Point2D(2, 0), Point2D(sqrt(2)/2, sqrt(2)/2)) """ def __new__(cls, *args, **kwargs): if len(args) != 3: if 'sss' in kwargs: return _sss(*[simplify(a) for a in kwargs['sss']]) if 'asa' in kwargs: return _asa(*[simplify(a) for a in kwargs['asa']]) if 'sas' in kwargs: return _sas(*[simplify(a) for a in kwargs['sas']]) msg = "Triangle instantiates with three points or a valid keyword." raise GeometryError(msg) vertices = [Point(a, dim=2, **kwargs) for a in args] # remove consecutive duplicates nodup = [] for p in vertices: if nodup and p == nodup[-1]: continue nodup.append(p) if len(nodup) > 1 and nodup[-1] == nodup[0]: nodup.pop() # last point was same as first # remove collinear points i = -3 while i < len(nodup) - 3 and len(nodup) > 2: a, b, c = sorted( [nodup[i], nodup[i + 1], nodup[i + 2]], key=default_sort_key) if Point.is_collinear(a, b, c): nodup[i] = a nodup[i + 1] = None nodup.pop(i + 1) i += 1 vertices = list(filter(lambda x: x is not None, nodup)) if len(vertices) == 3: return GeometryEntity.__new__(cls, *vertices, **kwargs) elif len(vertices) == 2: return Segment(*vertices, **kwargs) else: return Point(*vertices, **kwargs) @property def vertices(self): """The triangle's vertices Returns ======= vertices : tuple Each element in the tuple is a Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Triangle, Point >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t.vertices (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3)) """ return self.args def is_similar(t1, t2): """Is another triangle similar to this one. Two triangles are similar if one can be uniformly scaled to the other. Parameters ========== other: Triangle Returns ======= is_similar : boolean See Also ======== sympy.geometry.entity.GeometryEntity.is_similar Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -3)) >>> t1.is_similar(t2) True >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -4)) >>> t1.is_similar(t2) False """ if not isinstance(t2, Polygon): return False s1_1, s1_2, s1_3 = [side.length for side in t1.sides] s2 = [side.length for side in t2.sides] def _are_similar(u1, u2, u3, v1, v2, v3): e1 = simplify(u1/v1) e2 = simplify(u2/v2) e3 = simplify(u3/v3) return bool(e1 == e2) and bool(e2 == e3) # There's only 6 permutations, so write them out return _are_similar(s1_1, s1_2, s1_3, *s2) or \ _are_similar(s1_1, s1_3, s1_2, *s2) or \ _are_similar(s1_2, s1_1, s1_3, *s2) or \ _are_similar(s1_2, s1_3, s1_1, *s2) or \ _are_similar(s1_3, s1_1, s1_2, *s2) or \ _are_similar(s1_3, s1_2, s1_1, *s2) def is_equilateral(self): """Are all the sides the same length? Returns ======= is_equilateral : boolean See Also ======== sympy.geometry.entity.GeometryEntity.is_similar, RegularPolygon is_isosceles, is_right, is_scalene Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t1.is_equilateral() False >>> from sympy import sqrt >>> t2 = Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))) >>> t2.is_equilateral() True """ return not has_variety(s.length for s in self.sides) def is_isosceles(self): """Are two or more of the sides the same length? Returns ======= is_isosceles : boolean See Also ======== is_equilateral, is_right, is_scalene Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(2, 4)) >>> t1.is_isosceles() True """ return has_dups(s.length for s in self.sides) def is_scalene(self): """Are all the sides of the triangle of different lengths? Returns ======= is_scalene : boolean See Also ======== is_equilateral, is_isosceles, is_right Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(1, 4)) >>> t1.is_scalene() True """ return not has_dups(s.length for s in self.sides) def is_right(self): """Is the triangle right-angled. Returns ======= is_right : boolean See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular is_equilateral, is_isosceles, is_scalene Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t1.is_right() True """ s = self.sides return Segment.is_perpendicular(s[0], s[1]) or \ Segment.is_perpendicular(s[1], s[2]) or \ Segment.is_perpendicular(s[0], s[2]) @property def altitudes(self): """The altitudes of the triangle. An altitude of a triangle is a segment through a vertex, perpendicular to the opposite side, with length being the height of the vertex measured from the line containing the side. Returns ======= altitudes : dict The dictionary consists of keys which are vertices and values which are Segments. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment.length Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.altitudes[p1] Segment2D(Point2D(0, 0), Point2D(1/2, 1/2)) """ s = self.sides v = self.vertices return {v[0]: s[1].perpendicular_segment(v[0]), v[1]: s[2].perpendicular_segment(v[1]), v[2]: s[0].perpendicular_segment(v[2])} @property def orthocenter(self): """The orthocenter of the triangle. The orthocenter is the intersection of the altitudes of a triangle. It may lie inside, outside or on the triangle. Returns ======= orthocenter : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.orthocenter Point2D(0, 0) """ a = self.altitudes v = self.vertices return Line(a[v[0]]).intersection(Line(a[v[1]]))[0] @property def circumcenter(self): """The circumcenter of the triangle The circumcenter is the center of the circumcircle. Returns ======= circumcenter : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.circumcenter Point2D(1/2, 1/2) """ a, b, c = [x.perpendicular_bisector() for x in self.sides] if not a.intersection(b): print(a,b,a.intersection(b)) return a.intersection(b)[0] @property def circumradius(self): """The radius of the circumcircle of the triangle. Returns ======= circumradius : number of Basic instance See Also ======== sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy import Point, Triangle >>> a = Symbol('a') >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, a) >>> t = Triangle(p1, p2, p3) >>> t.circumradius sqrt(a**2/4 + 1/4) """ return Point.distance(self.circumcenter, self.vertices[0]) @property def circumcircle(self): """The circle which passes through the three vertices of the triangle. Returns ======= circumcircle : Circle See Also ======== sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.circumcircle Circle(Point2D(1/2, 1/2), sqrt(2)/2) """ return Circle(self.circumcenter, self.circumradius) def bisectors(self): """The angle bisectors of the triangle. An angle bisector of a triangle is a straight line through a vertex which cuts the corresponding angle in half. Returns ======= bisectors : dict Each key is a vertex (Point) and each value is the corresponding bisector (Segment). See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Triangle, Segment >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> from sympy import sqrt >>> t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1)) True """ # use lines containing sides so containment check during # intersection calculation can be avoided, thus reducing # the processing time for calculating the bisectors s = [Line(l) for l in self.sides] v = self.vertices c = self.incenter l1 = Segment(v[0], Line(v[0], c).intersection(s[1])[0]) l2 = Segment(v[1], Line(v[1], c).intersection(s[2])[0]) l3 = Segment(v[2], Line(v[2], c).intersection(s[0])[0]) return {v[0]: l1, v[1]: l2, v[2]: l3} @property def incenter(self): """The center of the incircle. The incircle is the circle which lies inside the triangle and touches all three sides. Returns ======= incenter : Point See Also ======== incircle, sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.incenter Point2D(1 - sqrt(2)/2, 1 - sqrt(2)/2) """ s = self.sides l = Matrix([s[i].length for i in [1, 2, 0]]) p = sum(l) v = self.vertices x = simplify(l.dot(Matrix([vi.x for vi in v]))/p) y = simplify(l.dot(Matrix([vi.y for vi in v]))/p) return Point(x, y) @property def inradius(self): """The radius of the incircle. Returns ======= inradius : number of Basic instance See Also ======== incircle, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(4, 0), Point(0, 3) >>> t = Triangle(p1, p2, p3) >>> t.inradius 1 """ return simplify(2 * self.area / self.perimeter) @property def incircle(self): """The incircle of the triangle. The incircle is the circle which lies inside the triangle and touches all three sides. Returns ======= incircle : Circle See Also ======== sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(2, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.incircle Circle(Point2D(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2)) """ return Circle(self.incenter, self.inradius) @property def exradii(self): """The radius of excircles of a triangle. An excircle of the triangle is a circle lying outside the triangle, tangent to one of its sides and tangent to the extensions of the other two. Returns ======= exradii : dict See Also ======== sympy.geometry.polygon.Triangle.inradius Examples ======== The exradius touches the side of the triangle to which it is keyed, e.g. the exradius touching side 2 is: >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.exradii[t.sides[2]] -2 + sqrt(10) References ========== .. [1] http://mathworld.wolfram.com/Exradius.html .. [2] http://mathworld.wolfram.com/Excircles.html """ side = self.sides a = side[0].length b = side[1].length c = side[2].length s = (a+b+c)/2 area = self.area exradii = {self.sides[0]: simplify(area/(s-a)), self.sides[1]: simplify(area/(s-b)), self.sides[2]: simplify(area/(s-c))} return exradii @property def excenters(self): """Excenters of the triangle. An excenter is the center of a circle that is tangent to a side of the triangle and the extensions of the other two sides. Returns ======= excenters : dict Examples ======== The excenters are keyed to the side of the triangle to which their corresponding excircle is tangent: The center is keyed, e.g. the excenter of a circle touching side 0 is: >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.excenters[t.sides[0]] Point2D(12*sqrt(10), 2/3 + sqrt(10)/3) See Also ======== sympy.geometry.polygon.Triangle.exradii References ========== .. [1] http://mathworld.wolfram.com/Excircles.html """ s = self.sides v = self.vertices a = s[0].length b = s[1].length c = s[2].length x = [v[0].x, v[1].x, v[2].x] y = [v[0].y, v[1].y, v[2].y] exc_coords = { "x1": simplify(-a*x[0]+b*x[1]+c*x[2]/(-a+b+c)), "x2": simplify(a*x[0]-b*x[1]+c*x[2]/(a-b+c)), "x3": simplify(a*x[0]+b*x[1]-c*x[2]/(a+b-c)), "y1": simplify(-a*y[0]+b*y[1]+c*y[2]/(-a+b+c)), "y2": simplify(a*y[0]-b*y[1]+c*y[2]/(a-b+c)), "y3": simplify(a*y[0]+b*y[1]-c*y[2]/(a+b-c)) } excenters = { s[0]: Point(exc_coords["x1"], exc_coords["y1"]), s[1]: Point(exc_coords["x2"], exc_coords["y2"]), s[2]: Point(exc_coords["x3"], exc_coords["y3"]) } return excenters @property def medians(self): """The medians of the triangle. A median of a triangle is a straight line through a vertex and the midpoint of the opposite side, and divides the triangle into two equal areas. Returns ======= medians : dict Each key is a vertex (Point) and each value is the median (Segment) at that point. See Also ======== sympy.geometry.point.Point.midpoint, sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.medians[p1] Segment2D(Point2D(0, 0), Point2D(1/2, 1/2)) """ s = self.sides v = self.vertices return {v[0]: Segment(v[0], s[1].midpoint), v[1]: Segment(v[1], s[2].midpoint), v[2]: Segment(v[2], s[0].midpoint)} @property def medial(self): """The medial triangle of the triangle. The triangle which is formed from the midpoints of the three sides. Returns ======= medial : Triangle See Also ======== sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.medial Triangle(Point2D(1/2, 0), Point2D(1/2, 1/2), Point2D(0, 1/2)) """ s = self.sides return Triangle(s[0].midpoint, s[1].midpoint, s[2].midpoint) @property def nine_point_circle(self): """The nine-point circle of the triangle. Nine-point circle is the circumcircle of the medial triangle, which passes through the feet of altitudes and the middle points of segments connecting the vertices and the orthocenter. Returns ======= nine_point_circle : Circle See also ======== sympy.geometry.line.Segment.midpoint sympy.geometry.polygon.Triangle.medial sympy.geometry.polygon.Triangle.orthocenter Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.nine_point_circle Circle(Point2D(1/4, 1/4), sqrt(2)/4) """ return Circle(*self.medial.vertices) @property def eulerline(self): """The Euler line of the triangle. The line which passes through circumcenter, centroid and orthocenter. Returns ======= eulerline : Line (or Point for equilateral triangles in which case all centers coincide) Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.eulerline Line2D(Point2D(0, 0), Point2D(1/2, 1/2)) """ if self.is_equilateral(): return self.orthocenter return Line(self.orthocenter, self.circumcenter) def rad(d): """Return the radian value for the given degrees (pi = 180 degrees).""" return d*pi/180 def deg(r): """Return the degree value for the given radians (pi = 180 degrees).""" return r/pi*180 def _slope(d): rv = tan(rad(d)) return rv def _asa(d1, l, d2): """Return triangle having side with length l on the x-axis.""" xy = Line((0, 0), slope=_slope(d1)).intersection( Line((l, 0), slope=_slope(180 - d2)))[0] return Triangle((0, 0), (l, 0), xy) def _sss(l1, l2, l3): """Return triangle having side of length l1 on the x-axis.""" c1 = Circle((0, 0), l3) c2 = Circle((l1, 0), l2) inter = [a for a in c1.intersection(c2) if a.y.is_nonnegative] if not inter: return None pt = inter[0] return Triangle((0, 0), (l1, 0), pt) def _sas(l1, d, l2): """Return triangle having side with length l2 on the x-axis.""" p1 = Point(0, 0) p2 = Point(l2, 0) p3 = Point(cos(rad(d))*l1, sin(rad(d))*l1) return Triangle(p1, p2, p3)
245812393de1bba77b321f6c76abd2c42dd1c655651ff73282c5e9b17f7b60c6
"""Recurrence Operators""" from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.printing import sstr from sympy.core.sympify import sympify def RecurrenceOperators(base, generator): """ Returns an Algebra of Recurrence Operators and the operator for shifting i.e. the `Sn` operator. The first argument needs to be the base polynomial ring for the algebra and the second argument must be a generator which can be either a noncommutative Symbol or a string. Examples ======== >>> from sympy import ZZ >>> from sympy import symbols >>> from sympy.holonomic.recurrence import RecurrenceOperators >>> n = symbols('n', integer=True) >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn') """ ring = RecurrenceOperatorAlgebra(base, generator) return (ring, ring.shift_operator) class RecurrenceOperatorAlgebra: """ A Recurrence Operator Algebra is a set of noncommutative polynomials in intermediate `Sn` and coefficients in a base ring A. It follows the commutation rule: Sn * a(n) = a(n + 1) * Sn This class represents a Recurrence Operator Algebra and serves as the parent ring for Recurrence Operators. Examples ======== >>> from sympy import ZZ >>> from sympy import symbols >>> from sympy.holonomic.recurrence import RecurrenceOperators >>> n = symbols('n', integer=True) >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn') >>> R Univariate Recurrence Operator Algebra in intermediate Sn over the base ring ZZ[n] See Also ======== RecurrenceOperator """ def __init__(self, base, generator): # the base ring for the algebra self.base = base # the operator representing shift i.e. `Sn` self.shift_operator = RecurrenceOperator( [base.zero, base.one], self) if generator is None: self.gen_symbol = symbols('Sn', commutative=False) else: if isinstance(generator, str): self.gen_symbol = symbols(generator, commutative=False) elif isinstance(generator, Symbol): self.gen_symbol = generator def __str__(self): string = 'Univariate Recurrence Operator Algebra in intermediate '\ + sstr(self.gen_symbol) + ' over the base ring ' + \ (self.base).__str__() return string __repr__ = __str__ def __eq__(self, other): if self.base == other.base and self.gen_symbol == other.gen_symbol: return True else: return False def _add_lists(list1, list2): if len(list1) <= len(list2): sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):] else: sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):] return sol class RecurrenceOperator: """ The Recurrence Operators are defined by a list of polynomials in the base ring and the parent ring of the Operator. Explanation =========== Takes a list of polynomials for each power of Sn and the parent ring which must be an instance of RecurrenceOperatorAlgebra. A Recurrence Operator can be created easily using the operator `Sn`. See examples below. Examples ======== >>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators >>> from sympy import ZZ >>> from sympy import symbols >>> n = symbols('n', integer=True) >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn') >>> RecurrenceOperator([0, 1, n**2], R) (1)Sn + (n**2)Sn**2 >>> Sn*n (n + 1)Sn >>> n*Sn*n + 1 - Sn**2*n (1) + (n**2 + n)Sn + (-n - 2)Sn**2 See Also ======== DifferentialOperatorAlgebra """ _op_priority = 20 def __init__(self, list_of_poly, parent): # the parent ring for this operator # must be an RecurrenceOperatorAlgebra object self.parent = parent # sequence of polynomials in n for each power of Sn # represents the operator # convert the expressions into ring elements using from_sympy if isinstance(list_of_poly, list): for i, j in enumerate(list_of_poly): if isinstance(j, int): list_of_poly[i] = self.parent.base.from_sympy(S(j)) elif not isinstance(j, self.parent.base.dtype): list_of_poly[i] = self.parent.base.from_sympy(j) self.listofpoly = list_of_poly self.order = len(self.listofpoly) - 1 def __mul__(self, other): """ Multiplies two Operators and returns another RecurrenceOperator instance using the commutation rule Sn * a(n) = a(n + 1) * Sn """ listofself = self.listofpoly base = self.parent.base if not isinstance(other, RecurrenceOperator): if not isinstance(other, self.parent.base.dtype): listofother = [self.parent.base.from_sympy(sympify(other))] else: listofother = [other] else: listofother = other.listofpoly # multiply a polynomial `b` with a list of polynomials def _mul_dmp_diffop(b, listofother): if isinstance(listofother, list): sol = [] for i in listofother: sol.append(i * b) return sol else: return [b * listofother] sol = _mul_dmp_diffop(listofself[0], listofother) # compute Sn^i * b def _mul_Sni_b(b): sol = [base.zero] if isinstance(b, list): for i in b: j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One) sol.append(base.from_sympy(j)) else: j = b.subs(base.gens[0], base.gens[0] + S.One) sol.append(base.from_sympy(j)) return sol for i in range(1, len(listofself)): # find Sn^i * b in ith iteration listofother = _mul_Sni_b(listofother) # solution = solution + listofself[i] * (Sn^i * b) sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) return RecurrenceOperator(sol, self.parent) def __rmul__(self, other): if not isinstance(other, RecurrenceOperator): if isinstance(other, int): other = S(other) if not isinstance(other, self.parent.base.dtype): other = (self.parent.base).from_sympy(other) sol = [] for j in self.listofpoly: sol.append(other * j) return RecurrenceOperator(sol, self.parent) def __add__(self, other): if isinstance(other, RecurrenceOperator): sol = _add_lists(self.listofpoly, other.listofpoly) return RecurrenceOperator(sol, self.parent) else: if isinstance(other, int): other = S(other) list_self = self.listofpoly if not isinstance(other, self.parent.base.dtype): list_other = [((self.parent).base).from_sympy(other)] else: list_other = [other] sol = [] sol.append(list_self[0] + list_other[0]) sol += list_self[1:] return RecurrenceOperator(sol, self.parent) __radd__ = __add__ def __sub__(self, other): return self + (-1) * other def __rsub__(self, other): return (-1) * self + other def __pow__(self, n): if n == 1: return self if n == 0: return RecurrenceOperator([self.parent.base.one], self.parent) # if self is `Sn` if self.listofpoly == self.parent.shift_operator.listofpoly: sol = [] for i in range(0, n): sol.append(self.parent.base.zero) sol.append(self.parent.base.one) return RecurrenceOperator(sol, self.parent) else: if n % 2 == 1: powreduce = self**(n - 1) return powreduce * self elif n % 2 == 0: powreduce = self**(n / 2) return powreduce * powreduce def __str__(self): listofpoly = self.listofpoly print_str = '' for i, j in enumerate(listofpoly): if j == self.parent.base.zero: continue if i == 0: print_str += '(' + sstr(j) + ')' continue if print_str: print_str += ' + ' if i == 1: print_str += '(' + sstr(j) + ')Sn' continue print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i) return print_str __repr__ = __str__ def __eq__(self, other): if isinstance(other, RecurrenceOperator): if self.listofpoly == other.listofpoly and self.parent == other.parent: return True else: return False else: if self.listofpoly[0] == other: for i in self.listofpoly[1:]: if i is not self.parent.base.zero: return False return True else: return False class HolonomicSequence: """ A Holonomic Sequence is a type of sequence satisfying a linear homogeneous recurrence relation with Polynomial coefficients. Alternatively, A sequence is Holonomic if and only if its generating function is a Holonomic Function. """ def __init__(self, recurrence, u0=[]): self.recurrence = recurrence if not isinstance(u0, list): self.u0 = [u0] else: self.u0 = u0 if len(self.u0) == 0: self._have_init_cond = False else: self._have_init_cond = True self.n = recurrence.parent.base.gens[0] def __repr__(self): str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n)) if not self._have_init_cond: return str_sol else: cond_str = '' seq_str = 0 for i in self.u0: cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i)) seq_str += 1 sol = str_sol + cond_str return sol __str__ = __repr__ def __eq__(self, other): if self.recurrence == other.recurrence: if self.n == other.n: if self._have_init_cond and other._have_init_cond: if self.u0 == other.u0: return True else: return False else: return True else: return False else: return False
bd9b2efb7160850499e34177045861b7b1c85f35ca03dce58d2e9cfe7ea14702
""" This module implements Holonomic Functions and various operations on them. """ from sympy.core import Add, Mul, Pow from sympy.core.numbers import NaN, Infinity, NegativeInfinity, Float, I, pi from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import binomial, factorial, rf from sympy.functions.elementary.exponential import exp_polar, exp, log from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, sinc) from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper, meijerg from sympy.integrals import meijerint from sympy.matrices import Matrix from sympy.polys.rings import PolyElement from sympy.polys.fields import FracElement from sympy.polys.domains import QQ, RR from sympy.polys.polyclasses import DMF from sympy.polys.polyroots import roots from sympy.polys.polytools import Poly from sympy.polys.matrices import DomainMatrix from sympy.printing import sstr from sympy.series.limits import limit from sympy.series.order import Order from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.simplify import nsimplify from sympy.solvers.solvers import solve from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError, SingularityError, NotHolonomicError) def _find_nonzero_solution(r, homosys): ones = lambda shape: DomainMatrix.ones(shape, r.domain) particular, nullspace = r._solve(homosys) nullity = nullspace.shape[0] nullpart = ones((1, nullity)) * nullspace sol = (particular + nullpart).transpose() return sol def DifferentialOperators(base, generator): r""" This function is used to create annihilators using ``Dx``. Explanation =========== Returns an Algebra of Differential Operators also called Weyl Algebra and the operator for differentiation i.e. the ``Dx`` operator. Parameters ========== base: Base polynomial ring for the algebra. The base polynomial ring is the ring of polynomials in :math:`x` that will appear as coefficients in the operators. generator: Generator of the algebra which can be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D". Examples ======== >>> from sympy import ZZ >>> from sympy.abc import x >>> from sympy.holonomic.holonomic import DifferentialOperators >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') >>> R Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x] >>> Dx*x (1) + (x)*Dx """ ring = DifferentialOperatorAlgebra(base, generator) return (ring, ring.derivative_operator) class DifferentialOperatorAlgebra: r""" An Ore Algebra is a set of noncommutative polynomials in the intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`. It follows the commutation rule: .. math :: Dxa = \sigma(a)Dx + \delta(a) for :math:`a \subset A`. Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A` is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`. If one takes the sigma as identity map and delta as the standard derivation then it becomes the algebra of Differential Operators also called a Weyl Algebra i.e. an algebra whose elements are Differential Operators. This class represents a Weyl Algebra and serves as the parent ring for Differential Operators. Examples ======== >>> from sympy import ZZ >>> from sympy import symbols >>> from sympy.holonomic.holonomic import DifferentialOperators >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') >>> R Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x] See Also ======== DifferentialOperator """ def __init__(self, base, generator): # the base polynomial ring for the algebra self.base = base # the operator representing differentiation i.e. `Dx` self.derivative_operator = DifferentialOperator( [base.zero, base.one], self) if generator is None: self.gen_symbol = Symbol('Dx', commutative=False) else: if isinstance(generator, str): self.gen_symbol = Symbol(generator, commutative=False) elif isinstance(generator, Symbol): self.gen_symbol = generator def __str__(self): string = 'Univariate Differential Operator Algebra in intermediate '\ + sstr(self.gen_symbol) + ' over the base ring ' + \ (self.base).__str__() return string __repr__ = __str__ def __eq__(self, other): if self.base == other.base and self.gen_symbol == other.gen_symbol: return True else: return False class DifferentialOperator: """ Differential Operators are elements of Weyl Algebra. The Operators are defined by a list of polynomials in the base ring and the parent ring of the Operator i.e. the algebra it belongs to. Explanation =========== Takes a list of polynomials for each power of ``Dx`` and the parent ring which must be an instance of DifferentialOperatorAlgebra. A Differential Operator can be created easily using the operator ``Dx``. See examples below. Examples ======== >>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> DifferentialOperator([0, 1, x**2], R) (1)*Dx + (x**2)*Dx**2 >>> (x*Dx*x + 1 - Dx**2)**2 (2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4 See Also ======== DifferentialOperatorAlgebra """ _op_priority = 20 def __init__(self, list_of_poly, parent): """ Parameters ========== list_of_poly: List of polynomials belonging to the base ring of the algebra. parent: Parent algebra of the operator. """ # the parent ring for this operator # must be an DifferentialOperatorAlgebra object self.parent = parent base = self.parent.base self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0] # sequence of polynomials in x for each power of Dx # the list should not have trailing zeroes # represents the operator # convert the expressions into ring elements using from_sympy for i, j in enumerate(list_of_poly): if not isinstance(j, base.dtype): list_of_poly[i] = base.from_sympy(sympify(j)) else: list_of_poly[i] = base.from_sympy(base.to_sympy(j)) self.listofpoly = list_of_poly # highest power of `Dx` self.order = len(self.listofpoly) - 1 def __mul__(self, other): """ Multiplies two DifferentialOperator and returns another DifferentialOperator instance using the commutation rule Dx*a = a*Dx + a' """ listofself = self.listofpoly if not isinstance(other, DifferentialOperator): if not isinstance(other, self.parent.base.dtype): listofother = [self.parent.base.from_sympy(sympify(other))] else: listofother = [other] else: listofother = other.listofpoly # multiplies a polynomial `b` with a list of polynomials def _mul_dmp_diffop(b, listofother): if isinstance(listofother, list): sol = [] for i in listofother: sol.append(i * b) return sol else: return [b * listofother] sol = _mul_dmp_diffop(listofself[0], listofother) # compute Dx^i * b def _mul_Dxi_b(b): sol1 = [self.parent.base.zero] sol2 = [] if isinstance(b, list): for i in b: sol1.append(i) sol2.append(i.diff()) else: sol1.append(self.parent.base.from_sympy(b)) sol2.append(self.parent.base.from_sympy(b).diff()) return _add_lists(sol1, sol2) for i in range(1, len(listofself)): # find Dx^i * b in ith iteration listofother = _mul_Dxi_b(listofother) # solution = solution + listofself[i] * (Dx^i * b) sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) return DifferentialOperator(sol, self.parent) def __rmul__(self, other): if not isinstance(other, DifferentialOperator): if not isinstance(other, self.parent.base.dtype): other = (self.parent.base).from_sympy(sympify(other)) sol = [] for j in self.listofpoly: sol.append(other * j) return DifferentialOperator(sol, self.parent) def __add__(self, other): if isinstance(other, DifferentialOperator): sol = _add_lists(self.listofpoly, other.listofpoly) return DifferentialOperator(sol, self.parent) else: list_self = self.listofpoly if not isinstance(other, self.parent.base.dtype): list_other = [((self.parent).base).from_sympy(sympify(other))] else: list_other = [other] sol = [] sol.append(list_self[0] + list_other[0]) sol += list_self[1:] return DifferentialOperator(sol, self.parent) __radd__ = __add__ def __sub__(self, other): return self + (-1) * other def __rsub__(self, other): return (-1) * self + other def __neg__(self): return -1 * self def __truediv__(self, other): return self * (S.One / other) def __pow__(self, n): if n == 1: return self if n == 0: return DifferentialOperator([self.parent.base.one], self.parent) # if self is `Dx` if self.listofpoly == self.parent.derivative_operator.listofpoly: sol = [] for i in range(0, n): sol.append(self.parent.base.zero) sol.append(self.parent.base.one) return DifferentialOperator(sol, self.parent) # the general case else: if n % 2 == 1: powreduce = self**(n - 1) return powreduce * self elif n % 2 == 0: powreduce = self**(n / 2) return powreduce * powreduce def __str__(self): listofpoly = self.listofpoly print_str = '' for i, j in enumerate(listofpoly): if j == self.parent.base.zero: continue if i == 0: print_str += '(' + sstr(j) + ')' continue if print_str: print_str += ' + ' if i == 1: print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol) continue print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i) return print_str __repr__ = __str__ def __eq__(self, other): if isinstance(other, DifferentialOperator): if self.listofpoly == other.listofpoly and self.parent == other.parent: return True else: return False else: if self.listofpoly[0] == other: for i in self.listofpoly[1:]: if i is not self.parent.base.zero: return False return True else: return False def is_singular(self, x0): """ Checks if the differential equation is singular at x0. """ base = self.parent.base return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x) class HolonomicFunction: r""" A Holonomic Function is a solution to a linear homogeneous ordinary differential equation with polynomial coefficients. This differential equation can also be represented by an annihilator i.e. a Differential Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions, initial conditions can also be provided along with the annihilator. Explanation =========== Holonomic functions have closure properties and thus forms a ring. Given two Holonomic Functions f and g, their sum, product, integral and derivative is also a Holonomic Function. For ordinary points initial condition should be a vector of values of the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`. For regular singular points initial conditions can also be provided in this format: :math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}` where s0, s1, ... are the roots of indicial equation and vectors :math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial terms of the associated power series. See Examples below. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols, S >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x >>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x) >>> p + q # annihilator of e^x + sin(x) HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1]) >>> p * q # annihilator of e^x * sin(x) HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1]) An example of initial conditions for regular singular points, the indicial equation has only one root `1/2`. >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}) HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]}) >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr() sqrt(x) To plot a Holonomic Function, one can use `.evalf()` for numerical computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib. >>> import sympy.holonomic # doctest: +SKIP >>> from sympy import var, sin # doctest: +SKIP >>> import matplotlib.pyplot as plt # doctest: +SKIP >>> import numpy as np # doctest: +SKIP >>> var("x") # doctest: +SKIP >>> r = np.linspace(1, 5, 100) # doctest: +SKIP >>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP >>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP >>> plt.show() # doctest: +SKIP """ _op_priority = 20 def __init__(self, annihilator, x, x0=0, y0=None): """ Parameters ========== annihilator: Annihilator of the Holonomic Function, represented by a `DifferentialOperator` object. x: Variable of the function. x0: The point at which initial conditions are stored. Generally an integer. y0: The initial condition. The proper format for the initial condition is described in class docstring. To make the function unique, length of the vector `y0` should be equal to or greater than the order of differential equation. """ # initial condition self.y0 = y0 # the point for initial conditions, default is zero. self.x0 = x0 # differential operator L such that L.f = 0 self.annihilator = annihilator self.x = x def __str__(self): if self._have_init_cond(): str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\ sstr(self.x), sstr(self.x0), sstr(self.y0)) else: str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\ sstr(self.x)) return str_sol __repr__ = __str__ def unify(self, other): """ Unifies the base polynomial ring of a given two Holonomic Functions. """ R1 = self.annihilator.parent.base R2 = other.annihilator.parent.base dom1 = R1.dom dom2 = R2.dom if R1 == R2: return (self, other) R = (dom1.unify(dom2)).old_poly_ring(self.x) newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol)) sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly] sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly] sol1 = DifferentialOperator(sol1, newparent) sol2 = DifferentialOperator(sol2, newparent) sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0) sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0) return (sol1, sol2) def is_singularics(self): """ Returns True if the function have singular initial condition in the dictionary format. Returns False if the function have ordinary initial condition in the list format. Returns None for all other cases. """ if isinstance(self.y0, dict): return True elif isinstance(self.y0, list): return False def _have_init_cond(self): """ Checks if the function have initial condition. """ return bool(self.y0) def _singularics_to_ord(self): """ Converts a singular initial condition to ordinary if possible. """ a = list(self.y0)[0] b = self.y0[a] if len(self.y0) == 1 and a == int(a) and a > 0: y0 = [] a = int(a) for i in range(a): y0.append(S.Zero) y0 += [j * factorial(a + i) for i, j in enumerate(b)] return HolonomicFunction(self.annihilator, self.x, self.x0, y0) def __add__(self, other): # if the ground domains are different if self.annihilator.parent.base != other.annihilator.parent.base: a, b = self.unify(other) return a + b deg1 = self.annihilator.order deg2 = other.annihilator.order dim = max(deg1, deg2) R = self.annihilator.parent.base K = R.get_field() rowsself = [self.annihilator] rowsother = [other.annihilator] gen = self.annihilator.parent.derivative_operator # constructing annihilators up to order dim for i in range(dim - deg1): diff1 = (gen * rowsself[-1]) rowsself.append(diff1) for i in range(dim - deg2): diff2 = (gen * rowsother[-1]) rowsother.append(diff2) row = rowsself + rowsother # constructing the matrix of the ansatz r = [] for expr in row: p = [] for i in range(dim + 1): if i >= len(expr.listofpoly): p.append(K.zero) else: p.append(K.new(expr.listofpoly[i].rep)) r.append(p) # solving the linear system using gauss jordan solver r = DomainMatrix(r, (len(row), dim+1), K).transpose() homosys = DomainMatrix.zeros((dim+1, 1), K) sol = _find_nonzero_solution(r, homosys) # if a solution is not obtained then increasing the order by 1 in each # iteration while sol.is_zero_matrix: dim += 1 diff1 = (gen * rowsself[-1]) rowsself.append(diff1) diff2 = (gen * rowsother[-1]) rowsother.append(diff2) row = rowsself + rowsother r = [] for expr in row: p = [] for i in range(dim + 1): if i >= len(expr.listofpoly): p.append(K.zero) else: p.append(K.new(expr.listofpoly[i].rep)) r.append(p) # solving the linear system using gauss jordan solver r = DomainMatrix(r, (len(row), dim+1), K).transpose() homosys = DomainMatrix.zeros((dim+1, 1), K) sol = _find_nonzero_solution(r, homosys) # taking only the coefficients needed to multiply with `self` # can be also be done the other way by taking R.H.S and multiplying with # `other` sol = sol.flat()[:dim + 1 - deg1] sol1 = _normalize(sol, self.annihilator.parent) # annihilator of the solution sol = sol1 * (self.annihilator) sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False) if not (self._have_init_cond() and other._have_init_cond()): return HolonomicFunction(sol, self.x) # both the functions have ordinary initial conditions if self.is_singularics() == False and other.is_singularics() == False: # directly add the corresponding value if self.x0 == other.x0: # try to extended the initial conditions # using the annihilator y1 = _extend_y0(self, sol.order) y2 = _extend_y0(other, sol.order) y0 = [a + b for a, b in zip(y1, y2)] return HolonomicFunction(sol, self.x, self.x0, y0) else: # change the intiial conditions to a same point selfat0 = self.annihilator.is_singular(0) otherat0 = other.annihilator.is_singular(0) if self.x0 == 0 and not selfat0 and not otherat0: return self + other.change_ics(0) elif other.x0 == 0 and not selfat0 and not otherat0: return self.change_ics(0) + other else: selfatx0 = self.annihilator.is_singular(self.x0) otheratx0 = other.annihilator.is_singular(self.x0) if not selfatx0 and not otheratx0: return self + other.change_ics(self.x0) else: return self.change_ics(other.x0) + other if self.x0 != other.x0: return HolonomicFunction(sol, self.x) # if the functions have singular_ics y1 = None y2 = None if self.is_singularics() == False and other.is_singularics() == True: # convert the ordinary initial condition to singular. _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] y1 = {S.Zero: _y0} y2 = other.y0 elif self.is_singularics() == True and other.is_singularics() == False: _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] y1 = self.y0 y2 = {S.Zero: _y0} elif self.is_singularics() == True and other.is_singularics() == True: y1 = self.y0 y2 = other.y0 # computing singular initial condition for the result # taking union of the series terms of both functions y0 = {} for i in y1: # add corresponding initial terms if the power # on `x` is same if i in y2: y0[i] = [a + b for a, b in zip(y1[i], y2[i])] else: y0[i] = y1[i] for i in y2: if i not in y1: y0[i] = y2[i] return HolonomicFunction(sol, self.x, self.x0, y0) def integrate(self, limits, initcond=False): """ Integrates the given holonomic function. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1 HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1]) >>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x)) HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0]) """ # to get the annihilator, just multiply by Dx from right D = self.annihilator.parent.derivative_operator # if the function have initial conditions of the series format if self.is_singularics() == True: r = self._singularics_to_ord() if r: return r.integrate(limits, initcond=initcond) # computing singular initial condition for the function # produced after integration. y0 = {} for i in self.y0: c = self.y0[i] c2 = [] for j in range(len(c)): if c[j] == 0: c2.append(S.Zero) # if power on `x` is -1, the integration becomes log(x) # TODO: Implement this case elif i + j + 1 == 0: raise NotImplementedError("logarithmic terms in the series are not supported") else: c2.append(c[j] / S(i + j + 1)) y0[i + 1] = c2 if hasattr(limits, "__iter__"): raise NotImplementedError("Definite integration for singular initial conditions") return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) # if no initial conditions are available for the function if not self._have_init_cond(): if initcond: return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero]) return HolonomicFunction(self.annihilator * D, self.x) # definite integral # initial conditions for the answer will be stored at point `a`, # where `a` is the lower limit of the integrand if hasattr(limits, "__iter__"): if len(limits) == 3 and limits[0] == self.x: x0 = self.x0 a = limits[1] b = limits[2] definite = True else: definite = False y0 = [S.Zero] y0 += self.y0 indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) if not definite: return indefinite_integral # use evalf to get the values at `a` if x0 != a: try: indefinite_expr = indefinite_integral.to_expr() except (NotHyperSeriesError, NotPowerSeriesError): indefinite_expr = None if indefinite_expr: lower = indefinite_expr.subs(self.x, a) if isinstance(lower, NaN): lower = indefinite_expr.limit(self.x, a) else: lower = indefinite_integral.evalf(a) if b == self.x: y0[0] = y0[0] - lower return HolonomicFunction(self.annihilator * D, self.x, x0, y0) elif S(b).is_Number: if indefinite_expr: upper = indefinite_expr.subs(self.x, b) if isinstance(upper, NaN): upper = indefinite_expr.limit(self.x, b) else: upper = indefinite_integral.evalf(b) return upper - lower # if the upper limit is `x`, the answer will be a function if b == self.x: return HolonomicFunction(self.annihilator * D, self.x, a, y0) # if the upper limits is a Number, a numerical value will be returned elif S(b).is_Number: try: s = HolonomicFunction(self.annihilator * D, self.x, a,\ y0).to_expr() indefinite = s.subs(self.x, b) if not isinstance(indefinite, NaN): return indefinite else: return s.limit(self.x, b) except (NotHyperSeriesError, NotPowerSeriesError): return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b) return HolonomicFunction(self.annihilator * D, self.x) def diff(self, *args, **kwargs): r""" Differentiation of the given Holonomic function. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr() cos(x) >>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr() 2*exp(2*x) See Also ======== .integrate() """ kwargs.setdefault('evaluate', True) if args: if args[0] != self.x: return S.Zero elif len(args) == 2: sol = self for i in range(args[1]): sol = sol.diff(args[0]) return sol ann = self.annihilator # if the function is constant. if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1: return S.Zero # if the coefficient of y in the differential equation is zero. # a shifting is done to compute the answer in this case. elif ann.listofpoly[0] == ann.parent.base.zero: sol = DifferentialOperator(ann.listofpoly[1:], ann.parent) if self._have_init_cond(): # if ordinary initial condition if self.is_singularics() == False: return HolonomicFunction(sol, self.x, self.x0, self.y0[1:]) # TODO: support for singular initial condition return HolonomicFunction(sol, self.x) else: return HolonomicFunction(sol, self.x) # the general algorithm R = ann.parent.base K = R.get_field() seq_dmf = [K.new(i.rep) for i in ann.listofpoly] # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0 rhs = [i / seq_dmf[0] for i in seq_dmf[1:]] rhs.insert(0, K.zero) # differentiate both lhs and rhs sol = _derivate_diff_eq(rhs) # add the term y' in lhs to rhs sol = _add_lists(sol, [K.zero, K.one]) sol = _normalize(sol[1:], self.annihilator.parent, negative=False) if not self._have_init_cond() or self.is_singularics() == True: return HolonomicFunction(sol, self.x) y0 = _extend_y0(self, sol.order + 1)[1:] return HolonomicFunction(sol, self.x, self.x0, y0) def __eq__(self, other): if self.annihilator == other.annihilator: if self.x == other.x: if self._have_init_cond() and other._have_init_cond(): if self.x0 == other.x0 and self.y0 == other.y0: return True else: return False else: return True else: return False else: return False def __mul__(self, other): ann_self = self.annihilator if not isinstance(other, HolonomicFunction): other = sympify(other) if other.has(self.x): raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.") if not self._have_init_cond(): return self else: y0 = _extend_y0(self, ann_self.order) y1 = [] for j in y0: y1.append((Poly.new(j, self.x) * other).rep) return HolonomicFunction(ann_self, self.x, self.x0, y1) if self.annihilator.parent.base != other.annihilator.parent.base: a, b = self.unify(other) return a * b ann_other = other.annihilator list_self = [] list_other = [] a = ann_self.order b = ann_other.order R = ann_self.parent.base K = R.get_field() for j in ann_self.listofpoly: list_self.append(K.new(j.rep)) for j in ann_other.listofpoly: list_other.append(K.new(j.rep)) # will be used to reduce the degree self_red = [-list_self[i] / list_self[a] for i in range(a)] other_red = [-list_other[i] / list_other[b] for i in range(b)] # coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g) coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)] coeff_mul[0][0] = K.one # making the ansatz lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]] lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose() homo_sys = DomainMatrix.zeros((a*b, 1), K) sol = _find_nonzero_solution(lin_sys, homo_sys) # until a non trivial solution is found while sol.is_zero_matrix: # updating the coefficients Dx^i(f).Dx^j(g) for next degree for i in range(a - 1, -1, -1): for j in range(b - 1, -1, -1): coeff_mul[i][j + 1] += coeff_mul[i][j] coeff_mul[i + 1][j] += coeff_mul[i][j] if isinstance(coeff_mul[i][j], K.dtype): coeff_mul[i][j] = DMFdiff(coeff_mul[i][j]) else: coeff_mul[i][j] = coeff_mul[i][j].diff(self.x) # reduce the terms to lower power using annihilators of f, g for i in range(a + 1): if not coeff_mul[i][b].is_zero: for j in range(b): coeff_mul[i][j] += other_red[j] * \ coeff_mul[i][b] coeff_mul[i][b] = K.zero # not d2 + 1, as that is already covered in previous loop for j in range(b): if not coeff_mul[a][j] == 0: for i in range(a): coeff_mul[i][j] += self_red[i] * \ coeff_mul[a][j] coeff_mul[a][j] = K.zero lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)]) lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose() sol = _find_nonzero_solution(lin_sys, homo_sys) sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False) if not (self._have_init_cond() and other._have_init_cond()): return HolonomicFunction(sol_ann, self.x) if self.is_singularics() == False and other.is_singularics() == False: # if both the conditions are at same point if self.x0 == other.x0: # try to find more initial conditions y0_self = _extend_y0(self, sol_ann.order) y0_other = _extend_y0(other, sol_ann.order) # h(x0) = f(x0) * g(x0) y0 = [y0_self[0] * y0_other[0]] # coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg) for i in range(1, min(len(y0_self), len(y0_other))): coeff = [[0 for i in range(i + 1)] for j in range(i + 1)] for j in range(i + 1): for k in range(i + 1): if j + k == i: coeff[j][k] = binomial(i, j) sol = 0 for j in range(i + 1): for k in range(i + 1): sol += coeff[j][k]* y0_self[j] * y0_other[k] y0.append(sol) return HolonomicFunction(sol_ann, self.x, self.x0, y0) # if the points are different, consider one else: selfat0 = self.annihilator.is_singular(0) otherat0 = other.annihilator.is_singular(0) if self.x0 == 0 and not selfat0 and not otherat0: return self * other.change_ics(0) elif other.x0 == 0 and not selfat0 and not otherat0: return self.change_ics(0) * other else: selfatx0 = self.annihilator.is_singular(self.x0) otheratx0 = other.annihilator.is_singular(self.x0) if not selfatx0 and not otheratx0: return self * other.change_ics(self.x0) else: return self.change_ics(other.x0) * other if self.x0 != other.x0: return HolonomicFunction(sol_ann, self.x) # if the functions have singular_ics y1 = None y2 = None if self.is_singularics() == False and other.is_singularics() == True: _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] y1 = {S.Zero: _y0} y2 = other.y0 elif self.is_singularics() == True and other.is_singularics() == False: _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] y1 = self.y0 y2 = {S.Zero: _y0} elif self.is_singularics() == True and other.is_singularics() == True: y1 = self.y0 y2 = other.y0 y0 = {} # multiply every possible pair of the series terms for i in y1: for j in y2: k = min(len(y1[i]), len(y2[j])) c = [] for a in range(k): s = S.Zero for b in range(a + 1): s += y1[i][b] * y2[j][a - b] c.append(s) if not i + j in y0: y0[i + j] = c else: y0[i + j] = [a + b for a, b in zip(c, y0[i + j])] return HolonomicFunction(sol_ann, self.x, self.x0, y0) __rmul__ = __mul__ def __sub__(self, other): return self + other * -1 def __rsub__(self, other): return self * -1 + other def __neg__(self): return -1 * self def __truediv__(self, other): return self * (S.One / other) def __pow__(self, n): if self.annihilator.order <= 1: ann = self.annihilator parent = ann.parent if self.y0 is None: y0 = None else: y0 = [list(self.y0)[0] ** n] p0 = ann.listofpoly[0] p1 = ann.listofpoly[1] p0 = (Poly.new(p0, self.x) * n).rep sol = [parent.base.to_sympy(i) for i in [p0, p1]] dd = DifferentialOperator(sol, parent) return HolonomicFunction(dd, self.x, self.x0, y0) if n < 0: raise NotHolonomicError("Negative Power on a Holonomic Function") if n == 0: Dx = self.annihilator.parent.derivative_operator return HolonomicFunction(Dx, self.x, S.Zero, [S.One]) if n == 1: return self else: if n % 2 == 1: powreduce = self**(n - 1) return powreduce * self elif n % 2 == 0: powreduce = self**(n / 2) return powreduce * powreduce def degree(self): """ Returns the highest power of `x` in the annihilator. """ sol = [i.degree() for i in self.annihilator.listofpoly] return max(sol) def composition(self, expr, *args, **kwargs): """ Returns function after composition of a holonomic function with an algebraic function. The method cannot compute initial conditions for the result by itself, so they can be also be provided. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2) HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1]) >>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0]) HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0]) See Also ======== from_hyper() """ R = self.annihilator.parent a = self.annihilator.order diff = expr.diff(self.x) listofpoly = self.annihilator.listofpoly for i, j in enumerate(listofpoly): if isinstance(j, self.annihilator.parent.base.dtype): listofpoly[i] = self.annihilator.parent.base.to_sympy(j) r = listofpoly[a].subs({self.x:expr}) subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)] coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a)) coeffs[0] = S.One system = [coeffs] homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose() while True: coeffs_next = [p.diff(self.x) for p in coeffs] for i in range(a - 1): coeffs_next[i + 1] += (coeffs[i] * diff) for i in range(a): coeffs_next[i] += (coeffs[-1] * subs[i] * diff) coeffs = coeffs_next # check for linear relations system.append(coeffs) sol, taus = (Matrix(system).transpose() ).gauss_jordan_solve(homogeneous) if sol.is_zero_matrix is not True: break tau = list(taus)[0] sol = sol.subs(tau, 1) sol = _normalize(sol[0:], R, negative=False) # if initial conditions are given for the resulting function if args: return HolonomicFunction(sol, self.x, args[0], args[1]) return HolonomicFunction(sol, self.x) def to_sequence(self, lb=True): r""" Finds recurrence relation for the coefficients in the series expansion of the function about :math:`x_0`, where :math:`x_0` is the point at which the initial condition is stored. Explanation =========== If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]` is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the smallest ``n`` for which the recurrence holds true. If the point :math:`x_0` is regular singular, a list of solutions in the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`. Each tuple in this vector represents a recurrence relation :math:`R` associated with a root of the indicial equation ``p``. Conditions of a different format can also be provided in this case, see the docstring of HolonomicFunction class. If it's not possible to numerically compute a initial condition, it is returned as a symbol :math:`C_j`, denoting the coefficient of :math:`(x - x_0)^j` in the power series about :math:`x_0`. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols, S >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence() [(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)] >>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence() [(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)] >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence() [(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)] See Also ======== HolonomicFunction.series() References ========== .. [1] https://hal.inria.fr/inria-00070025/document .. [2] http://www.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf """ if self.x0 != 0: return self.shift_x(self.x0).to_sequence() # check whether a power series exists if the point is singular if self.annihilator.is_singular(self.x0): return self._frobenius(lb=lb) dict1 = {} n = Symbol('n', integer=True) dom = self.annihilator.parent.base.dom R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') # substituting each term of the form `x^k Dx^j` in the # annihilator, according to the formula below: # x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo)) # for explanation see [2]. for i, j in enumerate(self.annihilator.listofpoly): listofdmp = j.all_coeffs() degree = len(listofdmp) - 1 for k in range(degree + 1): coeff = listofdmp[degree - k] if coeff == 0: continue if (i - k, k) in dict1: dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i)) else: dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i)) sol = [] keylist = [i[0] for i in dict1] lower = min(keylist) upper = max(keylist) degree = self.degree() # the recurrence relation holds for all values of # n greater than smallest_n, i.e. n >= smallest_n smallest_n = lower + degree dummys = {} eqs = [] unknowns = [] # an appropriate shift of the recurrence for j in range(lower, upper + 1): if j in keylist: temp = S.Zero for k in dict1.keys(): if k[0] == j: temp += dict1[k].subs(n, n - lower) sol.append(temp) else: sol.append(S.Zero) # the recurrence relation sol = RecurrenceOperator(sol, R) # computing the initial conditions for recurrence order = sol.order all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') all_roots = all_roots.keys() if all_roots: max_root = max(all_roots) + 1 smallest_n = max(max_root, smallest_n) order += smallest_n y0 = _extend_y0(self, order) u0 = [] # u(n) = y^n(0)/factorial(n) for i, j in enumerate(y0): u0.append(j / factorial(i)) # if sufficient conditions can't be computed then # try to use the series method i.e. # equate the coefficients of x^k in the equation formed by # substituting the series in differential equation, to zero. if len(u0) < order: for i in range(degree): eq = S.Zero for j in dict1: if i + j[0] < 0: dummys[i + j[0]] = S.Zero elif i + j[0] < len(u0): dummys[i + j[0]] = u0[i + j[0]] elif not i + j[0] in dummys: dummys[i + j[0]] = Symbol('C_%s' %(i + j[0])) unknowns.append(dummys[i + j[0]]) if j[1] <= i: eq += dict1[j].subs(n, i) * dummys[i + j[0]] eqs.append(eq) # solve the system of equations formed soleqs = solve(eqs, *unknowns) if isinstance(soleqs, dict): for i in range(len(u0), order): if i not in dummys: dummys[i] = Symbol('C_%s' %i) if dummys[i] in soleqs: u0.append(soleqs[dummys[i]]) else: u0.append(dummys[i]) if lb: return [(HolonomicSequence(sol, u0), smallest_n)] return [HolonomicSequence(sol, u0)] for i in range(len(u0), order): if i not in dummys: dummys[i] = Symbol('C_%s' %i) s = False for j in soleqs: if dummys[i] in j: u0.append(j[dummys[i]]) s = True if not s: u0.append(dummys[i]) if lb: return [(HolonomicSequence(sol, u0), smallest_n)] return [HolonomicSequence(sol, u0)] def _frobenius(self, lb=True): # compute the roots of indicial equation indicialroots = self._indicial() reals = [] compl = [] for i in ordered(indicialroots.keys()): if i.is_real: reals.extend([i] * indicialroots[i]) else: a, b = i.as_real_imag() compl.extend([(i, a, b)] * indicialroots[i]) # sort the roots for a fixed ordering of solution compl.sort(key=lambda x : x[1]) compl.sort(key=lambda x : x[2]) reals.sort() # grouping the roots, roots differ by an integer are put in the same group. grp = [] for i in reals: intdiff = False if len(grp) == 0: grp.append([i]) continue for j in grp: if int(j[0] - i) == j[0] - i: j.append(i) intdiff = True break if not intdiff: grp.append([i]) # True if none of the roots differ by an integer i.e. # each element in group have only one member independent = True if all(len(i) == 1 for i in grp) else False allpos = all(i >= 0 for i in reals) allint = all(int(i) == i for i in reals) # if initial conditions are provided # then use them. if self.is_singularics() == True: rootstoconsider = [] for i in ordered(self.y0.keys()): for j in ordered(indicialroots.keys()): if j == i: rootstoconsider.append(i) elif allpos and allint: rootstoconsider = [min(reals)] elif independent: rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl] elif not allint: rootstoconsider = [] for i in reals: if not int(i) == i: rootstoconsider.append(i) elif not allpos: if not self._have_init_cond() or S(self.y0[0]).is_finite == False: rootstoconsider = [min(reals)] else: posroots = [] for i in reals: if i >= 0: posroots.append(i) rootstoconsider = [min(posroots)] n = Symbol('n', integer=True) dom = self.annihilator.parent.base.dom R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') finalsol = [] char = ord('C') for p in rootstoconsider: dict1 = {} for i, j in enumerate(self.annihilator.listofpoly): listofdmp = j.all_coeffs() degree = len(listofdmp) - 1 for k in range(degree + 1): coeff = listofdmp[degree - k] if coeff == 0: continue if (i - k, k - i) in dict1: dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) else: dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) sol = [] keylist = [i[0] for i in dict1] lower = min(keylist) upper = max(keylist) degree = max([i[1] for i in dict1]) degree2 = min([i[1] for i in dict1]) smallest_n = lower + degree dummys = {} eqs = [] unknowns = [] for j in range(lower, upper + 1): if j in keylist: temp = S.Zero for k in dict1.keys(): if k[0] == j: temp += dict1[k].subs(n, n - lower) sol.append(temp) else: sol.append(S.Zero) # the recurrence relation sol = RecurrenceOperator(sol, R) # computing the initial conditions for recurrence order = sol.order all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') all_roots = all_roots.keys() if all_roots: max_root = max(all_roots) + 1 smallest_n = max(max_root, smallest_n) order += smallest_n u0 = [] if self.is_singularics() == True: u0 = self.y0[p] elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1: y0 = _extend_y0(self, order + int(p)) # u(n) = y^n(0)/factorial(n) if len(y0) > int(p): for i in range(int(p), len(y0)): u0.append(y0[i] / factorial(i)) if len(u0) < order: for i in range(degree2, degree): eq = S.Zero for j in dict1: if i + j[0] < 0: dummys[i + j[0]] = S.Zero elif i + j[0] < len(u0): dummys[i + j[0]] = u0[i + j[0]] elif not i + j[0] in dummys: letter = chr(char) + '_%s' %(i + j[0]) dummys[i + j[0]] = Symbol(letter) unknowns.append(dummys[i + j[0]]) if j[1] <= i: eq += dict1[j].subs(n, i) * dummys[i + j[0]] eqs.append(eq) # solve the system of equations formed soleqs = solve(eqs, *unknowns) if isinstance(soleqs, dict): for i in range(len(u0), order): if i not in dummys: letter = chr(char) + '_%s' %i dummys[i] = Symbol(letter) if dummys[i] in soleqs: u0.append(soleqs[dummys[i]]) else: u0.append(dummys[i]) if lb: finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) continue else: finalsol.append((HolonomicSequence(sol, u0), p)) continue for i in range(len(u0), order): if i not in dummys: letter = chr(char) + '_%s' %i dummys[i] = Symbol(letter) s = False for j in soleqs: if dummys[i] in j: u0.append(j[dummys[i]]) s = True if not s: u0.append(dummys[i]) if lb: finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) else: finalsol.append((HolonomicSequence(sol, u0), p)) char += 1 return finalsol def series(self, n=6, coefficient=False, order=True, _recur=None): r""" Finds the power series expansion of given holonomic function about :math:`x_0`. Explanation =========== A list of series might be returned if :math:`x_0` is a regular point with multiple roots of the indicial equation. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6) >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x) x - x**3/6 + x**5/120 - x**7/5040 + O(x**8) See Also ======== HolonomicFunction.to_sequence() """ if _recur is None: recurrence = self.to_sequence() else: recurrence = _recur if isinstance(recurrence, tuple) and len(recurrence) == 2: recurrence = recurrence[0] constantpower = 0 elif isinstance(recurrence, tuple) and len(recurrence) == 3: constantpower = recurrence[1] recurrence = recurrence[0] elif len(recurrence) == 1 and len(recurrence[0]) == 2: recurrence = recurrence[0][0] constantpower = 0 elif len(recurrence) == 1 and len(recurrence[0]) == 3: constantpower = recurrence[0][1] recurrence = recurrence[0][0] else: sol = [] for i in recurrence: sol.append(self.series(_recur=i)) return sol n = n - int(constantpower) l = len(recurrence.u0) - 1 k = recurrence.recurrence.order x = self.x x0 = self.x0 seq_dmp = recurrence.recurrence.listofpoly R = recurrence.recurrence.parent.base K = R.get_field() seq = [] for i, j in enumerate(seq_dmp): seq.append(K.new(j.rep)) sub = [-seq[i] / seq[k] for i in range(k)] sol = [i for i in recurrence.u0] if l + 1 >= n: pass else: # use the initial conditions to find the next term for i in range(l + 1 - k, n - k): coeff = S.Zero for j in range(k): if i + j >= 0: coeff += DMFsubs(sub[j], i) * sol[i + j] sol.append(coeff) if coefficient: return sol ser = S.Zero for i, j in enumerate(sol): ser += x**(i + constantpower) * j if order: ser += Order(x**(n + int(constantpower)), x) if x0 != 0: return ser.subs(x, x - x0) return ser def _indicial(self): """ Computes roots of the Indicial equation. """ if self.x0 != 0: return self.shift_x(self.x0)._indicial() list_coeff = self.annihilator.listofpoly R = self.annihilator.parent.base x = self.x s = R.zero y = R.one def _pole_degree(poly): root_all = roots(R.to_sympy(poly), x, filter='Z') if 0 in root_all.keys(): return root_all[0] else: return 0 degree = [j.degree() for j in list_coeff] degree = max(degree) inf = 10 * (max(1, degree) + max(1, self.annihilator.order)) deg = lambda q: inf if q.is_zero else _pole_degree(q) b = deg(list_coeff[0]) for j in range(1, len(list_coeff)): b = min(b, deg(list_coeff[j]) - j) for i, j in enumerate(list_coeff): listofdmp = j.all_coeffs() degree = len(listofdmp) - 1 if - i - b <= 0 and degree - i - b >= 0: s = s + listofdmp[degree - i - b] * y y *= x - i return roots(R.to_sympy(s), x) def evalf(self, points, method='RK4', h=0.05, derivatives=False): r""" Finds numerical value of a holonomic function using numerical methods. (RK4 by default). A set of points (real or complex) must be provided which will be the path for the numerical integration. Explanation =========== The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical values will be computed at each point in this order :math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`. Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') A straight line on the real axis from (0 to 1) >>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] Runge-Kutta 4th order on e^x from 0.1 to 1. Exact solution at 1 is 2.71828182845905 >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r) [1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069, 1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232, 2.45960141378007, 2.71827974413517] Euler's method for the same >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler') [1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881, 2.357947691, 2.5937424601] One can also observe that the value obtained using Runge-Kutta 4th order is much more accurate than Euler's method. """ from sympy.holonomic.numerical import _evalf lp = False # if a point `b` is given instead of a mesh if not hasattr(points, "__iter__"): lp = True b = S(points) if self.x0 == b: return _evalf(self, [b], method=method, derivatives=derivatives)[-1] if not b.is_Number: raise NotImplementedError a = self.x0 if a > b: h = -h n = int((b - a) / h) points = [a + h] for i in range(n - 1): points.append(points[-1] + h) for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x): if i == self.x0 or i in points: raise SingularityError(self, i) if lp: return _evalf(self, points, method=method, derivatives=derivatives)[-1] return _evalf(self, points, method=method, derivatives=derivatives) def change_x(self, z): """ Changes only the variable of Holonomic Function, for internal purposes. For composition use HolonomicFunction.composition() """ dom = self.annihilator.parent.base.dom R = dom.old_poly_ring(z) parent, _ = DifferentialOperators(R, 'Dx') sol = [] for j in self.annihilator.listofpoly: sol.append(R(j.rep)) sol = DifferentialOperator(sol, parent) return HolonomicFunction(sol, z, self.x0, self.y0) def shift_x(self, a): """ Substitute `x + a` for `x`. """ x = self.x listaftershift = self.annihilator.listofpoly base = self.annihilator.parent.base sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift] sol = DifferentialOperator(sol, self.annihilator.parent) x0 = self.x0 - a if not self._have_init_cond(): return HolonomicFunction(sol, x) return HolonomicFunction(sol, x, x0, self.y0) def to_hyper(self, as_list=False, _recur=None): r""" Returns a hypergeometric function (or linear combination of them) representing the given holonomic function. Explanation =========== Returns an answer of the form: `a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots` This is very useful as one can now use ``hyperexpand`` to find the symbolic expressions/functions. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> # sin(x) >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper() x*hyper((), (3/2,), -x**2/4) >>> # exp(x) >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper() hyper((), (), x) See Also ======== from_hyper, from_meijerg """ if _recur is None: recurrence = self.to_sequence() else: recurrence = _recur if isinstance(recurrence, tuple) and len(recurrence) == 2: smallest_n = recurrence[1] recurrence = recurrence[0] constantpower = 0 elif isinstance(recurrence, tuple) and len(recurrence) == 3: smallest_n = recurrence[2] constantpower = recurrence[1] recurrence = recurrence[0] elif len(recurrence) == 1 and len(recurrence[0]) == 2: smallest_n = recurrence[0][1] recurrence = recurrence[0][0] constantpower = 0 elif len(recurrence) == 1 and len(recurrence[0]) == 3: smallest_n = recurrence[0][2] constantpower = recurrence[0][1] recurrence = recurrence[0][0] else: sol = self.to_hyper(as_list=as_list, _recur=recurrence[0]) for i in recurrence[1:]: sol += self.to_hyper(as_list=as_list, _recur=i) return sol u0 = recurrence.u0 r = recurrence.recurrence x = self.x x0 = self.x0 # order of the recurrence relation m = r.order # when no recurrence exists, and the power series have finite terms if m == 0: nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R') sol = S.Zero for j, i in enumerate(nonzeroterms): if i < 0 or int(i) != i: continue i = int(i) if i < len(u0): if isinstance(u0[i], (PolyElement, FracElement)): u0[i] = u0[i].as_expr() sol += u0[i] * x**i else: sol += Symbol('C_%s' %j) * x**i if isinstance(sol, (PolyElement, FracElement)): sol = sol.as_expr() * x**constantpower else: sol = sol * x**constantpower if as_list: if x0 != 0: return [(sol.subs(x, x - x0), )] return [(sol, )] if x0 != 0: return sol.subs(x, x - x0) return sol if smallest_n + m > len(u0): raise NotImplementedError("Can't compute sufficient Initial Conditions") # check if the recurrence represents a hypergeometric series is_hyper = True for i in range(1, len(r.listofpoly)-1): if r.listofpoly[i] != r.parent.base.zero: is_hyper = False break if not is_hyper: raise NotHyperSeriesError(self, self.x0) a = r.listofpoly[0] b = r.listofpoly[-1] # the constant multiple of argument of hypergeometric function if isinstance(a.rep[0], (PolyElement, FracElement)): c = - (S(a.rep[0].as_expr()) * m**(a.degree())) / (S(b.rep[0].as_expr()) * m**(b.degree())) else: c = - (S(a.rep[0]) * m**(a.degree())) / (S(b.rep[0]) * m**(b.degree())) sol = 0 arg1 = roots(r.parent.base.to_sympy(a), recurrence.n) arg2 = roots(r.parent.base.to_sympy(b), recurrence.n) # iterate through the initial conditions to find # the hypergeometric representation of the given # function. # The answer will be a linear combination # of different hypergeometric series which satisfies # the recurrence. if as_list: listofsol = [] for i in range(smallest_n + m): # if the recurrence relation doesn't hold for `n = i`, # then a Hypergeometric representation doesn't exist. # add the algebraic term a * x**i to the solution, # where a is u0[i] if i < smallest_n: if as_list: listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), )) else: sol += S(u0[i]) * x**i continue # if the coefficient u0[i] is zero, then the # independent hypergeomtric series starting with # x**i is not a part of the answer. if S(u0[i]) == 0: continue ap = [] bq = [] # substitute m * n + i for n for k in ordered(arg1.keys()): ap.extend([nsimplify((i - k) / m)] * arg1[k]) for k in ordered(arg2.keys()): bq.extend([nsimplify((i - k) / m)] * arg2[k]) # convention of (k + 1) in the denominator if 1 in bq: bq.remove(1) else: ap.append(1) if as_list: listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0))) else: sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i if as_list: return listofsol sol = sol * x**constantpower if x0 != 0: return sol.subs(x, x - x0) return sol def to_expr(self): """ Converts a Holonomic Function back to elementary functions. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols, S >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr() besselj(1, x) >>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr() x*log(x + 1) + log(x + 1) + 1 """ return hyperexpand(self.to_hyper()).simplify() def change_ics(self, b, lenics=None): """ Changes the point `x0` to ``b`` for initial conditions. Examples ======== >>> from sympy.holonomic import expr_to_holonomic >>> from sympy import symbols, sin, exp >>> x = symbols('x') >>> expr_to_holonomic(sin(x)).change_ics(1) HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)]) >>> expr_to_holonomic(exp(x)).change_ics(2) HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)]) """ symbolic = True if lenics is None and len(self.y0) > self.annihilator.order: lenics = len(self.y0) dom = self.annihilator.parent.base.domain try: sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom) except (NotPowerSeriesError, NotHyperSeriesError): symbolic = False if symbolic and sol.x0 == b: return sol y0 = self.evalf(b, derivatives=True) return HolonomicFunction(self.annihilator, self.x, b, y0) def to_meijerg(self): """ Returns a linear combination of Meijer G-functions. Examples ======== >>> from sympy.holonomic import expr_to_holonomic >>> from sympy import sin, cos, hyperexpand, log, symbols >>> x = symbols('x') >>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg()) sin(x) + cos(x) >>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() log(x) See Also ======== to_hyper() """ # convert to hypergeometric first rep = self.to_hyper(as_list=True) sol = S.Zero for i in rep: if len(i) == 1: sol += i[0] elif len(i) == 2: sol += i[0] * _hyper_to_meijerg(i[1]) return sol def from_hyper(func, x0=0, evalf=False): r""" Converts a hypergeometric function to holonomic. ``func`` is the Hypergeometric Function and ``x0`` is the point at which initial conditions are required. Examples ======== >>> from sympy.holonomic.holonomic import from_hyper >>> from sympy import symbols, hyper, S >>> x = symbols('x') >>> from_hyper(hyper([], [S(3)/2], x**2/4)) HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)]) """ a = func.ap b = func.bq z = func.args[2] x = z.atoms(Symbol).pop() R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') # generalized hypergeometric differential equation r1 = 1 for i in range(len(a)): r1 = r1 * (x * Dx + a[i]) r2 = Dx for i in range(len(b)): r2 = r2 * (x * Dx + b[i] - 1) sol = r1 - r2 simp = hyperexpand(func) if simp in (Infinity, NegativeInfinity): return HolonomicFunction(sol, x).composition(z) def _find_conditions(simp, x, x0, order, evalf=False): y0 = [] for i in range(order): if evalf: val = simp.subs(x, x0).evalf() else: val = simp.subs(x, x0) # return None if it is Infinite or NaN if val.is_finite is False or isinstance(val, NaN): return None y0.append(val) simp = simp.diff(x) return y0 # if the function is known symbolically if not isinstance(simp, hyper): y0 = _find_conditions(simp, x, x0, sol.order) while not y0: # if values don't exist at 0, then try to find initial # conditions at 1. If it doesn't exist at 1 too then # try 2 and so on. x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order) return HolonomicFunction(sol, x).composition(z, x0, y0) if isinstance(simp, hyper): x0 = 1 # use evalf if the function can't be simplified y0 = _find_conditions(simp, x, x0, sol.order, evalf) while not y0: x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order, evalf) return HolonomicFunction(sol, x).composition(z, x0, y0) return HolonomicFunction(sol, x).composition(z) def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ): """ Converts a Meijer G-function to Holonomic. ``func`` is the G-Function and ``x0`` is the point at which initial conditions are required. Examples ======== >>> from sympy.holonomic.holonomic import from_meijerg >>> from sympy import symbols, meijerg, S >>> x = symbols('x') >>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4)) HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)]) """ a = func.ap b = func.bq n = len(func.an) m = len(func.bm) p = len(a) z = func.args[2] x = z.atoms(Symbol).pop() R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx') # compute the differential equation satisfied by the # Meijer G-function. mnp = (-1)**(m + n - p) r1 = x * mnp for i in range(len(a)): r1 *= x * Dx + 1 - a[i] r2 = 1 for i in range(len(b)): r2 *= x * Dx - b[i] sol = r1 - r2 if not initcond: return HolonomicFunction(sol, x).composition(z) simp = hyperexpand(func) if simp in (Infinity, NegativeInfinity): return HolonomicFunction(sol, x).composition(z) def _find_conditions(simp, x, x0, order, evalf=False): y0 = [] for i in range(order): if evalf: val = simp.subs(x, x0).evalf() else: val = simp.subs(x, x0) if val.is_finite is False or isinstance(val, NaN): return None y0.append(val) simp = simp.diff(x) return y0 # computing initial conditions if not isinstance(simp, meijerg): y0 = _find_conditions(simp, x, x0, sol.order) while not y0: x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order) return HolonomicFunction(sol, x).composition(z, x0, y0) if isinstance(simp, meijerg): x0 = 1 y0 = _find_conditions(simp, x, x0, sol.order, evalf) while not y0: x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order, evalf) return HolonomicFunction(sol, x).composition(z, x0, y0) return HolonomicFunction(sol, x).composition(z) x_1 = Dummy('x_1') _lookup_table = None domain_for_table = None from sympy.integrals.meijerint import _mytype def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True): """ Converts a function or an expression to a holonomic function. Parameters ========== func: The expression to be converted. x: variable for the function. x0: point at which initial condition must be computed. y0: One can optionally provide initial condition if the method is not able to do it automatically. lenics: Number of terms in the initial condition. By default it is equal to the order of the annihilator. domain: Ground domain for the polynomials in ``x`` appearing as coefficients in the annihilator. initcond: Set it false if you do not want the initial conditions to be computed. Examples ======== >>> from sympy.holonomic.holonomic import expr_to_holonomic >>> from sympy import sin, exp, symbols >>> x = symbols('x') >>> expr_to_holonomic(sin(x)) HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1]) >>> expr_to_holonomic(exp(x)) HolonomicFunction((-1) + (1)*Dx, x, 0, [1]) See Also ======== sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table """ func = sympify(func) syms = func.free_symbols if not x: if len(syms) == 1: x= syms.pop() else: raise ValueError("Specify the variable for the function") elif x in syms: syms.remove(x) extra_syms = list(syms) if domain is None: if func.has(Float): domain = RR else: domain = QQ if len(extra_syms) != 0: domain = domain[extra_syms].get_field() # try to convert if the function is polynomial or rational solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond) if solpoly: return solpoly # create the lookup table global _lookup_table, domain_for_table if not _lookup_table: domain_for_table = domain _lookup_table = {} _create_table(_lookup_table, domain=domain) elif domain != domain_for_table: domain_for_table = domain _lookup_table = {} _create_table(_lookup_table, domain=domain) # use the table directly to convert to Holonomic if func.is_Function: f = func.subs(x, x_1) t = _mytype(f, x_1) if t in _lookup_table: l = _lookup_table[t] sol = l[0][1].change_x(x) else: sol = _convert_meijerint(func, x, initcond=False, domain=domain) if not sol: raise NotImplementedError if y0: sol.y0 = y0 if y0 or not initcond: sol.x0 = x0 return sol if not lenics: lenics = sol.annihilator.order _y0 = _find_conditions(func, x, x0, lenics) while not _y0: x0 += 1 _y0 = _find_conditions(func, x, x0, lenics) return HolonomicFunction(sol.annihilator, x, x0, _y0) if y0 or not initcond: sol = sol.composition(func.args[0]) if y0: sol.y0 = y0 sol.x0 = x0 return sol if not lenics: lenics = sol.annihilator.order _y0 = _find_conditions(func, x, x0, lenics) while not _y0: x0 += 1 _y0 = _find_conditions(func, x, x0, lenics) return sol.composition(func.args[0], x0, _y0) # iterate through the expression recursively args = func.args f = func.func sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain) if f is Add: for i in range(1, len(args)): sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) elif f is Mul: for i in range(1, len(args)): sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) elif f is Pow: sol = sol**args[1] sol.x0 = x0 if not sol: raise NotImplementedError if y0: sol.y0 = y0 if y0 or not initcond: return sol if sol.y0: return sol if not lenics: lenics = sol.annihilator.order if sol.annihilator.is_singular(x0): r = sol._indicial() l = list(r) if len(r) == 1 and r[l[0]] == S.One: r = l[0] g = func / (x - x0)**r singular_ics = _find_conditions(g, x, x0, lenics) singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] y0 = {r:singular_ics} return HolonomicFunction(sol.annihilator, x, x0, y0) _y0 = _find_conditions(func, x, x0, lenics) while not _y0: x0 += 1 _y0 = _find_conditions(func, x, x0, lenics) return HolonomicFunction(sol.annihilator, x, x0, _y0) ## Some helper functions ## def _normalize(list_of, parent, negative=True): """ Normalize a given annihilator """ num = [] denom = [] base = parent.base K = base.get_field() lcm_denom = base.from_sympy(S.One) list_of_coeff = [] # convert polynomials to the elements of associated # fraction field for i, j in enumerate(list_of): if isinstance(j, base.dtype): list_of_coeff.append(K.new(j.rep)) elif not isinstance(j, K.dtype): list_of_coeff.append(K.from_sympy(sympify(j))) else: list_of_coeff.append(j) # corresponding numerators of the sequence of polynomials num.append(list_of_coeff[i].numer()) # corresponding denominators denom.append(list_of_coeff[i].denom()) # lcm of denominators in the coefficients for i in denom: lcm_denom = i.lcm(lcm_denom) if negative: lcm_denom = -lcm_denom lcm_denom = K.new(lcm_denom.rep) # multiply the coefficients with lcm for i, j in enumerate(list_of_coeff): list_of_coeff[i] = j * lcm_denom gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep) # gcd of numerators in the coefficients for i in num: gcd_numer = i.gcd(gcd_numer) gcd_numer = K.new(gcd_numer.rep) # divide all the coefficients by the gcd for i, j in enumerate(list_of_coeff): frac_ans = j / gcd_numer list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep) return DifferentialOperator(list_of_coeff, parent) def _derivate_diff_eq(listofpoly): """ Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0 where a0, a1,... are polynomials or rational functions. The function returns b0, b1, b2... such that the differential equation b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the former equation. """ sol = [] a = len(listofpoly) - 1 sol.append(DMFdiff(listofpoly[0])) for i, j in enumerate(listofpoly[1:]): sol.append(DMFdiff(j) + listofpoly[i]) sol.append(listofpoly[a]) return sol def _hyper_to_meijerg(func): """ Converts a `hyper` to meijerg. """ ap = func.ap bq = func.bq ispoly = any(i <= 0 and int(i) == i for i in ap) if ispoly: return hyperexpand(func) z = func.args[2] # parameters of the `meijerg` function. an = (1 - i for i in ap) anp = () bm = (S.Zero, ) bmq = (1 - i for i in bq) k = S.One for i in bq: k = k * gamma(i) for i in ap: k = k / gamma(i) return k * meijerg(an, anp, bm, bmq, -z) def _add_lists(list1, list2): """Takes polynomial sequences of two annihilators a and b and returns the list of polynomials of sum of a and b. """ if len(list1) <= len(list2): sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):] else: sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):] return sol def _extend_y0(Holonomic, n): """ Tries to find more initial conditions by substituting the initial value point in the differential equation. """ if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True: return Holonomic.y0 annihilator = Holonomic.annihilator a = annihilator.order listofpoly = [] y0 = Holonomic.y0 R = annihilator.parent.base K = R.get_field() for i, j in enumerate(annihilator.listofpoly): if isinstance(j, annihilator.parent.base.dtype): listofpoly.append(K.new(j.rep)) if len(y0) < a or n <= len(y0): return y0 else: list_red = [-listofpoly[i] / listofpoly[a] for i in range(a)] if len(y0) > a: y1 = [y0[i] for i in range(a)] else: y1 = [i for i in y0] for i in range(n - a): sol = 0 for a, b in zip(y1, list_red): r = DMFsubs(b, Holonomic.x0) if not getattr(r, 'is_finite', True): return y0 if isinstance(r, (PolyElement, FracElement)): r = r.as_expr() sol += a * r y1.append(sol) list_red = _derivate_diff_eq(list_red) return y0 + y1[len(y0):] def DMFdiff(frac): # differentiate a DMF object represented as p/q if not isinstance(frac, DMF): return frac.diff() K = frac.ring p = K.numer(frac) q = K.denom(frac) sol_num = - p * q.diff() + q * p.diff() sol_denom = q**2 return K((sol_num.rep, sol_denom.rep)) def DMFsubs(frac, x0, mpm=False): # substitute the point x0 in DMF object of the form p/q if not isinstance(frac, DMF): return frac p = frac.num q = frac.den sol_p = S.Zero sol_q = S.Zero if mpm: from mpmath import mp for i, j in enumerate(reversed(p)): if mpm: j = sympify(j)._to_mpmath(mp.prec) sol_p += j * x0**i for i, j in enumerate(reversed(q)): if mpm: j = sympify(j)._to_mpmath(mp.prec) sol_q += j * x0**i if isinstance(sol_p, (PolyElement, FracElement)): sol_p = sol_p.as_expr() if isinstance(sol_q, (PolyElement, FracElement)): sol_q = sol_q.as_expr() return sol_p / sol_q def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True): """ Converts polynomials, rationals and algebraic functions to holonomic. """ ispoly = func.is_polynomial() if not ispoly: israt = func.is_rational_function() else: israt = True if not (ispoly or israt): basepoly, ratexp = func.as_base_exp() if basepoly.is_polynomial() and ratexp.is_Number: if isinstance(ratexp, Float): ratexp = nsimplify(ratexp) m, n = ratexp.p, ratexp.q is_alg = True else: is_alg = False else: is_alg = True if not (ispoly or israt or is_alg): return None R = domain.old_poly_ring(x) _, Dx = DifferentialOperators(R, 'Dx') # if the function is constant if not func.has(x): return HolonomicFunction(Dx, x, 0, [func]) if ispoly: # differential equation satisfied by polynomial sol = func * Dx - func.diff(x) sol = _normalize(sol.listofpoly, sol.parent, negative=False) is_singular = sol.is_singular(x0) # try to compute the conditions for singular points if y0 is None and x0 == 0 and is_singular: rep = R.from_sympy(func).rep for i, j in enumerate(reversed(rep)): if j == 0: continue else: coeff = list(reversed(rep))[i:] indicial = i break for i, j in enumerate(coeff): if isinstance(j, (PolyElement, FracElement)): coeff[i] = j.as_expr() y0 = {indicial: S(coeff)} elif israt: p, q = func.as_numer_denom() # differential equation satisfied by rational sol = p * q * Dx + p * q.diff(x) - q * p.diff(x) sol = _normalize(sol.listofpoly, sol.parent, negative=False) elif is_alg: sol = n * (x / m) * Dx - 1 sol = HolonomicFunction(sol, x).composition(basepoly).annihilator is_singular = sol.is_singular(x0) # try to compute the conditions for singular points if y0 is None and x0 == 0 and is_singular and \ (lenics is None or lenics <= 1): rep = R.from_sympy(basepoly).rep for i, j in enumerate(reversed(rep)): if j == 0: continue if isinstance(j, (PolyElement, FracElement)): j = j.as_expr() coeff = S(j)**ratexp indicial = S(i) * ratexp break if isinstance(coeff, (PolyElement, FracElement)): coeff = coeff.as_expr() y0 = {indicial: S([coeff])} if y0 or not initcond: return HolonomicFunction(sol, x, x0, y0) if not lenics: lenics = sol.order if sol.is_singular(x0): r = HolonomicFunction(sol, x, x0)._indicial() l = list(r) if len(r) == 1 and r[l[0]] == S.One: r = l[0] g = func / (x - x0)**r singular_ics = _find_conditions(g, x, x0, lenics) singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] y0 = {r:singular_ics} return HolonomicFunction(sol, x, x0, y0) y0 = _find_conditions(func, x, x0, lenics) while not y0: x0 += 1 y0 = _find_conditions(func, x, x0, lenics) return HolonomicFunction(sol, x, x0, y0) def _convert_meijerint(func, x, initcond=True, domain=QQ): args = meijerint._rewrite1(func, x) if args: fac, po, g, _ = args else: return None # lists for sum of meijerg functions fac_list = [fac * i[0] for i in g] t = po.as_base_exp() s = t[1] if t[0] == x else S.Zero po_list = [s + i[1] for i in g] G_list = [i[2] for i in g] # finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z) def _shift(func, s): z = func.args[-1] if z.has(I): z = z.subs(exp_polar, exp) d = z.collect(x, evaluate=False) b = list(d)[0] a = d[b] t = b.as_base_exp() b = t[1] if t[0] == x else S.Zero r = s / b an = (i + r for i in func.args[0][0]) ap = (i + r for i in func.args[0][1]) bm = (i + r for i in func.args[1][0]) bq = (i + r for i in func.args[1][1]) return a**-r, meijerg((an, ap), (bm, bq), z) coeff, m = _shift(G_list[0], po_list[0]) sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain) # add all the meijerg functions after converting to holonomic for i in range(1, len(G_list)): coeff, m = _shift(G_list[i], po_list[i]) sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain) return sol def _create_table(table, domain=QQ): """ Creates the look-up table. For a similar implementation see meijerint._create_lookup_table. """ def add(formula, annihilator, arg, x0=0, y0=()): """ Adds a formula in the dictionary """ table.setdefault(_mytype(formula, x_1), []).append((formula, HolonomicFunction(annihilator, arg, x0, y0))) R = domain.old_poly_ring(x_1) _, Dx = DifferentialOperators(R, 'Dx') # add some basic functions add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1]) add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0]) add(exp(x_1), Dx - 1, x_1, 0, 1) add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1]) add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)]) add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1]) add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0]) add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1) add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) def _find_conditions(func, x, x0, order): y0 = [] for i in range(order): val = func.subs(x, x0) if isinstance(val, NaN): val = limit(func, x, x0) if val.is_finite is False or isinstance(val, NaN): return None y0.append(val) func = func.diff(x) return y0
6eddf5485e918f9c6325368b92fd4f8156eb08a757e24945f9ce19508b2a28b9
import re import typing from itertools import product from typing import Any, Dict as tDict, Tuple as tTuple, List, Optional, Union as tUnion, Callable import sympy from sympy import Mul, Add, Pow, log, exp, sqrt, cos, sin, tan, asin, acos, acot, asec, acsc, sinh, cosh, tanh, asinh, \ acosh, atanh, acoth, asech, acsch, expand, im, flatten, polylog, cancel, expand_trig, sign, simplify, \ UnevaluatedExpr, S, atan, atan2, Mod, Max, Min, rf, Ei, Si, Ci, airyai, airyaiprime, airybi, primepi, prime, \ isprime, cot, sec, csc, csch, sech, coth, Function, I, pi, Tuple, GreaterThan, StrictGreaterThan, StrictLessThan, \ LessThan, Equality, Or, And, Lambda, Integer, Dummy, symbols from sympy.core.sympify import sympify, _sympify from sympy.functions.special.bessel import airybiprime from sympy.functions.special.error_functions import li from sympy.utilities.exceptions import sympy_deprecation_warning def mathematica(s, additional_translations=None): """ Translate a string containing a Wolfram Mathematica expression to a SymPy expression. If the translator is unable to find a suitable SymPy expression, the ``FullForm`` of the Mathematica expression will be output, using SymPy ``Function`` objects as nodes of the syntax tree. Examples ======== >>> from sympy.parsing.mathematica import mathematica >>> mathematica("Sin[x]^2 Tan[y]") sin(x)**2*tan(y) >>> e = mathematica("F[7,5,3]") >>> e F(7, 5, 3) >>> from sympy import Function, Max, Min >>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x)) 21 Both standard input form and Mathematica full form are supported: >>> mathematica("x*(a + b)") x*(a + b) >>> mathematica("Times[x, Plus[a, b]]") x*(a + b) To get a matrix from Wolfram's code: >>> m = mathematica("{{a, b}, {c, d}}") >>> m ((a, b), (c, d)) >>> from sympy import Matrix >>> Matrix(m) Matrix([ [a, b], [c, d]]) If the translation into equivalent SymPy expressions fails, an SymPy expression equivalent to Wolfram Mathematica's "FullForm" will be created: >>> mathematica("x_.") Optional(Pattern(x, Blank())) >>> mathematica("Plus @@ {x, y, z}") Apply(Plus, (x, y, z)) >>> mathematica("f[x_, 3] := x^3 /; x > 0") SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0)) """ parser = MathematicaParser(additional_translations) if additional_translations is not None: sympy_deprecation_warning( """The ``additional_translations`` parameter for the Mathematica parser is now deprecated. Use SymPy's .replace( ) or .subs( ) methods on the output expression instead.""", deprecated_since_version="1.11", active_deprecations_target="mathematica-parser-additional-translations", ) return sympify(parser._parse_old(s)) return parser.parse(s) def _parse_Function(*args): if len(args) == 1: arg = args[0] Slot = Function("Slot") slots = arg.atoms(Slot) numbers = [a.args[0] for a in slots] number_of_arguments = max(numbers) if isinstance(number_of_arguments, Integer): variables = symbols(f"dummy0:{number_of_arguments}", cls=Dummy) return Lambda(variables, arg.xreplace({Slot(i+1): v for i, v in enumerate(variables)})) return Lambda((), arg) elif len(args) == 2: variables = args[0] body = args[1] return Lambda(variables, body) else: raise SyntaxError("Function node expects 1 or 2 arguments") def _deco(cls): cls._initialize_class() return cls @_deco class MathematicaParser: """ An instance of this class converts a string of a Wolfram Mathematica expression to a SymPy expression. The main parser acts internally in three stages: 1. tokenizer: tokenizes the Mathematica expression and adds the missing * operators. Handled by ``_from_mathematica_to_tokens(...)`` 2. full form list: sort the list of strings output by the tokenizer into a syntax tree of nested lists and strings, equivalent to Mathematica's ``FullForm`` expression output. This is handled by the function ``_from_tokens_to_fullformlist(...)``. 3. SymPy expression: the syntax tree expressed as full form list is visited and the nodes with equivalent classes in SymPy are replaced. Unknown syntax tree nodes are cast to SymPy ``Function`` objects. This is handled by ``_from_fullformlist_to_sympy(...)``. """ # left: Mathematica, right: SymPy CORRESPONDENCES = { 'Sqrt[x]': 'sqrt(x)', 'Exp[x]': 'exp(x)', 'Log[x]': 'log(x)', 'Log[x,y]': 'log(y,x)', 'Log2[x]': 'log(x,2)', 'Log10[x]': 'log(x,10)', 'Mod[x,y]': 'Mod(x,y)', 'Max[*x]': 'Max(*x)', 'Min[*x]': 'Min(*x)', 'Pochhammer[x,y]':'rf(x,y)', 'ArcTan[x,y]':'atan2(y,x)', 'ExpIntegralEi[x]': 'Ei(x)', 'SinIntegral[x]': 'Si(x)', 'CosIntegral[x]': 'Ci(x)', 'AiryAi[x]': 'airyai(x)', 'AiryAiPrime[x]': 'airyaiprime(x)', 'AiryBi[x]' :'airybi(x)', 'AiryBiPrime[x]' :'airybiprime(x)', 'LogIntegral[x]':' li(x)', 'PrimePi[x]': 'primepi(x)', 'Prime[x]': 'prime(x)', 'PrimeQ[x]': 'isprime(x)' } # trigonometric, e.t.c. for arc, tri, h in product(('', 'Arc'), ( 'Sin', 'Cos', 'Tan', 'Cot', 'Sec', 'Csc'), ('', 'h')): fm = arc + tri + h + '[x]' if arc: # arc func fs = 'a' + tri.lower() + h + '(x)' else: # non-arc func fs = tri.lower() + h + '(x)' CORRESPONDENCES.update({fm: fs}) REPLACEMENTS = { ' ': '', '^': '**', '{': '[', '}': ']', } RULES = { # a single whitespace to '*' 'whitespace': ( re.compile(r''' (?:(?<=[a-zA-Z\d])|(?<=\d\.)) # a letter or a number \s+ # any number of whitespaces (?:(?=[a-zA-Z\d])|(?=\.\d)) # a letter or a number ''', re.VERBOSE), '*'), # add omitted '*' character 'add*_1': ( re.compile(r''' (?:(?<=[])\d])|(?<=\d\.)) # ], ) or a number # '' (?=[(a-zA-Z]) # ( or a single letter ''', re.VERBOSE), '*'), # add omitted '*' character (variable letter preceding) 'add*_2': ( re.compile(r''' (?<=[a-zA-Z]) # a letter \( # ( as a character (?=.) # any characters ''', re.VERBOSE), '*('), # convert 'Pi' to 'pi' 'Pi': ( re.compile(r''' (?: \A|(?<=[^a-zA-Z]) ) Pi # 'Pi' is 3.14159... in Mathematica (?=[^a-zA-Z]) ''', re.VERBOSE), 'pi'), } # Mathematica function name pattern FM_PATTERN = re.compile(r''' (?: \A|(?<=[^a-zA-Z]) # at the top or a non-letter ) [A-Z][a-zA-Z\d]* # Function (?=\[) # [ as a character ''', re.VERBOSE) # list or matrix pattern (for future usage) ARG_MTRX_PATTERN = re.compile(r''' \{.*\} ''', re.VERBOSE) # regex string for function argument pattern ARGS_PATTERN_TEMPLATE = r''' (?: \A|(?<=[^a-zA-Z]) ) {arguments} # model argument like x, y,... (?=[^a-zA-Z]) ''' # will contain transformed CORRESPONDENCES dictionary TRANSLATIONS = {} # type: tDict[tTuple[str, int], tDict[str, Any]] # cache for a raw users' translation dictionary cache_original = {} # type: tDict[tTuple[str, int], tDict[str, Any]] # cache for a compiled users' translation dictionary cache_compiled = {} # type: tDict[tTuple[str, int], tDict[str, Any]] @classmethod def _initialize_class(cls): # get a transformed CORRESPONDENCES dictionary d = cls._compile_dictionary(cls.CORRESPONDENCES) cls.TRANSLATIONS.update(d) def __init__(self, additional_translations=None): self.translations = {} # update with TRANSLATIONS (class constant) self.translations.update(self.TRANSLATIONS) if additional_translations is None: additional_translations = {} # check the latest added translations if self.__class__.cache_original != additional_translations: if not isinstance(additional_translations, dict): raise ValueError('The argument must be dict type') # get a transformed additional_translations dictionary d = self._compile_dictionary(additional_translations) # update cache self.__class__.cache_original = additional_translations self.__class__.cache_compiled = d # merge user's own translations self.translations.update(self.__class__.cache_compiled) @classmethod def _compile_dictionary(cls, dic): # for return d = {} for fm, fs in dic.items(): # check function form cls._check_input(fm) cls._check_input(fs) # uncover '*' hiding behind a whitespace fm = cls._apply_rules(fm, 'whitespace') fs = cls._apply_rules(fs, 'whitespace') # remove whitespace(s) fm = cls._replace(fm, ' ') fs = cls._replace(fs, ' ') # search Mathematica function name m = cls.FM_PATTERN.search(fm) # if no-hit if m is None: err = "'{f}' function form is invalid.".format(f=fm) raise ValueError(err) # get Mathematica function name like 'Log' fm_name = m.group() # get arguments of Mathematica function args, end = cls._get_args(m) # function side check. (e.g.) '2*Func[x]' is invalid. if m.start() != 0 or end != len(fm): err = "'{f}' function form is invalid.".format(f=fm) raise ValueError(err) # check the last argument's 1st character if args[-1][0] == '*': key_arg = '*' else: key_arg = len(args) key = (fm_name, key_arg) # convert '*x' to '\\*x' for regex re_args = [x if x[0] != '*' else '\\' + x for x in args] # for regex. Example: (?:(x|y|z)) xyz = '(?:(' + '|'.join(re_args) + '))' # string for regex compile patStr = cls.ARGS_PATTERN_TEMPLATE.format(arguments=xyz) pat = re.compile(patStr, re.VERBOSE) # update dictionary d[key] = {} d[key]['fs'] = fs # SymPy function template d[key]['args'] = args # args are ['x', 'y'] for example d[key]['pat'] = pat return d def _convert_function(self, s): '''Parse Mathematica function to SymPy one''' # compiled regex object pat = self.FM_PATTERN scanned = '' # converted string cur = 0 # position cursor while True: m = pat.search(s) if m is None: # append the rest of string scanned += s break # get Mathematica function name fm = m.group() # get arguments, and the end position of fm function args, end = self._get_args(m) # the start position of fm function bgn = m.start() # convert Mathematica function to SymPy one s = self._convert_one_function(s, fm, args, bgn, end) # update cursor cur = bgn # append converted part scanned += s[:cur] # shrink s s = s[cur:] return scanned def _convert_one_function(self, s, fm, args, bgn, end): # no variable-length argument if (fm, len(args)) in self.translations: key = (fm, len(args)) # x, y,... model arguments x_args = self.translations[key]['args'] # make CORRESPONDENCES between model arguments and actual ones d = {k: v for k, v in zip(x_args, args)} # with variable-length argument elif (fm, '*') in self.translations: key = (fm, '*') # x, y,..*args (model arguments) x_args = self.translations[key]['args'] # make CORRESPONDENCES between model arguments and actual ones d = {} for i, x in enumerate(x_args): if x[0] == '*': d[x] = ','.join(args[i:]) break d[x] = args[i] # out of self.translations else: err = "'{f}' is out of the whitelist.".format(f=fm) raise ValueError(err) # template string of converted function template = self.translations[key]['fs'] # regex pattern for x_args pat = self.translations[key]['pat'] scanned = '' cur = 0 while True: m = pat.search(template) if m is None: scanned += template break # get model argument x = m.group() # get a start position of the model argument xbgn = m.start() # add the corresponding actual argument scanned += template[:xbgn] + d[x] # update cursor to the end of the model argument cur = m.end() # shrink template template = template[cur:] # update to swapped string s = s[:bgn] + scanned + s[end:] return s @classmethod def _get_args(cls, m): '''Get arguments of a Mathematica function''' s = m.string # whole string anc = m.end() + 1 # pointing the first letter of arguments square, curly = [], [] # stack for brakets args = [] # current cursor cur = anc for i, c in enumerate(s[anc:], anc): # extract one argument if c == ',' and (not square) and (not curly): args.append(s[cur:i]) # add an argument cur = i + 1 # move cursor # handle list or matrix (for future usage) if c == '{': curly.append(c) elif c == '}': curly.pop() # seek corresponding ']' with skipping irrevant ones if c == '[': square.append(c) elif c == ']': if square: square.pop() else: # empty stack args.append(s[cur:i]) break # the next position to ']' bracket (the function end) func_end = i + 1 return args, func_end @classmethod def _replace(cls, s, bef): aft = cls.REPLACEMENTS[bef] s = s.replace(bef, aft) return s @classmethod def _apply_rules(cls, s, bef): pat, aft = cls.RULES[bef] return pat.sub(aft, s) @classmethod def _check_input(cls, s): for bracket in (('[', ']'), ('{', '}'), ('(', ')')): if s.count(bracket[0]) != s.count(bracket[1]): err = "'{f}' function form is invalid.".format(f=s) raise ValueError(err) if '{' in s: err = "Currently list is not supported." raise ValueError(err) def _parse_old(self, s): # input check self._check_input(s) # uncover '*' hiding behind a whitespace s = self._apply_rules(s, 'whitespace') # remove whitespace(s) s = self._replace(s, ' ') # add omitted '*' character s = self._apply_rules(s, 'add*_1') s = self._apply_rules(s, 'add*_2') # translate function s = self._convert_function(s) # '^' to '**' s = self._replace(s, '^') # 'Pi' to 'pi' s = self._apply_rules(s, 'Pi') # '{', '}' to '[', ']', respectively # s = cls._replace(s, '{') # currently list is not taken into account # s = cls._replace(s, '}') return s def parse(self, s): s2 = self._from_mathematica_to_tokens(s) s3 = self._from_tokens_to_fullformlist(s2) s4 = self._from_fullformlist_to_sympy(s3) return s4 INFIX = "Infix" PREFIX = "Prefix" POSTFIX = "Postfix" FLAT = "Flat" RIGHT = "Right" LEFT = "Left" _mathematica_op_precedence: List[tTuple[str, Optional[str], tDict[str, tUnion[str, Callable]]]] = [ (POSTFIX, None, {";": lambda x: x + ["Null"] if isinstance(x, list) and x and x[0] == "CompoundExpression" else ["CompoundExpression", x, "Null"]}), (INFIX, FLAT, {";": "CompoundExpression"}), (INFIX, RIGHT, {"=": "Set", ":=": "SetDelayed", "+=": "AddTo", "-=": "SubtractFrom", "*=": "TimesBy", "/=": "DivideBy"}), (INFIX, LEFT, {"//": lambda x, y: [x, y]}), (POSTFIX, None, {"&": "Function"}), (INFIX, LEFT, {"/.": "ReplaceAll"}), (INFIX, RIGHT, {"->": "Rule", ":>": "RuleDelayed"}), (INFIX, LEFT, {"/;": "Condition"}), (INFIX, FLAT, {"|": "Alternatives"}), (POSTFIX, None, {"..": "Repeated", "...": "RepeatedNull"}), (INFIX, FLAT, {"||": "Or"}), (INFIX, FLAT, {"&&": "And"}), (PREFIX, None, {"!": "Not"}), (INFIX, FLAT, {"===": "SameQ", "=!=": "UnsameQ"}), (INFIX, FLAT, {"==": "Equal", "!=": "Unequal", "<=": "LessEqual", "<": "Less", ">=": "GreaterEqual", ">": "Greater"}), (INFIX, None, {";;": "Span"}), (INFIX, FLAT, {"+": "Plus", "-": "Plus"}), (INFIX, FLAT, {"*": "Times", "/": "Times"}), (INFIX, FLAT, {".": "Dot"}), (PREFIX, None, {"-": lambda x: MathematicaParser._get_neg(x), "+": lambda x: x}), (INFIX, RIGHT, {"^": "Power"}), (INFIX, RIGHT, {"@@": "Apply", "/@": "Map", "//@": "MapAll", "@@@": lambda x, y: ["Apply", x, y, ["List", "1"]]}), (POSTFIX, None, {"'": "Derivative", "!": "Factorial", "!!": "Factorial2", "--": "Decrement"}), (INFIX, None, {"[": lambda x, y: [x, *y], "[[": lambda x, y: ["Part", x, *y]}), (PREFIX, None, {"{": lambda x: ["List", *x], "(": lambda x: x[0]}), (INFIX, None, {"?": "PatternTest"}), (POSTFIX, None, { "_": lambda x: ["Pattern", x, ["Blank"]], "_.": lambda x: ["Optional", ["Pattern", x, ["Blank"]]], "__": lambda x: ["Pattern", x, ["BlankSequence"]], "___": lambda x: ["Pattern", x, ["BlankNullSequence"]], }), (INFIX, None, {"_": lambda x, y: ["Pattern", x, ["Blank", y]]}), (PREFIX, None, {"#": "Slot", "##": "SlotSequence"}), ] _missing_arguments_default = { "#": lambda: ["Slot", "1"], "##": lambda: ["SlotSequence", "1"], } _literal = r"[A-Za-z][A-Za-z0-9]*" _number = r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)" _enclosure_open = ["(", "[", "[[", "{"] _enclosure_close = [")", "]", "]]", "}"] @classmethod def _get_neg(cls, x): return f"-{x}" if isinstance(x, str) and re.match(MathematicaParser._number, x) else ["Times", "-1", x] @classmethod def _get_inv(cls, x): return ["Power", x, "-1"] _regex_tokenizer = None def _get_tokenizer(self): if self._regex_tokenizer is not None: # Check if the regular expression has already been compiled: return self._regex_tokenizer tokens = [self._literal, self._number] tokens_escape = self._enclosure_open[:] + self._enclosure_close[:] for typ, strat, symdict in self._mathematica_op_precedence: for k in symdict: tokens_escape.append(k) tokens_escape.sort(key=lambda x: -len(x)) tokens.extend(map(re.escape, tokens_escape)) tokens.append(",") tokens.append("\n") tokenizer = re.compile("(" + "|".join(tokens) + ")") self._regex_tokenizer = tokenizer return self._regex_tokenizer def _from_mathematica_to_tokens(self, code: str): tokenizer = self._get_tokenizer() # Remove comments: while True: pos_comment_start = code.find("(*") if pos_comment_start == -1: break pos_comment_end = code.find("*)") if pos_comment_end == -1 or pos_comment_end < pos_comment_start: raise SyntaxError("mismatch in comment (* *) code") code = code[:pos_comment_start] + code[pos_comment_end+2:] tokens = tokenizer.findall(code) # Remove newlines at the beginning while tokens and tokens[0] == "\n": tokens.pop(0) # Remove newlines at the end while tokens and tokens[-1] == "\n": tokens.pop(-1) return tokens def _is_op(self, token: tUnion[str, list]) -> bool: if isinstance(token, list): return False if re.match(self._literal, token): return False if re.match("-?" + self._number, token): return False return True def _is_valid_star1(self, token: tUnion[str, list]) -> bool: if token in (")", "}"): return True return not self._is_op(token) def _is_valid_star2(self, token: tUnion[str, list]) -> bool: if token in ("(", "{"): return True return not self._is_op(token) def _from_tokens_to_fullformlist(self, tokens: list): stack: List[list] = [[]] open_seq = [] pointer: int = 0 while pointer < len(tokens): token = tokens[pointer] if token in self._enclosure_open: stack[-1].append(token) open_seq.append(token) stack.append([]) elif token == ",": if len(stack[-1]) == 0 and stack[-2][-1] == open_seq[-1]: raise SyntaxError("%s cannot be followed by comma ," % open_seq[-1]) stack[-1] = self._parse_after_braces(stack[-1]) stack.append([]) elif token in self._enclosure_close: ind = self._enclosure_close.index(token) if self._enclosure_open[ind] != open_seq[-1]: unmatched_enclosure = SyntaxError("unmatched enclosure") if token == "]]" and open_seq[-1] == "[": if open_seq[-2] == "[": # These two lines would be logically correct, but are # unnecessary: # token = "]" # tokens[pointer] = "]" tokens.insert(pointer+1, "]") elif open_seq[-2] == "[[": if tokens[pointer+1] == "]": tokens[pointer+1] = "]]" elif tokens[pointer+1] == "]]": tokens[pointer+1] = "]]" tokens.insert(pointer+2, "]") else: raise unmatched_enclosure else: raise unmatched_enclosure if len(stack[-1]) == 0 and stack[-2][-1] == "(": raise SyntaxError("( ) not valid syntax") last_stack = self._parse_after_braces(stack[-1], True) stack[-1] = last_stack new_stack_element = [] while stack[-1][-1] != open_seq[-1]: new_stack_element.append(stack.pop()) new_stack_element.reverse() if open_seq[-1] == "(" and len(new_stack_element) != 1: raise SyntaxError("( must be followed by one expression, %i detected" % len(new_stack_element)) stack[-1].append(new_stack_element) open_seq.pop(-1) else: stack[-1].append(token) pointer += 1 assert len(stack) == 1 return self._parse_after_braces(stack[0]) def _util_remove_newlines(self, lines: list, tokens: list, inside_enclosure: bool): pointer = 0 size = len(tokens) while pointer < size: token = tokens[pointer] if token == "\n": if inside_enclosure: # Ignore newlines inside enclosures tokens.pop(pointer) size -= 1 continue if pointer == 0: tokens.pop(0) size -= 1 continue if pointer > 1: try: prev_expr = self._parse_after_braces(tokens[:pointer], inside_enclosure) except SyntaxError: tokens.pop(pointer) size -= 1 continue else: prev_expr = tokens[0] if len(prev_expr) > 0 and prev_expr[0] == "CompoundExpression": lines.extend(prev_expr[1:]) else: lines.append(prev_expr) for i in range(pointer): tokens.pop(0) size -= pointer pointer = 0 continue pointer += 1 def _util_add_missing_asterisks(self, tokens: list): size: int = len(tokens) pointer: int = 0 while pointer < size: if (pointer > 0 and self._is_valid_star1(tokens[pointer - 1]) and self._is_valid_star2(tokens[pointer])): # This is a trick to add missing * operators in the expression, # `"*" in op_dict` makes sure the precedence level is the same as "*", # while `not self._is_op( ... )` makes sure this and the previous # expression are not operators. if tokens[pointer] == "(": # ( has already been processed by now, replace: tokens[pointer] = "*" tokens[pointer + 1] = tokens[pointer + 1][0] else: tokens.insert(pointer, "*") pointer += 1 size += 1 pointer += 1 def _parse_after_braces(self, tokens: list, inside_enclosure: bool = False): op_dict: dict changed: bool = False lines: list = [] self._util_remove_newlines(lines, tokens, inside_enclosure) for op_type, grouping_strat, op_dict in reversed(self._mathematica_op_precedence): if "*" in op_dict: self._util_add_missing_asterisks(tokens) size: int = len(tokens) pointer: int = 0 while pointer < size: token = tokens[pointer] if isinstance(token, str) and token in op_dict: op_name: tUnion[str, Callable] = op_dict[token] node: list first_index: int if isinstance(op_name, str): node = [op_name] first_index = 1 else: node = [] first_index = 0 if token in ("+", "-") and op_type == self.PREFIX and pointer > 0 and not self._is_op(tokens[pointer - 1]): # Make sure that PREFIX + - don't match expressions like a + b or a - b, # the INFIX + - are supposed to match that expression: pointer += 1 continue if op_type == self.INFIX: if pointer == 0 or pointer == size - 1 or self._is_op(tokens[pointer - 1]) or self._is_op(tokens[pointer + 1]): pointer += 1 continue changed = True tokens[pointer] = node if op_type == self.INFIX: arg1 = tokens.pop(pointer-1) arg2 = tokens.pop(pointer) if token == "/": arg2 = self._get_inv(arg2) elif token == "-": arg2 = self._get_neg(arg2) pointer -= 1 size -= 2 node.append(arg1) node_p = node if grouping_strat == self.FLAT: while pointer + 2 < size and self._check_op_compatible(tokens[pointer+1], token): node_p.append(arg2) other_op = tokens.pop(pointer+1) arg2 = tokens.pop(pointer+1) if other_op == "/": arg2 = self._get_inv(arg2) elif other_op == "-": arg2 = self._get_neg(arg2) size -= 2 node_p.append(arg2) elif grouping_strat == self.RIGHT: while pointer + 2 < size and tokens[pointer+1] == token: node_p.append([op_name, arg2]) node_p = node_p[-1] tokens.pop(pointer+1) arg2 = tokens.pop(pointer+1) size -= 2 node_p.append(arg2) elif grouping_strat == self.LEFT: while pointer + 1 < size and tokens[pointer+1] == token: if isinstance(op_name, str): node_p[first_index] = [op_name, node_p[first_index], arg2] else: node_p[first_index] = op_name(node_p[first_index], arg2) tokens.pop(pointer+1) arg2 = tokens.pop(pointer+1) size -= 2 node_p.append(arg2) else: node.append(arg2) elif op_type == self.PREFIX: assert grouping_strat is None if pointer == size - 1 or self._is_op(tokens[pointer + 1]): tokens[pointer] = self._missing_arguments_default[token]() else: node.append(tokens.pop(pointer+1)) size -= 1 elif op_type == self.POSTFIX: assert grouping_strat is None if pointer == 0 or self._is_op(tokens[pointer - 1]): tokens[pointer] = self._missing_arguments_default[token]() else: node.append(tokens.pop(pointer-1)) pointer -= 1 size -= 1 if isinstance(op_name, Callable): # type: ignore op_call: Callable = typing.cast(Callable, op_name) new_node = op_call(*node) node.clear() if isinstance(new_node, list): node.extend(new_node) else: tokens[pointer] = new_node pointer += 1 if len(tokens) > 1 or (len(lines) == 0 and len(tokens) == 0): if changed: # Trick to deal with cases in which an operator with lower # precedence should be transformed before an operator of higher # precedence. Such as in the case of `#&[x]` (that is # equivalent to `Lambda(d_, d_)(x)` in SymPy). In this case the # operator `&` has lower precedence than `[`, but needs to be # evaluated first because otherwise `# (&[x])` is not a valid # expression: return self._parse_after_braces(tokens, inside_enclosure) raise SyntaxError("unable to create a single AST for the expression") if len(lines) > 0: if tokens[0] and tokens[0][0] == "CompoundExpression": tokens = tokens[0][1:] compound_expression = ["CompoundExpression", *lines, *tokens] return compound_expression return tokens[0] def _check_op_compatible(self, op1: str, op2: str): if op1 == op2: return True muldiv = {"*", "/"} addsub = {"+", "-"} if op1 in muldiv and op2 in muldiv: return True if op1 in addsub and op2 in addsub: return True return False def _from_fullform_to_fullformlist(self, wmexpr: str): """ Parses FullForm[Downvalues[]] generated by Mathematica """ out: list = [] stack = [out] generator = re.finditer(r'[\[\],]', wmexpr) last_pos = 0 for match in generator: if match is None: break position = match.start() last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip() if match.group() == ',': if last_expr != '': stack[-1].append(last_expr) elif match.group() == ']': if last_expr != '': stack[-1].append(last_expr) stack.pop() elif match.group() == '[': stack[-1].append([last_expr]) stack.append(stack[-1][-1]) last_pos = match.end() return out[0] def _from_fullformlist_to_fullformsympy(self, pylist: list): from sympy import Function, Symbol def converter(expr): if isinstance(expr, list): if len(expr) > 0: head = expr[0] args = [converter(arg) for arg in expr[1:]] return Function(head)(*args) else: raise ValueError("error") elif isinstance(expr, str): return Symbol(expr) else: return _sympify(expr) return converter(pylist) _node_conversions = dict( Times=Mul, Plus=Add, Power=Pow, Log=lambda *a: log(*reversed(a)), Log2=lambda x: log(x, 2), Log10=lambda x: log(x, 10), Exp=exp, Sqrt=sqrt, Sin=sin, Cos=cos, Tan=tan, Cot=cot, Sec=sec, Csc=csc, ArcSin=asin, ArcCos=acos, ArcTan=lambda *a: atan2(*reversed(a)) if len(a) == 2 else atan(*a), ArcCot=acot, ArcSec=asec, ArcCsc=acsc, Sinh=sinh, Cosh=cosh, Tanh=tanh, Coth=coth, Sech=sech, Csch=csch, ArcSinh=asinh, ArcCosh=acosh, ArcTanh=atanh, ArcCoth=acoth, ArcSech=asech, ArcCsch=acsch, Expand=expand, Im=im, Re=sympy.re, Flatten=flatten, Polylog=polylog, Cancel=cancel, # Gamma=gamma, TrigExpand=expand_trig, Sign=sign, Simplify=simplify, Defer=UnevaluatedExpr, Identity=S, # Sum=Sum_doit, # Module=With, # Block=With, Null=lambda *a: S.Zero, Mod=Mod, Max=Max, Min=Min, Pochhammer=rf, ExpIntegralEi=Ei, SinIntegral=Si, CosIntegral=Ci, AiryAi=airyai, AiryAiPrime=airyaiprime, AiryBi=airybi, AiryBiPrime=airybiprime, LogIntegral=li, PrimePi=primepi, Prime=prime, PrimeQ=isprime, List=Tuple, Greater=StrictGreaterThan, GreaterEqual=GreaterThan, Less=StrictLessThan, LessEqual=LessThan, Equal=Equality, Or=Or, And=And, Function=_parse_Function, ) _atom_conversions = { "I": I, "Pi": pi, } def _from_fullformlist_to_sympy(self, full_form_list): def recurse(expr): if isinstance(expr, list): if isinstance(expr[0], list): head = recurse(expr[0]) else: head = self._node_conversions.get(expr[0], Function(expr[0])) return head(*list(recurse(arg) for arg in expr[1:])) else: return self._atom_conversions.get(expr, sympify(expr)) return recurse(full_form_list) def _from_fullformsympy_to_sympy(self, mform): expr = mform for mma_form, sympy_node in self._node_conversions.items(): expr = expr.replace(Function(mma_form), sympy_node) return expr
d9c12d6a5024516d4865936d3aab9e51335e227ba53b6b50c98f502d4cfe1e4b
"""Transform a string with Python-like source code into SymPy expression. """ from tokenize import (generate_tokens, untokenize, TokenError, NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE) from keyword import iskeyword import ast import unicodedata from io import StringIO import builtins import types from typing import Tuple as tTuple, Dict as tDict, Any, Callable, \ List, Optional, Union as tUnion from sympy.assumptions.ask import AssumptionKeys from sympy.core.basic import Basic from sympy.core import Symbol from sympy.core.function import arity, Function from sympy.utilities.iterables import iterable from sympy.utilities.misc import filldedent, func_name from sympy.functions.elementary.miscellaneous import Max, Min null = '' TOKEN = tTuple[int, str] DICT = tDict[str, Any] TRANS = Callable[[List[TOKEN], DICT, DICT], List[TOKEN]] def _token_splittable(token_name: str) -> bool: """ Predicate for whether a token name can be split into multiple tokens. A token is splittable if it does not contain an underscore character and it is not the name of a Greek letter. This is used to implicitly convert expressions like 'xyz' into 'x*y*z'. """ if '_' in token_name: return False try: return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name) except KeyError: return len(token_name) > 1 def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None): """ Predicate for whether a token name represents a callable function. Essentially wraps ``callable``, but looks up the token name in the locals and globals. """ func = local_dict.get(token[1]) if not func: func = global_dict.get(token[1]) return callable(func) and not isinstance(func, Symbol) def _add_factorial_tokens(name: str, result: List[TOKEN]) -> List[TOKEN]: if result == [] or result[-1][1] == '(': raise TokenError() beginning = [(NAME, name), (OP, '(')] end = [(OP, ')')] diff = 0 length = len(result) for index, token in enumerate(result[::-1]): toknum, tokval = token i = length - index - 1 if tokval == ')': diff += 1 elif tokval == '(': diff -= 1 if diff == 0: if i - 1 >= 0 and result[i - 1][0] == NAME: return result[:i - 1] + beginning + result[i - 1:] + end else: return result[:i] + beginning + result[i:] + end return result class ParenthesisGroup(List[TOKEN]): """List of tokens representing an expression in parentheses.""" pass class AppliedFunction: """ A group of tokens representing a function and its arguments. `exponent` is for handling the shorthand sin^2, ln^2, etc. """ def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None): if exponent is None: exponent = [] self.function = function self.args = args self.exponent = exponent self.items = ['function', 'args', 'exponent'] def expand(self) -> List[TOKEN]: """Return a list of tokens representing the function""" return [self.function, *self.args] def __getitem__(self, index): return getattr(self, self.items[index]) def __repr__(self): return "AppliedFunction(%s, %s, %s)" % (self.function, self.args, self.exponent) def _flatten(result: List[tUnion[TOKEN, AppliedFunction]]): result2: List[TOKEN] = [] for tok in result: if isinstance(tok, AppliedFunction): result2.extend(tok.expand()) else: result2.append(tok) return result2 def _group_parentheses(recursor: TRANS): def _inner(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Group tokens between parentheses with ParenthesisGroup. Also processes those tokens recursively. """ result: List[tUnion[TOKEN, ParenthesisGroup]] = [] stacks: List[ParenthesisGroup] = [] stacklevel = 0 for token in tokens: if token[0] == OP: if token[1] == '(': stacks.append(ParenthesisGroup([])) stacklevel += 1 elif token[1] == ')': stacks[-1].append(token) stack = stacks.pop() if len(stacks) > 0: # We don't recurse here since the upper-level stack # would reprocess these tokens stacks[-1].extend(stack) else: # Recurse here to handle nested parentheses # Strip off the outer parentheses to avoid an infinite loop inner = stack[1:-1] inner = recursor(inner, local_dict, global_dict) parenGroup = [stack[0]] + inner + [stack[-1]] result.append(ParenthesisGroup(parenGroup)) stacklevel -= 1 continue if stacklevel: stacks[-1].append(token) else: result.append(token) if stacklevel: raise TokenError("Mismatched parentheses") return result return _inner def _apply_functions(tokens: List[tUnion[TOKEN, ParenthesisGroup]], local_dict: DICT, global_dict: DICT): """Convert a NAME token + ParenthesisGroup into an AppliedFunction. Note that ParenthesisGroups, if not applied to any function, are converted back into lists of tokens. """ result: List[tUnion[TOKEN, AppliedFunction]] = [] symbol = None for tok in tokens: if isinstance(tok, ParenthesisGroup): if symbol and _token_callable(symbol, local_dict, global_dict): result[-1] = AppliedFunction(symbol, tok) symbol = None else: result.extend(tok) elif tok[0] == NAME: symbol = tok result.append(tok) else: symbol = None result.append(tok) return result def _implicit_multiplication(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT): """Implicitly adds '*' tokens. Cases: - Two AppliedFunctions next to each other ("sin(x)cos(x)") - AppliedFunction next to an open parenthesis ("sin x (cos x + 1)") - A close parenthesis next to an AppliedFunction ("(x+2)sin x")\ - A close parenthesis next to an open parenthesis ("(x+2)(x+3)") - AppliedFunction next to an implicitly applied function ("sin(x)cos x") """ result: List[tUnion[TOKEN, AppliedFunction]] = [] skip = False for tok, nextTok in zip(tokens, tokens[1:]): result.append(tok) if skip: skip = False continue if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME: # Dotted name. Do not do implicit multiplication skip = True continue if isinstance(tok, AppliedFunction): if isinstance(nextTok, AppliedFunction): result.append((OP, '*')) elif nextTok == (OP, '('): # Applied function followed by an open parenthesis if tok.function[1] == "Function": tok.function = (tok.function[0], 'Symbol') result.append((OP, '*')) elif nextTok[0] == NAME: # Applied function followed by implicitly applied function result.append((OP, '*')) else: if tok == (OP, ')'): if isinstance(nextTok, AppliedFunction): # Close parenthesis followed by an applied function result.append((OP, '*')) elif nextTok[0] == NAME: # Close parenthesis followed by an implicitly applied function result.append((OP, '*')) elif nextTok == (OP, '('): # Close parenthesis followed by an open parenthesis result.append((OP, '*')) elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict): if isinstance(nextTok, AppliedFunction) or \ (nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)): # Constant followed by (implicitly applied) function result.append((OP, '*')) elif nextTok == (OP, '('): # Constant followed by parenthesis result.append((OP, '*')) elif nextTok[0] == NAME: # Constant followed by constant result.append((OP, '*')) if tokens: result.append(tokens[-1]) return result def _implicit_application(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT): """Adds parentheses as needed after functions.""" result: List[tUnion[TOKEN, AppliedFunction]] = [] appendParen = 0 # number of closing parentheses to add skip = 0 # number of tokens to delay before adding a ')' (to # capture **, ^, etc.) exponentSkip = False # skipping tokens before inserting parentheses to # work with function exponentiation for tok, nextTok in zip(tokens, tokens[1:]): result.append(tok) if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]): if _token_callable(tok, local_dict, global_dict, nextTok): # type: ignore result.append((OP, '(')) appendParen += 1 # name followed by exponent - function exponentiation elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'): if _token_callable(tok, local_dict, global_dict): # type: ignore exponentSkip = True elif exponentSkip: # if the last token added was an applied function (i.e. the # power of the function exponent) OR a multiplication (as # implicit multiplication would have added an extraneous # multiplication) if (isinstance(tok, AppliedFunction) or (tok[0] == OP and tok[1] == '*')): # don't add anything if the next token is a multiplication # or if there's already a parenthesis (if parenthesis, still # stop skipping tokens) if not (nextTok[0] == OP and nextTok[1] == '*'): if not(nextTok[0] == OP and nextTok[1] == '('): result.append((OP, '(')) appendParen += 1 exponentSkip = False elif appendParen: if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'): skip = 1 continue if skip: skip -= 1 continue result.append((OP, ')')) appendParen -= 1 if tokens: result.append(tokens[-1]) if appendParen: result.extend([(OP, ')')] * appendParen) return result def function_exponentiation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Allows functions to be exponentiated, e.g. ``cos**2(x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, function_exponentiation) >>> transformations = standard_transformations + (function_exponentiation,) >>> parse_expr('sin**4(x)', transformations=transformations) sin(x)**4 """ result: List[TOKEN] = [] exponent: List[TOKEN] = [] consuming_exponent = False level = 0 for tok, nextTok in zip(tokens, tokens[1:]): if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**': if _token_callable(tok, local_dict, global_dict): consuming_exponent = True elif consuming_exponent: if tok[0] == NAME and tok[1] == 'Function': tok = (NAME, 'Symbol') exponent.append(tok) # only want to stop after hitting ) if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(': consuming_exponent = False # if implicit multiplication was used, we may have )*( instead if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(': consuming_exponent = False del exponent[-1] continue elif exponent and not consuming_exponent: if tok[0] == OP: if tok[1] == '(': level += 1 elif tok[1] == ')': level -= 1 if level == 0: result.append(tok) result.extend(exponent) exponent = [] continue result.append(tok) if tokens: result.append(tokens[-1]) if exponent: result.extend(exponent) return result def split_symbols_custom(predicate: Callable[[str], bool]): """Creates a transformation that splits symbol names. ``predicate`` should return True if the symbol name is to be split. For instance, to retain the default behavior but avoid splitting certain symbol names, a predicate like this would work: >>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable, ... standard_transformations, implicit_multiplication, ... split_symbols_custom) >>> def can_split(symbol): ... if symbol not in ('list', 'of', 'unsplittable', 'names'): ... return _token_splittable(symbol) ... return False ... >>> transformation = split_symbols_custom(can_split) >>> parse_expr('unsplittable', transformations=standard_transformations + ... (transformation, implicit_multiplication)) unsplittable """ def _split_symbols(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): result: List[TOKEN] = [] split = False split_previous=False for tok in tokens: if split_previous: # throw out closing parenthesis of Symbol that was split split_previous=False continue split_previous=False if tok[0] == NAME and tok[1] in ['Symbol', 'Function']: split = True elif split and tok[0] == NAME: symbol = tok[1][1:-1] if predicate(symbol): tok_type = result[-2][1] # Symbol or Function del result[-2:] # Get rid of the call to Symbol i = 0 while i < len(symbol): char = symbol[i] if char in local_dict or char in global_dict: result.append((NAME, "%s" % char)) elif char.isdigit(): chars = [char] for i in range(i + 1, len(symbol)): if not symbol[i].isdigit(): i -= 1 break chars.append(symbol[i]) char = ''.join(chars) result.extend([(NAME, 'Number'), (OP, '('), (NAME, "'%s'" % char), (OP, ')')]) else: use = tok_type if i == len(symbol) else 'Symbol' result.extend([(NAME, use), (OP, '('), (NAME, "'%s'" % char), (OP, ')')]) i += 1 # Set split_previous=True so will skip # the closing parenthesis of the original Symbol split = False split_previous = True continue else: split = False result.append(tok) return result return _split_symbols #: Splits symbol names for implicit multiplication. #: #: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not #: split Greek character names, so ``theta`` will *not* become #: ``t*h*e*t*a``. Generally this should be used with #: ``implicit_multiplication``. split_symbols = split_symbols_custom(_token_splittable) def implicit_multiplication(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Makes the multiplication operator optional in most cases. Use this before :func:`implicit_application`, otherwise expressions like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication) >>> transformations = standard_transformations + (implicit_multiplication,) >>> parse_expr('3 x y', transformations=transformations) 3*x*y """ # These are interdependent steps, so we don't expose them separately res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _implicit_multiplication(res2, local_dict, global_dict) result = _flatten(res3) return result def implicit_application(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Makes parentheses optional in some cases for function calls. Use this after :func:`implicit_multiplication`, otherwise expressions like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_application) >>> transformations = standard_transformations + (implicit_application,) >>> parse_expr('cot z + csc z', transformations=transformations) cot(z) + csc(z) """ res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _implicit_application(res2, local_dict, global_dict) result = _flatten(res3) return result def implicit_multiplication_application(result: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Allows a slightly relaxed syntax. - Parentheses for single-argument method calls are optional. - Multiplication is implicit. - Symbol names can be split (i.e. spaces are not needed between symbols). - Functions can be exponentiated. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication_application) >>> parse_expr("10sin**2 x**2 + 3xyz + tan theta", ... transformations=(standard_transformations + ... (implicit_multiplication_application,))) 3*x*y*z + 10*sin(x**2)**2 + tan(theta) """ for step in (split_symbols, implicit_multiplication, implicit_application, function_exponentiation): result = step(result, local_dict, global_dict) return result def auto_symbol(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Inserts calls to ``Symbol``/``Function`` for undefined variables.""" result: List[TOKEN] = [] prevTok = (-1, '') tokens.append((-1, '')) # so zip traverses all tokens for tok, nextTok in zip(tokens, tokens[1:]): tokNum, tokVal = tok nextTokNum, nextTokVal = nextTok if tokNum == NAME: name = tokVal if (name in ['True', 'False', 'None'] or iskeyword(name) # Don't convert attribute access or (prevTok[0] == OP and prevTok[1] == '.') # Don't convert keyword arguments or (prevTok[0] == OP and prevTok[1] in ('(', ',') and nextTokNum == OP and nextTokVal == '=') # the name has already been defined or name in local_dict and local_dict[name] is not null): result.append((NAME, name)) continue elif name in local_dict: local_dict.setdefault(null, set()).add(name) if nextTokVal == '(': local_dict[name] = Function(name) else: local_dict[name] = Symbol(name) result.append((NAME, name)) continue elif name in global_dict: obj = global_dict[name] if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj): result.append((NAME, name)) continue result.extend([ (NAME, 'Symbol' if nextTokVal != '(' else 'Function'), (OP, '('), (NAME, repr(str(name))), (OP, ')'), ]) else: result.append((tokNum, tokVal)) prevTok = (tokNum, tokVal) return result def lambda_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Substitutes "lambda" with its SymPy equivalent Lambda(). However, the conversion does not take place if only "lambda" is passed because that is a syntax error. """ result: List[TOKEN] = [] flag = False toknum, tokval = tokens[0] tokLen = len(tokens) if toknum == NAME and tokval == 'lambda': if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE: # In Python 3.6.7+, inputs without a newline get NEWLINE added to # the tokens result.extend(tokens) elif tokLen > 2: result.extend([ (NAME, 'Lambda'), (OP, '('), (OP, '('), (OP, ')'), (OP, ')'), ]) for tokNum, tokVal in tokens[1:]: if tokNum == OP and tokVal == ':': tokVal = ',' flag = True if not flag and tokNum == OP and tokVal in ('*', '**'): raise TokenError("Starred arguments in lambda not supported") if flag: result.insert(-1, (tokNum, tokVal)) else: result.insert(-2, (tokNum, tokVal)) else: result.extend(tokens) return result def factorial_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Allows standard notation for factorial.""" result: List[TOKEN] = [] nfactorial = 0 for toknum, tokval in tokens: if toknum == ERRORTOKEN: op = tokval if op == '!': nfactorial += 1 else: nfactorial = 0 result.append((OP, op)) else: if nfactorial == 1: result = _add_factorial_tokens('factorial', result) elif nfactorial == 2: result = _add_factorial_tokens('factorial2', result) elif nfactorial > 2: raise TokenError nfactorial = 0 result.append((toknum, tokval)) return result def convert_xor(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Treats XOR, ``^``, as exponentiation, ``**``.""" result: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == OP: if tokval == '^': result.append((OP, '**')) else: result.append((toknum, tokval)) else: result.append((toknum, tokval)) return result def repeated_decimals(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """ Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90) Run this before auto_number. """ result: List[TOKEN] = [] def is_digit(s): return all(i in '0123456789_' for i in s) # num will running match any DECIMAL [ INTEGER ] num: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == NUMBER: if (not num and '.' in tokval and 'e' not in tokval.lower() and 'j' not in tokval.lower()): num.append((toknum, tokval)) elif is_digit(tokval)and len(num) == 2: num.append((toknum, tokval)) elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]): # Python 2 tokenizes 00123 as '00', '123' # Python 3 tokenizes 01289 as '012', '89' num.append((toknum, tokval)) else: num = [] elif toknum == OP: if tokval == '[' and len(num) == 1: num.append((OP, tokval)) elif tokval == ']' and len(num) >= 3: num.append((OP, tokval)) elif tokval == '.' and not num: # handle .[1] num.append((NUMBER, '0.')) else: num = [] else: num = [] result.append((toknum, tokval)) if num and num[-1][1] == ']': # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post, # and d/e = repetend result = result[:-len(num)] pre, post = num[0][1].split('.') repetend = num[2][1] if len(num) == 5: repetend += num[3][1] pre = pre.replace('_', '') post = post.replace('_', '') repetend = repetend.replace('_', '') zeros = '0'*len(post) post, repetends = [w.lstrip('0') for w in [post, repetend]] # or else interpreted as octal a = pre or '0' b, c = post or '0', '1' + zeros d, e = repetends, ('9'*len(repetend)) + zeros seq = [ (OP, '('), (NAME, 'Integer'), (OP, '('), (NUMBER, a), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'), (OP, ')'), ] result.extend(seq) num = [] return result def auto_number(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """ Converts numeric literals to use SymPy equivalents. Complex numbers use ``I``, integer literals use ``Integer``, and float literals use ``Float``. """ result: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == NUMBER: number = tokval postfix = [] if number.endswith('j') or number.endswith('J'): number = number[:-1] postfix = [(OP, '*'), (NAME, 'I')] if '.' in number or (('e' in number or 'E' in number) and not (number.startswith('0x') or number.startswith('0X'))): seq = [(NAME, 'Float'), (OP, '('), (NUMBER, repr(str(number))), (OP, ')')] else: seq = [(NAME, 'Integer'), (OP, '('), ( NUMBER, number), (OP, ')')] result.extend(seq + postfix) else: result.append((toknum, tokval)) return result def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Converts floats into ``Rational``. Run AFTER ``auto_number``.""" result: List[TOKEN] = [] passed_float = False for toknum, tokval in tokens: if toknum == NAME: if tokval == 'Float': passed_float = True tokval = 'Rational' result.append((toknum, tokval)) elif passed_float == True and toknum == NUMBER: passed_float = False result.append((STRING, tokval)) else: result.append((toknum, tokval)) return result def _transform_equals_sign(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Transforms the equals sign ``=`` to instances of Eq. This is a helper function for ``convert_equals_signs``. Works with expressions containing one equals sign and no nesting. Expressions like ``(1=2)=False`` will not work with this and should be used with ``convert_equals_signs``. Examples: 1=2 to Eq(1,2) 1*2=x to Eq(1*2, x) This does not deal with function arguments yet. """ result: List[TOKEN] = [] if (OP, "=") in tokens: result.append((NAME, "Eq")) result.append((OP, "(")) for token in tokens: if token == (OP, "="): result.append((OP, ",")) continue result.append(token) result.append((OP, ")")) else: result = tokens return result def convert_equals_signs(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """ Transforms all the equals signs ``=`` to instances of Eq. Parses the equals signs in the expression and replaces them with appropriate Eq instances. Also works with nested equals signs. Does not yet play well with function arguments. For example, the expression ``(x=y)`` is ambiguous and can be interpreted as x being an argument to a function and ``convert_equals_signs`` will not work for this. See also ======== convert_equality_operators Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, convert_equals_signs) >>> parse_expr("1*2=x", transformations=( ... standard_transformations + (convert_equals_signs,))) Eq(2, x) >>> parse_expr("(1*2=x)=False", transformations=( ... standard_transformations + (convert_equals_signs,))) Eq(Eq(2, x), False) """ res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _transform_equals_sign(res2, local_dict, global_dict) result = _flatten(res3) return result #: Standard transformations for :func:`parse_expr`. #: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy #: datatypes and allows the use of standard factorial notation (e.g. ``x!``). standard_transformations: tTuple[TRANS, ...] \ = (lambda_notation, auto_symbol, repeated_decimals, auto_number, factorial_notation) def stringify_expr(s: str, local_dict: DICT, global_dict: DICT, transformations: tTuple[TRANS, ...]) -> str: """ Converts the string ``s`` to Python code, in ``local_dict`` Generally, ``parse_expr`` should be used. """ tokens = [] input_code = StringIO(s.strip()) for toknum, tokval, _, _, _ in generate_tokens(input_code.readline): tokens.append((toknum, tokval)) for transform in transformations: tokens = transform(tokens, local_dict, global_dict) return untokenize(tokens) def eval_expr(code, local_dict: DICT, global_dict: DICT): """ Evaluate Python code generated by ``stringify_expr``. Generally, ``parse_expr`` should be used. """ expr = eval( code, global_dict, local_dict) # take local objects in preference return expr def parse_expr(s: str, local_dict: Optional[DICT] = None, transformations: tUnion[tTuple[TRANS, ...], str] \ = standard_transformations, global_dict: Optional[DICT] = None, evaluate=True): """Converts the string ``s`` to a SymPy expression, in ``local_dict`` Parameters ========== s : str The string to parse. local_dict : dict, optional A dictionary of local variables to use when parsing. global_dict : dict, optional A dictionary of global variables. By default, this is initialized with ``from sympy import *``; provide this parameter to override this behavior (for instance, to parse ``"Q & S"``). transformations : tuple or str A tuple of transformation functions used to modify the tokens of the parsed expression before evaluation. The default transformations convert numeric literals into their SymPy equivalents, convert undefined variables into SymPy symbols, and allow the use of standard mathematical factorial notation (e.g. ``x!``). Selection via string is available (see below). evaluate : bool, optional When False, the order of the arguments will remain as they were in the string and automatic simplification that would normally occur is suppressed. (see examples) Examples ======== >>> from sympy.parsing.sympy_parser import parse_expr >>> parse_expr("1/2") 1/2 >>> type(_) <class 'sympy.core.numbers.Half'> >>> from sympy.parsing.sympy_parser import standard_transformations,\\ ... implicit_multiplication_application >>> transformations = (standard_transformations + ... (implicit_multiplication_application,)) >>> parse_expr("2x", transformations=transformations) 2*x When evaluate=False, some automatic simplifications will not occur: >>> parse_expr("2**3"), parse_expr("2**3", evaluate=False) (8, 2**3) In addition the order of the arguments will not be made canonical. This feature allows one to tell exactly how the expression was entered: >>> a = parse_expr('1 + x', evaluate=False) >>> b = parse_expr('x + 1', evaluate=0) >>> a == b False >>> a.args (1, x) >>> b.args (x, 1) Note, however, that when these expressions are printed they will appear the same: >>> assert str(a) == str(b) As a convenience, transformations can be seen by printing ``transformations``: >>> from sympy.parsing.sympy_parser import transformations >>> print(transformations) 0: lambda_notation 1: auto_symbol 2: repeated_decimals 3: auto_number 4: factorial_notation 5: implicit_multiplication_application 6: convert_xor 7: implicit_application 8: implicit_multiplication 9: convert_equals_signs 10: function_exponentiation 11: rationalize The ``T`` object provides a way to select these transformations: >>> from sympy.parsing.sympy_parser import T If you print it, you will see the same list as shown above. >>> str(T) == str(transformations) True Standard slicing will return a tuple of transformations: >>> T[:5] == standard_transformations True So ``T`` can be used to specify the parsing transformations: >>> parse_expr("2x", transformations=T[:5]) Traceback (most recent call last): ... SyntaxError: invalid syntax >>> parse_expr("2x", transformations=T[:6]) 2*x >>> parse_expr('.3', transformations=T[3, 11]) 3/10 >>> parse_expr('.3x', transformations=T[:]) 3*x/10 As a further convenience, strings 'implicit' and 'all' can be used to select 0-5 and all the transformations, respectively. >>> parse_expr('.3x', transformations='all') 3*x/10 See Also ======== stringify_expr, eval_expr, standard_transformations, implicit_multiplication_application """ if local_dict is None: local_dict = {} elif not isinstance(local_dict, dict): raise TypeError('expecting local_dict to be a dict') elif null in local_dict: raise ValueError('cannot use "" in local_dict') if global_dict is None: global_dict = {} exec('from sympy import *', global_dict) builtins_dict = vars(builtins) for name, obj in builtins_dict.items(): if isinstance(obj, types.BuiltinFunctionType): global_dict[name] = obj global_dict['max'] = Max global_dict['min'] = Min elif not isinstance(global_dict, dict): raise TypeError('expecting global_dict to be a dict') transformations = transformations or () if isinstance(transformations, str): if transformations == 'all': _transformations = T[:] elif transformations == 'implicit': _transformations = T[:6] else: raise ValueError('unknown transformation group name') else: _transformations = transformations if _transformations: if not iterable(_transformations): raise TypeError( '`transformations` should be a list of functions.') for _ in _transformations: if not callable(_): raise TypeError(filldedent(''' expected a function in `transformations`, not %s''' % func_name(_))) if arity(_) != 3: raise TypeError(filldedent(''' a transformation should be function that takes 3 arguments''')) code = stringify_expr(s, local_dict, global_dict, _transformations) if not evaluate: code = compile(evaluateFalse(code), '<string>', 'eval') try: rv = eval_expr(code, local_dict, global_dict) # restore neutral definitions for names for i in local_dict.pop(null, ()): local_dict[i] = null return rv except Exception as e: # restore neutral definitions for names for i in local_dict.pop(null, ()): local_dict[i] = null raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}") def evaluateFalse(s: str): """ Replaces operators with the SymPy equivalent and sets evaluate=False. """ node = ast.parse(s) transformed_node = EvaluateFalseTransformer().visit(node) # node is a Module, we want an Expression transformed_node = ast.Expression(transformed_node.body[0].value) return ast.fix_missing_locations(transformed_node) class EvaluateFalseTransformer(ast.NodeTransformer): operators = { ast.Add: 'Add', ast.Mult: 'Mul', ast.Pow: 'Pow', ast.Sub: 'Add', ast.Div: 'Mul', ast.BitOr: 'Or', ast.BitAnd: 'And', ast.BitXor: 'Not', } functions = ( 'Abs', 'im', 're', 'sign', 'arg', 'conjugate', 'acos', 'acot', 'acsc', 'asec', 'asin', 'atan', 'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh', 'cos', 'cot', 'csc', 'sec', 'sin', 'tan', 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh', 'exp', 'ln', 'log', 'sqrt', 'cbrt', ) def flatten(self, args, func): result = [] for arg in args: if isinstance(arg, ast.Call): arg_func = arg.func if isinstance(arg_func, ast.Call): arg_func = arg_func.func if arg_func.id == func: result.extend(self.flatten(arg.args, func)) else: result.append(arg) else: result.append(arg) return result def visit_BinOp(self, node): if node.op.__class__ in self.operators: sympy_class = self.operators[node.op.__class__] right = self.visit(node.right) left = self.visit(node.left) rev = False if isinstance(node.op, ast.Sub): right = ast.Call( func=ast.Name(id='Mul', ctx=ast.Load()), args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) elif isinstance(node.op, ast.Div): if isinstance(node.left, ast.UnaryOp): left, right = right, left rev = True left = ast.Call( func=ast.Name(id='Pow', ctx=ast.Load()), args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) else: right = ast.Call( func=ast.Name(id='Pow', ctx=ast.Load()), args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) if rev: # undo reversal left, right = right, left new_node = ast.Call( func=ast.Name(id=sympy_class, ctx=ast.Load()), args=[left, right], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) if sympy_class in ('Add', 'Mul'): # Denest Add or Mul as appropriate new_node.args = self.flatten(new_node.args, sympy_class) return new_node return node def visit_Call(self, node): new_node = self.generic_visit(node) if isinstance(node.func, ast.Name) and node.func.id in self.functions: new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))) return new_node _transformation = { # items can be added but never re-ordered 0: lambda_notation, 1: auto_symbol, 2: repeated_decimals, 3: auto_number, 4: factorial_notation, 5: implicit_multiplication_application, 6: convert_xor, 7: implicit_application, 8: implicit_multiplication, 9: convert_equals_signs, 10: function_exponentiation, 11: rationalize} transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items()) class _T(): """class to retrieve transformations from a given slice EXAMPLES ======== >>> from sympy.parsing.sympy_parser import T, standard_transformations >>> assert T[:5] == standard_transformations """ def __init__(self): self.N = len(_transformation) def __str__(self): return transformations def __getitem__(self, t): if not type(t) is tuple: t = (t,) i = [] for ti in t: if type(ti) is int: i.append(range(self.N)[ti]) elif type(ti) is slice: i.extend(list(range(*ti.indices(self.N)))) else: raise TypeError('unexpected slice arg') return tuple([_transformation[_] for _ in i]) T = _T()
3306bfffda516b03f82e24121b4e83fdc6d2da14a1737b1a31a728152aa042f8
""" This module implements the functionality to take any Python expression as a string and fix all numbers and other things before evaluating it, thus 1/2 returns Integer(1)/Integer(2) We use the ast module for this. It is well documented at docs.python.org. Some tips to understand how this works: use dump() to get a nice representation of any node. Then write a string of what you want to get, e.g. "Integer(1)", parse it, dump it and you'll see that you need to do "Call(Name('Integer', Load()), [node], [], None, None)". You do not need to bother with lineno and col_offset, just call fix_missing_locations() before returning the node. """ from sympy.core.basic import Basic from sympy.core.sympify import SympifyError from ast import parse, NodeTransformer, Call, Name, Load, \ fix_missing_locations, Str, Tuple class Transform(NodeTransformer): def __init__(self, local_dict, global_dict): NodeTransformer.__init__(self) self.local_dict = local_dict self.global_dict = global_dict def visit_Constant(self, node): if isinstance(node.value, int): return fix_missing_locations(Call(func=Name('Integer', Load()), args=[node], keywords=[])) elif isinstance(node.value, float): return fix_missing_locations(Call(func=Name('Float', Load()), args=[node], keywords=[])) return node def visit_Num(self, node): """This function exists for backwards compatibility with Python 3.7. It should be removed when SymPy removes support for Python 3.7.""" if isinstance(node.n, int): return fix_missing_locations(Call(func=Name('Integer', Load()), args=[node], keywords=[])) elif isinstance(node.n, float): return fix_missing_locations(Call(func=Name('Float', Load()), args=[node], keywords=[])) return node def visit_Name(self, node): if node.id in self.local_dict: return node elif node.id in self.global_dict: name_obj = self.global_dict[node.id] if isinstance(name_obj, (Basic, type)) or callable(name_obj): return node elif node.id in ['True', 'False']: return node return fix_missing_locations(Call(func=Name('Symbol', Load()), args=[Str(node.id)], keywords=[])) def visit_Lambda(self, node): args = [self.visit(arg) for arg in node.args.args] body = self.visit(node.body) n = Call(func=Name('Lambda', Load()), args=[Tuple(args, Load()), body], keywords=[]) return fix_missing_locations(n) def parse_expr(s, local_dict): """ Converts the string "s" to a SymPy expression, in local_dict. It converts all numbers to Integers before feeding it to Python and automatically creates Symbols. """ global_dict = {} exec('from sympy import *', global_dict) try: a = parse(s.strip(), mode="eval") except SyntaxError: raise SympifyError("Cannot parse %s." % repr(s)) a = Transform(local_dict, global_dict).visit(a) e = compile(a, "<string>", "eval") return eval(e, global_dict, local_dict)
795793f76c1ebd9d11ebd76f883f3abe8588cd03a38c9cab40311d7f90a0750d
from sympy.core.numbers import Float from sympy.core.singleton import S from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.polynomials import assoc_laguerre from sympy.functions.special.spherical_harmonics import Ynm def R_nl(n, l, r, Z=1): """ Returns the Hydrogen radial wavefunction R_{nl}. Parameters ========== n : integer Principal Quantum Number which is an integer with possible values as 1, 2, 3, 4,... l : integer ``l`` is the Angular Momentum Quantum Number with values ranging from 0 to ``n-1``. r : Radial coordinate. Z : Atomic number (1 for Hydrogen, 2 for Helium, ...) Everything is in Hartree atomic units. Examples ======== >>> from sympy.physics.hydrogen import R_nl >>> from sympy.abc import r, Z >>> R_nl(1, 0, r, Z) 2*sqrt(Z**3)*exp(-Z*r) >>> R_nl(2, 0, r, Z) sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4 >>> R_nl(2, 1, r, Z) sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12 For Hydrogen atom, you can just use the default value of Z=1: >>> R_nl(1, 0, r) 2*exp(-r) >>> R_nl(2, 0, r) sqrt(2)*(2 - r)*exp(-r/2)/4 >>> R_nl(3, 0, r) 2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27 For Silver atom, you would use Z=47: >>> R_nl(1, 0, r, Z=47) 94*sqrt(47)*exp(-47*r) >>> R_nl(2, 0, r, Z=47) 47*sqrt(94)*(2 - 47*r)*exp(-47*r/2)/4 >>> R_nl(3, 0, r, Z=47) 94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27 The normalization of the radial wavefunction is: >>> from sympy import integrate, oo >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo)) 1 It holds for any atomic number: >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo)) 1 """ # sympify arguments n, l, r, Z = map(S, [n, l, r, Z]) # radial quantum number n_r = n - l - 1 # rescaled "r" a = 1/Z # Bohr radius r0 = 2 * r / (n * a) # normalization coefficient C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l))) # This is an equivalent normalization coefficient, that can be found in # some books. Both coefficients seem to be the same fast: # C = S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l))) return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2) def Psi_nlm(n, l, m, r, phi, theta, Z=1): """ Returns the Hydrogen wave function psi_{nlm}. It's the product of the radial wavefunction R_{nl} and the spherical harmonic Y_{l}^{m}. Parameters ========== n : integer Principal Quantum Number which is an integer with possible values as 1, 2, 3, 4,... l : integer ``l`` is the Angular Momentum Quantum Number with values ranging from 0 to ``n-1``. m : integer ``m`` is the Magnetic Quantum Number with values ranging from ``-l`` to ``l``. r : radial coordinate phi : azimuthal angle theta : polar angle Z : atomic number (1 for Hydrogen, 2 for Helium, ...) Everything is in Hartree atomic units. Examples ======== >>> from sympy.physics.hydrogen import Psi_nlm >>> from sympy import Symbol >>> r=Symbol("r", positive=True) >>> phi=Symbol("phi", real=True) >>> theta=Symbol("theta", real=True) >>> Z=Symbol("Z", positive=True, integer=True, nonzero=True) >>> Psi_nlm(1,0,0,r,phi,theta,Z) Z**(3/2)*exp(-Z*r)/sqrt(pi) >>> Psi_nlm(2,1,1,r,phi,theta,Z) -Z**(5/2)*r*exp(I*phi)*exp(-Z*r/2)*sin(theta)/(8*sqrt(pi)) Integrating the absolute square of a hydrogen wavefunction psi_{nlm} over the whole space leads 1. The normalization of the hydrogen wavefunctions Psi_nlm is: >>> from sympy import integrate, conjugate, pi, oo, sin >>> wf=Psi_nlm(2,1,1,r,phi,theta,Z) >>> abs_sqrd=wf*conjugate(wf) >>> jacobi=r**2*sin(theta) >>> integrate(abs_sqrd*jacobi, (r,0,oo), (phi,0,2*pi), (theta,0,pi)) 1 """ # sympify arguments n, l, m, r, phi, theta, Z = map(S, [n, l, m, r, phi, theta, Z]) # check if values for n,l,m make physically sense if n.is_integer and n < 1: raise ValueError("'n' must be positive integer") if l.is_integer and not (n > l): raise ValueError("'n' must be greater than 'l'") if m.is_integer and not (abs(m) <= l): raise ValueError("|'m'| must be less or equal 'l'") # return the hydrogen wave function return R_nl(n, l, r, Z)*Ynm(l, m, theta, phi).expand(func=True) def E_nl(n, Z=1): """ Returns the energy of the state (n, l) in Hartree atomic units. The energy does not depend on "l". Parameters ========== n : integer Principal Quantum Number which is an integer with possible values as 1, 2, 3, 4,... Z : Atomic number (1 for Hydrogen, 2 for Helium, ...) Examples ======== >>> from sympy.physics.hydrogen import E_nl >>> from sympy.abc import n, Z >>> E_nl(n, Z) -Z**2/(2*n**2) >>> E_nl(1) -1/2 >>> E_nl(2) -1/8 >>> E_nl(3) -1/18 >>> E_nl(3, 47) -2209/18 """ n, Z = S(n), S(Z) if n.is_integer and (n < 1): raise ValueError("'n' must be positive integer") return -Z**2/(2*n**2) def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")): """ Returns the relativistic energy of the state (n, l, spin) in Hartree atomic units. The energy is calculated from the Dirac equation. The rest mass energy is *not* included. Parameters ========== n : integer Principal Quantum Number which is an integer with possible values as 1, 2, 3, 4,... l : integer ``l`` is the Angular Momentum Quantum Number with values ranging from 0 to ``n-1``. spin_up : True if the electron spin is up (default), otherwise down Z : Atomic number (1 for Hydrogen, 2 for Helium, ...) c : Speed of light in atomic units. Default value is 137.035999037, taken from http://arxiv.org/abs/1012.3627 Examples ======== >>> from sympy.physics.hydrogen import E_nl_dirac >>> E_nl_dirac(1, 0) -0.500006656595360 >>> E_nl_dirac(2, 0) -0.125002080189006 >>> E_nl_dirac(2, 1) -0.125000416028342 >>> E_nl_dirac(2, 1, False) -0.125002080189006 >>> E_nl_dirac(3, 0) -0.0555562951740285 >>> E_nl_dirac(3, 1) -0.0555558020932949 >>> E_nl_dirac(3, 1, False) -0.0555562951740285 >>> E_nl_dirac(3, 2) -0.0555556377366884 >>> E_nl_dirac(3, 2, False) -0.0555558020932949 """ n, l, Z, c = map(S, [n, l, Z, c]) if not (l >= 0): raise ValueError("'l' must be positive or zero") if not (n > l): raise ValueError("'n' must be greater than 'l'") if (l == 0 and spin_up is False): raise ValueError("Spin must be up for l==0.") # skappa is sign*kappa, where sign contains the correct sign if spin_up: skappa = -l - 1 else: skappa = -l beta = sqrt(skappa**2 - Z**2/c**2) return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2
8c77db5a4ccbda6c85b7edfd928750a39c0fb9b0713592979658ee4b164be1b1
"""Known matrices related to physics""" from sympy.core.numbers import I from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.utilities.decorator import deprecated def msigma(i): r"""Returns a Pauli matrix `\sigma_i` with `i=1,2,3`. References ========== .. [1] https://en.wikipedia.org/wiki/Pauli_matrices Examples ======== >>> from sympy.physics.matrices import msigma >>> msigma(1) Matrix([ [0, 1], [1, 0]]) """ if i == 1: mat = ( (0, 1), (1, 0) ) elif i == 2: mat = ( (0, -I), (I, 0) ) elif i == 3: mat = ( (1, 0), (0, -1) ) else: raise IndexError("Invalid Pauli index") return Matrix(mat) def pat_matrix(m, dx, dy, dz): """Returns the Parallel Axis Theorem matrix to translate the inertia matrix a distance of `(dx, dy, dz)` for a body of mass m. Examples ======== To translate a body having a mass of 2 units a distance of 1 unit along the `x`-axis we get: >>> from sympy.physics.matrices import pat_matrix >>> pat_matrix(2, 1, 0, 0) Matrix([ [0, 0, 0], [0, 2, 0], [0, 0, 2]]) """ dxdy = -dx*dy dydz = -dy*dz dzdx = -dz*dx dxdx = dx**2 dydy = dy**2 dzdz = dz**2 mat = ((dydy + dzdz, dxdy, dzdx), (dxdy, dxdx + dzdz, dydz), (dzdx, dydz, dydy + dxdx)) return m*Matrix(mat) def mgamma(mu, lower=False): r"""Returns a Dirac gamma matrix `\gamma^\mu` in the standard (Dirac) representation. Explanation =========== If you want `\gamma_\mu`, use ``gamma(mu, True)``. We use a convention: `\gamma^5 = i \cdot \gamma^0 \cdot \gamma^1 \cdot \gamma^2 \cdot \gamma^3` `\gamma_5 = i \cdot \gamma_0 \cdot \gamma_1 \cdot \gamma_2 \cdot \gamma_3 = - \gamma^5` References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_matrices Examples ======== >>> from sympy.physics.matrices import mgamma >>> mgamma(1) Matrix([ [ 0, 0, 0, 1], [ 0, 0, 1, 0], [ 0, -1, 0, 0], [-1, 0, 0, 0]]) """ if mu not in (0, 1, 2, 3, 5): raise IndexError("Invalid Dirac index") if mu == 0: mat = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1) ) elif mu == 1: mat = ( (0, 0, 0, 1), (0, 0, 1, 0), (0, -1, 0, 0), (-1, 0, 0, 0) ) elif mu == 2: mat = ( (0, 0, 0, -I), (0, 0, I, 0), (0, I, 0, 0), (-I, 0, 0, 0) ) elif mu == 3: mat = ( (0, 0, 1, 0), (0, 0, 0, -1), (-1, 0, 0, 0), (0, 1, 0, 0) ) elif mu == 5: mat = ( (0, 0, 1, 0), (0, 0, 0, 1), (1, 0, 0, 0), (0, 1, 0, 0) ) m = Matrix(mat) if lower: if mu in (1, 2, 3, 5): m = -m return m #Minkowski tensor using the convention (+,-,-,-) used in the Quantum Field #Theory minkowski_tensor = Matrix( ( (1, 0, 0, 0), (0, -1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1) )) @deprecated( """ The sympy.physics.matrices.mdft method is deprecated. Use sympy.DFT(n).as_explicit() instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-physics-mdft", ) def mdft(n): r""" .. deprecated:: 1.9 Use DFT from sympy.matrices.expressions.fourier instead. To get identical behavior to ``mdft(n)``, use ``DFT(n).as_explicit()``. """ from sympy.matrices.expressions.fourier import DFT return DFT(n).as_mutable()
aa664dca079391e56548f8f716dcf677d7cf6372ddbc17bca4430d710318def4
from sympy import permutedims from sympy.core.numbers import Number from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray from sympy.tensor.tensor import (Tensor, TensExpr, TensAdd, TensMul, TensorIndex) class PartialDerivative(TensExpr): """ Partial derivative for tensor expressions. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorHead >>> from sympy.tensor.toperators import PartialDerivative >>> from sympy import symbols >>> L = TensorIndexType("L") >>> A = TensorHead("A", [L]) >>> B = TensorHead("B", [L]) >>> i, j, k = symbols("i j k") >>> expr = PartialDerivative(A(i), A(j)) >>> expr PartialDerivative(A(i), A(j)) The ``PartialDerivative`` object behaves like a tensorial expression: >>> expr.get_indices() [i, -j] Notice that the deriving variables have opposite valence than the printed one: ``A(j)`` is printed as covariant, but the index of the derivative is actually contravariant, i.e. ``-j``. Indices can be contracted: >>> expr = PartialDerivative(A(i), A(i)) >>> expr PartialDerivative(A(L_0), A(L_0)) >>> expr.get_indices() [L_0, -L_0] The method ``.get_indices()`` always returns all indices (even the contracted ones). If only uncontracted indices are needed, call ``.get_free_indices()``: >>> expr.get_free_indices() [] Nested partial derivatives are flattened: >>> expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(k)) >>> expr PartialDerivative(A(i), A(j), A(k)) >>> expr.get_indices() [i, -j, -k] Replace a derivative with array values: >>> from sympy.abc import x, y >>> from sympy import sin, log >>> compA = [sin(x), log(x)*y**3] >>> compB = [x, y] >>> expr = PartialDerivative(A(i), B(j)) >>> expr.replace_with_arrays({A(i): compA, B(i): compB}) [[cos(x), 0], [y**3/x, 3*y**2*log(x)]] The returned array is indexed by `(i, -j)`. Be careful that other SymPy modules put the indices of the deriving variables before the indices of the derivand in the derivative result. For example: >>> expr.get_free_indices() [i, -j] >>> from sympy import Matrix, Array >>> Matrix(compA).diff(Matrix(compB)).reshape(2, 2) [[cos(x), y**3/x], [0, 3*y**2*log(x)]] >>> Array(compA).diff(Array(compB)) [[cos(x), y**3/x], [0, 3*y**2*log(x)]] These are the transpose of the result of ``PartialDerivative``, as the matrix and the array modules put the index `-j` before `i` in the derivative result. An array read with index order `(-j, i)` is indeed the transpose of the same array read with index order `(i, -j)`. By specifying the index order to ``.replace_with_arrays`` one can get a compatible expression: >>> expr.replace_with_arrays({A(i): compA, B(i): compB}, [-j, i]) [[cos(x), y**3/x], [0, 3*y**2*log(x)]] """ def __new__(cls, expr, *variables): # Flatten: if isinstance(expr, PartialDerivative): variables = expr.variables + variables expr = expr.expr args, indices, free, dum = cls._contract_indices_for_derivative( S(expr), variables) obj = TensExpr.__new__(cls, *args) obj._indices = indices obj._free = free obj._dum = dum return obj @property def coeff(self): return S.One @property def nocoeff(self): return self @classmethod def _contract_indices_for_derivative(cls, expr, variables): variables_opposite_valence = [] for i in variables: if isinstance(i, Tensor): i_free_indices = i.get_free_indices() variables_opposite_valence.append( i.xreplace({k: -k for k in i_free_indices})) elif isinstance(i, Symbol): variables_opposite_valence.append(i) args, indices, free, dum = TensMul._tensMul_contract_indices( [expr] + variables_opposite_valence, replace_indices=True) for i in range(1, len(args)): args_i = args[i] if isinstance(args_i, Tensor): i_indices = args[i].get_free_indices() args[i] = args[i].xreplace({k: -k for k in i_indices}) return args, indices, free, dum def doit(self): args, indices, free, dum = self._contract_indices_for_derivative(self.expr, self.variables) obj = self.func(*args) obj._indices = indices obj._free = free obj._dum = dum return obj def _expand_partial_derivative(self): args, indices, free, dum = self._contract_indices_for_derivative(self.expr, self.variables) obj = self.func(*args) obj._indices = indices obj._free = free obj._dum = dum result = obj if not args[0].free_symbols: return S.Zero elif isinstance(obj.expr, TensAdd): # take care of sums of multi PDs result = obj.expr.func(*[ self.func(a, *obj.variables)._expand_partial_derivative() for a in result.expr.args]) elif isinstance(obj.expr, TensMul): # take care of products of multi PDs if len(obj.variables) == 1: # derivative with respect to single variable terms = [] mulargs = list(obj.expr.args) for ind in range(len(mulargs)): if not isinstance(sympify(mulargs[ind]), Number): # a number coefficient is not considered for # expansion of PartialDerivative d = self.func(mulargs[ind], *obj.variables)._expand_partial_derivative() terms.append(TensMul(*(mulargs[:ind] + [d] + mulargs[(ind + 1):]))) result = TensAdd.fromiter(terms) else: # derivative with respect to multiple variables # decompose: # partial(expr, (u, v)) # = partial(partial(expr, u).doit(), v).doit() result = obj.expr # init with expr for v in obj.variables: result = self.func(result, v)._expand_partial_derivative() # then throw PD on it return result def _perform_derivative(self): result = self.expr for v in self.variables: if isinstance(result, TensExpr): result = result._eval_partial_derivative(v) else: if v._diff_wrt: result = result._eval_derivative(v) else: result = S.Zero return result def get_indices(self): return self._indices def get_free_indices(self): free = sorted(self._free, key=lambda x: x[1]) return [i[0] for i in free] def _replace_indices(self, repl): expr = self.expr.xreplace(repl) mirrored = {-k: -v for k, v in repl.items()} variables = [i.xreplace(mirrored) for i in self.variables] return self.func(expr, *variables) @property def expr(self): return self.args[0] @property def variables(self): return self.args[1:] def _extract_data(self, replacement_dict): from .array import derive_by_array, tensorcontraction indices, array = self.expr._extract_data(replacement_dict) for variable in self.variables: var_indices, var_array = variable._extract_data(replacement_dict) var_indices = [-i for i in var_indices] coeff_array, var_array = zip(*[i.as_coeff_Mul() for i in var_array]) dim_before = len(array.shape) array = derive_by_array(array, var_array) dim_after = len(array.shape) dim_increase = dim_after - dim_before array = permutedims(array, [i + dim_increase for i in range(dim_before)] + list(range(dim_increase))) array = array.as_mutable() # type: MutableDenseNDimArray varindex = var_indices[0] # type: TensorIndex # Remove coefficients of base vector: coeff_index = [0] + [slice(None) for i in range(len(indices))] for i, coeff in enumerate(coeff_array): coeff_index[0] = i array[tuple(coeff_index)] /= coeff if -varindex in indices: pos = indices.index(-varindex) array = tensorcontraction(array, (0, pos+1)) indices.pop(pos) else: indices.append(varindex) return indices, array
4476468c895edcfd5f5bd25459b9e2f2106bbc2af147b06400b6aa306502efa8
""" This module defines tensors with abstract index notation. The abstract index notation has been first formalized by Penrose. Tensor indices are formal objects, with a tensor type; there is no notion of index range, it is only possible to assign the dimension, used to trace the Kronecker delta; the dimension can be a Symbol. The Einstein summation convention is used. The covariant indices are indicated with a minus sign in front of the index. For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c`` contracted. A tensor expression ``t`` can be called; called with its indices in sorted order it is equal to itself: in the above example ``t(a, b) == t``; one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``. The contracted indices are dummy indices, internally they have no name, the indices being represented by a graph-like structure. Tensors are put in canonical form using ``canon_bp``, which uses the Butler-Portugal algorithm for canonicalization using the monoterm symmetries of the tensors. If there is a (anti)symmetric metric, the indices can be raised and lowered when the tensor is put in canonical form. """ from typing import Any, Dict as tDict, List, Set as tSet, Tuple as tTuple from functools import reduce from abc import abstractmethod, ABCMeta from collections import defaultdict import operator import itertools from sympy.core.mul import prod from sympy.core.numbers import (Integer, Rational) from sympy.combinatorics import Permutation from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \ bsgs_direct_product, canonicalize, riemann_bsgs from sympy.core import Basic, Expr, sympify, Add, Mul, S from sympy.core.assumptions import ManagedProperties from sympy.core.containers import Tuple, Dict from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import CantSympify, _sympify from sympy.core.operations import AssocOp from sympy.external.gmpy import SYMPY_INTS from sympy.matrices import eye from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.decorator import memoize_property, deprecated def deprecate_data(): sympy_deprecation_warning( """ The data attribute of TensorIndexType is deprecated. Use The replace_with_arrays() method instead. """, deprecated_since_version="1.4", active_deprecations_target="deprecated-tensorindextype-attrs", stacklevel=4, ) def deprecate_fun_eval(): sympy_deprecation_warning( """ The Tensor.fun_eval() method is deprecated. Use Tensor.substitute_indices() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensor-fun-eval", stacklevel=4, ) def deprecate_call(): sympy_deprecation_warning( """ Calling a tensor like Tensor(*indices) is deprecated. Use Tensor.substitute_indices() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensor-fun-eval", stacklevel=4, ) class _IndexStructure(CantSympify): """ This class handles the indices (free and dummy ones). It contains the algorithms to manage the dummy indices replacements and contractions of free indices under multiplications of tensor expressions, as well as stuff related to canonicalization sorting, getting the permutation of the expression and so on. It also includes tools to get the ``TensorIndex`` objects corresponding to the given index structure. """ def __init__(self, free, dum, index_types, indices, canon_bp=False): self.free = free self.dum = dum self.index_types = index_types self.indices = indices self._ext_rank = len(self.free) + 2*len(self.dum) self.dum.sort(key=lambda x: x[0]) @staticmethod def from_indices(*indices): """ Create a new ``_IndexStructure`` object from a list of ``indices``. Explanation =========== ``indices`` ``TensorIndex`` objects, the indices. Contractions are detected upon construction. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) >>> _IndexStructure.from_indices(m0, m1, -m1, m3) _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz]) """ free, dum = _IndexStructure._free_dum_from_indices(*indices) index_types = [i.tensor_index_type for i in indices] indices = _IndexStructure._replace_dummy_names(indices, free, dum) return _IndexStructure(free, dum, index_types, indices) @staticmethod def from_components_free_dum(components, free, dum): index_types = [] for component in components: index_types.extend(component.index_types) indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types) return _IndexStructure(free, dum, index_types, indices) @staticmethod def _free_dum_from_indices(*indices): """ Convert ``indices`` into ``free``, ``dum`` for single component tensor. Explanation =========== ``free`` list of tuples ``(index, pos, 0)``, where ``pos`` is the position of index in the list of indices formed by the component tensors ``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)`` Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \ _IndexStructure >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3) ([(m0, 0), (m3, 3)], [(1, 2)]) """ n = len(indices) if n == 1: return [(indices[0], 0)], [] # find the positions of the free indices and of the dummy indices free = [True]*len(indices) index_dict = {} dum = [] for i, index in enumerate(indices): name = index.name typ = index.tensor_index_type contr = index.is_up if (name, typ) in index_dict: # found a pair of dummy indices is_contr, pos = index_dict[(name, typ)] # check consistency and update free if is_contr: if contr: raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i)) else: free[pos] = False free[i] = False else: if contr: free[pos] = False free[i] = False else: raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i)) if contr: dum.append((i, pos)) else: dum.append((pos, i)) else: index_dict[(name, typ)] = index.is_up, i free = [(index, i) for i, index in enumerate(indices) if free[i]] free.sort() return free, dum def get_indices(self): """ Get a list of indices, creating new tensor indices to complete dummy indices. """ return self.indices[:] @staticmethod def generate_indices_from_free_dum_index_types(free, dum, index_types): indices = [None]*(len(free)+2*len(dum)) for idx, pos in free: indices[pos] = idx generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) for pos1, pos2 in dum: typ1 = index_types[pos1] indname = generate_dummy_name(typ1) indices[pos1] = TensorIndex(indname, typ1, True) indices[pos2] = TensorIndex(indname, typ1, False) return _IndexStructure._replace_dummy_names(indices, free, dum) @staticmethod def _get_generator_for_dummy_indices(free): cdt = defaultdict(int) # if the free indices have names with dummy_name, start with an # index higher than those for the dummy indices # to avoid name collisions for indx, ipos in free: if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name: cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1) def dummy_name_gen(tensor_index_type): nd = str(cdt[tensor_index_type]) cdt[tensor_index_type] += 1 return tensor_index_type.dummy_name + '_' + nd return dummy_name_gen @staticmethod def _replace_dummy_names(indices, free, dum): dum.sort(key=lambda x: x[0]) new_indices = [ind for ind in indices] assert len(indices) == len(free) + 2*len(dum) generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) for ipos1, ipos2 in dum: typ1 = new_indices[ipos1].tensor_index_type indname = generate_dummy_name(typ1) new_indices[ipos1] = TensorIndex(indname, typ1, True) new_indices[ipos2] = TensorIndex(indname, typ1, False) return new_indices def get_free_indices(self): # type: () -> List[TensorIndex] """ Get a list of free indices. """ # get sorted indices according to their position: free = sorted(self.free, key=lambda x: x[1]) return [i[0] for i in free] def __str__(self): return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types) def __repr__(self): return self.__str__() def _get_sorted_free_indices_for_canon(self): sorted_free = self.free[:] sorted_free.sort(key=lambda x: x[0]) return sorted_free def _get_sorted_dum_indices_for_canon(self): return sorted(self.dum, key=lambda x: x[0]) def _get_lexicographically_sorted_index_types(self): permutation = self.indices_canon_args()[0] index_types = [None]*self._ext_rank for i, it in enumerate(self.index_types): index_types[permutation(i)] = it return index_types def _get_lexicographically_sorted_indices(self): permutation = self.indices_canon_args()[0] indices = [None]*self._ext_rank for i, it in enumerate(self.indices): indices[permutation(i)] = it return indices def perm2tensor(self, g, is_canon_bp=False): """ Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``. Explanation =========== ``g`` permutation corresponding to the tensor in the representation used in canonicalization ``is_canon_bp`` if True, then ``g`` is the permutation corresponding to the canonical form of the tensor """ sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()] lex_index_types = self._get_lexicographically_sorted_index_types() lex_indices = self._get_lexicographically_sorted_indices() nfree = len(sorted_free) rank = self._ext_rank dum = [[None]*2 for i in range((rank - nfree)//2)] free = [] index_types = [None]*rank indices = [None]*rank for i in range(rank): gi = g[i] index_types[i] = lex_index_types[gi] indices[i] = lex_indices[gi] if gi < nfree: ind = sorted_free[gi] assert index_types[i] == sorted_free[gi].tensor_index_type free.append((ind, i)) else: j = gi - nfree idum, cov = divmod(j, 2) if cov: dum[idum][1] = i else: dum[idum][0] = i dum = [tuple(x) for x in dum] return _IndexStructure(free, dum, index_types, indices) def indices_canon_args(self): """ Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize`` See ``canonicalize`` in ``tensor_can.py`` in combinatorics module. """ # to be called after sorted_components from sympy.combinatorics.permutations import _af_new n = self._ext_rank g = [None]*n + [n, n+1] # Converts the symmetry of the metric into msym from .canonicalize() # method in the combinatorics module def metric_symmetry_to_msym(metric): if metric is None: return None sym = metric.symmetry if sym == TensorSymmetry.fully_symmetric(2): return 0 if sym == TensorSymmetry.fully_symmetric(-2): return 1 return None # ordered indices: first the free indices, ordered by types # then the dummy indices, ordered by types and contravariant before # covariant # g[position in tensor] = position in ordered indices for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()): g[ipos] = i pos = len(self.free) j = len(self.free) dummies = [] prev = None a = [] msym = [] for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon(): g[ipos1] = j g[ipos2] = j + 1 j += 2 typ = self.index_types[ipos1] if typ != prev: if a: dummies.append(a) a = [pos, pos + 1] prev = typ msym.append(metric_symmetry_to_msym(typ.metric)) else: a.extend([pos, pos + 1]) pos += 2 if a: dummies.append(a) return _af_new(g), dummies, msym def components_canon_args(components): numtyp = [] prev = None for t in components: if t == prev: numtyp[-1][1] += 1 else: prev = t numtyp.append([prev, 1]) v = [] for h, n in numtyp: if h.comm in (0, 1): comm = h.comm else: comm = TensorManager.get_comm(h.comm, h.comm) v.append((h.symmetry.base, h.symmetry.generators, n, comm)) return v class _TensorDataLazyEvaluator(CantSympify): """ EXPERIMENTAL: do not rely on this class, it may change without deprecation warnings in future versions of SymPy. Explanation =========== This object contains the logic to associate components data to a tensor expression. Components data are set via the ``.data`` property of tensor expressions, is stored inside this class as a mapping between the tensor expression and the ``ndarray``. Computations are executed lazily: whereas the tensor expressions can have contractions, tensor products, and additions, components data are not computed until they are accessed by reading the ``.data`` property associated to the tensor expression. """ _substitutions_dict = dict() # type: tDict[Any, Any] _substitutions_dict_tensmul = dict() # type: tDict[Any, Any] def __getitem__(self, key): dat = self._get(key) if dat is None: return None from .array import NDimArray if not isinstance(dat, NDimArray): return dat if dat.rank() == 0: return dat[()] elif dat.rank() == 1 and len(dat) == 1: return dat[0] return dat def _get(self, key): """ Retrieve ``data`` associated with ``key``. Explanation =========== This algorithm looks into ``self._substitutions_dict`` for all ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a TensorHead instance). It reconstructs the components data that the tensor expression should have by performing on components data the operations that correspond to the abstract tensor operations applied. Metric tensor is handled in a different manner: it is pre-computed in ``self._substitutions_dict_tensmul``. """ if key in self._substitutions_dict: return self._substitutions_dict[key] if isinstance(key, TensorHead): return None if isinstance(key, Tensor): # special case to handle metrics. Metric tensors cannot be # constructed through contraction by the metric, their # components show if they are a matrix or its inverse. signature = tuple([i.is_up for i in key.get_indices()]) srch = (key.component,) + signature if srch in self._substitutions_dict_tensmul: return self._substitutions_dict_tensmul[srch] array_list = [self.data_from_tensor(key)] return self.data_contract_dum(array_list, key.dum, key.ext_rank) if isinstance(key, TensMul): tensmul_args = key.args if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1: # special case to handle metrics. Metric tensors cannot be # constructed through contraction by the metric, their # components show if they are a matrix or its inverse. signature = tuple([i.is_up for i in tensmul_args[0].get_indices()]) srch = (tensmul_args[0].components[0],) + signature if srch in self._substitutions_dict_tensmul: return self._substitutions_dict_tensmul[srch] #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)] data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)] coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)]) if all(i is None for i in data_list): return None if any(i is None for i in data_list): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank) return coeff*data_result if isinstance(key, TensAdd): data_list = [] free_args_list = [] for arg in key.args: if isinstance(arg, TensExpr): data_list.append(arg.data) free_args_list.append([x[0] for x in arg.free]) else: data_list.append(arg) free_args_list.append([]) if all(i is None for i in data_list): return None if any(i is None for i in data_list): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") sum_list = [] from .array import permutedims for data, free_args in zip(data_list, free_args_list): if len(free_args) < 2: sum_list.append(data) else: free_args_pos = {y: x for x, y in enumerate(free_args)} axes = [free_args_pos[arg] for arg in key.free_args] sum_list.append(permutedims(data, axes)) return reduce(lambda x, y: x+y, sum_list) return None @staticmethod def data_contract_dum(ndarray_list, dum, ext_rank): from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray arrays = list(map(MutableDenseNDimArray, ndarray_list)) prodarr = tensorproduct(*arrays) return tensorcontraction(prodarr, *dum) def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead): """ This method is used when assigning components data to a ``TensMul`` object, it converts components data to a fully contravariant ndarray, which is then stored according to the ``TensorHead`` key. """ if data is None: return None return self._correct_signature_from_indices( data, tensmul.get_indices(), tensmul.free, tensmul.dum, True) def data_from_tensor(self, tensor): """ This method corrects the components data to the right signature (covariant/contravariant) using the metric associated with each ``TensorIndexType``. """ tensorhead = tensor.component if tensorhead.data is None: return None return self._correct_signature_from_indices( tensorhead.data, tensor.get_indices(), tensor.free, tensor.dum) def _assign_data_to_tensor_expr(self, key, data): if isinstance(key, TensAdd): raise ValueError('cannot assign data to TensAdd') # here it is assumed that `key` is a `TensMul` instance. if len(key.components) != 1: raise ValueError('cannot assign data to TensMul with multiple components') tensorhead = key.components[0] newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead) return tensorhead, newdata def _check_permutations_on_data(self, tens, data): from .array import permutedims from .array.arrayop import Flatten if isinstance(tens, TensorHead): rank = tens.rank generators = tens.symmetry.generators elif isinstance(tens, Tensor): rank = tens.rank generators = tens.components[0].symmetry.generators elif isinstance(tens, TensorIndexType): rank = tens.metric.rank generators = tens.metric.symmetry.generators # Every generator is a permutation, check that by permuting the array # by that permutation, the array will be the same, except for a # possible sign change if the permutation admits it. for gener in generators: sign_change = +1 if (gener(rank) == rank) else -1 data_swapped = data last_data = data permute_axes = list(map(gener, list(range(rank)))) # the order of a permutation is the number of times to get the # identity by applying that permutation. for i in range(gener.order()-1): data_swapped = permutedims(data_swapped, permute_axes) # if any value in the difference array is non-zero, raise an error: if any(Flatten(last_data - sign_change*data_swapped)): raise ValueError("Component data symmetry structure error") last_data = data_swapped def __setitem__(self, key, value): """ Set the components data of a tensor object/expression. Explanation =========== Components data are transformed to the all-contravariant form and stored with the corresponding ``TensorHead`` object. If a ``TensorHead`` object cannot be uniquely identified, it will raise an error. """ data = _TensorDataLazyEvaluator.parse_data(value) self._check_permutations_on_data(key, data) # TensorHead and TensorIndexType can be assigned data directly, while # TensMul must first convert data to a fully contravariant form, and # assign it to its corresponding TensorHead single component. if not isinstance(key, (TensorHead, TensorIndexType)): key, data = self._assign_data_to_tensor_expr(key, data) if isinstance(key, TensorHead): for dim, indextype in zip(data.shape, key.index_types): if indextype.data is None: raise ValueError("index type {} has no components data"\ " associated (needed to raise/lower index)".format(indextype)) if not indextype.dim.is_number: continue if dim != indextype.dim: raise ValueError("wrong dimension of ndarray") self._substitutions_dict[key] = data def __delitem__(self, key): del self._substitutions_dict[key] def __contains__(self, key): return key in self._substitutions_dict def add_metric_data(self, metric, data): """ Assign data to the ``metric`` tensor. The metric tensor behaves in an anomalous way when raising and lowering indices. Explanation =========== A fully covariant metric is the inverse transpose of the fully contravariant metric (it is meant matrix inverse). If the metric is symmetric, the transpose is not necessary and mixed covariant/contravariant metrics are Kronecker deltas. """ # hard assignment, data should not be added to `TensorHead` for metric: # the problem with `TensorHead` is that the metric is anomalous, i.e. # raising and lowering the index means considering the metric or its # inverse, this is not the case for other tensors. self._substitutions_dict_tensmul[metric, True, True] = data inverse_transpose = self.inverse_transpose_matrix(data) # in symmetric spaces, the transpose is the same as the original matrix, # the full covariant metric tensor is the inverse transpose, so this # code will be able to handle non-symmetric metrics. self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose # now mixed cases, these are identical to the unit matrix if the metric # is symmetric. m = data.tomatrix() invt = inverse_transpose.tomatrix() self._substitutions_dict_tensmul[metric, True, False] = m * invt self._substitutions_dict_tensmul[metric, False, True] = invt * m @staticmethod def _flip_index_by_metric(data, metric, pos): from .array import tensorproduct, tensorcontraction mdim = metric.rank() ddim = data.rank() if pos == 0: data = tensorcontraction( tensorproduct( metric, data ), (1, mdim+pos) ) else: data = tensorcontraction( tensorproduct( data, metric ), (pos, ddim) ) return data @staticmethod def inverse_matrix(ndarray): m = ndarray.tomatrix().inv() return _TensorDataLazyEvaluator.parse_data(m) @staticmethod def inverse_transpose_matrix(ndarray): m = ndarray.tomatrix().inv().T return _TensorDataLazyEvaluator.parse_data(m) @staticmethod def _correct_signature_from_indices(data, indices, free, dum, inverse=False): """ Utility function to correct the values inside the components data ndarray according to whether indices are covariant or contravariant. It uses the metric matrix to lower values of covariant indices. """ # change the ndarray values according covariantness/contravariantness of the indices # use the metric for i, indx in enumerate(indices): if not indx.is_up and not inverse: data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i) elif not indx.is_up and inverse: data = _TensorDataLazyEvaluator._flip_index_by_metric( data, _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data), i ) return data @staticmethod def _sort_data_axes(old, new): from .array import permutedims new_data = old.data.copy() old_free = [i[0] for i in old.free] new_free = [i[0] for i in new.free] for i in range(len(new_free)): for j in range(i, len(old_free)): if old_free[j] == new_free[i]: old_free[i], old_free[j] = old_free[j], old_free[i] new_data = permutedims(new_data, (i, j)) break return new_data @staticmethod def add_rearrange_tensmul_parts(new_tensmul, old_tensmul): def sorted_compo(): return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul) _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo() @staticmethod def parse_data(data): """ Transform ``data`` to array. The parameter ``data`` may contain data in various formats, e.g. nested lists, SymPy ``Matrix``, and so on. Examples ======== >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12]) [1, 3, -6, 12] >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]]) [[1, 2], [4, 7]] """ from .array import MutableDenseNDimArray if not isinstance(data, MutableDenseNDimArray): if len(data) == 2 and hasattr(data[0], '__call__'): data = MutableDenseNDimArray(data[0], data[1]) else: data = MutableDenseNDimArray(data) return data _tensor_data_substitution_dict = _TensorDataLazyEvaluator() class _TensorManager: """ Class to manage tensor properties. Notes ===== Tensors belong to tensor commutation groups; each group has a label ``comm``; there are predefined labels: ``0`` tensors commuting with any other tensor ``1`` tensors anticommuting among themselves ``2`` tensors not commuting, apart with those with ``comm=0`` Other groups can be defined using ``set_comm``; tensors in those groups commute with those with ``comm=0``; by default they do not commute with any other group. """ def __init__(self): self._comm_init() def _comm_init(self): self._comm = [{} for i in range(3)] for i in range(3): self._comm[0][i] = 0 self._comm[i][0] = 0 self._comm[1][1] = 1 self._comm[2][1] = None self._comm[1][2] = None self._comm_symbols2i = {0:0, 1:1, 2:2} self._comm_i2symbol = {0:0, 1:1, 2:2} @property def comm(self): return self._comm def comm_symbols2i(self, i): """ Get the commutation group number corresponding to ``i``. ``i`` can be a symbol or a number or a string. If ``i`` is not already defined its commutation group number is set. """ if i not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[n][0] = 0 self._comm[0][n] = 0 self._comm_symbols2i[i] = n self._comm_i2symbol[n] = i return n return self._comm_symbols2i[i] def comm_i2symbol(self, i): """ Returns the symbol corresponding to the commutation group number. """ return self._comm_i2symbol[i] def set_comm(self, i, j, c): """ Set the commutation parameter ``c`` for commutation groups ``i, j``. Parameters ========== i, j : symbols representing commutation groups c : group commutation number Notes ===== ``i, j`` can be symbols, strings or numbers, apart from ``0, 1`` and ``2`` which are reserved respectively for commuting, anticommuting tensors and tensors not commuting with any other group apart with the commuting tensors. For the remaining cases, use this method to set the commutation rules; by default ``c=None``. The group commutation number ``c`` is assigned in correspondence to the group commutation symbols; it can be 0 commuting 1 anticommuting None no commutation property Examples ======== ``G`` and ``GH`` do not commute with themselves and commute with each other; A is commuting. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz') >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz) >>> A = TensorHead('A', [Lorentz]) >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm') >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm') >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0) >>> (GH(i1)*G(i0)).canon_bp() G(i0)*GH(i1) >>> (G(i1)*G(i0)).canon_bp() G(i1)*G(i0) >>> (G(i1)*A(i0)).canon_bp() A(i0)*G(i1) """ if c not in (0, 1, None): raise ValueError('`c` can assume only the values 0, 1 or None') if i not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[n][0] = 0 self._comm[0][n] = 0 self._comm_symbols2i[i] = n self._comm_i2symbol[n] = i if j not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[0][n] = 0 self._comm[n][0] = 0 self._comm_symbols2i[j] = n self._comm_i2symbol[n] = j ni = self._comm_symbols2i[i] nj = self._comm_symbols2i[j] self._comm[ni][nj] = c self._comm[nj][ni] = c def set_comms(self, *args): """ Set the commutation group numbers ``c`` for symbols ``i, j``. Parameters ========== args : sequence of ``(i, j, c)`` """ for i, j, c in args: self.set_comm(i, j, c) def get_comm(self, i, j): """ Return the commutation parameter for commutation group numbers ``i, j`` see ``_TensorManager.set_comm`` """ return self._comm[i].get(j, 0 if i == 0 or j == 0 else None) def clear(self): """ Clear the TensorManager. """ self._comm_init() TensorManager = _TensorManager() class TensorIndexType(Basic): """ A TensorIndexType is characterized by its name and its metric. Parameters ========== name : name of the tensor type dummy_name : name of the head of dummy indices dim : dimension, it can be a symbol or an integer or ``None`` eps_dim : dimension of the epsilon tensor metric_symmetry : integer that denotes metric symmetry or ``None`` for no metirc metric_name : string with the name of the metric tensor Attributes ========== ``metric`` : the metric tensor ``delta`` : ``Kronecker delta`` ``epsilon`` : the ``Levi-Civita epsilon`` tensor ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis. Notes ===== The possible values of the ``metric_symmetry`` parameter are: ``1`` : metric tensor is fully symmetric ``0`` : metric tensor possesses no index symmetry ``-1`` : metric tensor is fully antisymmetric ``None``: there is no metric tensor (metric equals to ``None``) The metric is assumed to be symmetric by default. It can also be set to a custom tensor by the ``.set_metric()`` method. If there is a metric the metric is used to raise and lower indices. In the case of non-symmetric metric, the following raising and lowering conventions will be adopted: ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)`` From these it is easy to find: ``g(-a, b) = delta(-a, b)`` where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta`` (see ``TensorIndex`` for the conventions on indices). For antisymmetric metrics there is also the following equality: ``g(a, -b) = -delta(a, -b)`` If there is no metric it is not possible to raise or lower indices; e.g. the index of the defining representation of ``SU(N)`` is 'covariant' and the conjugate representation is 'contravariant'; for ``N > 2`` they are linearly independent. ``eps_dim`` is by default equal to ``dim``, if the latter is an integer; else it can be assigned (for use in naive dimensional regularization); if ``eps_dim`` is not an integer ``epsilon`` is ``None``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> Lorentz.metric metric(Lorentz,Lorentz) """ def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None, metric_symmetry=1, metric_name='metric', **kwargs): if 'dummy_fmt' in kwargs: dummy_fmt = kwargs['dummy_fmt'] sympy_deprecation_warning( f""" The dummy_fmt keyword to TensorIndexType is deprecated. Use dummy_name={dummy_fmt} instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-dummy-fmt", ) dummy_name = dummy_fmt if isinstance(name, str): name = Symbol(name) if dummy_name is None: dummy_name = str(name)[0] if isinstance(dummy_name, str): dummy_name = Symbol(dummy_name) if dim is None: dim = Symbol("dim_" + dummy_name.name) else: dim = sympify(dim) if eps_dim is None: eps_dim = dim else: eps_dim = sympify(eps_dim) metric_symmetry = sympify(metric_symmetry) if isinstance(metric_name, str): metric_name = Symbol(metric_name) if 'metric' in kwargs: SymPyDeprecationWarning( """ The 'metric' keyword argument to TensorIndexType is deprecated. Use the 'metric_symmetry' keyword argument or the TensorIndexType.set_metric() method instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-metric", ) metric = kwargs.get('metric') if metric is not None: if metric in (True, False, 0, 1): metric_name = 'metric' #metric_antisym = metric else: metric_name = metric.name #metric_antisym = metric.antisym if metric: metric_symmetry = -1 else: metric_symmetry = 1 obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim, metric_symmetry, metric_name) obj._autogenerated = [] return obj @property def name(self): return self.args[0].name @property def dummy_name(self): return self.args[1].name @property def dim(self): return self.args[2] @property def eps_dim(self): return self.args[3] @memoize_property def metric(self): metric_symmetry = self.args[4] metric_name = self.args[5] if metric_symmetry is None: return None if metric_symmetry == 0: symmetry = TensorSymmetry.no_symmetry(2) elif metric_symmetry == 1: symmetry = TensorSymmetry.fully_symmetric(2) elif metric_symmetry == -1: symmetry = TensorSymmetry.fully_symmetric(-2) return TensorHead(metric_name, [self]*2, symmetry) @memoize_property def delta(self): return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2)) @memoize_property def epsilon(self): if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)): return None symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim) return TensorHead('Eps', [self]*self.eps_dim, symmetry) def set_metric(self, tensor): self._metric = tensor def __lt__(self, other): return self.name < other.name def __str__(self): return self.name __repr__ = __str__ # Everything below this line is deprecated @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # This assignment is a bit controversial, should metric components be assigned # to the metric only or also to the TensorIndexType object? The advantage here # is the ability to assign a 1D array and transform it to a 2D diagonal array. from .array import MutableDenseNDimArray data = _TensorDataLazyEvaluator.parse_data(data) if data.rank() > 2: raise ValueError("data have to be of rank 1 (diagonal metric) or 2.") if data.rank() == 1: if self.dim.is_number: nda_dim = data.shape[0] if nda_dim != self.dim: raise ValueError("Dimension mismatch") dim = data.shape[0] newndarray = MutableDenseNDimArray.zeros(dim, dim) for i, val in enumerate(data): newndarray[i, i] = val data = newndarray dim1, dim2 = data.shape if dim1 != dim2: raise ValueError("Non-square matrix tensor.") if self.dim.is_number: if self.dim != dim1: raise ValueError("Dimension mismatch") _tensor_data_substitution_dict[self] = data _tensor_data_substitution_dict.add_metric_data(self.metric, data) with ignore_warnings(SymPyDeprecationWarning): delta = self.get_kronecker_delta() i1 = TensorIndex('i1', self) i2 = TensorIndex('i2', self) with ignore_warnings(SymPyDeprecationWarning): delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1)) @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] @deprecated( """ The TensorIndexType.get_kronecker_delta() method is deprecated. Use the TensorIndexType.delta attribute instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-methods", ) def get_kronecker_delta(self): sym2 = TensorSymmetry(get_symmetric_group_sgs(2)) delta = TensorHead('KD', [self]*2, sym2) return delta @deprecated( """ The TensorIndexType.get_epsilon() method is deprecated. Use the TensorIndexType.epsilon attribute instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-methods", ) def get_epsilon(self): if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)): return None sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1)) epsilon = TensorHead('Eps', [self]*self._eps_dim, sym) return epsilon def _components_data_full_destroy(self): """ EXPERIMENTAL: do not rely on this API method. This destroys components data associated to the ``TensorIndexType``, if any, specifically: * metric tensor data * Kronecker tensor data """ if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def delete_tensmul_data(key): if key in _tensor_data_substitution_dict._substitutions_dict_tensmul: del _tensor_data_substitution_dict._substitutions_dict_tensmul[key] # delete metric data: delete_tensmul_data((self.metric, True, True)) delete_tensmul_data((self.metric, True, False)) delete_tensmul_data((self.metric, False, True)) delete_tensmul_data((self.metric, False, False)) # delete delta tensor data: delta = self.get_kronecker_delta() if delta in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[delta] class TensorIndex(Basic): """ Represents a tensor index Parameters ========== name : name of the index, or ``True`` if you want it to be automatically assigned tensor_index_type : ``TensorIndexType`` of the index is_up : flag for contravariant index (is_up=True by default) Attributes ========== ``name`` ``tensor_index_type`` ``is_up`` Notes ===== Tensor indices are contracted with the Einstein summation convention. An index can be in contravariant or in covariant form; in the latter case it is represented prepending a ``-`` to the index name. Adding ``-`` to a covariant (is_up=False) index makes it contravariant. Dummy indices have a name with head given by ``tensor_inde_type.dummy_name`` with underscore and a number. Similar to ``symbols`` multiple contravariant indices can be created at once using ``tensor_indices(s, typ)``, where ``s`` is a string of names. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> mu = TensorIndex('mu', Lorentz, is_up=False) >>> nu, rho = tensor_indices('nu, rho', Lorentz) >>> A = TensorHead('A', [Lorentz, Lorentz]) >>> A(mu, nu) A(-mu, nu) >>> A(-mu, -rho) A(mu, -rho) >>> A(mu, -mu) A(-L_0, L_0) """ def __new__(cls, name, tensor_index_type, is_up=True): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name elif name is True: name = "_i{}".format(len(tensor_index_type._autogenerated)) name_symbol = Symbol(name) tensor_index_type._autogenerated.append(name_symbol) else: raise ValueError("invalid name") is_up = sympify(is_up) return Basic.__new__(cls, name_symbol, tensor_index_type, is_up) @property def name(self): return self.args[0].name @property def tensor_index_type(self): return self.args[1] @property def is_up(self): return self.args[2] def _print(self): s = self.name if not self.is_up: s = '-%s' % s return s def __lt__(self, other): return ((self.tensor_index_type, self.name) < (other.tensor_index_type, other.name)) def __neg__(self): t1 = TensorIndex(self.name, self.tensor_index_type, (not self.is_up)) return t1 def tensor_indices(s, typ): """ Returns list of tensor indices given their names and their types. Parameters ========== s : string of comma separated names of indices typ : ``TensorIndexType`` of the indices Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) """ if isinstance(s, str): a = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') tilist = [TensorIndex(i, typ) for i in a] if len(tilist) == 1: return tilist[0] return tilist class TensorSymmetry(Basic): """ Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric index permutation). For the relevant terminology see ``tensor_can.py`` section of the combinatorics module. Parameters ========== bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor Attributes ========== ``base`` : base of the BSGS ``generators`` : generators of the BSGS ``rank`` : rank of the tensor Notes ===== A tensor can have an arbitrary monoterm symmetry provided by its BSGS. Multiterm symmetries, like the cyclic symmetry of the Riemann tensor (i.e., Bianchi identity), are not covered. See combinatorics module for information on how to generate BSGS for a general index permutation group. Simple symmetries can be generated using built-in methods. See Also ======== sympy.combinatorics.tensor_can.get_symmetric_group_sgs Examples ======== Define a symmetric tensor of rank 2 >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> sym = TensorSymmetry(get_symmetric_group_sgs(2)) >>> T = TensorHead('T', [Lorentz]*2, sym) Note, that the same can also be done using built-in TensorSymmetry methods >>> sym2 = TensorSymmetry.fully_symmetric(2) >>> sym == sym2 True """ def __new__(cls, *args, **kw_args): if len(args) == 1: base, generators = args[0] elif len(args) == 2: base, generators = args else: raise TypeError("bsgs required, either two separate parameters or one tuple") if not isinstance(base, Tuple): base = Tuple(*base) if not isinstance(generators, Tuple): generators = Tuple(*generators) return Basic.__new__(cls, base, generators, **kw_args) @property def base(self): return self.args[0] @property def generators(self): return self.args[1] @property def rank(self): return self.generators[0].size - 2 @classmethod def fully_symmetric(cls, rank): """ Returns a fully symmetric (antisymmetric if ``rank``<0) TensorSymmetry object for ``abs(rank)`` indices. """ if rank > 0: bsgs = get_symmetric_group_sgs(rank, False) elif rank < 0: bsgs = get_symmetric_group_sgs(-rank, True) elif rank == 0: bsgs = ([], [Permutation(1)]) return TensorSymmetry(bsgs) @classmethod def direct_product(cls, *args): """ Returns a TensorSymmetry object that is being a direct product of fully (anti-)symmetric index permutation groups. Notes ===== Some examples for different values of ``(*args)``: ``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)`` ``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)`` ``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)`` ``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting ``(1, 1, 1)`` tensor with 3 indices without any symmetry """ base, sgs = [], [Permutation(1)] for arg in args: if arg > 0: bsgs2 = get_symmetric_group_sgs(arg, False) elif arg < 0: bsgs2 = get_symmetric_group_sgs(-arg, True) else: continue base, sgs = bsgs_direct_product(base, sgs, *bsgs2) return TensorSymmetry(base, sgs) @classmethod def riemann(cls): """ Returns a monotorem symmetry of the Riemann tensor """ return TensorSymmetry(riemann_bsgs) @classmethod def no_symmetry(cls, rank): """ TensorSymmetry object for ``rank`` indices with no symmetry """ return TensorSymmetry([], [Permutation(rank+1)]) @deprecated( """ The tensorsymmetry() function is deprecated. Use the TensorSymmetry constructor instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorsymmetry", ) def tensorsymmetry(*args): """ Returns a ``TensorSymmetry`` object. This method is deprecated, use ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead. Explanation =========== One can represent a tensor with any monoterm slot symmetry group using a BSGS. ``args`` can be a BSGS ``args[0]`` base ``args[1]`` sgs Usually tensors are in (direct products of) representations of the symmetric group; ``args`` can be a list of lists representing the shapes of Young tableaux Notes ===== For instance: ``[[1]]`` vector ``[[1]*n]`` symmetric tensor of rank ``n`` ``[[n]]`` antisymmetric tensor of rank ``n`` ``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor ``[[1],[1]]`` vector*vector ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector Notice that with the shape ``[2, 2]`` we associate only the monoterm symmetries of the Riemann tensor; this is an abuse of notation, since the shape ``[2, 2]`` corresponds usually to the irreducible representation characterized by the monoterm symmetries and by the cyclic symmetry. """ from sympy.combinatorics import Permutation def tableau2bsgs(a): if len(a) == 1: # antisymmetric vector n = a[0] bsgs = get_symmetric_group_sgs(n, 1) else: if all(x == 1 for x in a): # symmetric vector n = len(a) bsgs = get_symmetric_group_sgs(n) elif a == [2, 2]: bsgs = riemann_bsgs else: raise NotImplementedError return bsgs if not args: return TensorSymmetry(Tuple(), Tuple(Permutation(1))) if len(args) == 2 and isinstance(args[1][0], Permutation): return TensorSymmetry(args) base, sgs = tableau2bsgs(args[0]) for a in args[1:]: basex, sgsx = tableau2bsgs(a) base, sgs = bsgs_direct_product(base, sgs, basex, sgsx) return TensorSymmetry(Tuple(base, sgs)) @deprecated( "TensorType is deprecated. Use tensor_heads() instead.", deprecated_since_version="1.5", active_deprecations_target="deprecated-tensortype", ) class TensorType(Basic): """ Class of tensor types. Deprecated, use tensor_heads() instead. Parameters ========== index_types : list of ``TensorIndexType`` of the tensor indices symmetry : ``TensorSymmetry`` of the tensor Attributes ========== ``index_types`` ``symmetry`` ``types`` : list of ``TensorIndexType`` without repetitions """ is_commutative = False def __new__(cls, index_types, symmetry, **kw_args): assert symmetry.rank == len(index_types) obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args) return obj @property def index_types(self): return self.args[0] @property def symmetry(self): return self.args[1] @property def types(self): return sorted(set(self.index_types), key=lambda x: x.name) def __str__(self): return 'TensorType(%s)' % ([str(x) for x in self.index_types]) def __call__(self, s, comm=0): """ Return a TensorHead object or a list of TensorHead objects. Parameters ========== s : name or string of names. comm : Commutation group. see ``_TensorManager.set_comm`` """ if isinstance(s, str): names = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') if len(names) == 1: return TensorHead(names[0], self.index_types, self.symmetry, comm) else: return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names] @deprecated( """ The tensorhead() function is deprecated. Use tensor_heads() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorhead", ) def tensorhead(name, typ, sym=None, comm=0): """ Function generating tensorhead(s). This method is deprecated, use TensorHead constructor or tensor_heads() instead. Parameters ========== name : name or sequence of names (as in ``symbols``) typ : index types sym : same as ``*args`` in ``tensorsymmetry`` comm : commutation group number see ``_TensorManager.set_comm`` """ if sym is None: sym = [[1] for i in range(len(typ))] with ignore_warnings(SymPyDeprecationWarning): sym = tensorsymmetry(*sym) return TensorHead(name, typ, sym, comm) class TensorHead(Basic): """ Tensor head of the tensor. Parameters ========== name : name of the tensor index_types : list of TensorIndexType symmetry : TensorSymmetry of the tensor comm : commutation group number Attributes ========== ``name`` ``index_types`` ``rank`` : total number of indices ``symmetry`` ``comm`` : commutation group Notes ===== Similar to ``symbols`` multiple TensorHeads can be created using ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s`` is the string of names and ``sym`` is the monoterm tensor symmetry (see ``tensorsymmetry``). A ``TensorHead`` belongs to a commutation group, defined by a symbol on number ``comm`` (see ``_TensorManager.set_comm``); tensors in a commutation group have the same commutation properties; by default ``comm`` is ``0``, the group of the commuting tensors. Examples ======== Define a fully antisymmetric tensor of rank 2: >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> asym2 = TensorSymmetry.fully_symmetric(-2) >>> A = TensorHead('A', [Lorentz, Lorentz], asym2) Examples with ndarray values, the components data assigned to the ``TensorHead`` object are assumed to be in a fully-contravariant representation. In case it is necessary to assign components data which represents the values of a non-fully covariant tensor, see the other examples. >>> from sympy.tensor.tensor import tensor_indices >>> from sympy import diag >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i0, i1 = tensor_indices('i0:2', Lorentz) Specify a replacement dictionary to keep track of the arrays to use for replacements in the tensorial expression. The ``TensorIndexType`` is associated to the metric used for contractions (in fully covariant form): >>> repl = {Lorentz: diag(1, -1, -1, -1)} Let's see some examples of working with components with the electromagnetic tensor: >>> from sympy import symbols >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z') >>> c = symbols('c', positive=True) Let's define `F`, an antisymmetric tensor: >>> F = TensorHead('F', [Lorentz, Lorentz], asym2) Let's update the dictionary to contain the matrix to use in the replacements: >>> repl.update({F(-i0, -i1): [ ... [0, Ex/c, Ey/c, Ez/c], ... [-Ex/c, 0, -Bz, By], ... [-Ey/c, Bz, 0, -Bx], ... [-Ez/c, -By, Bx, 0]]}) Now it is possible to retrieve the contravariant form of the Electromagnetic tensor: >>> F(i0, i1).replace_with_arrays(repl, [i0, i1]) [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]] and the mixed contravariant-covariant form: >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1]) [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]] Energy-momentum of a particle may be represented as: >>> from sympy import symbols >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1)) >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True) >>> repl.update({P(i0): [E, px, py, pz]}) The contravariant and covariant components are, respectively: >>> P(i0).replace_with_arrays(repl, [i0]) [E, p_x, p_y, p_z] >>> P(-i0).replace_with_arrays(repl, [-i0]) [E, -p_x, -p_y, -p_z] The contraction of a 1-index tensor by itself: >>> expr = P(i0)*P(-i0) >>> expr.replace_with_arrays(repl, []) E**2 - p_x**2 - p_y**2 - p_z**2 """ is_commutative = False def __new__(cls, name, index_types, symmetry=None, comm=0): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name else: raise ValueError("invalid name") if symmetry is None: symmetry = TensorSymmetry.no_symmetry(len(index_types)) else: assert symmetry.rank == len(index_types) obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry) obj.comm = TensorManager.comm_symbols2i(comm) return obj @property def name(self): return self.args[0].name @property def index_types(self): return list(self.args[1]) @property def symmetry(self): return self.args[2] @property def rank(self): return len(self.index_types) def __lt__(self, other): return (self.name, self.index_types) < (other.name, other.index_types) def commutes_with(self, other): """ Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute. Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute. """ r = TensorManager.get_comm(self.comm, other.comm) return r def _print(self): return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types])) def __call__(self, *indices, **kw_args): """ Returns a tensor with indices. Explanation =========== There is a special behavior in case of indices denoted by ``True``, they are considered auto-matrix indices, their slots are automatically filled, and confer to the tensor the behavior of a matrix or vector upon multiplication with another tensor containing auto-matrix indices of the same ``TensorIndexType``. This means indices get summed over the same way as in matrix multiplication. For matrix behavior, define two auto-matrix indices, for vector behavior define just one. Indices can also be strings, in which case the attribute ``index_types`` is used to convert them to proper ``TensorIndex``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b = tensor_indices('a,b', Lorentz) >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) >>> t = A(a, -b) >>> t A(a, -b) """ updated_indices = [] for idx, typ in zip(indices, self.index_types): if isinstance(idx, str): idx = idx.strip().replace(" ", "") if idx.startswith('-'): updated_indices.append(TensorIndex(idx[1:], typ, is_up=False)) else: updated_indices.append(TensorIndex(idx, typ)) else: updated_indices.append(idx) updated_indices += indices[len(updated_indices):] tensor = Tensor(self, updated_indices, **kw_args) return tensor.doit() # Everything below this line is deprecated def __pow__(self, other): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No power on abstract tensors.") from .array import tensorproduct, tensorcontraction metrics = [_.data for _ in self.index_types] marray = self.data marraydim = marray.rank() for metric in metrics: marray = tensorproduct(marray, metric, marray) marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2)) return marray ** (other * S.Half) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() def _components_data_full_destroy(self): """ EXPERIMENTAL: do not rely on this API method. Destroy components data associated to the ``TensorHead`` object, this checks for attached components data, and destroys components data too. """ # do not garbage collect Kronecker tensor (it should be done by # ``TensorIndexType`` garbage collection) deprecate_data() if self.name == "KD": return # the data attached to a tensor must be deleted only by the TensorHead # destructor. If the TensorHead is deleted, it means that there are no # more instances of that tensor anywhere. if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def tensor_heads(s, index_types, symmetry=None, comm=0): """ Returns a sequence of TensorHeads from a string `s` """ if isinstance(s, str): names = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') thlist = [TensorHead(name, index_types, symmetry, comm) for name in names] if len(thlist) == 1: return thlist[0] return thlist class _TensorMetaclass(ManagedProperties, ABCMeta): pass class TensExpr(Expr, metaclass=_TensorMetaclass): """ Abstract base class for tensor expressions Notes ===== A tensor expression is an expression formed by tensors; currently the sums of tensors are distributed. A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``. ``TensMul`` objects are formed by products of component tensors, and include a coefficient, which is a SymPy expression. In the internal representation contracted indices are represented by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position of the component tensor with contravariant index, ``ipos1`` is the slot which the index occupies in that component tensor. Contracted indices are therefore nameless in the internal representation. """ _op_priority = 12.0 is_commutative = False def __neg__(self): return self*S.NegativeOne def __abs__(self): raise NotImplementedError def __add__(self, other): return TensAdd(self, other).doit() def __radd__(self, other): return TensAdd(other, self).doit() def __sub__(self, other): return TensAdd(self, -other).doit() def __rsub__(self, other): return TensAdd(other, -self).doit() def __mul__(self, other): """ Multiply two tensors using Einstein summation convention. Explanation =========== If the two tensors have an index in common, one contravariant and the other covariant, in their product the indices are summed Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t1 = p(m0) >>> t2 = q(-m0) >>> t1*t2 p(L_0)*q(-L_0) """ return TensMul(self, other).doit() def __rmul__(self, other): return TensMul(other, self).doit() def __truediv__(self, other): other = _sympify(other) if isinstance(other, TensExpr): raise ValueError('cannot divide by a tensor') return TensMul(self, S.One/other).doit() def __rtruediv__(self, other): raise ValueError('cannot divide by a tensor') def __pow__(self, other): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No power without ndarray data.") from .array import tensorproduct, tensorcontraction free = self.free marray = self.data mdim = marray.rank() for metric in free: marray = tensorcontraction( tensorproduct( marray, metric[0].tensor_index_type.data, marray), (0, mdim), (mdim+1, mdim+2) ) return marray ** (other * S.Half) def __rpow__(self, other): raise NotImplementedError @property @abstractmethod def nocoeff(self): raise NotImplementedError("abstract method") @property @abstractmethod def coeff(self): raise NotImplementedError("abstract method") @abstractmethod def get_indices(self): raise NotImplementedError("abstract method") @abstractmethod def get_free_indices(self): # type: () -> List[TensorIndex] raise NotImplementedError("abstract method") @abstractmethod def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr raise NotImplementedError("abstract method") def fun_eval(self, *index_tuples): deprecate_fun_eval() return self.substitute_indices(*index_tuples) def get_matrix(self): """ DEPRECATED: do not use. Returns ndarray components data as a matrix, if components data are available and ndarray dimension does not exceed 2. """ from sympy.matrices.dense import Matrix deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if 0 < self.rank <= 2: rows = self.data.shape[0] columns = self.data.shape[1] if self.rank == 2 else 1 if self.rank == 2: mat_list = [] * rows for i in range(rows): mat_list.append([]) for j in range(columns): mat_list[i].append(self[i, j]) else: mat_list = [None] * rows for i in range(rows): mat_list[i] = self[i] return Matrix(mat_list) else: raise NotImplementedError( "missing multidimensional reduction to matrix.") @staticmethod def _get_indices_permutation(indices1, indices2): return [indices1.index(i) for i in indices2] def expand(self, **hints): return _expand(self, **hints).doit() def _expand(self, **kwargs): return self def _get_free_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_free_indices_set()) return indset def _get_dummy_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_dummy_indices_set()) return indset def _get_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_indices_set()) return indset @property def _iterate_dummy_indices(self): dummy_set = self._get_dummy_indices_set() def recursor(expr, pos): if isinstance(expr, TensorIndex): if expr in dummy_set: yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @property def _iterate_free_indices(self): free_set = self._get_free_indices_set() def recursor(expr, pos): if isinstance(expr, TensorIndex): if expr in free_set: yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @property def _iterate_indices(self): def recursor(expr, pos): if isinstance(expr, TensorIndex): yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @staticmethod def _contract_and_permute_with_metric(metric, array, pos, dim): # TODO: add possibility of metric after (spinors) from .array import tensorcontraction, tensorproduct, permutedims array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos)) permu = list(range(dim)) permu[0], permu[pos] = permu[pos], permu[0] return permutedims(array, permu) @staticmethod def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict): from .array import permutedims index_types1 = [i.tensor_index_type for i in free_ind1] # Check if variance of indices needs to be fixed: pos2up = [] pos2down = [] free2remaining = free_ind2[:] for pos1, index1 in enumerate(free_ind1): if index1 in free2remaining: pos2 = free2remaining.index(index1) free2remaining[pos2] = None continue if -index1 in free2remaining: pos2 = free2remaining.index(-index1) free2remaining[pos2] = None free_ind2[pos2] = index1 if index1.is_up: pos2up.append(pos2) else: pos2down.append(pos2) else: index2 = free2remaining[pos1] if index2 is None: raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) free2remaining[pos1] = None free_ind2[pos1] = index1 if index1.is_up ^ index2.is_up: if index1.is_up: pos2up.append(pos1) else: pos2down.append(pos1) if len(set(free_ind1) & set(free_ind2)) < len(free_ind1): raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) # Raise indices: for pos in pos2up: index_type_pos = index_types1[pos] # type: TensorIndexType if index_type_pos not in replacement_dict: raise ValueError("No metric provided to lower index") metric = replacement_dict[index_type_pos] metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric) array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1)) # Lower indices: for pos in pos2down: index_type_pos = index_types1[pos] # type: TensorIndexType if index_type_pos not in replacement_dict: raise ValueError("No metric provided to lower index") metric = replacement_dict[index_type_pos] array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1)) if free_ind1: permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1) array = permutedims(array, permutation) if hasattr(array, "rank") and array.rank() == 0: array = array[()] return free_ind2, array def replace_with_arrays(self, replacement_dict, indices=None): """ Replace the tensorial expressions with arrays. The final array will correspond to the N-dimensional array with indices arranged according to ``indices``. Parameters ========== replacement_dict dictionary containing the replacement rules for tensors. indices the index order with respect to which the array is read. The original index order will be used if no value is passed. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices >>> from sympy.tensor.tensor import TensorHead >>> from sympy import symbols, diag >>> L = TensorIndexType("L") >>> i, j = tensor_indices("i j", L) >>> A = TensorHead("A", [L]) >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i]) [1, 2] Since 'indices' is optional, we can also call replace_with_arrays by this way if no specific index order is needed: >>> A(i).replace_with_arrays({A(i): [1, 2]}) [1, 2] >>> expr = A(i)*A(j) >>> expr.replace_with_arrays({A(i): [1, 2]}) [[1, 2], [2, 4]] For contractions, specify the metric of the ``TensorIndexType``, which in this case is ``L``, in its covariant form: >>> expr = A(i)*A(-i) >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)}) -3 Symmetrization of an array: >>> H = TensorHead("H", [L, L]) >>> a, b, c, d = symbols("a b c d") >>> expr = H(i, j)/2 + H(j, i)/2 >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]}) [[a, b/2 + c/2], [b/2 + c/2, d]] Anti-symmetrization of an array: >>> expr = H(i, j)/2 - H(j, i)/2 >>> repl = {H(i, j): [[a, b], [c, d]]} >>> expr.replace_with_arrays(repl) [[0, b/2 - c/2], [-b/2 + c/2, 0]] The same expression can be read as the transpose by inverting ``i`` and ``j``: >>> expr.replace_with_arrays(repl, [j, i]) [[0, -b/2 + c/2], [b/2 - c/2, 0]] """ from .array import Array indices = indices or [] remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()} for i, index in enumerate(indices): if isinstance(index, (Symbol, Mul)): if index in remap: indices[i] = remap[index] else: indices[i] = -remap[-index] replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()} # Check dimensions of replaced arrays: for tensor, array in replacement_dict.items(): if isinstance(tensor, TensorIndexType): expected_shape = [tensor.dim for i in range(2)] else: expected_shape = [index_type.dim for index_type in tensor.index_types] if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if dim1.is_number else True for dim1, dim2 in zip(expected_shape, array.shape))): raise ValueError("shapes for tensor %s expected to be %s, "\ "replacement array shape is %s" % (tensor, expected_shape, array.shape)) ret_indices, array = self._extract_data(replacement_dict) last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict) return array def _check_add_Sum(self, expr, index_symbols): from sympy.concrete.summations import Sum indices = self.get_indices() dum = self.dum sum_indices = [ (index_symbols[i], 0, indices[i].tensor_index_type.dim-1) for i, j in dum] if sum_indices: expr = Sum(expr, *sum_indices) return expr def _expand_partial_derivative(self): # simply delegate the _expand_partial_derivative() to # its arguments to expand a possibly found PartialDerivative return self.func(*[ a._expand_partial_derivative() if isinstance(a, TensExpr) else a for a in self.args]) class TensAdd(TensExpr, AssocOp): """ Sum of tensors. Parameters ========== free_args : list of the free indices Attributes ========== ``args`` : tuple of addends ``rank`` : rank of the tensor ``free_args`` : list of the free indices in sorted order Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b = tensor_indices('a,b', Lorentz) >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(a) + q(a); t p(a) + q(a) Examples with components data added to the tensor expression: >>> from sympy import symbols, diag >>> x, y, z, t = symbols("x y z t") >>> repl = {} >>> repl[Lorentz] = diag(1, -1, -1, -1) >>> repl[p(a)] = [1, 2, 3, 4] >>> repl[q(a)] = [x, y, z, t] The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58 >>> expr = p(a) + q(a) >>> expr.replace_with_arrays(repl, [a]) [x + 1, y + 2, z + 3, t + 4] """ def __new__(cls, *args, **kw_args): args = [_sympify(x) for x in args if x] args = TensAdd._tensAdd_flatten(args) args.sort(key=default_sort_key) if not args: return S.Zero if len(args) == 1: return args[0] return Basic.__new__(cls, *args, **kw_args) @property def coeff(self): return S.One @property def nocoeff(self): return self def get_free_indices(self): # type: () -> List[TensorIndex] return self.free_indices def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args] return self.func(*newargs) @memoize_property def rank(self): if isinstance(self.args[0], TensExpr): return self.args[0].rank else: return 0 @memoize_property def free_args(self): if isinstance(self.args[0], TensExpr): return self.args[0].free_args else: return [] @memoize_property def free_indices(self): if isinstance(self.args[0], TensExpr): return self.args[0].get_free_indices() else: return set() def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args if not args: return S.Zero if len(args) == 1 and not isinstance(args[0], TensExpr): return args[0] # now check that all addends have the same indices: TensAdd._tensAdd_check(args) # if TensAdd has only 1 element in its `args`: if len(args) == 1: # and isinstance(args[0], TensMul): return args[0] # Remove zeros: args = [x for x in args if x] # if there are no more args (i.e. have cancelled out), # just return zero: if not args: return S.Zero if len(args) == 1: return args[0] # Collect terms appearing more than once, differing by their coefficients: args = TensAdd._tensAdd_collect_terms(args) # collect canonicalized terms def sort_key(t): if not isinstance(t, TensExpr): return [], [], [] if hasattr(t, "_index_structure") and hasattr(t, "components"): x = get_index_structure(t) return t.components, x.free, x.dum return [], [], [] args.sort(key=sort_key) if not args: return S.Zero # it there is only a component tensor return it if len(args) == 1: return args[0] obj = self.func(*args) return obj @staticmethod def _tensAdd_flatten(args): # flatten TensAdd, coerce terms which are not tensors to tensors a = [] for x in args: if isinstance(x, (Add, TensAdd)): a.extend(list(x.args)) else: a.append(x) args = [x for x in a if x.coeff] return args @staticmethod def _tensAdd_check(args): # check that all addends have the same free indices def get_indices_set(x): # type: (Expr) -> tSet[TensorIndex] if isinstance(x, TensExpr): return set(x.get_free_indices()) return set() indices0 = get_indices_set(args[0]) # type: tSet[TensorIndex] list_indices = [get_indices_set(arg) for arg in args[1:]] # type: List[tSet[TensorIndex]] if not all(x == indices0 for x in list_indices): raise ValueError('all tensors must have the same indices') @staticmethod def _tensAdd_collect_terms(args): # collect TensMul terms differing at most by their coefficient terms_dict = defaultdict(list) scalars = S.Zero if isinstance(args[0], TensExpr): free_indices = set(args[0].get_free_indices()) else: free_indices = set() for arg in args: if not isinstance(arg, TensExpr): if free_indices != set(): raise ValueError("wrong valence") scalars += arg continue if free_indices != set(arg.get_free_indices()): raise ValueError("wrong valence") # TODO: what is the part which is not a coeff? # needs an implementation similar to .as_coeff_Mul() terms_dict[arg.nocoeff].append(arg.coeff) new_args = [TensMul(Add(*coeff), t).doit() for t, coeff in terms_dict.items() if Add(*coeff) != 0] if isinstance(scalars, Add): new_args = list(scalars.args) + new_args elif scalars != 0: new_args = [scalars] + new_args return new_args def get_indices(self): indices = [] for arg in self.args: indices.extend([i for i in get_indices(arg) if i not in indices]) return indices def _expand(self, **hints): return TensAdd(*[_expand(i, **hints) for i in self.args]) def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self index_tuples = list(zip(free_args, indices)) a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args] res = TensAdd(*a).doit() return res def canon_bp(self): """ Canonicalize using the Butler-Portugal algorithm for canonicalization under monoterm symmetries. """ expr = self.expand() args = [canon_bp(x) for x in expr.args] res = TensAdd(*args).doit() return res def equals(self, other): other = _sympify(other) if isinstance(other, TensMul) and other.coeff == 0: return all(x.coeff == 0 for x in self.args) if isinstance(other, TensExpr): if self.rank != other.rank: return False if isinstance(other, TensAdd): if set(self.args) != set(other.args): return False else: return True t = self - other if not isinstance(t, TensExpr): return t == 0 else: if isinstance(t, TensMul): return t.coeff == 0 else: return all(x.coeff == 0 for x in t.args) def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def contract_delta(self, delta): args = [x.contract_delta(delta) for x in self.args] t = TensAdd(*args).doit() return canon_bp(t) def contract_metric(self, g): """ Raise or lower indices with the metric ``g``. Parameters ========== g : metric contract_all : if True, eliminate all ``g`` which are contracted Notes ===== see the ``TensorIndexType`` docstring for the contraction conventions """ args = [contract_metric(x, g) for x in self.args] t = TensAdd(*args).doit() return canon_bp(t) def substitute_indices(self, *index_tuples): new_args = [] for arg in self.args: if isinstance(arg, TensExpr): arg = arg.substitute_indices(*index_tuples) new_args.append(arg) return TensAdd(*new_args).doit() def _print(self): a = [] args = self.args for x in args: a.append(str(x)) s = ' + '.join(a) s = s.replace('+ -', '- ') return s def _extract_data(self, replacement_dict): from sympy.tensor.array import Array, permutedims args_indices, arrays = zip(*[ arg._extract_data(replacement_dict) if isinstance(arg, TensExpr) else ([], arg) for arg in self.args ]) arrays = [Array(i) for i in arrays] ref_indices = args_indices[0] for i in range(1, len(args_indices)): indices = args_indices[i] array = arrays[i] permutation = TensMul._get_indices_permutation(indices, ref_indices) arrays[i] = permutedims(array, permutation) return ref_indices, sum(arrays, Array.zeros(*array.shape)) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self.expand()] @data.setter def data(self, data): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def __iter__(self): deprecate_data() if not self.data: raise ValueError("No iteration on abstract tensors") return self.data.flatten().__iter__() def _eval_rewrite_as_Indexed(self, *args): return Add.fromiter(args) def _eval_partial_derivative(self, s): # Evaluation like Add list_addends = [] for a in self.args: if isinstance(a, TensExpr): list_addends.append(a._eval_partial_derivative(s)) # do not call diff if s is no symbol elif s._diff_wrt: list_addends.append(a._eval_derivative(s)) return self.func(*list_addends) class Tensor(TensExpr): """ Base tensor class, i.e. this represents a tensor, the single unit to be put into an expression. Explanation =========== This object is usually created from a ``TensorHead``, by attaching indices to it. Indices preceded by a minus sign are considered contravariant, otherwise covariant. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L") >>> mu, nu = tensor_indices('mu nu', Lorentz) >>> A = TensorHead("A", [Lorentz, Lorentz]) >>> A(mu, -nu) A(mu, -nu) >>> A(mu, -mu) A(L_0, -L_0) It is also possible to use symbols instead of inidices (appropriate indices are then generated automatically). >>> from sympy import Symbol >>> x = Symbol('x') >>> A(x, mu) A(x, mu) >>> A(x, -x) A(L_0, -L_0) """ is_commutative = False _index_structure = None # type: _IndexStructure args: tTuple[TensorHead, Tuple] def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args): indices = cls._parse_indices(tensor_head, indices) obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args) obj._index_structure = _IndexStructure.from_indices(*indices) obj._free = obj._index_structure.free[:] obj._dum = obj._index_structure.dum[:] obj._ext_rank = obj._index_structure._ext_rank obj._coeff = S.One obj._nocoeff = obj obj._component = tensor_head obj._components = [tensor_head] if tensor_head.rank != len(indices): raise ValueError("wrong number of indices") obj.is_canon_bp = is_canon_bp obj._index_map = Tensor._build_index_map(indices, obj._index_structure) return obj @property def free(self): return self._free @property def dum(self): return self._dum @property def ext_rank(self): return self._ext_rank @property def coeff(self): return self._coeff @property def nocoeff(self): return self._nocoeff @property def component(self): return self._component @property def components(self): return self._components @property def head(self): return self.args[0] @property def indices(self): return self.args[1] @property def free_indices(self): return set(self._index_structure.get_free_indices()) @property def index_types(self): return self.head.index_types @property def rank(self): return len(self.free_indices) @staticmethod def _build_index_map(indices, index_structure): index_map = {} for idx in indices: index_map[idx] = (indices.index(idx),) return index_map def doit(self, **kwargs): args, indices, free, dum = TensMul._tensMul_contract_indices([self]) return args[0] @staticmethod def _parse_indices(tensor_head, indices): if not isinstance(indices, (tuple, list, Tuple)): raise TypeError("indices should be an array, got %s" % type(indices)) indices = list(indices) for i, index in enumerate(indices): if isinstance(index, Symbol): indices[i] = TensorIndex(index, tensor_head.index_types[i], True) elif isinstance(index, Mul): c, e = index.as_coeff_Mul() if c == -1 and isinstance(e, Symbol): indices[i] = TensorIndex(e, tensor_head.index_types[i], False) else: raise ValueError("index not understood: %s" % index) elif not isinstance(index, TensorIndex): raise TypeError("wrong type for index: %s is %s" % (index, type(index))) return indices def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit() def _get_free_indices_set(self): return {i[0] for i in self._index_structure.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self._index_structure.dum)) return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos} def _get_indices_set(self): return set(self.args[1].args) @property def free_in_args(self): return [(ind, pos, 0) for ind, pos in self.free] @property def dum_in_args(self): return [(p1, p2, 0, 0) for p1, p2 in self.dum] @property def free_args(self): return sorted([x[0] for x in self.free]) def commutes_with(self, other): """ :param other: :return: 0 commute 1 anticommute None neither commute nor anticommute """ if not isinstance(other, TensExpr): return 0 elif isinstance(other, Tensor): return self.component.commutes_with(other.component) return NotImplementedError def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g``. For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp) def canon_bp(self): if self.is_canon_bp: return self expr = self.expand() g, dummies, msym = expr._index_structure.indices_canon_args() v = components_canon_args([expr.component]) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tensor = self.perm2tensor(can, True) return tensor def split(self): return [self] def _expand(self, **kwargs): return self def sorted_components(self): return self def get_indices(self): # type: () -> List[TensorIndex] """ Get a list of indices, corresponding to those of the tensor. """ return list(self.args[1]) def get_free_indices(self): # type: () -> List[TensorIndex] """ Get a list of free indices, corresponding to those of the tensor. """ return self._index_structure.get_free_indices() def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> Tensor # TODO: this could be optimized by only swapping the indices # instead of visiting the whole expression tree: return self.xreplace(repl) def as_base_exp(self): return self, S.One def substitute_indices(self, *index_tuples): """ Return a tensor with free indices substituted according to ``index_tuples``. ``index_types`` list of tuples ``(old_index, new_index)``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(i, k)*B(-k, -j); t A(i, L_0)*B(-L_0, -j) >>> t.substitute_indices((i, k),(-j, l)) A(k, L_0)*B(-L_0, l) """ indices = [] for index in self.indices: for ind_old, ind_new in index_tuples: if (index.name == ind_old.name and index.tensor_index_type == ind_old.tensor_index_type): if index.is_up == ind_old.is_up: indices.append(ind_new) else: indices.append(-ind_new) break else: indices.append(index) return self.head(*indices) def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t # TODO: put this into TensExpr? def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() # TODO: put this into TensExpr? def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _extract_data(self, replacement_dict): from .array import Array for k, v in replacement_dict.items(): if isinstance(k, Tensor) and k.args[0] == self.args[0]: other = k array = v break else: raise ValueError("%s not found in %s" % (self, replacement_dict)) # TODO: inefficient, this should be done at root level only: replacement_dict = {k: Array(v) for k, v in replacement_dict.items()} array = Array(array) dum1 = self.dum dum2 = other.dum if len(dum2) > 0: for pair in dum2: # allow `dum2` if the contained values are also in `dum1`. if pair not in dum1: raise NotImplementedError("%s with contractions is not implemented" % other) # Remove elements in `dum2` from `dum1`: dum1 = [pair for pair in dum1 if pair not in dum2] if len(dum1) > 0: indices1 = self.get_indices() indices2 = other.get_indices() repl = {} for p1, p2 in dum1: repl[indices2[p2]] = -indices2[p1] for pos in (p1, p2): if indices1[pos].is_up ^ indices2[pos].is_up: metric = replacement_dict[indices1[pos].tensor_index_type] if indices1[pos].is_up: metric = _TensorDataLazyEvaluator.inverse_matrix(metric) array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2)) other = other.xreplace(repl).doit() array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2)) free_ind1 = self.get_free_indices() free_ind2 = other.get_free_indices() return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # TODO: check data compatibility with properties of tensor. with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] def _print(self): indices = [str(ind) for ind in self.indices] component = self.component if component.rank > 0: return ('%s(%s)' % (component.name, ', '.join(indices))) else: return ('%s' % component.name) def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return S.One == other def _get_compar_comp(self): t = self.canon_bp() r = (t.coeff, tuple(t.components), \ tuple(sorted(t.free)), tuple(sorted(t.dum))) return r return _get_compar_comp(self) == _get_compar_comp(other) def contract_metric(self, g): # if metric is not the same, ignore this step: if self.component != g: return self # in case there are free components, do not perform anything: if len(self.free) != 0: return self #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError sign = S.One typ = g.index_types[0] if not antisym: # g(i, -i) sign = sign*typ.dim else: # g(i, -i) sign = sign*typ.dim dp0, dp1 = self.dum[0] if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign return sign def contract_delta(self, metric): return self.contract_metric(metric) def _eval_rewrite_as_Indexed(self, tens, indices): from sympy.tensor.indexed import Indexed # TODO: replace .args[0] with .name: index_symbols = [i.args[0] for i in self.get_indices()] expr = Indexed(tens.args[0], *index_symbols) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s): # type: (Tensor) -> Expr if not isinstance(s, Tensor): return S.Zero else: # @a_i/@a_k = delta_i^k # @a_i/@a^k = g_ij delta^j_k # @a^i/@a^k = delta^i_k # @a^i/@a_k = g^ij delta_j^k # TODO: if there is no metric present, the derivative should be zero? if self.head != s.head: return S.Zero # if heads are the same, provide delta and/or metric products # for every free index pair in the appropriate tensor # assumed that the free indices are in proper order # A contravariante index in the derivative becomes covariant # after performing the derivative and vice versa kronecker_delta_list = [1] # not guarantee a correct index order for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())): if iself.tensor_index_type != iother.tensor_index_type: raise ValueError("index types not compatible") else: tensor_index_type = iself.tensor_index_type tensor_metric = tensor_index_type.metric dummy = TensorIndex("d_" + str(count), tensor_index_type, is_up=iself.is_up) if iself.is_up == iother.is_up: kroneckerdelta = tensor_index_type.delta(iself, -iother) else: kroneckerdelta = ( TensMul(tensor_metric(iself, dummy), tensor_index_type.delta(-dummy, -iother)) ) kronecker_delta_list.append(kroneckerdelta) return TensMul.fromiter(kronecker_delta_list).doit() # doit necessary to rename dummy indices accordingly class TensMul(TensExpr, AssocOp): """ Product of tensors. Parameters ========== coeff : SymPy coefficient of the tensor args Attributes ========== ``components`` : list of ``TensorHead`` of the component tensors ``types`` : list of nonrepeated ``TensorIndexType`` ``free`` : list of ``(ind, ipos, icomp)``, see Notes ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes ``ext_rank`` : rank of the tensor counting the dummy indices ``rank`` : rank of the tensor ``coeff`` : SymPy coefficient of the tensor ``free_args`` : list of the free indices in sorted order ``is_canon_bp`` : ``True`` if the tensor in in canonical form Notes ===== ``args[0]`` list of ``TensorHead`` of the component tensors. ``args[1]`` list of ``(ind, ipos, icomp)`` where ``ind`` is a free index, ``ipos`` is the slot position of ``ind`` in the ``icomp``-th component tensor. ``args[2]`` list of tuples representing dummy indices. ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant dummy index is the ``ipos1``-th slot position in the ``icomp1``-th component tensor; the corresponding covariant index is in the ``ipos2`` slot position in the ``icomp2``-th component tensor. """ identity = S.One _index_structure = None # type: _IndexStructure def __new__(cls, *args, **kw_args): is_canon_bp = kw_args.get('is_canon_bp', False) args = list(map(_sympify, args)) # Flatten: args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])] args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False) # Data for indices: index_types = [i.tensor_index_type for i in indices] index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) obj = TensExpr.__new__(cls, *args) obj._indices = indices obj._index_types = index_types[:] obj._index_structure = index_structure obj._free = index_structure.free[:] obj._dum = index_structure.dum[:] obj._free_indices = {x[0] for x in obj.free} obj._rank = len(obj.free) obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) obj._coeff = S.One obj._is_canon_bp = is_canon_bp return obj index_types = property(lambda self: self._index_types) free = property(lambda self: self._free) dum = property(lambda self: self._dum) free_indices = property(lambda self: self._free_indices) rank = property(lambda self: self._rank) ext_rank = property(lambda self: self._ext_rank) @staticmethod def _indices_to_free_dum(args_indices): free2pos1 = {} free2pos2 = {} dummy_data = [] indices = [] # Notation for positions (to better understand the code): # `pos1`: position in the `args`. # `pos2`: position in the indices. # Example: # A(i, j)*B(k, m, n)*C(p) # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul). # `pos2` of `n` is 4 because it's the fifth overall index. # Counter for the index position wrt the whole expression: pos2 = 0 for pos1, arg_indices in enumerate(args_indices): for index_pos, index in enumerate(arg_indices): if not isinstance(index, TensorIndex): raise TypeError("expected TensorIndex") if -index in free2pos1: # Dummy index detected: other_pos1 = free2pos1.pop(-index) other_pos2 = free2pos2.pop(-index) if index.is_up: dummy_data.append((index, pos1, other_pos1, pos2, other_pos2)) else: dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2)) indices.append(index) elif index in free2pos1: raise ValueError("Repeated index: %s" % index) else: free2pos1[index] = pos1 free2pos2[index] = pos2 indices.append(index) pos2 += 1 free = [(i, p) for (i, p) in free2pos2.items()] free_names = [i.name for i in free2pos2.keys()] dummy_data.sort(key=lambda x: x[3]) return indices, free, free_names, dummy_data @staticmethod def _dummy_data_to_dum(dummy_data): return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data] @staticmethod def _tensMul_contract_indices(args, replace_indices=True): replacements = [{} for _ in args] #_index_order = all(_has_index_order(arg) for arg in args) args_indices = [get_indices(arg) for arg in args] indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) cdt = defaultdict(int) def dummy_name_gen(tensor_index_type): nd = str(cdt[tensor_index_type]) cdt[tensor_index_type] += 1 return tensor_index_type.dummy_name + '_' + nd if replace_indices: for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data: index_type = old_index.tensor_index_type while True: dummy_name = dummy_name_gen(index_type) if dummy_name not in free_names: break dummy = TensorIndex(dummy_name, index_type, True) replacements[pos1cov][old_index] = dummy replacements[pos1contra][-old_index] = -dummy indices[pos2cov] = dummy indices[pos2contra] = -dummy args = [ arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg, repl in zip(args, replacements)] dum = TensMul._dummy_data_to_dum(dummy_data) return args, indices, free, dum @staticmethod def _get_components_from_args(args): """ Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied by one another. """ components = [] for arg in args: if not isinstance(arg, TensExpr): continue if isinstance(arg, TensAdd): continue components.extend(arg.components) return components @staticmethod def _rebuild_tensors_list(args, index_structure): indices = index_structure.get_indices() #tensors = [None for i in components] # pre-allocate list ind_pos = 0 for i, arg in enumerate(args): if not isinstance(arg, TensExpr): continue prev_pos = ind_pos ind_pos += arg.ext_rank args[i] = Tensor(arg.component, indices[prev_pos:ind_pos]) def doit(self, **kwargs): is_canon_bp = self._is_canon_bp deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args args = [arg for arg in args if arg != self.identity] # Extract non-tensor coefficients: coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One) args = [arg for arg in args if isinstance(arg, TensExpr)] if len(args) == 0: return coeff if coeff != self.identity: args = [coeff] + args if coeff == 0: return S.Zero if len(args) == 1: return args[0] args, indices, free, dum = TensMul._tensMul_contract_indices(args) # Data for indices: index_types = [i.tensor_index_type for i in indices] index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) obj = self.func(*args) obj._index_types = index_types obj._index_structure = index_structure obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) obj._coeff = coeff obj._is_canon_bp = is_canon_bp return obj # TODO: this method should be private # TODO: should this method be renamed _from_components_free_dum ? @staticmethod def from_data(coeff, components, free, dum, **kw_args): return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit() @staticmethod def _get_tensors_from_components_free_dum(components, free, dum): """ Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``. """ index_structure = _IndexStructure.from_components_free_dum(components, free, dum) indices = index_structure.get_indices() tensors = [None for i in components] # pre-allocate list # distribute indices on components to build a list of tensors: ind_pos = 0 for i, component in enumerate(components): prev_pos = ind_pos ind_pos += component.rank tensors[i] = Tensor(component, indices[prev_pos:ind_pos]) return tensors def _get_free_indices_set(self): return {i[0] for i in self.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self.dum)) return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos} def _get_position_offset_for_indices(self): arg_offset = [None for i in range(self.ext_rank)] counter = 0 for i, arg in enumerate(self.args): if not isinstance(arg, TensExpr): continue for j in range(arg.ext_rank): arg_offset[j + counter] = counter counter += arg.ext_rank return arg_offset @property def free_args(self): return sorted([x[0] for x in self.free]) @property def components(self): return self._get_components_from_args(self.args) @property def free_in_args(self): arg_offset = self._get_position_offset_for_indices() argpos = self._get_indices_to_args_pos() return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free] @property def coeff(self): # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)]) return self._coeff @property def nocoeff(self): return self.func(*[t for t in self.args if isinstance(t, TensExpr)]).doit() @property def dum_in_args(self): arg_offset = self._get_position_offset_for_indices() argpos = self._get_indices_to_args_pos() return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum] def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return self.coeff == other return self.canon_bp() == other.canon_bp() def get_indices(self): """ Returns the list of indices of the tensor. Explanation =========== The indices are listed in the order in which they appear in the component tensors. The dummy indices are given a name which does not collide with the names of the free indices. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m1)*g(m0,m2) >>> t.get_indices() [m1, m0, m2] >>> t2 = p(m1)*g(-m1, m2) >>> t2.get_indices() [L_0, -L_0, m2] """ return self._indices def get_free_indices(self): # type: () -> List[TensorIndex] """ Returns the list of free indices of the tensor. Explanation =========== The indices are listed in the order in which they appear in the component tensors. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m1)*g(m0,m2) >>> t.get_free_indices() [m1, m0, m2] >>> t2 = p(m1)*g(-m1, m2) >>> t2.get_free_indices() [m2] """ return self._index_structure.get_free_indices() def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]) def split(self): """ Returns a list of tensors, whose product is ``self``. Explanation =========== Dummy indices contracted among different tensor components become free indices with the same name as the one used to represent the dummy indices. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(a,b)*B(-b,c) >>> t A(a, L_0)*B(-L_0, c) >>> t.split() [A(a, L_0), B(-L_0, c)] """ if self.args == (): return [self] splitp = [] res = 1 for arg in self.args: if isinstance(arg, Tensor): splitp.append(res*arg) res = 1 else: res *= arg return splitp def _expand(self, **hints): # TODO: temporary solution, in the future this should be linked to # `Expr.expand`. args = [_expand(arg, **hints) for arg in self.args] args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in args] return TensAdd(*[ TensMul(*i) for i in itertools.product(*args1)] ) def __neg__(self): return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit() def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _get_args_for_traditional_printer(self): args = list(self.args) if (self.coeff < 0) == True: # expressions like "-A(a)" sign = "-" if self.coeff == S.NegativeOne: args = args[1:] else: args[0] = -args[0] else: sign = "" return sign, args def _sort_args_for_sorted_components(self): """ Returns the ``args`` sorted according to the components commutation properties. Explanation =========== The sorting is done taking into account the commutation group of the component tensors. """ cv = [arg for arg in self.args if isinstance(arg, TensExpr)] sign = 1 n = len(cv) - 1 for i in range(n): for j in range(n, i, -1): c = cv[j-1].commutes_with(cv[j]) # if `c` is `None`, it does neither commute nor anticommute, skip: if c not in (0, 1): continue typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name) typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name) if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name): cv[j-1], cv[j] = cv[j], cv[j-1] # if `c` is 1, the anticommute, so change sign: if c: sign = -sign coeff = sign * self.coeff if coeff != 1: return [coeff] + cv return cv def sorted_components(self): """ Returns a tensor product with sorted components. """ return TensMul(*self._sort_args_for_sorted_components()).doit() def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g`` For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp=is_canon_bp) def canon_bp(self): """ Canonicalize using the Butler-Portugal algorithm for canonicalization under monoterm symmetries. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) >>> t = A(m0,-m1)*A(m1,-m0) >>> t.canon_bp() -A(L_0, L_1)*A(-L_0, -L_1) >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0) >>> t.canon_bp() 0 """ if self._is_canon_bp: return self expr = self.expand() if isinstance(expr, TensAdd): return expr.canon_bp() if not expr.components: return expr t = expr.sorted_components() g, dummies, msym = t._index_structure.indices_canon_args() v = components_canon_args(t.components) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tmul = t.perm2tensor(can, True) return tmul def contract_delta(self, delta): t = self.contract_metric(delta) return t def _get_indices_to_args_pos(self): """ Get a dict mapping the index position to TensMul's argument number. """ pos_map = dict() pos_counter = 0 for arg_i, arg in enumerate(self.args): if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) for i in range(arg.ext_rank): pos_map[pos_counter] = arg_i pos_counter += 1 return pos_map def contract_metric(self, g): """ Raise or lower indices with the metric ``g``. Parameters ========== g : metric Notes ===== See the ``TensorIndexType`` docstring for the contraction conventions. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m0)*q(m1)*g(-m0, -m1) >>> t.canon_bp() metric(L_0, L_1)*p(-L_0)*q(-L_1) >>> t.contract_metric(g).canon_bp() p(L_0)*q(-L_0) """ expr = self.expand() if self != expr: expr = expr.canon_bp() return expr.contract_metric(g) pos_map = self._get_indices_to_args_pos() args = list(self.args) #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError # list of positions of the metric ``g`` inside ``args`` gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g] if not gpos: return self # Sign is either 1 or -1, to correct the sign after metric contraction # (for spinor indices). sign = 1 dum = self.dum[:] free = self.free[:] elim = set() for gposx in gpos: if gposx in elim: continue free1 = [x for x in free if pos_map[x[1]] == gposx] dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx] if not dum1: continue elim.add(gposx) # subs with the multiplication neutral element, that is, remove it: args[gposx] = 1 if len(dum1) == 2: if not antisym: dum10, dum11 = dum1 if pos_map[dum10[1]] == gposx: # the index with pos p0 contravariant p0 = dum10[0] else: # the index with pos p0 is covariant p0 = dum10[1] if pos_map[dum11[1]] == gposx: # the index with pos p1 is contravariant p1 = dum11[0] else: # the index with pos p1 is covariant p1 = dum11[1] dum.append((p0, p1)) else: dum10, dum11 = dum1 # change the sign to bring the indices of the metric to contravariant # form; change the sign if dum10 has the metric index in position 0 if pos_map[dum10[1]] == gposx: # the index with pos p0 is contravariant p0 = dum10[0] if dum10[1] == 1: sign = -sign else: # the index with pos p0 is covariant p0 = dum10[1] if dum10[0] == 0: sign = -sign if pos_map[dum11[1]] == gposx: # the index with pos p1 is contravariant p1 = dum11[0] sign = -sign else: # the index with pos p1 is covariant p1 = dum11[1] dum.append((p0, p1)) elif len(dum1) == 1: if not antisym: dp0, dp1 = dum1[0] if pos_map[dp0] == pos_map[dp1]: # g(i, -i) typ = g.index_types[0] sign = sign*typ.dim else: # g(i0, i1)*p(-i1) if pos_map[dp0] == gposx: p1 = dp1 else: p1 = dp0 ind, p = free1[0] free.append((ind, p1)) else: dp0, dp1 = dum1[0] if pos_map[dp0] == pos_map[dp1]: # g(i, -i) typ = g.index_types[0] sign = sign*typ.dim if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign else: # g(i0, i1)*p(-i1) if pos_map[dp0] == gposx: p1 = dp1 if dp0 == 0: sign = -sign else: p1 = dp0 ind, p = free1[0] free.append((ind, p1)) dum = [x for x in dum if x not in dum1] free = [x for x in free if x not in free1] # shift positions: shift = 0 shifts = [0]*len(args) for i in range(len(args)): if i in elim: shift += 2 continue shifts[i] = shift free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim] dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for i, (p0, p1) in enumerate(dum) if pos_map[p0] not in elim and pos_map[p1] not in elim] res = sign*TensMul(*args).doit() if not isinstance(res, TensExpr): return res im = _IndexStructure.from_components_free_dum(res.components, free, dum) return res._set_new_index_structure(im) def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") args = list(self.args)[:] pos = 0 for i, arg in enumerate(args): if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) ext_rank = arg.ext_rank args[i] = arg._set_indices(*indices[pos:pos+ext_rank]) pos += ext_rank return TensMul(*args, is_canon_bp=is_canon_bp).doit() @staticmethod def _index_replacement_for_contract_metric(args, free, dum): for arg in args: if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) def substitute_indices(self, *index_tuples): new_args = [] for arg in self.args: if isinstance(arg, TensExpr): arg = arg.substitute_indices(*index_tuples) new_args.append(arg) return TensMul(*new_args).doit() def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t def _extract_data(self, replacement_dict): args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)]) coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One) indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) dum = TensMul._dummy_data_to_dum(dummy_data) ext_rank = self.ext_rank free.sort(key=lambda x: x[1]) free_indices = [i[0] for i in free] return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): dat = _tensor_data_substitution_dict[self.expand()] return dat @data.setter def data(self, data): deprecate_data() raise ValueError("Not possible to set component data to a tensor expression") @data.deleter def data(self): deprecate_data() raise ValueError("Not possible to delete component data to a tensor expression") def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No iteration on abstract tensors") return self.data.__iter__() def _eval_rewrite_as_Indexed(self, *args): from sympy.concrete.summations import Sum index_symbols = [i.args[0] for i in self.get_indices()] args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args] expr = Mul.fromiter(args) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s): # Evaluation like Mul terms = [] for i, arg in enumerate(self.args): # checking whether some tensor instance is differentiated # or some other thing is necessary, but ugly if isinstance(arg, TensExpr): d = arg._eval_partial_derivative(s) else: # do not call diff is s is no symbol if s._diff_wrt: d = arg._eval_derivative(s) else: d = S.Zero if d: terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:])) return TensAdd.fromiter(terms) class TensorElement(TensExpr): """ Tensor with evaluated components. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry >>> from sympy import symbols >>> L = TensorIndexType("L") >>> i, j, k = symbols("i j k") >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2)) >>> A(i, j).get_free_indices() [i, j] If we want to set component ``i`` to a specific value, use the ``TensorElement`` class: >>> from sympy.tensor.tensor import TensorElement >>> te = TensorElement(A(i, j), {i: 2}) As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd element), the free indices will only contain ``j``: >>> te.get_free_indices() [j] """ def __new__(cls, expr, index_map): if not isinstance(expr, Tensor): # remap if not isinstance(expr, TensExpr): raise TypeError("%s is not a tensor expression" % expr) return expr.func(*[TensorElement(arg, index_map) for arg in expr.args]) expr_free_indices = expr.get_free_indices() name_translation = {i.args[0]: i for i in expr_free_indices} index_map = {name_translation.get(index, index): value for index, value in index_map.items()} index_map = {index: value for index, value in index_map.items() if index in expr_free_indices} if len(index_map) == 0: return expr free_indices = [i for i in expr_free_indices if i not in index_map.keys()] index_map = Dict(index_map) obj = TensExpr.__new__(cls, expr, index_map) obj._free_indices = free_indices return obj @property def free(self): return [(index, i) for i, index in enumerate(self.get_free_indices())] @property def dum(self): # TODO: inherit dummies from expr return [] @property def expr(self): return self._args[0] @property def index_map(self): return self._args[1] @property def coeff(self): return S.One @property def nocoeff(self): return self def get_free_indices(self): return self._free_indices def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr # TODO: can be improved: return self.xreplace(repl) def get_indices(self): return self.get_free_indices() def _extract_data(self, replacement_dict): ret_indices, array = self.expr._extract_data(replacement_dict) index_map = self.index_map slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices) ret_indices = [i for i in ret_indices if i not in index_map] array = array.__getitem__(slice_tuple) return ret_indices, array def canon_bp(p): """ Butler-Portugal canonicalization. See ``tensor_can.py`` from the combinatorics module for the details. """ if isinstance(p, TensExpr): return p.canon_bp() return p def tensor_mul(*a): """ product of tensors """ if not a: return TensMul.from_data(S.One, [], [], []) t = a[0] for tx in a[1:]: t = t*tx return t def riemann_cyclic_replace(t_r): """ replace Riemann tensor with an equivalent expression ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)`` """ free = sorted(t_r.free, key=lambda x: x[1]) m, n, p, q = [x[0] for x in free] t0 = t_r*Rational(2, 3) t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3) t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3) t3 = t0 + t1 + t2 return t3 def riemann_cyclic(t2): """ Replace each Riemann tensor with an equivalent expression satisfying the cyclic identity. This trick is discussed in the reference guide to Cadabra. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l)) >>> riemann_cyclic(t) 0 """ t2 = t2.expand() if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3).doit() if not t3: return t3 else: return canon_bp(t3) def get_lines(ex, index_type): """ Returns ``(lines, traces, rest)`` for an index type, where ``lines`` is the list of list of positions of a matrix line, ``traces`` is the list of list of traced matrix lines, ``rest`` is the rest of the elements ot the tensor. """ def _join_lines(a): i = 0 while i < len(a): x = a[i] xend = x[-1] xstart = x[0] hit = True while hit: hit = False for j in range(i + 1, len(a)): if j >= len(a): break if a[j][0] == xend: hit = True x.extend(a[j][1:]) xend = x[-1] a.pop(j) continue if a[j][0] == xstart: hit = True a[i] = reversed(a[j][1:]) + x x = a[i] xstart = a[i][0] a.pop(j) continue if a[j][-1] == xend: hit = True x.extend(reversed(a[j][:-1])) xend = x[-1] a.pop(j) continue if a[j][-1] == xstart: hit = True a[i] = a[j][:-1] + x x = a[i] xstart = x[0] a.pop(j) continue i += 1 return a arguments = ex.args dt = {} for c in ex.args: if not isinstance(c, TensExpr): continue if c in dt: continue index_types = c.index_types a = [] for i in range(len(index_types)): if index_types[i] is index_type: a.append(i) if len(a) > 2: raise ValueError('at most two indices of type %s allowed' % index_type) if len(a) == 2: dt[c] = a #dum = ex.dum lines = [] traces = [] traces1 = [] #indices_to_args_pos = ex._get_indices_to_args_pos() # TODO: add a dum_to_components_map ? for p0, p1, c0, c1 in ex.dum_in_args: if arguments[c0] not in dt: continue if c0 == c1: traces.append([c0]) continue ta0 = dt[arguments[c0]] ta1 = dt[arguments[c1]] if p0 not in ta0: continue if ta0.index(p0) == ta1.index(p1): # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1; # to deal with this case one could add to the position # a flag for transposition; # one could write [(c0, False), (c1, True)] raise NotImplementedError # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1 # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0 ta0 = dt[arguments[c0]] b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0) lines1 = lines[:] for line in lines: if line[-1] == b0: if line[0] == b1: n = line.index(min(line)) traces1.append(line) traces.append(line[n:] + line[:n]) else: line.append(b1) break elif line[0] == b1: line.insert(0, b0) break else: lines1.append([b0, b1]) lines = [x for x in lines1 if x not in traces1] lines = _join_lines(lines) rest = [] for line in lines: for y in line: rest.append(y) for line in traces: for y in line: rest.append(y) rest = [x for x in range(len(arguments)) if x not in rest] return lines, traces, rest def get_free_indices(t): if not isinstance(t, TensExpr): return () return t.get_free_indices() def get_indices(t): if not isinstance(t, TensExpr): return () return t.get_indices() def get_index_structure(t): if isinstance(t, TensExpr): return t._index_structure return _IndexStructure([], [], [], []) def get_coeff(t): if isinstance(t, Tensor): return S.One if isinstance(t, TensMul): return t.coeff if isinstance(t, TensExpr): raise ValueError("no coefficient associated to this tensor expression") return t def contract_metric(t, g): if isinstance(t, TensExpr): return t.contract_metric(g) return t def perm2tensor(t, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g`` For further details, see the method in ``TIDS`` with the same name. """ if not isinstance(t, TensExpr): return t elif isinstance(t, (Tensor, TensMul)): nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp) res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp) if g[-1] != len(g) - 1: return -res return res raise NotImplementedError() def substitute_indices(t, *index_tuples): if not isinstance(t, TensExpr): return t return t.substitute_indices(*index_tuples) def _expand(expr, **kwargs): if isinstance(expr, TensExpr): return expr._expand(**kwargs) else: return expr.expand(**kwargs)
d8f7a1e32dab16df646ca5828c6fedc3f32092fb05771d14dbdbe28fe79e4f2e
r"""Module that defines indexed objects The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a matrix element ``M[i, j]`` as in the following diagram:: 1) The Indexed class represents the entire indexed object. | ___|___ ' ' M[i, j] / \__\______ | | | | | 2) The Idx class represents indices; each Idx can | optionally contain information about its range. | 3) IndexedBase represents the 'stem' of an indexed object, here `M`. The stem used by itself is usually taken to represent the entire array. There can be any number of indices on an Indexed object. No transformation properties are implemented in these Base objects, but implicit contraction of repeated indices is supported. Note that the support for complicated (i.e. non-atomic) integer expressions as indices is limited. (This should be improved in future releases.) Examples ======== To express the above matrix element example you would write: >>> from sympy import symbols, IndexedBase, Idx >>> M = IndexedBase('M') >>> i, j = symbols('i j', cls=Idx) >>> M[i, j] M[i, j] Repeated indices in a product implies a summation, so to express a matrix-vector product in terms of Indexed objects: >>> x = IndexedBase('x') >>> M[i, j]*x[j] M[i, j]*x[j] If the indexed objects will be converted to component based arrays, e.g. with the code printers or the autowrap framework, you also need to provide (symbolic or numerical) dimensions. This can be done by passing an optional shape parameter to IndexedBase upon construction: >>> dim1, dim2 = symbols('dim1 dim2', integer=True) >>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2)) >>> A.shape (dim1, 2*dim1, dim2) >>> A[i, j, 3].shape (dim1, 2*dim1, dim2) If an IndexedBase object has no shape information, it is assumed that the array is as large as the ranges of its indices: >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> M[i, j].shape (m, n) >>> M[i, j].ranges [(0, m - 1), (0, n - 1)] The above can be compared with the following: >>> A[i, 2, j].shape (dim1, 2*dim1, dim2) >>> A[i, 2, j].ranges [(0, m - 1), None, (0, n - 1)] To analyze the structure of indexed expressions, you can use the methods get_indices() and get_contraction_structure(): >>> from sympy.tensor import get_indices, get_contraction_structure >>> get_indices(A[i, j, j]) ({i}, {}) >>> get_contraction_structure(A[i, j, j]) {(j,): {A[i, j, j]}} See the appropriate docstrings for a detailed explanation of the output. """ # TODO: (some ideas for improvement) # # o test and guarantee numpy compatibility # - implement full support for broadcasting # - strided arrays # # o more functions to analyze indexed expressions # - identify standard constructs, e.g matrix-vector product in a subexpression # # o functions to generate component based arrays (numpy and sympy.Matrix) # - generate a single array directly from Indexed # - convert simple sub-expressions # # o sophisticated indexing (possibly in subclasses to preserve simplicity) # - Idx with range smaller than dimension of Indexed # - Idx with stepsize != 1 # - Idx with step determined by function call from collections.abc import Iterable from sympy.core.numbers import Number from sympy.core.assumptions import StdFactKB from sympy.core import Expr, Tuple, sympify, S from sympy.core.symbol import _filter_assumptions, Symbol from sympy.core.logic import fuzzy_bool, fuzzy_not from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.multipledispatch import dispatch from sympy.utilities.iterables import is_sequence, NotIterable from sympy.utilities.misc import filldedent class IndexException(Exception): pass class Indexed(Expr): """Represents a mathematical object with indices. >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j) A[i, j] It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``: ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``. >>> A = IndexedBase('A') >>> a_ij = A[i, j] # Prefer this, >>> b_ij = Indexed(A, i, j) # over this. >>> a_ij == b_ij True """ is_commutative = True is_Indexed = True is_symbol = True is_Atom = True def __new__(cls, base, *args, **kw_args): from sympy.tensor.array.ndim_array import NDimArray from sympy.matrices.matrices import MatrixBase if not args: raise IndexException("Indexed needs at least one index.") if isinstance(base, (str, Symbol)): base = IndexedBase(base) elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase): raise TypeError(filldedent(""" The base can only be replaced with a string, Symbol, IndexedBase or an object with a method for getting items (i.e. an object with a `__getitem__` method). """)) args = list(map(sympify, args)) if isinstance(base, (NDimArray, Iterable, Tuple, MatrixBase)) and all(i.is_number for i in args): if len(args) == 1: return base[args[0]] else: return base[args] base = _sympify(base) obj = Expr.__new__(cls, base, *args, **kw_args) try: IndexedBase._set_assumptions(obj, base.assumptions0) except AttributeError: IndexedBase._set_assumptions(obj, {}) return obj def _hashable_content(self): return super()._hashable_content() + tuple(sorted(self.assumptions0.items())) @property def name(self): return str(self) @property def _diff_wrt(self): """Allow derivatives with respect to an ``Indexed`` object.""" return True def _eval_derivative(self, wrt): from sympy.tensor.array.ndim_array import NDimArray if isinstance(wrt, Indexed) and wrt.base == self.base: if len(self.indices) != len(wrt.indices): msg = "Different # of indices: d({!s})/d({!s})".format(self, wrt) raise IndexException(msg) result = S.One for index1, index2 in zip(self.indices, wrt.indices): result *= KroneckerDelta(index1, index2) return result elif isinstance(self.base, NDimArray): from sympy.tensor.array import derive_by_array return Indexed(derive_by_array(self.base, wrt), *self.args[1:]) else: if Tuple(self.indices).has(wrt): return S.NaN return S.Zero @property def assumptions0(self): return {k: v for k, v in self._assumptions.items() if v is not None} @property def base(self): """Returns the ``IndexedBase`` of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).base A >>> B = IndexedBase('B') >>> B == B[i, j].base True """ return self.args[0] @property def indices(self): """ Returns the indices of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).indices (i, j) """ return self.args[1:] @property def rank(self): """ Returns the rank of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j, k, l, m = symbols('i:m', cls=Idx) >>> Indexed('A', i, j).rank 2 >>> q = Indexed('A', i, j, k, l, m) >>> q.rank 5 >>> q.rank == len(q.indices) True """ return len(self.args) - 1 @property def shape(self): """Returns a list with dimensions of each index. Dimensions is a property of the array, not of the indices. Still, if the ``IndexedBase`` does not define a shape attribute, it is assumed that the ranges of the indices correspond to the shape of the array. >>> from sympy import IndexedBase, Idx, symbols >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', m) >>> A = IndexedBase('A', shape=(n, n)) >>> B = IndexedBase('B') >>> A[i, j].shape (n, n) >>> B[i, j].shape (m, m) """ if self.base.shape: return self.base.shape sizes = [] for i in self.indices: upper = getattr(i, 'upper', None) lower = getattr(i, 'lower', None) if None in (upper, lower): raise IndexException(filldedent(""" Range is not defined for all indices in: %s""" % self)) try: size = upper - lower + 1 except TypeError: raise IndexException(filldedent(""" Shape cannot be inferred from Idx with undefined range: %s""" % self)) sizes.append(size) return Tuple(*sizes) @property def ranges(self): """Returns a list of tuples with lower and upper range of each index. If an index does not define the data members upper and lower, the corresponding slot in the list contains ``None`` instead of a tuple. Examples ======== >>> from sympy import Indexed,Idx, symbols >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges [(0, 1), (0, 3), (0, 7)] >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges [(0, 2), (0, 2), (0, 2)] >>> x, y, z = symbols('x y z', integer=True) >>> Indexed('A', x, y, z).ranges [None, None, None] """ ranges = [] sentinel = object() for i in self.indices: upper = getattr(i, 'upper', sentinel) lower = getattr(i, 'lower', sentinel) if sentinel not in (upper, lower): ranges.append((lower, upper)) else: ranges.append(None) return ranges def _sympystr(self, p): indices = list(map(p.doprint, self.indices)) return "%s[%s]" % (p.doprint(self.base), ", ".join(indices)) @property def free_symbols(self): base_free_symbols = self.base.free_symbols indices_free_symbols = { fs for i in self.indices for fs in i.free_symbols} if base_free_symbols: return {self} | base_free_symbols | indices_free_symbols else: return indices_free_symbols @property def expr_free_symbols(self): from sympy.utilities.exceptions import sympy_deprecation_warning sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return {self} class IndexedBase(Expr, NotIterable): """Represent the base or stem of an indexed object The IndexedBase class represent an array that contains elements. The main purpose of this class is to allow the convenient creation of objects of the Indexed class. The __getitem__ method of IndexedBase returns an instance of Indexed. Alone, without indices, the IndexedBase class can be used as a notation for e.g. matrix equations, resembling what you could do with the Symbol class. But, the IndexedBase class adds functionality that is not available for Symbol instances: - An IndexedBase object can optionally store shape information. This can be used in to check array conformance and conditions for numpy broadcasting. (TODO) - An IndexedBase object implements syntactic sugar that allows easy symbolic representation of array operations, using implicit summation of repeated indices. - The IndexedBase object symbolizes a mathematical structure equivalent to arrays, and is recognized as such for code generation and automatic compilation and wrapping. >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> A = IndexedBase('A'); A A >>> type(A) <class 'sympy.tensor.indexed.IndexedBase'> When an IndexedBase object receives indices, it returns an array with named axes, represented by an Indexed object: >>> i, j = symbols('i j', integer=True) >>> A[i, j, 2] A[i, j, 2] >>> type(A[i, j, 2]) <class 'sympy.tensor.indexed.Indexed'> The IndexedBase constructor takes an optional shape argument. If given, it overrides any shape information in the indices. (But not the index ranges!) >>> m, n, o, p = symbols('m n o p', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> A[i, j].shape (m, n) >>> B = IndexedBase('B', shape=(o, p)) >>> B[i, j].shape (o, p) Assumptions can be specified with keyword arguments the same way as for Symbol: >>> A_real = IndexedBase('A', real=True) >>> A_real.is_real True >>> A != A_real True Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase: >>> I = symbols('I', integer=True) >>> C_inherit = IndexedBase(I) >>> C_explicit = IndexedBase('I', integer=True) >>> C_inherit == C_explicit True """ is_commutative = True is_symbol = True is_Atom = True @staticmethod def _set_assumptions(obj, assumptions): """Set assumptions on obj, making sure to apply consistent values.""" tmp_asm_copy = assumptions.copy() is_commutative = fuzzy_bool(assumptions.get('commutative', True)) assumptions['commutative'] = is_commutative obj._assumptions = StdFactKB(assumptions) obj._assumptions._generator = tmp_asm_copy # Issue #8873 def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array.ndim_array import NDimArray assumptions, kw_args = _filter_assumptions(kw_args) if isinstance(label, str): label = Symbol(label, **assumptions) elif isinstance(label, Symbol): assumptions = label._merge(assumptions) elif isinstance(label, (MatrixBase, NDimArray)): return label elif isinstance(label, Iterable): return _sympify(label) else: label = _sympify(label) if is_sequence(shape): shape = Tuple(*shape) elif shape is not None: shape = Tuple(shape) if shape is not None: obj = Expr.__new__(cls, label, shape) else: obj = Expr.__new__(cls, label) obj._shape = shape obj._offset = offset obj._strides = strides obj._name = str(label) IndexedBase._set_assumptions(obj, assumptions) return obj @property def name(self): return self._name def _hashable_content(self): return super()._hashable_content() + tuple(sorted(self.assumptions0.items())) @property def assumptions0(self): return {k: v for k, v in self._assumptions.items() if v is not None} def __getitem__(self, indices, **kw_args): if is_sequence(indices): # Special case needed because M[*my_tuple] is a syntax error. if self.shape and len(self.shape) != len(indices): raise IndexException("Rank mismatch.") return Indexed(self, *indices, **kw_args) else: if self.shape and len(self.shape) != 1: raise IndexException("Rank mismatch.") return Indexed(self, indices, **kw_args) @property def shape(self): """Returns the shape of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase, Idx >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).shape (x, y) Note: If the shape of the ``IndexedBase`` is specified, it will override any shape information given by the indices. >>> A = IndexedBase('A', shape=(x, y)) >>> B = IndexedBase('B') >>> i = Idx('i', 2) >>> j = Idx('j', 1) >>> A[i, j].shape (x, y) >>> B[i, j].shape (2, 1) """ return self._shape @property def strides(self): """Returns the strided scheme for the ``IndexedBase`` object. Normally this is a tuple denoting the number of steps to take in the respective dimension when traversing an array. For code generation purposes strides='C' and strides='F' can also be used. strides='C' would mean that code printer would unroll in row-major order and 'F' means unroll in column major order. """ return self._strides @property def offset(self): """Returns the offset for the ``IndexedBase`` object. This is the value added to the resulting index when the 2D Indexed object is unrolled to a 1D form. Used in code generation. Examples ========== >>> from sympy.printing import ccode >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> l, m, n, o = symbols('l m n o', integer=True) >>> A = IndexedBase('A', strides=(l, m, n), offset=o) >>> i, j, k = map(Idx, 'ijk') >>> ccode(A[i, j, k]) 'A[l*i + m*j + n*k + o]' """ return self._offset @property def label(self): """Returns the label of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).label A """ return self.args[0] def _sympystr(self, p): return p.doprint(self.label) class Idx(Expr): """Represents an integer index as an ``Integer`` or integer expression. There are a number of ways to create an ``Idx`` object. The constructor takes two arguments: ``label`` An integer or a symbol that labels the index. ``range`` Optionally you can specify a range as either * ``Symbol`` or integer: This is interpreted as a dimension. Lower and upper bounds are set to ``0`` and ``range - 1``, respectively. * ``tuple``: The two elements are interpreted as the lower and upper bounds of the range, respectively. Note: bounds of the range are assumed to be either integer or infinite (oo and -oo are allowed to specify an unbounded range). If ``n`` is given as a bound, then ``n.is_integer`` must not return false. For convenience, if the label is given as a string it is automatically converted to an integer symbol. (Note: this conversion is not done for range or dimension arguments.) Examples ======== >>> from sympy import Idx, symbols, oo >>> n, i, L, U = symbols('n i L U', integer=True) If a string is given for the label an integer ``Symbol`` is created and the bounds are both ``None``: >>> idx = Idx('qwerty'); idx qwerty >>> idx.lower, idx.upper (None, None) Both upper and lower bounds can be specified: >>> idx = Idx(i, (L, U)); idx i >>> idx.lower, idx.upper (L, U) When only a single bound is given it is interpreted as the dimension and the lower bound defaults to 0: >>> idx = Idx(i, n); idx.lower, idx.upper (0, n - 1) >>> idx = Idx(i, 4); idx.lower, idx.upper (0, 3) >>> idx = Idx(i, oo); idx.lower, idx.upper (0, oo) """ is_integer = True is_finite = True is_real = True is_symbol = True is_Atom = True _diff_wrt = True def __new__(cls, label, range=None, **kw_args): if isinstance(label, str): label = Symbol(label, integer=True) label, range = list(map(sympify, (label, range))) if label.is_Number: if not label.is_integer: raise TypeError("Index is not an integer number.") return label if not label.is_integer: raise TypeError("Idx object requires an integer label.") elif is_sequence(range): if len(range) != 2: raise ValueError(filldedent(""" Idx range tuple must have length 2, but got %s""" % len(range))) for bound in range: if (bound.is_integer is False and bound is not S.Infinity and bound is not S.NegativeInfinity): raise TypeError("Idx object requires integer bounds.") args = label, Tuple(*range) elif isinstance(range, Expr): if range is not S.Infinity and fuzzy_not(range.is_integer): raise TypeError("Idx object requires an integer dimension.") args = label, Tuple(0, range - 1) elif range: raise TypeError(filldedent(""" The range must be an ordered iterable or integer SymPy expression.""")) else: args = label, obj = Expr.__new__(cls, *args, **kw_args) obj._assumptions["finite"] = True obj._assumptions["real"] = True return obj @property def label(self): """Returns the label (Integer or integer expression) of the Idx object. Examples ======== >>> from sympy import Idx, Symbol >>> x = Symbol('x', integer=True) >>> Idx(x).label x >>> j = Symbol('j', integer=True) >>> Idx(j).label j >>> Idx(j + 1).label j + 1 """ return self.args[0] @property def lower(self): """Returns the lower bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).lower 0 >>> Idx('j', 5).lower 0 >>> Idx('j').lower is None True """ try: return self.args[1][0] except IndexError: return @property def upper(self): """Returns the upper bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).upper 1 >>> Idx('j', 5).upper 4 >>> Idx('j').upper is None True """ try: return self.args[1][1] except IndexError: return def _sympystr(self, p): return p.doprint(self.label) @property def name(self): return self.label.name if self.label.is_Symbol else str(self.label) @property def free_symbols(self): return {self} @dispatch(Idx, Idx) def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = rhs if rhs.upper is None else rhs.upper other_lower = rhs if rhs.lower is None else rhs.lower if lhs.lower is not None and (lhs.lower >= other_upper) == True: return True if lhs.upper is not None and (lhs.upper < other_lower) == True: return False return None @dispatch(Idx, Number) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = rhs other_lower = rhs if lhs.lower is not None and (lhs.lower >= other_upper) == True: return True if lhs.upper is not None and (lhs.upper < other_lower) == True: return False return None @dispatch(Number, Idx) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = lhs other_lower = lhs if rhs.upper is not None and (rhs.upper <= other_lower) == True: return True if rhs.lower is not None and (rhs.lower > other_upper) == True: return False return None
98d29dc87be3e62f646025bfe17a2a9642c69a1b4e0fdc9020edf080b6b82653
""" Boolean algebra module for SymPy """ from collections import defaultdict from itertools import chain, combinations, product, permutations from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.cache import cacheit from sympy.core.containers import Tuple from sympy.core.decorators import sympify_method_args, sympify_return from sympy.core.function import Application, Derivative from sympy.core.kind import BooleanKind, NumberKind from sympy.core.numbers import Number from sympy.core.operations import LatticeOp from sympy.core.singleton import Singleton, S from sympy.core.sorting import ordered from sympy.core.sympify import _sympy_converter, _sympify, sympify from sympy.utilities.iterables import sift, ibin from sympy.utilities.misc import filldedent def as_Boolean(e): """Like ``bool``, return the Boolean value of an expression, e, which can be any instance of :py:class:`~.Boolean` or ``bool``. Examples ======== >>> from sympy import true, false, nan >>> from sympy.logic.boolalg import as_Boolean >>> from sympy.abc import x >>> as_Boolean(0) is false True >>> as_Boolean(1) is true True >>> as_Boolean(x) x >>> as_Boolean(2) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `2`. >>> as_Boolean(nan) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `nan`. """ from sympy.core.symbol import Symbol if e == True: return S.true if e == False: return S.false if isinstance(e, Symbol): z = e.is_zero if z is None: return e return S.false if z else S.true if isinstance(e, Boolean): return e raise TypeError('expecting bool or Boolean, not `%s`.' % e) @sympify_method_args class Boolean(Basic): """A Boolean object is an object for which logic operations make sense.""" __slots__ = () kind = BooleanKind @sympify_return([('other', 'Boolean')], NotImplemented) def __and__(self, other): return And(self, other) __rand__ = __and__ @sympify_return([('other', 'Boolean')], NotImplemented) def __or__(self, other): return Or(self, other) __ror__ = __or__ def __invert__(self): """Overloading for ~""" return Not(self) @sympify_return([('other', 'Boolean')], NotImplemented) def __rshift__(self, other): return Implies(self, other) @sympify_return([('other', 'Boolean')], NotImplemented) def __lshift__(self, other): return Implies(other, self) __rrshift__ = __lshift__ __rlshift__ = __rshift__ @sympify_return([('other', 'Boolean')], NotImplemented) def __xor__(self, other): return Xor(self, other) __rxor__ = __xor__ def equals(self, other): """ Returns ``True`` if the given formulas have the same truth table. For two formulas to be equal they must have the same literals. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy import And, Or, Not >>> (A >> B).equals(~B >> ~A) True >>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C))) False >>> Not(And(A, Not(A))).equals(Or(B, Not(B))) False """ from sympy.logic.inference import satisfiable from sympy.core.relational import Relational if self.has(Relational) or other.has(Relational): raise NotImplementedError('handling of relationals') return self.atoms() == other.atoms() and \ not satisfiable(Not(Equivalent(self, other))) def to_nnf(self, simplify=True): # override where necessary return self def as_set(self): """ Rewrites Boolean expression in terms of real sets. Examples ======== >>> from sympy import Symbol, Eq, Or, And >>> x = Symbol('x', real=True) >>> Eq(x, 0).as_set() {0} >>> (x > 0).as_set() Interval.open(0, oo) >>> And(-2 < x, x < 2).as_set() Interval.open(-2, 2) >>> Or(x < -2, 2 < x).as_set() Union(Interval.open(-oo, -2), Interval.open(2, oo)) """ from sympy.calculus.util import periodicity from sympy.core.relational import Relational free = self.free_symbols if len(free) == 1: x = free.pop() if x.kind is NumberKind: reps = {} for r in self.atoms(Relational): if periodicity(r, x) not in (0, None): s = r._eval_as_set() if s in (S.EmptySet, S.UniversalSet, S.Reals): reps[r] = s.as_relational(x) continue raise NotImplementedError(filldedent(''' as_set is not implemented for relationals with periodic solutions ''')) new = self.subs(reps) if new.func != self.func: return new.as_set() # restart with new obj else: return new._eval_as_set() return self._eval_as_set() else: raise NotImplementedError("Sorry, as_set has not yet been" " implemented for multivariate" " expressions") @property def binary_symbols(self): from sympy.core.relational import Eq, Ne return set().union(*[i.binary_symbols for i in self.args if i.is_Boolean or i.is_Symbol or isinstance(i, (Eq, Ne))]) def _eval_refine(self, assumptions): from sympy.assumptions import ask ret = ask(self, assumptions) if ret is True: return true elif ret is False: return false return None class BooleanAtom(Boolean): """ Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`. """ is_Boolean = True is_Atom = True _op_priority = 11 # higher than Expr def simplify(self, *a, **kw): return self def expand(self, *a, **kw): return self @property def canonical(self): return self def _noop(self, other=None): raise TypeError('BooleanAtom not allowed in this context.') __add__ = _noop __radd__ = _noop __sub__ = _noop __rsub__ = _noop __mul__ = _noop __rmul__ = _noop __pow__ = _noop __rpow__ = _noop __truediv__ = _noop __rtruediv__ = _noop __mod__ = _noop __rmod__ = _noop _eval_power = _noop # /// drop when Py2 is no longer supported def __lt__(self, other): raise TypeError(filldedent(''' A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. ''')) __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ # \\\ def _eval_simplify(self, **kwargs): return self class BooleanTrue(BooleanAtom, metaclass=Singleton): """ SymPy version of ``True``, a singleton that can be accessed via ``S.true``. This is the SymPy version of ``True``, for use in the logic module. The primary advantage of using ``true`` instead of ``True`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with True they act bitwise on 1. Functions in the logic module will return this class when they evaluate to true. Notes ===== There is liable to be some confusion as to when ``True`` should be used and when ``S.true`` should be used in various contexts throughout SymPy. An important thing to remember is that ``sympify(True)`` returns ``S.true``. This means that for the most part, you can just use ``True`` and it will automatically be converted to ``S.true`` when necessary, similar to how you can generally use 1 instead of ``S.One``. The rule of thumb is: "If the boolean in question can be replaced by an arbitrary symbolic ``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``. Otherwise, use ``True``" In other words, use ``S.true`` only on those contexts where the boolean is being used as a symbolic representation of truth. For example, if the object ends up in the ``.args`` of any expression, then it must necessarily be ``S.true`` instead of ``True``, as elements of ``.args`` must be ``Basic``. On the other hand, ``==`` is not a symbolic operation in SymPy, since it always returns ``True`` or ``False``, and does so in terms of structural equality rather than mathematical, so it should return ``True``. The assumptions system should use ``True`` and ``False``. Aside from not satisfying the above rule of thumb, the assumptions system uses a three-valued logic (``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false`` represent a two-valued logic. When in doubt, use ``True``. "``S.true == True is True``." While "``S.true is True``" is ``False``, "``S.true == True``" is ``True``, so if there is any doubt over whether a function or expression will return ``S.true`` or ``True``, just use ``==`` instead of ``is`` to do the comparison, and it will work in either case. Finally, for boolean flags, it's better to just use ``if x`` instead of ``if x is True``. To quote PEP 8: Do not compare boolean values to ``True`` or ``False`` using ``==``. * Yes: ``if greeting:`` * No: ``if greeting == True:`` * Worse: ``if greeting is True:`` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(True) True >>> _ is True, _ is true (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True (False, -2) >>> true >> true, True >> True (True, 0) Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True (False, -2) >>> true >> true, True >> True (True, 0) See Also ======== sympy.logic.boolalg.BooleanFalse """ def __bool__(self): return True def __hash__(self): return hash(True) def __eq__(self, other): if other is True: return True if other is False: return False return super().__eq__(other) @property def negated(self): return S.false def as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import true >>> true.as_set() UniversalSet """ return S.UniversalSet class BooleanFalse(BooleanAtom, metaclass=Singleton): """ SymPy version of ``False``, a singleton that can be accessed via ``S.false``. This is the SymPy version of ``False``, for use in the logic module. The primary advantage of using ``false`` instead of ``False`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with ``False`` they act bitwise on 0. Functions in the logic module will return this class when they evaluate to false. Notes ====== See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(False) False >>> _ is False, _ is false (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for false but a bitwise result for False >>> ~false, ~False (True, -1) >>> false >> false, False >> False (True, 0) See Also ======== sympy.logic.boolalg.BooleanTrue """ def __bool__(self): return False def __hash__(self): return hash(False) def __eq__(self, other): if other is True: return False if other is False: return True return super().__eq__(other) @property def negated(self): return S.true def as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import false >>> false.as_set() EmptySet """ return S.EmptySet true = BooleanTrue() false = BooleanFalse() # We want S.true and S.false to work, rather than S.BooleanTrue and # S.BooleanFalse, but making the class and instance names the same causes some # major issues (like the inability to import the class directly from this # file). S.true = true S.false = false _sympy_converter[bool] = lambda x: S.true if x else S.false class BooleanFunction(Application, Boolean): """Boolean function is a function that lives in a boolean space It is used as base class for :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Not`, etc. """ is_Boolean = True def _eval_simplify(self, **kwargs): rv = simplify_univariate(self) if not isinstance(rv, BooleanFunction): return rv.simplify(**kwargs) rv = rv.func(*[a.simplify(**kwargs) for a in rv.args]) return simplify_logic(rv) def simplify(self, **kwargs): from sympy.simplify.simplify import simplify return simplify(self, **kwargs) def __lt__(self, other): raise TypeError(filldedent(''' A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. ''')) __le__ = __lt__ __ge__ = __lt__ __gt__ = __lt__ @classmethod def binary_check_and_simplify(self, *args): from sympy.core.relational import Relational, Eq, Ne args = [as_Boolean(i) for i in args] bin_syms = set().union(*[i.binary_symbols for i in args]) rel = set().union(*[i.atoms(Relational) for i in args]) reps = {} for x in bin_syms: for r in rel: if x in bin_syms and x in r.free_symbols: if isinstance(r, (Eq, Ne)): if not ( S.true in r.args or S.false in r.args): reps[r] = S.false else: raise TypeError(filldedent(''' Incompatible use of binary symbol `%s` as a real variable in `%s` ''' % (x, r))) return [i.subs(reps) for i in args] def to_nnf(self, simplify=True): return self._to_nnf(*self.args, simplify=simplify) def to_anf(self, deep=True): return self._to_anf(*self.args, deep=deep) @classmethod def _to_nnf(cls, *args, **kwargs): simplify = kwargs.get('simplify', True) argset = set() for arg in args: if not is_literal(arg): arg = arg.to_nnf(simplify) if simplify: if isinstance(arg, cls): arg = arg.args else: arg = (arg,) for a in arg: if Not(a) in argset: return cls.zero argset.add(a) else: argset.add(arg) return cls(*argset) @classmethod def _to_anf(cls, *args, **kwargs): deep = kwargs.get('deep', True) argset = set() for arg in args: if deep: if not is_literal(arg) or isinstance(arg, Not): arg = arg.to_anf(deep=deep) argset.add(arg) else: argset.add(arg) return cls(*argset, remove_true=False) # the diff method below is copied from Expr class def diff(self, *symbols, **assumptions): assumptions.setdefault("evaluate", True) return Derivative(self, *symbols, **assumptions) def _eval_derivative(self, x): if x in self.binary_symbols: from sympy.core.relational import Eq from sympy.functions.elementary.piecewise import Piecewise return Piecewise( (0, Eq(self.subs(x, 0), self.subs(x, 1))), (1, True)) elif x in self.free_symbols: # not implemented, see https://www.encyclopediaofmath.org/ # index.php/Boolean_differential_calculus pass else: return S.Zero class And(LatticeOp, BooleanFunction): """ Logical AND function. It evaluates its arguments in order, returning false immediately when an argument is false and true if they are all true. Examples ======== >>> from sympy.abc import x, y >>> from sympy import And >>> x & y x & y Notes ===== The ``&`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise and. Hence, ``And(a, b)`` and ``a & b`` will produce different results if ``a`` and ``b`` are integers. >>> And(x, y).subs(x, 1) y """ zero = false identity = true nargs = None @classmethod def _new_args_filter(cls, args): args = BooleanFunction.binary_check_and_simplify(*args) args = LatticeOp._new_args_filter(args, And) newargs = [] rel = set() for x in ordered(args): if x.is_Relational: c = x.canonical if c in rel: continue elif c.negated.canonical in rel: return [S.false] else: rel.add(c) newargs.append(x) return newargs def _eval_subs(self, old, new): args = [] bad = None for i in self.args: try: i = i.subs(old, new) except TypeError: # store TypeError if bad is None: bad = i continue if i == False: return S.false elif i != True: args.append(i) if bad is not None: # let it raise bad.subs(old, new) # If old is And, replace the parts of the arguments with new if all # are there if isinstance(old, And): old_set = set(old.args) if old_set.issubset(args): args = set(args) - old_set args.add(new) return self.func(*args) def _eval_simplify(self, **kwargs): from sympy.core.relational import Equality, Relational from sympy.solvers.solveset import linear_coeffs # standard simplify rv = super()._eval_simplify(**kwargs) if not isinstance(rv, And): return rv # simplify args that are equalities involving # symbols so x == 0 & x == y -> x==0 & y == 0 Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational), binary=True) if not Rel: return rv eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True) measure = kwargs['measure'] if eqs: ratio = kwargs['ratio'] reps = {} sifted = {} # group by length of free symbols sifted = sift(ordered([ (i.free_symbols, i) for i in eqs]), lambda x: len(x[0])) eqs = [] nonlineqs = [] while 1 in sifted: for free, e in sifted.pop(1): x = free.pop() if (e.lhs != x or x in e.rhs.free_symbols) and x not in reps: try: m, b = linear_coeffs( e.rewrite(Add, evaluate=False), x) enew = e.func(x, -b/m) if measure(enew) <= ratio*measure(e): e = enew else: eqs.append(e) continue except ValueError: pass if x in reps: eqs.append(e.subs(x, reps[x])) elif e.lhs == x and x not in e.rhs.free_symbols: reps[x] = e.rhs eqs.append(e) else: # x is not yet identified, but may be later nonlineqs.append(e) resifted = defaultdict(list) for k in sifted: for f, e in sifted[k]: e = e.xreplace(reps) f = e.free_symbols resifted[len(f)].append((f, e)) sifted = resifted for k in sifted: eqs.extend([e for f, e in sifted[k]]) nonlineqs = [ei.subs(reps) for ei in nonlineqs] other = [ei.subs(reps) for ei in other] rv = rv.func(*([i.canonical for i in (eqs + nonlineqs + other)] + nonRel)) patterns = _simplify_patterns_and() threeterm_patterns = _simplify_patterns_and3() return _apply_patternbased_simplification(rv, patterns, measure, S.false, threeterm_patterns=threeterm_patterns) def _eval_as_set(self): from sympy.sets.sets import Intersection return Intersection(*[arg.as_set() for arg in self.args]) def _eval_rewrite_as_Nor(self, *args, **kwargs): return Nor(*[Not(arg) for arg in self.args]) def to_anf(self, deep=True): if deep: result = And._to_anf(*self.args, deep=deep) return distribute_xor_over_and(result) return self class Or(LatticeOp, BooleanFunction): """ Logical OR function It evaluates its arguments in order, returning true immediately when an argument is true, and false if they are all false. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Or >>> x | y x | y Notes ===== The ``|`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if ``a`` and ``b`` are integers. >>> Or(x, y).subs(x, 0) y """ zero = true identity = false @classmethod def _new_args_filter(cls, args): newargs = [] rel = [] args = BooleanFunction.binary_check_and_simplify(*args) for x in args: if x.is_Relational: c = x.canonical if c in rel: continue nc = c.negated.canonical if any(r == nc for r in rel): return [S.true] rel.append(c) newargs.append(x) return LatticeOp._new_args_filter(newargs, Or) def _eval_subs(self, old, new): args = [] bad = None for i in self.args: try: i = i.subs(old, new) except TypeError: # store TypeError if bad is None: bad = i continue if i == True: return S.true elif i != False: args.append(i) if bad is not None: # let it raise bad.subs(old, new) # If old is Or, replace the parts of the arguments with new if all # are there if isinstance(old, Or): old_set = set(old.args) if old_set.issubset(args): args = set(args) - old_set args.add(new) return self.func(*args) def _eval_as_set(self): from sympy.sets.sets import Union return Union(*[arg.as_set() for arg in self.args]) def _eval_rewrite_as_Nand(self, *args, **kwargs): return Nand(*[Not(arg) for arg in self.args]) def _eval_simplify(self, **kwargs): from sympy.core.relational import Le, Ge, Eq lege = self.atoms(Le, Ge) if lege: reps = {i: self.func( Eq(i.lhs, i.rhs), i.strict) for i in lege} return self.xreplace(reps)._eval_simplify(**kwargs) # standard simplify rv = super()._eval_simplify(**kwargs) if not isinstance(rv, Or): return rv patterns = _simplify_patterns_or() return _apply_patternbased_simplification(rv, patterns, kwargs['measure'], S.true) def to_anf(self, deep=True): args = range(1, len(self.args) + 1) args = (combinations(self.args, j) for j in args) args = chain.from_iterable(args) # powerset args = (And(*arg) for arg in args) args = map(lambda x: to_anf(x, deep=deep) if deep else x, args) return Xor(*list(args), remove_true=False) class Not(BooleanFunction): """ Logical Not function (negation) Returns ``true`` if the statement is ``false`` or ``False``. Returns ``false`` if the statement is ``true`` or ``True``. Examples ======== >>> from sympy import Not, And, Or >>> from sympy.abc import x, A, B >>> Not(True) False >>> Not(False) True >>> Not(And(True, False)) True >>> Not(Or(True, False)) False >>> Not(And(And(True, x), Or(x, False))) ~x >>> ~x ~x >>> Not(And(Or(A, B), Or(~A, ~B))) ~((A | B) & (~A | ~B)) Notes ===== - The ``~`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is an integer. Furthermore, since bools in Python subclass from ``int``, ``~True`` is the same as ``~1`` which is ``-2``, which has a boolean value of True. To avoid this issue, use the SymPy boolean types ``true`` and ``false``. >>> from sympy import true >>> ~True -2 >>> ~true False """ is_Not = True @classmethod def eval(cls, arg): if isinstance(arg, Number) or arg in (True, False): return false if arg else true if arg.is_Not: return arg.args[0] # Simplify Relational objects. if arg.is_Relational: return arg.negated def _eval_as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import Not, Symbol >>> x = Symbol('x') >>> Not(x > 0).as_set() Interval(-oo, 0) """ return self.args[0].as_set().complement(S.Reals) def to_nnf(self, simplify=True): if is_literal(self): return self expr = self.args[0] func, args = expr.func, expr.args if func == And: return Or._to_nnf(*[Not(arg) for arg in args], simplify=simplify) if func == Or: return And._to_nnf(*[Not(arg) for arg in args], simplify=simplify) if func == Implies: a, b = args return And._to_nnf(a, Not(b), simplify=simplify) if func == Equivalent: return And._to_nnf(Or(*args), Or(*[Not(arg) for arg in args]), simplify=simplify) if func == Xor: result = [] for i in range(1, len(args)+1, 2): for neg in combinations(args, i): clause = [Not(s) if s in neg else s for s in args] result.append(Or(*clause)) return And._to_nnf(*result, simplify=simplify) if func == ITE: a, b, c = args return And._to_nnf(Or(a, Not(c)), Or(Not(a), Not(b)), simplify=simplify) raise ValueError("Illegal operator %s in expression" % func) def to_anf(self, deep=True): return Xor._to_anf(true, self.args[0], deep=deep) class Xor(BooleanFunction): """ Logical XOR (exclusive OR) function. Returns True if an odd number of the arguments are True and the rest are False. Returns False if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xor(True, False) True >>> Xor(True, True) False >>> Xor(True, False, True, True, False) True >>> Xor(True, False, True, False) False >>> x ^ y x ^ y Notes ===== The ``^`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise xor. In particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and ``b`` are integers. >>> Xor(x, y).subs(y, 0) x """ def __new__(cls, *args, remove_true=True, **kwargs): argset = set() obj = super().__new__(cls, *args, **kwargs) for arg in obj._args: if isinstance(arg, Number) or arg in (True, False): if arg: arg = true else: continue if isinstance(arg, Xor): for a in arg.args: argset.remove(a) if a in argset else argset.add(a) elif arg in argset: argset.remove(arg) else: argset.add(arg) rel = [(r, r.canonical, r.negated.canonical) for r in argset if r.is_Relational] odd = False # is number of complimentary pairs odd? start 0 -> False remove = [] for i, (r, c, nc) in enumerate(rel): for j in range(i + 1, len(rel)): rj, cj = rel[j][:2] if cj == nc: odd = ~odd break elif cj == c: break else: continue remove.append((r, rj)) if odd: argset.remove(true) if true in argset else argset.add(true) for a, b in remove: argset.remove(a) argset.remove(b) if len(argset) == 0: return false elif len(argset) == 1: return argset.pop() elif True in argset and remove_true: argset.remove(True) return Not(Xor(*argset)) else: obj._args = tuple(ordered(argset)) obj._argset = frozenset(argset) return obj # XXX: This should be cached on the object rather than using cacheit # Maybe it can be computed in __new__? @property # type: ignore @cacheit def args(self): return tuple(ordered(self._argset)) def to_nnf(self, simplify=True): args = [] for i in range(0, len(self.args)+1, 2): for neg in combinations(self.args, i): clause = [Not(s) if s in neg else s for s in self.args] args.append(Or(*clause)) return And._to_nnf(*args, simplify=simplify) def _eval_rewrite_as_Or(self, *args, **kwargs): a = self.args return Or(*[_convert_to_varsSOP(x, self.args) for x in _get_odd_parity_terms(len(a))]) def _eval_rewrite_as_And(self, *args, **kwargs): a = self.args return And(*[_convert_to_varsPOS(x, self.args) for x in _get_even_parity_terms(len(a))]) def _eval_simplify(self, **kwargs): # as standard simplify uses simplify_logic which writes things as # And and Or, we only simplify the partial expressions before using # patterns rv = self.func(*[a.simplify(**kwargs) for a in self.args]) if not isinstance(rv, Xor): # This shouldn't really happen here return rv patterns = _simplify_patterns_xor() return _apply_patternbased_simplification(rv, patterns, kwargs['measure'], None) def _eval_subs(self, old, new): # If old is Xor, replace the parts of the arguments with new if all # are there if isinstance(old, Xor): old_set = set(old.args) if old_set.issubset(self.args): args = set(self.args) - old_set args.add(new) return self.func(*args) class Nand(BooleanFunction): """ Logical NAND function. It evaluates its arguments in order, giving True immediately if any of them are False, and False if they are all True. Returns True if any of the arguments are False Returns False if all arguments are True Examples ======== >>> from sympy.logic.boolalg import Nand >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nand(False, True) True >>> Nand(True, True) False >>> Nand(x, y) ~(x & y) """ @classmethod def eval(cls, *args): return Not(And(*args)) class Nor(BooleanFunction): """ Logical NOR function. It evaluates its arguments in order, giving False immediately if any of them are True, and True if they are all False. Returns False if any argument is True Returns True if all arguments are False Examples ======== >>> from sympy.logic.boolalg import Nor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nor(True, False) False >>> Nor(True, True) False >>> Nor(False, True) False >>> Nor(False, False) True >>> Nor(x, y) ~(x | y) """ @classmethod def eval(cls, *args): return Not(Or(*args)) class Xnor(BooleanFunction): """ Logical XNOR function. Returns False if an odd number of the arguments are True and the rest are False. Returns True if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xnor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xnor(True, False) False >>> Xnor(True, True) True >>> Xnor(True, False, True, True, False) False >>> Xnor(True, False, True, False) True """ @classmethod def eval(cls, *args): return Not(Xor(*args)) class Implies(BooleanFunction): r""" Logical implication. A implies B is equivalent to if A then B. Mathematically, it is written as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``. Accepts two Boolean arguments; A and B. Returns False if A is True and B is False Returns True otherwise. Examples ======== >>> from sympy.logic.boolalg import Implies >>> from sympy import symbols >>> x, y = symbols('x y') >>> Implies(True, False) False >>> Implies(False, False) True >>> Implies(True, True) True >>> Implies(False, True) True >>> x >> y Implies(x, y) >>> y << x Implies(x, y) Notes ===== The ``>>`` and ``<<`` operators are provided as a convenience, but note that their use here is different from their normal use in Python, which is bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different things if ``a`` and ``b`` are integers. In particular, since Python considers ``True`` and ``False`` to be integers, ``True >> True`` will be the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To avoid this issue, use the SymPy objects ``true`` and ``false``. >>> from sympy import true, false >>> True >> False 1 >>> true >> false False """ @classmethod def eval(cls, *args): try: newargs = [] for x in args: if isinstance(x, Number) or x in (0, 1): newargs.append(bool(x)) else: newargs.append(x) A, B = newargs except ValueError: raise ValueError( "%d operand(s) used for an Implies " "(pairs are required): %s" % (len(args), str(args))) if A in (True, False) or B in (True, False): return Or(Not(A), B) elif A == B: return S.true elif A.is_Relational and B.is_Relational: if A.canonical == B.canonical: return S.true if A.negated.canonical == B.canonical: return B else: return Basic.__new__(cls, *args) def to_nnf(self, simplify=True): a, b = self.args return Or._to_nnf(Not(a), b, simplify=simplify) def to_anf(self, deep=True): a, b = self.args return Xor._to_anf(true, a, And(a, b), deep=deep) class Equivalent(BooleanFunction): """ Equivalence relation. ``Equivalent(A, B)`` is True iff A and B are both True or both False. Returns True if all of the arguments are logically equivalent. Returns False otherwise. For two arguments, this is equivalent to :py:class:`~.Xnor`. Examples ======== >>> from sympy.logic.boolalg import Equivalent, And >>> from sympy.abc import x >>> Equivalent(False, False, False) True >>> Equivalent(True, False, False) False >>> Equivalent(x, And(x, True)) True """ def __new__(cls, *args, **options): from sympy.core.relational import Relational args = [_sympify(arg) for arg in args] argset = set(args) for x in args: if isinstance(x, Number) or x in [True, False]: # Includes 0, 1 argset.discard(x) argset.add(bool(x)) rel = [] for r in argset: if isinstance(r, Relational): rel.append((r, r.canonical, r.negated.canonical)) remove = [] for i, (r, c, nc) in enumerate(rel): for j in range(i + 1, len(rel)): rj, cj = rel[j][:2] if cj == nc: return false elif cj == c: remove.append((r, rj)) break for a, b in remove: argset.remove(a) argset.remove(b) argset.add(True) if len(argset) <= 1: return true if True in argset: argset.discard(True) return And(*argset) if False in argset: argset.discard(False) return And(*[Not(arg) for arg in argset]) _args = frozenset(argset) obj = super().__new__(cls, _args) obj._argset = _args return obj # XXX: This should be cached on the object rather than using cacheit # Maybe it can be computed in __new__? @property # type: ignore @cacheit def args(self): return tuple(ordered(self._argset)) def to_nnf(self, simplify=True): args = [] for a, b in zip(self.args, self.args[1:]): args.append(Or(Not(a), b)) args.append(Or(Not(self.args[-1]), self.args[0])) return And._to_nnf(*args, simplify=simplify) def to_anf(self, deep=True): a = And(*self.args) b = And(*[to_anf(Not(arg), deep=False) for arg in self.args]) b = distribute_xor_over_and(b) return Xor._to_anf(a, b, deep=deep) class ITE(BooleanFunction): """ If-then-else clause. ``ITE(A, B, C)`` evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans. From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer, where A is the select signal. Examples ======== >>> from sympy.logic.boolalg import ITE, And, Xor, Or >>> from sympy.abc import x, y, z >>> ITE(True, False, True) False >>> ITE(Or(True, False), And(True, True), Xor(True, True)) True >>> ITE(x, y, z) ITE(x, y, z) >>> ITE(True, x, y) x >>> ITE(False, x, y) y >>> ITE(x, y, y) y Trying to use non-Boolean args will generate a TypeError: >>> ITE(True, [], ()) Traceback (most recent call last): ... TypeError: expecting bool, Boolean or ITE, not `[]` """ def __new__(cls, *args, **kwargs): from sympy.core.relational import Eq, Ne if len(args) != 3: raise ValueError('expecting exactly 3 args') a, b, c = args # check use of binary symbols if isinstance(a, (Eq, Ne)): # in this context, we can evaluate the Eq/Ne # if one arg is a binary symbol and the other # is true/false b, c = map(as_Boolean, (b, c)) bin_syms = set().union(*[i.binary_symbols for i in (b, c)]) if len(set(a.args) - bin_syms) == 1: # one arg is a binary_symbols _a = a if a.lhs is S.true: a = a.rhs elif a.rhs is S.true: a = a.lhs elif a.lhs is S.false: a = Not(a.rhs) elif a.rhs is S.false: a = Not(a.lhs) else: # binary can only equal True or False a = S.false if isinstance(_a, Ne): a = Not(a) else: a, b, c = BooleanFunction.binary_check_and_simplify( a, b, c) rv = None if kwargs.get('evaluate', True): rv = cls.eval(a, b, c) if rv is None: rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False) return rv @classmethod def eval(cls, *args): from sympy.core.relational import Eq, Ne # do the args give a singular result? a, b, c = args if isinstance(a, (Ne, Eq)): _a = a if S.true in a.args: a = a.lhs if a.rhs is S.true else a.rhs elif S.false in a.args: a = Not(a.lhs) if a.rhs is S.false else Not(a.rhs) else: _a = None if _a is not None and isinstance(_a, Ne): a = Not(a) if a is S.true: return b if a is S.false: return c if b == c: return b else: # or maybe the results allow the answer to be expressed # in terms of the condition if b is S.true and c is S.false: return a if b is S.false and c is S.true: return Not(a) if [a, b, c] != args: return cls(a, b, c, evaluate=False) def to_nnf(self, simplify=True): a, b, c = self.args return And._to_nnf(Or(Not(a), b), Or(a, c), simplify=simplify) def _eval_as_set(self): return self.to_nnf().as_set() def _eval_rewrite_as_Piecewise(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise return Piecewise((args[1], args[0]), (args[2], True)) class Exclusive(BooleanFunction): """ True if only one or no argument is true. ``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``. For two arguments, this is equivalent to :py:class:`~.Xor`. Examples ======== >>> from sympy.logic.boolalg import Exclusive >>> Exclusive(False, False, False) True >>> Exclusive(False, True, False) True >>> Exclusive(False, True, True) False """ @classmethod def eval(cls, *args): and_args = [] for a, b in combinations(args, 2): and_args.append(Not(And(a, b))) return And(*and_args) # end class definitions. Some useful methods def conjuncts(expr): """Return a list of the conjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import conjuncts >>> from sympy.abc import A, B >>> conjuncts(A & B) frozenset({A, B}) >>> conjuncts(A | B) frozenset({A | B}) """ return And.make_args(expr) def disjuncts(expr): """Return a list of the disjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import disjuncts >>> from sympy.abc import A, B >>> disjuncts(A | B) frozenset({A, B}) >>> disjuncts(A & B) frozenset({A & B}) """ return Or.make_args(expr) def distribute_and_over_or(expr): """ Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. Examples ======== >>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_and_over_or(Or(A, And(Not(B), Not(C)))) (A | ~B) & (A | ~C) """ return _distribute((expr, And, Or)) def distribute_or_over_and(expr): """ Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in DNF. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_or_over_and(And(Or(Not(A), B), C)) (B & C) | (C & ~A) """ return _distribute((expr, Or, And)) def distribute_xor_over_and(expr): """ Given a sentence ``expr`` consisting of conjunction and exclusive disjunctions of literals, return an equivalent exclusive disjunction. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not >>> from sympy.abc import A, B, C >>> distribute_xor_over_and(And(Xor(Not(A), B), C)) (B & C) ^ (C & ~A) """ return _distribute((expr, Xor, And)) def _distribute(info): """ Distributes ``info[1]`` over ``info[2]`` with respect to ``info[0]``. """ if isinstance(info[0], info[2]): for arg in info[0].args: if isinstance(arg, info[1]): conj = arg break else: return info[0] rest = info[2](*[a for a in info[0].args if a is not conj]) return info[1](*list(map(_distribute, [(info[2](c, rest), info[1], info[2]) for c in conj.args])), remove_true=False) elif isinstance(info[0], info[1]): return info[1](*list(map(_distribute, [(x, info[1], info[2]) for x in info[0].args])), remove_true=False) else: return info[0] def to_anf(expr, deep=True): r""" Converts expr to Algebraic Normal Form (ANF). ANF is a canonical normal form, which means that two equivalent formulas will convert to the same ANF. A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it can be: - purely true, - purely false, - conjunction of variables, - exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. If ``deep`` is ``False``, arguments of the boolean expression are considered variables, i.e. only the top-level expression is converted to ANF. Examples ======== >>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent >>> from sympy.logic.boolalg import to_anf >>> from sympy.abc import A, B, C >>> to_anf(Not(A)) A ^ True >>> to_anf(And(Or(A, B), Not(C))) A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C) >>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False) True ^ ~A ^ (~A & (Equivalent(B, C))) """ expr = sympify(expr) if is_anf(expr): return expr return expr.to_anf(deep=deep) def to_nnf(expr, simplify=True): """ Converts ``expr`` to Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplify`` is ``True``, the result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C, D >>> from sympy.logic.boolalg import Not, Equivalent, to_nnf >>> to_nnf(Not((~A & ~B) | (C & D))) (A | B) & (~C | ~D) >>> to_nnf(Equivalent(A >> B, B >> A)) (A | ~B | (A & ~B)) & (B | ~A | (B & ~A)) """ if is_nnf(expr, simplify): return expr return expr.to_nnf(simplify) def to_cnf(expr, simplify=False, force=False): """ Convert a propositional logical sentence ``expr`` to conjunctive normal form: ``((A | ~B | ...) & (B | C | ...) & ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest CNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables the `force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_cnf >>> from sympy.abc import A, B, D >>> to_cnf(~(A | B) | D) (D | ~A) & (D | ~B) >>> to_cnf((A | B) & (A | ~A), True) A | B """ expr = sympify(expr) if not isinstance(expr, BooleanFunction): return expr if simplify: if not force and len(_find_predicates(expr)) > 8: raise ValueError(filldedent(''' To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.''')) return simplify_logic(expr, 'cnf', True, force=force) # Don't convert unless we have to if is_cnf(expr): return expr expr = eliminate_implications(expr) res = distribute_and_over_or(expr) return res def to_dnf(expr, simplify=False, force=False): """ Convert a propositional logical sentence ``expr`` to disjunctive normal form: ``((A & ~B & ...) | (B & C & ...) | ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest DNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables, the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_dnf >>> from sympy.abc import A, B, C >>> to_dnf(B & (A | C)) (A & B) | (B & C) >>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True) A | C """ expr = sympify(expr) if not isinstance(expr, BooleanFunction): return expr if simplify: if not force and len(_find_predicates(expr)) > 8: raise ValueError(filldedent(''' To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.''')) return simplify_logic(expr, 'dnf', True, force=force) # Don't convert unless we have to if is_dnf(expr): return expr expr = eliminate_implications(expr) return distribute_or_over_and(expr) def is_anf(expr): r""" Checks if ``expr`` is in Algebraic Normal Form (ANF). A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it is purely true, purely false, conjunction of variables or exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. Examples ======== >>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf >>> from sympy.abc import A, B, C >>> is_anf(true) True >>> is_anf(A) True >>> is_anf(And(A, B, C)) True >>> is_anf(Xor(A, Not(B))) False """ expr = sympify(expr) if is_literal(expr) and not isinstance(expr, Not): return True if isinstance(expr, And): for arg in expr.args: if not arg.is_Symbol: return False return True elif isinstance(expr, Xor): for arg in expr.args: if isinstance(arg, And): for a in arg.args: if not a.is_Symbol: return False elif is_literal(arg): if isinstance(arg, Not): return False else: return False return True else: return False def is_nnf(expr, simplified=True): """ Checks if ``expr`` is in Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplified`` is ``True``, checks if result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy.logic.boolalg import Not, is_nnf >>> is_nnf(A & B | ~C) True >>> is_nnf((A | ~A) & (B | C)) False >>> is_nnf((A | ~A) & (B | C), False) True >>> is_nnf(Not(A & B) | C) False >>> is_nnf((A >> B) & (B >> A)) False """ expr = sympify(expr) if is_literal(expr): return True stack = [expr] while stack: expr = stack.pop() if expr.func in (And, Or): if simplified: args = expr.args for arg in args: if Not(arg) in args: return False stack.extend(expr.args) elif not is_literal(expr): return False return True def is_cnf(expr): """ Test whether or not an expression is in conjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_cnf >>> from sympy.abc import A, B, C >>> is_cnf(A | B | C) True >>> is_cnf(A & B & C) True >>> is_cnf((A & B) | C) False """ return _is_form(expr, And, Or) def is_dnf(expr): """ Test whether or not an expression is in disjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_dnf >>> from sympy.abc import A, B, C >>> is_dnf(A | B | C) True >>> is_dnf(A & B & C) True >>> is_dnf((A & B) | C) True >>> is_dnf(A & (B | C)) False """ return _is_form(expr, Or, And) def _is_form(expr, function1, function2): """ Test whether or not an expression is of the required form. """ expr = sympify(expr) vals = function1.make_args(expr) if isinstance(expr, function1) else [expr] for lit in vals: if isinstance(lit, function2): vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit] for l in vals2: if is_literal(l) is False: return False elif is_literal(lit) is False: return False return True def eliminate_implications(expr): """ Change :py:class:`~.Implies` and :py:class:`~.Equivalent` into :py:class:`~.And`, :py:class:`~.Or`, and :py:class:`~.Not`. That is, return an expression that is equivalent to ``expr``, but has only ``&``, ``|``, and ``~`` as logical operators. Examples ======== >>> from sympy.logic.boolalg import Implies, Equivalent, \ eliminate_implications >>> from sympy.abc import A, B, C >>> eliminate_implications(Implies(A, B)) B | ~A >>> eliminate_implications(Equivalent(A, B)) (A | ~B) & (B | ~A) >>> eliminate_implications(Equivalent(A, B, C)) (A | ~C) & (B | ~A) & (C | ~B) """ return to_nnf(expr, simplify=False) def is_literal(expr): """ Returns True if expr is a literal, else False. Examples ======== >>> from sympy import Or, Q >>> from sympy.abc import A, B >>> from sympy.logic.boolalg import is_literal >>> is_literal(A) True >>> is_literal(~A) True >>> is_literal(Q.zero(A)) True >>> is_literal(A + B) True >>> is_literal(Or(A, B)) False """ from sympy.assumptions import AppliedPredicate if isinstance(expr, Not): return is_literal(expr.args[0]) elif expr in (True, False) or isinstance(expr, AppliedPredicate) or expr.is_Atom: return True elif not isinstance(expr, BooleanFunction) and all( (isinstance(expr, AppliedPredicate) or a.is_Atom) for a in expr.args): return True return False def to_int_repr(clauses, symbols): """ Takes clauses in CNF format and puts them into an integer representation. Examples ======== >>> from sympy.logic.boolalg import to_int_repr >>> from sympy.abc import x, y >>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}] True """ # Convert the symbol list into a dict symbols = dict(list(zip(symbols, list(range(1, len(symbols) + 1))))) def append_symbol(arg, symbols): if isinstance(arg, Not): return -symbols[arg.args[0]] else: return symbols[arg] return [{append_symbol(arg, symbols) for arg in Or.make_args(c)} for c in clauses] def term_to_integer(term): """ Return an integer corresponding to the base-2 digits given by *term*. Parameters ========== term : a string or list of ones and zeros Examples ======== >>> from sympy.logic.boolalg import term_to_integer >>> term_to_integer([1, 0, 0]) 4 >>> term_to_integer('100') 4 """ return int(''.join(list(map(str, list(term)))), 2) integer_to_term = ibin # XXX could delete? def truth_table(expr, variables, input=True): """ Return a generator of all possible configurations of the input variables, and the result of the boolean expression for those values. Parameters ========== expr : Boolean expression variables : list of variables input : bool (default ``True``) Indicates whether to return the input combinations. Examples ======== >>> from sympy.logic.boolalg import truth_table >>> from sympy.abc import x,y >>> table = truth_table(x >> y, [x, y]) >>> for t in table: ... print('{0} -> {1}'.format(*t)) [0, 0] -> True [0, 1] -> True [1, 0] -> False [1, 1] -> True >>> table = truth_table(x | y, [x, y]) >>> list(table) [([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)] If ``input`` is ``False``, ``truth_table`` returns only a list of truth values. In this case, the corresponding input values of variables can be deduced from the index of a given output. >>> from sympy.utilities.iterables import ibin >>> vars = [y, x] >>> values = truth_table(x >> y, vars, input=False) >>> values = list(values) >>> values [True, False, True, True] >>> for i, value in enumerate(values): ... print('{0} -> {1}'.format(list(zip( ... vars, ibin(i, len(vars)))), value)) [(y, 0), (x, 0)] -> True [(y, 0), (x, 1)] -> False [(y, 1), (x, 0)] -> True [(y, 1), (x, 1)] -> True """ variables = [sympify(v) for v in variables] expr = sympify(expr) if not isinstance(expr, BooleanFunction) and not is_literal(expr): return table = product((0, 1), repeat=len(variables)) for term in table: value = expr.xreplace(dict(zip(variables, term))) if input: yield list(term), value else: yield value def _check_pair(minterm1, minterm2): """ Checks if a pair of minterms differs by only one bit. If yes, returns index, else returns `-1`. """ # Early termination seems to be faster than list comprehension, # at least for large examples. index = -1 for x, i in enumerate(minterm1): # zip(minterm1, minterm2) is slower if i != minterm2[x]: if index == -1: index = x else: return -1 return index def _convert_to_varsSOP(minterm, variables): """ Converts a term in the expansion of a function from binary to its variable form (for SOP). """ temp = [variables[n] if val == 1 else Not(variables[n]) for n, val in enumerate(minterm) if val != 3] return And(*temp) def _convert_to_varsPOS(maxterm, variables): """ Converts a term in the expansion of a function from binary to its variable form (for POS). """ temp = [variables[n] if val == 0 else Not(variables[n]) for n, val in enumerate(maxterm) if val != 3] return Or(*temp) def _convert_to_varsANF(term, variables): """ Converts a term in the expansion of a function from binary to its variable form (for ANF). Parameters ========== term : list of 1's and 0's (complementation patter) variables : list of variables """ temp = [variables[n] for n, t in enumerate(term) if t == 1] if not temp: return true return And(*temp) def _get_odd_parity_terms(n): """ Returns a list of lists, with all possible combinations of n zeros and ones with an odd number of ones. """ return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1] def _get_even_parity_terms(n): """ Returns a list of lists, with all possible combinations of n zeros and ones with an even number of ones. """ return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0] def _simplified_pairs(terms): """ Reduces a set of minterms, if possible, to a simplified set of minterms with one less variable in the terms using QM method. """ if not terms: return [] simplified_terms = [] todo = list(range(len(terms))) # Count number of ones as _check_pair can only potentially match if there # is at most a difference of a single one termdict = defaultdict(list) for n, term in enumerate(terms): ones = sum([1 for t in term if t == 1]) termdict[ones].append(n) variables = len(terms[0]) for k in range(variables): for i in termdict[k]: for j in termdict[k+1]: index = _check_pair(terms[i], terms[j]) if index != -1: # Mark terms handled todo[i] = todo[j] = None # Copy old term newterm = terms[i][:] # Set differing position to don't care newterm[index] = 3 # Add if not already there if newterm not in simplified_terms: simplified_terms.append(newterm) if simplified_terms: # Further simplifications only among the new terms simplified_terms = _simplified_pairs(simplified_terms) # Add remaining, non-simplified, terms simplified_terms.extend([terms[i] for i in todo if i is not None]) return simplified_terms def _rem_redundancy(l1, terms): """ After the truth table has been sufficiently simplified, use the prime implicant table method to recognize and eliminate redundant pairs, and return the essential arguments. """ if not terms: return [] nterms = len(terms) nl1 = len(l1) # Create dominating matrix dommatrix = [[0]*nl1 for n in range(nterms)] colcount = [0]*nl1 rowcount = [0]*nterms for primei, prime in enumerate(l1): for termi, term in enumerate(terms): # Check prime implicant covering term if all(t == 3 or t == mt for t, mt in zip(prime, term)): dommatrix[termi][primei] = 1 colcount[primei] += 1 rowcount[termi] += 1 # Keep track if anything changed anythingchanged = True # Then, go again while anythingchanged: anythingchanged = False for rowi in range(nterms): # Still non-dominated? if rowcount[rowi]: row = dommatrix[rowi] for row2i in range(nterms): # Still non-dominated? if rowi != row2i and rowcount[rowi] and (rowcount[rowi] <= rowcount[row2i]): row2 = dommatrix[row2i] if all(row2[n] >= row[n] for n in range(nl1)): # row2 dominating row, remove row2 rowcount[row2i] = 0 anythingchanged = True for primei, prime in enumerate(row2): if prime: # Make corresponding entry 0 dommatrix[row2i][primei] = 0 colcount[primei] -= 1 colcache = dict() for coli in range(nl1): # Still non-dominated? if colcount[coli]: if coli in colcache: col = colcache[coli] else: col = [dommatrix[i][coli] for i in range(nterms)] colcache[coli] = col for col2i in range(nl1): # Still non-dominated? if coli != col2i and colcount[col2i] and (colcount[coli] >= colcount[col2i]): if col2i in colcache: col2 = colcache[col2i] else: col2 = [dommatrix[i][col2i] for i in range(nterms)] colcache[col2i] = col2 if all(col[n] >= col2[n] for n in range(nterms)): # col dominating col2, remove col2 colcount[col2i] = 0 anythingchanged = True for termi, term in enumerate(col2): if term and dommatrix[termi][col2i]: # Make corresponding entry 0 dommatrix[termi][col2i] = 0 rowcount[termi] -= 1 if not anythingchanged: # Heuristically select the prime implicant covering most terms maxterms = 0 bestcolidx = -1 for coli in range(nl1): s = colcount[coli] if s > maxterms: bestcolidx = coli maxterms = s # In case we found a prime implicant covering at least two terms if bestcolidx != -1 and maxterms > 1: for primei, prime in enumerate(l1): if primei != bestcolidx: for termi, term in enumerate(colcache[bestcolidx]): if term and dommatrix[termi][primei]: # Make corresponding entry 0 dommatrix[termi][primei] = 0 anythingchanged = True rowcount[termi] -= 1 colcount[primei] -= 1 return [l1[i] for i in range(nl1) if colcount[i]] def _input_to_binlist(inputlist, variables): binlist = [] bits = len(variables) for val in inputlist: if isinstance(val, int): binlist.append(ibin(val, bits)) elif isinstance(val, dict): nonspecvars = list(variables) for key in val.keys(): nonspecvars.remove(key) for t in product((0, 1), repeat=len(nonspecvars)): d = dict(zip(nonspecvars, t)) d.update(val) binlist.append([d[v] for v in variables]) elif isinstance(val, (list, tuple)): if len(val) != bits: raise ValueError("Each term must contain {bits} bits as there are" "\n{bits} variables (or be an integer)." "".format(bits=bits)) binlist.append(list(val)) else: raise TypeError("A term list can only contain lists," " ints or dicts.") return binlist def SOPform(variables, minterms, dontcares=None): """ The SOPform function uses simplified_pairs and a redundant group- eliminating algorithm to convert the list of all input combos that generate '1' (the minterms) into the smallest sum-of-products form. The variables must be given as the first argument. Return a logical :py:class:`~.Or` function (i.e., the "sum of products" or "SOP" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import SOPform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], ... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> SOPform([w, x, y, z], minterms) (x & ~w) | (y & z & ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (w & y & z) | (~w & ~y) | (x & z & ~w) References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm """ if not minterms: return false variables = tuple(map(sympify, variables)) minterms = _input_to_binlist(minterms, variables) dontcares = _input_to_binlist((dontcares or []), variables) for d in dontcares: if d in minterms: raise ValueError('%s in minterms is also in dontcares' % d) return _sop_form(variables, minterms, dontcares) def _sop_form(variables, minterms, dontcares): new = _simplified_pairs(minterms + dontcares) essential = _rem_redundancy(new, minterms) return Or(*[_convert_to_varsSOP(x, variables) for x in essential]) def POSform(variables, minterms, dontcares=None): """ The POSform function uses simplified_pairs and a redundant-group eliminating algorithm to convert the list of all input combinations that generate '1' (the minterms) into the smallest product-of-sums form. The variables must be given as the first argument. Return a logical :py:class:`~.And` function (i.e., the "product of sums" or "POS" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import POSform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], ... [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> POSform([w, x, y, z], minterms) (x | y) & (x | z) & (~w | ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> POSform([w, x, y, z], minterms, dontcares) (w | x) & (y | ~w) & (z | ~y) References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm """ if not minterms: return false variables = tuple(map(sympify, variables)) minterms = _input_to_binlist(minterms, variables) dontcares = _input_to_binlist((dontcares or []), variables) for d in dontcares: if d in minterms: raise ValueError('%s in minterms is also in dontcares' % d) maxterms = [] for t in product((0, 1), repeat=len(variables)): t = list(t) if (t not in minterms) and (t not in dontcares): maxterms.append(t) new = _simplified_pairs(maxterms + dontcares) essential = _rem_redundancy(new, maxterms) return And(*[_convert_to_varsPOS(x, variables) for x in essential]) def ANFform(variables, truthvalues): """ The ANFform function converts the list of truth values to Algebraic Normal Form (ANF). The variables must be given as the first argument. Return True, False, logical :py:class:`~.And` funciton (i.e., the "Zhegalkin monomial") or logical :py:class:`~.Xor` function (i.e., the "Zhegalkin polynomial"). When True and False are represented by 1 and 0, respectively, then :py:class:`~.And` is multiplication and :py:class:`~.Xor` is addition. Formally a "Zhegalkin monomial" is the product (logical And) of a finite set of distinct variables, including the empty set whose product is denoted 1 (True). A "Zhegalkin polynomial" is the sum (logical Xor) of a set of Zhegalkin monomials, with the empty set denoted by 0 (False). Parameters ========== variables : list of variables truthvalues : list of 1's and 0's (result column of truth table) Examples ======== >>> from sympy.logic.boolalg import ANFform >>> from sympy.abc import x, y >>> ANFform([x], [1, 0]) x ^ True >>> ANFform([x, y], [0, 1, 1, 1]) x ^ y ^ (x & y) References ========== .. [1] https://en.wikipedia.org/wiki/Zhegalkin_polynomial """ n_vars = len(variables) n_values = len(truthvalues) if n_values != 2 ** n_vars: raise ValueError("The number of truth values must be equal to 2^%d, " "got %d" % (n_vars, n_values)) variables = tuple(map(sympify, variables)) coeffs = anf_coeffs(truthvalues) terms = [] for i, t in enumerate(product((0, 1), repeat=n_vars)): if coeffs[i] == 1: terms.append(t) return Xor(*[_convert_to_varsANF(x, variables) for x in terms], remove_true=False) def anf_coeffs(truthvalues): """ Convert a list of truth values of some boolean expression to the list of coefficients of the polynomial mod 2 (exclusive disjunction) representing the boolean expression in ANF (i.e., the "Zhegalkin polynomial"). There are `2^n` possible Zhegalkin monomials in `n` variables, since each monomial is fully specified by the presence or absence of each variable. We can enumerate all the monomials. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. A given monomial's presence or absence in a polynomial corresponds to that monomial's coefficient being 1 or 0 respectively. Examples ======== >>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor >>> from sympy.abc import a, b, c >>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1] >>> coeffs = anf_coeffs(truthvalues) >>> coeffs [0, 1, 1, 0, 0, 0, 1, 0] >>> polynomial = Xor(*[ ... bool_monomial(k, [a, b, c]) ... for k, coeff in enumerate(coeffs) if coeff == 1 ... ]) >>> polynomial b ^ c ^ (a & b) """ s = '{:b}'.format(len(truthvalues)) n = len(s) - 1 if len(truthvalues) != 2**n: raise ValueError("The number of truth values must be a power of two, " "got %d" % len(truthvalues)) coeffs = [[v] for v in truthvalues] for i in range(n): tmp = [] for j in range(2 ** (n-i-1)): tmp.append(coeffs[2*j] + list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1]))) coeffs = tmp return coeffs[0] def bool_minterm(k, variables): """ Return the k-th minterm. Minterms are numbered by a binary encoding of the complementation pattern of the variables. This convention assigns the value 1 to the direct form and 0 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation patter) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_minterm >>> from sympy.abc import x, y, z >>> bool_minterm([1, 0, 1], [x, y, z]) x & z & ~y >>> bool_minterm(6, [x, y, z]) x & y & ~z References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsSOP(k, variables) def bool_maxterm(k, variables): """ Return the k-th maxterm. Each maxterm is assigned an index based on the opposite conventional binary encoding used for minterms. The maxterm convention assigns the value 0 to the direct form and 1 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation pattern) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_maxterm >>> from sympy.abc import x, y, z >>> bool_maxterm([1, 0, 1], [x, y, z]) y | ~x | ~z >>> bool_maxterm(6, [x, y, z]) z | ~x | ~y References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsPOS(k, variables) def bool_monomial(k, variables): """ Return the k-th monomial. Monomials are numbered by a binary encoding of the presence and absences of the variables. This convention assigns the value 1 to the presence of variable and 0 to the absence of variable. Each boolean function can be uniquely represented by a Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin Polynomial of the boolean function with `n` variables can contain up to `2^n` monomials. We can enumarate all the monomials. Each monomial is fully specified by the presence or absence of each variable. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. Parameters ========== k : int or list of 1's and 0's variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_monomial >>> from sympy.abc import x, y, z >>> bool_monomial([1, 0, 1], [x, y, z]) x & z >>> bool_monomial(6, [x, y, z]) x & y """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsANF(k, variables) def _find_predicates(expr): """Helper to find logical predicates in BooleanFunctions. A logical predicate is defined here as anything within a BooleanFunction that is not a BooleanFunction itself. """ if not isinstance(expr, BooleanFunction): return {expr} return set().union(*(map(_find_predicates, expr.args))) def simplify_logic(expr, form=None, deep=True, force=False): """ This function simplifies a boolean function to its simplified version in SOP or POS form. The return type is an :py:class:`~.Or` or :py:class:`~.And` object in SymPy. Parameters ========== expr : Boolean expression form : string (``'cnf'`` or ``'dnf'``) or ``None`` (default). If ``'cnf'`` or ``'dnf'``, the simplest expression in the corresponding normal form is returned; if ``None``, the answer is returned according to the form with fewest args (in CNF by default). deep : bool (default ``True``) Indicates whether to recursively simplify any non-boolean functions contained within the input. force : bool (default ``False``) As the simplifications require exponential time in the number of variables, there is by default a limit on expressions with 8 variables. When the expression has more than 8 variables only symbolical simplification (controlled by ``deep``) is made. By setting ``force`` to ``True``, this limit is removed. Be aware that this can lead to very long simplification times. Examples ======== >>> from sympy.logic import simplify_logic >>> from sympy.abc import x, y, z >>> from sympy import S >>> b = (~x & ~y & ~z) | ( ~x & ~y & z) >>> simplify_logic(b) ~x & ~y >>> S(b) (z & ~x & ~y) | (~x & ~y & ~z) >>> simplify_logic(_) ~x & ~y """ if form not in (None, 'cnf', 'dnf'): raise ValueError("form can be cnf or dnf only") expr = sympify(expr) # check for quick exit if form is given: right form and all args are # literal and do not involve Not if form: form_ok = False if form == 'cnf': form_ok = is_cnf(expr) elif form == 'dnf': form_ok = is_dnf(expr) if form_ok and all(is_literal(a) for a in expr.args): return expr from sympy.core.relational import Relational if deep: variables = expr.atoms(Relational) from sympy.simplify.simplify import simplify s = tuple(map(simplify, variables)) expr = expr.xreplace(dict(zip(variables, s))) if not isinstance(expr, BooleanFunction): return expr # Replace Relationals with Dummys to possibly # reduce the number of variables repl = dict() undo = dict() from sympy.core.symbol import Dummy variables = expr.atoms(Relational) while variables: var = variables.pop() if var.is_Relational: d = Dummy() undo[d] = var repl[var] = d nvar = var.negated if nvar in variables: repl[nvar] = Not(d) variables.remove(nvar) expr = expr.xreplace(repl) # Get new variables after replacing variables = _find_predicates(expr) if not force and len(variables) > 8: return expr.xreplace(undo) # group into constants and variable values c, v = sift(ordered(variables), lambda x: x in (True, False), binary=True) variables = c + v truthtable = [] # standardize constants to be 1 or 0 in keeping with truthtable c = [1 if i == True else 0 for i in c] truthtable = _get_truthtable(v, expr, c) big = len(truthtable) >= (2 ** (len(variables) - 1)) if form == 'dnf' or form is None and big: return _sop_form(variables, truthtable, []).xreplace(undo) return POSform(variables, truthtable).xreplace(undo) def _get_truthtable(variables, expr, const): """ Return a list of all combinations leading to a True result for ``expr``. """ def _get_tt(inputs): if variables: v = variables.pop() tab = [[i[0].xreplace({v: false}), [0] + i[1]] for i in inputs if i[0] is not false] tab.extend([[i[0].xreplace({v: true}), [1] + i[1]] for i in inputs if i[0] is not false]) return _get_tt(tab) return inputs return [const + k[1] for k in _get_tt([[expr, []]]) if k[0]] def _finger(eq): """ Assign a 5-item fingerprint to each symbol in the equation: [ # of times it appeared as a Symbol; # of times it appeared as a Not(symbol); # of times it appeared as a Symbol in an And or Or; # of times it appeared as a Not(Symbol) in an And or Or; a sorted tuple of tuples, (i, j, k), where i is the number of arguments in an And or Or with which it appeared as a Symbol, and j is the number of arguments that were Not(Symbol); k is the number of times that (i, j) was seen. ] Examples ======== >>> from sympy.logic.boolalg import _finger as finger >>> from sympy import And, Or, Not, Xor, to_cnf, symbols >>> from sympy.abc import a, b, x, y >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y)) >>> dict(finger(eq)) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (0, 0, 1, 0, ((2, 1, 1),)): [a, b], (0, 0, 1, 2, ((2, 0, 1),)): [y]} >>> dict(finger(x & ~y)) {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]} In the following, the (5, 2, 6) means that there were 6 Or functions in which a symbol appeared as itself amongst 5 arguments in which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)`` is counted once for a0, a1 and a2. >>> dict(finger(to_cnf(Xor(*symbols('a:5'))))) {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]} The equation must not have more than one level of nesting: >>> dict(finger(And(Or(x, y), y))) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]} >>> dict(finger(And(Or(x, And(a, x)), y))) Traceback (most recent call last): ... NotImplementedError: unexpected level of nesting So y and x have unique fingerprints, but a and b do not. """ f = eq.free_symbols d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f]))) for a in eq.args: if a.is_Symbol: d[a][0] += 1 elif a.is_Not: d[a.args[0]][1] += 1 else: o = len(a.args), sum(isinstance(ai, Not) for ai in a.args) for ai in a.args: if ai.is_Symbol: d[ai][2] += 1 d[ai][-1][o] += 1 elif ai.is_Not: d[ai.args[0]][3] += 1 else: raise NotImplementedError('unexpected level of nesting') inv = defaultdict(list) for k, v in ordered(iter(d.items())): v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()])) inv[tuple(v)].append(k) return inv def bool_map(bool1, bool2): """ Return the simplified version of *bool1*, and the mapping of variables that makes the two expressions *bool1* and *bool2* represent the same logical behaviour for some correspondence between the variables of each. If more than one mappings of this sort exist, one of them is returned. For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``. If no such mapping exists, return ``False``. Examples ======== >>> from sympy import SOPform, bool_map, Or, And, Not, Xor >>> from sympy.abc import w, x, y, z, a, b, c, d >>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]]) >>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]]) >>> bool_map(function1, function2) (y & ~z, {y: a, z: b}) The results are not necessarily unique, but they are canonical. Here, ``(w, z)`` could be ``(a, d)`` or ``(d, a)``: >>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y)) >>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c)) >>> bool_map(eq, eq2) ((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d}) >>> eq = And(Xor(a, b), c, And(c,d)) >>> bool_map(eq, eq.subs(c, x)) (c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x}) """ def match(function1, function2): """Return the mapping that equates variables between two simplified boolean expressions if possible. By "simplified" we mean that a function has been denested and is either an And (or an Or) whose arguments are either symbols (x), negated symbols (Not(x)), or Or (or an And) whose arguments are only symbols or negated symbols. For example, ``And(x, Not(y), Or(w, Not(z)))``. Basic.match is not robust enough (see issue 4835) so this is a workaround that is valid for simplified boolean expressions """ # do some quick checks if function1.__class__ != function2.__class__: return None # maybe simplification makes them the same? if len(function1.args) != len(function2.args): return None # maybe simplification makes them the same? if function1.is_Symbol: return {function1: function2} # get the fingerprint dictionaries f1 = _finger(function1) f2 = _finger(function2) # more quick checks if len(f1) != len(f2): return False # assemble the match dictionary if possible matchdict = {} for k in f1.keys(): if k not in f2: return False if len(f1[k]) != len(f2[k]): return False for i, x in enumerate(f1[k]): matchdict[x] = f2[k][i] return matchdict a = simplify_logic(bool1) b = simplify_logic(bool2) m = match(a, b) if m: return a, m return m def _apply_patternbased_simplification(rv, patterns, measure, dominatingvalue, replacementvalue=None, threeterm_patterns=None): """ Replace patterns of Relational Parameters ========== rv : Expr Boolean expression patterns : tuple Tuple of tuples, with (pattern to simplify, simplified pattern). measure : function Simplification measure. dominatingvalue : Boolean or ``None`` The dominating value for the function of consideration. For example, for :py:class:`~.And` ``S.false`` is dominating. As soon as one expression is ``S.false`` in :py:class:`~.And`, the whole expression is ``S.false``. replacementvalue : Boolean or ``None``, optional The resulting value for the whole expression if one argument evaluates to ``dominatingvalue``. For example, for :py:class:`~.Nand` ``S.false`` is dominating, but in this case the resulting value is ``S.true``. Default is ``None``. If ``replacementvalue`` is ``None`` and ``dominatingvalue`` is not ``None``, ``replacementvalue = dominatingvalue``. """ from sympy.core.relational import Relational, _canonical if replacementvalue is None and dominatingvalue is not None: replacementvalue = dominatingvalue # Use replacement patterns for Relationals Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational), binary=True) if len(Rel) <= 1: return rv Rel, nonRealRel = sift(Rel, lambda i: not any(s.is_real is False for s in i.free_symbols), binary=True) Rel = [i.canonical for i in Rel] if threeterm_patterns and len(Rel) >= 3: Rel = _apply_patternbased_threeterm_simplification(Rel, threeterm_patterns, rv.func, dominatingvalue, replacementvalue, measure) Rel = _apply_patternbased_twoterm_simplification(Rel, patterns, rv.func, dominatingvalue, replacementvalue, measure) rv = rv.func(*([_canonical(i) for i in ordered(Rel)] + nonRel + nonRealRel)) return rv def _apply_patternbased_twoterm_simplification(Rel, patterns, func, dominatingvalue, replacementvalue, measure): """ Apply pattern-based two-term simplification.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core.relational import Ge, Gt, _Inequality changed = True while changed and len(Rel) >= 2: changed = False # Use only < or <= Rel = [r.reversed if isinstance(r, (Ge, Gt)) else r for r in Rel] # Sort based on ordered Rel = list(ordered(Rel)) # Eq and Ne must be tested reversed as well rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel] # Create a list of possible replacements results = [] # Try all combinations of possibly reversed relational for ((i, pi), (j, pj)) in combinations(enumerate(rtmp), 2): for pattern, simp in patterns: res = [] for p1, p2 in product(pi, pj): # use SymPy matching oldexpr = Tuple(p1, p2) tmpres = oldexpr.match(pattern) if tmpres: res.append((tmpres, oldexpr)) if res: for tmpres, oldexpr in res: # we have a matching, compute replacement np = simp.xreplace(tmpres) if np == dominatingvalue: # if dominatingvalue, the whole expression # will be replacementvalue return [replacementvalue] # add replacement if not isinstance(np, ITE) and not np.has(Min, Max): # We only want to use ITE and Min/Max replacements if # they simplify to a relational costsaving = measure(func(*oldexpr.args)) - measure(np) if costsaving > 0: results.append((costsaving, ([i, j], np))) if results: # Sort results based on complexity results = list(reversed(sorted(results, key=lambda pair: pair[0]))) # Replace the one providing most simplification replacement = results[0][1] idx, newrel = replacement idx.sort() # Remove the old relationals for index in reversed(idx): del Rel[index] if dominatingvalue is None or newrel != Not(dominatingvalue): # Insert the new one (no need to insert a value that will # not affect the result) if newrel.func == func: for a in newrel.args: Rel.append(a) else: Rel.append(newrel) # We did change something so try again changed = True return Rel def _apply_patternbased_threeterm_simplification(Rel, patterns, func, dominatingvalue, replacementvalue, measure): """ Apply pattern-based three-term simplification.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core.relational import Le, Lt, _Inequality changed = True while changed and len(Rel) >= 3: changed = False # Use only > or >= Rel = [r.reversed if isinstance(r, (Le, Lt)) else r for r in Rel] # Sort based on ordered Rel = list(ordered(Rel)) # Create a list of possible replacements results = [] # Eq and Ne must be tested reversed as well rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel] # Try all combinations of possibly reversed relational for ((i, pi), (j, pj), (k, pk)) in permutations(enumerate(rtmp), 3): for pattern, simp in patterns: res = [] for p1, p2, p3 in product(pi, pj, pk): # use SymPy matching oldexpr = Tuple(p1, p2, p3) tmpres = oldexpr.match(pattern) if tmpres: res.append((tmpres, oldexpr)) if res: for tmpres, oldexpr in res: # we have a matching, compute replacement np = simp.xreplace(tmpres) if np == dominatingvalue: # if dominatingvalue, the whole expression # will be replacementvalue return [replacementvalue] # add replacement if not isinstance(np, ITE) and not np.has(Min, Max): # We only want to use ITE and Min/Max replacements if # they simplify to a relational costsaving = measure(func(*oldexpr.args)) - measure(np) if costsaving > 0: results.append((costsaving, ([i, j, k], np))) if results: # Sort results based on complexity results = list(reversed(sorted(results, key=lambda pair: pair[0]))) # Replace the one providing most simplification replacement = results[0][1] idx, newrel = replacement idx.sort() # Remove the old relationals for index in reversed(idx): del Rel[index] if dominatingvalue is None or newrel != Not(dominatingvalue): # Insert the new one (no need to insert a value that will # not affect the result) if newrel.func == func: for a in newrel.args: Rel.append(a) else: Rel.append(newrel) # We did change something so try again changed = True return Rel def _simplify_patterns_and(): """ Two-term patterns for And.""" from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Min, Max a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_and = ((Tuple(Eq(a, b), Lt(a, b)), S.false), #(Tuple(Eq(a, b), Lt(b, a)), S.false), #(Tuple(Le(b, a), Lt(a, b)), S.false), #(Tuple(Lt(b, a), Le(a, b)), S.false), (Tuple(Lt(b, a), Lt(a, b)), S.false), (Tuple(Eq(a, b), Le(b, a)), Eq(a, b)), #(Tuple(Eq(a, b), Le(a, b)), Eq(a, b)), #(Tuple(Le(b, a), Lt(b, a)), Gt(a, b)), (Tuple(Le(b, a), Le(a, b)), Eq(a, b)), #(Tuple(Le(b, a), Ne(a, b)), Gt(a, b)), #(Tuple(Lt(b, a), Ne(a, b)), Gt(a, b)), (Tuple(Le(a, b), Lt(a, b)), Lt(a, b)), (Tuple(Le(a, b), Ne(a, b)), Lt(a, b)), (Tuple(Lt(a, b), Ne(a, b)), Lt(a, b)), # Sign (Tuple(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), Ge(a, Max(b, c))), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Ge(a, b), Gt(a, c))), (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Max(b, c))), (Tuple(Le(a, b), Le(a, c)), Le(a, Min(b, c))), (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))), (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))), (Tuple(Le(a, b), Le(c, a)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, S.false, And(Le(a, b), Ge(a, c))))), (Tuple(Le(c, a), Le(a, b)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, S.false, And(Le(a, b), Ge(a, c))))), (Tuple(Lt(a, b), Lt(c, a)), ITE(b < c, S.false, And(Lt(a, b), Gt(a, c)))), (Tuple(Lt(c, a), Lt(a, b)), ITE(b < c, S.false, And(Lt(a, b), Gt(a, c)))), (Tuple(Le(a, b), Lt(c, a)), ITE(b <= c, S.false, And(Le(a, b), Gt(a, c)))), (Tuple(Le(c, a), Lt(a, b)), ITE(b <= c, S.false, And(Lt(a, b), Ge(a, c)))), (Tuple(Eq(a, b), Eq(a, c)), ITE(Eq(b, c), Eq(a, b), S.false)), (Tuple(Lt(a, b), Lt(-b, a)), ITE(b > 0, Lt(Abs(a), b), S.false)), (Tuple(Le(a, b), Le(-b, a)), ITE(b >= 0, Le(Abs(a), b), S.false)), ) return _matchers_and def _simplify_patterns_and3(): """ Three-term patterns for And.""" from sympy.core import Wild from sympy.core.relational import Eq, Ge, Gt a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, pattern3, simplified) # Do not use Le, Lt _matchers_and = ((Tuple(Ge(a, b), Ge(b, c), Gt(c, a)), S.false), (Tuple(Ge(a, b), Gt(b, c), Gt(c, a)), S.false), (Tuple(Gt(a, b), Gt(b, c), Gt(c, a)), S.false), # (Tuple(Ge(c, a), Gt(a, b), Gt(b, c)), S.false), # Lower bound relations # Commented out combinations that does not simplify (Tuple(Ge(a, b), Ge(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))), (Tuple(Ge(a, b), Ge(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))), # (Tuple(Ge(a, b), Gt(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))), (Tuple(Ge(a, b), Gt(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))), # (Tuple(Gt(a, b), Ge(a, c), Ge(b, c)), And(Gt(a, b), Ge(b, c))), (Tuple(Ge(a, c), Gt(a, b), Gt(b, c)), And(Gt(a, b), Gt(b, c))), (Tuple(Ge(b, c), Gt(a, b), Gt(a, c)), And(Gt(a, b), Ge(b, c))), (Tuple(Gt(a, b), Gt(a, c), Gt(b, c)), And(Gt(a, b), Gt(b, c))), # Upper bound relations # Commented out combinations that does not simplify (Tuple(Ge(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))), (Tuple(Ge(b, a), Ge(c, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))), # (Tuple(Ge(b, a), Gt(c, a), Ge(b, c)), And(Gt(c, a), Ge(b, c))), (Tuple(Ge(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))), # (Tuple(Gt(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))), (Tuple(Ge(c, a), Gt(b, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))), (Tuple(Ge(b, c), Gt(b, a), Gt(c, a)), And(Gt(c, a), Ge(b, c))), (Tuple(Gt(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))), # Circular relation (Tuple(Ge(a, b), Ge(b, c), Ge(c, a)), And(Eq(a, b), Eq(b, c))), ) return _matchers_and def _simplify_patterns_or(): """ Two-term patterns for Or.""" from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Min, Max a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_or = ((Tuple(Le(b, a), Le(a, b)), S.true), #(Tuple(Le(b, a), Lt(a, b)), S.true), (Tuple(Le(b, a), Ne(a, b)), S.true), #(Tuple(Le(a, b), Lt(b, a)), S.true), #(Tuple(Le(a, b), Ne(a, b)), S.true), #(Tuple(Eq(a, b), Le(b, a)), Ge(a, b)), #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)), (Tuple(Eq(a, b), Le(a, b)), Le(a, b)), (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)), #(Tuple(Le(b, a), Lt(b, a)), Ge(a, b)), (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)), (Tuple(Lt(b, a), Ne(a, b)), Ne(a, b)), (Tuple(Le(a, b), Lt(a, b)), Le(a, b)), #(Tuple(Lt(a, b), Ne(a, b)), Ne(a, b)), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), Ge(a, Min(b, c))), #(Tuple(Ge(b, a), Ge(c, a)), Ge(Min(b, c), a)), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Gt(a, c), Ge(a, b))), (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Min(b, c))), #(Tuple(Gt(b, a), Gt(c, a)), Gt(Min(b, c), a)), (Tuple(Le(a, b), Le(a, c)), Le(a, Max(b, c))), #(Tuple(Le(b, a), Le(c, a)), Le(Max(b, c), a)), (Tuple(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))), (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))), #(Tuple(Lt(b, a), Lt(c, a)), Lt(Max(b, c), a)), (Tuple(Le(a, b), Le(c, a)), ITE(b >= c, S.true, Or(Le(a, b), Ge(a, c)))), (Tuple(Le(c, a), Le(a, b)), ITE(b >= c, S.true, Or(Le(a, b), Ge(a, c)))), (Tuple(Lt(a, b), Lt(c, a)), ITE(b > c, S.true, Or(Lt(a, b), Gt(a, c)))), (Tuple(Lt(c, a), Lt(a, b)), ITE(b > c, S.true, Or(Lt(a, b), Gt(a, c)))), (Tuple(Le(a, b), Lt(c, a)), ITE(b >= c, S.true, Or(Le(a, b), Gt(a, c)))), (Tuple(Le(c, a), Lt(a, b)), ITE(b >= c, S.true, Or(Lt(a, b), Ge(a, c)))), (Tuple(Lt(b, a), Lt(a, -b)), ITE(b >= 0, Gt(Abs(a), b), S.true)), (Tuple(Le(b, a), Le(a, -b)), ITE(b > 0, Ge(Abs(a), b), S.true)), ) return _matchers_or def _simplify_patterns_xor(): """ Two-term patterns for Xor.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_xor = (#(Tuple(Le(b, a), Lt(a, b)), S.true), #(Tuple(Lt(b, a), Le(a, b)), S.true), #(Tuple(Eq(a, b), Le(b, a)), Gt(a, b)), #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)), (Tuple(Eq(a, b), Le(a, b)), Lt(a, b)), (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)), (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)), (Tuple(Le(a, b), Le(b, a)), Ne(a, b)), (Tuple(Le(b, a), Ne(a, b)), Le(a, b)), # (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)), (Tuple(Lt(b, a), Ne(a, b)), Lt(a, b)), # (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)), # (Tuple(Le(a, b), Ne(a, b)), Ge(a, b)), # (Tuple(Lt(a, b), Ne(a, b)), Gt(a, b)), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, And(Gt(a, c), Lt(a, b)), And(Ge(a, b), Le(a, c)))), (Tuple(Lt(b, a), Lt(c, a)), And(Gt(a, Min(b, c)), Le(a, Max(b, c)))), (Tuple(Le(a, b), Le(a, c)), And(Le(a, Max(b, c)), Gt(a, Min(b, c)))), (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, And(Lt(a, c), Gt(a, b)), And(Le(a, b), Ge(a, c)))), (Tuple(Lt(a, b), Lt(a, c)), And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))), ) return _matchers_xor def simplify_univariate(expr): """return a simplified version of univariate boolean expression, else ``expr``""" from sympy.functions.elementary.piecewise import Piecewise from sympy.core.relational import Eq, Ne if not isinstance(expr, BooleanFunction): return expr if expr.atoms(Eq, Ne): return expr c = expr free = c.free_symbols if len(free) != 1: return c x = free.pop() ok, i = Piecewise((0, c), evaluate=False )._intervals(x, err_on_Eq=True) if not ok: return c if not i: return S.false args = [] for a, b, _, _ in i: if a is S.NegativeInfinity: if b is S.Infinity: c = S.true else: if c.subs(x, b) == True: c = (x <= b) else: c = (x < b) else: incl_a = (c.subs(x, a) == True) incl_b = (c.subs(x, b) == True) if incl_a and incl_b: if b.is_infinite: c = (x >= a) else: c = And(a <= x, x <= b) elif incl_a: c = And(a <= x, x < b) elif incl_b: if b.is_infinite: c = (x > a) else: c = And(a < x, x <= b) else: c = And(a < x, x < b) args.append(c) return Or(*args) # Classes corresponding to logic gates # Used in gateinputcount method BooleanGates = (And, Or, Xor, Nand, Nor, Not, Xnor, ITE) def gateinputcount(expr): """ Return the total number of inputs for the logic gates realizing the Boolean expression. Returns ======= int Number of gate inputs Note ==== Not all Boolean functions count as gate here, only those that are considered to be standard gates. These are: :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Xor`, :py:class:`~.Not`, and :py:class:`~.ITE` (multiplexer). :py:class:`~.Nand`, :py:class:`~.Nor`, and :py:class:`~.Xnor` will be evaluated to ``Not(And())`` etc. Examples ======== >>> from sympy.logic import And, Or, Nand, Not, gateinputcount >>> from sympy.abc import x, y, z >>> expr = And(x, y) >>> gateinputcount(expr) 2 >>> gateinputcount(Or(expr, z)) 4 Note that ``Nand`` is automatically evaluated to ``Not(And())`` so >>> gateinputcount(Nand(x, y, z)) 4 >>> gateinputcount(Not(And(x, y, z))) 4 Although this can be avoided by using ``evaluate=False`` >>> gateinputcount(Nand(x, y, z, evaluate=False)) 3 Also note that a comparison will count as a Boolean variable: >>> gateinputcount(And(x > z, y >= 2)) 2 As will a symbol: >>> gateinputcount(x) 0 """ if not isinstance(expr, Boolean): raise TypeError("Expression must be Boolean") if isinstance(expr, BooleanGates): return len(expr.args) + sum(gateinputcount(x) for x in expr.args) return 0
98c9cdb034f118aaa21b42404ec3385bd6f98e096169ccbebe6470d9a6688e06
from contextlib import contextmanager from threading import local from sympy.core.function import expand_mul class DotProdSimpState(local): def __init__(self): self.state = None _dotprodsimp_state = DotProdSimpState() @contextmanager def dotprodsimp(x): old = _dotprodsimp_state.state try: _dotprodsimp_state.state = x yield finally: _dotprodsimp_state.state = old def _dotprodsimp(expr, withsimp=False): """Wrapper for simplify.dotprodsimp to avoid circular imports.""" from sympy.simplify.simplify import dotprodsimp as dps return dps(expr, withsimp=withsimp) def _get_intermediate_simp(deffunc=lambda x: x, offfunc=lambda x: x, onfunc=_dotprodsimp, dotprodsimp=None): """Support function for controlling intermediate simplification. Returns a simplification function according to the global setting of dotprodsimp operation. ``deffunc`` - Function to be used by default. ``offfunc`` - Function to be used if dotprodsimp has been turned off. ``onfunc`` - Function to be used if dotprodsimp has been turned on. ``dotprodsimp`` - True, False or None. Will be overridden by global _dotprodsimp_state.state if that is not None. """ if dotprodsimp is False or _dotprodsimp_state.state is False: return offfunc if dotprodsimp is True or _dotprodsimp_state.state is True: return onfunc return deffunc # None, None def _get_intermediate_simp_bool(default=False, dotprodsimp=None): """Same as ``_get_intermediate_simp`` but returns bools instead of functions by default.""" return _get_intermediate_simp(default, False, True, dotprodsimp) def _iszero(x): """Returns True if x is zero.""" return getattr(x, 'is_zero', None) def _is_zero_after_expand_mul(x): """Tests by expand_mul only, suitable for polynomials and rational functions.""" return expand_mul(x) == 0 def _simplify(expr): """ Wrapper to avoid circular imports. """ from sympy.simplify.simplify import simplify return simplify(expr)
ed981479b1ef41a9c97630ef81e4a4c1702eda3dfa26d3637ddfaaf35610d984
import copy from sympy.core import S from sympy.core.function import expand_mul from sympy.functions.elementary.miscellaneous import Min, sqrt from sympy.functions.elementary.complexes import sign from .common import NonSquareMatrixError, NonPositiveDefiniteMatrixError from .utilities import _get_intermediate_simp, _iszero from .determinant import _find_reasonable_pivot_naive def _rank_decomposition(M, iszerofunc=_iszero, simplify=False): r"""Returns a pair of matrices (`C`, `F`) with matching rank such that `A = C F`. Parameters ========== iszerofunc : Function, optional A function used for detecting whether an element can act as a pivot. ``lambda x: x.is_zero`` is used by default. simplify : Bool or Function, optional A function used to simplify elements when looking for a pivot. By default SymPy's ``simplify`` is used. Returns ======= (C, F) : Matrices `C` and `F` are full-rank matrices with rank as same as `A`, whose product gives `A`. See Notes for additional mathematical details. Examples ======== >>> from sympy import Matrix >>> A = Matrix([ ... [1, 3, 1, 4], ... [2, 7, 3, 9], ... [1, 5, 3, 1], ... [1, 2, 0, 8] ... ]) >>> C, F = A.rank_decomposition() >>> C Matrix([ [1, 3, 4], [2, 7, 9], [1, 5, 1], [1, 2, 8]]) >>> F Matrix([ [1, 0, -2, 0], [0, 1, 1, 0], [0, 0, 0, 1]]) >>> C * F == A True Notes ===== Obtaining `F`, an RREF of `A`, is equivalent to creating a product .. math:: E_n E_{n-1} ... E_1 A = F where `E_n, E_{n-1}, \dots, E_1` are the elimination matrices or permutation matrices equivalent to each row-reduction step. The inverse of the same product of elimination matrices gives `C`: .. math:: C = \left(E_n E_{n-1} \dots E_1\right)^{-1} It is not necessary, however, to actually compute the inverse: the columns of `C` are those from the original matrix with the same column indices as the indices of the pivot columns of `F`. References ========== .. [1] https://en.wikipedia.org/wiki/Rank_factorization .. [2] Piziak, R.; Odell, P. L. (1 June 1999). "Full Rank Factorization of Matrices". Mathematics Magazine. 72 (3): 193. doi:10.2307/2690882 See Also ======== sympy.matrices.matrices.MatrixReductions.rref """ F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc, pivots=True) rank = len(pivot_cols) C = M.extract(range(M.rows), pivot_cols) F = F[:rank, :] return C, F def _liupc(M): """Liu's algorithm, for pre-determination of the Elimination Tree of the given matrix, used in row-based symbolic Cholesky factorization. Examples ======== >>> from sympy import SparseMatrix >>> S = SparseMatrix([ ... [1, 0, 3, 2], ... [0, 0, 1, 0], ... [4, 0, 0, 5], ... [0, 6, 7, 0]]) >>> S.liupc() ([[0], [], [0], [1, 2]], [4, 3, 4, 4]) References ========== .. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees, Jeroen Van Grondelle (1999) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582 """ # Algorithm 2.4, p 17 of reference # get the indices of the elements that are non-zero on or below diag R = [[] for r in range(M.rows)] for r, c, _ in M.row_list(): if c <= r: R[r].append(c) inf = len(R) # nothing will be this large parent = [inf]*M.rows virtual = [inf]*M.rows for r in range(M.rows): for c in R[r][:-1]: while virtual[c] < r: t = virtual[c] virtual[c] = r c = t if virtual[c] == inf: parent[c] = virtual[c] = r return R, parent def _row_structure_symbolic_cholesky(M): """Symbolic cholesky factorization, for pre-determination of the non-zero structure of the Cholesky factororization. Examples ======== >>> from sympy import SparseMatrix >>> S = SparseMatrix([ ... [1, 0, 3, 2], ... [0, 0, 1, 0], ... [4, 0, 0, 5], ... [0, 6, 7, 0]]) >>> S.row_structure_symbolic_cholesky() [[0], [], [0], [1, 2]] References ========== .. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees, Jeroen Van Grondelle (1999) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582 """ R, parent = M.liupc() inf = len(R) # this acts as infinity Lrow = copy.deepcopy(R) for k in range(M.rows): for j in R[k]: while j != inf and j != k: Lrow[k].append(j) j = parent[j] Lrow[k] = list(sorted(set(Lrow[k]))) return Lrow def _cholesky(M, hermitian=True): """Returns the Cholesky-type decomposition L of a matrix A such that L * L.H == A if hermitian flag is True, or L * L.T == A if hermitian is False. A must be a Hermitian positive-definite matrix if hermitian is True, or a symmetric matrix if it is False. Examples ======== >>> from sympy import Matrix >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> A.cholesky() Matrix([ [ 5, 0, 0], [ 3, 3, 0], [-1, 1, 3]]) >>> A.cholesky() * A.cholesky().T Matrix([ [25, 15, -5], [15, 18, 0], [-5, 0, 11]]) The matrix can have complex entries: >>> from sympy import I >>> A = Matrix(((9, 3*I), (-3*I, 5))) >>> A.cholesky() Matrix([ [ 3, 0], [-I, 2]]) >>> A.cholesky() * A.cholesky().H Matrix([ [ 9, 3*I], [-3*I, 5]]) Non-hermitian Cholesky-type decomposition may be useful when the matrix is not positive-definite. >>> A = Matrix([[1, 2], [2, 1]]) >>> L = A.cholesky(hermitian=False) >>> L Matrix([ [1, 0], [2, sqrt(3)*I]]) >>> L*L.T == A True See Also ======== sympy.matrices.dense.DenseMatrix.LDLdecomposition sympy.matrices.matrices.MatrixBase.LUdecomposition QRdecomposition """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") L = MutableDenseMatrix.zeros(M.rows, M.rows) if hermitian: for i in range(M.rows): for j in range(i): L[i, j] = ((1 / L[j, j])*(M[i, j] - sum(L[i, k]*L[j, k].conjugate() for k in range(j)))) Lii2 = (M[i, i] - sum(L[i, k]*L[i, k].conjugate() for k in range(i))) if Lii2.is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") L[i, i] = sqrt(Lii2) else: for i in range(M.rows): for j in range(i): L[i, j] = ((1 / L[j, j])*(M[i, j] - sum(L[i, k]*L[j, k] for k in range(j)))) L[i, i] = sqrt(M[i, i] - sum(L[i, k]**2 for k in range(i))) return M._new(L) def _cholesky_sparse(M, hermitian=True): """ Returns the Cholesky decomposition L of a matrix A such that L * L.T = A A must be a square, symmetric, positive-definite and non-singular matrix Examples ======== >>> from sympy import SparseMatrix >>> A = SparseMatrix(((25,15,-5),(15,18,0),(-5,0,11))) >>> A.cholesky() Matrix([ [ 5, 0, 0], [ 3, 3, 0], [-1, 1, 3]]) >>> A.cholesky() * A.cholesky().T == A True The matrix can have complex entries: >>> from sympy import I >>> A = SparseMatrix(((9, 3*I), (-3*I, 5))) >>> A.cholesky() Matrix([ [ 3, 0], [-I, 2]]) >>> A.cholesky() * A.cholesky().H Matrix([ [ 9, 3*I], [-3*I, 5]]) Non-hermitian Cholesky-type decomposition may be useful when the matrix is not positive-definite. >>> A = SparseMatrix([[1, 2], [2, 1]]) >>> L = A.cholesky(hermitian=False) >>> L Matrix([ [1, 0], [2, sqrt(3)*I]]) >>> L*L.T == A True See Also ======== sympy.matrices.sparse.SparseMatrix.LDLdecomposition sympy.matrices.matrices.MatrixBase.LUdecomposition QRdecomposition """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") dps = _get_intermediate_simp(expand_mul, expand_mul) Crowstruc = M.row_structure_symbolic_cholesky() C = MutableDenseMatrix.zeros(M.rows) for i in range(len(Crowstruc)): for j in Crowstruc[i]: if i != j: C[i, j] = M[i, j] summ = 0 for p1 in Crowstruc[i]: if p1 < j: for p2 in Crowstruc[j]: if p2 < j: if p1 == p2: if hermitian: summ += C[i, p1]*C[j, p1].conjugate() else: summ += C[i, p1]*C[j, p1] else: break else: break C[i, j] = dps((C[i, j] - summ) / C[j, j]) else: # i == j C[j, j] = M[j, j] summ = 0 for k in Crowstruc[j]: if k < j: if hermitian: summ += C[j, k]*C[j, k].conjugate() else: summ += C[j, k]**2 else: break Cjj2 = dps(C[j, j] - summ) if hermitian and Cjj2.is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") C[j, j] = sqrt(Cjj2) return M._new(C) def _LDLdecomposition(M, hermitian=True): """Returns the LDL Decomposition (L, D) of matrix A, such that L * D * L.H == A if hermitian flag is True, or L * D * L.T == A if hermitian is False. This method eliminates the use of square root. Further this ensures that all the diagonal entries of L are 1. A must be a Hermitian positive-definite matrix if hermitian is True, or a symmetric matrix otherwise. Examples ======== >>> from sympy import Matrix, eye >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0, 0], [ 3/5, 1, 0], [-1/5, 1/3, 1]]) >>> D Matrix([ [25, 0, 0], [ 0, 9, 0], [ 0, 0, 9]]) >>> L * D * L.T * A.inv() == eye(A.rows) True The matrix can have complex entries: >>> from sympy import I >>> A = Matrix(((9, 3*I), (-3*I, 5))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0], [-I/3, 1]]) >>> D Matrix([ [9, 0], [0, 4]]) >>> L*D*L.H == A True See Also ======== sympy.matrices.dense.DenseMatrix.cholesky sympy.matrices.matrices.MatrixBase.LUdecomposition QRdecomposition """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") D = MutableDenseMatrix.zeros(M.rows, M.rows) L = MutableDenseMatrix.eye(M.rows) if hermitian: for i in range(M.rows): for j in range(i): L[i, j] = (1 / D[j, j])*(M[i, j] - sum( L[i, k]*L[j, k].conjugate()*D[k, k] for k in range(j))) D[i, i] = (M[i, i] - sum(L[i, k]*L[i, k].conjugate()*D[k, k] for k in range(i))) if D[i, i].is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") else: for i in range(M.rows): for j in range(i): L[i, j] = (1 / D[j, j])*(M[i, j] - sum( L[i, k]*L[j, k]*D[k, k] for k in range(j))) D[i, i] = M[i, i] - sum(L[i, k]**2*D[k, k] for k in range(i)) return M._new(L), M._new(D) def _LDLdecomposition_sparse(M, hermitian=True): """ Returns the LDL Decomposition (matrices ``L`` and ``D``) of matrix ``A``, such that ``L * D * L.T == A``. ``A`` must be a square, symmetric, positive-definite and non-singular. This method eliminates the use of square root and ensures that all the diagonal entries of L are 1. Examples ======== >>> from sympy import SparseMatrix >>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0, 0], [ 3/5, 1, 0], [-1/5, 1/3, 1]]) >>> D Matrix([ [25, 0, 0], [ 0, 9, 0], [ 0, 0, 9]]) >>> L * D * L.T == A True """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") dps = _get_intermediate_simp(expand_mul, expand_mul) Lrowstruc = M.row_structure_symbolic_cholesky() L = MutableDenseMatrix.eye(M.rows) D = MutableDenseMatrix.zeros(M.rows, M.cols) for i in range(len(Lrowstruc)): for j in Lrowstruc[i]: if i != j: L[i, j] = M[i, j] summ = 0 for p1 in Lrowstruc[i]: if p1 < j: for p2 in Lrowstruc[j]: if p2 < j: if p1 == p2: if hermitian: summ += L[i, p1]*L[j, p1].conjugate()*D[p1, p1] else: summ += L[i, p1]*L[j, p1]*D[p1, p1] else: break else: break L[i, j] = dps((L[i, j] - summ) / D[j, j]) else: # i == j D[i, i] = M[i, i] summ = 0 for k in Lrowstruc[i]: if k < i: if hermitian: summ += L[i, k]*L[i, k].conjugate()*D[k, k] else: summ += L[i, k]**2*D[k, k] else: break D[i, i] = dps(D[i, i] - summ) if hermitian and D[i, i].is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") return M._new(L), M._new(D) def _LUdecomposition(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False): """Returns (L, U, perm) where L is a lower triangular matrix with unit diagonal, U is an upper triangular matrix, and perm is a list of row swap index pairs. If A is the original matrix, then ``A = (L*U).permuteBkwd(perm)``, and the row permutation matrix P such that $P A = L U$ can be computed by ``P = eye(A.rows).permuteFwd(perm)``. See documentation for LUCombined for details about the keyword argument rankcheck, iszerofunc, and simpfunc. Parameters ========== rankcheck : bool, optional Determines if this function should detect the rank deficiency of the matrixis and should raise a ``ValueError``. iszerofunc : function, optional A function which determines if a given expression is zero. The function should be a callable that takes a single SymPy expression and returns a 3-valued boolean value ``True``, ``False``, or ``None``. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. simpfunc : function or None, optional A function that simplifies the input. If this is specified as a function, this function should be a callable that takes a single SymPy expression and returns an another SymPy expression that is algebraically equivalent. If ``None``, it indicates that the pivot search algorithm should not attempt to simplify any candidate pivots. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[4, 3], [6, 3]]) >>> L, U, _ = a.LUdecomposition() >>> L Matrix([ [ 1, 0], [3/2, 1]]) >>> U Matrix([ [4, 3], [0, -3/2]]) See Also ======== sympy.matrices.dense.DenseMatrix.cholesky sympy.matrices.dense.DenseMatrix.LDLdecomposition QRdecomposition LUdecomposition_Simple LUdecompositionFF LUsolve """ combined, p = M.LUdecomposition_Simple(iszerofunc=iszerofunc, simpfunc=simpfunc, rankcheck=rankcheck) # L is lower triangular ``M.rows x M.rows`` # U is upper triangular ``M.rows x M.cols`` # L has unit diagonal. For each column in combined, the subcolumn # below the diagonal of combined is shared by L. # If L has more columns than combined, then the remaining subcolumns # below the diagonal of L are zero. # The upper triangular portion of L and combined are equal. def entry_L(i, j): if i < j: # Super diagonal entry return M.zero elif i == j: return M.one elif j < combined.cols: return combined[i, j] # Subdiagonal entry of L with no corresponding # entry in combined return M.zero def entry_U(i, j): return M.zero if i > j else combined[i, j] L = M._new(combined.rows, combined.rows, entry_L) U = M._new(combined.rows, combined.cols, entry_U) return L, U, p def _LUdecomposition_Simple(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False): r"""Compute the PLU decomposition of the matrix. Parameters ========== rankcheck : bool, optional Determines if this function should detect the rank deficiency of the matrixis and should raise a ``ValueError``. iszerofunc : function, optional A function which determines if a given expression is zero. The function should be a callable that takes a single SymPy expression and returns a 3-valued boolean value ``True``, ``False``, or ``None``. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. simpfunc : function or None, optional A function that simplifies the input. If this is specified as a function, this function should be a callable that takes a single SymPy expression and returns an another SymPy expression that is algebraically equivalent. If ``None``, it indicates that the pivot search algorithm should not attempt to simplify any candidate pivots. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. Returns ======= (lu, row_swaps) : (Matrix, list) If the original matrix is a $m, n$ matrix: *lu* is a $m, n$ matrix, which contains result of the decomposition in a compresed form. See the notes section to see how the matrix is compressed. *row_swaps* is a $m$-element list where each element is a pair of row exchange indices. ``A = (L*U).permute_backward(perm)``, and the row permutation matrix $P$ from the formula $P A = L U$ can be computed by ``P=eye(A.row).permute_forward(perm)``. Raises ====== ValueError Raised if ``rankcheck=True`` and the matrix is found to be rank deficient during the computation. Notes ===== About the PLU decomposition: PLU decomposition is a generalization of a LU decomposition which can be extended for rank-deficient matrices. It can further be generalized for non-square matrices, and this is the notation that SymPy is using. PLU decomposition is a decomposition of a $m, n$ matrix $A$ in the form of $P A = L U$ where * $L$ is a $m, m$ lower triangular matrix with unit diagonal entries. * $U$ is a $m, n$ upper triangular matrix. * $P$ is a $m, m$ permutation matrix. So, for a square matrix, the decomposition would look like: .. math:: L = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ L_{1, 0} & 1 & 0 & \cdots & 0 \\ L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 \end{bmatrix} .. math:: U = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ 0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & U_{n-1, n-1} \end{bmatrix} And for a matrix with more rows than the columns, the decomposition would look like: .. math:: L = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 & 0 & \cdots & 0 \\ L_{1, 0} & 1 & 0 & \cdots & 0 & 0 & \cdots & 0 \\ L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 & 0 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 & 0 & \cdots & 0 \\ L_{n, 0} & L_{n, 1} & L_{n, 2} & \cdots & L_{n, n-1} & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1} & 0 & \cdots & 1 \\ \end{bmatrix} .. math:: U = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ 0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & U_{n-1, n-1} \\ 0 & 0 & 0 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 0 \end{bmatrix} Finally, for a matrix with more columns than the rows, the decomposition would look like: .. math:: L = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ L_{1, 0} & 1 & 0 & \cdots & 0 \\ L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & 1 \end{bmatrix} .. math:: U = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1} & \cdots & U_{0, n-1} \\ 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1} & \cdots & U_{1, n-1} \\ 0 & 0 & U_{2, 2} & \cdots & U_{2, m-1} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots & \cdots & \vdots \\ 0 & 0 & 0 & \cdots & U_{m-1, m-1} & \cdots & U_{m-1, n-1} \\ \end{bmatrix} About the compressed LU storage: The results of the decomposition are often stored in compressed forms rather than returning $L$ and $U$ matrices individually. It may be less intiuitive, but it is commonly used for a lot of numeric libraries because of the efficiency. The storage matrix is defined as following for this specific method: * The subdiagonal elements of $L$ are stored in the subdiagonal portion of $LU$, that is $LU_{i, j} = L_{i, j}$ whenever $i > j$. * The elements on the diagonal of $L$ are all 1, and are not explicitly stored. * $U$ is stored in the upper triangular portion of $LU$, that is $LU_{i, j} = U_{i, j}$ whenever $i <= j$. * For a case of $m > n$, the right side of the $L$ matrix is trivial to store. * For a case of $m < n$, the below side of the $U$ matrix is trivial to store. So, for a square matrix, the compressed output matrix would be: .. math:: LU = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1} \end{bmatrix} For a matrix with more rows than the columns, the compressed output matrix would be: .. math:: LU = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1} \\ \end{bmatrix} For a matrix with more columns than the rows, the compressed output matrix would be: .. math:: LU = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1} & \cdots & U_{0, n-1} \\ L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1} & \cdots & U_{1, n-1} \\ L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, m-1} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots & \cdots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & U_{m-1, m-1} & \cdots & U_{m-1, n-1} \\ \end{bmatrix} About the pivot searching algorithm: When a matrix contains symbolic entries, the pivot search algorithm differs from the case where every entry can be categorized as zero or nonzero. The algorithm searches column by column through the submatrix whose top left entry coincides with the pivot position. If it exists, the pivot is the first entry in the current search column that iszerofunc guarantees is nonzero. If no such candidate exists, then each candidate pivot is simplified if simpfunc is not None. The search is repeated, with the difference that a candidate may be the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero. In the second search the pivot is the first candidate that iszerofunc can guarantee is nonzero. If no such candidate exists, then the pivot is the first candidate for which iszerofunc returns None. If no such candidate exists, then the search is repeated in the next column to the right. The pivot search algorithm differs from the one in ``rref()``, which relies on ``_find_reasonable_pivot()``. Future versions of ``LUdecomposition_simple()`` may use ``_find_reasonable_pivot()``. See Also ======== sympy.matrices.matrices.MatrixBase.LUdecomposition LUdecompositionFF LUsolve """ if rankcheck: # https://github.com/sympy/sympy/issues/9796 pass if S.Zero in M.shape: # Define LU decomposition of a matrix with no entries as a matrix # of the same dimensions with all zero entries. return M.zeros(M.rows, M.cols), [] dps = _get_intermediate_simp() lu = M.as_mutable() row_swaps = [] pivot_col = 0 for pivot_row in range(0, lu.rows - 1): # Search for pivot. Prefer entry that iszeropivot determines # is nonzero, over entry that iszeropivot cannot guarantee # is zero. # XXX ``_find_reasonable_pivot`` uses slow zero testing. Blocked by bug #10279 # Future versions of LUdecomposition_simple can pass iszerofunc and simpfunc # to _find_reasonable_pivot(). # In pass 3 of _find_reasonable_pivot(), the predicate in ``if x.equals(S.Zero):`` # calls sympy.simplify(), and not the simplification function passed in via # the keyword argument simpfunc. iszeropivot = True while pivot_col != M.cols and iszeropivot: sub_col = (lu[r, pivot_col] for r in range(pivot_row, M.rows)) pivot_row_offset, pivot_value, is_assumed_non_zero, ind_simplified_pairs =\ _find_reasonable_pivot_naive(sub_col, iszerofunc, simpfunc) iszeropivot = pivot_value is None if iszeropivot: # All candidate pivots in this column are zero. # Proceed to next column. pivot_col += 1 if rankcheck and pivot_col != pivot_row: # All entries including and below the pivot position are # zero, which indicates that the rank of the matrix is # strictly less than min(num rows, num cols) # Mimic behavior of previous implementation, by throwing a # ValueError. raise ValueError("Rank of matrix is strictly less than" " number of rows or columns." " Pass keyword argument" " rankcheck=False to compute" " the LU decomposition of this matrix.") candidate_pivot_row = None if pivot_row_offset is None else pivot_row + pivot_row_offset if candidate_pivot_row is None and iszeropivot: # If candidate_pivot_row is None and iszeropivot is True # after pivot search has completed, then the submatrix # below and to the right of (pivot_row, pivot_col) is # all zeros, indicating that Gaussian elimination is # complete. return lu, row_swaps # Update entries simplified during pivot search. for offset, val in ind_simplified_pairs: lu[pivot_row + offset, pivot_col] = val if pivot_row != candidate_pivot_row: # Row swap book keeping: # Record which rows were swapped. # Update stored portion of L factor by multiplying L on the # left and right with the current permutation. # Swap rows of U. row_swaps.append([pivot_row, candidate_pivot_row]) # Update L. lu[pivot_row, 0:pivot_row], lu[candidate_pivot_row, 0:pivot_row] = \ lu[candidate_pivot_row, 0:pivot_row], lu[pivot_row, 0:pivot_row] # Swap pivot row of U with candidate pivot row. lu[pivot_row, pivot_col:lu.cols], lu[candidate_pivot_row, pivot_col:lu.cols] = \ lu[candidate_pivot_row, pivot_col:lu.cols], lu[pivot_row, pivot_col:lu.cols] # Introduce zeros below the pivot by adding a multiple of the # pivot row to a row under it, and store the result in the # row under it. # Only entries in the target row whose index is greater than # start_col may be nonzero. start_col = pivot_col + 1 for row in range(pivot_row + 1, lu.rows): # Store factors of L in the subcolumn below # (pivot_row, pivot_row). lu[row, pivot_row] = \ dps(lu[row, pivot_col]/lu[pivot_row, pivot_col]) # Form the linear combination of the pivot row and the current # row below the pivot row that zeros the entries below the pivot. # Employing slicing instead of a loop here raises # NotImplementedError: Cannot add Zero to MutableSparseMatrix # in sympy/matrices/tests/test_sparse.py. # c = pivot_row + 1 if pivot_row == pivot_col else pivot_col for c in range(start_col, lu.cols): lu[row, c] = dps(lu[row, c] - lu[row, pivot_row]*lu[pivot_row, c]) if pivot_row != pivot_col: # matrix rank < min(num rows, num cols), # so factors of L are not stored directly below the pivot. # These entries are zero by construction, so don't bother # computing them. for row in range(pivot_row + 1, lu.rows): lu[row, pivot_col] = M.zero pivot_col += 1 if pivot_col == lu.cols: # All candidate pivots are zero implies that Gaussian # elimination is complete. return lu, row_swaps if rankcheck: if iszerofunc( lu[Min(lu.rows, lu.cols) - 1, Min(lu.rows, lu.cols) - 1]): raise ValueError("Rank of matrix is strictly less than" " number of rows or columns." " Pass keyword argument" " rankcheck=False to compute" " the LU decomposition of this matrix.") return lu, row_swaps def _LUdecompositionFF(M): """Compute a fraction-free LU decomposition. Returns 4 matrices P, L, D, U such that PA = L D**-1 U. If the elements of the matrix belong to some integral domain I, then all elements of L, D and U are guaranteed to belong to I. See Also ======== sympy.matrices.matrices.MatrixBase.LUdecomposition LUdecomposition_Simple LUsolve References ========== .. [1] W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms for LU and QR factors". Frontiers in Computer Science in China, Vol 2, no. 1, pp. 67-80, 2008. """ from sympy.matrices import SparseMatrix zeros = SparseMatrix.zeros eye = SparseMatrix.eye n, m = M.rows, M.cols U, L, P = M.as_mutable(), eye(n), eye(n) DD = zeros(n, n) oldpivot = 1 for k in range(n - 1): if U[k, k] == 0: for kpivot in range(k + 1, n): if U[kpivot, k]: break else: raise ValueError("Matrix is not full rank") U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:] L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k] P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :] L [k, k] = Ukk = U[k, k] DD[k, k] = oldpivot * Ukk for i in range(k + 1, n): L[i, k] = Uik = U[i, k] for j in range(k + 1, m): U[i, j] = (Ukk * U[i, j] - U[k, j] * Uik) / oldpivot U[i, k] = 0 oldpivot = Ukk DD[n - 1, n - 1] = oldpivot return P, L, DD, U def _singular_value_decomposition(A): r"""Returns a Condensed Singular Value decomposition. Explanation =========== A Singular Value decomposition is a decomposition in the form $A = U \Sigma V$ where - $U, V$ are column orthogonal matrix. - $\Sigma$ is a diagonal matrix, where the main diagonal contains singular values of matrix A. A column orthogonal matrix satisfies $\mathbb{I} = U^H U$ while a full orthogonal matrix satisfies relation $\mathbb{I} = U U^H = U^H U$ where $\mathbb{I}$ is an identity matrix with matching dimensions. For matrices which are not square or are rank-deficient, it is sufficient to return a column orthogonal matrix because augmenting them may introduce redundant computations. In condensed Singular Value Decomposition we only return column orthognal matrices because of this reason If you want to augment the results to return a full orthogonal decomposition, you should use the following procedures. - Augment the $U, V$ matrices with columns that are orthogonal to every other columns and make it square. - Augument the $\Sigma$ matrix with zero rows to make it have the same shape as the original matrix. The procedure will be illustrated in the examples section. Examples ======== we take a full rank matrix first: >>> from sympy import Matrix >>> A = Matrix([[1, 2],[2,1]]) >>> U, S, V = A.singular_value_decomposition() >>> U Matrix([ [ sqrt(2)/2, sqrt(2)/2], [-sqrt(2)/2, sqrt(2)/2]]) >>> S Matrix([ [1, 0], [0, 3]]) >>> V Matrix([ [-sqrt(2)/2, sqrt(2)/2], [ sqrt(2)/2, sqrt(2)/2]]) If a matrix if square and full rank both U, V are orthogonal in both directions >>> U * U.H Matrix([ [1, 0], [0, 1]]) >>> U.H * U Matrix([ [1, 0], [0, 1]]) >>> V * V.H Matrix([ [1, 0], [0, 1]]) >>> V.H * V Matrix([ [1, 0], [0, 1]]) >>> A == U * S * V.H True >>> C = Matrix([ ... [1, 0, 0, 0, 2], ... [0, 0, 3, 0, 0], ... [0, 0, 0, 0, 0], ... [0, 2, 0, 0, 0], ... ]) >>> U, S, V = C.singular_value_decomposition() >>> V.H * V Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> V * V.H Matrix([ [1/5, 0, 0, 0, 2/5], [ 0, 1, 0, 0, 0], [ 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 0], [2/5, 0, 0, 0, 4/5]]) If you want to augment the results to be a full orthogonal decomposition, you should augment $V$ with an another orthogonal column. You are able to append an arbitrary standard basis that are linearly independent to every other columns and you can run the Gram-Schmidt process to make them augmented as orthogonal basis. >>> V_aug = V.row_join(Matrix([[0,0,0,0,1], ... [0,0,0,1,0]]).H) >>> V_aug = V_aug.QRdecomposition()[0] >>> V_aug Matrix([ [0, sqrt(5)/5, 0, -2*sqrt(5)/5, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 2*sqrt(5)/5, 0, sqrt(5)/5, 0]]) >>> V_aug.H * V_aug Matrix([ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) >>> V_aug * V_aug.H Matrix([ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) Similarly we augment U >>> U_aug = U.row_join(Matrix([0,0,1,0])) >>> U_aug = U_aug.QRdecomposition()[0] >>> U_aug Matrix([ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) >>> U_aug.H * U_aug Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) >>> U_aug * U_aug.H Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) We add 2 zero columns and one row to S >>> S_aug = S.col_join(Matrix([[0,0,0]])) >>> S_aug = S_aug.row_join(Matrix([[0,0,0,0], ... [0,0,0,0]]).H) >>> S_aug Matrix([ [2, 0, 0, 0, 0], [0, sqrt(5), 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0]]) >>> U_aug * S_aug * V_aug.H == C True """ AH = A.H m, n = A.shape if m >= n: V, S = (AH * A).diagonalize() ranked = [] for i, x in enumerate(S.diagonal()): if not x.is_zero: ranked.append(i) V = V[:, ranked] Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked] S = S.zeros(len(Singular_vals)) for i in range(len(Singular_vals)): S[i, i] = Singular_vals[i] V, _ = V.QRdecomposition() U = A * V * S.inv() else: U, S = (A * AH).diagonalize() ranked = [] for i, x in enumerate(S.diagonal()): if not x.is_zero: ranked.append(i) U = U[:, ranked] Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked] S = S.zeros(len(Singular_vals)) for i in range(len(Singular_vals)): S[i, i] = Singular_vals[i] U, _ = U.QRdecomposition() V = AH * U * S.inv() return U, S, V def _QRdecomposition_optional(M, normalize=True): def dot(u, v): return u.dot(v, hermitian=True) dps = _get_intermediate_simp(expand_mul, expand_mul) A = M.as_mutable() ranked = list() Q = A R = A.zeros(A.cols) for j in range(A.cols): for i in range(j): if Q[:, i].is_zero_matrix: continue R[i, j] = dot(Q[:, i], Q[:, j]) / dot(Q[:, i], Q[:, i]) R[i, j] = dps(R[i, j]) Q[:, j] -= Q[:, i] * R[i, j] Q[:, j] = dps(Q[:, j]) if Q[:, j].is_zero_matrix is False: ranked.append(j) R[j, j] = M.one Q = Q.extract(range(Q.rows), ranked) R = R.extract(ranked, range(R.cols)) if normalize: # Normalization for i in range(Q.cols): norm = Q[:, i].norm() Q[:, i] /= norm R[i, :] *= norm return M.__class__(Q), M.__class__(R) def _QRdecomposition(M): r"""Returns a QR decomposition. Explanation =========== A QR decomposition is a decomposition in the form $A = Q R$ where - $Q$ is a column orthogonal matrix. - $R$ is a upper triangular (trapezoidal) matrix. A column orthogonal matrix satisfies $\mathbb{I} = Q^H Q$ while a full orthogonal matrix satisfies relation $\mathbb{I} = Q Q^H = Q^H Q$ where $I$ is an identity matrix with matching dimensions. For matrices which are not square or are rank-deficient, it is sufficient to return a column orthogonal matrix because augmenting them may introduce redundant computations. And an another advantage of this is that you can easily inspect the matrix rank by counting the number of columns of $Q$. If you want to augment the results to return a full orthogonal decomposition, you should use the following procedures. - Augment the $Q$ matrix with columns that are orthogonal to every other columns and make it square. - Augument the $R$ matrix with zero rows to make it have the same shape as the original matrix. The procedure will be illustrated in the examples section. Examples ======== A full rank matrix example: >>> from sympy import Matrix >>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]]) >>> Q, R = A.QRdecomposition() >>> Q Matrix([ [ 6/7, -69/175, -58/175], [ 3/7, 158/175, 6/175], [-2/7, 6/35, -33/35]]) >>> R Matrix([ [14, 21, -14], [ 0, 175, -70], [ 0, 0, 35]]) If the matrix is square and full rank, the $Q$ matrix becomes orthogonal in both directions, and needs no augmentation. >>> Q * Q.H Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> Q.H * Q Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> A == Q*R True A rank deficient matrix example: >>> A = Matrix([[12, -51, 0], [6, 167, 0], [-4, 24, 0]]) >>> Q, R = A.QRdecomposition() >>> Q Matrix([ [ 6/7, -69/175], [ 3/7, 158/175], [-2/7, 6/35]]) >>> R Matrix([ [14, 21, 0], [ 0, 175, 0]]) QRdecomposition might return a matrix Q that is rectangular. In this case the orthogonality condition might be satisfied as $\mathbb{I} = Q.H*Q$ but not in the reversed product $\mathbb{I} = Q * Q.H$. >>> Q.H * Q Matrix([ [1, 0], [0, 1]]) >>> Q * Q.H Matrix([ [27261/30625, 348/30625, -1914/6125], [ 348/30625, 30589/30625, 198/6125], [ -1914/6125, 198/6125, 136/1225]]) If you want to augment the results to be a full orthogonal decomposition, you should augment $Q$ with an another orthogonal column. You are able to append an arbitrary standard basis that are linearly independent to every other columns and you can run the Gram-Schmidt process to make them augmented as orthogonal basis. >>> Q_aug = Q.row_join(Matrix([0, 0, 1])) >>> Q_aug = Q_aug.QRdecomposition()[0] >>> Q_aug Matrix([ [ 6/7, -69/175, 58/175], [ 3/7, 158/175, -6/175], [-2/7, 6/35, 33/35]]) >>> Q_aug.H * Q_aug Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> Q_aug * Q_aug.H Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) Augmenting the $R$ matrix with zero row is straightforward. >>> R_aug = R.col_join(Matrix([[0, 0, 0]])) >>> R_aug Matrix([ [14, 21, 0], [ 0, 175, 0], [ 0, 0, 0]]) >>> Q_aug * R_aug == A True A zero matrix example: >>> from sympy import Matrix >>> A = Matrix.zeros(3, 4) >>> Q, R = A.QRdecomposition() They may return matrices with zero rows and columns. >>> Q Matrix(3, 0, []) >>> R Matrix(0, 4, []) >>> Q*R Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) As the same augmentation rule described above, $Q$ can be augmented with columns of an identity matrix and $R$ can be augmented with rows of a zero matrix. >>> Q_aug = Q.row_join(Matrix.eye(3)) >>> R_aug = R.col_join(Matrix.zeros(3, 4)) >>> Q_aug * Q_aug.T Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> R_aug Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> Q_aug * R_aug == A True See Also ======== sympy.matrices.dense.DenseMatrix.cholesky sympy.matrices.dense.DenseMatrix.LDLdecomposition sympy.matrices.matrices.MatrixBase.LUdecomposition QRsolve """ return _QRdecomposition_optional(M, normalize=True) def _upper_hessenberg_decomposition(A): """Converts a matrix into Hessenberg matrix H Returns 2 matrices H, P s.t. $P H P^{T} = A$, where H is an upper hessenberg matrix and P is an orthogonal matrix Examples ======== >>> from sympy import Matrix >>> A = Matrix([ ... [1,2,3], ... [-3,5,6], ... [4,-8,9], ... ]) >>> H, P = A.upper_hessenberg_decomposition() >>> H Matrix([ [1, 6/5, 17/5], [5, 213/25, -134/25], [0, 216/25, 137/25]]) >>> P Matrix([ [1, 0, 0], [0, -3/5, 4/5], [0, 4/5, 3/5]]) >>> P * H * P.H == A True References ========== .. [#] https://mathworld.wolfram.com/HessenbergDecomposition.html """ M = A.as_mutable() if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") n = M.cols P = M.eye(n) H = M for j in range(n - 2): u = H[j + 1:, j] if u[1:, :].is_zero_matrix: continue if sign(u[0]) != 0: u[0] = u[0] + sign(u[0]) * u.norm() else: u[0] = u[0] + u.norm() v = u / u.norm() H[j + 1:, :] = H[j + 1:, :] - 2 * v * (v.H * H[j + 1:, :]) H[:, j + 1:] = H[:, j + 1:] - (H[:, j + 1:] * (2 * v)) * v.H P[:, j + 1:] = P[:, j + 1:] - (P[:, j + 1:] * (2 * v)) * v.H return H, P
bf06fa6dddab3dc01a0f9cd2cb00b2ee2bf4314dac4cadb372a50b57e5734873
from types import FunctionType from sympy.core.numbers import Float, Integer from sympy.core.singleton import S from sympy.core.symbol import uniquely_named_symbol from sympy.core.mul import Mul from sympy.polys import PurePoly, cancel from sympy.core.sympify import sympify from sympy.functions.combinatorial.numbers import nC from sympy.polys.matrices.domainmatrix import DomainMatrix from .common import NonSquareMatrixError from .utilities import ( _get_intermediate_simp, _get_intermediate_simp_bool, _iszero, _is_zero_after_expand_mul, _dotprodsimp, _simplify) def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify): """ Find the lowest index of an item in ``col`` that is suitable for a pivot. If ``col`` consists only of Floats, the pivot with the largest norm is returned. Otherwise, the first element where ``iszerofunc`` returns False is used. If ``iszerofunc`` does not return false, items are simplified and retested until a suitable pivot is found. Returns a 4-tuple (pivot_offset, pivot_val, assumed_nonzero, newly_determined) where pivot_offset is the index of the pivot, pivot_val is the (possibly simplified) value of the pivot, assumed_nonzero is True if an assumption that the pivot was non-zero was made without being proved, and newly_determined are elements that were simplified during the process of pivot finding.""" newly_determined = [] col = list(col) # a column that contains a mix of floats and integers # but at least one float is considered a numerical # column, and so we do partial pivoting if all(isinstance(x, (Float, Integer)) for x in col) and any( isinstance(x, Float) for x in col): col_abs = [abs(x) for x in col] max_value = max(col_abs) if iszerofunc(max_value): # just because iszerofunc returned True, doesn't # mean the value is numerically zero. Make sure # to replace all entries with numerical zeros if max_value != 0: newly_determined = [(i, 0) for i, x in enumerate(col) if x != 0] return (None, None, False, newly_determined) index = col_abs.index(max_value) return (index, col[index], False, newly_determined) # PASS 1 (iszerofunc directly) possible_zeros = [] for i, x in enumerate(col): is_zero = iszerofunc(x) # is someone wrote a custom iszerofunc, it may return # BooleanFalse or BooleanTrue instead of True or False, # so use == for comparison instead of `is` if is_zero == False: # we found something that is definitely not zero return (i, x, False, newly_determined) possible_zeros.append(is_zero) # by this point, we've found no certain non-zeros if all(possible_zeros): # if everything is definitely zero, we have # no pivot return (None, None, False, newly_determined) # PASS 2 (iszerofunc after simplify) # we haven't found any for-sure non-zeros, so # go through the elements iszerofunc couldn't # make a determination about and opportunistically # simplify to see if we find something for i, x in enumerate(col): if possible_zeros[i] is not None: continue simped = simpfunc(x) is_zero = iszerofunc(simped) if is_zero in (True, False): newly_determined.append((i, simped)) if is_zero == False: return (i, simped, False, newly_determined) possible_zeros[i] = is_zero # after simplifying, some things that were recognized # as zeros might be zeros if all(possible_zeros): # if everything is definitely zero, we have # no pivot return (None, None, False, newly_determined) # PASS 3 (.equals(0)) # some expressions fail to simplify to zero, but # ``.equals(0)`` evaluates to True. As a last-ditch # attempt, apply ``.equals`` to these expressions for i, x in enumerate(col): if possible_zeros[i] is not None: continue if x.equals(S.Zero): # ``.iszero`` may return False with # an implicit assumption (e.g., ``x.equals(0)`` # when ``x`` is a symbol), so only treat it # as proved when ``.equals(0)`` returns True possible_zeros[i] = True newly_determined.append((i, S.Zero)) if all(possible_zeros): return (None, None, False, newly_determined) # at this point there is nothing that could definitely # be a pivot. To maintain compatibility with existing # behavior, we'll assume that an illdetermined thing is # non-zero. We should probably raise a warning in this case i = possible_zeros.index(None) return (i, col[i], True, newly_determined) def _find_reasonable_pivot_naive(col, iszerofunc=_iszero, simpfunc=None): """ Helper that computes the pivot value and location from a sequence of contiguous matrix column elements. As a side effect of the pivot search, this function may simplify some of the elements of the input column. A list of these simplified entries and their indices are also returned. This function mimics the behavior of _find_reasonable_pivot(), but does less work trying to determine if an indeterminate candidate pivot simplifies to zero. This more naive approach can be much faster, with the trade-off that it may erroneously return a pivot that is zero. ``col`` is a sequence of contiguous column entries to be searched for a suitable pivot. ``iszerofunc`` is a callable that returns a Boolean that indicates if its input is zero, or None if no such determination can be made. ``simpfunc`` is a callable that simplifies its input. It must return its input if it does not simplify its input. Passing in ``simpfunc=None`` indicates that the pivot search should not attempt to simplify any candidate pivots. Returns a 4-tuple: (pivot_offset, pivot_val, assumed_nonzero, newly_determined) ``pivot_offset`` is the sequence index of the pivot. ``pivot_val`` is the value of the pivot. pivot_val and col[pivot_index] are equivalent, but will be different when col[pivot_index] was simplified during the pivot search. ``assumed_nonzero`` is a boolean indicating if the pivot cannot be guaranteed to be zero. If assumed_nonzero is true, then the pivot may or may not be non-zero. If assumed_nonzero is false, then the pivot is non-zero. ``newly_determined`` is a list of index-value pairs of pivot candidates that were simplified during the pivot search. """ # indeterminates holds the index-value pairs of each pivot candidate # that is neither zero or non-zero, as determined by iszerofunc(). # If iszerofunc() indicates that a candidate pivot is guaranteed # non-zero, or that every candidate pivot is zero then the contents # of indeterminates are unused. # Otherwise, the only viable candidate pivots are symbolic. # In this case, indeterminates will have at least one entry, # and all but the first entry are ignored when simpfunc is None. indeterminates = [] for i, col_val in enumerate(col): col_val_is_zero = iszerofunc(col_val) if col_val_is_zero == False: # This pivot candidate is non-zero. return i, col_val, False, [] elif col_val_is_zero is None: # The candidate pivot's comparison with zero # is indeterminate. indeterminates.append((i, col_val)) if len(indeterminates) == 0: # All candidate pivots are guaranteed to be zero, i.e. there is # no pivot. return None, None, False, [] if simpfunc is None: # Caller did not pass in a simplification function that might # determine if an indeterminate pivot candidate is guaranteed # to be nonzero, so assume the first indeterminate candidate # is non-zero. return indeterminates[0][0], indeterminates[0][1], True, [] # newly_determined holds index-value pairs of candidate pivots # that were simplified during the search for a non-zero pivot. newly_determined = [] for i, col_val in indeterminates: tmp_col_val = simpfunc(col_val) if id(col_val) != id(tmp_col_val): # simpfunc() simplified this candidate pivot. newly_determined.append((i, tmp_col_val)) if iszerofunc(tmp_col_val) == False: # Candidate pivot simplified to a guaranteed non-zero value. return i, tmp_col_val, False, newly_determined return indeterminates[0][0], indeterminates[0][1], True, newly_determined # This functions is a candidate for caching if it gets implemented for matrices. def _berkowitz_toeplitz_matrix(M): """Return (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm corresponding to ``M`` and A is the first principal submatrix. """ # the 0 x 0 case is trivial if M.rows == 0 and M.cols == 0: return M._new(1,1, [M.one]) # # Partition M = [ a_11 R ] # [ C A ] # a, R = M[0,0], M[0, 1:] C, A = M[1:, 0], M[1:,1:] # # The Toeplitz matrix looks like # # [ 1 ] # [ -a 1 ] # [ -RC -a 1 ] # [ -RAC -RC -a 1 ] # [ -RA**2C -RAC -RC -a 1 ] # etc. # Compute the diagonal entries. # Because multiplying matrix times vector is so much # more efficient than matrix times matrix, recursively # compute -R * A**n * C. diags = [C] for i in range(M.rows - 2): diags.append(A.multiply(diags[i], dotprodsimp=None)) diags = [(-R).multiply(d, dotprodsimp=None)[0, 0] for d in diags] diags = [M.one, -a] + diags def entry(i,j): if j > i: return M.zero return diags[i - j] toeplitz = M._new(M.cols + 1, M.rows, entry) return (A, toeplitz) # This functions is a candidate for caching if it gets implemented for matrices. def _berkowitz_vector(M): """ Run the Berkowitz algorithm and return a vector whose entries are the coefficients of the characteristic polynomial of ``M``. Given N x N matrix, efficiently compute coefficients of characteristic polynomials of ``M`` without division in the ground domain. This method is particularly useful for computing determinant, principal minors and characteristic polynomial when ``M`` has complicated coefficients e.g. polynomials. Semi-direct usage of this algorithm is also important in computing efficiently sub-resultant PRS. Assuming that M is a square matrix of dimension N x N and I is N x N identity matrix, then the Berkowitz vector is an N x 1 vector whose entries are coefficients of the polynomial charpoly(M) = det(t*I - M) As a consequence, all polynomials generated by Berkowitz algorithm are monic. For more information on the implemented algorithm refer to: [1] S.J. Berkowitz, On computing the determinant in small parallel time using a small number of processors, ACM, Information Processing Letters 18, 1984, pp. 147-150 [2] M. Keber, Division-Free computation of sub-resultants using Bezout matrices, Tech. Report MPI-I-2006-1-006, Saarbrucken, 2006 """ # handle the trivial cases if M.rows == 0 and M.cols == 0: return M._new(1, 1, [M.one]) elif M.rows == 1 and M.cols == 1: return M._new(2, 1, [M.one, -M[0,0]]) submat, toeplitz = _berkowitz_toeplitz_matrix(M) return toeplitz.multiply(_berkowitz_vector(submat), dotprodsimp=None) def _adjugate(M, method="berkowitz"): """Returns the adjugate, or classical adjoint, of a matrix. That is, the transpose of the matrix of cofactors. https://en.wikipedia.org/wiki/Adjugate Parameters ========== method : string, optional Method to use to find the cofactors, can be "bareiss", "berkowitz" or "lu". Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2], [3, 4]]) >>> M.adjugate() Matrix([ [ 4, -2], [-3, 1]]) See Also ======== cofactor_matrix sympy.matrices.common.MatrixCommon.transpose """ return M.cofactor_matrix(method=method).transpose() # This functions is a candidate for caching if it gets implemented for matrices. def _charpoly(M, x='lambda', simplify=_simplify): """Computes characteristic polynomial det(x*I - M) where I is the identity matrix. A PurePoly is returned, so using different variables for ``x`` does not affect the comparison or the polynomials: Parameters ========== x : string, optional Name for the "lambda" variable, defaults to "lambda". simplify : function, optional Simplification function to use on the characteristic polynomial calculated. Defaults to ``simplify``. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[1, 3], [2, 0]]) >>> M.charpoly() PurePoly(lambda**2 - lambda - 6, lambda, domain='ZZ') >>> M.charpoly(x) == M.charpoly(y) True >>> M.charpoly(x) == M.charpoly(y) True Specifying ``x`` is optional; a symbol named ``lambda`` is used by default (which looks good when pretty-printed in unicode): >>> M.charpoly().as_expr() lambda**2 - lambda - 6 And if ``x`` clashes with an existing symbol, underscores will be prepended to the name to make it unique: >>> M = Matrix([[1, 2], [x, 0]]) >>> M.charpoly(x).as_expr() _x**2 - _x - 2*x Whether you pass a symbol or not, the generator can be obtained with the gen attribute since it may not be the same as the symbol that was passed: >>> M.charpoly(x).gen _x >>> M.charpoly(x).gen == x False Notes ===== The Samuelson-Berkowitz algorithm is used to compute the characteristic polynomial efficiently and without any division operations. Thus the characteristic polynomial over any commutative ring without zero divisors can be computed. If the determinant det(x*I - M) can be found out easily as in the case of an upper or a lower triangular matrix, then instead of Samuelson-Berkowitz algorithm, eigenvalues are computed and the characteristic polynomial with their help. See Also ======== det """ if not M.is_square: raise NonSquareMatrixError() if M.is_lower or M.is_upper: diagonal_elements = M.diagonal() x = uniquely_named_symbol(x, diagonal_elements, modify=lambda s: '_' + s) m = 1 for i in diagonal_elements: m = m * (x - simplify(i)) return PurePoly(m, x) berk_vector = _berkowitz_vector(M) x = uniquely_named_symbol(x, berk_vector, modify=lambda s: '_' + s) return PurePoly([simplify(a) for a in berk_vector], x) def _cofactor(M, i, j, method="berkowitz"): """Calculate the cofactor of an element. Parameters ========== method : string, optional Method to use to find the cofactors, can be "bareiss", "berkowitz" or "lu". Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2], [3, 4]]) >>> M.cofactor(0, 1) -3 See Also ======== cofactor_matrix minor minor_submatrix """ if not M.is_square or M.rows < 1: raise NonSquareMatrixError() return S.NegativeOne**((i + j) % 2) * M.minor(i, j, method) def _cofactor_matrix(M, method="berkowitz"): """Return a matrix containing the cofactor of each element. Parameters ========== method : string, optional Method to use to find the cofactors, can be "bareiss", "berkowitz" or "lu". Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2], [3, 4]]) >>> M.cofactor_matrix() Matrix([ [ 4, -3], [-2, 1]]) See Also ======== cofactor minor minor_submatrix """ if not M.is_square or M.rows < 1: raise NonSquareMatrixError() return M._new(M.rows, M.cols, lambda i, j: M.cofactor(i, j, method)) def _per(M): """Returns the permanent of a matrix. Unlike determinant, permanent is defined for both square and non-square matrices. For an m x n matrix, with m less than or equal to n, it is given as the sum over the permutations s of size less than or equal to m on [1, 2, . . . n] of the product from i = 1 to m of M[i, s[i]]. Taking the transpose will not affect the value of the permanent. In the case of a square matrix, this is the same as the permutation definition of the determinant, but it does not take the sign of the permutation into account. Computing the permanent with this definition is quite inefficient, so here the Ryser formula is used. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> M.per() 450 >>> M = Matrix([1, 5, 7]) >>> M.per() 13 References ========== .. [1] Prof. Frank Ben's notes: https://math.berkeley.edu/~bernd/ban275.pdf .. [2] Wikipedia article on Permanent: https://en.wikipedia.org/wiki/Permanent_(mathematics) .. [3] https://reference.wolfram.com/language/ref/Permanent.html .. [4] Permanent of a rectangular matrix : https://arxiv.org/pdf/0904.3251.pdf """ import itertools m, n = M.shape if m > n: M = M.T m, n = n, m s = list(range(n)) subsets = [] for i in range(1, m + 1): subsets += list(map(list, itertools.combinations(s, i))) perm = 0 for subset in subsets: prod = 1 sub_len = len(subset) for i in range(m): prod *= sum([M[i, j] for j in subset]) perm += prod * S.NegativeOne**sub_len * nC(n - sub_len, m - sub_len) perm *= S.NegativeOne**m perm = sympify(perm) return perm.simplify() def _det_DOM(M): DOM = DomainMatrix.from_Matrix(M, field=True, extension=True) K = DOM.domain return K.to_sympy(DOM.det()) # This functions is a candidate for caching if it gets implemented for matrices. def _det(M, method="bareiss", iszerofunc=None): """Computes the determinant of a matrix if ``M`` is a concrete matrix object otherwise return an expressions ``Determinant(M)`` if ``M`` is a ``MatrixSymbol`` or other expression. Parameters ========== method : string, optional Specifies the algorithm used for computing the matrix determinant. If the matrix is at most 3x3, a hard-coded formula is used and the specified method is ignored. Otherwise, it defaults to ``'bareiss'``. Also, if the matrix is an upper or a lower triangular matrix, determinant is computed by simple multiplication of diagonal elements, and the specified method is ignored. If it is set to ``'domain-ge'``, then Gaussian elimination method will be used via using DomainMatrix. If it is set to ``'bareiss'``, Bareiss' fraction-free algorithm will be used. If it is set to ``'berkowitz'``, Berkowitz' algorithm will be used. Otherwise, if it is set to ``'lu'``, LU decomposition will be used. .. note:: For backward compatibility, legacy keys like "bareis" and "det_lu" can still be used to indicate the corresponding methods. And the keys are also case-insensitive for now. However, it is suggested to use the precise keys for specifying the method. iszerofunc : FunctionType or None, optional If it is set to ``None``, it will be defaulted to ``_iszero`` if the method is set to ``'bareiss'``, and ``_is_zero_after_expand_mul`` if the method is set to ``'lu'``. It can also accept any user-specified zero testing function, if it is formatted as a function which accepts a single symbolic argument and returns ``True`` if it is tested as zero and ``False`` if it tested as non-zero, and also ``None`` if it is undecidable. Returns ======= det : Basic Result of determinant. Raises ====== ValueError If unrecognized keys are given for ``method`` or ``iszerofunc``. NonSquareMatrixError If attempted to calculate determinant from a non-square matrix. Examples ======== >>> from sympy import Matrix, eye, det >>> I3 = eye(3) >>> det(I3) 1 >>> M = Matrix([[1, 2], [3, 4]]) >>> det(M) -2 >>> det(M) == M.det() True >>> M.det(method="domain-ge") -2 """ # sanitize `method` method = method.lower() if method == "bareis": method = "bareiss" elif method == "det_lu": method = "lu" if method not in ("bareiss", "berkowitz", "lu", "domain-ge"): raise ValueError("Determinant method '%s' unrecognized" % method) if iszerofunc is None: if method == "bareiss": iszerofunc = _is_zero_after_expand_mul elif method == "lu": iszerofunc = _iszero elif not isinstance(iszerofunc, FunctionType): raise ValueError("Zero testing method '%s' unrecognized" % iszerofunc) n = M.rows if n == M.cols: # square check is done in individual method functions if n == 0: return M.one elif n == 1: return M[0, 0] elif n == 2: m = M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0] return _get_intermediate_simp(_dotprodsimp)(m) elif n == 3: m = (M[0, 0] * M[1, 1] * M[2, 2] + M[0, 1] * M[1, 2] * M[2, 0] + M[0, 2] * M[1, 0] * M[2, 1] - M[0, 2] * M[1, 1] * M[2, 0] - M[0, 0] * M[1, 2] * M[2, 1] - M[0, 1] * M[1, 0] * M[2, 2]) return _get_intermediate_simp(_dotprodsimp)(m) dets = [] for b in M.strongly_connected_components(): if method == "domain-ge": # uses DomainMatrix to evalute determinant det = _det_DOM(M[b, b]) elif method == "bareiss": det = M[b, b]._eval_det_bareiss(iszerofunc=iszerofunc) elif method == "berkowitz": det = M[b, b]._eval_det_berkowitz() elif method == "lu": det = M[b, b]._eval_det_lu(iszerofunc=iszerofunc) dets.append(det) return Mul(*dets) # This functions is a candidate for caching if it gets implemented for matrices. def _det_bareiss(M, iszerofunc=_is_zero_after_expand_mul): """Compute matrix determinant using Bareiss' fraction-free algorithm which is an extension of the well known Gaussian elimination method. This approach is best suited for dense symbolic matrices and will result in a determinant with minimal number of fractions. It means that less term rewriting is needed on resulting formulae. Parameters ========== iszerofunc : function, optional The function to use to determine zeros when doing an LU decomposition. Defaults to ``lambda x: x.is_zero``. TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. """ # Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's # thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf def bareiss(mat, cumm=1): if mat.rows == 0: return mat.one elif mat.rows == 1: return mat[0, 0] # find a pivot and extract the remaining matrix # With the default iszerofunc, _find_reasonable_pivot slows down # the computation by the factor of 2.5 in one test. # Relevant issues: #10279 and #13877. pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc) if pivot_pos is None: return mat.zero # if we have a valid pivot, we'll do a "row swap", so keep the # sign of the det sign = (-1) ** (pivot_pos % 2) # we want every row but the pivot row and every column rows = list(i for i in range(mat.rows) if i != pivot_pos) cols = list(range(mat.cols)) tmp_mat = mat.extract(rows, cols) def entry(i, j): ret = (pivot_val*tmp_mat[i, j + 1] - mat[pivot_pos, j + 1]*tmp_mat[i, 0]) / cumm if _get_intermediate_simp_bool(True): return _dotprodsimp(ret) elif not ret.is_Atom: return cancel(ret) return ret return sign*bareiss(M._new(mat.rows - 1, mat.cols - 1, entry), pivot_val) if not M.is_square: raise NonSquareMatrixError() if M.rows == 0: return M.one # sympy/matrices/tests/test_matrices.py contains a test that # suggests that the determinant of a 0 x 0 matrix is one, by # convention. return bareiss(M) def _det_berkowitz(M): """ Use the Berkowitz algorithm to compute the determinant.""" if not M.is_square: raise NonSquareMatrixError() if M.rows == 0: return M.one # sympy/matrices/tests/test_matrices.py contains a test that # suggests that the determinant of a 0 x 0 matrix is one, by # convention. berk_vector = _berkowitz_vector(M) return (-1)**(len(berk_vector) - 1) * berk_vector[-1] # This functions is a candidate for caching if it gets implemented for matrices. def _det_LU(M, iszerofunc=_iszero, simpfunc=None): """ Computes the determinant of a matrix from its LU decomposition. This function uses the LU decomposition computed by LUDecomposition_Simple(). The keyword arguments iszerofunc and simpfunc are passed to LUDecomposition_Simple(). iszerofunc is a callable that returns a boolean indicating if its input is zero, or None if it cannot make the determination. simpfunc is a callable that simplifies its input. The default is simpfunc=None, which indicate that the pivot search algorithm should not attempt to simplify any candidate pivots. If simpfunc fails to simplify its input, then it must return its input instead of a copy. Parameters ========== iszerofunc : function, optional The function to use to determine zeros when doing an LU decomposition. Defaults to ``lambda x: x.is_zero``. simpfunc : function, optional The simplification function to use when looking for zeros for pivots. """ if not M.is_square: raise NonSquareMatrixError() if M.rows == 0: return M.one # sympy/matrices/tests/test_matrices.py contains a test that # suggests that the determinant of a 0 x 0 matrix is one, by # convention. lu, row_swaps = M.LUdecomposition_Simple(iszerofunc=iszerofunc, simpfunc=simpfunc) # P*A = L*U => det(A) = det(L)*det(U)/det(P) = det(P)*det(U). # Lower triangular factor L encoded in lu has unit diagonal => det(L) = 1. # P is a permutation matrix => det(P) in {-1, 1} => 1/det(P) = det(P). # LUdecomposition_Simple() returns a list of row exchange index pairs, rather # than a permutation matrix, but det(P) = (-1)**len(row_swaps). # Avoid forming the potentially time consuming product of U's diagonal entries # if the product is zero. # Bottom right entry of U is 0 => det(A) = 0. # It may be impossible to determine if this entry of U is zero when it is symbolic. if iszerofunc(lu[lu.rows-1, lu.rows-1]): return M.zero # Compute det(P) det = -M.one if len(row_swaps)%2 else M.one # Compute det(U) by calculating the product of U's diagonal entries. # The upper triangular portion of lu is the upper triangular portion of the # U factor in the LU decomposition. for k in range(lu.rows): det *= lu[k, k] # return det(P)*det(U) return det def _minor(M, i, j, method="berkowitz"): """Return the (i,j) minor of ``M``. That is, return the determinant of the matrix obtained by deleting the `i`th row and `j`th column from ``M``. Parameters ========== i, j : int The row and column to exclude to obtain the submatrix. method : string, optional Method to use to find the determinant of the submatrix, can be "bareiss", "berkowitz" or "lu". Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> M.minor(1, 1) -12 See Also ======== minor_submatrix cofactor det """ if not M.is_square: raise NonSquareMatrixError() return M.minor_submatrix(i, j).det(method=method) def _minor_submatrix(M, i, j): """Return the submatrix obtained by removing the `i`th row and `j`th column from ``M`` (works with Pythonic negative indices). Parameters ========== i, j : int The row and column to exclude to obtain the submatrix. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> M.minor_submatrix(1, 1) Matrix([ [1, 3], [7, 9]]) See Also ======== minor cofactor """ if i < 0: i += M.rows if j < 0: j += M.cols if not 0 <= i < M.rows or not 0 <= j < M.cols: raise ValueError("`i` and `j` must satisfy 0 <= i < ``M.rows`` " "(%d)" % M.rows + "and 0 <= j < ``M.cols`` (%d)." % M.cols) rows = [a for a in range(M.rows) if a != i] cols = [a for a in range(M.cols) if a != j] return M.extract(rows, cols)
dba03829493a8e489f946f650a3d57da03ad4c4d53d2507084b32813bd7c348c
from types import FunctionType from .utilities import _get_intermediate_simp, _iszero, _dotprodsimp, _simplify from .determinant import _find_reasonable_pivot def _row_reduce_list(mat, rows, cols, one, iszerofunc, simpfunc, normalize_last=True, normalize=True, zero_above=True): """Row reduce a flat list representation of a matrix and return a tuple (rref_matrix, pivot_cols, swaps) where ``rref_matrix`` is a flat list, ``pivot_cols`` are the pivot columns and ``swaps`` are any row swaps that were used in the process of row reduction. Parameters ========== mat : list list of matrix elements, must be ``rows`` * ``cols`` in length rows, cols : integer number of rows and columns in flat list representation one : SymPy object represents the value one, from ``Matrix.one`` iszerofunc : determines if an entry can be used as a pivot simpfunc : used to simplify elements and test if they are zero if ``iszerofunc`` returns `None` normalize_last : indicates where all row reduction should happen in a fraction-free manner and then the rows are normalized (so that the pivots are 1), or whether rows should be normalized along the way (like the naive row reduction algorithm) normalize : whether pivot rows should be normalized so that the pivot value is 1 zero_above : whether entries above the pivot should be zeroed. If ``zero_above=False``, an echelon matrix will be returned. """ def get_col(i): return mat[i::cols] def row_swap(i, j): mat[i*cols:(i + 1)*cols], mat[j*cols:(j + 1)*cols] = \ mat[j*cols:(j + 1)*cols], mat[i*cols:(i + 1)*cols] def cross_cancel(a, i, b, j): """Does the row op row[i] = a*row[i] - b*row[j]""" q = (j - i)*cols for p in range(i*cols, (i + 1)*cols): mat[p] = isimp(a*mat[p] - b*mat[p + q]) isimp = _get_intermediate_simp(_dotprodsimp) piv_row, piv_col = 0, 0 pivot_cols = [] swaps = [] # use a fraction free method to zero above and below each pivot while piv_col < cols and piv_row < rows: pivot_offset, pivot_val, \ assumed_nonzero, newly_determined = _find_reasonable_pivot( get_col(piv_col)[piv_row:], iszerofunc, simpfunc) # _find_reasonable_pivot may have simplified some things # in the process. Let's not let them go to waste for (offset, val) in newly_determined: offset += piv_row mat[offset*cols + piv_col] = val if pivot_offset is None: piv_col += 1 continue pivot_cols.append(piv_col) if pivot_offset != 0: row_swap(piv_row, pivot_offset + piv_row) swaps.append((piv_row, pivot_offset + piv_row)) # if we aren't normalizing last, we normalize # before we zero the other rows if normalize_last is False: i, j = piv_row, piv_col mat[i*cols + j] = one for p in range(i*cols + j + 1, (i + 1)*cols): mat[p] = isimp(mat[p] / pivot_val) # after normalizing, the pivot value is 1 pivot_val = one # zero above and below the pivot for row in range(rows): # don't zero our current row if row == piv_row: continue # don't zero above the pivot unless we're told. if zero_above is False and row < piv_row: continue # if we're already a zero, don't do anything val = mat[row*cols + piv_col] if iszerofunc(val): continue cross_cancel(pivot_val, row, val, piv_row) piv_row += 1 # normalize each row if normalize_last is True and normalize is True: for piv_i, piv_j in enumerate(pivot_cols): pivot_val = mat[piv_i*cols + piv_j] mat[piv_i*cols + piv_j] = one for p in range(piv_i*cols + piv_j + 1, (piv_i + 1)*cols): mat[p] = isimp(mat[p] / pivot_val) return mat, tuple(pivot_cols), tuple(swaps) # This functions is a candidate for caching if it gets implemented for matrices. def _row_reduce(M, iszerofunc, simpfunc, normalize_last=True, normalize=True, zero_above=True): mat, pivot_cols, swaps = _row_reduce_list(list(M), M.rows, M.cols, M.one, iszerofunc, simpfunc, normalize_last=normalize_last, normalize=normalize, zero_above=zero_above) return M._new(M.rows, M.cols, mat), pivot_cols, swaps def _is_echelon(M, iszerofunc=_iszero): """Returns `True` if the matrix is in echelon form. That is, all rows of zeros are at the bottom, and below each leading non-zero in a row are exclusively zeros.""" if M.rows <= 0 or M.cols <= 0: return True zeros_below = all(iszerofunc(t) for t in M[1:, 0]) if iszerofunc(M[0, 0]): return zeros_below and _is_echelon(M[:, 1:], iszerofunc) return zeros_below and _is_echelon(M[1:, 1:], iszerofunc) def _echelon_form(M, iszerofunc=_iszero, simplify=False, with_pivots=False): """Returns a matrix row-equivalent to ``M`` that is in echelon form. Note that echelon form of a matrix is *not* unique, however, properties like the row space and the null space are preserved. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2], [3, 4]]) >>> M.echelon_form() Matrix([ [1, 2], [0, -2]]) """ simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify mat, pivots, _ = _row_reduce(M, iszerofunc, simpfunc, normalize_last=True, normalize=False, zero_above=False) if with_pivots: return mat, pivots return mat # This functions is a candidate for caching if it gets implemented for matrices. def _rank(M, iszerofunc=_iszero, simplify=False): """Returns the rank of a matrix. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x >>> m = Matrix([[1, 2], [x, 1 - 1/x]]) >>> m.rank() 2 >>> n = Matrix(3, 3, range(1, 10)) >>> n.rank() 2 """ def _permute_complexity_right(M, iszerofunc): """Permute columns with complicated elements as far right as they can go. Since the ``sympy`` row reduction algorithms start on the left, having complexity right-shifted speeds things up. Returns a tuple (mat, perm) where perm is a permutation of the columns to perform to shift the complex columns right, and mat is the permuted matrix.""" def complexity(i): # the complexity of a column will be judged by how many # element's zero-ness cannot be determined return sum(1 if iszerofunc(e) is None else 0 for e in M[:, i]) complex = [(complexity(i), i) for i in range(M.cols)] perm = [j for (i, j) in sorted(complex)] return (M.permute(perm, orientation='cols'), perm) simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify # for small matrices, we compute the rank explicitly # if is_zero on elements doesn't answer the question # for small matrices, we fall back to the full routine. if M.rows <= 0 or M.cols <= 0: return 0 if M.rows <= 1 or M.cols <= 1: zeros = [iszerofunc(x) for x in M] if False in zeros: return 1 if M.rows == 2 and M.cols == 2: zeros = [iszerofunc(x) for x in M] if False not in zeros and None not in zeros: return 0 d = M.det() if iszerofunc(d) and False in zeros: return 1 if iszerofunc(d) is False: return 2 mat, _ = _permute_complexity_right(M, iszerofunc=iszerofunc) _, pivots, _ = _row_reduce(mat, iszerofunc, simpfunc, normalize_last=True, normalize=False, zero_above=False) return len(pivots) def _rref(M, iszerofunc=_iszero, simplify=False, pivots=True, normalize_last=True): """Return reduced row-echelon form of matrix and indices of pivot vars. Parameters ========== iszerofunc : Function A function used for detecting whether an element can act as a pivot. ``lambda x: x.is_zero`` is used by default. simplify : Function A function used to simplify elements when looking for a pivot. By default SymPy's ``simplify`` is used. pivots : True or False If ``True``, a tuple containing the row-reduced matrix and a tuple of pivot columns is returned. If ``False`` just the row-reduced matrix is returned. normalize_last : True or False If ``True``, no pivots are normalized to `1` until after all entries above and below each pivot are zeroed. This means the row reduction algorithm is fraction free until the very last step. If ``False``, the naive row reduction procedure is used where each pivot is normalized to be `1` before row operations are used to zero above and below the pivot. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x >>> m = Matrix([[1, 2], [x, 1 - 1/x]]) >>> m.rref() (Matrix([ [1, 0], [0, 1]]), (0, 1)) >>> rref_matrix, rref_pivots = m.rref() >>> rref_matrix Matrix([ [1, 0], [0, 1]]) >>> rref_pivots (0, 1) Notes ===== The default value of ``normalize_last=True`` can provide significant speedup to row reduction, especially on matrices with symbols. However, if you depend on the form row reduction algorithm leaves entries of the matrix, set ``noramlize_last=False`` """ simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify mat, pivot_cols, _ = _row_reduce(M, iszerofunc, simpfunc, normalize_last, normalize=True, zero_above=True) if pivots: mat = (mat, pivot_cols) return mat
dcd598f281e24c6756411e807d9a60d9f3ad8d1735287ef9cb19084cdcc270f8
from mpmath.matrices.matrices import _matrix from sympy.core import Basic, Dict, Tuple from sympy.core.numbers import Integer from sympy.core.cache import cacheit from sympy.core.sympify import _sympy_converter as sympify_converter, _sympify from sympy.matrices.dense import DenseMatrix from sympy.matrices.expressions import MatrixExpr from sympy.matrices.matrices import MatrixBase from sympy.matrices.repmatrix import RepMatrix from sympy.matrices.sparse import SparseRepMatrix from sympy.multipledispatch import dispatch def sympify_matrix(arg): return arg.as_immutable() sympify_converter[MatrixBase] = sympify_matrix def sympify_mpmath_matrix(arg): mat = [_sympify(x) for x in arg] return ImmutableDenseMatrix(arg.rows, arg.cols, mat) sympify_converter[_matrix] = sympify_mpmath_matrix class ImmutableRepMatrix(RepMatrix, MatrixExpr): # type: ignore """Immutable matrix based on RepMatrix Uses DomainMAtrix as the internal representation. """ # # This is a subclass of RepMatrix that adds/overrides some methods to make # the instances Basic and immutable. ImmutableRepMatrix is a superclass for # both ImmutableDenseMatrix and ImmutableSparseMatrix. # def __new__(cls, *args, **kwargs): return cls._new(*args, **kwargs) __hash__ = MatrixExpr.__hash__ def copy(self): return self @property def cols(self): return self._cols @property def rows(self): return self._rows @property def shape(self): return self._rows, self._cols def as_immutable(self): return self def _entry(self, i, j, **kwargs): return self[i, j] def __setitem__(self, *args): raise TypeError("Cannot set values of {}".format(self.__class__)) def is_diagonalizable(self, reals_only=False, **kwargs): return super().is_diagonalizable( reals_only=reals_only, **kwargs) is_diagonalizable.__doc__ = SparseRepMatrix.is_diagonalizable.__doc__ is_diagonalizable = cacheit(is_diagonalizable) class ImmutableDenseMatrix(DenseMatrix, ImmutableRepMatrix): # type: ignore """Create an immutable version of a matrix. Examples ======== >>> from sympy import eye, ImmutableMatrix >>> ImmutableMatrix(eye(3)) Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> _[0, 0] = 42 Traceback (most recent call last): ... TypeError: Cannot set values of ImmutableDenseMatrix """ # MatrixExpr is set as NotIterable, but we want explicit matrices to be # iterable _iterable = True _class_priority = 8 _op_priority = 10.001 @classmethod def _new(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], ImmutableDenseMatrix): return args[0] if kwargs.get('copy', True) is False: if len(args) != 3: raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") rows, cols, flat_list = args else: rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) flat_list = list(flat_list) # create a shallow copy rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list) return cls._fromrep(rep) @classmethod def _fromrep(cls, rep): rows, cols = rep.shape flat_list = rep.to_sympy().to_list_flat() obj = Basic.__new__(cls, Integer(rows), Integer(cols), Tuple(*flat_list, sympify=False)) obj._rows = rows obj._cols = cols obj._rep = rep return obj # make sure ImmutableDenseMatrix is aliased as ImmutableMatrix ImmutableMatrix = ImmutableDenseMatrix class ImmutableSparseMatrix(SparseRepMatrix, ImmutableRepMatrix): # type:ignore """Create an immutable version of a sparse matrix. Examples ======== >>> from sympy import eye, ImmutableSparseMatrix >>> ImmutableSparseMatrix(1, 1, {}) Matrix([[0]]) >>> ImmutableSparseMatrix(eye(3)) Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> _[0, 0] = 42 Traceback (most recent call last): ... TypeError: Cannot set values of ImmutableSparseMatrix >>> _.shape (3, 3) """ is_Matrix = True _class_priority = 9 @classmethod def _new(cls, *args, **kwargs): rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs) rep = cls._smat_to_DomainMatrix(rows, cols, smat) return cls._fromrep(rep) @classmethod def _fromrep(cls, rep): rows, cols = rep.shape smat = rep.to_sympy().to_dok() obj = Basic.__new__(cls, Integer(rows), Integer(cols), Dict(smat)) obj._rows = rows obj._cols = cols obj._rep = rep return obj @dispatch(ImmutableDenseMatrix, ImmutableDenseMatrix) def _eval_is_eq(lhs, rhs): # noqa:F811 """Helper method for Equality with matrices.sympy. Relational automatically converts matrices to ImmutableDenseMatrix instances, so this method only applies here. Returns True if the matrices are definitively the same, False if they are definitively different, and None if undetermined (e.g. if they contain Symbols). Returning None triggers default handling of Equalities. """ if lhs.shape != rhs.shape: return False return (lhs - rhs).is_zero_matrix
87006f67080a31827560d35083a5daa8e593dc5ee933b0f59fe725e9be697fe8
""" Basic methods common to all matrices to be used when creating more advanced matrices (e.g., matrices over rings, etc.). """ from collections import defaultdict from collections.abc import Iterable from inspect import isfunction from functools import reduce from sympy.assumptions.refine import refine from sympy.core import SympifyError, Add from sympy.core.basic import Atom from sympy.core.decorators import call_highest_priority from sympy.core.kind import Kind, NumberKind from sympy.core.logic import fuzzy_and, FuzzyBool from sympy.core.mod import Mod from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.complexes import Abs, re, im from .utilities import _dotprodsimp, _simplify from sympy.polys.polytools import Poly from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import flatten, is_sequence from sympy.utilities.misc import as_int, filldedent from sympy.tensor.array import NDimArray from .utilities import _get_intermediate_simp_bool class MatrixError(Exception): pass class ShapeError(ValueError, MatrixError): """Wrong matrix shape""" pass class NonSquareMatrixError(ShapeError): pass class NonInvertibleMatrixError(ValueError, MatrixError): """The matrix in not invertible (division by multidimensional zero error).""" pass class NonPositiveDefiniteMatrixError(ValueError, MatrixError): """The matrix is not a positive-definite matrix.""" pass class MatrixRequired: """All subclasses of matrix objects must implement the required matrix properties listed here.""" rows = None # type: int cols = None # type: int _simplify = None @classmethod def _new(cls, *args, **kwargs): """`_new` must, at minimum, be callable as `_new(rows, cols, mat) where mat is a flat list of the elements of the matrix.""" raise NotImplementedError("Subclasses must implement this.") def __eq__(self, other): raise NotImplementedError("Subclasses must implement this.") def __getitem__(self, key): """Implementations of __getitem__ should accept ints, in which case the matrix is indexed as a flat list, tuples (i,j) in which case the (i,j) entry is returned, slices, or mixed tuples (a,b) where a and b are any combination of slices and integers.""" raise NotImplementedError("Subclasses must implement this.") def __len__(self): """The total number of entries in the matrix.""" raise NotImplementedError("Subclasses must implement this.") @property def shape(self): raise NotImplementedError("Subclasses must implement this.") class MatrixShaping(MatrixRequired): """Provides basic matrix shaping and extracting of submatrices""" def _eval_col_del(self, col): def entry(i, j): return self[i, j] if j < col else self[i, j + 1] return self._new(self.rows, self.cols - 1, entry) def _eval_col_insert(self, pos, other): def entry(i, j): if j < pos: return self[i, j] elif pos <= j < pos + other.cols: return other[i, j - pos] return self[i, j - other.cols] return self._new(self.rows, self.cols + other.cols, entry) def _eval_col_join(self, other): rows = self.rows def entry(i, j): if i < rows: return self[i, j] return other[i - rows, j] return classof(self, other)._new(self.rows + other.rows, self.cols, entry) def _eval_extract(self, rowsList, colsList): mat = list(self) cols = self.cols indices = (i * cols + j for i in rowsList for j in colsList) return self._new(len(rowsList), len(colsList), list(mat[i] for i in indices)) def _eval_get_diag_blocks(self): sub_blocks = [] def recurse_sub_blocks(M): i = 1 while i <= M.shape[0]: if i == 1: to_the_right = M[0, i:] to_the_bottom = M[i:, 0] else: to_the_right = M[:i, i:] to_the_bottom = M[i:, :i] if any(to_the_right) or any(to_the_bottom): i += 1 continue else: sub_blocks.append(M[:i, :i]) if M.shape == M[:i, :i].shape: return else: recurse_sub_blocks(M[i:, i:]) return recurse_sub_blocks(self) return sub_blocks def _eval_row_del(self, row): def entry(i, j): return self[i, j] if i < row else self[i + 1, j] return self._new(self.rows - 1, self.cols, entry) def _eval_row_insert(self, pos, other): entries = list(self) insert_pos = pos * self.cols entries[insert_pos:insert_pos] = list(other) return self._new(self.rows + other.rows, self.cols, entries) def _eval_row_join(self, other): cols = self.cols def entry(i, j): if j < cols: return self[i, j] return other[i, j - cols] return classof(self, other)._new(self.rows, self.cols + other.cols, entry) def _eval_tolist(self): return [list(self[i,:]) for i in range(self.rows)] def _eval_todok(self): dok = {} rows, cols = self.shape for i in range(rows): for j in range(cols): val = self[i, j] if val != self.zero: dok[i, j] = val return dok def _eval_vec(self): rows = self.rows def entry(n, _): # we want to read off the columns first j = n // rows i = n - j * rows return self[i, j] return self._new(len(self), 1, entry) def _eval_vech(self, diagonal): c = self.cols v = [] if diagonal: for j in range(c): for i in range(j, c): v.append(self[i, j]) else: for j in range(c): for i in range(j + 1, c): v.append(self[i, j]) return self._new(len(v), 1, v) def col_del(self, col): """Delete the specified column.""" if col < 0: col += self.cols if not 0 <= col < self.cols: raise IndexError("Column {} is out of range.".format(col)) return self._eval_col_del(col) def col_insert(self, pos, other): """Insert one or more columns at the given column position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.col_insert(1, V) Matrix([ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]) See Also ======== col row_insert """ # Allows you to build a matrix even if it is null matrix if not self: return type(self)(other) pos = as_int(pos) if pos < 0: pos = self.cols + pos if pos < 0: pos = 0 elif pos > self.cols: pos = self.cols if self.rows != other.rows: raise ShapeError( "`self` and `other` must have the same number of rows.") return self._eval_col_insert(pos, other) def col_join(self, other): """Concatenates two matrices along self's last and other's first row. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.col_join(V) Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 1, 1]]) See Also ======== col row_join """ # A null matrix can always be stacked (see #10770) if self.rows == 0 and self.cols != other.cols: return self._new(0, other.cols, []).col_join(other) if self.cols != other.cols: raise ShapeError( "`self` and `other` must have the same number of columns.") return self._eval_col_join(other) def col(self, j): """Elementary column selector. Examples ======== >>> from sympy import eye >>> eye(2).col(0) Matrix([ [1], [0]]) See Also ======== row col_del col_join col_insert """ return self[:, j] def extract(self, rowsList, colsList): r"""Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range $-n \le i < n$ where $n$ is the number of rows or columns. Examples ======== >>> from sympy import Matrix >>> m = Matrix(4, 3, range(12)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) >>> m.extract([0, 1, 3], [0, 1]) Matrix([ [0, 1], [3, 4], [9, 10]]) Rows or columns can be repeated: >>> m.extract([0, 0, 1], [-1]) Matrix([ [2], [2], [5]]) Every other row can be taken by using range to provide the indices: >>> m.extract(range(0, m.rows, 2), [-1]) Matrix([ [2], [8]]) RowsList or colsList can also be a list of booleans, in which case the rows or columns corresponding to the True values will be selected: >>> m.extract([0, 1, 2, 3], [True, False, True]) Matrix([ [0, 2], [3, 5], [6, 8], [9, 11]]) """ if not is_sequence(rowsList) or not is_sequence(colsList): raise TypeError("rowsList and colsList must be iterable") # ensure rowsList and colsList are lists of integers if rowsList and all(isinstance(i, bool) for i in rowsList): rowsList = [index for index, item in enumerate(rowsList) if item] if colsList and all(isinstance(i, bool) for i in colsList): colsList = [index for index, item in enumerate(colsList) if item] # ensure everything is in range rowsList = [a2idx(k, self.rows) for k in rowsList] colsList = [a2idx(k, self.cols) for k in colsList] return self._eval_extract(rowsList, colsList) def get_diag_blocks(self): """Obtains the square sub-matrices on the main diagonal of a square matrix. Useful for inverting symbolic matrices or solving systems of linear equations which may be decoupled by having a block diagonal structure. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) >>> a1, a2, a3 = A.get_diag_blocks() >>> a1 Matrix([ [1, 3], [y, z**2]]) >>> a2 Matrix([[x]]) >>> a3 Matrix([[0]]) """ return self._eval_get_diag_blocks() @classmethod def hstack(cls, *args): """Return a matrix formed by joining args horizontally (i.e. by repeated application of row_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.hstack(eye(2), 2*eye(2)) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2]]) """ if len(args) == 0: return cls._new() kls = type(args[0]) return reduce(kls.row_join, args) def reshape(self, rows, cols): """Reshape the matrix. Total number of elements must remain the same. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 3, lambda i, j: 1) >>> m Matrix([ [1, 1, 1], [1, 1, 1]]) >>> m.reshape(1, 6) Matrix([[1, 1, 1, 1, 1, 1]]) >>> m.reshape(3, 2) Matrix([ [1, 1], [1, 1], [1, 1]]) """ if self.rows * self.cols != rows * cols: raise ValueError("Invalid reshape parameters %d %d" % (rows, cols)) return self._new(rows, cols, lambda i, j: self[i * cols + j]) def row_del(self, row): """Delete the specified row.""" if row < 0: row += self.rows if not 0 <= row < self.rows: raise IndexError("Row {} is out of range.".format(row)) return self._eval_row_del(row) def row_insert(self, pos, other): """Insert one or more rows at the given row position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.row_insert(1, V) Matrix([ [0, 0, 0], [1, 1, 1], [0, 0, 0], [0, 0, 0]]) See Also ======== row col_insert """ # Allows you to build a matrix even if it is null matrix if not self: return self._new(other) pos = as_int(pos) if pos < 0: pos = self.rows + pos if pos < 0: pos = 0 elif pos > self.rows: pos = self.rows if self.cols != other.cols: raise ShapeError( "`self` and `other` must have the same number of columns.") return self._eval_row_insert(pos, other) def row_join(self, other): """Concatenates two matrices along self's last and rhs's first column Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.row_join(V) Matrix([ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]) See Also ======== row col_join """ # A null matrix can always be stacked (see #10770) if self.cols == 0 and self.rows != other.rows: return self._new(other.rows, 0, []).row_join(other) if self.rows != other.rows: raise ShapeError( "`self` and `rhs` must have the same number of rows.") return self._eval_row_join(other) def diagonal(self, k=0): """Returns the kth diagonal of self. The main diagonal corresponds to `k=0`; diagonals above and below correspond to `k > 0` and `k < 0`, respectively. The values of `self[i, j]` for which `j - i = k`, are returned in order of increasing `i + j`, starting with `i + j = |k|`. Examples ======== >>> from sympy import Matrix >>> m = Matrix(3, 3, lambda i, j: j - i); m Matrix([ [ 0, 1, 2], [-1, 0, 1], [-2, -1, 0]]) >>> _.diagonal() Matrix([[0, 0, 0]]) >>> m.diagonal(1) Matrix([[1, 1]]) >>> m.diagonal(-2) Matrix([[-2]]) Even though the diagonal is returned as a Matrix, the element retrieval can be done with a single index: >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1] 2 See Also ======== diag - to create a diagonal matrix """ rv = [] k = as_int(k) r = 0 if k > 0 else -k c = 0 if r else k while True: if r == self.rows or c == self.cols: break rv.append(self[r, c]) r += 1 c += 1 if not rv: raise ValueError(filldedent(''' The %s diagonal is out of range [%s, %s]''' % ( k, 1 - self.rows, self.cols - 1))) return self._new(1, len(rv), rv) def row(self, i): """Elementary row selector. Examples ======== >>> from sympy import eye >>> eye(2).row(0) Matrix([[1, 0]]) See Also ======== col row_del row_join row_insert """ return self[i, :] @property def shape(self): """The shape (dimensions) of the matrix as the 2-tuple (rows, cols). Examples ======== >>> from sympy import zeros >>> M = zeros(2, 3) >>> M.shape (2, 3) >>> M.rows 2 >>> M.cols 3 """ return (self.rows, self.cols) def todok(self): """Return the matrix as dictionary of keys. Examples ======== >>> from sympy import Matrix >>> M = Matrix.eye(3) >>> M.todok() {(0, 0): 1, (1, 1): 1, (2, 2): 1} """ return self._eval_todok() def tolist(self): """Return the Matrix as a nested Python list. Examples ======== >>> from sympy import Matrix, ones >>> m = Matrix(3, 3, range(9)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> m.tolist() [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> ones(3, 0).tolist() [[], [], []] When there are no rows then it will not be possible to tell how many columns were in the original matrix: >>> ones(0, 3).tolist() [] """ if not self.rows: return [] if not self.cols: return [[] for i in range(self.rows)] return self._eval_tolist() def todod(M): """Returns matrix as dict of dicts containing non-zero elements of the Matrix Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1],[0, 3]]) >>> A Matrix([ [0, 1], [0, 3]]) >>> A.todod() {0: {1: 1}, 1: {1: 3}} """ rowsdict = {} Mlol = M.tolist() for i, Mi in enumerate(Mlol): row = {j: Mij for j, Mij in enumerate(Mi) if Mij} if row: rowsdict[i] = row return rowsdict def vec(self): """Return the Matrix converted into a one column matrix by stacking columns Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 3], [2, 4]]) >>> m Matrix([ [1, 3], [2, 4]]) >>> m.vec() Matrix([ [1], [2], [3], [4]]) See Also ======== vech """ return self._eval_vec() def vech(self, diagonal=True, check_symmetry=True): """Reshapes the matrix into a column vector by stacking the elements in the lower triangle. Parameters ========== diagonal : bool, optional If ``True``, it includes the diagonal elements. check_symmetry : bool, optional If ``True``, it checks whether the matrix is symmetric. Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 2], [2, 3]]) >>> m Matrix([ [1, 2], [2, 3]]) >>> m.vech() Matrix([ [1], [2], [3]]) >>> m.vech(diagonal=False) Matrix([[2]]) Notes ===== This should work for symmetric matrices and ``vech`` can represent symmetric matrices in vector form with less size than ``vec``. See Also ======== vec """ if not self.is_square: raise NonSquareMatrixError if check_symmetry and not self.is_symmetric(): raise ValueError("The matrix is not symmetric.") return self._eval_vech(diagonal) @classmethod def vstack(cls, *args): """Return a matrix formed by joining args vertically (i.e. by repeated application of col_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.vstack(eye(2), 2*eye(2)) Matrix([ [1, 0], [0, 1], [2, 0], [0, 2]]) """ if len(args) == 0: return cls._new() kls = type(args[0]) return reduce(kls.col_join, args) class MatrixSpecial(MatrixRequired): """Construction of special matrices""" @classmethod def _eval_diag(cls, rows, cols, diag_dict): """diag_dict is a defaultdict containing all the entries of the diagonal matrix.""" def entry(i, j): return diag_dict[(i, j)] return cls._new(rows, cols, entry) @classmethod def _eval_eye(cls, rows, cols): vals = [cls.zero]*(rows*cols) vals[::cols+1] = [cls.one]*min(rows, cols) return cls._new(rows, cols, vals, copy=False) @classmethod def _eval_jordan_block(cls, rows, cols, eigenvalue, band='upper'): if band == 'lower': def entry(i, j): if i == j: return eigenvalue elif j + 1 == i: return cls.one return cls.zero else: def entry(i, j): if i == j: return eigenvalue elif i + 1 == j: return cls.one return cls.zero return cls._new(rows, cols, entry) @classmethod def _eval_ones(cls, rows, cols): def entry(i, j): return cls.one return cls._new(rows, cols, entry) @classmethod def _eval_zeros(cls, rows, cols): return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False) @classmethod def _eval_wilkinson(cls, n): def entry(i, j): return cls.one if i + 1 == j else cls.zero D = cls._new(2*n + 1, 2*n + 1, entry) wminus = cls.diag([i for i in range(-n, n + 1)], unpack=True) + D + D.T wplus = abs(cls.diag([i for i in range(-n, n + 1)], unpack=True)) + D + D.T return wminus, wplus @classmethod def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs): """Returns a matrix with the specified diagonal. If matrices are passed, a block-diagonal matrix is created (i.e. the "direct sum" of the matrices). kwargs ====== rows : rows of the resulting matrix; computed if not given. cols : columns of the resulting matrix; computed if not given. cls : class for the resulting matrix unpack : bool which, when True (default), unpacks a single sequence rather than interpreting it as a Matrix. strict : bool which, when False (default), allows Matrices to have variable-length rows. Examples ======== >>> from sympy import Matrix >>> Matrix.diag(1, 2, 3) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) The current default is to unpack a single sequence. If this is not desired, set `unpack=False` and it will be interpreted as a matrix. >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) True When more than one element is passed, each is interpreted as something to put on the diagonal. Lists are converted to matrices. Filling of the diagonal always continues from the bottom right hand corner of the previous item: this will create a block-diagonal matrix whether the matrices are square or not. >>> col = [1, 2, 3] >>> row = [[4, 5]] >>> Matrix.diag(col, row) Matrix([ [1, 0, 0], [2, 0, 0], [3, 0, 0], [0, 4, 5]]) When `unpack` is False, elements within a list need not all be of the same length. Setting `strict` to True would raise a ValueError for the following: >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False) Matrix([ [1, 2, 3], [4, 5, 0], [6, 0, 0]]) The type of the returned matrix can be set with the ``cls`` keyword. >>> from sympy import ImmutableMatrix >>> from sympy.utilities.misc import func_name >>> func_name(Matrix.diag(1, cls=ImmutableMatrix)) 'ImmutableDenseMatrix' A zero dimension matrix can be used to position the start of the filling at the start of an arbitrary row or column: >>> from sympy import ones >>> r2 = ones(0, 2) >>> Matrix.diag(r2, 1, 2) Matrix([ [0, 0, 1, 0], [0, 0, 0, 2]]) See Also ======== eye diagonal - to extract a diagonal .dense.diag .expressions.blockmatrix.BlockMatrix .sparsetools.banded - to create multi-diagonal matrices """ from sympy.matrices.matrices import MatrixBase from sympy.matrices.dense import Matrix from sympy.matrices import SparseMatrix klass = kwargs.get('cls', kls) if unpack and len(args) == 1 and is_sequence(args[0]) and \ not isinstance(args[0], MatrixBase): args = args[0] # fill a default dict with the diagonal entries diag_entries = defaultdict(int) rmax = cmax = 0 # keep track of the biggest index seen for m in args: if isinstance(m, list): if strict: # if malformed, Matrix will raise an error _ = Matrix(m) r, c = _.shape m = _.tolist() else: r, c, smat = SparseMatrix._handle_creation_inputs(m) for (i, j), _ in smat.items(): diag_entries[(i + rmax, j + cmax)] = _ m = [] # to skip process below elif hasattr(m, 'shape'): # a Matrix # convert to list of lists r, c = m.shape m = m.tolist() else: # in this case, we're a single value diag_entries[(rmax, cmax)] = m rmax += 1 cmax += 1 continue # process list of lists for i in range(len(m)): for j, _ in enumerate(m[i]): diag_entries[(i + rmax, j + cmax)] = _ rmax += r cmax += c if rows is None: rows, cols = cols, rows if rows is None: rows, cols = rmax, cmax else: cols = rows if cols is None else cols if rows < rmax or cols < cmax: raise ValueError(filldedent(''' The constructed matrix is {} x {} but a size of {} x {} was specified.'''.format(rmax, cmax, rows, cols))) return klass._eval_diag(rows, cols, diag_entries) @classmethod def eye(kls, rows, cols=None, **kwargs): """Returns an identity matrix. Args ==== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_eye(rows, cols) @classmethod def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): """Returns a Jordan block Parameters ========== size : Integer, optional Specifies the shape of the Jordan block matrix. eigenvalue : Number or Symbol Specifies the value for the main diagonal of the matrix. .. note:: The keyword ``eigenval`` is also specified as an alias of this keyword, but it is not recommended to use. We may deprecate the alias in later release. band : 'upper' or 'lower', optional Specifies the position of the off-diagonal to put `1` s on. cls : Matrix, optional Specifies the matrix class of the output form. If it is not specified, the class type where the method is being executed on will be returned. rows, cols : Integer, optional Specifies the shape of the Jordan block matrix. See Notes section for the details of how these key works. .. deprecated:: 1.4 The rows and cols parameters are deprecated and will be removed in a future version. Returns ======= Matrix A Jordan block matrix. Raises ====== ValueError If insufficient arguments are given for matrix size specification, or no eigenvalue is given. Examples ======== Creating a default Jordan block: >>> from sympy import Matrix >>> from sympy.abc import x >>> Matrix.jordan_block(4, x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) Creating an alternative Jordan block matrix where `1` is on lower off-diagonal: >>> Matrix.jordan_block(4, x, band='lower') Matrix([ [x, 0, 0, 0], [1, x, 0, 0], [0, 1, x, 0], [0, 0, 1, x]]) Creating a Jordan block with keyword arguments >>> Matrix.jordan_block(size=4, eigenvalue=x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) Notes ===== .. deprecated:: 1.4 This feature is deprecated and will be removed in a future version. The keyword arguments ``size``, ``rows``, ``cols`` relates to the Jordan block size specifications. If you want to create a square Jordan block, specify either one of the three arguments. If you want to create a rectangular Jordan block, specify ``rows`` and ``cols`` individually. +--------------------------------+---------------------+ | Arguments Given | Matrix Shape | +----------+----------+----------+----------+----------+ | size | rows | cols | rows | cols | +==========+==========+==========+==========+==========+ | size | Any | size | size | +----------+----------+----------+----------+----------+ | | None | ValueError | | +----------+----------+----------+----------+ | None | rows | None | rows | rows | | +----------+----------+----------+----------+ | | None | cols | cols | cols | + +----------+----------+----------+----------+ | | rows | cols | rows | cols | +----------+----------+----------+----------+----------+ References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_matrix """ if 'rows' in kwargs or 'cols' in kwargs: msg = """ The 'rows' and 'cols' keywords to Matrix.jordan_block() are deprecated. Use the 'size' parameter instead. """ if 'rows' in kwargs and 'cols' in kwargs: msg += f"""\ To get a non-square Jordan block matrix use a more generic banded matrix constructor, like def entry(i, j): if i == j: return eigenvalue elif {"i + 1 == j" if band == 'upper' else "j + 1 == i"}: return 1 return 0 Matrix({kwargs['rows']}, {kwargs['cols']}, entry) """ sympy_deprecation_warning(msg, deprecated_since_version="1.4", active_deprecations_target="deprecated-matrix-jordan_block-rows-cols") klass = kwargs.pop('cls', kls) rows = kwargs.pop('rows', None) cols = kwargs.pop('cols', None) eigenval = kwargs.get('eigenval', None) if eigenvalue is None and eigenval is None: raise ValueError("Must supply an eigenvalue") elif eigenvalue != eigenval and None not in (eigenval, eigenvalue): raise ValueError( "Inconsistent values are given: 'eigenval'={}, " "'eigenvalue'={}".format(eigenval, eigenvalue)) else: if eigenval is not None: eigenvalue = eigenval if (size, rows, cols) == (None, None, None): raise ValueError("Must supply a matrix size") if size is not None: rows, cols = size, size elif rows is not None and cols is None: cols = rows elif cols is not None and rows is None: rows = cols rows, cols = as_int(rows), as_int(cols) return klass._eval_jordan_block(rows, cols, eigenvalue, band) @classmethod def ones(kls, rows, cols=None, **kwargs): """Returns a matrix of ones. Args ==== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_ones(rows, cols) @classmethod def zeros(kls, rows, cols=None, **kwargs): """Returns a matrix of zeros. Args ==== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_zeros(rows, cols) @classmethod def companion(kls, poly): """Returns a companion matrix of a polynomial. Examples ======== >>> from sympy import Matrix, Poly, Symbol, symbols >>> x = Symbol('x') >>> c0, c1, c2, c3, c4 = symbols('c0:5') >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) >>> Matrix.companion(p) Matrix([ [0, 0, 0, 0, -c0], [1, 0, 0, 0, -c1], [0, 1, 0, 0, -c2], [0, 0, 1, 0, -c3], [0, 0, 0, 1, -c4]]) """ poly = kls._sympify(poly) if not isinstance(poly, Poly): raise ValueError("{} must be a Poly instance.".format(poly)) if not poly.is_monic: raise ValueError("{} must be a monic polynomial.".format(poly)) if not poly.is_univariate: raise ValueError( "{} must be a univariate polynomial.".format(poly)) size = poly.degree() if not size >= 1: raise ValueError( "{} must have degree not less than 1.".format(poly)) coeffs = poly.all_coeffs() def entry(i, j): if j == size - 1: return -coeffs[-1 - i] elif i == j + 1: return kls.one return kls.zero return kls._new(size, size, entry) @classmethod def wilkinson(kls, n, **kwargs): """Returns two square Wilkinson Matrix of size 2*n + 1 $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n) Examples ======== >>> from sympy import Matrix >>> wminus, wplus = Matrix.wilkinson(3) >>> wminus Matrix([ [-3, 1, 0, 0, 0, 0, 0], [ 1, -2, 1, 0, 0, 0, 0], [ 0, 1, -1, 1, 0, 0, 0], [ 0, 0, 1, 0, 1, 0, 0], [ 0, 0, 0, 1, 1, 1, 0], [ 0, 0, 0, 0, 1, 2, 1], [ 0, 0, 0, 0, 0, 1, 3]]) >>> wplus Matrix([ [3, 1, 0, 0, 0, 0, 0], [1, 2, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]]) References ========== .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp. """ klass = kwargs.get('cls', kls) n = as_int(n) return klass._eval_wilkinson(n) class MatrixProperties(MatrixRequired): """Provides basic properties of a matrix.""" def _eval_atoms(self, *types): result = set() for i in self: result.update(i.atoms(*types)) return result def _eval_free_symbols(self): return set().union(*(i.free_symbols for i in self if i)) def _eval_has(self, *patterns): return any(a.has(*patterns) for a in self) def _eval_is_anti_symmetric(self, simpfunc): if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)): return False return True def _eval_is_diagonal(self): for i in range(self.rows): for j in range(self.cols): if i != j and self[i, j]: return False return True # _eval_is_hermitian is called by some general SymPy # routines and has a different *args signature. Make # sure the names don't clash by adding `_matrix_` in name. def _eval_is_matrix_hermitian(self, simpfunc): mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate())) return mat.is_zero_matrix def _eval_is_Identity(self) -> FuzzyBool: def dirac(i, j): if i == j: return 1 return 0 return all(self[i, j] == dirac(i, j) for i in range(self.rows) for j in range(self.cols)) def _eval_is_lower_hessenberg(self): return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 2, self.cols)) def _eval_is_lower(self): return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 1, self.cols)) def _eval_is_symbolic(self): return self.has(Symbol) def _eval_is_symmetric(self, simpfunc): mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i])) return mat.is_zero_matrix def _eval_is_zero_matrix(self): if any(i.is_zero == False for i in self): return False if any(i.is_zero is None for i in self): return None return True def _eval_is_upper_hessenberg(self): return all(self[i, j].is_zero for i in range(2, self.rows) for j in range(min(self.cols, (i - 1)))) def _eval_values(self): return [i for i in self if not i.is_zero] def _has_positive_diagonals(self): diagonal_entries = (self[i, i] for i in range(self.rows)) return fuzzy_and(x.is_positive for x in diagonal_entries) def _has_nonnegative_diagonals(self): diagonal_entries = (self[i, i] for i in range(self.rows)) return fuzzy_and(x.is_nonnegative for x in diagonal_entries) def atoms(self, *types): """Returns the atoms that form the current object. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Matrix >>> Matrix([[x]]) Matrix([[x]]) >>> _.atoms() {x} >>> Matrix([[x, y], [y, x]]) Matrix([ [x, y], [y, x]]) >>> _.atoms() {x, y} """ types = tuple(t if isinstance(t, type) else type(t) for t in types) if not types: types = (Atom,) return self._eval_atoms(*types) @property def free_symbols(self): """Returns the free symbols within the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix([[x], [1]]).free_symbols {x} """ return self._eval_free_symbols() def has(self, *patterns): """Test whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import Matrix, SparseMatrix, Float >>> from sympy.abc import x, y >>> A = Matrix(((1, x), (0.2, 3))) >>> B = SparseMatrix(((1, x), (0.2, 3))) >>> A.has(x) True >>> A.has(y) False >>> A.has(Float) True >>> B.has(x) True >>> B.has(y) False >>> B.has(Float) True """ return self._eval_has(*patterns) def is_anti_symmetric(self, simplify=True): """Check if matrix M is an antisymmetric matrix, that is, M is a square matrix with all M[i, j] == -M[j, i]. When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is simplified before testing to see if it is zero. By default, the SymPy simplify function is used. To use a custom function set simplify to a function that accepts a single argument which returns a simplified expression. To skip simplification, set simplify to False but note that although this will be faster, it may induce false negatives. Examples ======== >>> from sympy import Matrix, symbols >>> m = Matrix(2, 2, [0, 1, -1, 0]) >>> m Matrix([ [ 0, 1], [-1, 0]]) >>> m.is_anti_symmetric() True >>> x, y = symbols('x y') >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) >>> m Matrix([ [ 0, 0, x], [-y, 0, 0]]) >>> m.is_anti_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, ... -(x + 1)**2, 0, x*y, ... -y, -x*y, 0]) Simplification of matrix elements is done by default so even though two elements which should be equal and opposite would not pass an equality test, the matrix is still reported as anti-symmetric: >>> m[0, 1] == -m[1, 0] False >>> m.is_anti_symmetric() True If ``simplify=False`` is used for the case when a Matrix is already simplified, this will speed things up. Here, we see that without simplification the matrix does not appear anti-symmetric: >>> m.is_anti_symmetric(simplify=False) False But if the matrix were already expanded, then it would appear anti-symmetric and simplification in the is_anti_symmetric routine is not needed: >>> m = m.expand() >>> m.is_anti_symmetric(simplify=False) True """ # accept custom simplification simpfunc = simplify if not isfunction(simplify): simpfunc = _simplify if simplify else lambda x: x if not self.is_square: return False return self._eval_is_anti_symmetric(simpfunc) def is_diagonal(self): """Check if matrix is diagonal, that is matrix in which the entries outside the main diagonal are all zero. Examples ======== >>> from sympy import Matrix, diag >>> m = Matrix(2, 2, [1, 0, 0, 2]) >>> m Matrix([ [1, 0], [0, 2]]) >>> m.is_diagonal() True >>> m = Matrix(2, 2, [1, 1, 0, 2]) >>> m Matrix([ [1, 1], [0, 2]]) >>> m.is_diagonal() False >>> m = diag(1, 2, 3) >>> m Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> m.is_diagonal() True See Also ======== is_lower is_upper sympy.matrices.matrices.MatrixEigen.is_diagonalizable diagonalize """ return self._eval_is_diagonal() @property def is_weakly_diagonally_dominant(self): r"""Tests if the matrix is row weakly diagonally dominant. Explanation =========== A $n, n$ matrix $A$ is row weakly diagonally dominant if .. math:: \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in \{ 0, ..., n-1 \} Examples ======== >>> from sympy import Matrix >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) >>> A.is_weakly_diagonally_dominant True >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) >>> A.is_weakly_diagonally_dominant False >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) >>> A.is_weakly_diagonally_dominant True Notes ===== If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix. """ if not self.is_square: return False rows, cols = self.shape def test_row(i): summation = self.zero for j in range(cols): if i != j: summation += Abs(self[i, j]) return (Abs(self[i, i]) - summation).is_nonnegative return fuzzy_and(test_row(i) for i in range(rows)) @property def is_strongly_diagonally_dominant(self): r"""Tests if the matrix is row strongly diagonally dominant. Explanation =========== A $n, n$ matrix $A$ is row strongly diagonally dominant if .. math:: \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in \{ 0, ..., n-1 \} Examples ======== >>> from sympy import Matrix >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) >>> A.is_strongly_diagonally_dominant False >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) >>> A.is_strongly_diagonally_dominant False >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) >>> A.is_strongly_diagonally_dominant True Notes ===== If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix. """ if not self.is_square: return False rows, cols = self.shape def test_row(i): summation = self.zero for j in range(cols): if i != j: summation += Abs(self[i, j]) return (Abs(self[i, i]) - summation).is_positive return fuzzy_and(test_row(i) for i in range(rows)) @property def is_hermitian(self): """Checks if the matrix is Hermitian. In a Hermitian matrix element i,j is the complex conjugate of element j,i. Examples ======== >>> from sympy import Matrix >>> from sympy import I >>> from sympy.abc import x >>> a = Matrix([[1, I], [-I, 1]]) >>> a Matrix([ [ 1, I], [-I, 1]]) >>> a.is_hermitian True >>> a[0, 0] = 2*I >>> a.is_hermitian False >>> a[0, 0] = x >>> a.is_hermitian >>> a[0, 1] = a[1, 0]*I >>> a.is_hermitian False """ if not self.is_square: return False return self._eval_is_matrix_hermitian(_simplify) @property def is_Identity(self) -> FuzzyBool: if not self.is_square: return False return self._eval_is_Identity() @property def is_lower_hessenberg(self): r"""Checks if the matrix is in the lower-Hessenberg form. The lower hessenberg matrix has zero entries above the first superdiagonal. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a Matrix([ [1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a.is_lower_hessenberg True See Also ======== is_upper_hessenberg is_lower """ return self._eval_is_lower_hessenberg() @property def is_lower(self): """Check if matrix is a lower triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_lower True >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5]) >>> m Matrix([ [0, 0, 0], [2, 0, 0], [1, 4, 0], [6, 6, 5]]) >>> m.is_lower True >>> from sympy.abc import x, y >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y]) >>> m Matrix([ [x**2 + y, x + y**2], [ 0, x + y]]) >>> m.is_lower False See Also ======== is_upper is_diagonal is_lower_hessenberg """ return self._eval_is_lower() @property def is_square(self): """Checks if a matrix is square. A matrix is square if the number of rows equals the number of columns. The empty matrix is square by definition, since the number of rows and the number of columns are both zero. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 3], [4, 5, 6]]) >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> c = Matrix([]) >>> a.is_square False >>> b.is_square True >>> c.is_square True """ return self.rows == self.cols def is_symbolic(self): """Checks if any elements contain Symbols. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.is_symbolic() True """ return self._eval_is_symbolic() def is_symmetric(self, simplify=True): """Check if matrix is symmetric matrix, that is square matrix and is equal to its transpose. By default, simplifications occur before testing symmetry. They can be skipped using 'simplify=False'; while speeding things a bit, this may however induce false negatives. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [0, 1, 1, 2]) >>> m Matrix([ [0, 1], [1, 2]]) >>> m.is_symmetric() True >>> m = Matrix(2, 2, [0, 1, 2, 0]) >>> m Matrix([ [0, 1], [2, 0]]) >>> m.is_symmetric() False >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) >>> m Matrix([ [0, 0, 0], [0, 0, 0]]) >>> m.is_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) >>> m Matrix([ [ 1, x**2 + 2*x + 1, y], [(x + 1)**2, 2, 0], [ y, 0, 3]]) >>> m.is_symmetric() True If the matrix is already simplified, you may speed-up is_symmetric() test by using 'simplify=False'. >>> bool(m.is_symmetric(simplify=False)) False >>> m1 = m.expand() >>> m1.is_symmetric(simplify=False) True """ simpfunc = simplify if not isfunction(simplify): simpfunc = _simplify if simplify else lambda x: x if not self.is_square: return False return self._eval_is_symmetric(simpfunc) @property def is_upper_hessenberg(self): """Checks if the matrix is the upper-Hessenberg form. The upper hessenberg matrix has zero entries below the first subdiagonal. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a Matrix([ [1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a.is_upper_hessenberg True See Also ======== is_lower_hessenberg is_upper """ return self._eval_is_upper_hessenberg() @property def is_upper(self): """Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_upper True >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) >>> m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) >>> m.is_upper True >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) >>> m Matrix([ [4, 2, 5], [6, 1, 1]]) >>> m.is_upper False See Also ======== is_lower is_diagonal is_upper_hessenberg """ return all(self[i, j].is_zero for i in range(1, self.rows) for j in range(min(i, self.cols))) @property def is_zero_matrix(self): """Checks if a matrix is a zero matrix. A matrix is zero if every element is zero. A matrix need not be square to be considered zero. The empty matrix is zero by the principle of vacuous truth. For a matrix that may or may not be zero (e.g. contains a symbol), this will be None Examples ======== >>> from sympy import Matrix, zeros >>> from sympy.abc import x >>> a = Matrix([[0, 0], [0, 0]]) >>> b = zeros(3, 4) >>> c = Matrix([[0, 1], [0, 0]]) >>> d = Matrix([]) >>> e = Matrix([[x, 0], [0, 0]]) >>> a.is_zero_matrix True >>> b.is_zero_matrix True >>> c.is_zero_matrix False >>> d.is_zero_matrix True >>> e.is_zero_matrix """ return self._eval_is_zero_matrix() def values(self): """Return non-zero values of self.""" return self._eval_values() class MatrixOperations(MatrixRequired): """Provides basic matrix shape and elementwise operations. Should not be instantiated directly.""" def _eval_adjoint(self): return self.transpose().conjugate() def _eval_applyfunc(self, f): out = self._new(self.rows, self.cols, [f(x) for x in self]) return out def _eval_as_real_imag(self): # type: ignore return (self.applyfunc(re), self.applyfunc(im)) def _eval_conjugate(self): return self.applyfunc(lambda x: x.conjugate()) def _eval_permute_cols(self, perm): # apply the permutation to a list mapping = list(perm) def entry(i, j): return self[i, mapping[j]] return self._new(self.rows, self.cols, entry) def _eval_permute_rows(self, perm): # apply the permutation to a list mapping = list(perm) def entry(i, j): return self[mapping[i], j] return self._new(self.rows, self.cols, entry) def _eval_trace(self): return sum(self[i, i] for i in range(self.rows)) def _eval_transpose(self): return self._new(self.cols, self.rows, lambda i, j: self[j, i]) def adjoint(self): """Conjugate transpose or Hermitian conjugation.""" return self._eval_adjoint() def applyfunc(self, f): """Apply a function to each element of the matrix. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, lambda i, j: i*2+j) >>> m Matrix([ [0, 1], [2, 3]]) >>> m.applyfunc(lambda i: 2*i) Matrix([ [0, 2], [4, 6]]) """ if not callable(f): raise TypeError("`f` must be callable.") return self._eval_applyfunc(f) def as_real_imag(self, deep=True, **hints): """Returns a tuple containing the (real, imaginary) part of matrix.""" # XXX: Ignoring deep and hints... return self._eval_as_real_imag() def conjugate(self): """Return the by-element conjugation. Examples ======== >>> from sympy import SparseMatrix, I >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) >>> a Matrix([ [1, 2 + I], [3, 4], [I, -I]]) >>> a.C Matrix([ [ 1, 2 - I], [ 3, 4], [-I, I]]) See Also ======== transpose: Matrix transposition H: Hermite conjugation sympy.matrices.matrices.MatrixBase.D: Dirac conjugation """ return self._eval_conjugate() def doit(self, **kwargs): return self.applyfunc(lambda x: x.doit()) def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): """Apply evalf() to each element of self.""" options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, 'quad':quad, 'verbose':verbose} return self.applyfunc(lambda i: i.evalf(n, **options)) def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): """Apply core.function.expand to each entry of the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix(1, 1, [x*(x+1)]) Matrix([[x*(x + 1)]]) >>> _.expand() Matrix([[x**2 + x]]) """ return self.applyfunc(lambda x: x.expand( deep, modulus, power_base, power_exp, mul, log, multinomial, basic, **hints)) @property def H(self): """Return Hermite conjugate. Examples ======== >>> from sympy import Matrix, I >>> m = Matrix((0, 1 + I, 2, 3)) >>> m Matrix([ [ 0], [1 + I], [ 2], [ 3]]) >>> m.H Matrix([[0, 1 - I, 2, 3]]) See Also ======== conjugate: By-element conjugation sympy.matrices.matrices.MatrixBase.D: Dirac conjugation """ return self.T.C def permute(self, perm, orientation='rows', direction='forward'): r"""Permute the rows or columns of a matrix by the given list of swaps. Parameters ========== perm : Permutation, list, or list of lists A representation for the permutation. If it is ``Permutation``, it is used directly with some resizing with respect to the matrix size. If it is specified as list of lists, (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed from applying the product of cycles. The direction how the cyclic product is applied is described in below. If it is specified as a list, the list should represent an array form of a permutation. (e.g., ``[1, 2, 0]``) which would would form the swapping function `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`. orientation : 'rows', 'cols' A flag to control whether to permute the rows or the columns direction : 'forward', 'backward' A flag to control whether to apply the permutations from the start of the list first, or from the back of the list first. For example, if the permutation specification is ``[[0, 1], [0, 2]]``, If the flag is set to ``'forward'``, the cycle would be formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`. If the flag is set to ``'backward'``, the cycle would be formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`. If the argument ``perm`` is not in a form of list of lists, this flag takes no effect. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') Matrix([ [0, 0, 1], [1, 0, 0], [0, 1, 0]]) >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') Matrix([ [0, 1, 0], [0, 0, 1], [1, 0, 0]]) Notes ===== If a bijective function `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the permutation. If the matrix `A` is the matrix to permute, represented as a horizontal or a vertical stack of vectors: .. math:: A = \begin{bmatrix} a_0 \\ a_1 \\ \vdots \\ a_{n-1} \end{bmatrix} = \begin{bmatrix} \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} \end{bmatrix} If the matrix `B` is the result, the permutation of matrix rows is defined as: .. math:: B := \begin{bmatrix} a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)} \end{bmatrix} And the permutation of matrix columns is defined as: .. math:: B := \begin{bmatrix} \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & \cdots & \alpha_{\sigma(n-1)} \end{bmatrix} """ from sympy.combinatorics import Permutation # allow british variants and `columns` if direction == 'forwards': direction = 'forward' if direction == 'backwards': direction = 'backward' if orientation == 'columns': orientation = 'cols' if direction not in ('forward', 'backward'): raise TypeError("direction='{}' is an invalid kwarg. " "Try 'forward' or 'backward'".format(direction)) if orientation not in ('rows', 'cols'): raise TypeError("orientation='{}' is an invalid kwarg. " "Try 'rows' or 'cols'".format(orientation)) if not isinstance(perm, (Permutation, Iterable)): raise ValueError( "{} must be a list, a list of lists, " "or a SymPy permutation object.".format(perm)) # ensure all swaps are in range max_index = self.rows if orientation == 'rows' else self.cols if not all(0 <= t <= max_index for t in flatten(list(perm))): raise IndexError("`swap` indices out of range.") if perm and not isinstance(perm, Permutation) and \ isinstance(perm[0], Iterable): if direction == 'forward': perm = list(reversed(perm)) perm = Permutation(perm, size=max_index+1) else: perm = Permutation(perm, size=max_index+1) if orientation == 'rows': return self._eval_permute_rows(perm) if orientation == 'cols': return self._eval_permute_cols(perm) def permute_cols(self, swaps, direction='forward'): """Alias for ``self.permute(swaps, orientation='cols', direction=direction)`` See Also ======== permute """ return self.permute(swaps, orientation='cols', direction=direction) def permute_rows(self, swaps, direction='forward'): """Alias for ``self.permute(swaps, orientation='rows', direction=direction)`` See Also ======== permute """ return self.permute(swaps, orientation='rows', direction=direction) def refine(self, assumptions=True): """Apply refine to each element of the matrix. Examples ======== >>> from sympy import Symbol, Matrix, Abs, sqrt, Q >>> x = Symbol('x') >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) Matrix([ [ Abs(x)**2, sqrt(x**2)], [sqrt(x**2), Abs(x)**2]]) >>> _.refine(Q.real(x)) Matrix([ [ x**2, Abs(x)], [Abs(x), x**2]]) """ return self.applyfunc(lambda x: refine(x, assumptions)) def replace(self, F, G, map=False, simultaneous=True, exact=None): """Replaces Function F in Matrix entries with Function G. Examples ======== >>> from sympy import symbols, Function, Matrix >>> F, G = symbols('F, G', cls=Function) >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M Matrix([ [F(0), F(1)], [F(1), F(2)]]) >>> N = M.replace(F,G) >>> N Matrix([ [G(0), G(1)], [G(1), G(2)]]) """ return self.applyfunc( lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact)) def rot90(self, k=1): """Rotates Matrix by 90 degrees Parameters ========== k : int Specifies how many times the matrix is rotated by 90 degrees (clockwise when positive, counter-clockwise when negative). Examples ======== >>> from sympy import Matrix, symbols >>> A = Matrix(2, 2, symbols('a:d')) >>> A Matrix([ [a, b], [c, d]]) Rotating the matrix clockwise one time: >>> A.rot90(1) Matrix([ [c, a], [d, b]]) Rotating the matrix anticlockwise two times: >>> A.rot90(-2) Matrix([ [d, c], [b, a]]) """ mod = k%4 if mod == 0: return self if mod == 1: return self[::-1, ::].T if mod == 2: return self[::-1, ::-1] if mod == 3: return self[::, ::-1].T def simplify(self, **kwargs): """Apply simplify to each element of the matrix. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, sin, cos >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) Matrix([[x*sin(y)**2 + x*cos(y)**2]]) >>> _.simplify() Matrix([[x]]) """ return self.applyfunc(lambda x: x.simplify(**kwargs)) def subs(self, *args, **kwargs): # should mirror core.basic.subs """Return a new matrix with subs applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.subs(x, y) Matrix([[y]]) >>> Matrix(_).subs(y, x) Matrix([[x]]) """ if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]): args = (list(args[0]),) return self.applyfunc(lambda x: x.subs(*args, **kwargs)) def trace(self): """ Returns the trace of a square matrix i.e. the sum of the diagonal elements. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.trace() 5 """ if self.rows != self.cols: raise NonSquareMatrixError() return self._eval_trace() def transpose(self): """ Returns the transpose of the matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.transpose() Matrix([ [1, 3], [2, 4]]) >>> from sympy import Matrix, I >>> m=Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m.transpose() Matrix([ [ 1, 3], [2 + I, 4]]) >>> m.T == m.transpose() True See Also ======== conjugate: By-element conjugation """ return self._eval_transpose() @property def T(self): '''Matrix transposition''' return self.transpose() @property def C(self): '''By-element conjugation''' return self.conjugate() def n(self, *args, **kwargs): """Apply evalf() to each element of self.""" return self.evalf(*args, **kwargs) def xreplace(self, rule): # should mirror core.basic.xreplace """Return a new matrix with xreplace applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.xreplace({x: y}) Matrix([[y]]) >>> Matrix(_).xreplace({y: x}) Matrix([[x]]) """ return self.applyfunc(lambda x: x.xreplace(rule)) def _eval_simplify(self, **kwargs): # XXX: We can't use self.simplify here as mutable subclasses will # override simplify and have it return None return MatrixOperations.simplify(self, **kwargs) def _eval_trigsimp(self, **opts): from sympy.simplify.trigsimp import trigsimp return self.applyfunc(lambda x: trigsimp(x, **opts)) def upper_triangular(self, k=0): """returns the elements on and above the kth diagonal of a matrix. If k is not specified then simply returns upper-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.upper_triangular() Matrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) >>> A.upper_triangular(2) Matrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> A.upper_triangular(-1) Matrix([ [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k <= j else self.zero return self._new(self.rows, self.cols, entry) def lower_triangular(self, k=0): """returns the elements on and below the kth diagonal of a matrix. If k is not specified then simply returns lower-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.lower_triangular() Matrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) >>> A.lower_triangular(-2) Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0]]) >>> A.lower_triangular(1) Matrix([ [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k >= j else self.zero return self._new(self.rows, self.cols, entry) class MatrixArithmetic(MatrixRequired): """Provides basic matrix arithmetic operations. Should not be instantiated directly.""" _op_priority = 10.01 def _eval_Abs(self): return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j])) def _eval_add(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i, j] + other[i, j]) def _eval_matrix_mul(self, other): def entry(i, j): vec = [self[i,k]*other[k,j] for k in range(self.cols)] try: return Add(*vec) except (TypeError, SympifyError): # Some matrices don't work with `sum` or `Add` # They don't work with `sum` because `sum` tries to add `0` # Fall back to a safe way to multiply if the `Add` fails. return reduce(lambda a, b: a + b, vec) return self._new(self.rows, other.cols, entry) def _eval_matrix_mul_elementwise(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j]) def _eval_matrix_rmul(self, other): def entry(i, j): return sum(other[i,k]*self[k,j] for k in range(other.cols)) return self._new(other.rows, self.cols, entry) def _eval_pow_by_recursion(self, num): if num == 1: return self if num % 2 == 1: a, b = self, self._eval_pow_by_recursion(num - 1) else: a = b = self._eval_pow_by_recursion(num // 2) return a.multiply(b) def _eval_pow_by_cayley(self, exp): from sympy.discrete.recurrences import linrec_coeffs row = self.shape[0] p = self.charpoly() coeffs = (-p).all_coeffs()[1:] coeffs = linrec_coeffs(coeffs, exp) new_mat = self.eye(row) ans = self.zeros(row) for i in range(row): ans += coeffs[i]*new_mat new_mat *= self return ans def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None): if prevsimp is None: prevsimp = [True]*len(self) if num == 1: return self if num % 2 == 1: a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1, prevsimp=prevsimp) else: a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2, prevsimp=prevsimp) m = a.multiply(b, dotprodsimp=False) lenm = len(m) elems = [None]*lenm for i in range(lenm): if prevsimp[i]: elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True) else: elems[i] = m[i] return m._new(m.rows, m.cols, elems) def _eval_scalar_mul(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other) def _eval_scalar_rmul(self, other): return self._new(self.rows, self.cols, lambda i, j: other*self[i,j]) def _eval_Mod(self, other): return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other)) # Python arithmetic functions def __abs__(self): """Returns a new matrix with entry-wise absolute values.""" return self._eval_Abs() @call_highest_priority('__radd__') def __add__(self, other): """Return self + other, raising ShapeError if shapes do not match.""" if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented return NotImplemented other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. if hasattr(other, 'shape'): if self.shape != other.shape: raise ShapeError("Matrix size mismatch: %s + %s" % ( self.shape, other.shape)) # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): # call the highest-priority class's _eval_add a, b = self, other if a.__class__ != classof(a, b): b, a = a, b return a._eval_add(b) # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_add(self, other) raise TypeError('cannot add %s and %s' % (type(self), type(other))) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self * (self.one / other) @call_highest_priority('__rmatmul__') def __matmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__mul__(other) def __mod__(self, other): return self.applyfunc(lambda x: x % other) @call_highest_priority('__rmul__') def __mul__(self, other): """Return self*other where other is either a scalar or a matrix of compatible dimensions. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]]) True >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> A*B Matrix([ [30, 36, 42], [66, 81, 96]]) >>> B*A Traceback (most recent call last): ... ShapeError: Matrices size mismatch. >>> See Also ======== matrix_multiply_elementwise """ return self.multiply(other) def multiply(self, other, dotprodsimp=None): """Same as __mul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. """ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. Double check other is not explicitly not a Matrix. if (hasattr(other, 'shape') and len(other.shape) == 2 and (getattr(other, 'is_Matrix', True) or getattr(other, 'is_MatrixLike', True))): if self.shape[1] != other.shape[0]: raise ShapeError("Matrix size mismatch: %s * %s." % ( self.shape, other.shape)) # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): m = self._eval_matrix_mul(other) if isimpbool: return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) return m # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_matrix_mul(self, other) # if 'other' is not iterable then scalar multiplication. if not isinstance(other, Iterable): try: return self._eval_scalar_mul(other) except TypeError: pass return NotImplemented def multiply_elementwise(self, other): """Return the Hadamard product (elementwise product) of A and B Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> A.multiply_elementwise(B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== sympy.matrices.matrices.MatrixBase.cross sympy.matrices.matrices.MatrixBase.dot multiply """ if self.shape != other.shape: raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape)) return self._eval_matrix_mul_elementwise(other) def __neg__(self): return self._eval_scalar_mul(-1) @call_highest_priority('__rpow__') def __pow__(self, exp): """Return self**exp a scalar or symbol.""" return self.pow(exp) def pow(self, exp, method=None): r"""Return self**exp a scalar or symbol. Parameters ========== method : multiply, mulsimp, jordan, cayley If multiply then it returns exponentiation using recursion. If jordan then Jordan form exponentiation will be used. If cayley then the exponentiation is done using Cayley-Hamilton theorem. If mulsimp then the exponentiation is done using recursion with dotprodsimp. This specifies whether intermediate term algebraic simplification is used during naive matrix power to control expression blowup and thus speed up calculation. If None, then it heuristically decides which method to use. """ if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']: raise TypeError('No such method') if self.rows != self.cols: raise NonSquareMatrixError() a = self jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None) exp = sympify(exp) if exp.is_zero: return a._new(a.rows, a.cols, lambda i, j: int(i == j)) if exp == 1: return a diagonal = getattr(a, 'is_diagonal', None) if diagonal is not None and diagonal(): return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0) if exp.is_Number and exp % 1 == 0: if a.rows == 1: return a._new([[a[0]**exp]]) if exp < 0: exp = -exp a = a.inv() # When certain conditions are met, # Jordan block algorithm is faster than # computation by recursion. if method == 'jordan': try: return jordan_pow(exp) except MatrixError: if method == 'jordan': raise elif method == 'cayley': if not exp.is_Number or exp % 1 != 0: raise ValueError("cayley method is only valid for integer powers") return a._eval_pow_by_cayley(exp) elif method == "mulsimp": if not exp.is_Number or exp % 1 != 0: raise ValueError("mulsimp method is only valid for integer powers") return a._eval_pow_by_recursion_dotprodsimp(exp) elif method == "multiply": if not exp.is_Number or exp % 1 != 0: raise ValueError("multiply method is only valid for integer powers") return a._eval_pow_by_recursion(exp) elif method is None and exp.is_Number and exp % 1 == 0: # Decide heuristically which method to apply if a.rows == 2 and exp > 100000: return jordan_pow(exp) elif _get_intermediate_simp_bool(True, None): return a._eval_pow_by_recursion_dotprodsimp(exp) elif exp > 10000: return a._eval_pow_by_cayley(exp) else: return a._eval_pow_by_recursion(exp) if jordan_pow: try: return jordan_pow(exp) except NonInvertibleMatrixError: # Raised by jordan_pow on zero determinant matrix unless exp is # definitely known to be a non-negative integer. # Here we raise if n is definitely not a non-negative integer # but otherwise we can leave this as an unevaluated MatPow. if exp.is_integer is False or exp.is_nonnegative is False: raise from sympy.matrices.expressions import MatPow return MatPow(a, exp) @call_highest_priority('__add__') def __radd__(self, other): return self + other @call_highest_priority('__matmul__') def __rmatmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__rmul__(other) @call_highest_priority('__mul__') def __rmul__(self, other): return self.rmultiply(other) def rmultiply(self, other, dotprodsimp=None): """Same as __rmul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. """ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. Double check other is not explicitly not a Matrix. if (hasattr(other, 'shape') and len(other.shape) == 2 and (getattr(other, 'is_Matrix', True) or getattr(other, 'is_MatrixLike', True))): if self.shape[0] != other.shape[1]: raise ShapeError("Matrix size mismatch.") # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): m = self._eval_matrix_rmul(other) if isimpbool: return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) return m # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_matrix_rmul(self, other) # if 'other' is not iterable then scalar multiplication. if not isinstance(other, Iterable): try: return self._eval_scalar_rmul(other) except TypeError: pass return NotImplemented @call_highest_priority('__sub__') def __rsub__(self, a): return (-self) + a @call_highest_priority('__rsub__') def __sub__(self, a): return self + (-a) class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties, MatrixSpecial, MatrixShaping): """All common matrix operations including basic arithmetic, shaping, and special matrices like `zeros`, and `eye`.""" _diff_wrt = True # type: bool class _MinimalMatrix: """Class providing the minimum functionality for a matrix-like object and implementing every method required for a `MatrixRequired`. This class does not have everything needed to become a full-fledged SymPy object, but it will satisfy the requirements of anything inheriting from `MatrixRequired`. If you wish to make a specialized matrix type, make sure to implement these methods and properties with the exception of `__init__` and `__repr__` which are included for convenience.""" is_MatrixLike = True _sympify = staticmethod(sympify) _class_priority = 3 zero = S.Zero one = S.One is_Matrix = True is_MatrixExpr = False @classmethod def _new(cls, *args, **kwargs): return cls(*args, **kwargs) def __init__(self, rows, cols=None, mat=None, copy=False): if isfunction(mat): # if we passed in a function, use that to populate the indices mat = list(mat(i, j) for i in range(rows) for j in range(cols)) if cols is None and mat is None: mat = rows rows, cols = getattr(mat, 'shape', (rows, cols)) try: # if we passed in a list of lists, flatten it and set the size if cols is None and mat is None: mat = rows cols = len(mat[0]) rows = len(mat) mat = [x for l in mat for x in l] except (IndexError, TypeError): pass self.mat = tuple(self._sympify(x) for x in mat) self.rows, self.cols = rows, cols if self.rows is None or self.cols is None: raise NotImplementedError("Cannot initialize matrix with given parameters") def __getitem__(self, key): def _normalize_slices(row_slice, col_slice): """Ensure that row_slice and col_slice do not have `None` in their arguments. Any integers are converted to slices of length 1""" if not isinstance(row_slice, slice): row_slice = slice(row_slice, row_slice + 1, None) row_slice = slice(*row_slice.indices(self.rows)) if not isinstance(col_slice, slice): col_slice = slice(col_slice, col_slice + 1, None) col_slice = slice(*col_slice.indices(self.cols)) return (row_slice, col_slice) def _coord_to_index(i, j): """Return the index in _mat corresponding to the (i,j) position in the matrix. """ return i * self.cols + j if isinstance(key, tuple): i, j = key if isinstance(i, slice) or isinstance(j, slice): # if the coordinates are not slices, make them so # and expand the slices so they don't contain `None` i, j = _normalize_slices(i, j) rowsList, colsList = list(range(self.rows))[i], \ list(range(self.cols))[j] indices = (i * self.cols + j for i in rowsList for j in colsList) return self._new(len(rowsList), len(colsList), list(self.mat[i] for i in indices)) # if the key is a tuple of ints, change # it to an array index key = _coord_to_index(i, j) return self.mat[key] def __eq__(self, other): try: classof(self, other) except TypeError: return False return ( self.shape == other.shape and list(self) == list(other)) def __len__(self): return self.rows*self.cols def __repr__(self): return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols, self.mat) @property def shape(self): return (self.rows, self.cols) class _CastableMatrix: # this is needed here ONLY FOR TESTS. def as_mutable(self): return self def as_immutable(self): return self class _MatrixWrapper: """Wrapper class providing the minimum functionality for a matrix-like object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix math operations should work on matrix-like objects. This one is intended for matrix-like objects which use the same indexing format as SymPy with respect to returning matrix elements instead of rows for non-tuple indexes. """ is_Matrix = False # needs to be here because of __getattr__ is_MatrixLike = True def __init__(self, mat, shape): self.mat = mat self.shape = shape self.rows, self.cols = shape def __getitem__(self, key): if isinstance(key, tuple): return sympify(self.mat.__getitem__(key)) return sympify(self.mat.__getitem__((key // self.rows, key % self.cols))) def __iter__(self): # supports numpy.matrix and numpy.array mat = self.mat cols = self.cols return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols)) class MatrixKind(Kind): """ Kind for all matrices in SymPy. Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``, but any expression representing the matrix can have this. Parameters ========== element_kind : Kind Kind of the element. Default is :class:`sympy.core.kind.NumberKind`, which means that the matrix contains only numbers. Examples ======== Any instance of matrix class has ``MatrixKind``: >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 2,2) >>> A.kind MatrixKind(NumberKind) Although expression representing a matrix may be not instance of matrix class, it will have ``MatrixKind`` as well: >>> from sympy import MatrixExpr, Integral >>> from sympy.abc import x >>> intM = Integral(A, x) >>> isinstance(intM, MatrixExpr) False >>> intM.kind MatrixKind(NumberKind) Use ``isinstance()`` to check for ``MatrixKind`` without specifying the element kind. Use ``is`` with specifying the element kind: >>> from sympy import Matrix >>> from sympy.core import NumberKind >>> from sympy.matrices import MatrixKind >>> M = Matrix([1, 2]) >>> isinstance(M.kind, MatrixKind) True >>> M.kind is MatrixKind(NumberKind) True See Also ======== sympy.core.kind.NumberKind sympy.core.kind.UndefinedKind sympy.core.containers.TupleKind sympy.sets.sets.SetKind """ def __new__(cls, element_kind=NumberKind): obj = super().__new__(cls, element_kind) obj.element_kind = element_kind return obj def __repr__(self): return "MatrixKind(%s)" % self.element_kind def _matrixify(mat): """If `mat` is a Matrix or is matrix-like, return a Matrix or MatrixWrapper object. Otherwise `mat` is passed through without modification.""" if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False): return mat if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)): return mat shape = None if hasattr(mat, 'shape'): # numpy, scipy.sparse if len(mat.shape) == 2: shape = mat.shape elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath shape = (mat.rows, mat.cols) if shape: return _MatrixWrapper(mat, shape) return mat def a2idx(j, n=None): """Return integer after making positive and validating against n.""" if not isinstance(j, int): jindex = getattr(j, '__index__', None) if jindex is not None: j = jindex() else: raise IndexError("Invalid index a[%r]" % (j,)) if n is not None: if j < 0: j += n if not (j >= 0 and j < n): raise IndexError("Index out of range: a[%s]" % (j,)) return int(j) def classof(A, B): """ Get the type of the result when combining matrices of different types. Currently the strategy is that immutability is contagious. Examples ======== >>> from sympy import Matrix, ImmutableMatrix >>> from sympy.matrices.common import classof >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) >>> classof(M, IM) <class 'sympy.matrices.immutable.ImmutableDenseMatrix'> """ priority_A = getattr(A, '_class_priority', None) priority_B = getattr(B, '_class_priority', None) if None not in (priority_A, priority_B): if A._class_priority > B._class_priority: return A.__class__ else: return B.__class__ try: import numpy except ImportError: pass else: if isinstance(A, numpy.ndarray): return B.__class__ if isinstance(B, numpy.ndarray): return A.__class__ raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
87952a4a3046267f4a8befe583817a7a6f22ee8ff7fa41409b4747b684837aa1
import random from sympy.core.basic import Basic from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.trigonometric import cos, sin from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from .common import ShapeError from .decompositions import _cholesky, _LDLdecomposition from .matrices import MatrixBase from .repmatrix import MutableRepMatrix, RepMatrix from .solvers import _lower_triangular_solve, _upper_triangular_solve def _iszero(x): """Returns True if x is zero.""" return x.is_zero class DenseMatrix(RepMatrix): """Matrix implementation based on DomainMatrix as the internal representation""" # # DenseMatrix is a superclass for both MutableDenseMatrix and # ImmutableDenseMatrix. Methods shared by both classes but not for the # Sparse classes should be implemented here. # is_MatrixExpr = False # type: bool _op_priority = 10.01 _class_priority = 4 @property def _mat(self): sympy_deprecation_warning( """ The private _mat attribute of Matrix is deprecated. Use the .flat() method instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-private-matrix-attributes" ) return self.flat() def _eval_inverse(self, **kwargs): return self.inv(method=kwargs.get('method', 'GE'), iszerofunc=kwargs.get('iszerofunc', _iszero), try_block_diag=kwargs.get('try_block_diag', False)) def as_immutable(self): """Returns an Immutable version of this Matrix """ from .immutable import ImmutableDenseMatrix as cls return cls._fromrep(self._rep.copy()) def as_mutable(self): """Returns a mutable version of this matrix Examples ======== >>> from sympy import ImmutableMatrix >>> X = ImmutableMatrix([[1, 2], [3, 4]]) >>> Y = X.as_mutable() >>> Y[1, 1] = 5 # Can set values in Y >>> Y Matrix([ [1, 2], [3, 5]]) """ return Matrix(self) def cholesky(self, hermitian=True): return _cholesky(self, hermitian=hermitian) def LDLdecomposition(self, hermitian=True): return _LDLdecomposition(self, hermitian=hermitian) def lower_triangular_solve(self, rhs): return _lower_triangular_solve(self, rhs) def upper_triangular_solve(self, rhs): return _upper_triangular_solve(self, rhs) cholesky.__doc__ = _cholesky.__doc__ LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ def _force_mutable(x): """Return a matrix as a Matrix, otherwise return x.""" if getattr(x, 'is_Matrix', False): return x.as_mutable() elif isinstance(x, Basic): return x elif hasattr(x, '__array__'): a = x.__array__() if len(a.shape) == 0: return sympify(a) return Matrix(x) return x class MutableDenseMatrix(DenseMatrix, MutableRepMatrix): def simplify(self, **kwargs): """Applies simplify to the elements of a matrix in place. This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure)) See Also ======== sympy.simplify.simplify.simplify """ from sympy.simplify.simplify import simplify as _simplify for (i, j), element in self.todok().items(): self[i, j] = _simplify(element, **kwargs) MutableMatrix = Matrix = MutableDenseMatrix ########### # Numpy Utility Functions: # list2numpy, matrix2numpy, symmarray, rot_axis[123] ########### def list2numpy(l, dtype=object): # pragma: no cover """Converts Python list of SymPy expressions to a NumPy array. See Also ======== matrix2numpy """ from numpy import empty a = empty(len(l), dtype) for i, s in enumerate(l): a[i] = s return a def matrix2numpy(m, dtype=object): # pragma: no cover """Converts SymPy's matrix to a NumPy array. See Also ======== list2numpy """ from numpy import empty a = empty(m.shape, dtype) for i in range(m.rows): for j in range(m.cols): a[i, j] = m[i, j] return a def rot_axis3(theta): """Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis. Examples ======== >>> from sympy import pi, rot_axis3 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_axis3(theta) Matrix([ [ 1/2, sqrt(3)/2, 0], [-sqrt(3)/2, 1/2, 0], [ 0, 0, 1]]) If we rotate by pi/2 (90 degrees): >>> rot_axis3(pi/2) Matrix([ [ 0, 1, 0], [-1, 0, 0], [ 0, 0, 1]]) See Also ======== rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis """ ct = cos(theta) st = sin(theta) lil = ((ct, st, 0), (-st, ct, 0), (0, 0, 1)) return Matrix(lil) def rot_axis2(theta): """Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis. Examples ======== >>> from sympy import pi, rot_axis2 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_axis2(theta) Matrix([ [ 1/2, 0, -sqrt(3)/2], [ 0, 1, 0], [sqrt(3)/2, 0, 1/2]]) If we rotate by pi/2 (90 degrees): >>> rot_axis2(pi/2) Matrix([ [0, 0, -1], [0, 1, 0], [1, 0, 0]]) See Also ======== rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis """ ct = cos(theta) st = sin(theta) lil = ((ct, 0, -st), (0, 1, 0), (st, 0, ct)) return Matrix(lil) def rot_axis1(theta): """Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis. Examples ======== >>> from sympy import pi, rot_axis1 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_axis1(theta) Matrix([ [1, 0, 0], [0, 1/2, sqrt(3)/2], [0, -sqrt(3)/2, 1/2]]) If we rotate by pi/2 (90 degrees): >>> rot_axis1(pi/2) Matrix([ [1, 0, 0], [0, 0, 1], [0, -1, 0]]) See Also ======== rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis """ ct = cos(theta) st = sin(theta) lil = ((1, 0, 0), (0, ct, st), (0, -st, ct)) return Matrix(lil) @doctest_depends_on(modules=('numpy',)) def symarray(prefix, shape, **kwargs): # pragma: no cover r"""Create a numpy ndarray of symbols (as an object array). The created symbols are named ``prefix_i1_i2_``... You should thus provide a non-empty prefix if you want your symbols to be unique for different output arrays, as SymPy symbols with identical names are the same object. Parameters ---------- prefix : string A prefix prepended to the name of every symbol. shape : int or tuple Shape of the created array. If an int, the array is one-dimensional; for more than one dimension the shape must be a tuple. \*\*kwargs : dict keyword arguments passed on to Symbol Examples ======== These doctests require numpy. >>> from sympy import symarray >>> symarray('', 3) [_0 _1 _2] If you want multiple symarrays to contain distinct symbols, you *must* provide unique prefixes: >>> a = symarray('', 3) >>> b = symarray('', 3) >>> a[0] == b[0] True >>> a = symarray('a', 3) >>> b = symarray('b', 3) >>> a[0] == b[0] False Creating symarrays with a prefix: >>> symarray('a', 3) [a_0 a_1 a_2] For more than one dimension, the shape must be given as a tuple: >>> symarray('a', (2, 3)) [[a_0_0 a_0_1 a_0_2] [a_1_0 a_1_1 a_1_2]] >>> symarray('a', (2, 3, 2)) [[[a_0_0_0 a_0_0_1] [a_0_1_0 a_0_1_1] [a_0_2_0 a_0_2_1]] <BLANKLINE> [[a_1_0_0 a_1_0_1] [a_1_1_0 a_1_1_1] [a_1_2_0 a_1_2_1]]] For setting assumptions of the underlying Symbols: >>> [s.is_real for s in symarray('a', 2, real=True)] [True, True] """ from numpy import empty, ndindex arr = empty(shape, dtype=object) for index in ndindex(shape): arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))), **kwargs) return arr ############### # Functions ############### def casoratian(seqs, n, zero=True): """Given linear difference operator L of order 'k' and homogeneous equation Ly = 0 we want to compute kernel of L, which is a set of 'k' sequences: a(n), b(n), ... z(n). Solutions of L are linearly independent iff their Casoratian, denoted as C(a, b, ..., z), do not vanish for n = 0. Casoratian is defined by k x k determinant:: + a(n) b(n) . . . z(n) + | a(n+1) b(n+1) . . . z(n+1) | | . . . . | | . . . . | | . . . . | + a(n+k-1) b(n+k-1) . . . z(n+k-1) + It proves very useful in rsolve_hyper() where it is applied to a generating set of a recurrence to factor out linearly dependent solutions and return a basis: >>> from sympy import Symbol, casoratian, factorial >>> n = Symbol('n', integer=True) Exponential and factorial are linearly independent: >>> casoratian([2**n, factorial(n)], n) != 0 True """ seqs = list(map(sympify, seqs)) if not zero: f = lambda i, j: seqs[j].subs(n, n + i) else: f = lambda i, j: seqs[j].subs(n, i) k = len(seqs) return Matrix(k, k, f).det() def eye(*args, **kwargs): """Create square identity matrix n x n See Also ======== diag zeros ones """ return Matrix.eye(*args, **kwargs) def diag(*values, strict=True, unpack=False, **kwargs): """Returns a matrix with the provided values placed on the diagonal. If non-square matrices are included, they will produce a block-diagonal matrix. Examples ======== This version of diag is a thin wrapper to Matrix.diag that differs in that it treats all lists like matrices -- even when a single list is given. If this is not desired, either put a `*` before the list or set `unpack=True`. >>> from sympy import diag >>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3]) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> diag([1, 2, 3]) # a column vector Matrix([ [1], [2], [3]]) See Also ======== .common.MatrixCommon.eye .common.MatrixCommon.diagonal - to extract a diagonal .common.MatrixCommon.diag .expressions.blockmatrix.BlockMatrix """ return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs) def GramSchmidt(vlist, orthonormal=False): """Apply the Gram-Schmidt process to a set of vectors. Parameters ========== vlist : List of Matrix Vectors to be orthogonalized for. orthonormal : Bool, optional If true, return an orthonormal basis. Returns ======= vlist : List of Matrix Orthogonalized vectors Notes ===== This routine is mostly duplicate from ``Matrix.orthogonalize``, except for some difference that this always raises error when linearly dependent vectors are found, and the keyword ``normalize`` has been named as ``orthonormal`` in this function. See Also ======== .matrices.MatrixSubspaces.orthogonalize References ========== .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process """ return MutableDenseMatrix.orthogonalize( *vlist, normalize=orthonormal, rankcheck=True ) def hessian(f, varlist, constraints=()): """Compute Hessian matrix for a function f wrt parameters in varlist which may be given as a sequence or a row/column vector. A list of constraints may optionally be given. Examples ======== >>> from sympy import Function, hessian, pprint >>> from sympy.abc import x, y >>> f = Function('f')(x, y) >>> g1 = Function('g')(x, y) >>> g2 = x**2 + 3*y >>> pprint(hessian(f, (x, y), [g1, g2])) [ d d ] [ 0 0 --(g(x, y)) --(g(x, y)) ] [ dx dy ] [ ] [ 0 0 2*x 3 ] [ ] [ 2 2 ] [d d d ] [--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))] [dx 2 dy dx ] [ dx ] [ ] [ 2 2 ] [d d d ] [--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ] [dy dy dx 2 ] [ dy ] References ========== .. [1] https://en.wikipedia.org/wiki/Hessian_matrix See Also ======== sympy.matrices.matrices.MatrixCalculus.jacobian wronskian """ # f is the expression representing a function f, return regular matrix if isinstance(varlist, MatrixBase): if 1 not in varlist.shape: raise ShapeError("`varlist` must be a column or row vector.") if varlist.cols == 1: varlist = varlist.T varlist = varlist.tolist()[0] if is_sequence(varlist): n = len(varlist) if not n: raise ShapeError("`len(varlist)` must not be zero.") else: raise ValueError("Improper variable list in hessian function") if not getattr(f, 'diff'): # check differentiability raise ValueError("Function `f` (%s) is not differentiable" % f) m = len(constraints) N = m + n out = zeros(N) for k, g in enumerate(constraints): if not getattr(g, 'diff'): # check differentiability raise ValueError("Function `f` (%s) is not differentiable" % f) for i in range(n): out[k, i + m] = g.diff(varlist[i]) for i in range(n): for j in range(i, n): out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j]) for i in range(N): for j in range(i + 1, N): out[j, i] = out[i, j] return out def jordan_cell(eigenval, n): """ Create a Jordan block: Examples ======== >>> from sympy import jordan_cell >>> from sympy.abc import x >>> jordan_cell(x, 4) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) """ return Matrix.jordan_block(size=n, eigenvalue=eigenval) def matrix_multiply_elementwise(A, B): """Return the Hadamard product (elementwise product) of A and B >>> from sympy import Matrix, matrix_multiply_elementwise >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> matrix_multiply_elementwise(A, B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== sympy.matrices.common.MatrixCommon.__mul__ """ return A.multiply_elementwise(B) 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') return Matrix.ones(*args, **kwargs) def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False, percent=100, prng=None): """Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted the matrix will be square. If ``symmetric`` is True the matrix must be square. If ``percent`` is less than 100 then only approximately the given percentage of elements will be non-zero. The pseudo-random number generator used to generate matrix is chosen in the following way. * If ``prng`` is supplied, it will be used as random number generator. It should be an instance of ``random.Random``, or at least have ``randint`` and ``shuffle`` methods with same signatures. * if ``prng`` is not supplied but ``seed`` is supplied, then new ``random.Random`` with given ``seed`` will be created; * otherwise, a new ``random.Random`` with default seed will be used. Examples ======== >>> from sympy import randMatrix >>> randMatrix(3) # doctest:+SKIP [25, 45, 27] [44, 54, 9] [23, 96, 46] >>> randMatrix(3, 2) # doctest:+SKIP [87, 29] [23, 37] [90, 26] >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP [0, 2, 0] [2, 0, 1] [0, 0, 1] >>> randMatrix(3, symmetric=True) # doctest:+SKIP [85, 26, 29] [26, 71, 43] [29, 43, 57] >>> A = randMatrix(3, seed=1) >>> B = randMatrix(3, seed=2) >>> A == B False >>> A == randMatrix(3, seed=1) True >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP [77, 70, 0], [70, 0, 0], [ 0, 0, 88] """ # Note that ``Random()`` is equivalent to ``Random(None)`` prng = prng or random.Random(seed) if c is None: c = r if symmetric and r != c: raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c)) ij = range(r * c) if percent != 100: ij = prng.sample(ij, int(len(ij)*percent // 100)) m = zeros(r, c) if not symmetric: for ijk in ij: i, j = divmod(ijk, c) m[i, j] = prng.randint(min, max) else: for ijk in ij: i, j = divmod(ijk, c) if i <= j: m[i, j] = m[j, i] = prng.randint(min, max) return m def wronskian(functions, var, method='bareiss'): """ Compute Wronskian for [] of functions :: | f1 f2 ... fn | | f1' f2' ... fn' | | . . . . | W(f1, ..., fn) = | . . . . | | . . . . | | (n) (n) (n) | | D (f1) D (f2) ... D (fn) | see: https://en.wikipedia.org/wiki/Wronskian See Also ======== sympy.matrices.matrices.MatrixCalculus.jacobian hessian """ for index in range(0, len(functions)): functions[index] = sympify(functions[index]) n = len(functions) if n == 0: return S.One W = Matrix(n, n, lambda i, j: functions[i].diff(var, j)) return W.det(method) def zeros(*args, **kwargs): """Returns a matrix of zeros with ``rows`` rows and ``cols`` columns; if ``cols`` is omitted a square matrix will be returned. See Also ======== ones eye diag """ if 'c' in kwargs: kwargs['cols'] = kwargs.pop('c') return Matrix.zeros(*args, **kwargs)
b37798f08a9ab7d36f9fc3d90ead29c3bcc86906ef8c9f933ff1b01882929ddb
from sympy.core.function import expand_mul from sympy.core.symbol import Dummy, uniquely_named_symbol, symbols from sympy.utilities.iterables import numbered_symbols from .common import ShapeError, NonSquareMatrixError, NonInvertibleMatrixError from .eigen import _fuzzy_positive_definite from .utilities import _get_intermediate_simp, _iszero def _diagonal_solve(M, rhs): """Solves ``Ax = B`` efficiently, where A is a diagonal Matrix, with non-zero diagonal entries. Examples ======== >>> from sympy import Matrix, eye >>> A = eye(2)*2 >>> B = Matrix([[1, 2], [3, 4]]) >>> A.diagonal_solve(B) == B/2 True See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve LDLsolve LUsolve QRsolve pinv_solve """ if not M.is_diagonal(): raise TypeError("Matrix should be diagonal") if rhs.rows != M.rows: raise TypeError("Size mis-match") return M._new( rhs.rows, rhs.cols, lambda i, j: rhs[i, j] / M[i, i]) def _lower_triangular_solve(M, rhs): """Solves ``Ax = B``, where A is a lower triangular matrix. See Also ======== upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if rhs.rows != M.rows: raise ShapeError("Matrices size mismatch.") if not M.is_lower: raise ValueError("Matrix must be lower triangular.") dps = _get_intermediate_simp() X = MutableDenseMatrix.zeros(M.rows, rhs.cols) for j in range(rhs.cols): for i in range(M.rows): if M[i, i] == 0: raise TypeError("Matrix must be non-singular.") X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j] for k in range(i))) / M[i, i]) return M._new(X) def _lower_triangular_solve_sparse(M, rhs): """Solves ``Ax = B``, where A is a lower triangular matrix. See Also ======== upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if rhs.rows != M.rows: raise ShapeError("Matrices size mismatch.") if not M.is_lower: raise ValueError("Matrix must be lower triangular.") dps = _get_intermediate_simp() rows = [[] for i in range(M.rows)] for i, j, v in M.row_list(): if i > j: rows[i].append((j, v)) X = rhs.as_mutable() for j in range(rhs.cols): for i in range(rhs.rows): for u, v in rows[i]: X[i, j] -= v*X[u, j] X[i, j] = dps(X[i, j] / M[i, i]) return M._new(X) def _upper_triangular_solve(M, rhs): """Solves ``Ax = B``, where A is an upper triangular matrix. See Also ======== lower_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if rhs.rows != M.rows: raise ShapeError("Matrix size mismatch.") if not M.is_upper: raise TypeError("Matrix is not upper triangular.") dps = _get_intermediate_simp() X = MutableDenseMatrix.zeros(M.rows, rhs.cols) for j in range(rhs.cols): for i in reversed(range(M.rows)): if M[i, i] == 0: raise ValueError("Matrix must be non-singular.") X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j] for k in range(i + 1, M.rows))) / M[i, i]) return M._new(X) def _upper_triangular_solve_sparse(M, rhs): """Solves ``Ax = B``, where A is an upper triangular matrix. See Also ======== lower_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if rhs.rows != M.rows: raise ShapeError("Matrix size mismatch.") if not M.is_upper: raise TypeError("Matrix is not upper triangular.") dps = _get_intermediate_simp() rows = [[] for i in range(M.rows)] for i, j, v in M.row_list(): if i < j: rows[i].append((j, v)) X = rhs.as_mutable() for j in range(rhs.cols): for i in reversed(range(rhs.rows)): for u, v in reversed(rows[i]): X[i, j] -= v*X[u, j] X[i, j] = dps(X[i, j] / M[i, i]) return M._new(X) def _cholesky_solve(M, rhs): """Solves ``Ax = B`` using Cholesky decomposition, for a general square non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ if M.rows < M.cols: raise NotImplementedError( 'Under-determined System. Try M.gauss_jordan_solve(rhs)') hermitian = True reform = False if M.is_symmetric(): hermitian = False elif not M.is_hermitian: reform = True if reform or _fuzzy_positive_definite(M) is False: H = M.H M = H.multiply(M) rhs = H.multiply(rhs) hermitian = not M.is_symmetric() L = M.cholesky(hermitian=hermitian) Y = L.lower_triangular_solve(rhs) if hermitian: return (L.H).upper_triangular_solve(Y) else: return (L.T).upper_triangular_solve(Y) def _LDLsolve(M, rhs): """Solves ``Ax = B`` using LDL decomposition, for a general square and non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. Examples ======== >>> from sympy import Matrix, eye >>> A = eye(2)*2 >>> B = Matrix([[1, 2], [3, 4]]) >>> A.LDLsolve(B) == B/2 True See Also ======== sympy.matrices.dense.DenseMatrix.LDLdecomposition sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LUsolve QRsolve pinv_solve """ if M.rows < M.cols: raise NotImplementedError( 'Under-determined System. Try M.gauss_jordan_solve(rhs)') hermitian = True reform = False if M.is_symmetric(): hermitian = False elif not M.is_hermitian: reform = True if reform or _fuzzy_positive_definite(M) is False: H = M.H M = H.multiply(M) rhs = H.multiply(rhs) hermitian = not M.is_symmetric() L, D = M.LDLdecomposition(hermitian=hermitian) Y = L.lower_triangular_solve(rhs) Z = D.diagonal_solve(Y) if hermitian: return (L.H).upper_triangular_solve(Z) else: return (L.T).upper_triangular_solve(Z) def _LUsolve(M, rhs, iszerofunc=_iszero): """Solve the linear system ``Ax = rhs`` for ``x`` where ``A = M``. This is for symbolic matrices, for real or complex ones use mpmath.lu_solve or mpmath.qr_solve. See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve QRsolve pinv_solve LUdecomposition """ if rhs.rows != M.rows: raise ShapeError( "``M`` and ``rhs`` must have the same number of rows.") m = M.rows n = M.cols if m < n: raise NotImplementedError("Underdetermined systems not supported.") try: A, perm = M.LUdecomposition_Simple( iszerofunc=_iszero, rankcheck=True) except ValueError: raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") dps = _get_intermediate_simp() b = rhs.permute_rows(perm).as_mutable() # forward substitution, all diag entries are scaled to 1 for i in range(m): for j in range(min(i, n)): scale = A[i, j] b.zip_row_op(i, j, lambda x, y: dps(x - y * scale)) # consistency check for overdetermined systems if m > n: for i in range(n, m): for j in range(b.cols): if not iszerofunc(b[i, j]): raise ValueError("The system is inconsistent.") b = b[0:n, :] # truncate zero rows if consistent # backward substitution for i in range(n - 1, -1, -1): for j in range(i + 1, n): scale = A[i, j] b.zip_row_op(i, j, lambda x, y: dps(x - y * scale)) scale = A[i, i] b.row_op(i, lambda x, _: dps(x / scale)) return rhs.__class__(b) def _QRsolve(M, b): """Solve the linear system ``Ax = b``. ``M`` is the matrix ``A``, the method argument is the vector ``b``. The method returns the solution vector ``x``. If ``b`` is a matrix, the system is solved for each column of ``b`` and the return value is a matrix of the same shape as ``b``. This method is slower (approximately by a factor of 2) but more stable for floating-point arithmetic than the LUsolve method. However, LUsolve usually uses an exact arithmetic, so you do not need to use QRsolve. This is mainly for educational purposes and symbolic matrices, for real (or complex) matrices use mpmath.qr_solve. See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve pinv_solve QRdecomposition """ dps = _get_intermediate_simp(expand_mul, expand_mul) Q, R = M.QRdecomposition() y = Q.T * b # back substitution to solve R*x = y: # We build up the result "backwards" in the vector 'x' and reverse it # only in the end. x = [] n = R.rows for j in range(n - 1, -1, -1): tmp = y[j, :] for k in range(j + 1, n): tmp -= R[j, k] * x[n - 1 - k] tmp = dps(tmp) x.append(tmp / R[j, j]) return M.vstack(*x[::-1]) def _gauss_jordan_solve(M, B, freevar=False): """ Solves ``Ax = B`` using Gauss Jordan elimination. There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, it will be returned parametrically. If no solutions exist, It will throw ValueError. Parameters ========== B : Matrix The right hand side of the equation to be solved for. Must have the same number of rows as matrix A. freevar : boolean, optional Flag, when set to `True` will return the indices of the free variables in the solutions (column Matrix), for a system that is undetermined (e.g. A has more columns than rows), for which infinite solutions are possible, in terms of arbitrary values of free variables. Default `False`. Returns ======= x : Matrix The matrix that will satisfy ``Ax = B``. Will have as many rows as matrix A has columns, and as many columns as matrix B. params : Matrix If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of arbitrary parameters. These arbitrary parameters are returned as params Matrix. free_var_index : List, optional If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of arbitrary values of free variables. Then the indices of the free variables in the solutions (column Matrix) are returned by free_var_index, if the flag `freevar` is set to `True`. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) >>> B = Matrix([7, 12, 4]) >>> sol, params = A.gauss_jordan_solve(B) >>> sol Matrix([ [-2*tau0 - 3*tau1 + 2], [ tau0], [ 2*tau1 + 5], [ tau1]]) >>> params Matrix([ [tau0], [tau1]]) >>> taus_zeroes = { tau:0 for tau in params } >>> sol_unique = sol.xreplace(taus_zeroes) >>> sol_unique Matrix([ [2], [0], [5], [0]]) >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> B = Matrix([3, 6, 9]) >>> sol, params = A.gauss_jordan_solve(B) >>> sol Matrix([ [-1], [ 2], [ 0]]) >>> params Matrix(0, 1, []) >>> A = Matrix([[2, -7], [-1, 4]]) >>> B = Matrix([[-21, 3], [12, -2]]) >>> sol, params = A.gauss_jordan_solve(B) >>> sol Matrix([ [0, -2], [3, -1]]) >>> params Matrix(0, 2, []) >>> from sympy import Matrix >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) >>> B = Matrix([7, 12, 4]) >>> sol, params, freevars = A.gauss_jordan_solve(B, freevar=True) >>> sol Matrix([ [-2*tau0 - 3*tau1 + 2], [ tau0], [ 2*tau1 + 5], [ tau1]]) >>> params Matrix([ [tau0], [tau1]]) >>> freevars [1, 3] See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv References ========== .. [1] https://en.wikipedia.org/wiki/Gaussian_elimination """ from sympy.matrices import Matrix, zeros cls = M.__class__ aug = M.hstack(M.copy(), B.copy()) B_cols = B.cols row, col = aug[:, :-B_cols].shape # solve by reduced row echelon form A, pivots = aug.rref(simplify=True) A, v = A[:, :-B_cols], A[:, -B_cols:] pivots = list(filter(lambda p: p < col, pivots)) rank = len(pivots) # Get index of free symbols (free parameters) # non-pivots columns are free variables free_var_index = [c for c in range(A.cols) if c not in pivots] # Bring to block form permutation = Matrix(pivots + free_var_index).T # check for existence of solutions # rank of aug Matrix should be equal to rank of coefficient matrix if not v[rank:, :].is_zero_matrix: raise ValueError("Linear system has no solution") # Free parameters # what are current unnumbered free symbol names? name = uniquely_named_symbol('tau', aug, compare=lambda i: str(i).rstrip('1234567890'), modify=lambda s: '_' + s).name gen = numbered_symbols(name) tau = Matrix([next(gen) for k in range((col - rank)*B_cols)]).reshape( col - rank, B_cols) # Full parametric solution V = A[:rank, free_var_index] vt = v[:rank, :] free_sol = tau.vstack(vt - V * tau, tau) # Undo permutation sol = zeros(col, B_cols) for k in range(col): sol[permutation[k], :] = free_sol[k,:] sol, tau = cls(sol), cls(tau) if freevar: return sol, tau, free_var_index else: return sol, tau def _pinv_solve(M, B, arbitrary_matrix=None): """Solve ``Ax = B`` using the Moore-Penrose pseudoinverse. There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, one will be returned based on the value of arbitrary_matrix. If no solutions exist, the least-squares solution is returned. Parameters ========== B : Matrix The right hand side of the equation to be solved for. Must have the same number of rows as matrix A. arbitrary_matrix : Matrix If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary matrix. This parameter may be set to a specific matrix to use for that purpose; if so, it must be the same shape as x, with as many rows as matrix A has columns, and as many columns as matrix B. If left as None, an appropriate matrix containing dummy symbols in the form of ``wn_m`` will be used, with n and m being row and column position of each symbol. Returns ======= x : Matrix The matrix that will satisfy ``Ax = B``. Will have as many rows as matrix A has columns, and as many columns as matrix B. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> B = Matrix([7, 8]) >>> A.pinv_solve(B) Matrix([ [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18], [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9], [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]]) >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0])) Matrix([ [-55/18], [ 1/9], [ 59/18]]) See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv Notes ===== This may return either exact solutions or least squares solutions. To determine which, check ``A * A.pinv() * B == B``. It will be True if exact solutions exist, and False if only a least-squares solution exists. Be aware that the left hand side of that equation may need to be simplified to correctly compare to the right hand side. References ========== .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system """ from sympy.matrices import eye A = M A_pinv = M.pinv() if arbitrary_matrix is None: rows, cols = A.cols, B.cols w = symbols('w:{}_:{}'.format(rows, cols), cls=Dummy) arbitrary_matrix = M.__class__(cols, rows, w).T return A_pinv.multiply(B) + (eye(A.cols) - A_pinv.multiply(A)).multiply(arbitrary_matrix) def _solve(M, rhs, method='GJ'): """Solves linear equation where the unique solution exists. Parameters ========== rhs : Matrix Vector representing the right hand side of the linear equation. method : string, optional If set to ``'GJ'`` or ``'GE'``, the Gauss-Jordan elimination will be used, which is implemented in the routine ``gauss_jordan_solve``. If set to ``'LU'``, ``LUsolve`` routine will be used. If set to ``'QR'``, ``QRsolve`` routine will be used. If set to ``'PINV'``, ``pinv_solve`` routine will be used. It also supports the methods available for special linear systems For positive definite systems: If set to ``'CH'``, ``cholesky_solve`` routine will be used. If set to ``'LDL'``, ``LDLsolve`` routine will be used. To use a different method and to compute the solution via the inverse, use a method defined in the .inv() docstring. Returns ======= solutions : Matrix Vector representing the solution. Raises ====== ValueError If there is not a unique solution then a ``ValueError`` will be raised. If ``M`` is not square, a ``ValueError`` and a different routine for solving the system will be suggested. """ if method in ('GJ', 'GE'): try: soln, param = M.gauss_jordan_solve(rhs) if param: raise NonInvertibleMatrixError("Matrix det == 0; not invertible. " "Try ``M.gauss_jordan_solve(rhs)`` to obtain a parametric solution.") except ValueError: raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") return soln elif method == 'LU': return M.LUsolve(rhs) elif method == 'CH': return M.cholesky_solve(rhs) elif method == 'QR': return M.QRsolve(rhs) elif method == 'LDL': return M.LDLsolve(rhs) elif method == 'PINV': return M.pinv_solve(rhs) else: return M.inv(method=method).multiply(rhs) def _solve_least_squares(M, rhs, method='CH'): """Return the least-square fit to the data. Parameters ========== rhs : Matrix Vector representing the right hand side of the linear equation. method : string or boolean, optional If set to ``'CH'``, ``cholesky_solve`` routine will be used. If set to ``'LDL'``, ``LDLsolve`` routine will be used. If set to ``'QR'``, ``QRsolve`` routine will be used. If set to ``'PINV'``, ``pinv_solve`` routine will be used. Otherwise, the conjugate of ``M`` will be used to create a system of equations that is passed to ``solve`` along with the hint defined by ``method``. Returns ======= solutions : Matrix Vector representing the solution. Examples ======== >>> from sympy import Matrix, ones >>> A = Matrix([1, 2, 3]) >>> B = Matrix([2, 3, 4]) >>> S = Matrix(A.row_join(B)) >>> S Matrix([ [1, 2], [2, 3], [3, 4]]) If each line of S represent coefficients of Ax + By and x and y are [2, 3] then S*xy is: >>> r = S*Matrix([2, 3]); r Matrix([ [ 8], [13], [18]]) But let's add 1 to the middle value and then solve for the least-squares value of xy: >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy Matrix([ [ 5/3], [10/3]]) The error is given by S*xy - r: >>> S*xy - r Matrix([ [1/3], [1/3], [1/3]]) >>> _.norm().n(2) 0.58 If a different xy is used, the norm will be higher: >>> xy += ones(2, 1)/10 >>> (S*xy - r).norm().n(2) 1.5 """ if method == 'CH': return M.cholesky_solve(rhs) elif method == 'QR': return M.QRsolve(rhs) elif method == 'LDL': return M.LDLsolve(rhs) elif method == 'PINV': return M.pinv_solve(rhs) else: t = M.H return (t * M).solve(t * rhs, method=method)
12ecbf049b118505cb7818d017b6c2e4ef24cce421224ef3ad95b172d7846d35
from collections.abc import Callable from sympy.core.containers import Dict from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from sympy.utilities.misc import as_int from .matrices import MatrixBase from .repmatrix import MutableRepMatrix, RepMatrix from .utilities import _iszero from .decompositions import ( _liupc, _row_structure_symbolic_cholesky, _cholesky_sparse, _LDLdecomposition_sparse) from .solvers import ( _lower_triangular_solve_sparse, _upper_triangular_solve_sparse) class SparseRepMatrix(RepMatrix): """ A sparse matrix (a matrix with a large number of zero elements). Examples ======== >>> from sympy import SparseMatrix, ones >>> SparseMatrix(2, 2, range(4)) Matrix([ [0, 1], [2, 3]]) >>> SparseMatrix(2, 2, {(1, 1): 2}) Matrix([ [0, 0], [0, 2]]) A SparseMatrix can be instantiated from a ragged list of lists: >>> SparseMatrix([[1, 2, 3], [1, 2], [1]]) Matrix([ [1, 2, 3], [1, 2, 0], [1, 0, 0]]) For safety, one may include the expected size and then an error will be raised if the indices of any element are out of range or (for a flat list) if the total number of elements does not match the expected shape: >>> SparseMatrix(2, 2, [1, 2]) Traceback (most recent call last): ... ValueError: List length (2) != rows*columns (4) Here, an error is not raised because the list is not flat and no element is out of range: >>> SparseMatrix(2, 2, [[1, 2]]) Matrix([ [1, 2], [0, 0]]) But adding another element to the first (and only) row will cause an error to be raised: >>> SparseMatrix(2, 2, [[1, 2, 3]]) Traceback (most recent call last): ... ValueError: The location (0, 2) is out of designated range: (1, 1) To autosize the matrix, pass None for rows: >>> SparseMatrix(None, [[1, 2, 3]]) Matrix([[1, 2, 3]]) >>> SparseMatrix(None, {(1, 1): 1, (3, 3): 3}) Matrix([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 3]]) Values that are themselves a Matrix are automatically expanded: >>> SparseMatrix(4, 4, {(1, 1): ones(2)}) Matrix([ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]) A ValueError is raised if the expanding matrix tries to overwrite a different element already present: >>> SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}) Traceback (most recent call last): ... ValueError: collision at (1, 1) See Also ======== DenseMatrix MutableSparseMatrix ImmutableSparseMatrix """ @classmethod def _handle_creation_inputs(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], MatrixBase): rows = args[0].rows cols = args[0].cols smat = args[0].todok() return rows, cols, smat smat = {} # autosizing if len(args) == 2 and args[0] is None: args = [None, None, args[1]] if len(args) == 3: r, c = args[:2] if r is c is None: rows = cols = None elif None in (r, c): raise ValueError( 'Pass rows=None and no cols for autosizing.') else: rows, cols = as_int(args[0]), as_int(args[1]) if isinstance(args[2], Callable): op = args[2] if None in (rows, cols): raise ValueError( "{} and {} must be integers for this " "specification.".format(rows, cols)) row_indices = [cls._sympify(i) for i in range(rows)] col_indices = [cls._sympify(j) for j in range(cols)] for i in row_indices: for j in col_indices: value = cls._sympify(op(i, j)) if value != cls.zero: smat[i, j] = value return rows, cols, smat elif isinstance(args[2], (dict, Dict)): def update(i, j, v): # update smat and make sure there are no collisions if v: if (i, j) in smat and v != smat[i, j]: raise ValueError( "There is a collision at {} for {} and {}." .format((i, j), v, smat[i, j]) ) smat[i, j] = v # manual copy, copy.deepcopy() doesn't work for (r, c), v in args[2].items(): if isinstance(v, MatrixBase): for (i, j), vv in v.todok().items(): update(r + i, c + j, vv) elif isinstance(v, (list, tuple)): _, _, smat = cls._handle_creation_inputs(v, **kwargs) for i, j in smat: update(r + i, c + j, smat[i, j]) else: v = cls._sympify(v) update(r, c, cls._sympify(v)) elif is_sequence(args[2]): flat = not any(is_sequence(i) for i in args[2]) if not flat: _, _, smat = \ cls._handle_creation_inputs(args[2], **kwargs) else: flat_list = args[2] if len(flat_list) != rows * cols: raise ValueError( "The length of the flat list ({}) does not " "match the specified size ({} * {})." .format(len(flat_list), rows, cols) ) for i in range(rows): for j in range(cols): value = flat_list[i*cols + j] value = cls._sympify(value) if value != cls.zero: smat[i, j] = value if rows is None: # autosizing keys = smat.keys() rows = max([r for r, _ in keys]) + 1 if keys else 0 cols = max([c for _, c in keys]) + 1 if keys else 0 else: for i, j in smat.keys(): if i and i >= rows or j and j >= cols: raise ValueError( "The location {} is out of the designated range" "[{}, {}]x[{}, {}]" .format((i, j), 0, rows - 1, 0, cols - 1) ) return rows, cols, smat elif len(args) == 1 and isinstance(args[0], (list, tuple)): # list of values or lists v = args[0] c = 0 for i, row in enumerate(v): if not isinstance(row, (list, tuple)): row = [row] for j, vv in enumerate(row): if vv != cls.zero: smat[i, j] = cls._sympify(vv) c = max(c, len(row)) rows = len(v) if c else 0 cols = c return rows, cols, smat else: # handle full matrix forms with _handle_creation_inputs rows, cols, mat = super()._handle_creation_inputs(*args) for i in range(rows): for j in range(cols): value = mat[cols*i + j] if value != cls.zero: smat[i, j] = value return rows, cols, smat @property def _smat(self): sympy_deprecation_warning( """ The private _smat attribute of SparseMatrix is deprecated. Use the .todok() method instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-private-matrix-attributes" ) return self.todok() def _eval_inverse(self, **kwargs): return self.inv(method=kwargs.get('method', 'LDL'), iszerofunc=kwargs.get('iszerofunc', _iszero), try_block_diag=kwargs.get('try_block_diag', False)) def applyfunc(self, f): """Apply a function to each element of the matrix. Examples ======== >>> from sympy import SparseMatrix >>> m = SparseMatrix(2, 2, lambda i, j: i*2+j) >>> m Matrix([ [0, 1], [2, 3]]) >>> m.applyfunc(lambda i: 2*i) Matrix([ [0, 2], [4, 6]]) """ if not callable(f): raise TypeError("`f` must be callable.") # XXX: This only applies the function to the nonzero elements of the # matrix so is inconsistent with DenseMatrix.applyfunc e.g. # zeros(2, 2).applyfunc(lambda x: x + 1) dok = {} for k, v in self.todok().items(): fv = f(v) if fv != 0: dok[k] = fv return self._new(self.rows, self.cols, dok) def as_immutable(self): """Returns an Immutable version of this Matrix.""" from .immutable import ImmutableSparseMatrix return ImmutableSparseMatrix(self) def as_mutable(self): """Returns a mutable version of this matrix. Examples ======== >>> from sympy import ImmutableMatrix >>> X = ImmutableMatrix([[1, 2], [3, 4]]) >>> Y = X.as_mutable() >>> Y[1, 1] = 5 # Can set values in Y >>> Y Matrix([ [1, 2], [3, 5]]) """ return MutableSparseMatrix(self) def col_list(self): """Returns a column-sorted list of non-zero elements of the matrix. Examples ======== >>> from sympy import SparseMatrix >>> a=SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.CL [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)] See Also ======== sympy.matrices.sparse.SparseMatrix.row_list """ return [tuple(k + (self[k],)) for k in sorted(list(self.todok().keys()), key=lambda k: list(reversed(k)))] def nnz(self): """Returns the number of non-zero elements in Matrix.""" return len(self.todok()) def row_list(self): """Returns a row-sorted list of non-zero elements of the matrix. Examples ======== >>> from sympy import SparseMatrix >>> a = SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.RL [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)] See Also ======== sympy.matrices.sparse.SparseMatrix.col_list """ return [tuple(k + (self[k],)) for k in sorted(self.todok().keys(), key=list)] def scalar_multiply(self, scalar): "Scalar element-wise multiplication" return scalar * self def solve_least_squares(self, rhs, method='LDL'): """Return the least-square fit to the data. By default the cholesky_solve routine is used (method='CH'); other methods of matrix inversion can be used. To find out which are available, see the docstring of the .inv() method. Examples ======== >>> from sympy import SparseMatrix, Matrix, ones >>> A = Matrix([1, 2, 3]) >>> B = Matrix([2, 3, 4]) >>> S = SparseMatrix(A.row_join(B)) >>> S Matrix([ [1, 2], [2, 3], [3, 4]]) If each line of S represent coefficients of Ax + By and x and y are [2, 3] then S*xy is: >>> r = S*Matrix([2, 3]); r Matrix([ [ 8], [13], [18]]) But let's add 1 to the middle value and then solve for the least-squares value of xy: >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy Matrix([ [ 5/3], [10/3]]) The error is given by S*xy - r: >>> S*xy - r Matrix([ [1/3], [1/3], [1/3]]) >>> _.norm().n(2) 0.58 If a different xy is used, the norm will be higher: >>> xy += ones(2, 1)/10 >>> (S*xy - r).norm().n(2) 1.5 """ t = self.T return (t*self).inv(method=method)*t*rhs def solve(self, rhs, method='LDL'): """Return solution to self*soln = rhs using given inversion method. For a list of possible inversion methods, see the .inv() docstring. """ if not self.is_square: if self.rows < self.cols: raise ValueError('Under-determined system.') elif self.rows > self.cols: raise ValueError('For over-determined system, M, having ' 'more rows than columns, try M.solve_least_squares(rhs).') else: return self.inv(method=method).multiply(rhs) RL = property(row_list, None, None, "Alternate faster representation") CL = property(col_list, None, None, "Alternate faster representation") def liupc(self): return _liupc(self) def row_structure_symbolic_cholesky(self): return _row_structure_symbolic_cholesky(self) def cholesky(self, hermitian=True): return _cholesky_sparse(self, hermitian=hermitian) def LDLdecomposition(self, hermitian=True): return _LDLdecomposition_sparse(self, hermitian=hermitian) def lower_triangular_solve(self, rhs): return _lower_triangular_solve_sparse(self, rhs) def upper_triangular_solve(self, rhs): return _upper_triangular_solve_sparse(self, rhs) liupc.__doc__ = _liupc.__doc__ row_structure_symbolic_cholesky.__doc__ = _row_structure_symbolic_cholesky.__doc__ cholesky.__doc__ = _cholesky_sparse.__doc__ LDLdecomposition.__doc__ = _LDLdecomposition_sparse.__doc__ lower_triangular_solve.__doc__ = lower_triangular_solve.__doc__ upper_triangular_solve.__doc__ = upper_triangular_solve.__doc__ class MutableSparseMatrix(SparseRepMatrix, MutableRepMatrix): @classmethod def _new(cls, *args, **kwargs): rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs) rep = cls._smat_to_DomainMatrix(rows, cols, smat) return cls._fromrep(rep) SparseMatrix = MutableSparseMatrix
5d28390bf8e2e5cf83caea1f895f1660bb7c372f9e1db0c4e73ffd9d8f439f23
import mpmath as mp from collections.abc import Callable from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.function import diff from sympy.core.expr import Expr from sympy.core.kind import _NumberKind, UndefinedKind from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol, uniquely_named_symbol from sympy.core.sympify import sympify, _sympify from sympy.functions.combinatorial.factorials import binomial, factorial from sympy.functions.elementary.complexes import re from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.special.tensor_functions import KroneckerDelta, LeviCivita from sympy.polys import cancel from sympy.printing import sstr from sympy.printing.defaults import Printable from sympy.printing.str import StrPrinter from sympy.utilities.decorator import deprecated from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import flatten, NotIterable, is_sequence, reshape from sympy.utilities.misc import as_int, filldedent from .common import ( MatrixCommon, MatrixError, NonSquareMatrixError, NonInvertibleMatrixError, ShapeError, MatrixKind) from .utilities import _iszero, _is_zero_after_expand_mul, _simplify from .determinant import ( _find_reasonable_pivot, _find_reasonable_pivot_naive, _adjugate, _charpoly, _cofactor, _cofactor_matrix, _per, _det, _det_bareiss, _det_berkowitz, _det_LU, _minor, _minor_submatrix) from .reductions import _is_echelon, _echelon_form, _rank, _rref from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize from .eigen import ( _eigenvals, _eigenvects, _bidiagonalize, _bidiagonal_decomposition, _is_diagonalizable, _diagonalize, _is_positive_definite, _is_positive_semidefinite, _is_negative_definite, _is_negative_semidefinite, _is_indefinite, _jordan_form, _left_eigenvects, _singular_values) from .decompositions import ( _rank_decomposition, _cholesky, _LDLdecomposition, _LUdecomposition, _LUdecomposition_Simple, _LUdecompositionFF, _singular_value_decomposition, _QRdecomposition, _upper_hessenberg_decomposition) from .graph import ( _connected_components, _connected_components_decomposition, _strongly_connected_components, _strongly_connected_components_decomposition) from .solvers import ( _diagonal_solve, _lower_triangular_solve, _upper_triangular_solve, _cholesky_solve, _LDLsolve, _LUsolve, _QRsolve, _gauss_jordan_solve, _pinv_solve, _solve, _solve_least_squares) from .inverse import ( _pinv, _inv_mod, _inv_ADJ, _inv_GE, _inv_LU, _inv_CH, _inv_LDL, _inv_QR, _inv, _inv_block) class DeferredVector(Symbol, NotIterable): """A vector whose components are deferred (e.g. for use with lambdify) Examples ======== >>> from sympy import DeferredVector, lambdify >>> X = DeferredVector( 'X' ) >>> X X >>> expr = (X[0] + 2, X[2] + 3) >>> func = lambdify( X, expr) >>> func( [1, 2, 3] ) (3, 6) """ def __getitem__(self, i): if i == -0: i = 0 if i < 0: raise IndexError('DeferredVector index out of range') component_name = '%s[%d]' % (self.name, i) return Symbol(component_name) def __str__(self): return sstr(self) def __repr__(self): return "DeferredVector('%s')" % self.name class MatrixDeterminant(MatrixCommon): """Provides basic matrix determinant operations. Should not be instantiated directly. See ``determinant.py`` for their implementations.""" def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul): return _det_bareiss(self, iszerofunc=iszerofunc) def _eval_det_berkowitz(self): return _det_berkowitz(self) def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None): return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc) def _eval_determinant(self): # for expressions.determinant.Determinant return _det(self) def adjugate(self, method="berkowitz"): return _adjugate(self, method=method) def charpoly(self, x='lambda', simplify=_simplify): return _charpoly(self, x=x, simplify=simplify) def cofactor(self, i, j, method="berkowitz"): return _cofactor(self, i, j, method=method) def cofactor_matrix(self, method="berkowitz"): return _cofactor_matrix(self, method=method) def det(self, method="bareiss", iszerofunc=None): return _det(self, method=method, iszerofunc=iszerofunc) def per(self): return _per(self) def minor(self, i, j, method="berkowitz"): return _minor(self, i, j, method=method) def minor_submatrix(self, i, j): return _minor_submatrix(self, i, j) _find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__ _find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__ _eval_det_bareiss.__doc__ = _det_bareiss.__doc__ _eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__ _eval_det_lu.__doc__ = _det_LU.__doc__ _eval_determinant.__doc__ = _det.__doc__ adjugate.__doc__ = _adjugate.__doc__ charpoly.__doc__ = _charpoly.__doc__ cofactor.__doc__ = _cofactor.__doc__ cofactor_matrix.__doc__ = _cofactor_matrix.__doc__ det.__doc__ = _det.__doc__ per.__doc__ = _per.__doc__ minor.__doc__ = _minor.__doc__ minor_submatrix.__doc__ = _minor_submatrix.__doc__ class MatrixReductions(MatrixDeterminant): """Provides basic matrix row/column operations. Should not be instantiated directly. See ``reductions.py`` for some of their implementations.""" def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False): return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify, with_pivots=with_pivots) @property def is_echelon(self): return _is_echelon(self) def rank(self, iszerofunc=_iszero, simplify=False): return _rank(self, iszerofunc=iszerofunc, simplify=simplify) def rref(self, iszerofunc=_iszero, simplify=False, pivots=True, normalize_last=True): return _rref(self, iszerofunc=iszerofunc, simplify=simplify, pivots=pivots, normalize_last=normalize_last) echelon_form.__doc__ = _echelon_form.__doc__ is_echelon.__doc__ = _is_echelon.__doc__ rank.__doc__ = _rank.__doc__ rref.__doc__ = _rref.__doc__ def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"): """Validate the arguments for a row/column operation. ``error_str`` can be one of "row" or "col" depending on the arguments being parsed.""" if op not in ["n->kn", "n<->m", "n->n+km"]: raise ValueError("Unknown {} operation '{}'. Valid col operations " "are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op)) # define self_col according to error_str self_cols = self.cols if error_str == 'col' else self.rows # normalize and validate the arguments if op == "n->kn": col = col if col is not None else col1 if col is None or k is None: raise ValueError("For a {0} operation 'n->kn' you must provide the " "kwargs `{0}` and `k`".format(error_str)) if not 0 <= col < self_cols: raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) elif op == "n<->m": # we need two cols to swap. It does not matter # how they were specified, so gather them together and # remove `None` cols = {col, k, col1, col2}.difference([None]) if len(cols) > 2: # maybe the user left `k` by mistake? cols = {col, col1, col2}.difference([None]) if len(cols) != 2: raise ValueError("For a {0} operation 'n<->m' you must provide the " "kwargs `{0}1` and `{0}2`".format(error_str)) col1, col2 = cols if not 0 <= col1 < self_cols: raise ValueError("This matrix does not have a {} '{}'".format(error_str, col1)) if not 0 <= col2 < self_cols: raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2)) elif op == "n->n+km": col = col1 if col is None else col col2 = col1 if col2 is None else col2 if col is None or col2 is None or k is None: raise ValueError("For a {0} operation 'n->n+km' you must provide the " "kwargs `{0}`, `k`, and `{0}2`".format(error_str)) if col == col2: raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must " "be different.".format(error_str)) if not 0 <= col < self_cols: raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) if not 0 <= col2 < self_cols: raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2)) else: raise ValueError('invalid operation %s' % repr(op)) return op, col, k, col1, col2 def _eval_col_op_multiply_col_by_const(self, col, k): def entry(i, j): if j == col: return k * self[i, j] return self[i, j] return self._new(self.rows, self.cols, entry) def _eval_col_op_swap(self, col1, col2): def entry(i, j): if j == col1: return self[i, col2] elif j == col2: return self[i, col1] return self[i, j] return self._new(self.rows, self.cols, entry) def _eval_col_op_add_multiple_to_other_col(self, col, k, col2): def entry(i, j): if j == col: return self[i, j] + k * self[i, col2] return self[i, j] return self._new(self.rows, self.cols, entry) def _eval_row_op_swap(self, row1, row2): def entry(i, j): if i == row1: return self[row2, j] elif i == row2: return self[row1, j] return self[i, j] return self._new(self.rows, self.cols, entry) def _eval_row_op_multiply_row_by_const(self, row, k): def entry(i, j): if i == row: return k * self[i, j] return self[i, j] return self._new(self.rows, self.cols, entry) def _eval_row_op_add_multiple_to_other_row(self, row, k, row2): def entry(i, j): if i == row: return self[i, j] + k * self[row2, j] return self[i, j] return self._new(self.rows, self.cols, entry) def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None): """Performs the elementary column operation `op`. `op` may be one of * ``"n->kn"`` (column n goes to k*n) * ``"n<->m"`` (swap column n and column m) * ``"n->n+km"`` (column n goes to column n + k*column m) Parameters ========== op : string; the elementary row operation col : the column to apply the column operation k : the multiple to apply in the column operation col1 : one column of a column swap col2 : second column of a column swap or column "m" in the column operation "n->n+km" """ op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col") # now that we've validated, we're all good to dispatch if op == "n->kn": return self._eval_col_op_multiply_col_by_const(col, k) if op == "n<->m": return self._eval_col_op_swap(col1, col2) if op == "n->n+km": return self._eval_col_op_add_multiple_to_other_col(col, k, col2) def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None): """Performs the elementary row operation `op`. `op` may be one of * ``"n->kn"`` (row n goes to k*n) * ``"n<->m"`` (swap row n and row m) * ``"n->n+km"`` (row n goes to row n + k*row m) Parameters ========== op : string; the elementary row operation row : the row to apply the row operation k : the multiple to apply in the row operation row1 : one row of a row swap row2 : second row of a row swap or row "m" in the row operation "n->n+km" """ op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row") # now that we've validated, we're all good to dispatch if op == "n->kn": return self._eval_row_op_multiply_row_by_const(row, k) if op == "n<->m": return self._eval_row_op_swap(row1, row2) if op == "n->n+km": return self._eval_row_op_add_multiple_to_other_row(row, k, row2) class MatrixSubspaces(MatrixReductions): """Provides methods relating to the fundamental subspaces of a matrix. Should not be instantiated directly. See ``subspaces.py`` for their implementations.""" def columnspace(self, simplify=False): return _columnspace(self, simplify=simplify) def nullspace(self, simplify=False, iszerofunc=_iszero): return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc) def rowspace(self, simplify=False): return _rowspace(self, simplify=simplify) # This is a classmethod but is converted to such later in order to allow # assignment of __doc__ since that does not work for already wrapped # classmethods in Python 3.6. def orthogonalize(cls, *vecs, **kwargs): return _orthogonalize(cls, *vecs, **kwargs) columnspace.__doc__ = _columnspace.__doc__ nullspace.__doc__ = _nullspace.__doc__ rowspace.__doc__ = _rowspace.__doc__ orthogonalize.__doc__ = _orthogonalize.__doc__ orthogonalize = classmethod(orthogonalize) # type:ignore class MatrixEigen(MatrixSubspaces): """Provides basic matrix eigenvalue/vector operations. Should not be instantiated directly. See ``eigen.py`` for their implementations.""" def eigenvals(self, error_when_incomplete=True, **flags): return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags) def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags): return _eigenvects(self, error_when_incomplete=error_when_incomplete, iszerofunc=iszerofunc, **flags) def is_diagonalizable(self, reals_only=False, **kwargs): return _is_diagonalizable(self, reals_only=reals_only, **kwargs) def diagonalize(self, reals_only=False, sort=False, normalize=False): return _diagonalize(self, reals_only=reals_only, sort=sort, normalize=normalize) def bidiagonalize(self, upper=True): return _bidiagonalize(self, upper=upper) def bidiagonal_decomposition(self, upper=True): return _bidiagonal_decomposition(self, upper=upper) @property def is_positive_definite(self): return _is_positive_definite(self) @property def is_positive_semidefinite(self): return _is_positive_semidefinite(self) @property def is_negative_definite(self): return _is_negative_definite(self) @property def is_negative_semidefinite(self): return _is_negative_semidefinite(self) @property def is_indefinite(self): return _is_indefinite(self) def jordan_form(self, calc_transform=True, **kwargs): return _jordan_form(self, calc_transform=calc_transform, **kwargs) def left_eigenvects(self, **flags): return _left_eigenvects(self, **flags) def singular_values(self): return _singular_values(self) eigenvals.__doc__ = _eigenvals.__doc__ eigenvects.__doc__ = _eigenvects.__doc__ is_diagonalizable.__doc__ = _is_diagonalizable.__doc__ diagonalize.__doc__ = _diagonalize.__doc__ is_positive_definite.__doc__ = _is_positive_definite.__doc__ is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__ is_negative_definite.__doc__ = _is_negative_definite.__doc__ is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__ is_indefinite.__doc__ = _is_indefinite.__doc__ jordan_form.__doc__ = _jordan_form.__doc__ left_eigenvects.__doc__ = _left_eigenvects.__doc__ singular_values.__doc__ = _singular_values.__doc__ bidiagonalize.__doc__ = _bidiagonalize.__doc__ bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__ class MatrixCalculus(MatrixCommon): """Provides calculus-related matrix operations.""" def diff(self, *args, **kwargs): """Calculate the derivative of each element in the matrix. ``args`` will be passed to the ``integrate`` function. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.diff(x) Matrix([ [1, 0], [0, 0]]) See Also ======== integrate limit """ # XXX this should be handled here rather than in Derivative from sympy.tensor.array.array_derivatives import ArrayDerivative kwargs.setdefault('evaluate', True) deriv = ArrayDerivative(self, *args, evaluate=True) if not isinstance(self, Basic): return deriv.as_mutable() else: return deriv def _eval_derivative(self, arg): return self.applyfunc(lambda x: x.diff(arg)) def integrate(self, *args, **kwargs): """Integrate each element of the matrix. ``args`` will be passed to the ``integrate`` function. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.integrate((x, )) Matrix([ [x**2/2, x*y], [ x, 0]]) >>> M.integrate((x, 0, 2)) Matrix([ [2, 2*y], [2, 0]]) See Also ======== limit diff """ return self.applyfunc(lambda x: x.integrate(*args, **kwargs)) def jacobian(self, X): """Calculates the Jacobian matrix (derivative of a vector-valued function). Parameters ========== ``self`` : vector of expressions representing functions f_i(x_1, ..., x_n). X : set of x_i's in order, it can be a list or a Matrix Both ``self`` and X can be a row or a column matrix in any order (i.e., jacobian() should always work). Examples ======== >>> from sympy import sin, cos, Matrix >>> from sympy.abc import rho, phi >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2]) >>> Y = Matrix([rho, phi]) >>> X.jacobian(Y) Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)], [ 2*rho, 0]]) >>> X = Matrix([rho*cos(phi), rho*sin(phi)]) >>> X.jacobian(Y) Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)]]) See Also ======== hessian wronskian """ if not isinstance(X, MatrixBase): X = self._new(X) # Both X and ``self`` can be a row or a column matrix, so we need to make # sure all valid combinations work, but everything else fails: if self.shape[0] == 1: m = self.shape[1] elif self.shape[1] == 1: m = self.shape[0] else: raise TypeError("``self`` must be a row or a column matrix") if X.shape[0] == 1: n = X.shape[1] elif X.shape[1] == 1: n = X.shape[0] else: raise TypeError("X must be a row or a column matrix") # m is the number of functions and n is the number of variables # computing the Jacobian is now easy: return self._new(m, n, lambda j, i: self[j].diff(X[i])) def limit(self, *args): """Calculate the limit of each element in the matrix. ``args`` will be passed to the ``limit`` function. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.limit(x, 2) Matrix([ [2, y], [1, 0]]) See Also ======== integrate diff """ return self.applyfunc(lambda x: x.limit(*args)) # https://github.com/sympy/sympy/pull/12854 class MatrixDeprecated(MatrixCommon): """A class to house deprecated matrix methods.""" def _legacy_array_dot(self, b): """Compatibility function for deprecated behavior of ``matrix.dot(vector)`` """ from .dense import Matrix if not isinstance(b, MatrixBase): if is_sequence(b): if len(b) != self.cols and len(b) != self.rows: raise ShapeError( "Dimensions incorrect for dot product: %s, %s" % ( self.shape, len(b))) return self.dot(Matrix(b)) else: raise TypeError( "`b` must be an ordered iterable or Matrix, not %s." % type(b)) mat = self if mat.cols == b.rows: if b.cols != 1: mat = mat.T b = b.T prod = flatten((mat * b).tolist()) return prod if mat.cols == b.cols: return mat.dot(b.T) elif mat.rows == b.rows: return mat.T.dot(b) else: raise ShapeError("Dimensions incorrect for dot product: %s, %s" % ( self.shape, b.shape)) def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify): return self.charpoly(x=x) def berkowitz_det(self): """Computes determinant using Berkowitz method. See Also ======== det berkowitz """ return self.det(method='berkowitz') def berkowitz_eigenvals(self, **flags): """Computes eigenvalues of a Matrix using Berkowitz method. See Also ======== berkowitz """ return self.eigenvals(**flags) def berkowitz_minors(self): """Computes principal minors using Berkowitz method. See Also ======== berkowitz """ sign, minors = self.one, [] for poly in self.berkowitz(): minors.append(sign * poly[-1]) sign = -sign return tuple(minors) def berkowitz(self): from sympy.matrices import zeros berk = ((1,),) if not self: return berk if not self.is_square: raise NonSquareMatrixError() A, N = self, self.rows transforms = [0] * (N - 1) for n in range(N, 1, -1): T, k = zeros(n + 1, n), n - 1 R, C = -A[k, :k], A[:k, k] A, a = A[:k, :k], -A[k, k] items = [C] for i in range(0, n - 2): items.append(A * items[i]) for i, B in enumerate(items): items[i] = (R * B)[0, 0] items = [self.one, a] + items for i in range(n): T[i:, i] = items[:n - i + 1] transforms[k - 1] = T polys = [self._new([self.one, -A[0, 0]])] for i, T in enumerate(transforms): polys.append(T * polys[i]) return berk + tuple(map(tuple, polys)) def cofactorMatrix(self, method="berkowitz"): return self.cofactor_matrix(method=method) def det_bareis(self): return _det_bareiss(self) def det_LU_decomposition(self): """Compute matrix determinant using LU decomposition Note that this method fails if the LU decomposition itself fails. In particular, if the matrix has no inverse this method will fail. TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. See Also ======== det det_bareiss berkowitz_det """ return self.det(method='lu') def jordan_cell(self, eigenval, n): return self.jordan_block(size=n, eigenvalue=eigenval) def jordan_cells(self, calc_transformation=True): P, J = self.jordan_form() return P, J.get_diag_blocks() def minorEntry(self, i, j, method="berkowitz"): return self.minor(i, j, method=method) def minorMatrix(self, i, j): return self.minor_submatrix(i, j) def permuteBkwd(self, perm): """Permute the rows of the matrix with the given permutation in reverse.""" return self.permute_rows(perm, direction='backward') def permuteFwd(self, perm): """Permute the rows of the matrix with the given permutation.""" return self.permute_rows(perm, direction='forward') @Mul._kind_dispatcher.register(_NumberKind, MatrixKind) def num_mat_mul(k1, k2): """ Return MatrixKind. The element kind is selected by recursive dispatching. Do not need to dispatch in reversed order because KindDispatcher searches for this automatically. """ # Deal with Mul._kind_dispatcher's commutativity # XXX: this function is called with either k1 or k2 as MatrixKind because # the Mul kind dispatcher is commutative. Maybe it shouldn't be. Need to # swap the args here because NumberKind does not have an element_kind # attribute. if not isinstance(k2, MatrixKind): k1, k2 = k2, k1 elemk = Mul._kind_dispatcher(k1, k2.element_kind) return MatrixKind(elemk) @Mul._kind_dispatcher.register(MatrixKind, MatrixKind) def mat_mat_mul(k1, k2): """ Return MatrixKind. The element kind is selected by recursive dispatching. """ elemk = Mul._kind_dispatcher(k1.element_kind, k2.element_kind) return MatrixKind(elemk) class MatrixBase(MatrixDeprecated, MatrixCalculus, MatrixEigen, MatrixCommon, Printable): """Base class for matrix objects.""" # Added just for numpy compatibility __array_priority__ = 11 is_Matrix = True _class_priority = 3 _sympify = staticmethod(sympify) zero = S.Zero one = S.One @property def kind(self) -> MatrixKind: elem_kinds = set(e.kind for e in self.flat()) if len(elem_kinds) == 1: elemkind, = elem_kinds else: elemkind = UndefinedKind return MatrixKind(elemkind) def flat(self): return [self[i, j] for i in range(self.rows) for j in range(self.cols)] def __array__(self, dtype=object): from .dense import matrix2numpy return matrix2numpy(self, dtype=dtype) def __len__(self): """Return the number of elements of ``self``. Implemented mainly so bool(Matrix()) == False. """ return self.rows * self.cols def _matrix_pow_by_jordan_blocks(self, num): from sympy.matrices import diag, MutableMatrix def jordan_cell_power(jc, n): N = jc.shape[0] l = jc[0,0] if l.is_zero: if N == 1 and n.is_nonnegative: jc[0,0] = l**n elif not (n.is_integer and n.is_nonnegative): raise NonInvertibleMatrixError("Non-invertible matrix can only be raised to a nonnegative integer") else: for i in range(N): jc[0,i] = KroneckerDelta(i, n) else: for i in range(N): bn = binomial(n, i) if isinstance(bn, binomial): bn = bn._eval_expand_func() jc[0,i] = l**(n-i)*bn for i in range(N): for j in range(1, N-i): jc[j,i+j] = jc [j-1,i+j-1] P, J = self.jordan_form() jordan_cells = J.get_diag_blocks() # Make sure jordan_cells matrices are mutable: jordan_cells = [MutableMatrix(j) for j in jordan_cells] for j in jordan_cells: jordan_cell_power(j, num) return self._new(P.multiply(diag(*jordan_cells)) .multiply(P.inv())) def __str__(self): if S.Zero in self.shape: return 'Matrix(%s, %s, [])' % (self.rows, self.cols) return "Matrix(%s)" % str(self.tolist()) def _format_str(self, printer=None): if not printer: printer = StrPrinter() # Handle zero dimensions: if S.Zero in self.shape: return 'Matrix(%s, %s, [])' % (self.rows, self.cols) if self.rows == 1: return "Matrix([%s])" % self.table(printer, rowsep=',\n') return "Matrix([\n%s])" % self.table(printer, rowsep=',\n') @classmethod def irregular(cls, ntop, *matrices, **kwargs): """Return a matrix filled by the given matrices which are listed in order of appearance from left to right, top to bottom as they first appear in the matrix. They must fill the matrix completely. Examples ======== >>> from sympy import ones, Matrix >>> Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3, ... ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) Matrix([ [1, 2, 2, 2, 3, 3], [1, 2, 2, 2, 3, 3], [4, 2, 2, 2, 5, 5], [6, 6, 7, 7, 5, 5]]) """ ntop = as_int(ntop) # make sure we are working with explicit matrices b = [i.as_explicit() if hasattr(i, 'as_explicit') else i for i in matrices] q = list(range(len(b))) dat = [i.rows for i in b] active = [q.pop(0) for _ in range(ntop)] cols = sum([b[i].cols for i in active]) rows = [] while any(dat): r = [] for a, j in enumerate(active): r.extend(b[j][-dat[j], :]) dat[j] -= 1 if dat[j] == 0 and q: active[a] = q.pop(0) if len(r) != cols: raise ValueError(filldedent(''' Matrices provided do not appear to fill the space completely.''')) rows.append(r) return cls._new(rows) @classmethod def _handle_ndarray(cls, arg): # NumPy array or matrix or some other object that implements # __array__. So let's first use this method to get a # numpy.array() and then make a Python list out of it. arr = arg.__array__() if len(arr.shape) == 2: rows, cols = arr.shape[0], arr.shape[1] flat_list = [cls._sympify(i) for i in arr.ravel()] return rows, cols, flat_list elif len(arr.shape) == 1: flat_list = [cls._sympify(i) for i in arr] return arr.shape[0], 1, flat_list else: raise NotImplementedError( "SymPy supports just 1D and 2D matrices") @classmethod def _handle_creation_inputs(cls, *args, **kwargs): """Return the number of rows, cols and flat matrix elements. Examples ======== >>> from sympy import Matrix, I Matrix can be constructed as follows: * from a nested list of iterables >>> Matrix( ((1, 2+I), (3, 4)) ) Matrix([ [1, 2 + I], [3, 4]]) * from un-nested iterable (interpreted as a column) >>> Matrix( [1, 2] ) Matrix([ [1], [2]]) * from un-nested iterable with dimensions >>> Matrix(1, 2, [1, 2] ) Matrix([[1, 2]]) * from no arguments (a 0 x 0 matrix) >>> Matrix() Matrix(0, 0, []) * from a rule >>> Matrix(2, 2, lambda i, j: i/(j + 1) ) Matrix([ [0, 0], [1, 1/2]]) See Also ======== irregular - filling a matrix with irregular blocks """ from sympy.matrices import SparseMatrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.blockmatrix import BlockMatrix flat_list = None if len(args) == 1: # Matrix(SparseMatrix(...)) if isinstance(args[0], SparseMatrix): return args[0].rows, args[0].cols, flatten(args[0].tolist()) # Matrix(Matrix(...)) elif isinstance(args[0], MatrixBase): return args[0].rows, args[0].cols, args[0].flat() # Matrix(MatrixSymbol('X', 2, 2)) elif isinstance(args[0], Basic) and args[0].is_Matrix: return args[0].rows, args[0].cols, args[0].as_explicit().flat() elif isinstance(args[0], mp.matrix): M = args[0] flat_list = [cls._sympify(x) for x in M] return M.rows, M.cols, flat_list # Matrix(numpy.ones((2, 2))) elif hasattr(args[0], "__array__"): return cls._handle_ndarray(args[0]) # Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]]) elif is_sequence(args[0]) \ and not isinstance(args[0], DeferredVector): dat = list(args[0]) ismat = lambda i: isinstance(i, MatrixBase) and ( evaluate or isinstance(i, BlockMatrix) or isinstance(i, MatrixSymbol)) raw = lambda i: is_sequence(i) and not ismat(i) evaluate = kwargs.get('evaluate', True) if evaluate: def make_explicit(x): """make Block and Symbol explicit""" if isinstance(x, BlockMatrix): return x.as_explicit() elif isinstance(x, MatrixSymbol) and all(_.is_Integer for _ in x.shape): return x.as_explicit() else: return x def make_explicit_row(row): # Could be list or could be list of lists if isinstance(row, (list, tuple)): return [make_explicit(x) for x in row] else: return make_explicit(row) if isinstance(dat, (list, tuple)): dat = [make_explicit_row(row) for row in dat] if dat in ([], [[]]): rows = cols = 0 flat_list = [] elif not any(raw(i) or ismat(i) for i in dat): # a column as a list of values flat_list = [cls._sympify(i) for i in dat] rows = len(flat_list) cols = 1 if rows else 0 elif evaluate and all(ismat(i) for i in dat): # a column as a list of matrices ncol = {i.cols for i in dat if any(i.shape)} if ncol: if len(ncol) != 1: raise ValueError('mismatched dimensions') flat_list = [_ for i in dat for r in i.tolist() for _ in r] cols = ncol.pop() rows = len(flat_list)//cols else: rows = cols = 0 flat_list = [] elif evaluate and any(ismat(i) for i in dat): ncol = set() flat_list = [] for i in dat: if ismat(i): flat_list.extend( [k for j in i.tolist() for k in j]) if any(i.shape): ncol.add(i.cols) elif raw(i): if i: ncol.add(len(i)) flat_list.extend([cls._sympify(ij) for ij in i]) else: ncol.add(1) flat_list.append(i) if len(ncol) > 1: raise ValueError('mismatched dimensions') cols = ncol.pop() rows = len(flat_list)//cols else: # list of lists; each sublist is a logical row # which might consist of many rows if the values in # the row are matrices flat_list = [] ncol = set() rows = cols = 0 for row in dat: if not is_sequence(row) and \ not getattr(row, 'is_Matrix', False): raise ValueError('expecting list of lists') if hasattr(row, '__array__'): if 0 in row.shape: continue elif not row: continue if evaluate and all(ismat(i) for i in row): r, c, flatT = cls._handle_creation_inputs( [i.T for i in row]) T = reshape(flatT, [c]) flat = \ [T[i][j] for j in range(c) for i in range(r)] r, c = c, r else: r = 1 if getattr(row, 'is_Matrix', False): c = 1 flat = [row] else: c = len(row) flat = [cls._sympify(i) for i in row] ncol.add(c) if len(ncol) > 1: raise ValueError('mismatched dimensions') flat_list.extend(flat) rows += r cols = ncol.pop() if ncol else 0 elif len(args) == 3: rows = as_int(args[0]) cols = as_int(args[1]) if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) # Matrix(2, 2, lambda i, j: i+j) if len(args) == 3 and isinstance(args[2], Callable): op = args[2] flat_list = [] for i in range(rows): flat_list.extend( [cls._sympify(op(cls._sympify(i), cls._sympify(j))) for j in range(cols)]) # Matrix(2, 2, [1, 2, 3, 4]) elif len(args) == 3 and is_sequence(args[2]): flat_list = args[2] if len(flat_list) != rows * cols: raise ValueError( 'List length should be equal to rows*columns') flat_list = [cls._sympify(i) for i in flat_list] # Matrix() elif len(args) == 0: # Empty Matrix rows = cols = 0 flat_list = [] if flat_list is None: raise TypeError(filldedent(''' Data type not understood; expecting list of lists or lists of values.''')) return rows, cols, flat_list def _setitem(self, key, value): """Helper to set value at location given by key. Examples ======== >>> from sympy import Matrix, I, zeros, ones >>> m = Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m[1, 0] = 9 >>> m Matrix([ [1, 2 + I], [9, 4]]) >>> m[1, 0] = [[0, 1]] To replace row r you assign to position r*m where m is the number of columns: >>> M = zeros(4) >>> m = M.cols >>> M[3*m] = ones(1, m)*2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]]) And to replace column c you can assign to position c: >>> M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]]) """ from .dense import Matrix is_slice = isinstance(key, slice) i, j = key = self.key2ij(key) is_mat = isinstance(value, MatrixBase) if isinstance(i, slice) or isinstance(j, slice): if is_mat: self.copyin_matrix(key, value) return if not isinstance(value, Expr) and is_sequence(value): self.copyin_list(key, value) return raise ValueError('unexpected value: %s' % value) else: if (not is_mat and not isinstance(value, Basic) and is_sequence(value)): value = Matrix(value) is_mat = True if is_mat: if is_slice: key = (slice(*divmod(i, self.cols)), slice(*divmod(j, self.cols))) else: key = (slice(i, i + value.rows), slice(j, j + value.cols)) self.copyin_matrix(key, value) else: return i, j, self._sympify(value) return def add(self, b): """Return self + b """ return self + b def condition_number(self): """Returns the condition number of a matrix. This is the maximum singular value divided by the minimum singular value Examples ======== >>> from sympy import Matrix, S >>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]]) >>> A.condition_number() 100 See Also ======== singular_values """ if not self: return self.zero singularvalues = self.singular_values() return Max(*singularvalues) / Min(*singularvalues) def copy(self): """ Returns the copy of a matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.copy() Matrix([ [1, 2], [3, 4]]) """ return self._new(self.rows, self.cols, self.flat()) def cross(self, b): r""" Return the cross product of ``self`` and ``b`` relaxing the condition of compatible dimensions: if each has 3 elements, a matrix of the same type and shape as ``self`` will be returned. If ``b`` has the same shape as ``self`` then common identities for the cross product (like `a \times b = - b \times a`) will hold. Parameters ========== b : 3x1 or 1x3 Matrix See Also ======== dot multiply multiply_elementwise """ from sympy.matrices.expressions.matexpr import MatrixExpr if not isinstance(b, (MatrixBase, MatrixExpr)): raise TypeError( "{} must be a Matrix, not {}.".format(b, type(b))) if not (self.rows * self.cols == b.rows * b.cols == 3): raise ShapeError("Dimensions incorrect for cross product: %s x %s" % ((self.rows, self.cols), (b.rows, b.cols))) else: return self._new(self.rows, self.cols, ( (self[1] * b[2] - self[2] * b[1]), (self[2] * b[0] - self[0] * b[2]), (self[0] * b[1] - self[1] * b[0]))) @property def D(self): """Return Dirac conjugate (if ``self.rows == 4``). Examples ======== >>> from sympy import Matrix, I, eye >>> m = Matrix((0, 1 + I, 2, 3)) >>> m.D Matrix([[0, 1 - I, -2, -3]]) >>> m = (eye(4) + I*eye(4)) >>> m[0, 3] = 2 >>> m.D Matrix([ [1 - I, 0, 0, 0], [ 0, 1 - I, 0, 0], [ 0, 0, -1 + I, 0], [ 2, 0, 0, -1 + I]]) If the matrix does not have 4 rows an AttributeError will be raised because this property is only defined for matrices with 4 rows. >>> Matrix(eye(2)).D Traceback (most recent call last): ... AttributeError: Matrix has no attribute D. See Also ======== sympy.matrices.common.MatrixCommon.conjugate: By-element conjugation sympy.matrices.common.MatrixCommon.H: Hermite conjugation """ from sympy.physics.matrices import mgamma if self.rows != 4: # In Python 3.2, properties can only return an AttributeError # so we can't raise a ShapeError -- see commit which added the # first line of this inline comment. Also, there is no need # for a message since MatrixBase will raise the AttributeError raise AttributeError return self.H * mgamma(0) def dot(self, b, hermitian=None, conjugate_convention=None): """Return the dot or inner product of two vectors of equal length. Here ``self`` must be a ``Matrix`` of size 1 x n or n x 1, and ``b`` must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n. A scalar is returned. By default, ``dot`` does not conjugate ``self`` or ``b``, even if there are complex entries. Set ``hermitian=True`` (and optionally a ``conjugate_convention``) to compute the hermitian inner product. Possible kwargs are ``hermitian`` and ``conjugate_convention``. If ``conjugate_convention`` is ``"left"``, ``"math"`` or ``"maths"``, the conjugate of the first vector (``self``) is used. If ``"right"`` or ``"physics"`` is specified, the conjugate of the second vector ``b`` is used. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> v = Matrix([1, 1, 1]) >>> M.row(0).dot(v) 6 >>> M.col(0).dot(v) 12 >>> v = [3, 2, 1] >>> M.row(0).dot(v) 10 >>> from sympy import I >>> q = Matrix([1*I, 1*I, 1*I]) >>> q.dot(q, hermitian=False) -3 >>> q.dot(q, hermitian=True) 3 >>> q1 = Matrix([1, 1, 1*I]) >>> q.dot(q1, hermitian=True, conjugate_convention="maths") 1 - 2*I >>> q.dot(q1, hermitian=True, conjugate_convention="physics") 1 + 2*I See Also ======== cross multiply multiply_elementwise """ from .dense import Matrix if not isinstance(b, MatrixBase): if is_sequence(b): if len(b) != self.cols and len(b) != self.rows: raise ShapeError( "Dimensions incorrect for dot product: %s, %s" % ( self.shape, len(b))) return self.dot(Matrix(b)) else: raise TypeError( "`b` must be an ordered iterable or Matrix, not %s." % type(b)) mat = self if (1 not in mat.shape) or (1 not in b.shape) : sympy_deprecation_warning( """ Using the dot method to multiply non-row/column vectors is deprecated. Use * or @ to perform matrix multiplication. """, deprecated_since_version="1.2", active_deprecations_target="deprecated-matrix-dot-non-vector") return mat._legacy_array_dot(b) if len(mat) != len(b): raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape)) n = len(mat) if mat.shape != (1, n): mat = mat.reshape(1, n) if b.shape != (n, 1): b = b.reshape(n, 1) # Now ``mat`` is a row vector and ``b`` is a column vector. # If it so happens that only conjugate_convention is passed # then automatically set hermitian to True. If only hermitian # is true but no conjugate_convention is not passed then # automatically set it to ``"maths"`` if conjugate_convention is not None and hermitian is None: hermitian = True if hermitian and conjugate_convention is None: conjugate_convention = "maths" if hermitian == True: if conjugate_convention in ("maths", "left", "math"): mat = mat.conjugate() elif conjugate_convention in ("physics", "right"): b = b.conjugate() else: raise ValueError("Unknown conjugate_convention was entered." " conjugate_convention must be one of the" " following: math, maths, left, physics or right.") return (mat * b)[0] def dual(self): """Returns the dual of a matrix, which is: ``(1/2)*levicivita(i, j, k, l)*M(k, l)`` summed over indices `k` and `l` Since the levicivita method is anti_symmetric for any pairwise exchange of indices, the dual of a symmetric matrix is the zero matrix. Strictly speaking the dual defined here assumes that the 'matrix' `M` is a contravariant anti_symmetric second rank tensor, so that the dual is a covariant second rank tensor. """ from sympy.matrices import zeros M, n = self[:, :], self.rows work = zeros(n) if self.is_symmetric(): return work for i in range(1, n): for j in range(1, n): acum = 0 for k in range(1, n): acum += LeviCivita(i, j, 0, k) * M[0, k] work[i, j] = acum work[j, i] = -acum for l in range(1, n): acum = 0 for a in range(1, n): for b in range(1, n): acum += LeviCivita(0, l, a, b) * M[a, b] acum /= 2 work[0, l] = -acum work[l, 0] = acum return work def _eval_matrix_exp_jblock(self): """A helper function to compute an exponential of a Jordan block matrix Examples ======== >>> from sympy import Symbol, Matrix >>> l = Symbol('lamda') A trivial example of 1*1 Jordan block: >>> m = Matrix.jordan_block(1, l) >>> m._eval_matrix_exp_jblock() Matrix([[exp(lamda)]]) An example of 3*3 Jordan block: >>> m = Matrix.jordan_block(3, l) >>> m._eval_matrix_exp_jblock() Matrix([ [exp(lamda), exp(lamda), exp(lamda)/2], [ 0, exp(lamda), exp(lamda)], [ 0, 0, exp(lamda)]]) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition """ size = self.rows l = self[0, 0] exp_l = exp(l) bands = {i: exp_l / factorial(i) for i in range(size)} from .sparsetools import banded return self.__class__(banded(size, bands)) def analytic_func(self, f, x): """ Computes f(A) where A is a Square Matrix and f is an analytic function. Examples ======== >>> from sympy import Symbol, Matrix, S, log >>> x = Symbol('x') >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]]) >>> f = log(x) >>> m.analytic_func(f, x) Matrix([ [ 0, log(2)], [log(2), 0]]) Parameters ========== f : Expr Analytic Function x : Symbol parameter of f """ f, x = _sympify(f), _sympify(x) if not self.is_square: raise NonSquareMatrixError if not x.is_symbol: raise ValueError("{} must be a symbol.".format(x)) if x not in f.free_symbols: raise ValueError( "{} must be a parameter of {}.".format(x, f)) if x in self.free_symbols: raise ValueError( "{} must not be a parameter of {}.".format(x, self)) eigen = self.eigenvals() max_mul = max(eigen.values()) derivative = {} dd = f for i in range(max_mul - 1): dd = diff(dd, x) derivative[i + 1] = dd n = self.shape[0] r = self.zeros(n) f_val = self.zeros(n, 1) row = 0 for i in eigen: mul = eigen[i] f_val[row] = f.subs(x, i) if f_val[row].is_number and not f_val[row].is_complex: raise ValueError( "Cannot evaluate the function because the " "function {} is not analytic at the given " "eigenvalue {}".format(f, f_val[row])) val = 1 for a in range(n): r[row, a] = val val *= i if mul > 1: coe = [1 for ii in range(n)] deri = 1 while mul > 1: row = row + 1 mul -= 1 d_i = derivative[deri].subs(x, i) if d_i.is_number and not d_i.is_complex: raise ValueError( "Cannot evaluate the function because the " "derivative {} is not analytic at the given " "eigenvalue {}".format(derivative[deri], d_i)) f_val[row] = d_i for a in range(n): if a - deri + 1 <= 0: r[row, a] = 0 coe[a] = 0 continue coe[a] = coe[a]*(a - deri + 1) r[row, a] = coe[a]*pow(i, a - deri) deri += 1 row += 1 c = r.solve(f_val) ans = self.zeros(n) pre = self.eye(n) for i in range(n): ans = ans + c[i]*pre pre *= self return ans def exp(self): """Return the exponential of a square matrix Examples ======== >>> from sympy import Symbol, Matrix >>> t = Symbol('t') >>> m = Matrix([[0, 1], [-1, 0]]) * t >>> m.exp() Matrix([ [ exp(I*t)/2 + exp(-I*t)/2, -I*exp(I*t)/2 + I*exp(-I*t)/2], [I*exp(I*t)/2 - I*exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]]) """ if not self.is_square: raise NonSquareMatrixError( "Exponentiation is valid only for square matrices") try: P, J = self.jordan_form() cells = J.get_diag_blocks() except MatrixError: raise NotImplementedError( "Exponentiation is implemented only for matrices for which the Jordan normal form can be computed") blocks = [cell._eval_matrix_exp_jblock() for cell in cells] from sympy.matrices import diag eJ = diag(*blocks) # n = self.rows ret = P.multiply(eJ, dotprodsimp=None).multiply(P.inv(), dotprodsimp=None) if all(value.is_real for value in self.values()): return type(self)(re(ret)) else: return type(self)(ret) def _eval_matrix_log_jblock(self): """Helper function to compute logarithm of a jordan block. Examples ======== >>> from sympy import Symbol, Matrix >>> l = Symbol('lamda') A trivial example of 1*1 Jordan block: >>> m = Matrix.jordan_block(1, l) >>> m._eval_matrix_log_jblock() Matrix([[log(lamda)]]) An example of 3*3 Jordan block: >>> m = Matrix.jordan_block(3, l) >>> m._eval_matrix_log_jblock() Matrix([ [log(lamda), 1/lamda, -1/(2*lamda**2)], [ 0, log(lamda), 1/lamda], [ 0, 0, log(lamda)]]) """ size = self.rows l = self[0, 0] if l.is_zero: raise MatrixError( 'Could not take logarithm or reciprocal for the given ' 'eigenvalue {}'.format(l)) bands = {0: log(l)} for i in range(1, size): bands[i] = -((-l) ** -i) / i from .sparsetools import banded return self.__class__(banded(size, bands)) def log(self, simplify=cancel): """Return the logarithm of a square matrix Parameters ========== simplify : function, bool The function to simplify the result with. Default is ``cancel``, which is effective to reduce the expression growing for taking reciprocals and inverses for symbolic matrices. Examples ======== >>> from sympy import S, Matrix Examples for positive-definite matrices: >>> m = Matrix([[1, 1], [0, 1]]) >>> m.log() Matrix([ [0, 1], [0, 0]]) >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]]) >>> m.log() Matrix([ [ 0, log(2)], [log(2), 0]]) Examples for non positive-definite matrices: >>> m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]]) >>> m.log() Matrix([ [ I*pi/2, log(2) - I*pi/2], [log(2) - I*pi/2, I*pi/2]]) >>> m = Matrix( ... [[0, 0, 0, 1], ... [0, 0, 1, 0], ... [0, 1, 0, 0], ... [1, 0, 0, 0]]) >>> m.log() Matrix([ [ I*pi/2, 0, 0, -I*pi/2], [ 0, I*pi/2, -I*pi/2, 0], [ 0, -I*pi/2, I*pi/2, 0], [-I*pi/2, 0, 0, I*pi/2]]) """ if not self.is_square: raise NonSquareMatrixError( "Logarithm is valid only for square matrices") try: if simplify: P, J = simplify(self).jordan_form() else: P, J = self.jordan_form() cells = J.get_diag_blocks() except MatrixError: raise NotImplementedError( "Logarithm is implemented only for matrices for which " "the Jordan normal form can be computed") blocks = [ cell._eval_matrix_log_jblock() for cell in cells] from sympy.matrices import diag eJ = diag(*blocks) if simplify: ret = simplify(P * eJ * simplify(P.inv())) ret = self.__class__(ret) else: ret = P * eJ * P.inv() return ret def is_nilpotent(self): """Checks if a matrix is nilpotent. A matrix B is nilpotent if for some integer k, B**k is a zero matrix. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) >>> a.is_nilpotent() True >>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]]) >>> a.is_nilpotent() False """ if not self: return True if not self.is_square: raise NonSquareMatrixError( "Nilpotency is valid only for square matrices") x = uniquely_named_symbol('x', self, modify=lambda s: '_' + s) p = self.charpoly(x) if p.args[0] == x ** self.rows: return True return False def key2bounds(self, keys): """Converts a key with potentially mixed types of keys (integer and slice) into a tuple of ranges and raises an error if any index is out of ``self``'s range. See Also ======== key2ij """ from sympy.matrices.common import a2idx as a2idx_ # Remove this line after deprecation of a2idx from matrices.py islice, jslice = [isinstance(k, slice) for k in keys] if islice: if not self.rows: rlo = rhi = 0 else: rlo, rhi = keys[0].indices(self.rows)[:2] else: rlo = a2idx_(keys[0], self.rows) rhi = rlo + 1 if jslice: if not self.cols: clo = chi = 0 else: clo, chi = keys[1].indices(self.cols)[:2] else: clo = a2idx_(keys[1], self.cols) chi = clo + 1 return rlo, rhi, clo, chi def key2ij(self, key): """Converts key into canonical form, converting integers or indexable items into valid integers for ``self``'s range or returning slices unchanged. See Also ======== key2bounds """ from sympy.matrices.common import a2idx as a2idx_ # Remove this line after deprecation of a2idx from matrices.py if is_sequence(key): if not len(key) == 2: raise TypeError('key must be a sequence of length 2') return [a2idx_(i, n) if not isinstance(i, slice) else i for i, n in zip(key, self.shape)] elif isinstance(key, slice): return key.indices(len(self))[:2] else: return divmod(a2idx_(key, len(self)), self.cols) def normalized(self, iszerofunc=_iszero): """Return the normalized version of ``self``. Parameters ========== iszerofunc : Function, optional A function to determine whether ``self`` is a zero vector. The default ``_iszero`` tests to see if each element is exactly zero. Returns ======= Matrix Normalized vector form of ``self``. It has the same length as a unit vector. However, a zero vector will be returned for a vector with norm 0. Raises ====== ShapeError If the matrix is not in a vector form. See Also ======== norm """ if self.rows != 1 and self.cols != 1: raise ShapeError("A Matrix must be a vector to normalize.") norm = self.norm() if iszerofunc(norm): out = self.zeros(self.rows, self.cols) else: out = self.applyfunc(lambda i: i / norm) return out def norm(self, ord=None): """Return the Norm of a Matrix or Vector. In the simplest case this is the geometric size of the vector Other norms can be specified by the ord parameter ===== ============================ ========================== ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm 'fro' Frobenius norm - does not exist inf maximum row sum max(abs(x)) -inf -- min(abs(x)) 1 maximum column sum as below -1 -- as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other - does not exist sum(abs(x)**ord)**(1./ord) ===== ============================ ========================== Examples ======== >>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo >>> x = Symbol('x', real=True) >>> v = Matrix([cos(x), sin(x)]) >>> trigsimp( v.norm() ) 1 >>> v.norm(10) (sin(x)**10 + cos(x)**10)**(1/10) >>> A = Matrix([[1, 1], [1, 1]]) >>> A.norm(1) # maximum sum of absolute values of A is 2 2 >>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm) 2 >>> A.norm(-2) # Inverse spectral norm (smallest singular value) 0 >>> A.norm() # Frobenius Norm 2 >>> A.norm(oo) # Infinity Norm 2 >>> Matrix([1, -2]).norm(oo) 2 >>> Matrix([-1, 2]).norm(-oo) 1 See Also ======== normalized """ # Row or Column Vector Norms vals = list(self.values()) or [0] if S.One in self.shape: if ord in (2, None): # Common case sqrt(<x, x>) return sqrt(Add(*(abs(i) ** 2 for i in vals))) elif ord == 1: # sum(abs(x)) return Add(*(abs(i) for i in vals)) elif ord is S.Infinity: # max(abs(x)) return Max(*[abs(i) for i in vals]) elif ord is S.NegativeInfinity: # min(abs(x)) return Min(*[abs(i) for i in vals]) # Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord) # Note that while useful this is not mathematically a norm try: return Pow(Add(*(abs(i) ** ord for i in vals)), S.One / ord) except (NotImplementedError, TypeError): raise ValueError("Expected order to be Number, Symbol, oo") # Matrix Norms else: if ord == 1: # Maximum column sum m = self.applyfunc(abs) return Max(*[sum(m.col(i)) for i in range(m.cols)]) elif ord == 2: # Spectral Norm # Maximum singular value return Max(*self.singular_values()) elif ord == -2: # Minimum singular value return Min(*self.singular_values()) elif ord is S.Infinity: # Infinity Norm - Maximum row sum m = self.applyfunc(abs) return Max(*[sum(m.row(i)) for i in range(m.rows)]) elif (ord is None or isinstance(ord, str) and ord.lower() in ['f', 'fro', 'frobenius', 'vector']): # Reshape as vector and send back to norm function return self.vec().norm(ord=2) else: raise NotImplementedError("Matrix Norms under development") def print_nonzero(self, symb="X"): """Shows location of non-zero entries for fast shape lookup. Examples ======== >>> from sympy import Matrix, eye >>> m = Matrix(2, 3, lambda i, j: i*3+j) >>> m Matrix([ [0, 1, 2], [3, 4, 5]]) >>> m.print_nonzero() [ XX] [XXX] >>> m = eye(4) >>> m.print_nonzero("x") [x ] [ x ] [ x ] [ x] """ s = [] for i in range(self.rows): line = [] for j in range(self.cols): if self[i, j] == 0: line.append(" ") else: line.append(str(symb)) s.append("[%s]" % ''.join(line)) print('\n'.join(s)) def project(self, v): """Return the projection of ``self`` onto the line containing ``v``. Examples ======== >>> from sympy import Matrix, S, sqrt >>> V = Matrix([sqrt(3)/2, S.Half]) >>> x = Matrix([[1, 0]]) >>> V.project(x) Matrix([[sqrt(3)/2, 0]]) >>> V.project(-x) Matrix([[sqrt(3)/2, 0]]) """ return v * (self.dot(v) / v.dot(v)) def table(self, printer, rowstart='[', rowend=']', rowsep='\n', colsep=', ', align='right'): r""" String form of Matrix as a table. ``printer`` is the printer to use for on the elements (generally something like StrPrinter()) ``rowstart`` is the string used to start each row (by default '['). ``rowend`` is the string used to end each row (by default ']'). ``rowsep`` is the string used to separate rows (by default a newline). ``colsep`` is the string used to separate columns (by default ', '). ``align`` defines how the elements are aligned. Must be one of 'left', 'right', or 'center'. You can also use '<', '>', and '^' to mean the same thing, respectively. This is used by the string printer for Matrix. Examples ======== >>> from sympy import Matrix, StrPrinter >>> M = Matrix([[1, 2], [-33, 4]]) >>> printer = StrPrinter() >>> M.table(printer) '[ 1, 2]\n[-33, 4]' >>> print(M.table(printer)) [ 1, 2] [-33, 4] >>> print(M.table(printer, rowsep=',\n')) [ 1, 2], [-33, 4] >>> print('[%s]' % M.table(printer, rowsep=',\n')) [[ 1, 2], [-33, 4]] >>> print(M.table(printer, colsep=' ')) [ 1 2] [-33 4] >>> print(M.table(printer, align='center')) [ 1 , 2] [-33, 4] >>> print(M.table(printer, rowstart='{', rowend='}')) { 1, 2} {-33, 4} """ # Handle zero dimensions: if S.Zero in self.shape: return '[]' # Build table of string representations of the elements res = [] # Track per-column max lengths for pretty alignment maxlen = [0] * self.cols for i in range(self.rows): res.append([]) for j in range(self.cols): s = printer._print(self[i, j]) res[-1].append(s) maxlen[j] = max(len(s), maxlen[j]) # Patch strings together align = { 'left': 'ljust', 'right': 'rjust', 'center': 'center', '<': 'ljust', '>': 'rjust', '^': 'center', }[align] for i, row in enumerate(res): for j, elem in enumerate(row): row[j] = getattr(elem, align)(maxlen[j]) res[i] = rowstart + colsep.join(row) + rowend return rowsep.join(res) def rank_decomposition(self, iszerofunc=_iszero, simplify=False): return _rank_decomposition(self, iszerofunc=iszerofunc, simplify=simplify) def cholesky(self, hermitian=True): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def LDLdecomposition(self, hermitian=True): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def LUdecomposition(self, iszerofunc=_iszero, simpfunc=None, rankcheck=False): return _LUdecomposition(self, iszerofunc=iszerofunc, simpfunc=simpfunc, rankcheck=rankcheck) def LUdecomposition_Simple(self, iszerofunc=_iszero, simpfunc=None, rankcheck=False): return _LUdecomposition_Simple(self, iszerofunc=iszerofunc, simpfunc=simpfunc, rankcheck=rankcheck) def LUdecompositionFF(self): return _LUdecompositionFF(self) def singular_value_decomposition(self): return _singular_value_decomposition(self) def QRdecomposition(self): return _QRdecomposition(self) def upper_hessenberg_decomposition(self): return _upper_hessenberg_decomposition(self) def diagonal_solve(self, rhs): return _diagonal_solve(self, rhs) def lower_triangular_solve(self, rhs): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def upper_triangular_solve(self, rhs): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def cholesky_solve(self, rhs): return _cholesky_solve(self, rhs) def LDLsolve(self, rhs): return _LDLsolve(self, rhs) def LUsolve(self, rhs, iszerofunc=_iszero): return _LUsolve(self, rhs, iszerofunc=iszerofunc) def QRsolve(self, b): return _QRsolve(self, b) def gauss_jordan_solve(self, B, freevar=False): return _gauss_jordan_solve(self, B, freevar=freevar) def pinv_solve(self, B, arbitrary_matrix=None): return _pinv_solve(self, B, arbitrary_matrix=arbitrary_matrix) def solve(self, rhs, method='GJ'): return _solve(self, rhs, method=method) def solve_least_squares(self, rhs, method='CH'): return _solve_least_squares(self, rhs, method=method) def pinv(self, method='RD'): return _pinv(self, method=method) def inv_mod(self, m): return _inv_mod(self, m) def inverse_ADJ(self, iszerofunc=_iszero): return _inv_ADJ(self, iszerofunc=iszerofunc) def inverse_BLOCK(self, iszerofunc=_iszero): return _inv_block(self, iszerofunc=iszerofunc) def inverse_GE(self, iszerofunc=_iszero): return _inv_GE(self, iszerofunc=iszerofunc) def inverse_LU(self, iszerofunc=_iszero): return _inv_LU(self, iszerofunc=iszerofunc) def inverse_CH(self, iszerofunc=_iszero): return _inv_CH(self, iszerofunc=iszerofunc) def inverse_LDL(self, iszerofunc=_iszero): return _inv_LDL(self, iszerofunc=iszerofunc) def inverse_QR(self, iszerofunc=_iszero): return _inv_QR(self, iszerofunc=iszerofunc) def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False): return _inv(self, method=method, iszerofunc=iszerofunc, try_block_diag=try_block_diag) def connected_components(self): return _connected_components(self) def connected_components_decomposition(self): return _connected_components_decomposition(self) def strongly_connected_components(self): return _strongly_connected_components(self) def strongly_connected_components_decomposition(self, lower=True): return _strongly_connected_components_decomposition(self, lower=lower) _sage_ = Basic._sage_ rank_decomposition.__doc__ = _rank_decomposition.__doc__ cholesky.__doc__ = _cholesky.__doc__ LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ LUdecomposition.__doc__ = _LUdecomposition.__doc__ LUdecomposition_Simple.__doc__ = _LUdecomposition_Simple.__doc__ LUdecompositionFF.__doc__ = _LUdecompositionFF.__doc__ singular_value_decomposition.__doc__ = _singular_value_decomposition.__doc__ QRdecomposition.__doc__ = _QRdecomposition.__doc__ upper_hessenberg_decomposition.__doc__ = _upper_hessenberg_decomposition.__doc__ diagonal_solve.__doc__ = _diagonal_solve.__doc__ lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ cholesky_solve.__doc__ = _cholesky_solve.__doc__ LDLsolve.__doc__ = _LDLsolve.__doc__ LUsolve.__doc__ = _LUsolve.__doc__ QRsolve.__doc__ = _QRsolve.__doc__ gauss_jordan_solve.__doc__ = _gauss_jordan_solve.__doc__ pinv_solve.__doc__ = _pinv_solve.__doc__ solve.__doc__ = _solve.__doc__ solve_least_squares.__doc__ = _solve_least_squares.__doc__ pinv.__doc__ = _pinv.__doc__ inv_mod.__doc__ = _inv_mod.__doc__ inverse_ADJ.__doc__ = _inv_ADJ.__doc__ inverse_GE.__doc__ = _inv_GE.__doc__ inverse_LU.__doc__ = _inv_LU.__doc__ inverse_CH.__doc__ = _inv_CH.__doc__ inverse_LDL.__doc__ = _inv_LDL.__doc__ inverse_QR.__doc__ = _inv_QR.__doc__ inverse_BLOCK.__doc__ = _inv_block.__doc__ inv.__doc__ = _inv.__doc__ connected_components.__doc__ = _connected_components.__doc__ connected_components_decomposition.__doc__ = \ _connected_components_decomposition.__doc__ strongly_connected_components.__doc__ = \ _strongly_connected_components.__doc__ strongly_connected_components_decomposition.__doc__ = \ _strongly_connected_components_decomposition.__doc__ @deprecated( """ sympy.matrices.matrices.classof is deprecated. Use sympy.matrices.common.classof instead. """, deprecated_since_version="1.3", active_deprecations_target="deprecated-sympy-matrices-classof-a2idx", ) def classof(A, B): from sympy.matrices.common import classof as classof_ return classof_(A, B) @deprecated( """ sympy.matrices.matrices.a2idx is deprecated. Use sympy.matrices.common.a2idx instead. """, deprecated_since_version="1.3", active_deprecations_target="deprecated-sympy-matrices-classof-a2idx", ) def a2idx(j, n=None): from sympy.matrices.common import a2idx as a2idx_ return a2idx_(j, n)
399723273f9828f2e38bbcecf553b215050ddb470a859e66f9da821dd3379988
from types import FunctionType from collections import Counter from mpmath import mp, workprec from mpmath.libmp.libmpf import prec_to_dps from sympy.core.sorting import default_sort_key from sympy.core.evalf import DEFAULT_MAXPREC, PrecisionExhausted from sympy.core.logic import fuzzy_and, fuzzy_or from sympy.core.numbers import Float from sympy.core.sympify import _sympify from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys import roots, CRootOf, ZZ, QQ, EX from sympy.polys.matrices import DomainMatrix from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy from sympy.polys.polytools import gcd from sympy.utilities.exceptions import sympy_deprecation_warning from .common import MatrixError, NonSquareMatrixError from .determinant import _find_reasonable_pivot from .utilities import _iszero, _simplify def _eigenvals_eigenvects_mpmath(M): norm2 = lambda v: mp.sqrt(sum(i**2 for i in v)) v1 = None prec = max([x._prec for x in M.atoms(Float)]) eps = 2**-prec while prec < DEFAULT_MAXPREC: with workprec(prec): A = mp.matrix(M.evalf(n=prec_to_dps(prec))) E, ER = mp.eig(A) v2 = norm2([i for e in E for i in (mp.re(e), mp.im(e))]) if v1 is not None and mp.fabs(v1 - v2) < eps: return E, ER v1 = v2 prec *= 2 # we get here because the next step would have taken us # past MAXPREC or because we never took a step; in case # of the latter, we refuse to send back a solution since # it would not have been verified; we also resist taking # a small step to arrive exactly at MAXPREC since then # the two calculations might be artificially close. raise PrecisionExhausted def _eigenvals_mpmath(M, multiple=False): """Compute eigenvalues using mpmath""" E, _ = _eigenvals_eigenvects_mpmath(M) result = [_sympify(x) for x in E] if multiple: return result return dict(Counter(result)) def _eigenvects_mpmath(M): E, ER = _eigenvals_eigenvects_mpmath(M) result = [] for i in range(M.rows): eigenval = _sympify(E[i]) eigenvect = _sympify(ER[:, i]) result.append((eigenval, 1, [eigenvect])) return result # This function is a candidate for caching if it gets implemented for matrices. def _eigenvals( M, error_when_incomplete=True, *, simplify=False, multiple=False, rational=False, **flags): r"""Compute eigenvalues of the matrix. Parameters ========== error_when_incomplete : bool, optional If it is set to ``True``, it will raise an error if not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. simplify : bool or function, optional If it is set to ``True``, it attempts to return the most simplified form of expressions returned by applying default simplification method in every routine. If it is set to ``False``, it will skip simplification in this particular routine to save computation resources. If a function is passed to, it will attempt to apply the particular function as simplification method. rational : bool, optional If it is set to ``True``, every floating point numbers would be replaced with rationals before computation. It can solve some issues of ``roots`` routine not working well with floats. multiple : bool, optional If it is set to ``True``, the result will be in the form of a list. If it is set to ``False``, the result will be in the form of a dictionary. Returns ======= eigs : list or dict Eigenvalues of a matrix. The return format would be specified by the key ``multiple``. Raises ====== MatrixError If not enough roots had got computed. NonSquareMatrixError If attempted to compute eigenvalues from a non-square matrix. Examples ======== >>> from sympy import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvals() {-1: 1, 0: 1, 2: 1} See Also ======== MatrixDeterminant.charpoly eigenvects Notes ===== Eigenvalues of a matrix $A$ can be computed by solving a matrix equation $\det(A - \lambda I) = 0$ It's not always possible to return radical solutions for eigenvalues for matrices larger than $4, 4$ shape due to Abel-Ruffini theorem. If there is no radical solution is found for the eigenvalue, it may return eigenvalues in the form of :class:`sympy.polys.rootoftools.ComplexRootOf`. """ if not M: if multiple: return [] return {} if not M.is_square: raise NonSquareMatrixError("{} must be a square matrix.".format(M)) if M._rep.domain not in (ZZ, QQ): # Skip this check for ZZ/QQ because it can be slow if all(x.is_number for x in M) and M.has(Float): return _eigenvals_mpmath(M, multiple=multiple) if rational: from sympy.simplify import nsimplify M = M.applyfunc( lambda x: nsimplify(x, rational=True) if x.has(Float) else x) if multiple: return _eigenvals_list( M, error_when_incomplete=error_when_incomplete, simplify=simplify, **flags) return _eigenvals_dict( M, error_when_incomplete=error_when_incomplete, simplify=simplify, **flags) eigenvals_error_message = \ "It is not always possible to express the eigenvalues of a matrix " + \ "of size 5x5 or higher in radicals. " + \ "We have CRootOf, but domains other than the rationals are not " + \ "currently supported. " + \ "If there are no symbols in the matrix, " + \ "it should still be possible to compute numeric approximations " + \ "of the eigenvalues using " + \ "M.evalf().eigenvals() or M.charpoly().nroots()." def _eigenvals_list( M, error_when_incomplete=True, simplify=False, **flags): iblocks = M.strongly_connected_components() all_eigs = [] is_dom = M._rep.domain in (ZZ, QQ) for b in iblocks: # Fast path for a 1x1 block: if is_dom and len(b) == 1: index = b[0] val = M[index, index] all_eigs.append(val) continue block = M[b, b] if isinstance(simplify, FunctionType): charpoly = block.charpoly(simplify=simplify) else: charpoly = block.charpoly() eigs = roots(charpoly, multiple=True, **flags) if len(eigs) != block.rows: degree = int(charpoly.degree()) f = charpoly.as_expr() x = charpoly.gen try: eigs = [CRootOf(f, x, idx) for idx in range(degree)] except NotImplementedError: if error_when_incomplete: raise MatrixError(eigenvals_error_message) else: eigs = [] all_eigs += eigs if not simplify: return all_eigs if not isinstance(simplify, FunctionType): simplify = _simplify return [simplify(value) for value in all_eigs] def _eigenvals_dict( M, error_when_incomplete=True, simplify=False, **flags): iblocks = M.strongly_connected_components() all_eigs = {} is_dom = M._rep.domain in (ZZ, QQ) for b in iblocks: # Fast path for a 1x1 block: if is_dom and len(b) == 1: index = b[0] val = M[index, index] all_eigs[val] = all_eigs.get(val, 0) + 1 continue block = M[b, b] if isinstance(simplify, FunctionType): charpoly = block.charpoly(simplify=simplify) else: charpoly = block.charpoly() eigs = roots(charpoly, multiple=False, **flags) if sum(eigs.values()) != block.rows: degree = int(charpoly.degree()) f = charpoly.as_expr() x = charpoly.gen try: eigs = {CRootOf(f, x, idx): 1 for idx in range(degree)} except NotImplementedError: if error_when_incomplete: raise MatrixError(eigenvals_error_message) else: eigs = {} for k, v in eigs.items(): if k in all_eigs: all_eigs[k] += v else: all_eigs[k] = v if not simplify: return all_eigs if not isinstance(simplify, FunctionType): simplify = _simplify return {simplify(key): value for key, value in all_eigs.items()} def _eigenspace(M, eigenval, iszerofunc=_iszero, simplify=False): """Get a basis for the eigenspace for a particular eigenvalue""" m = M - M.eye(M.rows) * eigenval ret = m.nullspace(iszerofunc=iszerofunc) # The nullspace for a real eigenvalue should be non-trivial. # If we didn't find an eigenvector, try once more a little harder if len(ret) == 0 and simplify: ret = m.nullspace(iszerofunc=iszerofunc, simplify=True) if len(ret) == 0: raise NotImplementedError( "Can't evaluate eigenvector for eigenvalue {}".format(eigenval)) return ret def _eigenvects_DOM(M, **kwargs): DOM = DomainMatrix.from_Matrix(M, field=True, extension=True) DOM = DOM.to_dense() if DOM.domain != EX: rational, algebraic = dom_eigenvects(DOM) eigenvects = dom_eigenvects_to_sympy( rational, algebraic, M.__class__, **kwargs) eigenvects = sorted(eigenvects, key=lambda x: default_sort_key(x[0])) return eigenvects return None def _eigenvects_sympy(M, iszerofunc, simplify=True, **flags): eigenvals = M.eigenvals(rational=False, **flags) # Make sure that we have all roots in radical form for x in eigenvals: if x.has(CRootOf): raise MatrixError( "Eigenvector computation is not implemented if the matrix have " "eigenvalues in CRootOf form") eigenvals = sorted(eigenvals.items(), key=default_sort_key) ret = [] for val, mult in eigenvals: vects = _eigenspace(M, val, iszerofunc=iszerofunc, simplify=simplify) ret.append((val, mult, vects)) return ret # This functions is a candidate for caching if it gets implemented for matrices. def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, *, chop=False, **flags): """Compute eigenvectors of the matrix. Parameters ========== error_when_incomplete : bool, optional Raise an error when not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. iszerofunc : function, optional Specifies a zero testing function to be used in ``rref``. Default value is ``_iszero``, which uses SymPy's naive and fast default assumption handler. It can also accept any user-specified zero testing function, if it is formatted as a function which accepts a single symbolic argument and returns ``True`` if it is tested as zero and ``False`` if it is tested as non-zero, and ``None`` if it is undecidable. simplify : bool or function, optional If ``True``, ``as_content_primitive()`` will be used to tidy up normalization artifacts. It will also be used by the ``nullspace`` routine. chop : bool or positive number, optional If the matrix contains any Floats, they will be changed to Rationals for computation purposes, but the answers will be returned after being evaluated with evalf. The ``chop`` flag is passed to ``evalf``. When ``chop=True`` a default precision will be used; a number will be interpreted as the desired level of precision. Returns ======= ret : [(eigenval, multiplicity, eigenspace), ...] A ragged list containing tuples of data obtained by ``eigenvals`` and ``nullspace``. ``eigenspace`` is a list containing the ``eigenvector`` for each eigenvalue. ``eigenvector`` is a vector in the form of a ``Matrix``. e.g. a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``. Raises ====== NotImplementedError If failed to compute nullspace. Examples ======== >>> from sympy import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvects() [(-1, 1, [Matrix([ [-1], [ 1], [ 0]])]), (0, 1, [Matrix([ [ 0], [-1], [ 1]])]), (2, 1, [Matrix([ [2/3], [1/3], [ 1]])])] See Also ======== eigenvals MatrixSubspaces.nullspace """ simplify = flags.get('simplify', True) primitive = flags.get('simplify', False) flags.pop('simplify', None) # remove this if it's there flags.pop('multiple', None) # remove this if it's there if not isinstance(simplify, FunctionType): simpfunc = _simplify if simplify else lambda x: x has_floats = M.has(Float) if has_floats: if all(x.is_number for x in M): return _eigenvects_mpmath(M) from sympy.simplify import nsimplify M = M.applyfunc(lambda x: nsimplify(x, rational=True)) ret = _eigenvects_DOM(M) if ret is None: ret = _eigenvects_sympy(M, iszerofunc, simplify=simplify, **flags) if primitive: # if the primitive flag is set, get rid of any common # integer denominators def denom_clean(l): return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l] ret = [(val, mult, denom_clean(es)) for val, mult, es in ret] if has_floats: # if we had floats to start with, turn the eigenvectors to floats ret = [(val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es]) for val, mult, es in ret] return ret def _is_diagonalizable_with_eigen(M, reals_only=False): """See _is_diagonalizable. This function returns the bool along with the eigenvectors to avoid calculating them again in functions like ``diagonalize``.""" if not M.is_square: return False, [] eigenvecs = M.eigenvects(simplify=True) for val, mult, basis in eigenvecs: if reals_only and not val.is_real: # if we have a complex eigenvalue return False, eigenvecs if mult != len(basis): # if the geometric multiplicity doesn't equal the algebraic return False, eigenvecs return True, eigenvecs 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: sympy_deprecation_warning( """ The 'clear_cache' keyword to Matrix.is_diagonalizable is deprecated. It does nothing and should be omitted. """, deprecated_since_version="1.4", active_deprecations_target="deprecated-matrix-is_diagonalizable-cache", stacklevel=4, ) if 'clear_subproducts' in kwargs: sympy_deprecation_warning( """ The 'clear_subproducts' keyword to Matrix.is_diagonalizable is deprecated. It does nothing and should be omitted. """, deprecated_since_version="1.4", active_deprecations_target="deprecated-matrix-is_diagonalizable-cache", stacklevel=4, ) 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] #G&VL, Matrix Computations, Algo 5.4.2 def _householder_vector(x): if not x.cols == 1: raise ValueError("Input must be a column matrix") v = x.copy() v_plus = x.copy() v_minus = x.copy() q = x[0, 0] / abs(x[0, 0]) norm_x = x.norm() v_plus[0, 0] = x[0, 0] + q * norm_x v_minus[0, 0] = x[0, 0] - q * norm_x if x[1:, 0].norm() == 0: bet = 0 v[0, 0] = 1 else: if v_plus.norm() <= v_minus.norm(): v = v_plus else: v = v_minus v = v / v[0] bet = 2 / (v.norm() ** 2) return v, bet def _bidiagonal_decmp_hholder(M): m = M.rows n = M.cols A = M.as_mutable() U, V = A.eye(m), A.eye(n) for i in range(min(m, n)): v, bet = _householder_vector(A[i:, i]) hh_mat = A.eye(m - i) - bet * v * v.H A[i:, i:] = hh_mat * A[i:, i:] temp = A.eye(m) temp[i:, i:] = hh_mat U = U * temp if i + 1 <= n - 2: v, bet = _householder_vector(A[i, i+1:].T) hh_mat = A.eye(n - i - 1) - bet * v * v.H A[i:, i+1:] = A[i:, i+1:] * hh_mat temp = A.eye(n) temp[i+1:, i+1:] = hh_mat V = temp * V return U, A, V def _eval_bidiag_hholder(M): m = M.rows n = M.cols A = M.as_mutable() for i in range(min(m, n)): v, bet = _householder_vector(A[i:, i]) hh_mat = A.eye(m-i) - bet * v * v.H A[i:, i:] = hh_mat * A[i:, i:] if i + 1 <= n - 2: v, bet = _householder_vector(A[i, i+1:].T) hh_mat = A.eye(n - i - 1) - bet * v * v.H A[i:, i+1:] = A[i:, i+1:] * hh_mat return A def _bidiagonal_decomposition(M, upper=True): """ Returns $(U,B,V.H)$ for $$A = UBV^{H}$$ where $A$ is the input matrix, and $B$ is its Bidiagonalized form Note: Bidiagonal Computation can hang for symbolic matrices. Parameters ========== upper : bool. Whether to do upper bidiagnalization or lower. True for upper and False for lower. References ========== .. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition .. [2] Complex Matrix Bidiagonalization, https://github.com/vslobody/Householder-Bidiagonalization """ if not isinstance(upper, bool): raise ValueError("upper must be a boolean") if upper: return _bidiagonal_decmp_hholder(M) X = _bidiagonal_decmp_hholder(M.H) return X[2].H, X[1].H, X[0].H def _bidiagonalize(M, upper=True): """ Returns $B$, the Bidiagonalized form of the input matrix. Note: Bidiagonal Computation can hang for symbolic matrices. Parameters ========== upper : bool. Whether to do upper bidiagnalization or lower. True for upper and False for lower. References ========== .. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition .. [2] Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization """ if not isinstance(upper, bool): raise ValueError("upper must be a boolean") if upper: return _eval_bidiag_hholder(M) return _eval_bidiag_hholder(M.H).H def _diagonalize(M, reals_only=False, sort=False, normalize=False): """ Return (P, D), where D is diagonal and D = P^-1 * M * P where M is current matrix. Parameters ========== reals_only : bool. Whether to throw an error if complex numbers are need to diagonalize. (Default: False) sort : bool. Sort the eigenvalues along the diagonal. (Default: False) normalize : bool. If True, normalize the columns of P. (Default: False) Examples ======== >>> from sympy import Matrix >>> M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) >>> M Matrix([ [1, 2, 0], [0, 3, 0], [2, -4, 2]]) >>> (P, D) = M.diagonalize() >>> D Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> P Matrix([ [-1, 0, -1], [ 0, 0, -1], [ 2, 1, 2]]) >>> P.inv() * M * P Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) See Also ======== is_diagonal is_diagonalizable """ if not M.is_square: raise NonSquareMatrixError() is_diagonalizable, eigenvecs = _is_diagonalizable_with_eigen(M, reals_only=reals_only) if not is_diagonalizable: raise MatrixError("Matrix is not diagonalizable") if sort: eigenvecs = sorted(eigenvecs, key=default_sort_key) p_cols, diag = [], [] for val, mult, basis in eigenvecs: diag += [val] * mult p_cols += basis if normalize: p_cols = [v / v.norm() for v in p_cols] return M.hstack(*p_cols), M.diag(*diag) def _fuzzy_positive_definite(M): positive_diagonals = M._has_positive_diagonals() if positive_diagonals is False: return False if positive_diagonals and M.is_strongly_diagonally_dominant: return True return None def _fuzzy_positive_semidefinite(M): nonnegative_diagonals = M._has_nonnegative_diagonals() if nonnegative_diagonals is False: return False if nonnegative_diagonals and M.is_weakly_diagonally_dominant: return True return None def _is_positive_definite(M): if not M.is_hermitian: if not M.is_square: return False M = M + M.H fuzzy = _fuzzy_positive_definite(M) if fuzzy is not None: return fuzzy return _is_positive_definite_GE(M) def _is_positive_semidefinite(M): if not M.is_hermitian: if not M.is_square: return False M = M + M.H fuzzy = _fuzzy_positive_semidefinite(M) if fuzzy is not None: return fuzzy return _is_positive_semidefinite_cholesky(M) def _is_negative_definite(M): return _is_positive_definite(-M) def _is_negative_semidefinite(M): return _is_positive_semidefinite(-M) def _is_indefinite(M): if M.is_hermitian: eigen = M.eigenvals() args1 = [x.is_positive for x in eigen.keys()] any_positive = fuzzy_or(args1) args2 = [x.is_negative for x in eigen.keys()] any_negative = fuzzy_or(args2) return fuzzy_and([any_positive, any_negative]) elif M.is_square: return (M + M.H).is_indefinite return False def _is_positive_definite_GE(M): """A division-free gaussian elimination method for testing positive-definiteness.""" M = M.as_mutable() size = M.rows for i in range(size): is_positive = M[i, i].is_positive if is_positive is not True: return is_positive for j in range(i+1, size): M[j, i+1:] = M[i, i] * M[j, i+1:] - M[j, i] * M[i, i+1:] return True def _is_positive_semidefinite_cholesky(M): """Uses Cholesky factorization with complete pivoting References ========== .. [1] http://eprints.ma.man.ac.uk/1199/1/covered/MIMS_ep2008_116.pdf .. [2] https://www.value-at-risk.net/cholesky-factorization/ """ M = M.as_mutable() for k in range(M.rows): diags = [M[i, i] for i in range(k, M.rows)] pivot, pivot_val, nonzero, _ = _find_reasonable_pivot(diags) if nonzero: return None if pivot is None: for i in range(k+1, M.rows): for j in range(k, M.cols): iszero = M[i, j].is_zero if iszero is None: return None elif iszero is False: return False return True if M[k, k].is_negative or pivot_val.is_negative: return False elif not (M[k, k].is_nonnegative and pivot_val.is_nonnegative): return None if pivot > 0: M.col_swap(k, k+pivot) M.row_swap(k, k+pivot) M[k, k] = sqrt(M[k, k]) M[k, k+1:] /= M[k, k] M[k+1:, k+1:] -= M[k, k+1:].H * M[k, k+1:] return M[-1, -1].is_nonnegative _doc_positive_definite = \ r"""Finds out the definiteness of a matrix. Explanation =========== A square real matrix $A$ is: - A positive definite matrix if $x^T A x > 0$ for all non-zero real vectors $x$. - A positive semidefinite matrix if $x^T A x \geq 0$ for all non-zero real vectors $x$. - A negative definite matrix if $x^T A x < 0$ for all non-zero real vectors $x$. - A negative semidefinite matrix if $x^T A x \leq 0$ for all non-zero real vectors $x$. - An indefinite matrix if there exists non-zero real vectors $x, y$ with $x^T A x > 0 > y^T A y$. A square complex matrix $A$ is: - A positive definite matrix if $\text{re}(x^H A x) > 0$ for all non-zero complex vectors $x$. - A positive semidefinite matrix if $\text{re}(x^H A x) \geq 0$ for all non-zero complex vectors $x$. - A negative definite matrix if $\text{re}(x^H A x) < 0$ for all non-zero complex vectors $x$. - A negative semidefinite matrix if $\text{re}(x^H A x) \leq 0$ for all non-zero complex vectors $x$. - An indefinite matrix if there exists non-zero complex vectors $x, y$ with $\text{re}(x^H A x) > 0 > \text{re}(y^H A y)$. A matrix need not be symmetric or hermitian to be positive definite. - A real non-symmetric matrix is positive definite if and only if $\frac{A + A^T}{2}$ is positive definite. - A complex non-hermitian matrix is positive definite if and only if $\frac{A + A^H}{2}$ is positive definite. And this extension can apply for all the definitions above. However, for complex cases, you can restrict the definition of $\text{re}(x^H A x) > 0$ to $x^H A x > 0$ and require the matrix to be hermitian. But we do not present this restriction for computation because you can check ``M.is_hermitian`` independently with this and use the same procedure. Examples ======== An example of symmetric positive definite matrix: .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import Matrix, symbols >>> from sympy.plotting import plot3d >>> a, b = symbols('a b') >>> x = Matrix([a, b]) >>> A = Matrix([[1, 0], [0, 1]]) >>> A.is_positive_definite True >>> A.is_positive_semidefinite True >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) An example of symmetric positive semidefinite matrix: .. plot:: :context: close-figs :format: doctest :include-source: True >>> A = Matrix([[1, -1], [-1, 1]]) >>> A.is_positive_definite False >>> A.is_positive_semidefinite True >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) An example of symmetric negative definite matrix: .. plot:: :context: close-figs :format: doctest :include-source: True >>> A = Matrix([[-1, 0], [0, -1]]) >>> A.is_negative_definite True >>> A.is_negative_semidefinite True >>> A.is_indefinite False >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) An example of symmetric indefinite matrix: .. plot:: :context: close-figs :format: doctest :include-source: True >>> A = Matrix([[1, 2], [2, -1]]) >>> A.is_indefinite True >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) An example of non-symmetric positive definite matrix. .. plot:: :context: close-figs :format: doctest :include-source: True >>> A = Matrix([[1, 2], [-2, 1]]) >>> A.is_positive_definite True >>> A.is_positive_semidefinite True >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) Notes ===== Although some people trivialize the definition of positive definite matrices only for symmetric or hermitian matrices, this restriction is not correct because it does not classify all instances of positive definite matrices from the definition $x^T A x > 0$ or $\text{re}(x^H A x) > 0$. For instance, ``Matrix([[1, 2], [-2, 1]])`` presented in the example above is an example of real positive definite matrix that is not symmetric. However, since the following formula holds true; .. math:: \text{re}(x^H A x) > 0 \iff \text{re}(x^H \frac{A + A^H}{2} x) > 0 We can classify all positive definite matrices that may or may not be symmetric or hermitian by transforming the matrix to $\frac{A + A^T}{2}$ or $\frac{A + A^H}{2}$ (which is guaranteed to be always real symmetric or complex hermitian) and we can defer most of the studies to symmetric or hermitian positive definite matrices. But it is a different problem for the existance of Cholesky decomposition. Because even though a non symmetric or a non hermitian matrix can be positive definite, Cholesky or LDL decomposition does not exist because the decompositions require the matrix to be symmetric or hermitian. References ========== .. [1] https://en.wikipedia.org/wiki/Definiteness_of_a_matrix#Eigenvalues .. [2] http://mathworld.wolfram.com/PositiveDefiniteMatrix.html .. [3] Johnson, C. R. "Positive Definite Matrices." Amer. Math. Monthly 77, 259-264 1970. """ _is_positive_definite.__doc__ = _doc_positive_definite _is_positive_semidefinite.__doc__ = _doc_positive_definite _is_negative_definite.__doc__ = _doc_positive_definite _is_negative_semidefinite.__doc__ = _doc_positive_definite _is_indefinite.__doc__ = _doc_positive_definite def _jordan_form(M, calc_transform=True, *, chop=False): """Return $(P, J)$ where $J$ is a Jordan block matrix and $P$ is a matrix such that $M = P J P^{-1}$ Parameters ========== calc_transform : bool If ``False``, then only $J$ is returned. chop : bool All matrices are converted to exact types when computing eigenvalues and eigenvectors. As a result, there may be approximation errors. If ``chop==True``, these errors will be truncated. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[ 6, 5, -2, -3], [-3, -1, 3, 3], [ 2, 1, -2, -3], [-1, 1, 5, 5]]) >>> P, J = M.jordan_form() >>> J Matrix([ [2, 1, 0, 0], [0, 2, 0, 0], [0, 0, 2, 1], [0, 0, 0, 2]]) See Also ======== jordan_block """ if not M.is_square: raise NonSquareMatrixError("Only square matrices have Jordan forms") mat = M has_floats = M.has(Float) if has_floats: try: max_prec = max(term._prec for term in M.values() if isinstance(term, Float)) except ValueError: # if no term in the matrix is explicitly a Float calling max() # will throw a error so setting max_prec to default value of 53 max_prec = 53 # setting minimum max_dps to 15 to prevent loss of precision in # matrix containing non evaluated expressions max_dps = max(prec_to_dps(max_prec), 15) def restore_floats(*args): """If ``has_floats`` is `True`, cast all ``args`` as matrices of floats.""" if has_floats: args = [m.evalf(n=max_dps, chop=chop) for m in args] if len(args) == 1: return args[0] return args # cache calculations for some speedup mat_cache = {} def eig_mat(val, pow): """Cache computations of ``(M - val*I)**pow`` for quick retrieval""" if (val, pow) in mat_cache: return mat_cache[(val, pow)] if (val, pow - 1) in mat_cache: mat_cache[(val, pow)] = mat_cache[(val, pow - 1)].multiply( mat_cache[(val, 1)], dotprodsimp=None) else: mat_cache[(val, pow)] = (mat - val*M.eye(M.rows)).pow(pow) return mat_cache[(val, pow)] # helper functions def nullity_chain(val, algebraic_multiplicity): """Calculate the sequence [0, nullity(E), nullity(E**2), ...] until it is constant where ``E = M - val*I``""" # mat.rank() is faster than computing the null space, # so use the rank-nullity theorem cols = M.cols ret = [0] nullity = cols - eig_mat(val, 1).rank() i = 2 while nullity != ret[-1]: ret.append(nullity) if nullity == algebraic_multiplicity: break nullity = cols - eig_mat(val, i).rank() i += 1 # Due to issues like #7146 and #15872, SymPy sometimes # gives the wrong rank. In this case, raise an error # instead of returning an incorrect matrix if nullity < ret[-1] or nullity > algebraic_multiplicity: raise MatrixError( "SymPy had encountered an inconsistent " "result while computing Jordan block: " "{}".format(M)) return ret def blocks_from_nullity_chain(d): """Return a list of the size of each Jordan block. If d_n is the nullity of E**n, then the number of Jordan blocks of size n is 2*d_n - d_(n-1) - d_(n+1)""" # d[0] is always the number of columns, so skip past it mid = [2*d[n] - d[n - 1] - d[n + 1] for n in range(1, len(d) - 1)] # d is assumed to plateau with "d[ len(d) ] == d[-1]", so # 2*d_n - d_(n-1) - d_(n+1) == d_n - d_(n-1) end = [d[-1] - d[-2]] if len(d) > 1 else [d[0]] return mid + end def pick_vec(small_basis, big_basis): """Picks a vector from big_basis that isn't in the subspace spanned by small_basis""" if len(small_basis) == 0: return big_basis[0] for v in big_basis: _, pivots = M.hstack(*(small_basis + [v])).echelon_form( with_pivots=True) if pivots[-1] == len(small_basis): return v # roots doesn't like Floats, so replace them with Rationals if has_floats: from sympy.simplify import nsimplify mat = mat.applyfunc(lambda x: nsimplify(x, rational=True)) # first calculate the jordan block structure eigs = mat.eigenvals() # Make sure that we have all roots in radical form for x in eigs: if x.has(CRootOf): raise MatrixError( "Jordan normal form is not implemented if the matrix have " "eigenvalues in CRootOf form") # most matrices have distinct eigenvalues # and so are diagonalizable. In this case, don't # do extra work! if len(eigs.keys()) == mat.cols: blocks = list(sorted(eigs.keys(), key=default_sort_key)) jordan_mat = mat.diag(*blocks) if not calc_transform: return restore_floats(jordan_mat) jordan_basis = [eig_mat(eig, 1).nullspace()[0] for eig in blocks] basis_mat = mat.hstack(*jordan_basis) return restore_floats(basis_mat, jordan_mat) block_structure = [] for eig in sorted(eigs.keys(), key=default_sort_key): algebraic_multiplicity = eigs[eig] chain = nullity_chain(eig, algebraic_multiplicity) block_sizes = blocks_from_nullity_chain(chain) # if block_sizes = = [a, b, c, ...], then the number of # Jordan blocks of size 1 is a, of size 2 is b, etc. # create an array that has (eig, block_size) with one # entry for each block size_nums = [(i+1, num) for i, num in enumerate(block_sizes)] # we expect larger Jordan blocks to come earlier size_nums.reverse() block_structure.extend( [(eig, size) for size, num in size_nums for _ in range(num)]) jordan_form_size = sum(size for eig, size in block_structure) if jordan_form_size != M.rows: raise MatrixError( "SymPy had encountered an inconsistent result while " "computing Jordan block. : {}".format(M)) blocks = (mat.jordan_block(size=size, eigenvalue=eig) for eig, size in block_structure) jordan_mat = mat.diag(*blocks) if not calc_transform: return restore_floats(jordan_mat) # For each generalized eigenspace, calculate a basis. # We start by looking for a vector in null( (A - eig*I)**n ) # which isn't in null( (A - eig*I)**(n-1) ) where n is # the size of the Jordan block # # Ideally we'd just loop through block_structure and # compute each generalized eigenspace. However, this # causes a lot of unneeded computation. Instead, we # go through the eigenvalues separately, since we know # their generalized eigenspaces must have bases that # are linearly independent. jordan_basis = [] for eig in sorted(eigs.keys(), key=default_sort_key): eig_basis = [] for block_eig, size in block_structure: if block_eig != eig: continue null_big = (eig_mat(eig, size)).nullspace() null_small = (eig_mat(eig, size - 1)).nullspace() # we want to pick something that is in the big basis # and not the small, but also something that is independent # of any other generalized eigenvectors from a different # generalized eigenspace sharing the same eigenvalue. vec = pick_vec(null_small + eig_basis, null_big) new_vecs = [eig_mat(eig, i).multiply(vec, dotprodsimp=None) for i in range(size)] eig_basis.extend(new_vecs) jordan_basis.extend(reversed(new_vecs)) basis_mat = mat.hstack(*jordan_basis) return restore_floats(basis_mat, jordan_mat) def _left_eigenvects(M, **flags): """Returns left eigenvectors and eigenvalues. This function returns the list of triples (eigenval, multiplicity, basis) for the left eigenvectors. Options are the same as for eigenvects(), i.e. the ``**flags`` arguments gets passed directly to eigenvects(). Examples ======== >>> from sympy import Matrix >>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) >>> M.eigenvects() [(-1, 1, [Matrix([ [-1], [ 1], [ 0]])]), (0, 1, [Matrix([ [ 0], [-1], [ 1]])]), (2, 1, [Matrix([ [2/3], [1/3], [ 1]])])] >>> M.left_eigenvects() [(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2, 1, [Matrix([[1, 1, 1]])])] """ eigs = M.transpose().eigenvects(**flags) return [(val, mult, [l.transpose() for l in basis]) for val, mult, basis in eigs] def _singular_values(M): """Compute the singular values of a Matrix Examples ======== >>> from sympy import Matrix, Symbol >>> x = Symbol('x', real=True) >>> M = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]]) >>> M.singular_values() [sqrt(x**2 + 1), 1, 0] See Also ======== condition_number """ if M.rows >= M.cols: valmultpairs = M.H.multiply(M).eigenvals() else: valmultpairs = M.multiply(M.H).eigenvals() # Expands result from eigenvals into a simple list vals = [] for k, v in valmultpairs.items(): vals += [sqrt(k)] * v # dangerous! same k in several spots! # Pad with zeros if singular values are computed in reverse way, # to give consistent format. if len(vals) < M.cols: vals += [M.zero] * (M.cols - len(vals)) # sort them in descending order vals.sort(reverse=True, key=default_sort_key) return vals
6bfabbdad75c18d99a1a66a577a58d0ae44dcde84db9f7f215e989ed62d7d093
from collections import defaultdict from operator import index as index_ from sympy.core.expr import Expr from sympy.core.kind import Kind, NumberKind, UndefinedKind from sympy.core.numbers import Integer, Rational from sympy.core.sympify import _sympify, SympifyError from sympy.core.singleton import S from sympy.polys.domains import ZZ, QQ, EXRAW from sympy.polys.matrices import DomainMatrix from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from sympy.utilities.misc import filldedent from .common import classof from .matrices import MatrixBase, MatrixKind, ShapeError class RepMatrix(MatrixBase): """Matrix implementation based on DomainMatrix as an internal representation. The RepMatrix class is a superclass for Matrix, ImmutableMatrix, SparseMatrix and ImmutableSparseMatrix which are the main usable matrix classes in SymPy. Most methods on this class are simply forwarded to DomainMatrix. """ # # MatrixBase is the common superclass for all of the usable explicit matrix # classes in SymPy. The idea is that MatrixBase is an abstract class though # and that subclasses will implement the lower-level methods. # # RepMatrix is a subclass of MatrixBase that uses DomainMatrix as an # internal representation and delegates lower-level methods to # DomainMatrix. All of SymPy's standard explicit matrix classes subclass # RepMatrix and so use DomainMatrix internally. # # A RepMatrix uses an internal DomainMatrix with the domain set to ZZ, QQ # or EXRAW. The EXRAW domain is equivalent to the previous implementation # of Matrix that used Expr for the elements. The ZZ and QQ domains are used # when applicable just because they are compatible with the previous # implementation but are much more efficient. Other domains such as QQ[x] # are not used because they differ from Expr in some way (e.g. automatic # expansion of powers and products). # _rep: DomainMatrix def __eq__(self, other): # Skip sympify for mutable matrices... if not isinstance(other, RepMatrix): try: other = _sympify(other) except SympifyError: return NotImplemented if not isinstance(other, RepMatrix): return NotImplemented return self._rep.unify_eq(other._rep) @classmethod def _unify_element_sympy(cls, rep, element): domain = rep.domain element = _sympify(element) if domain != EXRAW: # The domain can only be ZZ, QQ or EXRAW if element.is_Integer: new_domain = domain elif element.is_Rational: new_domain = QQ else: new_domain = EXRAW # XXX: This converts the domain for all elements in the matrix # which can be slow. This happens e.g. if __setitem__ changes one # element to something that does not fit in the domain if new_domain != domain: rep = rep.convert_to(new_domain) domain = new_domain if domain != EXRAW: element = new_domain.from_sympy(element) if domain == EXRAW and not isinstance(element, Expr): sympy_deprecation_warning( """ non-Expr objects in a Matrix is deprecated. Matrix represents a mathematical matrix. To represent a container of non-numeric entities, Use a list of lists, TableForm, NumPy array, or some other data structure instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-non-expr-in-matrix", stacklevel=4, ) return rep, element @classmethod def _dod_to_DomainMatrix(cls, rows, cols, dod, types): if not all(issubclass(typ, Expr) for typ in types): sympy_deprecation_warning( """ non-Expr objects in a Matrix is deprecated. Matrix represents a mathematical matrix. To represent a container of non-numeric entities, Use a list of lists, TableForm, NumPy array, or some other data structure instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-non-expr-in-matrix", stacklevel=6, ) 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 @classmethod def _flat_list_to_DomainMatrix(cls, rows, cols, flat_list): elements_dod = defaultdict(dict) for n, element in enumerate(flat_list): if element != 0: i, j = divmod(n, cols) elements_dod[i][j] = element types = set(map(type, flat_list)) rep = cls._dod_to_DomainMatrix(rows, cols, elements_dod, types) return rep @classmethod def _smat_to_DomainMatrix(cls, rows, cols, smat): elements_dod = defaultdict(dict) for (i, j), element in smat.items(): if element != 0: elements_dod[i][j] = element types = set(map(type, smat.values())) rep = cls._dod_to_DomainMatrix(rows, cols, elements_dod, types) return rep def flat(self): return self._rep.to_sympy().to_list_flat() def _eval_tolist(self): return self._rep.to_sympy().to_list() def _eval_todok(self): return self._rep.to_sympy().to_dok() def _eval_values(self): return list(self.todok().values()) def copy(self): return self._fromrep(self._rep.copy()) @property def kind(self) -> MatrixKind: domain = self._rep.domain element_kind: Kind if domain in (ZZ, QQ): element_kind = NumberKind elif domain == EXRAW: kinds = set(e.kind for e in self.values()) if len(kinds) == 1: [element_kind] = kinds else: element_kind = UndefinedKind else: # pragma: no cover raise RuntimeError("Domain should only be ZZ, QQ or EXRAW") return MatrixKind(element_kind) def _eval_has(self, *patterns): # if the matrix has any zeros, see if S.Zero # has the pattern. If _smat is full length, # the matrix has no zeros. zhas = False dok = self.todok() if len(dok) != self.rows*self.cols: zhas = S.Zero.has(*patterns) return zhas or any(value.has(*patterns) for value in dok.values()) def _eval_is_Identity(self): if not all(self[i, i] == 1 for i in range(self.rows)): return False return len(self.todok()) == self.rows def _eval_is_symmetric(self, simpfunc): diff = (self - self.T).applyfunc(simpfunc) return len(diff.values()) == 0 def _eval_transpose(self): """Returns the transposed SparseMatrix of this SparseMatrix. Examples ======== >>> from sympy import SparseMatrix >>> a = SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.T Matrix([ [1, 3], [2, 4]]) """ return self._fromrep(self._rep.transpose()) def _eval_col_join(self, other): return self._fromrep(self._rep.vstack(other._rep)) def _eval_row_join(self, other): return self._fromrep(self._rep.hstack(other._rep)) def _eval_extract(self, rowsList, colsList): return self._fromrep(self._rep.extract(rowsList, colsList)) def __getitem__(self, key): return _getitem_RepMatrix(self, key) @classmethod def _eval_zeros(cls, rows, cols): rep = DomainMatrix.zeros((rows, cols), ZZ) return cls._fromrep(rep) @classmethod def _eval_eye(cls, rows, cols): rep = DomainMatrix.eye((rows, cols), ZZ) return cls._fromrep(rep) def _eval_add(self, other): return classof(self, other)._fromrep(self._rep + other._rep) def _eval_matrix_mul(self, other): return classof(self, other)._fromrep(self._rep * other._rep) def _eval_matrix_mul_elementwise(self, other): selfrep, otherrep = self._rep.unify(other._rep) newrep = selfrep.mul_elementwise(otherrep) return classof(self, other)._fromrep(newrep) def _eval_scalar_mul(self, other): rep, other = self._unify_element_sympy(self._rep, other) return self._fromrep(rep.scalarmul(other)) def _eval_scalar_rmul(self, other): rep, other = self._unify_element_sympy(self._rep, other) return self._fromrep(rep.rscalarmul(other)) def _eval_Abs(self): return self._fromrep(self._rep.applyfunc(abs)) def _eval_conjugate(self): rep = self._rep domain = rep.domain if domain in (ZZ, QQ): return self.copy() else: return self._fromrep(rep.applyfunc(lambda e: e.conjugate())) def equals(self, other, failing_expression=False): """Applies ``equals`` to corresponding elements of the matrices, trying to prove that the elements are equivalent, returning True if they are, False if any pair is not, and None (or the first failing expression if failing_expression is True) if it cannot be decided if the expressions are equivalent or not. This is, in general, an expensive operation. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x >>> A = Matrix([x*(x - 1), 0]) >>> B = Matrix([x**2 - x, 0]) >>> A == B False >>> A.simplify() == B.simplify() True >>> A.equals(B) True >>> A.equals(2) False See Also ======== sympy.core.expr.Expr.equals """ if self.shape != getattr(other, 'shape', None): return False rv = True for i in range(self.rows): for j in range(self.cols): ans = self[i, j].equals(other[i, j], failing_expression) if ans is False: return False elif ans is not True and rv is True: rv = ans return rv class MutableRepMatrix(RepMatrix): """Mutable matrix based on DomainMatrix as the internal representation""" # # MutableRepMatrix is a subclass of RepMatrix that adds/overrides methods # to make the instances mutable. MutableRepMatrix is a superclass for both # MutableDenseMatrix and MutableSparseMatrix. # is_zero = False def __new__(cls, *args, **kwargs): return cls._new(*args, **kwargs) @classmethod def _new(cls, *args, copy=True, **kwargs): if copy is False: # The input was rows, cols, [list]. # It should be used directly without creating a copy. if len(args) != 3: raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") rows, cols, flat_list = args else: rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) flat_list = list(flat_list) # create a shallow copy rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list) return cls._fromrep(rep) @classmethod def _fromrep(cls, rep): obj = super().__new__(cls) obj.rows, obj.cols = rep.shape obj._rep = rep return obj def copy(self): return self._fromrep(self._rep.copy()) def as_mutable(self): return self.copy() def __setitem__(self, key, value): """ Examples ======== >>> from sympy import Matrix, I, zeros, ones >>> m = Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m[1, 0] = 9 >>> m Matrix([ [1, 2 + I], [9, 4]]) >>> m[1, 0] = [[0, 1]] To replace row r you assign to position r*m where m is the number of columns: >>> M = zeros(4) >>> m = M.cols >>> M[3*m] = ones(1, m)*2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]]) And to replace column c you can assign to position c: >>> M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]]) """ rv = self._setitem(key, value) if rv is not None: i, j, value = rv self._rep, value = self._unify_element_sympy(self._rep, value) self._rep.rep.setitem(i, j, value) def _eval_col_del(self, col): self._rep = DomainMatrix.hstack(self._rep[:,:col], self._rep[:,col+1:]) self.cols -= 1 def _eval_row_del(self, row): self._rep = DomainMatrix.vstack(self._rep[:row,:], self._rep[row+1:, :]) self.rows -= 1 def _eval_col_insert(self, col, other): other = self._new(other) return self.hstack(self[:,:col], other, self[:,col:]) def _eval_row_insert(self, row, other): other = self._new(other) return self.vstack(self[:row,:], other, self[row:,:]) def col_op(self, j, f): """In-place operation on col j using two-arg functor whose args are interpreted as (self[i, j], i). Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M Matrix([ [1, 2, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== col row_op """ for i in range(self.rows): self[i, j] = f(self[i, j], i) def col_swap(self, i, j): """Swap the two given columns of the matrix in-place. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 0], [1, 0]]) >>> M Matrix([ [1, 0], [1, 0]]) >>> M.col_swap(0, 1) >>> M Matrix([ [0, 1], [0, 1]]) See Also ======== col row_swap """ for k in range(0, self.rows): self[k, i], self[k, j] = self[k, j], self[k, i] def row_op(self, i, f): """In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], j)``. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) See Also ======== row zip_row_op col_op """ for j in range(self.cols): self[i, j] = f(self[i, j], j) def row_swap(self, i, j): """Swap the two given rows of the matrix in-place. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[0, 1], [1, 0]]) >>> M Matrix([ [0, 1], [1, 0]]) >>> M.row_swap(0, 1) >>> M Matrix([ [1, 0], [0, 1]]) See Also ======== row col_swap """ for k in range(0, self.cols): self[i, k], self[j, k] = self[j, k], self[i, k] def zip_row_op(self, i, k, f): """In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], self[k, j])``. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) See Also ======== row row_op col_op """ for j in range(self.cols): self[i, j] = f(self[i, j], self[k, j]) def copyin_list(self, key, value): """Copy in elements from a list. Parameters ========== key : slice The section of this matrix to replace. value : iterable The iterable to copy values from. Examples ======== >>> from sympy import eye >>> I = eye(3) >>> I[:2, 0] = [1, 2] # col >>> I Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) >>> I[1, :2] = [[3, 4]] >>> I Matrix([ [1, 0, 0], [3, 4, 0], [0, 0, 1]]) See Also ======== copyin_matrix """ if not is_sequence(value): raise TypeError("`value` must be an ordered iterable, not %s." % type(value)) return self.copyin_matrix(key, type(self)(value)) def copyin_matrix(self, key, value): """Copy in values from a matrix into the given bounds. Parameters ========== key : slice The section of this matrix to replace. value : Matrix The matrix to copy values from. Examples ======== >>> from sympy import Matrix, eye >>> M = Matrix([[0, 1], [2, 3], [4, 5]]) >>> I = eye(3) >>> I[:3, :2] = M >>> I Matrix([ [0, 1, 0], [2, 3, 0], [4, 5, 1]]) >>> I[0, 1] = M >>> I Matrix([ [0, 0, 1], [2, 2, 3], [4, 4, 5]]) See Also ======== copyin_list """ rlo, rhi, clo, chi = self.key2bounds(key) shape = value.shape dr, dc = rhi - rlo, chi - clo if shape != (dr, dc): raise ShapeError(filldedent("The Matrix `value` doesn't have the " "same dimensions " "as the in sub-Matrix given by `key`.")) for i in range(value.rows): for j in range(value.cols): self[i + rlo, j + clo] = value[i, j] def fill(self, value): """Fill self with the given value. Notes ===== Unless many values are going to be deleted (i.e. set to zero) this will create a matrix that is slower than a dense matrix in operations. Examples ======== >>> from sympy import SparseMatrix >>> M = SparseMatrix.zeros(3); M Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> M.fill(1); M Matrix([ [1, 1, 1], [1, 1, 1], [1, 1, 1]]) See Also ======== zeros ones """ value = _sympify(value) if not value: self._rep = DomainMatrix.zeros(self.shape, EXRAW) else: elements_dod = {i: {j: value for j in range(self.cols)} for i in range(self.rows)} self._rep = DomainMatrix(elements_dod, self.shape, EXRAW) def _getitem_RepMatrix(self, key): """Return portion of self defined by key. If the key involves a slice then a list will be returned (if key is a single slice) or a matrix (if key was a tuple involving a slice). Examples ======== >>> from sympy import Matrix, I >>> m = Matrix([ ... [1, 2 + I], ... [3, 4 ]]) If the key is a tuple that does not involve a slice then that element is returned: >>> m[1, 0] 3 When a tuple key involves a slice, a matrix is returned. Here, the first column is selected (all rows, column 0): >>> m[:, 0] Matrix([ [1], [3]]) If the slice is not a tuple then it selects from the underlying list of elements that are arranged in row order and a list is returned if a slice is involved: >>> m[0] 1 >>> m[::2] [1, 3] """ if isinstance(key, tuple): i, j = key try: return self._rep.getitem_sympy(index_(i), index_(j)) except (TypeError, IndexError): if (isinstance(i, Expr) and not i.is_number) or (isinstance(j, Expr) and not j.is_number): if ((j < 0) is True) or ((j >= self.shape[1]) is True) or\ ((i < 0) is True) or ((i >= self.shape[0]) is True): raise ValueError("index out of boundary") from sympy.matrices.expressions.matexpr import MatrixElement return MatrixElement(self, i, j) if isinstance(i, slice): i = range(self.rows)[i] elif is_sequence(i): pass else: i = [i] if isinstance(j, slice): j = range(self.cols)[j] elif is_sequence(j): pass else: j = [j] return self.extract(i, j) else: # Index/slice like a flattened list rows, cols = self.shape # Raise the appropriate exception: if not rows * cols: return [][key] rep = self._rep.rep domain = rep.domain is_slice = isinstance(key, slice) if is_slice: values = [rep.getitem(*divmod(n, cols)) for n in range(rows * cols)[key]] else: values = [rep.getitem(*divmod(index_(key), cols))] if domain != EXRAW: to_sympy = domain.to_sympy values = [to_sympy(val) for val in values] if is_slice: return values else: return values[0]
b8ba38aa73f4c6f15c168e6185fea0ee91d21e245b710d404c32b0181c56ec21
from .utilities import _iszero def _columnspace(M, simplify=False): """Returns a list of vectors (Matrix objects) that span columnspace of ``M`` Examples ======== >>> from sympy import Matrix >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) >>> M Matrix([ [ 1, 3, 0], [-2, -6, 0], [ 3, 9, 6]]) >>> M.columnspace() [Matrix([ [ 1], [-2], [ 3]]), Matrix([ [0], [0], [6]])] See Also ======== nullspace rowspace """ reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True) return [M.col(i) for i in pivots] def _nullspace(M, simplify=False, iszerofunc=_iszero): """Returns list of vectors (Matrix objects) that span nullspace of ``M`` Examples ======== >>> from sympy import Matrix >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) >>> M Matrix([ [ 1, 3, 0], [-2, -6, 0], [ 3, 9, 6]]) >>> M.nullspace() [Matrix([ [-3], [ 1], [ 0]])] See Also ======== columnspace rowspace """ reduced, pivots = M.rref(iszerofunc=iszerofunc, simplify=simplify) free_vars = [i for i in range(M.cols) if i not in pivots] basis = [] for free_var in free_vars: # for each free variable, we will set it to 1 and all others # to 0. Then, we will use back substitution to solve the system vec = [M.zero] * M.cols vec[free_var] = M.one for piv_row, piv_col in enumerate(pivots): vec[piv_col] -= reduced[piv_row, free_var] basis.append(vec) return [M._new(M.cols, 1, b) for b in basis] def _rowspace(M, simplify=False): """Returns a list of vectors that span the row space of ``M``. Examples ======== >>> from sympy import Matrix >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) >>> M Matrix([ [ 1, 3, 0], [-2, -6, 0], [ 3, 9, 6]]) >>> M.rowspace() [Matrix([[1, 3, 0]]), Matrix([[0, 0, 6]])] """ reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True) return [reduced.row(i) for i in range(len(pivots))] def _orthogonalize(cls, *vecs, normalize=False, rankcheck=False): """Apply the Gram-Schmidt orthogonalization procedure to vectors supplied in ``vecs``. Parameters ========== vecs vectors to be made orthogonal normalize : bool If ``True``, return an orthonormal basis. rankcheck : bool If ``True``, the computation does not stop when encountering linearly dependent vectors. If ``False``, it will raise ``ValueError`` when any zero or linearly dependent vectors are found. Returns ======= list List of orthogonal (or orthonormal) basis vectors. Examples ======== >>> from sympy import I, Matrix >>> v = [Matrix([1, I]), Matrix([1, -I])] >>> Matrix.orthogonalize(*v) [Matrix([ [1], [I]]), Matrix([ [ 1], [-I]])] See Also ======== MatrixBase.QRdecomposition References ========== .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process """ from .decompositions import _QRdecomposition_optional if not vecs: return [] all_row_vecs = (vecs[0].rows == 1) vecs = [x.vec() for x in vecs] M = cls.hstack(*vecs) Q, R = _QRdecomposition_optional(M, normalize=normalize) if rankcheck and Q.cols < len(vecs): raise ValueError("GramSchmidt: vector set not linearly independent") ret = [] for i in range(Q.cols): if all_row_vecs: col = cls(Q[:, i].T) else: col = cls(Q[:, i]) ret.append(col) return ret
bc81a74982a78043c4b7a57ee9b78339700e63dba00cb27c7d73b1e47f4925c9
from sympy.core.decorators import _sympifyit from sympy.core.parameters import global_parameters from sympy.core.logic import fuzzy_bool from sympy.core.singleton import S from sympy.core.sympify import _sympify from .sets import Set, FiniteSet, SetKind class PowerSet(Set): r"""A symbolic object representing a power set. Parameters ========== arg : Set The set to take power of. evaluate : bool The flag to control evaluation. If the evaluation is disabled for finite sets, it can take advantage of using subset test as a membership test. Notes ===== Power set `\mathcal{P}(S)` is defined as a set containing all the subsets of `S`. If the set `S` is a finite set, its power set would have `2^{\left| S \right|}` elements, where `\left| S \right|` denotes the cardinality of `S`. Examples ======== >>> from sympy import PowerSet, S, FiniteSet A power set of a finite set: >>> PowerSet(FiniteSet(1, 2, 3)) PowerSet({1, 2, 3}) A power set of an empty set: >>> PowerSet(S.EmptySet) PowerSet(EmptySet) >>> PowerSet(PowerSet(S.EmptySet)) PowerSet(PowerSet(EmptySet)) A power set of an infinite set: >>> PowerSet(S.Reals) PowerSet(Reals) Evaluating the power set of a finite set to its explicit form: >>> PowerSet(FiniteSet(1, 2, 3)).rewrite(FiniteSet) FiniteSet(EmptySet, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}) References ========== .. [1] https://en.wikipedia.org/wiki/Power_set .. [2] https://en.wikipedia.org/wiki/Axiom_of_power_set """ def __new__(cls, arg, evaluate=None): if evaluate is None: evaluate=global_parameters.evaluate arg = _sympify(arg) if not isinstance(arg, Set): raise ValueError('{} must be a set.'.format(arg)) return super().__new__(cls, arg) @property def arg(self): return self.args[0] def _eval_rewrite_as_FiniteSet(self, *args, **kwargs): arg = self.arg if arg.is_FiniteSet: return arg.powerset() return None @_sympifyit('other', NotImplemented) def _contains(self, other): if not isinstance(other, Set): return None return fuzzy_bool(self.arg.is_superset(other)) def _eval_is_subset(self, other): if isinstance(other, PowerSet): return self.arg.is_subset(other.arg) def __len__(self): return 2 ** len(self.arg) def __iter__(self): found = [S.EmptySet] yield S.EmptySet for x in self.arg: temp = [] x = FiniteSet(x) for y in found: new = x + y yield new temp.append(new) found.extend(temp) @property def kind(self): return SetKind(self.arg.kind)
cac57720c6d513ed73837ce1b0cf3ef8fbcdd71439f4b0c0d481c78a7c8e3fba
from functools import reduce from itertools import product from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.logic import fuzzy_not, fuzzy_or, fuzzy_and from sympy.core.mod import Mod from sympy.core.numbers import oo, igcd, Rational from sympy.core.relational import Eq, is_eq from sympy.core.kind import NumberKind from sympy.core.singleton import Singleton, S from sympy.core.symbol import Dummy, symbols, Symbol from sympy.core.sympify import _sympify, sympify, _sympy_converter from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.trigonometric import sin, cos from sympy.logic.boolalg import And, Or from .sets import Set, Interval, Union, FiniteSet, ProductSet, SetKind from sympy.utilities.misc import filldedent class Rationals(Set, metaclass=Singleton): """ Represents the rational numbers. This set is also available as the singleton ``S.Rationals``. Examples ======== >>> from sympy import S >>> S.Half in S.Rationals True >>> iterable = iter(S.Rationals) >>> [next(iterable) for i in range(12)] [0, 1, -1, 1/2, 2, -1/2, -2, 1/3, 3, -1/3, -3, 2/3] """ is_iterable = True _inf = S.NegativeInfinity _sup = S.Infinity is_empty = False is_finite_set = False def _contains(self, other): if not isinstance(other, Expr): return False return other.is_rational def __iter__(self): yield S.Zero yield S.One yield S.NegativeOne d = 2 while True: for n in range(d): if igcd(n, d) == 1: yield Rational(n, d) yield Rational(d, n) yield Rational(-n, d) yield Rational(-d, n) d += 1 @property def _boundary(self): return S.Reals def _kind(self): return SetKind(NumberKind) class Naturals(Set, metaclass=Singleton): """ Represents the natural numbers (or counting numbers) which are all positive integers starting from 1. This set is also available as the singleton ``S.Naturals``. Examples ======== >>> from sympy import S, Interval, pprint >>> 5 in S.Naturals True >>> iterable = iter(S.Naturals) >>> next(iterable) 1 >>> next(iterable) 2 >>> next(iterable) 3 >>> pprint(S.Naturals.intersect(Interval(0, 10))) {1, 2, ..., 10} See Also ======== Naturals0 : non-negative integers (i.e. includes 0, too) Integers : also includes negative integers """ is_iterable = True _inf = S.One _sup = S.Infinity is_empty = False is_finite_set = False def _contains(self, other): if not isinstance(other, Expr): return False elif other.is_positive and other.is_integer: return True elif other.is_integer is False or other.is_positive is False: return False def _eval_is_subset(self, other): return Range(1, oo).is_subset(other) def _eval_is_superset(self, other): return Range(1, oo).is_superset(other) def __iter__(self): i = self._inf while True: yield i i = i + 1 @property def _boundary(self): return self def as_relational(self, x): return And(Eq(floor(x), x), x >= self.inf, x < oo) def _kind(self): return SetKind(NumberKind) class Naturals0(Naturals): """Represents the whole numbers which are all the non-negative integers, inclusive of zero. See Also ======== Naturals : positive integers; does not include 0 Integers : also includes the negative integers """ _inf = S.Zero def _contains(self, other): if not isinstance(other, Expr): return S.false elif other.is_integer and other.is_nonnegative: return S.true elif other.is_integer is False or other.is_nonnegative is False: return S.false def _eval_is_subset(self, other): return Range(oo).is_subset(other) def _eval_is_superset(self, other): return Range(oo).is_superset(other) class Integers(Set, metaclass=Singleton): """ Represents all integers: positive, negative and zero. This set is also available as the singleton ``S.Integers``. Examples ======== >>> from sympy import S, Interval, pprint >>> 5 in S.Naturals True >>> iterable = iter(S.Integers) >>> next(iterable) 0 >>> next(iterable) 1 >>> next(iterable) -1 >>> next(iterable) 2 >>> pprint(S.Integers.intersect(Interval(-4, 4))) {-4, -3, ..., 4} See Also ======== Naturals0 : non-negative integers Integers : positive and negative integers and zero """ is_iterable = True is_empty = False is_finite_set = False def _contains(self, other): if not isinstance(other, Expr): return S.false return other.is_integer def __iter__(self): yield S.Zero i = S.One while True: yield i yield -i i = i + 1 @property def _inf(self): return S.NegativeInfinity @property def _sup(self): return S.Infinity @property def _boundary(self): return self def _kind(self): return SetKind(NumberKind) def as_relational(self, x): return And(Eq(floor(x), x), -oo < x, x < oo) def _eval_is_subset(self, other): return Range(-oo, oo).is_subset(other) def _eval_is_superset(self, other): return Range(-oo, oo).is_superset(other) class Reals(Interval, metaclass=Singleton): """ Represents all real numbers from negative infinity to positive infinity, including all integer, rational and irrational numbers. This set is also available as the singleton ``S.Reals``. Examples ======== >>> from sympy import S, Rational, pi, I >>> 5 in S.Reals True >>> Rational(-1, 2) in S.Reals True >>> pi in S.Reals True >>> 3*I in S.Reals False >>> S.Reals.contains(pi) True See Also ======== ComplexRegion """ @property def start(self): return S.NegativeInfinity @property def end(self): return S.Infinity @property def left_open(self): return True @property def right_open(self): return True def __eq__(self, other): return other == Interval(S.NegativeInfinity, S.Infinity) def __hash__(self): return hash(Interval(S.NegativeInfinity, S.Infinity)) class ImageSet(Set): """ Image of a set under a mathematical function. The transformation must be given as a Lambda function which has as many arguments as the elements of the set upon which it operates, e.g. 1 argument when acting on the set of integers or 2 arguments when acting on a complex region. This function is not normally called directly, but is called from ``imageset``. Examples ======== >>> from sympy import Symbol, S, pi, Dummy, Lambda >>> from sympy import FiniteSet, ImageSet, Interval >>> x = Symbol('x') >>> N = S.Naturals >>> squares = ImageSet(Lambda(x, x**2), N) # {x**2 for x in N} >>> 4 in squares True >>> 5 in squares False >>> FiniteSet(0, 1, 2, 3, 4, 5, 6, 7, 9, 10).intersect(squares) {1, 4, 9} >>> square_iterable = iter(squares) >>> for i in range(4): ... next(square_iterable) 1 4 9 16 If you want to get value for `x` = 2, 1/2 etc. (Please check whether the `x` value is in ``base_set`` or not before passing it as args) >>> squares.lamda(2) 4 >>> squares.lamda(S(1)/2) 1/4 >>> n = Dummy('n') >>> solutions = ImageSet(Lambda(n, n*pi), S.Integers) # solutions of sin(x) = 0 >>> dom = Interval(-1, 1) >>> dom.intersect(solutions) {0} See Also ======== sympy.sets.sets.imageset """ def __new__(cls, flambda, *sets): if not isinstance(flambda, Lambda): raise ValueError('First argument must be a Lambda') signature = flambda.signature if len(signature) != len(sets): raise ValueError('Incompatible signature') sets = [_sympify(s) for s in sets] if not all(isinstance(s, Set) for s in sets): raise TypeError("Set arguments to ImageSet should of type Set") if not all(cls._check_sig(sg, st) for sg, st in zip(signature, sets)): raise ValueError("Signature %s does not match sets %s" % (signature, sets)) if flambda is S.IdentityFunction and len(sets) == 1: return sets[0] if not set(flambda.variables) & flambda.expr.free_symbols: is_empty = fuzzy_or(s.is_empty for s in sets) if is_empty == True: return S.EmptySet elif is_empty == False: return FiniteSet(flambda.expr) return Basic.__new__(cls, flambda, *sets) lamda = property(lambda self: self.args[0]) base_sets = property(lambda self: self.args[1:]) @property def base_set(self): # XXX: Maybe deprecate this? It is poorly defined in handling # the multivariate case... sets = self.base_sets if len(sets) == 1: return sets[0] else: return ProductSet(*sets).flatten() @property def base_pset(self): return ProductSet(*self.base_sets) @classmethod def _check_sig(cls, sig_i, set_i): if sig_i.is_symbol: return True elif isinstance(set_i, ProductSet): sets = set_i.sets if len(sig_i) != len(sets): return False # Recurse through the signature for nested tuples: return all(cls._check_sig(ts, ps) for ts, ps in zip(sig_i, sets)) else: # XXX: Need a better way of checking whether a set is a set of # Tuples or not. For example a FiniteSet can contain Tuples # but so can an ImageSet or a ConditionSet. Others like # Integers, Reals etc can not contain Tuples. We could just # list the possibilities here... Current code for e.g. # _contains probably only works for ProductSet. return True # Give the benefit of the doubt def __iter__(self): already_seen = set() for i in self.base_pset: val = self.lamda(*i) if val in already_seen: continue else: already_seen.add(val) yield val def _is_multivariate(self): return len(self.lamda.variables) > 1 def _contains(self, other): from sympy.solvers.solveset import _solveset_multi def get_symsetmap(signature, base_sets): '''Attempt to get a map of symbols to base_sets''' queue = list(zip(signature, base_sets)) symsetmap = {} for sig, base_set in queue: if sig.is_symbol: symsetmap[sig] = base_set elif base_set.is_ProductSet: sets = base_set.sets if len(sig) != len(sets): raise ValueError("Incompatible signature") # Recurse queue.extend(zip(sig, sets)) else: # If we get here then we have something like sig = (x, y) and # base_set = {(1, 2), (3, 4)}. For now we give up. return None return symsetmap def get_equations(expr, candidate): '''Find the equations relating symbols in expr and candidate.''' queue = [(expr, candidate)] for e, c in queue: if not isinstance(e, Tuple): yield Eq(e, c) elif not isinstance(c, Tuple) or len(e) != len(c): yield False return else: queue.extend(zip(e, c)) # Get the basic objects together: other = _sympify(other) expr = self.lamda.expr sig = self.lamda.signature variables = self.lamda.variables base_sets = self.base_sets # Use dummy symbols for ImageSet parameters so they don't match # anything in other rep = {v: Dummy(v.name) for v in variables} variables = [v.subs(rep) for v in variables] sig = sig.subs(rep) expr = expr.subs(rep) # Map the parts of other to those in the Lambda expr equations = [] for eq in get_equations(expr, other): # Unsatisfiable equation? if eq is False: return False equations.append(eq) # Map the symbols in the signature to the corresponding domains symsetmap = get_symsetmap(sig, base_sets) if symsetmap is None: # Can't factor the base sets to a ProductSet return None # Which of the variables in the Lambda signature need to be solved for? symss = (eq.free_symbols for eq in equations) variables = set(variables) & reduce(set.union, symss, set()) # Use internal multivariate solveset variables = tuple(variables) base_sets = [symsetmap[v] for v in variables] solnset = _solveset_multi(equations, variables, base_sets) if solnset is None: return None return fuzzy_not(solnset.is_empty) @property def is_iterable(self): return all(s.is_iterable for s in self.base_sets) def doit(self, **kwargs): from sympy.sets.setexpr import SetExpr f = self.lamda sig = f.signature if len(sig) == 1 and sig[0].is_symbol and isinstance(f.expr, Expr): base_set = self.base_sets[0] return SetExpr(base_set)._eval_func(f).set if all(s.is_FiniteSet for s in self.base_sets): return FiniteSet(*(f(*a) for a in product(*self.base_sets))) return self def _kind(self): return SetKind(self.lamda.expr.kind) class Range(Set): """ Represents a range of integers. Can be called as ``Range(stop)``, ``Range(start, stop)``, or ``Range(start, stop, step)``; when ``step`` is not given it defaults to 1. ``Range(stop)`` is the same as ``Range(0, stop, 1)`` and the stop value (just as for Python ranges) is not included in the Range values. >>> from sympy import Range >>> list(Range(3)) [0, 1, 2] The step can also be negative: >>> list(Range(10, 0, -2)) [10, 8, 6, 4, 2] The stop value is made canonical so equivalent ranges always have the same args: >>> Range(0, 10, 3) Range(0, 12, 3) Infinite ranges are allowed. ``oo`` and ``-oo`` are never included in the set (``Range`` is always a subset of ``Integers``). If the starting point is infinite, then the final value is ``stop - step``. To iterate such a range, it needs to be reversed: >>> from sympy import oo >>> r = Range(-oo, 1) >>> r[-1] 0 >>> next(iter(r)) Traceback (most recent call last): ... TypeError: Cannot iterate over Range with infinite start >>> next(iter(r.reversed)) 0 Although ``Range`` is a :class:`Set` (and supports the normal set operations) it maintains the order of the elements and can be used in contexts where ``range`` would be used. >>> from sympy import Interval >>> Range(0, 10, 2).intersect(Interval(3, 7)) Range(4, 8, 2) >>> list(_) [4, 6] Although slicing of a Range will always return a Range -- possibly empty -- an empty set will be returned from any intersection that is empty: >>> Range(3)[:0] Range(0, 0, 1) >>> Range(3).intersect(Interval(4, oo)) EmptySet >>> Range(3).intersect(Range(4, oo)) EmptySet Range will accept symbolic arguments but has very limited support for doing anything other than displaying the Range: >>> from sympy import Symbol, pprint >>> from sympy.abc import i, j, k >>> Range(i, j, k).start i >>> Range(i, j, k).inf Traceback (most recent call last): ... ValueError: invalid method for symbolic range Better success will be had when using integer symbols: >>> n = Symbol('n', integer=True) >>> r = Range(n, n + 20, 3) >>> r.inf n >>> pprint(r) {n, n + 3, ..., n + 18} """ def __new__(cls, *args): if len(args) == 1: if isinstance(args[0], range): raise TypeError( 'use sympify(%s) to convert range to Range' % args[0]) # expand range slc = slice(*args) if slc.step == 0: raise ValueError("step cannot be 0") start, stop, step = slc.start or 0, slc.stop, slc.step or 1 try: ok = [] for w in (start, stop, step): w = sympify(w) if w in [S.NegativeInfinity, S.Infinity] or ( w.has(Symbol) and w.is_integer != False): ok.append(w) elif not w.is_Integer: if w.is_infinite: raise ValueError('infinite symbols not allowed') raise ValueError else: ok.append(w) except ValueError: raise ValueError(filldedent(''' Finite arguments to Range must be integers; `imageset` can define other cases, e.g. use `imageset(i, i/10, Range(3))` to give [0, 1/10, 1/5].''')) start, stop, step = ok null = False if any(i.has(Symbol) for i in (start, stop, step)): dif = stop - start n = dif/step if n.is_Rational: if dif == 0: null = True else: # (x, x + 5, 2) or (x, 3*x, x) n = floor(n) end = start + n*step if dif.is_Rational: # (x, x + 5, 2) if (end - stop).is_negative: end += step else: # (x, 3*x, x) if (end/stop - 1).is_negative: end += step elif n.is_extended_negative: null = True else: end = stop # other methods like sup and reversed must fail elif start.is_infinite: span = step*(stop - start) if span is S.NaN or span <= 0: null = True elif step.is_Integer and stop.is_infinite and abs(step) != 1: raise ValueError(filldedent(''' Step size must be %s in this case.''' % (1 if step > 0 else -1))) else: end = stop else: oostep = step.is_infinite if oostep: step = S.One if step > 0 else S.NegativeOne n = ceiling((stop - start)/step) if n <= 0: null = True elif oostep: step = S.One # make it canonical end = start + step else: end = start + n*step if null: start = end = S.Zero step = S.One return Basic.__new__(cls, start, end, step) start = property(lambda self: self.args[0]) stop = property(lambda self: self.args[1]) step = property(lambda self: self.args[2]) @property def reversed(self): """Return an equivalent Range in the opposite order. Examples ======== >>> from sympy import Range >>> Range(10).reversed Range(9, -1, -1) """ if self.has(Symbol): n = (self.stop - self.start)/self.step if not n.is_extended_positive or not all( i.is_integer or i.is_infinite for i in self.args): raise ValueError('invalid method for symbolic range') if self.start == self.stop: return self return self.func( self.stop - self.step, self.start - self.step, -self.step) def _kind(self): return SetKind(NumberKind) def _contains(self, other): if self.start == self.stop: return S.false if other.is_infinite: return S.false if not other.is_integer: return other.is_integer if self.has(Symbol): n = (self.stop - self.start)/self.step if not n.is_extended_positive or not all( i.is_integer or i.is_infinite for i in self.args): return else: n = self.size if self.start.is_finite: ref = self.start elif self.stop.is_finite: ref = self.stop else: # both infinite; step is +/- 1 (enforced by __new__) return S.true if n == 1: return Eq(other, self[0]) res = (ref - other) % self.step if res == S.Zero: if self.has(Symbol): d = Dummy('i') return self.as_relational(d).subs(d, other) return And(other >= self.inf, other <= self.sup) elif res.is_Integer: # off sequence return S.false else: # symbolic/unsimplified residue modulo step return None def __iter__(self): n = self.size # validate if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer): raise TypeError("Cannot iterate over symbolic Range") if self.start in [S.NegativeInfinity, S.Infinity]: raise TypeError("Cannot iterate over Range with infinite start") elif self.start != self.stop: i = self.start if n.is_infinite: while True: yield i i += self.step else: for _ in range(n): yield i i += self.step @property def is_iterable(self): # Check that size can be determined, used by __iter__ dif = self.stop - self.start n = dif/self.step if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer): return False if self.start in [S.NegativeInfinity, S.Infinity]: return False if not (n.is_extended_nonnegative and all(i.is_integer for i in self.args)): return False return True def __len__(self): rv = self.size if rv is S.Infinity: raise ValueError('Use .size to get the length of an infinite Range') return int(rv) @property def size(self): if self.start == self.stop: return S.Zero dif = self.stop - self.start n = dif/self.step if n.is_infinite: return S.Infinity if n.is_extended_nonnegative and all(i.is_integer for i in self.args): return abs(floor(n)) raise ValueError('Invalid method for symbolic Range') @property def is_finite_set(self): if self.start.is_integer and self.stop.is_integer: return True return self.size.is_finite @property def is_empty(self): try: return self.size.is_zero except ValueError: return None def __bool__(self): # this only distinguishes between definite null range # and non-null/unknown null; getting True doesn't mean # that it actually is not null b = is_eq(self.start, self.stop) if b is None: raise ValueError('cannot tell if Range is null or not') return not bool(b) def __getitem__(self, i): ooslice = "cannot slice from the end with an infinite value" zerostep = "slice step cannot be zero" infinite = "slicing not possible on range with infinite start" # if we had to take every other element in the following # oo, ..., 6, 4, 2, 0 # we might get oo, ..., 4, 0 or oo, ..., 6, 2 ambiguous = "cannot unambiguously re-stride from the end " + \ "with an infinite value" if isinstance(i, slice): if self.size.is_finite: # validates, too if self.start == self.stop: return Range(0) start, stop, step = i.indices(self.size) n = ceiling((stop - start)/step) if n <= 0: return Range(0) canonical_stop = start + n*step end = canonical_stop - step ss = step*self.step return Range(self[start], self[end] + ss, ss) else: # infinite Range start = i.start stop = i.stop if i.step == 0: raise ValueError(zerostep) step = i.step or 1 ss = step*self.step #--------------------- # handle infinite Range # i.e. Range(-oo, oo) or Range(oo, -oo, -1) # -------------------- if self.start.is_infinite and self.stop.is_infinite: raise ValueError(infinite) #--------------------- # handle infinite on right # e.g. Range(0, oo) or Range(0, -oo, -1) # -------------------- if self.stop.is_infinite: # start and stop are not interdependent -- # they only depend on step --so we use the # equivalent reversed values return self.reversed[ stop if stop is None else -stop + 1: start if start is None else -start: step].reversed #--------------------- # handle infinite on the left # e.g. Range(oo, 0, -1) or Range(-oo, 0) # -------------------- # consider combinations of # start/stop {== None, < 0, == 0, > 0} and # step {< 0, > 0} if start is None: if stop is None: if step < 0: return Range(self[-1], self.start, ss) elif step > 1: raise ValueError(ambiguous) else: # == 1 return self elif stop < 0: if step < 0: return Range(self[-1], self[stop], ss) else: # > 0 return Range(self.start, self[stop], ss) elif stop == 0: if step > 0: return Range(0) else: # < 0 raise ValueError(ooslice) elif stop == 1: if step > 0: raise ValueError(ooslice) # infinite singleton else: # < 0 raise ValueError(ooslice) else: # > 1 raise ValueError(ooslice) elif start < 0: if stop is None: if step < 0: return Range(self[start], self.start, ss) else: # > 0 return Range(self[start], self.stop, ss) elif stop < 0: return Range(self[start], self[stop], ss) elif stop == 0: if step < 0: raise ValueError(ooslice) else: # > 0 return Range(0) elif stop > 0: raise ValueError(ooslice) elif start == 0: if stop is None: if step < 0: raise ValueError(ooslice) # infinite singleton elif step > 1: raise ValueError(ambiguous) else: # == 1 return self elif stop < 0: if step > 1: raise ValueError(ambiguous) elif step == 1: return Range(self.start, self[stop], ss) else: # < 0 return Range(0) else: # >= 0 raise ValueError(ooslice) elif start > 0: raise ValueError(ooslice) else: if self.start == self.stop: raise IndexError('Range index out of range') if not (all(i.is_integer or i.is_infinite for i in self.args) and ((self.stop - self.start)/ self.step).is_extended_positive): raise ValueError('Invalid method for symbolic Range') if i == 0: if self.start.is_infinite: raise ValueError(ooslice) return self.start if i == -1: if self.stop.is_infinite: raise ValueError(ooslice) return self.stop - self.step n = self.size # must be known for any other index rv = (self.stop if i < 0 else self.start) + i*self.step if rv.is_infinite: raise ValueError(ooslice) val = (rv - self.start)/self.step rel = fuzzy_or([val.is_infinite, fuzzy_and([val.is_nonnegative, (n-val).is_nonnegative])]) if rel: return rv if rel is None: raise ValueError('Invalid method for symbolic Range') raise IndexError("Range index out of range") @property def _inf(self): if not self: return S.EmptySet.inf if self.has(Symbol): if all(i.is_integer or i.is_infinite for i in self.args): dif = self.stop - self.start if self.step.is_positive and dif.is_positive: return self.start elif self.step.is_negative and dif.is_negative: return self.stop - self.step raise ValueError('invalid method for symbolic range') if self.step > 0: return self.start else: return self.stop - self.step @property def _sup(self): if not self: return S.EmptySet.sup if self.has(Symbol): if all(i.is_integer or i.is_infinite for i in self.args): dif = self.stop - self.start if self.step.is_positive and dif.is_positive: return self.stop - self.step elif self.step.is_negative and dif.is_negative: return self.start raise ValueError('invalid method for symbolic range') if self.step > 0: return self.stop - self.step else: return self.start @property def _boundary(self): return self def as_relational(self, x): """Rewrite a Range in terms of equalities and logic operators. """ if self.start.is_infinite: assert not self.stop.is_infinite # by instantiation a = self.reversed.start else: a = self.start step = self.step in_seq = Eq(Mod(x - a, step), 0) ints = And(Eq(Mod(a, 1), 0), Eq(Mod(step, 1), 0)) n = (self.stop - self.start)/self.step if n == 0: return S.EmptySet.as_relational(x) if n == 1: return And(Eq(x, a), ints) try: a, b = self.inf, self.sup except ValueError: a = None if a is not None: range_cond = And( x > a if a.is_infinite else x >= a, x < b if b.is_infinite else x <= b) else: a, b = self.start, self.stop - self.step range_cond = Or( And(self.step >= 1, x > a if a.is_infinite else x >= a, x < b if b.is_infinite else x <= b), And(self.step <= -1, x < a if a.is_infinite else x <= a, x > b if b.is_infinite else x >= b)) return And(in_seq, ints, range_cond) _sympy_converter[range] = lambda r: Range(r.start, r.stop, r.step) def normalize_theta_set(theta): r""" Normalize a Real Set `theta` in the interval `[0, 2\pi)`. It returns a normalized value of theta in the Set. For Interval, a maximum of one cycle $[0, 2\pi]$, is returned i.e. for theta equal to $[0, 10\pi]$, returned normalized value would be $[0, 2\pi)$. As of now intervals with end points as non-multiples of ``pi`` is not supported. Raises ====== NotImplementedError The algorithms for Normalizing theta Set are not yet implemented. ValueError The input is not valid, i.e. the input is not a real set. RuntimeError It is a bug, please report to the github issue tracker. Examples ======== >>> from sympy.sets.fancysets import normalize_theta_set >>> from sympy import Interval, FiniteSet, pi >>> normalize_theta_set(Interval(9*pi/2, 5*pi)) Interval(pi/2, pi) >>> normalize_theta_set(Interval(-3*pi/2, pi/2)) Interval.Ropen(0, 2*pi) >>> normalize_theta_set(Interval(-pi/2, pi/2)) Union(Interval(0, pi/2), Interval.Ropen(3*pi/2, 2*pi)) >>> normalize_theta_set(Interval(-4*pi, 3*pi)) Interval.Ropen(0, 2*pi) >>> normalize_theta_set(Interval(-3*pi/2, -pi/2)) Interval(pi/2, 3*pi/2) >>> normalize_theta_set(FiniteSet(0, pi, 3*pi)) {0, pi} """ from sympy.functions.elementary.trigonometric import _pi_coeff as coeff if theta.is_Interval: interval_len = theta.measure # one complete circle if interval_len >= 2*S.Pi: if interval_len == 2*S.Pi and theta.left_open and theta.right_open: k = coeff(theta.start) return Union(Interval(0, k*S.Pi, False, True), Interval(k*S.Pi, 2*S.Pi, True, True)) return Interval(0, 2*S.Pi, False, True) k_start, k_end = coeff(theta.start), coeff(theta.end) if k_start is None or k_end is None: raise NotImplementedError("Normalizing theta without pi as coefficient is " "not yet implemented") new_start = k_start*S.Pi new_end = k_end*S.Pi if new_start > new_end: return Union(Interval(S.Zero, new_end, False, theta.right_open), Interval(new_start, 2*S.Pi, theta.left_open, True)) else: return Interval(new_start, new_end, theta.left_open, theta.right_open) elif theta.is_FiniteSet: new_theta = [] for element in theta: k = coeff(element) if k is None: raise NotImplementedError('Normalizing theta without pi as ' 'coefficient, is not Implemented.') else: new_theta.append(k*S.Pi) return FiniteSet(*new_theta) elif theta.is_Union: return Union(*[normalize_theta_set(interval) for interval in theta.args]) elif theta.is_subset(S.Reals): raise NotImplementedError("Normalizing theta when, it is of type %s is not " "implemented" % type(theta)) else: raise ValueError(" %s is not a real set" % (theta)) class ComplexRegion(Set): r""" Represents the Set of all Complex Numbers. It can represent a region of Complex Plane in both the standard forms Polar and Rectangular coordinates. * Polar Form Input is in the form of the ProductSet or Union of ProductSets of the intervals of ``r`` and ``theta``, and use the flag ``polar=True``. .. math:: Z = \{z \in \mathbb{C} \mid z = r\times (\cos(\theta) + I\sin(\theta)), r \in [\texttt{r}], \theta \in [\texttt{theta}]\} * Rectangular Form Input is in the form of the ProductSet or Union of ProductSets of interval of x and y, the real and imaginary parts of the Complex numbers in a plane. Default input type is in rectangular form. .. math:: Z = \{z \in \mathbb{C} \mid z = x + Iy, x \in [\operatorname{re}(z)], y \in [\operatorname{im}(z)]\} Examples ======== >>> from sympy import ComplexRegion, Interval, S, I, Union >>> a = Interval(2, 3) >>> b = Interval(4, 6) >>> c1 = ComplexRegion(a*b) # Rectangular Form >>> c1 CartesianComplexRegion(ProductSet(Interval(2, 3), Interval(4, 6))) * c1 represents the rectangular region in complex plane surrounded by the coordinates (2, 4), (3, 4), (3, 6) and (2, 6), of the four vertices. >>> c = Interval(1, 8) >>> c2 = ComplexRegion(Union(a*b, b*c)) >>> c2 CartesianComplexRegion(Union(ProductSet(Interval(2, 3), Interval(4, 6)), ProductSet(Interval(4, 6), Interval(1, 8)))) * c2 represents the Union of two rectangular regions in complex plane. One of them surrounded by the coordinates of c1 and other surrounded by the coordinates (4, 1), (6, 1), (6, 8) and (4, 8). >>> 2.5 + 4.5*I in c1 True >>> 2.5 + 6.5*I in c1 False >>> r = Interval(0, 1) >>> theta = Interval(0, 2*S.Pi) >>> c2 = ComplexRegion(r*theta, polar=True) # Polar Form >>> c2 # unit Disk PolarComplexRegion(ProductSet(Interval(0, 1), Interval.Ropen(0, 2*pi))) * c2 represents the region in complex plane inside the Unit Disk centered at the origin. >>> 0.5 + 0.5*I in c2 True >>> 1 + 2*I in c2 False >>> unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) >>> upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) >>> intersection = unit_disk.intersect(upper_half_unit_disk) >>> intersection PolarComplexRegion(ProductSet(Interval(0, 1), Interval(0, pi))) >>> intersection == upper_half_unit_disk True See Also ======== CartesianComplexRegion PolarComplexRegion Complexes """ is_ComplexRegion = True def __new__(cls, sets, polar=False): if polar is False: return CartesianComplexRegion(sets) elif polar is True: return PolarComplexRegion(sets) else: raise ValueError("polar should be either True or False") @property def sets(self): """ Return raw input sets to the self. Examples ======== >>> from sympy import Interval, ComplexRegion, Union >>> a = Interval(2, 3) >>> b = Interval(4, 5) >>> c = Interval(1, 7) >>> C1 = ComplexRegion(a*b) >>> C1.sets ProductSet(Interval(2, 3), Interval(4, 5)) >>> C2 = ComplexRegion(Union(a*b, b*c)) >>> C2.sets Union(ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7))) """ return self.args[0] @property def psets(self): """ Return a tuple of sets (ProductSets) input of the self. Examples ======== >>> from sympy import Interval, ComplexRegion, Union >>> a = Interval(2, 3) >>> b = Interval(4, 5) >>> c = Interval(1, 7) >>> C1 = ComplexRegion(a*b) >>> C1.psets (ProductSet(Interval(2, 3), Interval(4, 5)),) >>> C2 = ComplexRegion(Union(a*b, b*c)) >>> C2.psets (ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7))) """ if self.sets.is_ProductSet: psets = () psets = psets + (self.sets, ) else: psets = self.sets.args return psets @property def a_interval(self): """ Return the union of intervals of `x` when, self is in rectangular form, or the union of intervals of `r` when self is in polar form. Examples ======== >>> from sympy import Interval, ComplexRegion, Union >>> a = Interval(2, 3) >>> b = Interval(4, 5) >>> c = Interval(1, 7) >>> C1 = ComplexRegion(a*b) >>> C1.a_interval Interval(2, 3) >>> C2 = ComplexRegion(Union(a*b, b*c)) >>> C2.a_interval Union(Interval(2, 3), Interval(4, 5)) """ a_interval = [] for element in self.psets: a_interval.append(element.args[0]) a_interval = Union(*a_interval) return a_interval @property def b_interval(self): """ Return the union of intervals of `y` when, self is in rectangular form, or the union of intervals of `theta` when self is in polar form. Examples ======== >>> from sympy import Interval, ComplexRegion, Union >>> a = Interval(2, 3) >>> b = Interval(4, 5) >>> c = Interval(1, 7) >>> C1 = ComplexRegion(a*b) >>> C1.b_interval Interval(4, 5) >>> C2 = ComplexRegion(Union(a*b, b*c)) >>> C2.b_interval Interval(1, 7) """ b_interval = [] for element in self.psets: b_interval.append(element.args[1]) b_interval = Union(*b_interval) return b_interval @property def _measure(self): """ The measure of self.sets. Examples ======== >>> from sympy import Interval, ComplexRegion, S >>> a, b = Interval(2, 5), Interval(4, 8) >>> c = Interval(0, 2*S.Pi) >>> c1 = ComplexRegion(a*b) >>> c1.measure 12 >>> c2 = ComplexRegion(a*c, polar=True) >>> c2.measure 6*pi """ return self.sets._measure def _kind(self): return self.args[0].kind @classmethod def from_real(cls, sets): """ Converts given subset of real numbers to a complex region. Examples ======== >>> from sympy import Interval, ComplexRegion >>> unit = Interval(0,1) >>> ComplexRegion.from_real(unit) CartesianComplexRegion(ProductSet(Interval(0, 1), {0})) """ if not sets.is_subset(S.Reals): raise ValueError("sets must be a subset of the real line") return CartesianComplexRegion(sets * FiniteSet(0)) def _contains(self, other): from sympy.functions import arg, Abs other = sympify(other) isTuple = isinstance(other, Tuple) if isTuple and len(other) != 2: raise ValueError('expecting Tuple of length 2') # If the other is not an Expression, and neither a Tuple if not isinstance(other, (Expr, Tuple)): return S.false # self in rectangular form if not self.polar: re, im = other if isTuple else other.as_real_imag() return fuzzy_or(fuzzy_and([ pset.args[0]._contains(re), pset.args[1]._contains(im)]) for pset in self.psets) # self in polar form elif self.polar: if other.is_zero: # ignore undefined complex argument return fuzzy_or(pset.args[0]._contains(S.Zero) for pset in self.psets) if isTuple: r, theta = other else: r, theta = Abs(other), arg(other) if theta.is_real and theta.is_number: # angles in psets are normalized to [0, 2pi) theta %= 2*S.Pi return fuzzy_or(fuzzy_and([ pset.args[0]._contains(r), pset.args[1]._contains(theta)]) for pset in self.psets) class CartesianComplexRegion(ComplexRegion): r""" Set representing a square region of the complex plane. .. math:: Z = \{z \in \mathbb{C} \mid z = x + Iy, x \in [\operatorname{re}(z)], y \in [\operatorname{im}(z)]\} Examples ======== >>> from sympy import ComplexRegion, I, Interval >>> region = ComplexRegion(Interval(1, 3) * Interval(4, 6)) >>> 2 + 5*I in region True >>> 5*I in region False See also ======== ComplexRegion PolarComplexRegion Complexes """ polar = False variables = symbols('x, y', cls=Dummy) def __new__(cls, sets): if sets == S.Reals*S.Reals: return S.Complexes if all(_a.is_FiniteSet for _a in sets.args) and (len(sets.args) == 2): # ** ProductSet of FiniteSets in the Complex Plane. ** # For Cases like ComplexRegion({2, 4}*{3}), It # would return {2 + 3*I, 4 + 3*I} # FIXME: This should probably be handled with something like: # return ImageSet(Lambda((x, y), x+I*y), sets).rewrite(FiniteSet) complex_num = [] for x in sets.args[0]: for y in sets.args[1]: complex_num.append(x + S.ImaginaryUnit*y) return FiniteSet(*complex_num) else: return Set.__new__(cls, sets) @property def expr(self): x, y = self.variables return x + S.ImaginaryUnit*y class PolarComplexRegion(ComplexRegion): r""" Set representing a polar region of the complex plane. .. math:: Z = \{z \in \mathbb{C} \mid z = r\times (\cos(\theta) + I\sin(\theta)), r \in [\texttt{r}], \theta \in [\texttt{theta}]\} Examples ======== >>> from sympy import ComplexRegion, Interval, oo, pi, I >>> rset = Interval(0, oo) >>> thetaset = Interval(0, pi) >>> upper_half_plane = ComplexRegion(rset * thetaset, polar=True) >>> 1 + I in upper_half_plane True >>> 1 - I in upper_half_plane False See also ======== ComplexRegion CartesianComplexRegion Complexes """ polar = True variables = symbols('r, theta', cls=Dummy) def __new__(cls, sets): new_sets = [] # sets is Union of ProductSets if not sets.is_ProductSet: for k in sets.args: new_sets.append(k) # sets is ProductSets else: new_sets.append(sets) # Normalize input theta for k, v in enumerate(new_sets): new_sets[k] = ProductSet(v.args[0], normalize_theta_set(v.args[1])) sets = Union(*new_sets) return Set.__new__(cls, sets) @property def expr(self): r, theta = self.variables return r*(cos(theta) + S.ImaginaryUnit*sin(theta)) class Complexes(CartesianComplexRegion, metaclass=Singleton): """ The :class:`Set` of all complex numbers Examples ======== >>> from sympy import S, I >>> S.Complexes Complexes >>> 1 + I in S.Complexes True See also ======== Reals ComplexRegion """ is_empty = False is_finite_set = False # Override property from superclass since Complexes has no args @property def sets(self): return ProductSet(S.Reals, S.Reals) def __new__(cls): return Set.__new__(cls)
5757d6e71c54ddf8b07ffd5aadfcc5698be3c299eb06f1de13f63da41d84b8e0
from typing import Any, Callable, Optional from functools import reduce from collections import defaultdict import inspect from sympy.core.kind import Kind, UndefinedKind, NumberKind from sympy.core.basic import Basic from sympy.core.containers import Tuple, TupleKind from sympy.core.decorators import sympify_method_args, sympify_return from sympy.core.evalf import EvalfMixin from sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.logic import (FuzzyBool, fuzzy_bool, fuzzy_or, fuzzy_and, fuzzy_not) from sympy.core.numbers import Float, Integer from sympy.core.operations import LatticeOp from sympy.core.parameters import global_parameters from sympy.core.relational import Eq, Ne, is_lt from sympy.core.singleton import Singleton, S from sympy.core.sorting import ordered from sympy.core.symbol import symbols, Symbol, Dummy, uniquely_named_symbol from sympy.core.sympify import _sympify, sympify, _sympy_converter from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import And, Or, Not, Xor, true, false from sympy.utilities.decorator import deprecated from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import (iproduct, sift, roundrobin, iterable, subsets) from sympy.utilities.misc import func_name, filldedent from mpmath import mpi, mpf from mpmath.libmp.libmpf import prec_to_dps tfn = defaultdict(lambda: None, { True: S.true, S.true: S.true, False: S.false, S.false: S.false}) @sympify_method_args class Set(Basic, EvalfMixin): """ The base class for any kind of set. Explanation =========== This is not meant to be used directly as a container of items. It does not behave like the builtin ``set``; see :class:`FiniteSet` for that. Real intervals are represented by the :class:`Interval` class and unions of sets by the :class:`Union` class. The empty set is represented by the :class:`EmptySet` class and available as a singleton as ``S.EmptySet``. """ __slots__ = () is_number = False is_iterable = False is_interval = False is_FiniteSet = False is_Interval = False is_ProductSet = False is_Union = False is_Intersection = None # type: Optional[bool] is_UniversalSet = None # type: Optional[bool] is_Complement = None # type: Optional[bool] is_ComplexRegion = False is_empty = None # type: FuzzyBool is_finite_set = None # type: FuzzyBool @property # type: ignore @deprecated( """ The is_EmptySet attribute of Set objects is deprecated. Use 's is S.EmptySet" or 's.is_empty' instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-is-emptyset", ) def is_EmptySet(self): return None @staticmethod def _infimum_key(expr): """ Return infimum (if possible) else S.Infinity. """ try: infimum = expr.inf assert infimum.is_comparable infimum = infimum.evalf() # issue #18505 except (NotImplementedError, AttributeError, AssertionError, ValueError): infimum = S.Infinity return infimum def union(self, other): """ Returns the union of ``self`` and ``other``. Examples ======== As a shortcut it is possible to use the ``+`` operator: >>> from sympy import Interval, FiniteSet >>> Interval(0, 1).union(Interval(2, 3)) Union(Interval(0, 1), Interval(2, 3)) >>> Interval(0, 1) + Interval(2, 3) Union(Interval(0, 1), Interval(2, 3)) >>> Interval(1, 2, True, True) + FiniteSet(2, 3) Union({3}, Interval.Lopen(1, 2)) Similarly it is possible to use the ``-`` operator for set differences: >>> Interval(0, 2) - Interval(0, 1) Interval.Lopen(1, 2) >>> Interval(1, 3) - FiniteSet(2) Union(Interval.Ropen(1, 2), Interval.Lopen(2, 3)) """ return Union(self, other) def intersect(self, other): """ Returns the intersection of 'self' and 'other'. Examples ======== >>> from sympy import Interval >>> Interval(1, 3).intersect(Interval(1, 2)) Interval(1, 2) >>> from sympy import imageset, Lambda, symbols, S >>> n, m = symbols('n m') >>> a = imageset(Lambda(n, 2*n), S.Integers) >>> a.intersect(imageset(Lambda(m, 2*m + 1), S.Integers)) EmptySet """ return Intersection(self, other) def intersection(self, other): """ Alias for :meth:`intersect()` """ return self.intersect(other) def is_disjoint(self, other): """ Returns True if ``self`` and ``other`` are disjoint. Examples ======== >>> from sympy import Interval >>> Interval(0, 2).is_disjoint(Interval(1, 2)) False >>> Interval(0, 2).is_disjoint(Interval(3, 4)) True References ========== .. [1] https://en.wikipedia.org/wiki/Disjoint_sets """ return self.intersect(other) == S.EmptySet def isdisjoint(self, other): """ Alias for :meth:`is_disjoint()` """ return self.is_disjoint(other) def complement(self, universe): r""" The complement of 'self' w.r.t the given universe. Examples ======== >>> from sympy import Interval, S >>> Interval(0, 1).complement(S.Reals) Union(Interval.open(-oo, 0), Interval.open(1, oo)) >>> Interval(0, 1).complement(S.UniversalSet) Complement(UniversalSet, Interval(0, 1)) """ return Complement(universe, self) def _complement(self, other): # this behaves as other - self if isinstance(self, ProductSet) and isinstance(other, ProductSet): # If self and other are disjoint then other - self == self if len(self.sets) != len(other.sets): return other # There can be other ways to represent this but this gives: # (A x B) - (C x D) = ((A - C) x B) U (A x (B - D)) overlaps = [] pairs = list(zip(self.sets, other.sets)) for n in range(len(pairs)): sets = (o if i != n else o-s for i, (s, o) in enumerate(pairs)) overlaps.append(ProductSet(*sets)) return Union(*overlaps) elif isinstance(other, Interval): if isinstance(self, (Interval, FiniteSet)): return Intersection(other, self.complement(S.Reals)) elif isinstance(other, Union): return Union(*(o - self for o in other.args)) elif isinstance(other, Complement): return Complement(other.args[0], Union(other.args[1], self), evaluate=False) elif other is S.EmptySet: return S.EmptySet elif isinstance(other, FiniteSet): sifted = sift(other, lambda x: fuzzy_bool(self.contains(x))) # ignore those that are contained in self return Union(FiniteSet(*(sifted[False])), Complement(FiniteSet(*(sifted[None])), self, evaluate=False) if sifted[None] else S.EmptySet) def symmetric_difference(self, other): """ Returns symmetric difference of ``self`` and ``other``. Examples ======== >>> from sympy import Interval, S >>> Interval(1, 3).symmetric_difference(S.Reals) Union(Interval.open(-oo, 1), Interval.open(3, oo)) >>> Interval(1, 10).symmetric_difference(S.Reals) Union(Interval.open(-oo, 1), Interval.open(10, oo)) >>> from sympy import S, EmptySet >>> S.Reals.symmetric_difference(EmptySet) Reals References ========== .. [1] https://en.wikipedia.org/wiki/Symmetric_difference """ return SymmetricDifference(self, other) def _symmetric_difference(self, other): return Union(Complement(self, other), Complement(other, self)) @property def inf(self): """ The infimum of ``self``. Examples ======== >>> from sympy import Interval, Union >>> Interval(0, 1).inf 0 >>> Union(Interval(0, 1), Interval(2, 3)).inf 0 """ return self._inf @property def _inf(self): raise NotImplementedError("(%s)._inf" % self) @property def sup(self): """ The supremum of ``self``. Examples ======== >>> from sympy import Interval, Union >>> Interval(0, 1).sup 1 >>> Union(Interval(0, 1), Interval(2, 3)).sup 3 """ return self._sup @property def _sup(self): raise NotImplementedError("(%s)._sup" % self) def contains(self, other): """ Returns a SymPy value indicating whether ``other`` is contained in ``self``: ``true`` if it is, ``false`` if it is not, else an unevaluated ``Contains`` expression (or, as in the case of ConditionSet and a union of FiniteSet/Intervals, an expression indicating the conditions for containment). Examples ======== >>> from sympy import Interval, S >>> from sympy.abc import x >>> Interval(0, 1).contains(0.5) True As a shortcut it is possible to use the ``in`` operator, but that will raise an error unless an affirmative true or false is not obtained. >>> Interval(0, 1).contains(x) (0 <= x) & (x <= 1) >>> x in Interval(0, 1) Traceback (most recent call last): ... TypeError: did not evaluate to a bool: None The result of 'in' is a bool, not a SymPy value >>> 1 in Interval(0, 2) True >>> _ is S.true False """ from .contains import Contains other = sympify(other, strict=True) c = self._contains(other) if isinstance(c, Contains): return c if c is None: return Contains(other, self, evaluate=False) b = tfn[c] if b is None: return c return b def _contains(self, other): raise NotImplementedError(filldedent(''' (%s)._contains(%s) is not defined. This method, when defined, will receive a sympified object. The method should return True, False, None or something that expresses what must be true for the containment of that object in self to be evaluated. If None is returned then a generic Contains object will be returned by the ``contains`` method.''' % (self, other))) def is_subset(self, other): """ Returns True if ``self`` is a subset of ``other``. Examples ======== >>> from sympy import Interval >>> Interval(0, 0.5).is_subset(Interval(0, 1)) True >>> Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) False """ if not isinstance(other, Set): raise ValueError("Unknown argument '%s'" % other) # Handle the trivial cases if self == other: return True is_empty = self.is_empty if is_empty is True: return True elif fuzzy_not(is_empty) and other.is_empty: return False if self.is_finite_set is False and other.is_finite_set: return False # Dispatch on subclass rules ret = self._eval_is_subset(other) if ret is not None: return ret ret = other._eval_is_superset(self) if ret is not None: return ret # Use pairwise rules from multiple dispatch from sympy.sets.handlers.issubset import is_subset_sets ret = is_subset_sets(self, other) if ret is not None: return ret # Fall back on computing the intersection # XXX: We shouldn't do this. A query like this should be handled # without evaluating new Set objects. It should be the other way round # so that the intersect method uses is_subset for evaluation. if self.intersect(other) == self: return True def _eval_is_subset(self, other): '''Returns a fuzzy bool for whether self is a subset of other.''' return None def _eval_is_superset(self, other): '''Returns a fuzzy bool for whether self is a subset of other.''' return None # This should be deprecated: def issubset(self, other): """ Alias for :meth:`is_subset()` """ return self.is_subset(other) def is_proper_subset(self, other): """ Returns True if ``self`` is a proper subset of ``other``. Examples ======== >>> from sympy import Interval >>> Interval(0, 0.5).is_proper_subset(Interval(0, 1)) True >>> Interval(0, 1).is_proper_subset(Interval(0, 1)) False """ if isinstance(other, Set): return self != other and self.is_subset(other) else: raise ValueError("Unknown argument '%s'" % other) def is_superset(self, other): """ Returns True if ``self`` is a superset of ``other``. Examples ======== >>> from sympy import Interval >>> Interval(0, 0.5).is_superset(Interval(0, 1)) False >>> Interval(0, 1).is_superset(Interval(0, 1, left_open=True)) True """ if isinstance(other, Set): return other.is_subset(self) else: raise ValueError("Unknown argument '%s'" % other) # This should be deprecated: def issuperset(self, other): """ Alias for :meth:`is_superset()` """ return self.is_superset(other) def is_proper_superset(self, other): """ Returns True if ``self`` is a proper superset of ``other``. Examples ======== >>> from sympy import Interval >>> Interval(0, 1).is_proper_superset(Interval(0, 0.5)) True >>> Interval(0, 1).is_proper_superset(Interval(0, 1)) False """ if isinstance(other, Set): return self != other and self.is_superset(other) else: raise ValueError("Unknown argument '%s'" % other) def _eval_powerset(self): from .powerset import PowerSet return PowerSet(self) def powerset(self): """ Find the Power set of ``self``. Examples ======== >>> from sympy import EmptySet, FiniteSet, Interval A power set of an empty set: >>> A = EmptySet >>> A.powerset() {EmptySet} A power set of a finite set: >>> A = FiniteSet(1, 2) >>> a, b, c = FiniteSet(1), FiniteSet(2), FiniteSet(1, 2) >>> A.powerset() == FiniteSet(a, b, c, EmptySet) True A power set of an interval: >>> Interval(1, 2).powerset() PowerSet(Interval(1, 2)) References ========== .. [1] https://en.wikipedia.org/wiki/Power_set """ return self._eval_powerset() @property def measure(self): """ The (Lebesgue) measure of ``self``. Examples ======== >>> from sympy import Interval, Union >>> Interval(0, 1).measure 1 >>> Union(Interval(0, 1), Interval(2, 3)).measure 2 """ return self._measure @property def kind(self): """ The kind of a Set Explanation =========== Any :class:`Set` will have kind :class:`SetKind` which is parametrised by the kind of the elements of the set. For example most sets are sets of numbers and will have kind ``SetKind(NumberKind)``. If elements of sets are different in kind than their kind will ``SetKind(UndefinedKind)``. See :class:`sympy.core.kind.Kind` for an explanation of the kind system. Examples ======== >>> from sympy import Interval, Matrix, FiniteSet, EmptySet, ProductSet, PowerSet >>> FiniteSet(Matrix([1, 2])).kind SetKind(MatrixKind(NumberKind)) >>> Interval(1, 2).kind SetKind(NumberKind) >>> EmptySet.kind SetKind() A :class:`sympy.sets.powerset.PowerSet` is a set of sets: >>> PowerSet({1, 2, 3}).kind SetKind(SetKind(NumberKind)) A :class:`ProductSet` represents the set of tuples of elements of other sets. Its kind is :class:`sympy.core.containers.TupleKind` parametrised by the kinds of the elements of those sets: >>> p = ProductSet(FiniteSet(1, 2), FiniteSet(3, 4)) >>> list(p) [(1, 3), (2, 3), (1, 4), (2, 4)] >>> p.kind SetKind(TupleKind(NumberKind, NumberKind)) When all elements of the set do not have same kind, the kind will be returned as ``SetKind(UndefinedKind)``: >>> FiniteSet(0, Matrix([1, 2])).kind SetKind(UndefinedKind) The kind of the elements of a set are given by the ``element_kind`` attribute of ``SetKind``: >>> Interval(1, 2).kind.element_kind NumberKind See Also ======== NumberKind sympy.core.kind.UndefinedKind sympy.core.containers.TupleKind MatrixKind sympy.matrices.expressions.sets.MatrixSet sympy.sets.conditionset.ConditionSet Rationals Naturals Integers sympy.sets.fancysets.ImageSet sympy.sets.fancysets.Range sympy.sets.fancysets.ComplexRegion sympy.sets.powerset.PowerSet sympy.sets.sets.ProductSet sympy.sets.sets.Interval sympy.sets.sets.Union sympy.sets.sets.Intersection sympy.sets.sets.Complement sympy.sets.sets.EmptySet sympy.sets.sets.UniversalSet sympy.sets.sets.FiniteSet sympy.sets.sets.SymmetricDifference sympy.sets.sets.DisjointUnion """ return self._kind() @property def boundary(self): """ The boundary or frontier of a set. Explanation =========== A point x is on the boundary of a set S if 1. x is in the closure of S. I.e. Every neighborhood of x contains a point in S. 2. x is not in the interior of S. I.e. There does not exist an open set centered on x contained entirely within S. There are the points on the outer rim of S. If S is open then these points need not actually be contained within S. For example, the boundary of an interval is its start and end points. This is true regardless of whether or not the interval is open. Examples ======== >>> from sympy import Interval >>> Interval(0, 1).boundary {0, 1} >>> Interval(0, 1, True, False).boundary {0, 1} """ return self._boundary @property def is_open(self): """ Property method to check whether a set is open. Explanation =========== A set is open if and only if it has an empty intersection with its boundary. In particular, a subset A of the reals is open if and only if each one of its points is contained in an open interval that is a subset of A. Examples ======== >>> from sympy import S >>> S.Reals.is_open True >>> S.Rationals.is_open False """ return Intersection(self, self.boundary).is_empty @property def is_closed(self): """ A property method to check whether a set is closed. Explanation =========== A set is closed if its complement is an open set. The closedness of a subset of the reals is determined with respect to R and its standard topology. Examples ======== >>> from sympy import Interval >>> Interval(0, 1).is_closed True """ return self.boundary.is_subset(self) @property def closure(self): """ Property method which returns the closure of a set. The closure is defined as the union of the set itself and its boundary. Examples ======== >>> from sympy import S, Interval >>> S.Reals.closure Reals >>> Interval(0, 1).closure Interval(0, 1) """ return self + self.boundary @property def interior(self): """ Property method which returns the interior of a set. The interior of a set S consists all points of S that do not belong to the boundary of S. Examples ======== >>> from sympy import Interval >>> Interval(0, 1).interior Interval.open(0, 1) >>> Interval(0, 1).boundary.interior EmptySet """ return self - self.boundary @property def _boundary(self): raise NotImplementedError() @property def _measure(self): raise NotImplementedError("(%s)._measure" % self) def _kind(self): return SetKind(UndefinedKind) def _eval_evalf(self, prec): dps = prec_to_dps(prec) return self.func(*[arg.evalf(n=dps) for arg in self.args]) @sympify_return([('other', 'Set')], NotImplemented) def __add__(self, other): return self.union(other) @sympify_return([('other', 'Set')], NotImplemented) def __or__(self, other): return self.union(other) @sympify_return([('other', 'Set')], NotImplemented) def __and__(self, other): return self.intersect(other) @sympify_return([('other', 'Set')], NotImplemented) def __mul__(self, other): return ProductSet(self, other) @sympify_return([('other', 'Set')], NotImplemented) def __xor__(self, other): return SymmetricDifference(self, other) @sympify_return([('exp', Expr)], NotImplemented) def __pow__(self, exp): if not (exp.is_Integer and exp >= 0): raise ValueError("%s: Exponent must be a positive Integer" % exp) return ProductSet(*[self]*exp) @sympify_return([('other', 'Set')], NotImplemented) def __sub__(self, other): return Complement(self, other) def __contains__(self, other): other = _sympify(other) c = self._contains(other) b = tfn[c] if b is None: # x in y must evaluate to T or F; to entertain a None # result with Set use y.contains(x) raise TypeError('did not evaluate to a bool: %r' % c) return b class ProductSet(Set): """ Represents a Cartesian Product of Sets. Explanation =========== Returns a Cartesian product given several sets as either an iterable or individual arguments. Can use ``*`` operator on any sets for convenient shorthand. Examples ======== >>> from sympy import Interval, FiniteSet, ProductSet >>> I = Interval(0, 5); S = FiniteSet(1, 2, 3) >>> ProductSet(I, S) ProductSet(Interval(0, 5), {1, 2, 3}) >>> (2, 2) in ProductSet(I, S) True >>> Interval(0, 1) * Interval(0, 1) # The unit square ProductSet(Interval(0, 1), Interval(0, 1)) >>> coin = FiniteSet('H', 'T') >>> set(coin**2) {(H, H), (H, T), (T, H), (T, T)} The Cartesian product is not commutative or associative e.g.: >>> I*S == S*I False >>> (I*I)*I == I*(I*I) False Notes ===== - Passes most operations down to the argument sets References ========== .. [1] https://en.wikipedia.org/wiki/Cartesian_product """ is_ProductSet = True def __new__(cls, *sets, **assumptions): if len(sets) == 1 and iterable(sets[0]) and not isinstance(sets[0], (Set, set)): sympy_deprecation_warning( """ ProductSet(iterable) is deprecated. Use ProductSet(*iterable) instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-productset-iterable", ) sets = tuple(sets[0]) sets = [sympify(s) for s in sets] if not all(isinstance(s, Set) for s in sets): raise TypeError("Arguments to ProductSet should be of type Set") # Nullary product of sets is *not* the empty set if len(sets) == 0: return FiniteSet(()) if S.EmptySet in sets: return S.EmptySet return Basic.__new__(cls, *sets, **assumptions) @property def sets(self): return self.args def flatten(self): def _flatten(sets): for s in sets: if s.is_ProductSet: yield from _flatten(s.sets) else: yield s return ProductSet(*_flatten(self.sets)) def _contains(self, element): """ ``in`` operator for ProductSets. Examples ======== >>> from sympy import Interval >>> (2, 3) in Interval(0, 5) * Interval(0, 5) True >>> (10, 10) in Interval(0, 5) * Interval(0, 5) False Passes operation on to constituent sets """ if element.is_Symbol: return None if not isinstance(element, Tuple) or len(element) != len(self.sets): return False return fuzzy_and(s._contains(e) for s, e in zip(self.sets, element)) def as_relational(self, *symbols): symbols = [_sympify(s) for s in symbols] if len(symbols) != len(self.sets) or not all( i.is_Symbol for i in symbols): raise ValueError( 'number of symbols must match the number of sets') return And(*[s.as_relational(i) for s, i in zip(self.sets, symbols)]) @property def _boundary(self): return Union(*(ProductSet(*(b + b.boundary if i != j else b.boundary for j, b in enumerate(self.sets))) for i, a in enumerate(self.sets))) @property def is_iterable(self): """ A property method which tests whether a set is iterable or not. Returns True if set is iterable, otherwise returns False. Examples ======== >>> from sympy import FiniteSet, Interval >>> I = Interval(0, 1) >>> A = FiniteSet(1, 2, 3, 4, 5) >>> I.is_iterable False >>> A.is_iterable True """ return all(set.is_iterable for set in self.sets) def __iter__(self): """ A method which implements is_iterable property method. If self.is_iterable returns True (both constituent sets are iterable), then return the Cartesian Product. Otherwise, raise TypeError. """ return iproduct(*self.sets) @property def is_empty(self): return fuzzy_or(s.is_empty for s in self.sets) @property def is_finite_set(self): all_finite = fuzzy_and(s.is_finite_set for s in self.sets) return fuzzy_or([self.is_empty, all_finite]) @property def _measure(self): measure = 1 for s in self.sets: measure *= s.measure return measure def _kind(self): return SetKind(TupleKind(*(i.kind.element_kind for i in self.args))) def __len__(self): return reduce(lambda a, b: a*b, (len(s) for s in self.args)) def __bool__(self): return all(self.sets) class Interval(Set): """ Represents a real interval as a Set. Usage: Returns an interval with end points ``start`` and ``end``. For ``left_open=True`` (default ``left_open`` is ``False``) the interval will be open on the left. Similarly, for ``right_open=True`` the interval will be open on the right. Examples ======== >>> from sympy import Symbol, Interval >>> Interval(0, 1) Interval(0, 1) >>> Interval.Ropen(0, 1) Interval.Ropen(0, 1) >>> Interval.Ropen(0, 1) Interval.Ropen(0, 1) >>> Interval.Lopen(0, 1) Interval.Lopen(0, 1) >>> Interval.open(0, 1) Interval.open(0, 1) >>> a = Symbol('a', real=True) >>> Interval(0, a) Interval(0, a) Notes ===== - Only real end points are supported - ``Interval(a, b)`` with $a > b$ will return the empty set - Use the ``evalf()`` method to turn an Interval into an mpmath ``mpi`` interval instance References ========== .. [1] https://en.wikipedia.org/wiki/Interval_%28mathematics%29 """ is_Interval = True def __new__(cls, start, end, left_open=False, right_open=False): start = _sympify(start) end = _sympify(end) left_open = _sympify(left_open) right_open = _sympify(right_open) if not all(isinstance(a, (type(true), type(false))) for a in [left_open, right_open]): raise NotImplementedError( "left_open and right_open can have only true/false values, " "got %s and %s" % (left_open, right_open)) # Only allow real intervals if fuzzy_not(fuzzy_and(i.is_extended_real for i in (start, end, end-start))): raise ValueError("Non-real intervals are not supported") # evaluate if possible if is_lt(end, start): return S.EmptySet elif (end - start).is_negative: return S.EmptySet if end == start and (left_open or right_open): return S.EmptySet if end == start and not (left_open or right_open): if start is S.Infinity or start is S.NegativeInfinity: return S.EmptySet return FiniteSet(end) # Make sure infinite interval end points are open. if start is S.NegativeInfinity: left_open = true if end is S.Infinity: right_open = true if start == S.Infinity or end == S.NegativeInfinity: return S.EmptySet return Basic.__new__(cls, start, end, left_open, right_open) @property def start(self): """ The left end point of the interval. This property takes the same value as the ``inf`` property. Examples ======== >>> from sympy import Interval >>> Interval(0, 1).start 0 """ return self._args[0] @property def end(self): """ The right end point of the interval. This property takes the same value as the ``sup`` property. Examples ======== >>> from sympy import Interval >>> Interval(0, 1).end 1 """ return self._args[1] @property def left_open(self): """ True if interval is left-open. Examples ======== >>> from sympy import Interval >>> Interval(0, 1, left_open=True).left_open True >>> Interval(0, 1, left_open=False).left_open False """ return self._args[2] @property def right_open(self): """ True if interval is right-open. Examples ======== >>> from sympy import Interval >>> Interval(0, 1, right_open=True).right_open True >>> Interval(0, 1, right_open=False).right_open False """ return self._args[3] @classmethod def open(cls, a, b): """Return an interval including neither boundary.""" return cls(a, b, True, True) @classmethod def Lopen(cls, a, b): """Return an interval not including the left boundary.""" return cls(a, b, True, False) @classmethod def Ropen(cls, a, b): """Return an interval not including the right boundary.""" return cls(a, b, False, True) @property def _inf(self): return self.start @property def _sup(self): return self.end @property def left(self): return self.start @property def right(self): return self.end @property def is_empty(self): if self.left_open or self.right_open: cond = self.start >= self.end # One/both bounds open else: cond = self.start > self.end # Both bounds closed return fuzzy_bool(cond) @property def is_finite_set(self): return self.measure.is_zero def _complement(self, other): if other == S.Reals: a = Interval(S.NegativeInfinity, self.start, True, not self.left_open) b = Interval(self.end, S.Infinity, not self.right_open, True) return Union(a, b) if isinstance(other, FiniteSet): nums = [m for m in other.args if m.is_number] if nums == []: return None return Set._complement(self, other) @property def _boundary(self): finite_points = [p for p in (self.start, self.end) if abs(p) != S.Infinity] return FiniteSet(*finite_points) def _contains(self, other): if (not isinstance(other, Expr) or other is S.NaN or other.is_real is False or other.has(S.ComplexInfinity)): # if an expression has zoo it will be zoo or nan # and neither of those is real return false if self.start is S.NegativeInfinity and self.end is S.Infinity: if other.is_real is not None: return other.is_real d = Dummy() return self.as_relational(d).subs(d, other) def as_relational(self, x): """Rewrite an interval in terms of inequalities and logic operators.""" x = sympify(x) if self.right_open: right = x < self.end else: right = x <= self.end if self.left_open: left = self.start < x else: left = self.start <= x return And(left, right) @property def _measure(self): return self.end - self.start def _kind(self): return SetKind(NumberKind) def to_mpi(self, prec=53): return mpi(mpf(self.start._eval_evalf(prec)), mpf(self.end._eval_evalf(prec))) def _eval_evalf(self, prec): return Interval(self.left._evalf(prec), self.right._evalf(prec), left_open=self.left_open, right_open=self.right_open) def _is_comparable(self, other): is_comparable = self.start.is_comparable is_comparable &= self.end.is_comparable is_comparable &= other.start.is_comparable is_comparable &= other.end.is_comparable return is_comparable @property def is_left_unbounded(self): """Return ``True`` if the left endpoint is negative infinity. """ return self.left is S.NegativeInfinity or self.left == Float("-inf") @property def is_right_unbounded(self): """Return ``True`` if the right endpoint is positive infinity. """ return self.right is S.Infinity or self.right == Float("+inf") def _eval_Eq(self, other): if not isinstance(other, Interval): if isinstance(other, FiniteSet): return false elif isinstance(other, Set): return None return false class Union(Set, LatticeOp): """ Represents a union of sets as a :class:`Set`. Examples ======== >>> from sympy import Union, Interval >>> Union(Interval(1, 2), Interval(3, 4)) Union(Interval(1, 2), Interval(3, 4)) The Union constructor will always try to merge overlapping intervals, if possible. For example: >>> Union(Interval(1, 2), Interval(2, 3)) Interval(1, 3) See Also ======== Intersection References ========== .. [1] https://en.wikipedia.org/wiki/Union_%28set_theory%29 """ is_Union = True @property def identity(self): return S.EmptySet @property def zero(self): return S.UniversalSet def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) # flatten inputs to merge intersections and iterables args = _sympify(args) # Reduce sets using known rules if evaluate: args = list(cls._new_args_filter(args)) return simplify_union(args) args = list(ordered(args, Set._infimum_key)) obj = Basic.__new__(cls, *args) obj._argset = frozenset(args) return obj @property def args(self): return self._args def _complement(self, universe): # DeMorgan's Law return Intersection(s.complement(universe) for s in self.args) @property def _inf(self): # We use Min so that sup is meaningful in combination with symbolic # interval end points. return Min(*[set.inf for set in self.args]) @property def _sup(self): # We use Max so that sup is meaningful in combination with symbolic # end points. return Max(*[set.sup for set in self.args]) @property def is_empty(self): return fuzzy_and(set.is_empty for set in self.args) @property def is_finite_set(self): return fuzzy_and(set.is_finite_set for set in self.args) @property def _measure(self): # Measure of a union is the sum of the measures of the sets minus # the sum of their pairwise intersections plus the sum of their # triple-wise intersections minus ... etc... # Sets is a collection of intersections and a set of elementary # sets which made up those intersections (called "sos" for set of sets) # An example element might of this list might be: # ( {A,B,C}, A.intersect(B).intersect(C) ) # Start with just elementary sets ( ({A}, A), ({B}, B), ... ) # Then get and subtract ( ({A,B}, (A int B), ... ) while non-zero sets = [(FiniteSet(s), s) for s in self.args] measure = 0 parity = 1 while sets: # Add up the measure of these sets and add or subtract it to total measure += parity * sum(inter.measure for sos, inter in sets) # For each intersection in sets, compute the intersection with every # other set not already part of the intersection. sets = ((sos + FiniteSet(newset), newset.intersect(intersection)) for sos, intersection in sets for newset in self.args if newset not in sos) # Clear out sets with no measure sets = [(sos, inter) for sos, inter in sets if inter.measure != 0] # Clear out duplicates sos_list = [] sets_list = [] for _set in sets: if _set[0] in sos_list: continue else: sos_list.append(_set[0]) sets_list.append(_set) sets = sets_list # Flip Parity - next time subtract/add if we added/subtracted here parity *= -1 return measure def _kind(self): kinds = tuple(arg.kind for arg in self.args if arg is not S.EmptySet) if not kinds: return SetKind() elif all(i == kinds[0] for i in kinds): return kinds[0] else: return SetKind(UndefinedKind) @property def _boundary(self): def boundary_of_set(i): """ The boundary of set i minus interior of all other sets """ b = self.args[i].boundary for j, a in enumerate(self.args): if j != i: b = b - a.interior return b return Union(*map(boundary_of_set, range(len(self.args)))) def _contains(self, other): return Or(*[s.contains(other) for s in self.args]) def is_subset(self, other): return fuzzy_and(s.is_subset(other) for s in self.args) def as_relational(self, symbol): """Rewrite a Union in terms of equalities and logic operators. """ if (len(self.args) == 2 and all(isinstance(i, Interval) for i in self.args)): # optimization to give 3 args as (x > 1) & (x < 5) & Ne(x, 3) # instead of as 4, ((1 <= x) & (x < 3)) | ((x <= 5) & (3 < x)) a, b = self.args if (a.sup == b.inf and not any(a.sup in i for i in self.args)): return And(Ne(symbol, a.sup), symbol < b.sup, symbol > a.inf) return Or(*[i.as_relational(symbol) for i in self.args]) @property def is_iterable(self): return all(arg.is_iterable for arg in self.args) def __iter__(self): return roundrobin(*(iter(arg) for arg in self.args)) class Intersection(Set, LatticeOp): """ Represents an intersection of sets as a :class:`Set`. Examples ======== >>> from sympy import Intersection, Interval >>> Intersection(Interval(1, 3), Interval(2, 4)) Interval(2, 3) We often use the .intersect method >>> Interval(1,3).intersect(Interval(2,4)) Interval(2, 3) See Also ======== Union References ========== .. [1] https://en.wikipedia.org/wiki/Intersection_%28set_theory%29 """ is_Intersection = True @property def identity(self): return S.UniversalSet @property def zero(self): return S.EmptySet def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) # flatten inputs to merge intersections and iterables args = list(ordered(set(_sympify(args)))) # Reduce sets using known rules if evaluate: args = list(cls._new_args_filter(args)) return simplify_intersection(args) args = list(ordered(args, Set._infimum_key)) obj = Basic.__new__(cls, *args) obj._argset = frozenset(args) return obj @property def args(self): return self._args @property def is_iterable(self): return any(arg.is_iterable for arg in self.args) @property def is_finite_set(self): if fuzzy_or(arg.is_finite_set for arg in self.args): return True def _kind(self): kinds = tuple(arg.kind for arg in self.args if arg is not S.UniversalSet) if not kinds: return SetKind(UndefinedKind) elif all(i == kinds[0] for i in kinds): return kinds[0] else: return SetKind() @property def _inf(self): raise NotImplementedError() @property def _sup(self): raise NotImplementedError() def _contains(self, other): return And(*[set.contains(other) for set in self.args]) def __iter__(self): sets_sift = sift(self.args, lambda x: x.is_iterable) completed = False candidates = sets_sift[True] + sets_sift[None] finite_candidates, others = [], [] for candidate in candidates: length = None try: length = len(candidate) except TypeError: others.append(candidate) if length is not None: finite_candidates.append(candidate) finite_candidates.sort(key=len) for s in finite_candidates + others: other_sets = set(self.args) - {s} other = Intersection(*other_sets, evaluate=False) completed = True for x in s: try: if x in other: yield x except TypeError: completed = False if completed: return if not completed: if not candidates: raise TypeError("None of the constituent sets are iterable") raise TypeError( "The computation had not completed because of the " "undecidable set membership is found in every candidates.") @staticmethod def _handle_finite_sets(args): '''Simplify intersection of one or more FiniteSets and other sets''' # First separate the FiniteSets from the others fs_args, others = sift(args, lambda x: x.is_FiniteSet, binary=True) # Let the caller handle intersection of non-FiniteSets if not fs_args: return # Convert to Python sets and build the set of all elements fs_sets = [set(fs) for fs in fs_args] all_elements = reduce(lambda a, b: a | b, fs_sets, set()) # Extract elements that are definitely in or definitely not in the # intersection. Here we check contains for all of args. definite = set() for e in all_elements: inall = fuzzy_and(s.contains(e) for s in args) if inall is True: definite.add(e) if inall is not None: for s in fs_sets: s.discard(e) # At this point all elements in all of fs_sets are possibly in the # intersection. In some cases this is because they are definitely in # the intersection of the finite sets but it's not clear if they are # members of others. We might have {m, n}, {m}, and Reals where we # don't know if m or n is real. We want to remove n here but it is # possibly in because it might be equal to m. So what we do now is # extract the elements that are definitely in the remaining finite # sets iteratively until we end up with {n}, {}. At that point if we # get any empty set all remaining elements are discarded. fs_elements = reduce(lambda a, b: a | b, fs_sets, set()) # Need fuzzy containment testing fs_symsets = [FiniteSet(*s) for s in fs_sets] while fs_elements: for e in fs_elements: infs = fuzzy_and(s.contains(e) for s in fs_symsets) if infs is True: definite.add(e) if infs is not None: for n, s in enumerate(fs_sets): # Update Python set and FiniteSet if e in s: s.remove(e) fs_symsets[n] = FiniteSet(*s) fs_elements.remove(e) break # If we completed the for loop without removing anything we are # done so quit the outer while loop else: break # If any of the sets of remainder elements is empty then we discard # all of them for the intersection. if not all(fs_sets): fs_sets = [set()] # Here we fold back the definitely included elements into each fs. # Since they are definitely included they must have been members of # each FiniteSet to begin with. We could instead fold these in with a # Union at the end to get e.g. {3}|({x}&{y}) rather than {3,x}&{3,y}. if definite: fs_sets = [fs | definite for fs in fs_sets] if fs_sets == [set()]: return S.EmptySet sets = [FiniteSet(*s) for s in fs_sets] # Any set in others is redundant if it contains all the elements that # are in the finite sets so we don't need it in the Intersection all_elements = reduce(lambda a, b: a | b, fs_sets, set()) is_redundant = lambda o: all(fuzzy_bool(o.contains(e)) for e in all_elements) others = [o for o in others if not is_redundant(o)] if others: rest = Intersection(*others) # XXX: Maybe this shortcut should be at the beginning. For large # FiniteSets it could much more efficient to process the other # sets first... if rest is S.EmptySet: return S.EmptySet # Flatten the Intersection if rest.is_Intersection: sets.extend(rest.args) else: sets.append(rest) if len(sets) == 1: return sets[0] else: return Intersection(*sets, evaluate=False) def as_relational(self, symbol): """Rewrite an Intersection in terms of equalities and logic operators""" return And(*[set.as_relational(symbol) for set in self.args]) class Complement(Set): r"""Represents the set difference or relative complement of a set with another set. $$A - B = \{x \in A \mid x \notin B\}$$ Examples ======== >>> from sympy import Complement, FiniteSet >>> Complement(FiniteSet(0, 1, 2), FiniteSet(1)) {0, 2} See Also ========= Intersection, Union References ========== .. [1] http://mathworld.wolfram.com/ComplementSet.html """ is_Complement = True def __new__(cls, a, b, evaluate=True): a, b = map(_sympify, (a, b)) if evaluate: return Complement.reduce(a, b) return Basic.__new__(cls, a, b) @staticmethod def reduce(A, B): """ Simplify a :class:`Complement`. """ if B == S.UniversalSet or A.is_subset(B): return S.EmptySet if isinstance(B, Union): return Intersection(*(s.complement(A) for s in B.args)) result = B._complement(A) if result is not None: return result else: return Complement(A, B, evaluate=False) def _contains(self, other): A = self.args[0] B = self.args[1] return And(A.contains(other), Not(B.contains(other))) def as_relational(self, symbol): """Rewrite a complement in terms of equalities and logic operators""" A, B = self.args A_rel = A.as_relational(symbol) B_rel = Not(B.as_relational(symbol)) return And(A_rel, B_rel) def _kind(self): return self.args[0].kind @property def is_iterable(self): if self.args[0].is_iterable: return True @property def is_finite_set(self): A, B = self.args a_finite = A.is_finite_set if a_finite is True: return True elif a_finite is False and B.is_finite_set: return False def __iter__(self): A, B = self.args for a in A: if a not in B: yield a else: continue class EmptySet(Set, metaclass=Singleton): """ Represents the empty set. The empty set is available as a singleton as ``S.EmptySet``. Examples ======== >>> from sympy import S, Interval >>> S.EmptySet EmptySet >>> Interval(1, 2).intersect(S.EmptySet) EmptySet See Also ======== UniversalSet References ========== .. [1] https://en.wikipedia.org/wiki/Empty_set """ is_empty = True is_finite_set = True is_FiniteSet = True @property # type: ignore @deprecated( """ The is_EmptySet attribute of Set objects is deprecated. Use 's is S.EmptySet" or 's.is_empty' instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-is-emptyset", ) def is_EmptySet(self): return True @property def _measure(self): return 0 def _contains(self, other): return false def as_relational(self, symbol): return false def __len__(self): return 0 def __iter__(self): return iter([]) def _eval_powerset(self): return FiniteSet(self) @property def _boundary(self): return self def _complement(self, other): return other def _kind(self): return SetKind() def _symmetric_difference(self, other): return other class UniversalSet(Set, metaclass=Singleton): """ Represents the set of all things. The universal set is available as a singleton as ``S.UniversalSet``. Examples ======== >>> from sympy import S, Interval >>> S.UniversalSet UniversalSet >>> Interval(1, 2).intersect(S.UniversalSet) Interval(1, 2) See Also ======== EmptySet References ========== .. [1] https://en.wikipedia.org/wiki/Universal_set """ is_UniversalSet = True is_empty = False is_finite_set = False def _complement(self, other): return S.EmptySet def _symmetric_difference(self, other): return other @property def _measure(self): return S.Infinity def _kind(self): return SetKind(UndefinedKind) def _contains(self, other): return true def as_relational(self, symbol): return true @property def _boundary(self): return S.EmptySet class FiniteSet(Set): """ Represents a finite set of discrete numbers. Examples ======== >>> from sympy import FiniteSet >>> FiniteSet(1, 2, 3, 4) {1, 2, 3, 4} >>> 3 in FiniteSet(1, 2, 3, 4) True >>> members = [1, 2, 3, 4] >>> f = FiniteSet(*members) >>> f {1, 2, 3, 4} >>> f - FiniteSet(2) {1, 3, 4} >>> f + FiniteSet(2, 5) {1, 2, 3, 4, 5} References ========== .. [1] https://en.wikipedia.org/wiki/Finite_set """ is_FiniteSet = True is_iterable = True is_empty = False is_finite_set = True def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) if evaluate: args = list(map(sympify, args)) if len(args) == 0: return S.EmptySet else: args = list(map(sympify, args)) # keep the form of the first canonical arg dargs = {} for i in reversed(list(ordered(args))): if i.is_Symbol: dargs[i] = i else: try: dargs[i.as_dummy()] = i except TypeError: # e.g. i = class without args like `Interval` dargs[i] = i _args_set = set(dargs.values()) args = list(ordered(_args_set, Set._infimum_key)) obj = Basic.__new__(cls, *args) obj._args_set = _args_set return obj def __iter__(self): return iter(self.args) def _complement(self, other): if isinstance(other, Interval): # Splitting in sub-intervals is only done for S.Reals; # other cases that need splitting will first pass through # Set._complement(). nums, syms = [], [] for m in self.args: if m.is_number and m.is_real: nums.append(m) elif m.is_real == False: pass # drop non-reals else: syms.append(m) # various symbolic expressions if other == S.Reals and nums != []: nums.sort() intervals = [] # Build up a list of intervals between the elements intervals += [Interval(S.NegativeInfinity, nums[0], True, True)] for a, b in zip(nums[:-1], nums[1:]): intervals.append(Interval(a, b, True, True)) # both open intervals.append(Interval(nums[-1], S.Infinity, True, True)) if syms != []: return Complement(Union(*intervals, evaluate=False), FiniteSet(*syms), evaluate=False) else: return Union(*intervals, evaluate=False) elif nums == []: # no splitting necessary or possible: if syms: return Complement(other, FiniteSet(*syms), evaluate=False) else: return other elif isinstance(other, FiniteSet): unk = [] for i in self: c = sympify(other.contains(i)) if c is not S.true and c is not S.false: unk.append(i) unk = FiniteSet(*unk) if unk == self: return not_true = [] for i in other: c = sympify(self.contains(i)) if c is not S.true: not_true.append(i) return Complement(FiniteSet(*not_true), unk) return Set._complement(self, other) def _contains(self, other): """ Tests whether an element, other, is in the set. Explanation =========== The actual test is for mathematical equality (as opposed to syntactical equality). In the worst case all elements of the set must be checked. Examples ======== >>> from sympy import FiniteSet >>> 1 in FiniteSet(1, 2) True >>> 5 in FiniteSet(1, 2) False """ if other in self._args_set: return True else: # evaluate=True is needed to override evaluate=False context; # we need Eq to do the evaluation return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True)) for e in self.args) def _eval_is_subset(self, other): return fuzzy_and(other._contains(e) for e in self.args) @property def _boundary(self): return self @property def _inf(self): return Min(*self) @property def _sup(self): return Max(*self) @property def measure(self): return 0 def _kind(self): if not self.args: return SetKind() elif all(i.kind == self.args[0].kind for i in self.args): return SetKind(self.args[0].kind) else: return SetKind(UndefinedKind) def __len__(self): return len(self.args) def as_relational(self, symbol): """Rewrite a FiniteSet in terms of equalities and logic operators. """ return Or(*[Eq(symbol, elem) for elem in self]) def compare(self, other): return (hash(self) - hash(other)) def _eval_evalf(self, prec): dps = prec_to_dps(prec) return FiniteSet(*[elem.evalf(n=dps) for elem in self]) def _eval_simplify(self, **kwargs): from sympy.simplify import simplify return FiniteSet(*[simplify(elem, **kwargs) for elem in self]) @property def _sorted_args(self): return self.args def _eval_powerset(self): return self.func(*[self.func(*s) for s in subsets(self.args)]) def _eval_rewrite_as_PowerSet(self, *args, **kwargs): """Rewriting method for a finite set to a power set.""" from .powerset import PowerSet is2pow = lambda n: bool(n and not n & (n - 1)) if not is2pow(len(self)): return None fs_test = lambda arg: isinstance(arg, Set) and arg.is_FiniteSet if not all(fs_test(arg) for arg in args): return None biggest = max(args, key=len) for arg in subsets(biggest.args): arg_set = FiniteSet(*arg) if arg_set not in args: return None return PowerSet(biggest) def __ge__(self, other): if not isinstance(other, Set): raise TypeError("Invalid comparison of set with %s" % func_name(other)) return other.is_subset(self) def __gt__(self, other): if not isinstance(other, Set): raise TypeError("Invalid comparison of set with %s" % func_name(other)) return self.is_proper_superset(other) def __le__(self, other): if not isinstance(other, Set): raise TypeError("Invalid comparison of set with %s" % func_name(other)) return self.is_subset(other) def __lt__(self, other): if not isinstance(other, Set): raise TypeError("Invalid comparison of set with %s" % func_name(other)) return self.is_proper_subset(other) def __eq__(self, other): if isinstance(other, (set, frozenset)): return self._args_set == other return super().__eq__(other) __hash__ : Callable[[Basic], Any] = Basic.__hash__ _sympy_converter[set] = lambda x: FiniteSet(*x) _sympy_converter[frozenset] = lambda x: FiniteSet(*x) class SymmetricDifference(Set): """Represents the set of elements which are in either of the sets and not in their intersection. Examples ======== >>> from sympy import SymmetricDifference, FiniteSet >>> SymmetricDifference(FiniteSet(1, 2, 3), FiniteSet(3, 4, 5)) {1, 2, 4, 5} See Also ======== Complement, Union References ========== .. [1] https://en.wikipedia.org/wiki/Symmetric_difference """ is_SymmetricDifference = True def __new__(cls, a, b, evaluate=True): if evaluate: return SymmetricDifference.reduce(a, b) return Basic.__new__(cls, a, b) @staticmethod def reduce(A, B): result = B._symmetric_difference(A) if result is not None: return result else: return SymmetricDifference(A, B, evaluate=False) def as_relational(self, symbol): """Rewrite a symmetric_difference in terms of equalities and logic operators""" A, B = self.args A_rel = A.as_relational(symbol) B_rel = B.as_relational(symbol) return Xor(A_rel, B_rel) @property def is_iterable(self): if all(arg.is_iterable for arg in self.args): return True def __iter__(self): args = self.args union = roundrobin(*(iter(arg) for arg in args)) for item in union: count = 0 for s in args: if item in s: count += 1 if count % 2 == 1: yield item class DisjointUnion(Set): """ Represents the disjoint union (also known as the external disjoint union) of a finite number of sets. Examples ======== >>> from sympy import DisjointUnion, FiniteSet, Interval, Union, Symbol >>> A = FiniteSet(1, 2, 3) >>> B = Interval(0, 5) >>> DisjointUnion(A, B) DisjointUnion({1, 2, 3}, Interval(0, 5)) >>> DisjointUnion(A, B).rewrite(Union) Union(ProductSet({1, 2, 3}, {0}), ProductSet(Interval(0, 5), {1})) >>> C = FiniteSet(Symbol('x'), Symbol('y'), Symbol('z')) >>> DisjointUnion(C, C) DisjointUnion({x, y, z}, {x, y, z}) >>> DisjointUnion(C, C).rewrite(Union) ProductSet({x, y, z}, {0, 1}) References ========== https://en.wikipedia.org/wiki/Disjoint_union """ def __new__(cls, *sets): dj_collection = [] for set_i in sets: if isinstance(set_i, Set): dj_collection.append(set_i) else: raise TypeError("Invalid input: '%s', input args \ to DisjointUnion must be Sets" % set_i) obj = Basic.__new__(cls, *dj_collection) return obj @property def sets(self): return self.args @property def is_empty(self): return fuzzy_and(s.is_empty for s in self.sets) @property def is_finite_set(self): all_finite = fuzzy_and(s.is_finite_set for s in self.sets) return fuzzy_or([self.is_empty, all_finite]) @property def is_iterable(self): if self.is_empty: return False iter_flag = True for set_i in self.sets: if not set_i.is_empty: iter_flag = iter_flag and set_i.is_iterable return iter_flag def _eval_rewrite_as_Union(self, *sets): """ Rewrites the disjoint union as the union of (``set`` x {``i``}) where ``set`` is the element in ``sets`` at index = ``i`` """ dj_union = S.EmptySet index = 0 for set_i in sets: if isinstance(set_i, Set): cross = ProductSet(set_i, FiniteSet(index)) dj_union = Union(dj_union, cross) index = index + 1 return dj_union def _contains(self, element): """ ``in`` operator for DisjointUnion Examples ======== >>> from sympy import Interval, DisjointUnion >>> D = DisjointUnion(Interval(0, 1), Interval(0, 2)) >>> (0.5, 0) in D True >>> (0.5, 1) in D True >>> (1.5, 0) in D False >>> (1.5, 1) in D True Passes operation on to constituent sets """ if not isinstance(element, Tuple) or len(element) != 2: return False if not element[1].is_Integer: return False if element[1] >= len(self.sets) or element[1] < 0: return False return element[0] in self.sets[element[1]] def _kind(self): if not self.args: return SetKind() elif all(i.kind == self.args[0].kind for i in self.args): return self.args[0].kind else: return SetKind(UndefinedKind) def __iter__(self): if self.is_iterable: iters = [] for i, s in enumerate(self.sets): iters.append(iproduct(s, {Integer(i)})) return iter(roundrobin(*iters)) else: raise ValueError("'%s' is not iterable." % self) def __len__(self): """ Returns the length of the disjoint union, i.e., the number of elements in the set. Examples ======== >>> from sympy import FiniteSet, DisjointUnion, EmptySet >>> D1 = DisjointUnion(FiniteSet(1, 2, 3, 4), EmptySet, FiniteSet(3, 4, 5)) >>> len(D1) 7 >>> D2 = DisjointUnion(FiniteSet(3, 5, 7), EmptySet, FiniteSet(3, 5, 7)) >>> len(D2) 6 >>> D3 = DisjointUnion(EmptySet, EmptySet) >>> len(D3) 0 Adds up the lengths of the constituent sets. """ if self.is_finite_set: size = 0 for set in self.sets: size += len(set) return size else: raise ValueError("'%s' is not a finite set." % self) def imageset(*args): r""" Return an image of the set under transformation ``f``. Explanation =========== If this function cannot compute the image, it returns an unevaluated ImageSet object. .. math:: \{ f(x) \mid x \in \mathrm{self} \} Examples ======== >>> from sympy import S, Interval, imageset, sin, Lambda >>> from sympy.abc import x >>> imageset(x, 2*x, Interval(0, 2)) Interval(0, 4) >>> imageset(lambda x: 2*x, Interval(0, 2)) Interval(0, 4) >>> imageset(Lambda(x, sin(x)), Interval(-2, 1)) ImageSet(Lambda(x, sin(x)), Interval(-2, 1)) >>> imageset(sin, Interval(-2, 1)) ImageSet(Lambda(x, sin(x)), Interval(-2, 1)) >>> imageset(lambda y: x + y, Interval(-2, 1)) ImageSet(Lambda(y, x + y), Interval(-2, 1)) Expressions applied to the set of Integers are simplified to show as few negatives as possible and linear expressions are converted to a canonical form. If this is not desirable then the unevaluated ImageSet should be used. >>> imageset(x, -2*x + 5, S.Integers) ImageSet(Lambda(x, 2*x + 1), Integers) See Also ======== sympy.sets.fancysets.ImageSet """ from .fancysets import ImageSet from .setexpr import set_function if len(args) < 2: raise ValueError('imageset expects at least 2 args, got: %s' % len(args)) if isinstance(args[0], (Symbol, tuple)) and len(args) > 2: f = Lambda(args[0], args[1]) set_list = args[2:] else: f = args[0] set_list = args[1:] if isinstance(f, Lambda): pass elif callable(f): nargs = getattr(f, 'nargs', {}) if nargs: if len(nargs) != 1: raise NotImplementedError(filldedent(''' This function can take more than 1 arg but the potentially complicated set input has not been analyzed at this point to know its dimensions. TODO ''')) N = nargs.args[0] if N == 1: s = 'x' else: s = [Symbol('x%i' % i) for i in range(1, N + 1)] else: s = inspect.signature(f).parameters dexpr = _sympify(f(*[Dummy() for i in s])) var = tuple(uniquely_named_symbol( Symbol(i), dexpr) for i in s) f = Lambda(var, f(*var)) else: raise TypeError(filldedent(''' expecting lambda, Lambda, or FunctionClass, not \'%s\'.''' % func_name(f))) if any(not isinstance(s, Set) for s in set_list): name = [func_name(s) for s in set_list] raise ValueError( 'arguments after mapping should be sets, not %s' % name) if len(set_list) == 1: set = set_list[0] try: # TypeError if arg count != set dimensions r = set_function(f, set) if r is None: raise TypeError if not r: return r except TypeError: r = ImageSet(f, set) if isinstance(r, ImageSet): f, set = r.args if f.variables[0] == f.expr: return set if isinstance(set, ImageSet): # XXX: Maybe this should just be: # f2 = set.lambda # fun = Lambda(f2.signature, f(*f2.expr)) # return imageset(fun, *set.base_sets) if len(set.lamda.variables) == 1 and len(f.variables) == 1: x = set.lamda.variables[0] y = f.variables[0] return imageset( Lambda(x, f.expr.subs(y, set.lamda.expr)), *set.base_sets) if r is not None: return r return ImageSet(f, *set_list) def is_function_invertible_in_set(func, setv): """ Checks whether function ``func`` is invertible when the domain is restricted to set ``setv``. """ # Functions known to always be invertible: if func in (exp, log): return True u = Dummy("u") fdiff = func(u).diff(u) # monotonous functions: # TODO: check subsets (`func` in `setv`) if (fdiff > 0) == True or (fdiff < 0) == True: return True # TODO: support more return None def simplify_union(args): """ Simplify a :class:`Union` using known rules. Explanation =========== We first start with global rules like 'Merge all FiniteSets' Then we iterate through all pairs and ask the constituent sets if they can simplify themselves with any other constituent. This process depends on ``union_sets(a, b)`` functions. """ from sympy.sets.handlers.union import union_sets # ===== Global Rules ===== if not args: return S.EmptySet for arg in args: if not isinstance(arg, Set): raise TypeError("Input args to Union must be Sets") # Merge all finite sets finite_sets = [x for x in args if x.is_FiniteSet] if len(finite_sets) > 1: a = (x for set in finite_sets for x in set) finite_set = FiniteSet(*a) args = [finite_set] + [x for x in args if not x.is_FiniteSet] # ===== Pair-wise Rules ===== # Here we depend on rules built into the constituent sets args = set(args) new_args = True while new_args: for s in args: new_args = False for t in args - {s}: new_set = union_sets(s, t) # This returns None if s does not know how to intersect # with t. Returns the newly intersected set otherwise if new_set is not None: if not isinstance(new_set, set): new_set = {new_set} new_args = (args - {s, t}).union(new_set) break if new_args: args = new_args break if len(args) == 1: return args.pop() else: return Union(*args, evaluate=False) def simplify_intersection(args): """ Simplify an intersection using known rules. Explanation =========== We first start with global rules like 'if any empty sets return empty set' and 'distribute any unions' Then we iterate through all pairs and ask the constituent sets if they can simplify themselves with any other constituent """ # ===== Global Rules ===== if not args: return S.UniversalSet for arg in args: if not isinstance(arg, Set): raise TypeError("Input args to Union must be Sets") # If any EmptySets return EmptySet if S.EmptySet in args: return S.EmptySet # Handle Finite sets rv = Intersection._handle_finite_sets(args) if rv is not None: return rv # If any of the sets are unions, return a Union of Intersections for s in args: if s.is_Union: other_sets = set(args) - {s} if len(other_sets) > 0: other = Intersection(*other_sets) return Union(*(Intersection(arg, other) for arg in s.args)) else: return Union(*[arg for arg in s.args]) for s in args: if s.is_Complement: args.remove(s) other_sets = args + [s.args[0]] return Complement(Intersection(*other_sets), s.args[1]) from sympy.sets.handlers.intersection import intersection_sets # At this stage we are guaranteed not to have any # EmptySets, FiniteSets, or Unions in the intersection # ===== Pair-wise Rules ===== # Here we depend on rules built into the constituent sets args = set(args) new_args = True while new_args: for s in args: new_args = False for t in args - {s}: new_set = intersection_sets(s, t) # This returns None if s does not know how to intersect # with t. Returns the newly intersected set otherwise if new_set is not None: new_args = (args - {s, t}).union({new_set}) break if new_args: args = new_args break if len(args) == 1: return args.pop() else: return Intersection(*args, evaluate=False) def _handle_finite_sets(op, x, y, commutative): # Handle finite sets: fs_args, other = sift([x, y], lambda x: isinstance(x, FiniteSet), binary=True) if len(fs_args) == 2: return FiniteSet(*[op(i, j) for i in fs_args[0] for j in fs_args[1]]) elif len(fs_args) == 1: sets = [_apply_operation(op, other[0], i, commutative) for i in fs_args[0]] return Union(*sets) else: return None def _apply_operation(op, x, y, commutative): from .fancysets import ImageSet d = Dummy('d') out = _handle_finite_sets(op, x, y, commutative) if out is None: out = op(x, y) if out is None and commutative: out = op(y, x) if out is None: _x, _y = symbols("x y") if isinstance(x, Set) and not isinstance(y, Set): out = ImageSet(Lambda(d, op(d, y)), x).doit() elif not isinstance(x, Set) and isinstance(y, Set): out = ImageSet(Lambda(d, op(x, d)), y).doit() else: out = ImageSet(Lambda((_x, _y), op(_x, _y)), x, y) return out def set_add(x, y): from sympy.sets.handlers.add import _set_add return _apply_operation(_set_add, x, y, commutative=True) def set_sub(x, y): from sympy.sets.handlers.add import _set_sub return _apply_operation(_set_sub, x, y, commutative=False) def set_mul(x, y): from sympy.sets.handlers.mul import _set_mul return _apply_operation(_set_mul, x, y, commutative=True) def set_div(x, y): from sympy.sets.handlers.mul import _set_div return _apply_operation(_set_div, x, y, commutative=False) def set_pow(x, y): from sympy.sets.handlers.power import _set_pow return _apply_operation(_set_pow, x, y, commutative=False) def set_function(f, x): from sympy.sets.handlers.functions import _set_function return _set_function(f, x) class SetKind(Kind): """ SetKind is kind for all Sets Every instance of Set will have kind ``SetKind`` parametrised by the kind of the elements of the ``Set``. The kind of the elements might be ``NumberKind``, or ``TupleKind`` or something else. When not all elements have the same kind then the kind of the elements will be given as ``UndefinedKind``. Parameters ========== element_kind: Kind (optional) The kind of the elements of the set. In a well defined set all elements will have the same kind. Otherwise the kind should :class:`sympy.core.kind.UndefinedKind`. The ``element_kind`` argument is optional but should only be omitted in the case of ``EmptySet`` whose kind is simply ``SetKind()`` Examples ======== >>> from sympy import Interval >>> Interval(1, 2).kind SetKind(NumberKind) >>> Interval(1,2).kind.element_kind NumberKind See Also ======== sympy.core.kind.NumberKind sympy.matrices.common.MatrixKind sympy.core.containers.TupleKind """ def __new__(cls, element_kind=None): obj = super().__new__(cls, element_kind) obj.element_kind = element_kind return obj def __repr__(self): if not self.element_kind: return "SetKind()" else: return "SetKind(%s)" % self.element_kind
981c71547205b7d51f75d032bf07ddfae56c3397e2b0d512bc174d587e5037f0
from sympy.core.singleton import S from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.function import Lambda, BadSignatureError from sympy.core.logic import fuzzy_bool from sympy.core.relational import Eq from sympy.core.symbol import Dummy from sympy.core.sympify import _sympify from sympy.logic.boolalg import And, as_Boolean from sympy.utilities.iterables import sift, flatten, has_dups from sympy.utilities.exceptions import sympy_deprecation_warning from .contains import Contains from .sets import Set, Union, FiniteSet, SetKind adummy = Dummy('conditionset') class ConditionSet(Set): r""" Set of elements which satisfies a given condition. .. math:: \{x \mid \textrm{condition}(x) = \texttt{True}, x \in S\} Examples ======== >>> from sympy import Symbol, S, ConditionSet, pi, Eq, sin, Interval >>> from sympy.abc import x, y, z >>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi)) >>> 2*pi in sin_sols True >>> pi/2 in sin_sols False >>> 3*pi in sin_sols False >>> 5 in ConditionSet(x, x**2 > 4, S.Reals) True If the value is not in the base set, the result is false: >>> 5 in ConditionSet(x, x**2 > 4, Interval(2, 4)) False Notes ===== Symbols with assumptions should be avoided or else the condition may evaluate without consideration of the set: >>> n = Symbol('n', negative=True) >>> cond = (n > 0); cond False >>> ConditionSet(n, cond, S.Integers) EmptySet Only free symbols can be changed by using `subs`: >>> c = ConditionSet(x, x < 1, {x, z}) >>> c.subs(x, y) ConditionSet(x, x < 1, {y, z}) To check if ``pi`` is in ``c`` use: >>> pi in c False If no base set is specified, the universal set is implied: >>> ConditionSet(x, x < 1).base_set UniversalSet Only symbols or symbol-like expressions can be used: >>> ConditionSet(x + 1, x + 1 < 1, S.Integers) Traceback (most recent call last): ... ValueError: non-symbol dummy not recognized in condition When the base set is a ConditionSet, the symbols will be unified if possible with preference for the outermost symbols: >>> ConditionSet(x, x < y, ConditionSet(z, z + y < 2, S.Integers)) ConditionSet(x, (x < y) & (x + y < 2), Integers) """ def __new__(cls, sym, condition, base_set=S.UniversalSet): 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) sympy_deprecation_warning( f""" Using a set for the condition in ConditionSet is deprecated. Use a boolean instead. In this case, replace {condition_orig} with {condition} """, deprecated_since_version='1.5', active_deprecations_target="deprecated-conditionset-set", ) condition = as_Boolean(condition) if condition is S.true: return base_set if condition is S.false: return S.EmptySet if base_set is S.EmptySet: return S.EmptySet # 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) sym = property(lambda self: self.args[0]) condition = property(lambda self: self.args[1]) base_set = property(lambda self: self.args[2]) @property def free_symbols(self): cond_syms = self.condition.free_symbols - self.sym.free_symbols return cond_syms | self.base_set.free_symbols @property def bound_symbols(self): return flatten([self.sym]) def _contains(self, other): def ok_sig(a, b): tuples = [isinstance(i, Tuple) for i in (a, b)] c = tuples.count(True) if c == 1: return False if c == 0: return True return len(a) == len(b) and all( ok_sig(i, j) for i, j in zip(a, b)) if not ok_sig(self.sym, other): return S.false # try doing base_cond first and return # False immediately if it is False base_cond = Contains(other, self.base_set) if base_cond is S.false: return S.false # Substitute other into condition. This could raise e.g. for # ConditionSet(x, 1/x >= 0, Reals).contains(0) lamda = Lambda((self.sym,), self.condition) try: lambda_cond = lamda(other) except TypeError: return Contains(other, self, evaluate=False) else: return And(base_cond, lambda_cond) def as_relational(self, other): f = Lambda(self.sym, self.condition) if isinstance(self.sym, Tuple): f = f(*other) else: f = f(other) return And(f, self.base_set.contains(other)) def _eval_subs(self, old, new): sym, cond, base = self.args dsym = sym.subs(old, adummy) insym = dsym.has(adummy) # prioritize changing a symbol in the base newbase = base.subs(old, new) if newbase != base: if not insym: cond = cond.subs(old, new) return self.func(sym, cond, newbase) if insym: pass # no change of bound symbols via subs elif getattr(new, '_diff_wrt', False): cond = cond.subs(old, new) else: pass # let error about the symbol raise from __new__ return self.func(sym, cond, base) def _kind(self): return SetKind(self.sym.kind)
02b33a4e1560a7802674622660d5af5644df974f8dadfdf5ca47cd3c87d8e48e
"""Implicit plotting module for SymPy. Explanation =========== The module implements a data series called ImplicitSeries which is used by ``Plot`` class to plot implicit plots for different backends. The module, by default, implements plotting using interval arithmetic. It switches to a fall back algorithm if the expression cannot be plotted using interval arithmetic. It is also possible to specify to use the fall back algorithm for all plots. Boolean combinations of expressions cannot be plotted by the fall back algorithm. See Also ======== sympy.plotting.plot References ========== .. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables. .. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval Arithmetic. Master's thesis. University of Toronto, 1996 """ from .plot import BaseSeries, Plot from .experimental_lambdify import experimental_lambdify, vectorized_lambdify from .intervalmath import interval from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational, StrictLessThan, StrictGreaterThan) from sympy.core.containers import Tuple from sympy.core.relational import Eq from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify from sympy.external import import_module from sympy.logic.boolalg import BooleanFunction from sympy.polys.polyutils import _sort_gens from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import flatten import warnings class ImplicitSeries(BaseSeries): """ Representation for Implicit plot """ is_implicit = True def __init__(self, expr, var_start_end_x, var_start_end_y, has_equality, use_interval_math, depth, nb_of_points, line_color): super().__init__() self.expr = sympify(expr) self.label = self.expr self.var_x = sympify(var_start_end_x[0]) self.start_x = float(var_start_end_x[1]) self.end_x = float(var_start_end_x[2]) self.var_y = sympify(var_start_end_y[0]) self.start_y = float(var_start_end_y[1]) self.end_y = float(var_start_end_y[2]) self.get_points = self.get_raster self.has_equality = has_equality # If the expression has equality, i.e. #Eq, Greaterthan, LessThan. self.nb_of_points = nb_of_points self.use_interval_math = use_interval_math self.depth = 4 + depth self.line_color = line_color def __str__(self): return ('Implicit equation: %s for ' '%s over %s and %s over %s') % ( str(self.expr), str(self.var_x), str((self.start_x, self.end_x)), str(self.var_y), str((self.start_y, self.end_y))) def get_raster(self): func = experimental_lambdify((self.var_x, self.var_y), self.expr, use_interval=True) xinterval = interval(self.start_x, self.end_x) yinterval = interval(self.start_y, self.end_y) try: func(xinterval, yinterval) except AttributeError: # XXX: AttributeError("'list' object has no attribute 'is_real'") # That needs fixing somehow - we shouldn't be catching # AttributeError here. if self.use_interval_math: warnings.warn("Adaptive meshing could not be applied to the" " expression. Using uniform meshing.", stacklevel=7) self.use_interval_math = False if self.use_interval_math: return self._get_raster_interval(func) else: return self._get_meshes_grid() def _get_raster_interval(self, func): """ Uses interval math to adaptively mesh and obtain the plot""" k = self.depth interval_list = [] #Create initial 32 divisions np = import_module('numpy') xsample = np.linspace(self.start_x, self.end_x, 33) ysample = np.linspace(self.start_y, self.end_y, 33) #Add a small jitter so that there are no false positives for equality. # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2) #which will draw a rectangle. jitterx = (np.random.rand( len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20 jittery = (np.random.rand( len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20 xsample += jitterx ysample += jittery xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1], xsample[1:])] yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1], ysample[1:])] interval_list = [[x, y] for x in xinter for y in yinter] plot_list = [] #recursive call refinepixels which subdivides the intervals which are #neither True nor False according to the expression. def refine_pixels(interval_list): """ Evaluates the intervals and subdivides the interval if the expression is partially satisfied.""" temp_interval_list = [] plot_list = [] for intervals in interval_list: #Convert the array indices to x and y values intervalx = intervals[0] intervaly = intervals[1] func_eval = func(intervalx, intervaly) #The expression is valid in the interval. Change the contour #array values to 1. if func_eval[1] is False or func_eval[0] is False: pass elif func_eval == (True, True): plot_list.append([intervalx, intervaly]) elif func_eval[1] is None or func_eval[0] is None: #Subdivide avgx = intervalx.mid avgy = intervaly.mid a = interval(intervalx.start, avgx) b = interval(avgx, intervalx.end) c = interval(intervaly.start, avgy) d = interval(avgy, intervaly.end) temp_interval_list.append([a, c]) temp_interval_list.append([a, d]) temp_interval_list.append([b, c]) temp_interval_list.append([b, d]) return temp_interval_list, plot_list while k >= 0 and len(interval_list): interval_list, plot_list_temp = refine_pixels(interval_list) plot_list.extend(plot_list_temp) k = k - 1 #Check whether the expression represents an equality #If it represents an equality, then none of the intervals #would have satisfied the expression due to floating point #differences. Add all the undecided values to the plot. if self.has_equality: for intervals in interval_list: intervalx = intervals[0] intervaly = intervals[1] func_eval = func(intervalx, intervaly) if func_eval[1] and func_eval[0] is not False: plot_list.append([intervalx, intervaly]) return plot_list, 'fill' def _get_meshes_grid(self): """Generates the mesh for generating a contour. In the case of equality, ``contour`` function of matplotlib can be used. In other cases, matplotlib's ``contourf`` is used. """ equal = False if isinstance(self.expr, Equality): expr = self.expr.lhs - self.expr.rhs equal = True elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)): expr = self.expr.lhs - self.expr.rhs elif isinstance(self.expr, (LessThan, StrictLessThan)): expr = self.expr.rhs - self.expr.lhs else: raise NotImplementedError("The expression is not supported for " "plotting in uniform meshed plot.") np = import_module('numpy') xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points) yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points) x_grid, y_grid = np.meshgrid(xarray, yarray) func = vectorized_lambdify((self.var_x, self.var_y), expr) z_grid = func(x_grid, y_grid) z_grid[np.ma.where(z_grid < 0)] = -1 z_grid[np.ma.where(z_grid > 0)] = 1 if equal: return xarray, yarray, z_grid, 'contour' else: return xarray, yarray, z_grid, 'contourf' @doctest_depends_on(modules=('matplotlib',)) def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0, points=300, line_color="blue", show=True, **kwargs): """A plot function to plot implicit equations / inequalities. Arguments ========= - ``expr`` : The equation / inequality that is to be plotted. - ``x_var`` (optional) : symbol to plot on x-axis or tuple giving symbol and range as ``(symbol, xmin, xmax)`` - ``y_var`` (optional) : symbol to plot on y-axis or tuple giving symbol and range as ``(symbol, ymin, ymax)`` If neither ``x_var`` nor ``y_var`` are given then the free symbols in the expression will be assigned in the order they are sorted. The following keyword arguments can also be used: - ``adaptive`` Boolean. The default value is set to True. It has to be set to False if you want to use a mesh grid. - ``depth`` integer. The depth of recursion for adaptive mesh grid. Default value is 0. Takes value in the range (0, 4). - ``points`` integer. The number of points if adaptive mesh grid is not used. Default value is 300. - ``show`` Boolean. Default value is True. If set to False, the plot will not be shown. See ``Plot`` for further information. - ``title`` string. The title for the plot. - ``xlabel`` string. The label for the x-axis - ``ylabel`` string. The label for the y-axis Aesthetics options: - ``line_color``: float or string. Specifies the color for the plot. See ``Plot`` to see how to set color for the plots. Default value is "Blue" plot_implicit, by default, uses interval arithmetic to plot functions. If the expression cannot be plotted using interval arithmetic, it defaults to a generating a contour using a mesh grid of fixed number of points. By setting adaptive to False, you can force plot_implicit to use the mesh grid. The mesh grid method can be effective when adaptive plotting using interval arithmetic, fails to plot with small line width. Examples ======== Plot expressions: .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import plot_implicit, symbols, Eq, And >>> x, y = symbols('x y') Without any ranges for the symbols in the expression: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p1 = plot_implicit(Eq(x**2 + y**2, 5)) With the range for the symbols: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p2 = plot_implicit( ... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3)) With depth of recursion as argument: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p3 = plot_implicit( ... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2) Using mesh grid and not using adaptive meshing: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p4 = plot_implicit( ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2), ... adaptive=False) Using mesh grid without using adaptive meshing with number of points specified: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p5 = plot_implicit( ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2), ... adaptive=False, points=400) Plotting regions: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p6 = plot_implicit(y > x**2) Plotting Using boolean conjunctions: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p7 = plot_implicit(And(y > x, y > -x)) When plotting an expression with a single variable (y - 1, for example), specify the x or the y variable explicitly: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p8 = plot_implicit(y - 1, y_var=y) >>> p9 = plot_implicit(x - 1, x_var=x) """ has_equality = False # Represents whether the expression contains an Equality, #GreaterThan or LessThan def arg_expand(bool_expr): """ Recursively expands the arguments of an Boolean Function """ for arg in bool_expr.args: if isinstance(arg, BooleanFunction): arg_expand(arg) elif isinstance(arg, Relational): arg_list.append(arg) arg_list = [] if isinstance(expr, BooleanFunction): arg_expand(expr) #Check whether there is an equality in the expression provided. if any(isinstance(e, (Equality, GreaterThan, LessThan)) for e in arg_list): has_equality = True elif not isinstance(expr, Relational): expr = Eq(expr, 0) has_equality = True elif isinstance(expr, (Equality, GreaterThan, LessThan)): has_equality = True xyvar = [i for i in (x_var, y_var) if i is not None] free_symbols = expr.free_symbols range_symbols = Tuple(*flatten(xyvar)).free_symbols undeclared = free_symbols - range_symbols if len(free_symbols & range_symbols) > 2: raise NotImplementedError("Implicit plotting is not implemented for " "more than 2 variables") #Create default ranges if the range is not provided. default_range = Tuple(-5, 5) def _range_tuple(s): if isinstance(s, Symbol): return Tuple(s) + default_range if len(s) == 3: return Tuple(*s) raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s) if len(xyvar) == 0: xyvar = list(_sort_gens(free_symbols)) var_start_end_x = _range_tuple(xyvar[0]) x = var_start_end_x[0] if len(xyvar) != 2: if x in undeclared or not undeclared: xyvar.append(Dummy('f(%s)' % x.name)) else: xyvar.append(undeclared.pop()) var_start_end_y = _range_tuple(xyvar[1]) #Check whether the depth is greater than 4 or less than 0. if depth > 4: depth = 4 elif depth < 0: depth = 0 series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y, has_equality, adaptive, depth, points, line_color) #set the x and y limits kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:]) kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:]) # set the x and y labels kwargs.setdefault('xlabel', var_start_end_x[0]) kwargs.setdefault('ylabel', var_start_end_y[0]) p = Plot(series_argument, **kwargs) if show: p.show() return p
b6e9d41226f40b3c69f04e91f044d4cb7df33f70cf26411eacb6a3a5f53e4131
"""Plotting module for SymPy. A plot is represented by the ``Plot`` class that contains a reference to the backend and a list of the data series to be plotted. The data series are instances of classes meant to simplify getting points and meshes from SymPy expressions. ``plot_backends`` is a dictionary with all the backends. This module gives only the essential. For all the fancy stuff use directly the backend. You can get the backend wrapper for every plot from the ``_backend`` attribute. Moreover the data series classes have various useful methods like ``get_points``, ``get_meshes``, etc, that may be useful if you wish to use another plotting library. Especially if you need publication ready graphs and this module is not enough for you - just get the ``_backend`` attribute and add whatever you want directly to it. In the case of matplotlib (the common way to graph data in python) just copy ``_backend.fig`` which is the figure and ``_backend.ax`` which is the axis and work on them as you would on any other matplotlib object. Simplicity of code takes much greater importance than performance. Do not use it if you care at all about performance. A new backend instance is initialized every time you call ``show()`` and the old one is left to the garbage collector. """ from collections.abc import Callable from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import arity, Function from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify from sympy.external import import_module from sympy.printing.latex import latex from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from .experimental_lambdify import (vectorized_lambdify, lambdify) # N.B. # When changing the minimum module version for matplotlib, please change # the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py` # Backend specific imports - textplot from sympy.plotting.textplot import textplot # Global variable # Set to False when running tests / doctests so that the plots don't show. _show = True def unset_show(): """ Disable show(). For use in the tests. """ global _show _show = False def _str_or_latex(label): if isinstance(label, Basic): return latex(label, mode='inline') return str(label) ############################################################################## # The public interface ############################################################################## class Plot: """The central class of the plotting module. Explanation =========== For interactive work the function :func:`plot()` is better suited. This class permits the plotting of SymPy expressions using numerous backends (:mod:`matplotlib`, textplot, the old pyglet module for SymPy, Google charts api, etc). The figure can contain an arbitrary number of plots of SymPy expressions, lists of coordinates of points, etc. Plot has a private attribute _series that contains all data series to be plotted (expressions for lines or surfaces, lists of points, etc (all subclasses of BaseSeries)). Those data series are instances of classes not imported by ``from sympy import *``. The customization of the figure is on two levels. Global options that concern the figure as a whole (e.g. title, xlabel, scale, etc) and per-data series options (e.g. name) and aesthetics (e.g. color, point shape, line type, etc.). The difference between options and aesthetics is that an aesthetic can be a function of the coordinates (or parameters in a parametric plot). The supported values for an aesthetic are: - None (the backend uses default values) - a constant - a function of one variable (the first coordinate or parameter) - a function of two variables (the first and second coordinate or parameters) - a function of three variables (only in nonparametric 3D plots) Their implementation depends on the backend so they may not work in some backends. If the plot is parametric and the arity of the aesthetic function permits it the aesthetic is calculated over parameters and not over coordinates. If the arity does not permit calculation over parameters the calculation is done over coordinates. Only cartesian coordinates are supported for the moment, but you can use the parametric plots to plot in polar, spherical and cylindrical coordinates. The arguments for the constructor Plot must be subclasses of BaseSeries. Any global option can be specified as a keyword argument. The global options for a figure are: - title : str - xlabel : str or Symbol - ylabel : str or Symbol - zlabel : str or Symbol - legend : bool - xscale : {'linear', 'log'} - yscale : {'linear', 'log'} - axis : bool - axis_center : tuple of two floats or {'center', 'auto'} - xlim : tuple of two floats - ylim : tuple of two floats - aspect_ratio : tuple of two floats or {'auto'} - autoscale : bool - margin : float in [0, 1] - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend - size : optional tuple of two floats, (width, height); default: None The per data series options and aesthetics are: There are none in the base series. See below for options for subclasses. Some data series support additional aesthetics or options: :class:`~.LineOver1DRangeSeries`, :class:`~.Parametric2DLineSeries`, and :class:`~.Parametric3DLineSeries` support the following: Aesthetics: - line_color : string, or float, or function, optional Specifies the color for the plot, which depends on the backend being used. For example, if ``MatplotlibBackend`` is being used, then Matplotlib string colors are acceptable (``"red"``, ``"r"``, ``"cyan"``, ``"c"``, ...). Alternatively, we can use a float number, 0 < color < 1, wrapped in a string (for example, ``line_color="0.5"``) to specify grayscale colors. Alternatively, We can specify a function returning a single float value: this will be used to apply a color-loop (for example, ``line_color=lambda x: math.cos(x)``). Note that by setting line_color, it would be applied simultaneously to all the series. Options: - label : str - steps : bool - integers_only : bool :class:`~.SurfaceOver2DRangeSeries` and :class:`~.ParametricSurfaceSeries` support the following: Aesthetics: - surface_color : function which returns a float. """ def __init__(self, *args, title=None, xlabel=None, ylabel=None, zlabel=None, aspect_ratio='auto', xlim=None, ylim=None, axis_center='auto', axis=True, xscale='linear', yscale='linear', legend=False, autoscale=True, margin=0, annotations=None, markers=None, rectangles=None, fill=None, backend='default', size=None, **kwargs): super().__init__() # Options for the graph as a whole. # The possible values for each option are described in the docstring of # Plot. They are based purely on convention, no checking is done. self.title = title self.xlabel = xlabel self.ylabel = ylabel self.zlabel = zlabel self.aspect_ratio = aspect_ratio self.axis_center = axis_center self.axis = axis self.xscale = xscale self.yscale = yscale self.legend = legend self.autoscale = autoscale self.margin = margin self.annotations = annotations self.markers = markers self.rectangles = rectangles self.fill = fill # Contains the data objects to be plotted. The backend should be smart # enough to iterate over this list. self._series = [] self._series.extend(args) # The backend type. On every show() a new backend instance is created # in self._backend which is tightly coupled to the Plot instance # (thanks to the parent attribute of the backend). if isinstance(backend, str): self.backend = plot_backends[backend] elif (type(backend) == type) and issubclass(backend, BaseBackend): self.backend = backend else: raise TypeError( "backend must be either a string or a subclass of BaseBackend") is_real = \ lambda lim: all(getattr(i, 'is_real', True) for i in lim) is_finite = \ lambda lim: all(getattr(i, 'is_finite', True) for i in lim) # reduce code repetition def check_and_set(t_name, t): if t: if not is_real(t): raise ValueError( "All numbers from {}={} must be real".format(t_name, t)) if not is_finite(t): raise ValueError( "All numbers from {}={} must be finite".format(t_name, t)) setattr(self, t_name, (float(t[0]), float(t[1]))) self.xlim = None check_and_set("xlim", xlim) self.ylim = None check_and_set("ylim", ylim) self.size = None check_and_set("size", size) def show(self): # TODO move this to the backend (also for save) if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.show() def save(self, path): if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.save(path) def __str__(self): series_strs = [('[%d]: ' % i) + str(s) for i, s in enumerate(self._series)] return 'Plot object containing:\n' + '\n'.join(series_strs) def __getitem__(self, index): return self._series[index] def __setitem__(self, index, *args): if len(args) == 1 and isinstance(args[0], BaseSeries): self._series[index] = args def __delitem__(self, index): del self._series[index] def append(self, arg): """Adds an element from a plot's series to an existing plot. Examples ======== Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the second plot's first series object to the first, use the ``append`` method, like so: .. plot:: :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') >>> p1 = plot(x*x, show=False) >>> p2 = plot(x, show=False) >>> p1.append(p2[0]) >>> p1 Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) [1]: cartesian line: x for x over (-10.0, 10.0) >>> p1.show() See Also ======== extend """ if isinstance(arg, BaseSeries): self._series.append(arg) else: raise TypeError('Must specify element of plot to append.') def extend(self, arg): """Adds all series from another plot. Examples ======== Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the second plot to the first, use the ``extend`` method, like so: .. plot:: :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') >>> p1 = plot(x**2, show=False) >>> p2 = plot(x, -x, show=False) >>> p1.extend(p2) >>> p1 Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) [1]: cartesian line: x for x over (-10.0, 10.0) [2]: cartesian line: -x for x over (-10.0, 10.0) >>> p1.show() """ if isinstance(arg, Plot): self._series.extend(arg._series) elif is_sequence(arg): self._series.extend(arg) else: raise TypeError('Expecting Plot or sequence of BaseSeries') class PlotGrid: """This class helps to plot subplots from already created SymPy plots in a single figure. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot, plot3d, PlotGrid >>> x, y = symbols('x, y') >>> p1 = plot(x, x**2, x**3, (x, -5, 5)) >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5))) >>> p3 = plot(x**3, (x, -5, 5)) >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5)) Plotting vertically in a single line: .. plot:: :context: close-figs :format: doctest :include-source: True >>> PlotGrid(2, 1, p1, p2) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x for x over (-5.0, 5.0) [1]: cartesian line: x**2 for x over (-5.0, 5.0) [2]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[1]:Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) Plotting horizontally in a single line: .. plot:: :context: close-figs :format: doctest :include-source: True >>> PlotGrid(1, 3, p2, p3, p4) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) Plot[1]:Plot object containing: [0]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[2]:Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) Plotting in a grid form: .. plot:: :context: close-figs :format: doctest :include-source: True >>> PlotGrid(2, 2, p1, p2, p3, p4) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x for x over (-5.0, 5.0) [1]: cartesian line: x**2 for x over (-5.0, 5.0) [2]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[1]:Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) Plot[2]:Plot object containing: [0]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[3]:Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) """ def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs): """ Parameters ========== nrows : The number of rows that should be in the grid of the required subplot. ncolumns : The number of columns that should be in the grid of the required subplot. nrows and ncolumns together define the required grid. Arguments ========= A list of predefined plot objects entered in a row-wise sequence i.e. plot objects which are to be in the top row of the required grid are written first, then the second row objects and so on Keyword arguments ================= show : Boolean The default value is set to ``True``. Set show to ``False`` and the function will not display the subplot. The returned instance of the ``PlotGrid`` class can then be used to save or display the plot by calling the ``save()`` and ``show()`` methods respectively. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. """ self.nrows = nrows self.ncolumns = ncolumns self._series = [] self.args = args for arg in args: self._series.append(arg._series) self.backend = DefaultBackend self.size = size if show: self.show() def show(self): if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.show() def save(self, path): if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.save(path) def __str__(self): plot_strs = [('Plot[%d]:' % i) + str(plot) for i, plot in enumerate(self.args)] return 'PlotGrid object containing:\n' + '\n'.join(plot_strs) ############################################################################## # Data Series ############################################################################## #TODO more general way to calculate aesthetics (see get_color_array) ### The base class for all series class BaseSeries: """Base class for the data objects containing stuff to be plotted. Explanation =========== The backend should check if it supports the data series that is given. (e.g. TextBackend supports only LineOver1DRangeSeries). It is the backend responsibility to know how to use the class of data series that is given. Some data series classes are grouped (using a class attribute like is_2Dline) according to the api they present (based only on convention). The backend is not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the is_2Dline group and presents the get_points method, but the TextBackend does not use the get_points method). """ # Some flags follow. The rationale for using flags instead of checking base # classes is that setting multiple flags is simpler than multiple # inheritance. is_2Dline = False # Some of the backends expect: # - get_points returning 1D np.arrays list_x, list_y # - get_color_array returning 1D np.array (done in Line2DBaseSeries) # with the colors calculated at the points from get_points is_3Dline = False # Some of the backends expect: # - get_points returning 1D np.arrays list_x, list_y, list_y # - get_color_array returning 1D np.array (done in Line2DBaseSeries) # with the colors calculated at the points from get_points is_3Dsurface = False # Some of the backends expect: # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays) # - get_points an alias for get_meshes is_contour = False # Some of the backends expect: # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays) # - get_points an alias for get_meshes is_implicit = False # Some of the backends expect: # - get_meshes returning mesh_x (1D array), mesh_y(1D array, # mesh_z (2D np.arrays) # - get_points an alias for get_meshes # Different from is_contour as the colormap in backend will be # different is_parametric = False # The calculation of aesthetics expects: # - get_parameter_points returning one or two np.arrays (1D or 2D) # used for calculation aesthetics def __init__(self): super().__init__() @property def is_3D(self): flags3D = [ self.is_3Dline, self.is_3Dsurface ] return any(flags3D) @property def is_line(self): flagslines = [ self.is_2Dline, self.is_3Dline ] return any(flagslines) ### 2D lines class Line2DBaseSeries(BaseSeries): """A base class for 2D lines. - adding the label, steps and only_integers options - making is_2Dline true - defining get_segments and get_color_array """ is_2Dline = True _dim = 2 def __init__(self): super().__init__() self.label = None self.steps = False self.only_integers = False self.line_color = None def get_data(self): """ Return lists of coordinates for plotting the line. Returns ======= x : list List of x-coordinates y : list List of y-coordinates z : list List of z-coordinates in case of Parametric3DLineSeries """ np = import_module('numpy') points = self.get_points() if self.steps is True: if len(points) == 2: x = np.array((points[0], points[0])).T.flatten()[1:] y = np.array((points[1], points[1])).T.flatten()[:-1] points = (x, y) else: x = np.repeat(points[0], 3)[2:] y = np.repeat(points[1], 3)[:-2] z = np.repeat(points[2], 3)[1:-1] points = (x, y, z) return points def get_segments(self): sympy_deprecation_warning( """ The Line2DBaseSeries.get_segments() method is deprecated. Instead, use the MatplotlibBackend.get_segments() method, or use The get_points() or get_data() methods. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-get-segments") np = import_module('numpy') points = type(self).get_data(self) points = np.ma.array(points).T.reshape(-1, 1, self._dim) return np.ma.concatenate([points[:-1], points[1:]], axis=1) def get_color_array(self): np = import_module('numpy') c = self.line_color if hasattr(c, '__call__'): f = np.vectorize(c) nargs = arity(c) if nargs == 1 and self.is_parametric: x = self.get_parameter_points() return f(centers_of_segments(x)) else: variables = list(map(centers_of_segments, self.get_points())) if nargs == 1: return f(variables[0]) elif nargs == 2: return f(*variables[:2]) else: # only if the line is 3D (otherwise raises an error) return f(*variables) else: return c*np.ones(self.nb_of_points) class List2DSeries(Line2DBaseSeries): """Representation for a line consisting of list of points.""" def __init__(self, list_x, list_y): np = import_module('numpy') super().__init__() self.list_x = np.array(list_x) self.list_y = np.array(list_y) self.label = 'list' def __str__(self): return 'list plot' def get_points(self): return (self.list_x, self.list_y) class LineOver1DRangeSeries(Line2DBaseSeries): """Representation for a line consisting of a SymPy expression over a range.""" def __init__(self, expr, var_start_end, **kwargs): super().__init__() self.expr = sympify(expr) self.label = kwargs.get('label', None) or self.expr self.var = sympify(var_start_end[0]) self.start = float(var_start_end[1]) self.end = float(var_start_end[2]) self.nb_of_points = kwargs.get('nb_of_points', 300) self.adaptive = kwargs.get('adaptive', True) self.depth = kwargs.get('depth', 12) self.line_color = kwargs.get('line_color', None) self.xscale = kwargs.get('xscale', 'linear') def __str__(self): return 'cartesian line: %s for %s over %s' % ( str(self.expr), str(self.var), str((self.start, self.end))) def get_points(self): """ Return lists of coordinates for plotting. Depending on the ``adaptive`` option, this function will either use an adaptive algorithm or it will uniformly sample the expression over the provided range. Returns ======= x : list List of x-coordinates y : list List of y-coordinates Explanation =========== The adaptive sampling is done by recursively checking if three points are almost collinear. If they are not collinear, then more points are added between those points. References ========== .. [1] Adaptive polygonal approximation of parametric curves, Luiz Henrique de Figueiredo. """ if self.only_integers or not self.adaptive: return self._uniform_sampling() else: f = lambdify([self.var], self.expr) x_coords = [] y_coords = [] np = import_module('numpy') def sample(p, q, depth): """ Samples recursively if three points are almost collinear. For depth < 6, points are added irrespective of whether they satisfy the collinearity condition or not. The maximum depth allowed is 12. """ # Randomly sample to avoid aliasing. random = 0.45 + np.random.rand() * 0.1 if self.xscale == 'log': xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) - np.log10(p[0]))) else: xnew = p[0] + random * (q[0] - p[0]) ynew = f(xnew) new_point = np.array([xnew, ynew]) # Maximum depth if depth > self.depth: x_coords.append(q[0]) y_coords.append(q[1]) # Sample irrespective of whether the line is flat till the # depth of 6. We are not using linspace to avoid aliasing. elif depth < 6: sample(p, new_point, depth + 1) sample(new_point, q, depth + 1) # Sample ten points if complex values are encountered # at both ends. If there is a real value in between, then # sample those points further. elif p[1] is None and q[1] is None: if self.xscale == 'log': xarray = np.logspace(p[0], q[0], 10) else: xarray = np.linspace(p[0], q[0], 10) yarray = list(map(f, xarray)) if not all(y is None for y in yarray): for i in range(len(yarray) - 1): if not (yarray[i] is None and yarray[i + 1] is None): sample([xarray[i], yarray[i]], [xarray[i + 1], yarray[i + 1]], depth + 1) # Sample further if one of the end points in None (i.e. a # complex value) or the three points are not almost collinear. elif (p[1] is None or q[1] is None or new_point[1] is None or not flat(p, new_point, q)): sample(p, new_point, depth + 1) sample(new_point, q, depth + 1) else: x_coords.append(q[0]) y_coords.append(q[1]) f_start = f(self.start) f_end = f(self.end) x_coords.append(self.start) y_coords.append(f_start) sample(np.array([self.start, f_start]), np.array([self.end, f_end]), 0) return (x_coords, y_coords) def _uniform_sampling(self): np = import_module('numpy') if self.only_integers is True: if self.xscale == 'log': list_x = np.logspace(int(self.start), int(self.end), num=int(self.end) - int(self.start) + 1) else: list_x = np.linspace(int(self.start), int(self.end), num=int(self.end) - int(self.start) + 1) else: if self.xscale == 'log': list_x = np.logspace(self.start, self.end, num=self.nb_of_points) else: list_x = np.linspace(self.start, self.end, num=self.nb_of_points) f = vectorized_lambdify([self.var], self.expr) list_y = f(list_x) return (list_x, list_y) class Parametric2DLineSeries(Line2DBaseSeries): """Representation for a line consisting of two parametric SymPy expressions over a range.""" is_parametric = True def __init__(self, expr_x, expr_y, var_start_end, **kwargs): super().__init__() self.expr_x = sympify(expr_x) self.expr_y = sympify(expr_y) self.label = kwargs.get('label', None) or \ Tuple(self.expr_x, self.expr_y) self.var = sympify(var_start_end[0]) self.start = float(var_start_end[1]) self.end = float(var_start_end[2]) self.nb_of_points = kwargs.get('nb_of_points', 300) self.adaptive = kwargs.get('adaptive', True) self.depth = kwargs.get('depth', 12) self.line_color = kwargs.get('line_color', None) def __str__(self): return 'parametric cartesian line: (%s, %s) for %s over %s' % ( str(self.expr_x), str(self.expr_y), str(self.var), str((self.start, self.end))) def get_parameter_points(self): np = import_module('numpy') return np.linspace(self.start, self.end, num=self.nb_of_points) def _uniform_sampling(self): param = self.get_parameter_points() fx = vectorized_lambdify([self.var], self.expr_x) fy = vectorized_lambdify([self.var], self.expr_y) list_x = fx(param) list_y = fy(param) return (list_x, list_y) def get_points(self): """ Return lists of coordinates for plotting. Depending on the ``adaptive`` option, this function will either use an adaptive algorithm or it will uniformly sample the expression over the provided range. Returns ======= x : list List of x-coordinates y : list List of y-coordinates Explanation =========== The adaptive sampling is done by recursively checking if three points are almost collinear. If they are not collinear, then more points are added between those points. References ========== .. [1] Adaptive polygonal approximation of parametric curves, Luiz Henrique de Figueiredo. """ if not self.adaptive: return self._uniform_sampling() f_x = lambdify([self.var], self.expr_x) f_y = lambdify([self.var], self.expr_y) x_coords = [] y_coords = [] def sample(param_p, param_q, p, q, depth): """ Samples recursively if three points are almost collinear. For depth < 6, points are added irrespective of whether they satisfy the collinearity condition or not. The maximum depth allowed is 12. """ # Randomly sample to avoid aliasing. np = import_module('numpy') random = 0.45 + np.random.rand() * 0.1 param_new = param_p + random * (param_q - param_p) xnew = f_x(param_new) ynew = f_y(param_new) new_point = np.array([xnew, ynew]) # Maximum depth if depth > self.depth: x_coords.append(q[0]) y_coords.append(q[1]) # Sample irrespective of whether the line is flat till the # depth of 6. We are not using linspace to avoid aliasing. elif depth < 6: sample(param_p, param_new, p, new_point, depth + 1) sample(param_new, param_q, new_point, q, depth + 1) # Sample ten points if complex values are encountered # at both ends. If there is a real value in between, then # sample those points further. elif ((p[0] is None and q[1] is None) or (p[1] is None and q[1] is None)): param_array = np.linspace(param_p, param_q, 10) x_array = list(map(f_x, param_array)) y_array = list(map(f_y, param_array)) if not all(x is None and y is None for x, y in zip(x_array, y_array)): for i in range(len(y_array) - 1): if ((x_array[i] is not None and y_array[i] is not None) or (x_array[i + 1] is not None and y_array[i + 1] is not None)): point_a = [x_array[i], y_array[i]] point_b = [x_array[i + 1], y_array[i + 1]] sample(param_array[i], param_array[i], point_a, point_b, depth + 1) # Sample further if one of the end points in None (i.e. a complex # value) or the three points are not almost collinear. elif (p[0] is None or p[1] is None or q[1] is None or q[0] is None or not flat(p, new_point, q)): sample(param_p, param_new, p, new_point, depth + 1) sample(param_new, param_q, new_point, q, depth + 1) else: x_coords.append(q[0]) y_coords.append(q[1]) f_start_x = f_x(self.start) f_start_y = f_y(self.start) start = [f_start_x, f_start_y] f_end_x = f_x(self.end) f_end_y = f_y(self.end) end = [f_end_x, f_end_y] x_coords.append(f_start_x) y_coords.append(f_start_y) sample(self.start, self.end, start, end, 0) return x_coords, y_coords ### 3D lines class Line3DBaseSeries(Line2DBaseSeries): """A base class for 3D lines. Most of the stuff is derived from Line2DBaseSeries.""" is_2Dline = False is_3Dline = True _dim = 3 def __init__(self): super().__init__() class Parametric3DLineSeries(Line3DBaseSeries): """Representation for a 3D line consisting of three parametric SymPy expressions and a range.""" is_parametric = True def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs): super().__init__() self.expr_x = sympify(expr_x) self.expr_y = sympify(expr_y) self.expr_z = sympify(expr_z) self.label = kwargs.get('label', None) or \ Tuple(self.expr_x, self.expr_y) self.var = sympify(var_start_end[0]) self.start = float(var_start_end[1]) self.end = float(var_start_end[2]) self.nb_of_points = kwargs.get('nb_of_points', 300) self.line_color = kwargs.get('line_color', None) self._xlim = None self._ylim = None self._zlim = None def __str__(self): return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % ( str(self.expr_x), str(self.expr_y), str(self.expr_z), str(self.var), str((self.start, self.end))) def get_parameter_points(self): np = import_module('numpy') return np.linspace(self.start, self.end, num=self.nb_of_points) def get_points(self): np = import_module('numpy') param = self.get_parameter_points() fx = vectorized_lambdify([self.var], self.expr_x) fy = vectorized_lambdify([self.var], self.expr_y) fz = vectorized_lambdify([self.var], self.expr_z) list_x = fx(param) list_y = fy(param) list_z = fz(param) list_x = np.array(list_x, dtype=np.float64) list_y = np.array(list_y, dtype=np.float64) list_z = np.array(list_z, dtype=np.float64) list_x = np.ma.masked_invalid(list_x) list_y = np.ma.masked_invalid(list_y) list_z = np.ma.masked_invalid(list_z) self._xlim = (np.amin(list_x), np.amax(list_x)) self._ylim = (np.amin(list_y), np.amax(list_y)) self._zlim = (np.amin(list_z), np.amax(list_z)) return list_x, list_y, list_z ### Surfaces class SurfaceBaseSeries(BaseSeries): """A base class for 3D surfaces.""" is_3Dsurface = True def __init__(self): super().__init__() self.surface_color = None def get_color_array(self): np = import_module('numpy') c = self.surface_color if isinstance(c, Callable): f = np.vectorize(c) nargs = arity(c) if self.is_parametric: variables = list(map(centers_of_faces, self.get_parameter_meshes())) if nargs == 1: return f(variables[0]) elif nargs == 2: return f(*variables) variables = list(map(centers_of_faces, self.get_meshes())) if nargs == 1: return f(variables[0]) elif nargs == 2: return f(*variables[:2]) else: return f(*variables) else: if isinstance(self, SurfaceOver2DRangeSeries): return c*np.ones(min(self.nb_of_points_x, self.nb_of_points_y)) else: return c*np.ones(min(self.nb_of_points_u, self.nb_of_points_v)) class SurfaceOver2DRangeSeries(SurfaceBaseSeries): """Representation for a 3D surface consisting of a SymPy expression and 2D range.""" def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs): super().__init__() self.expr = sympify(expr) self.var_x = sympify(var_start_end_x[0]) self.start_x = float(var_start_end_x[1]) self.end_x = float(var_start_end_x[2]) self.var_y = sympify(var_start_end_y[0]) self.start_y = float(var_start_end_y[1]) self.end_y = float(var_start_end_y[2]) self.nb_of_points_x = kwargs.get('nb_of_points_x', 50) self.nb_of_points_y = kwargs.get('nb_of_points_y', 50) self.surface_color = kwargs.get('surface_color', None) self._xlim = (self.start_x, self.end_x) self._ylim = (self.start_y, self.end_y) def __str__(self): return ('cartesian surface: %s for' ' %s over %s and %s over %s') % ( str(self.expr), str(self.var_x), str((self.start_x, self.end_x)), str(self.var_y), str((self.start_y, self.end_y))) def get_meshes(self): np = import_module('numpy') mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x, num=self.nb_of_points_x), np.linspace(self.start_y, self.end_y, num=self.nb_of_points_y)) f = vectorized_lambdify((self.var_x, self.var_y), self.expr) mesh_z = f(mesh_x, mesh_y) mesh_z = np.array(mesh_z, dtype=np.float64) mesh_z = np.ma.masked_invalid(mesh_z) self._zlim = (np.amin(mesh_z), np.amax(mesh_z)) return mesh_x, mesh_y, mesh_z class ParametricSurfaceSeries(SurfaceBaseSeries): """Representation for a 3D surface consisting of three parametric SymPy expressions and a range.""" is_parametric = True def __init__( self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v, **kwargs): super().__init__() self.expr_x = sympify(expr_x) self.expr_y = sympify(expr_y) self.expr_z = sympify(expr_z) self.var_u = sympify(var_start_end_u[0]) self.start_u = float(var_start_end_u[1]) self.end_u = float(var_start_end_u[2]) self.var_v = sympify(var_start_end_v[0]) self.start_v = float(var_start_end_v[1]) self.end_v = float(var_start_end_v[2]) self.nb_of_points_u = kwargs.get('nb_of_points_u', 50) self.nb_of_points_v = kwargs.get('nb_of_points_v', 50) self.surface_color = kwargs.get('surface_color', None) def __str__(self): return ('parametric cartesian surface: (%s, %s, %s) for' ' %s over %s and %s over %s') % ( str(self.expr_x), str(self.expr_y), str(self.expr_z), str(self.var_u), str((self.start_u, self.end_u)), str(self.var_v), str((self.start_v, self.end_v))) def get_parameter_meshes(self): np = import_module('numpy') return np.meshgrid(np.linspace(self.start_u, self.end_u, num=self.nb_of_points_u), np.linspace(self.start_v, self.end_v, num=self.nb_of_points_v)) def get_meshes(self): np = import_module('numpy') mesh_u, mesh_v = self.get_parameter_meshes() fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x) fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y) fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z) mesh_x = fx(mesh_u, mesh_v) mesh_y = fy(mesh_u, mesh_v) mesh_z = fz(mesh_u, mesh_v) mesh_x = np.array(mesh_x, dtype=np.float64) mesh_y = np.array(mesh_y, dtype=np.float64) mesh_z = np.array(mesh_z, dtype=np.float64) mesh_x = np.ma.masked_invalid(mesh_x) mesh_y = np.ma.masked_invalid(mesh_y) mesh_z = np.ma.masked_invalid(mesh_z) self._xlim = (np.amin(mesh_x), np.amax(mesh_x)) self._ylim = (np.amin(mesh_y), np.amax(mesh_y)) self._zlim = (np.amin(mesh_z), np.amax(mesh_z)) return mesh_x, mesh_y, mesh_z ### Contours class ContourSeries(BaseSeries): """Representation for a contour plot.""" # The code is mostly repetition of SurfaceOver2DRange. # Presently used in contour_plot function is_contour = True def __init__(self, expr, var_start_end_x, var_start_end_y): super().__init__() self.nb_of_points_x = 50 self.nb_of_points_y = 50 self.expr = sympify(expr) self.var_x = sympify(var_start_end_x[0]) self.start_x = float(var_start_end_x[1]) self.end_x = float(var_start_end_x[2]) self.var_y = sympify(var_start_end_y[0]) self.start_y = float(var_start_end_y[1]) self.end_y = float(var_start_end_y[2]) self.get_points = self.get_meshes self._xlim = (self.start_x, self.end_x) self._ylim = (self.start_y, self.end_y) def __str__(self): return ('contour: %s for ' '%s over %s and %s over %s') % ( str(self.expr), str(self.var_x), str((self.start_x, self.end_x)), str(self.var_y), str((self.start_y, self.end_y))) def get_meshes(self): np = import_module('numpy') mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x, num=self.nb_of_points_x), np.linspace(self.start_y, self.end_y, num=self.nb_of_points_y)) f = vectorized_lambdify((self.var_x, self.var_y), self.expr) return (mesh_x, mesh_y, f(mesh_x, mesh_y)) ############################################################################## # Backends ############################################################################## class BaseBackend: """Base class for all backends. A backend represents the plotting library, which implements the necessary functionalities in order to use SymPy plotting functions. How the plotting module works: 1. Whenever a plotting function is called, the provided expressions are processed and a list of instances of the :class:`BaseSeries` class is created, containing the necessary information to plot the expressions (e.g. the expression, ranges, series name, ...). Eventually, these objects will generate the numerical data to be plotted. 2. A :class:`~.Plot` object is instantiated, which stores the list of series and the main attributes of the plot (e.g. axis labels, title, ...). 3. When the ``show`` command is executed, a new backend is instantiated, which loops through each series object to generate and plot the numerical data. The backend is also going to set the axis labels, title, ..., according to the values stored in the Plot instance. The backend should check if it supports the data series that it is given (e.g. :class:`TextBackend` supports only :class:`LineOver1DRangeSeries`). It is the backend responsibility to know how to use the class of data series that it's given. Note that the current implementation of the ``*Series`` classes is "matplotlib-centric": the numerical data returned by the ``get_points`` and ``get_meshes`` methods is meant to be used directly by Matplotlib. Therefore, the new backend will have to pre-process the numerical data to make it compatible with the chosen plotting library. Keep in mind that future SymPy versions may improve the ``*Series`` classes in order to return numerical data "non-matplotlib-centric", hence if you code a new backend you have the responsibility to check if its working on each SymPy release. Please explore the :class:`MatplotlibBackend` source code to understand how a backend should be coded. Methods ======= In order to be used by SymPy plotting functions, a backend must implement the following methods: * show(self): used to loop over the data series, generate the numerical data, plot it and set the axis labels, title, ... * save(self, path): used to save the current plot to the specified file path. * close(self): used to close the current plot backend (note: some plotting library does not support this functionality. In that case, just raise a warning). See also ======== MatplotlibBackend """ def __init__(self, parent): super().__init__() self.parent = parent def show(self): raise NotImplementedError def save(self, path): raise NotImplementedError def close(self): raise NotImplementedError # Don't have to check for the success of importing matplotlib in each case; # we will only be using this backend if we can successfully import matploblib class MatplotlibBackend(BaseBackend): """ This class implements the functionalities to use Matplotlib with SymPy plotting functions. """ def __init__(self, parent): super().__init__(parent) self.matplotlib = import_module('matplotlib', import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']}, min_module_version='1.1.0', catch=(RuntimeError,)) self.plt = self.matplotlib.pyplot self.cm = self.matplotlib.cm self.LineCollection = self.matplotlib.collections.LineCollection aspect = getattr(self.parent, 'aspect_ratio', 'auto') if aspect != 'auto': aspect = float(aspect[1]) / aspect[0] if isinstance(self.parent, Plot): nrows, ncolumns = 1, 1 series_list = [self.parent._series] elif isinstance(self.parent, PlotGrid): nrows, ncolumns = self.parent.nrows, self.parent.ncolumns series_list = self.parent._series self.ax = [] self.fig = self.plt.figure(figsize=parent.size) for i, series in enumerate(series_list): are_3D = [s.is_3D for s in series] if any(are_3D) and not all(are_3D): raise ValueError('The matplotlib backend cannot mix 2D and 3D.') elif all(are_3D): # mpl_toolkits.mplot3d is necessary for # projection='3d' mpl_toolkits = import_module('mpl_toolkits', # noqa import_kwargs={'fromlist': ['mplot3d']}) self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect)) elif not any(are_3D): self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect)) self.ax[i].spines['left'].set_position('zero') self.ax[i].spines['right'].set_color('none') self.ax[i].spines['bottom'].set_position('zero') self.ax[i].spines['top'].set_color('none') self.ax[i].xaxis.set_ticks_position('bottom') self.ax[i].yaxis.set_ticks_position('left') @staticmethod def get_segments(x, y, z=None): """ Convert two list of coordinates to a list of segments to be used with Matplotlib's :class:`~matplotlib.collections.LineCollection`. Parameters ========== x : list List of x-coordinates y : list List of y-coordinates z : list List of z-coordinates for a 3D line. """ np = import_module('numpy') if z is not None: dim = 3 points = (x, y, z) else: dim = 2 points = (x, y) points = np.ma.array(points).T.reshape(-1, 1, dim) return np.ma.concatenate([points[:-1], points[1:]], axis=1) def _process_series(self, series, ax, parent): np = import_module('numpy') mpl_toolkits = import_module( 'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']}) # XXX Workaround for matplotlib issue # https://github.com/matplotlib/matplotlib/issues/17130 xlims, ylims, zlims = [], [], [] for s in series: # Create the collections if s.is_2Dline: x, y = s.get_data() if (isinstance(s.line_color, (int, float)) or callable(s.line_color)): segments = self.get_segments(x, y) collection = self.LineCollection(segments) collection.set_array(s.get_color_array()) ax.add_collection(collection) else: lbl = _str_or_latex(s.label) line, = ax.plot(x, y, label=lbl, color=s.line_color) elif s.is_contour: ax.contour(*s.get_meshes()) elif s.is_3Dline: x, y, z = s.get_data() if (isinstance(s.line_color, (int, float)) or callable(s.line_color)): art3d = mpl_toolkits.mplot3d.art3d segments = self.get_segments(x, y, z) collection = art3d.Line3DCollection(segments) collection.set_array(s.get_color_array()) ax.add_collection(collection) else: lbl = _str_or_latex(s.label) ax.plot(x, y, z, label=lbl, color=s.line_color) xlims.append(s._xlim) ylims.append(s._ylim) zlims.append(s._zlim) elif s.is_3Dsurface: x, y, z = s.get_meshes() collection = ax.plot_surface(x, y, z, cmap=getattr(self.cm, 'viridis', self.cm.jet), rstride=1, cstride=1, linewidth=0.1) if isinstance(s.surface_color, (float, int, Callable)): color_array = s.get_color_array() color_array = color_array.reshape(color_array.size) collection.set_array(color_array) else: collection.set_color(s.surface_color) xlims.append(s._xlim) ylims.append(s._ylim) zlims.append(s._zlim) elif s.is_implicit: points = s.get_raster() if len(points) == 2: # interval math plotting x, y = _matplotlib_list(points[0]) ax.fill(x, y, facecolor=s.line_color, edgecolor='None') else: # use contourf or contour depending on whether it is # an inequality or equality. # XXX: ``contour`` plots multiple lines. Should be fixed. ListedColormap = self.matplotlib.colors.ListedColormap colormap = ListedColormap(["white", s.line_color]) xarray, yarray, zarray, plot_type = points if plot_type == 'contour': ax.contour(xarray, yarray, zarray, cmap=colormap, label=_str_or_latex(s.label)) else: ax.contourf(xarray, yarray, zarray, cmap=colormap, label=_str_or_latex(s.label)) else: raise NotImplementedError( '{} is not supported in the SymPy plotting module ' 'with matplotlib backend. Please report this issue.' .format(ax)) Axes3D = mpl_toolkits.mplot3d.Axes3D if not isinstance(ax, Axes3D): ax.autoscale_view( scalex=ax.get_autoscalex_on(), scaley=ax.get_autoscaley_on()) else: # XXX Workaround for matplotlib issue # https://github.com/matplotlib/matplotlib/issues/17130 if xlims: xlims = np.array(xlims) xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1])) ax.set_xlim(xlim) else: ax.set_xlim([0, 1]) if ylims: ylims = np.array(ylims) ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1])) ax.set_ylim(ylim) else: ax.set_ylim([0, 1]) if zlims: zlims = np.array(zlims) zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1])) ax.set_zlim(zlim) else: ax.set_zlim([0, 1]) # Set global options. # TODO The 3D stuff # XXX The order of those is important. if parent.xscale and not isinstance(ax, Axes3D): ax.set_xscale(parent.xscale) if parent.yscale and not isinstance(ax, Axes3D): ax.set_yscale(parent.yscale) if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check ax.set_autoscale_on(parent.autoscale) if parent.axis_center: val = parent.axis_center if isinstance(ax, Axes3D): pass elif val == 'center': ax.spines['left'].set_position('center') ax.spines['bottom'].set_position('center') elif val == 'auto': xl, xh = ax.get_xlim() yl, yh = ax.get_ylim() pos_left = ('data', 0) if xl*xh <= 0 else 'center' pos_bottom = ('data', 0) if yl*yh <= 0 else 'center' ax.spines['left'].set_position(pos_left) ax.spines['bottom'].set_position(pos_bottom) else: ax.spines['left'].set_position(('data', val[0])) ax.spines['bottom'].set_position(('data', val[1])) if not parent.axis: ax.set_axis_off() if parent.legend: if ax.legend(): ax.legend_.set_visible(parent.legend) if parent.margin: ax.set_xmargin(parent.margin) ax.set_ymargin(parent.margin) if parent.title: ax.set_title(parent.title) if parent.xlabel: xlbl = _str_or_latex(parent.xlabel) ax.set_xlabel(xlbl, position=(1, 0)) if parent.ylabel: ylbl = _str_or_latex(parent.ylabel) ax.set_ylabel(ylbl, position=(0, 1)) if isinstance(ax, Axes3D) and parent.zlabel: zlbl = _str_or_latex(parent.zlabel) ax.set_zlabel(zlbl, position=(0, 1)) if parent.annotations: for a in parent.annotations: ax.annotate(**a) if parent.markers: for marker in parent.markers: # make a copy of the marker dictionary # so that it doesn't get altered m = marker.copy() args = m.pop('args') ax.plot(*args, **m) if parent.rectangles: for r in parent.rectangles: rect = self.matplotlib.patches.Rectangle(**r) ax.add_patch(rect) if parent.fill: ax.fill_between(**parent.fill) # xlim and ylim shoulld always be set at last so that plot limits # doesn't get altered during the process. if parent.xlim: ax.set_xlim(parent.xlim) if parent.ylim: ax.set_ylim(parent.ylim) def process_series(self): """ Iterates over every ``Plot`` object and further calls _process_series() """ parent = self.parent if isinstance(parent, Plot): series_list = [parent._series] else: series_list = parent._series for i, (series, ax) in enumerate(zip(series_list, self.ax)): if isinstance(self.parent, PlotGrid): parent = self.parent.args[i] self._process_series(series, ax, parent) def show(self): self.process_series() #TODO after fixing https://github.com/ipython/ipython/issues/1255 # you can uncomment the next line and remove the pyplot.show() call #self.fig.show() if _show: self.fig.tight_layout() self.plt.show() else: self.close() def save(self, path): self.process_series() self.fig.savefig(path) def close(self): self.plt.close(self.fig) class TextBackend(BaseBackend): def __init__(self, parent): super().__init__(parent) def show(self): if not _show: return if len(self.parent._series) != 1: raise ValueError( 'The TextBackend supports only one graph per Plot.') elif not isinstance(self.parent._series[0], LineOver1DRangeSeries): raise ValueError( 'The TextBackend supports only expressions over a 1D range') else: ser = self.parent._series[0] textplot(ser.expr, ser.start, ser.end) def close(self): pass class DefaultBackend(BaseBackend): def __new__(cls, parent): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: return MatplotlibBackend(parent) else: return TextBackend(parent) plot_backends = { 'matplotlib': MatplotlibBackend, 'text': TextBackend, 'default': DefaultBackend } ############################################################################## # Finding the centers of line segments or mesh faces ############################################################################## def centers_of_segments(array): np = import_module('numpy') return np.mean(np.vstack((array[:-1], array[1:])), 0) def centers_of_faces(array): np = import_module('numpy') return np.mean(np.dstack((array[:-1, :-1], array[1:, :-1], array[:-1, 1:], array[:-1, :-1], )), 2) def flat(x, y, z, eps=1e-3): """Checks whether three points are almost collinear""" np = import_module('numpy') # Workaround plotting piecewise (#8577): # workaround for `lambdify` in `.experimental_lambdify` fails # to return numerical values in some cases. Lower-level fix # in `lambdify` is possible. vector_a = (x - y).astype(np.float64) vector_b = (z - y).astype(np.float64) dot_product = np.dot(vector_a, vector_b) vector_a_norm = np.linalg.norm(vector_a) vector_b_norm = np.linalg.norm(vector_b) cos_theta = dot_product / (vector_a_norm * vector_b_norm) return abs(cos_theta + 1) < eps def _matplotlib_list(interval_list): """ Returns lists for matplotlib ``fill`` command from a list of bounding rectangular intervals """ xlist = [] ylist = [] if len(interval_list): for intervals in interval_list: intervalx = intervals[0] intervaly = intervals[1] xlist.extend([intervalx.start, intervalx.start, intervalx.end, intervalx.end, None]) ylist.extend([intervaly.start, intervaly.end, intervaly.end, intervaly.start, None]) else: #XXX Ugly hack. Matplotlib does not accept empty lists for ``fill`` xlist.extend((None, None, None, None)) ylist.extend((None, None, None, None)) return xlist, ylist ####New API for plotting module #### # TODO: Add color arrays for plots. # TODO: Add more plotting options for 3d plots. # TODO: Adaptive sampling for 3D plots. def plot(*args, show=True, **kwargs): """Plots a function of a single variable as a curve. Parameters ========== args : The first argument is the expression representing the function of single variable to be plotted. The last argument is a 3-tuple denoting the range of the free variable. e.g. ``(x, 0, 5)`` Typical usage examples are in the followings: - Plotting a single expression with a single range. ``plot(expr, range, **kwargs)`` - Plotting a single expression with the default range (-10, 10). ``plot(expr, **kwargs)`` - Plotting multiple expressions with a single range. ``plot(expr1, expr2, ..., range, **kwargs)`` - Plotting multiple expressions with multiple ranges. ``plot((expr1, range1), (expr2, range2), ..., **kwargs)`` It is best practice to specify range explicitly because default range may change in the future if a more advanced default range detection algorithm is implemented. show : bool, optional The default value is set to ``True``. Set show to ``False`` and the function will not display the plot. The returned instance of the ``Plot`` class can then be used to save or display the plot by calling the ``save()`` and ``show()`` methods respectively. line_color : string, or float, or function, optional Specifies the color for the plot. See ``Plot`` to see how to set color for the plots. Note that by setting ``line_color``, it would be applied simultaneously to all the series. title : str, optional Title of the plot. It is set to the latex representation of the expression, if the plot has only one expression. label : str, optional The label of the expression in the plot. It will be used when called with ``legend``. Default is the name of the expression. e.g. ``sin(x)`` xlabel : str or expression, optional Label for the x-axis. ylabel : str or expression, optional Label for the y-axis. xscale : 'linear' or 'log', optional Sets the scaling of the x-axis. yscale : 'linear' or 'log', optional Sets the scaling of the y-axis. axis_center : (float, float), optional Tuple of two floats denoting the coordinates of the center or {'center', 'auto'} xlim : (float, float), optional Denotes the x-axis limits, ``(min, max)```. ylim : (float, float), optional Denotes the y-axis limits, ``(min, max)```. annotations : list, optional A list of dictionaries specifying the type of annotation required. The keys in the dictionary should be equivalent to the arguments of the :mod:`matplotlib`'s :meth:`~matplotlib.axes.Axes.annotate` method. markers : list, optional A list of dictionaries specifying the type the markers required. The keys in the dictionary should be equivalent to the arguments of the :mod:`matplotlib`'s :func:`~matplotlib.pyplot.plot()` function along with the marker related keyworded arguments. rectangles : list, optional A list of dictionaries specifying the dimensions of the rectangles to be plotted. The keys in the dictionary should be equivalent to the arguments of the :mod:`matplotlib`'s :class:`~matplotlib.patches.Rectangle` class. fill : dict, optional A dictionary specifying the type of color filling required in the plot. The keys in the dictionary should be equivalent to the arguments of the :mod:`matplotlib`'s :meth:`~matplotlib.axes.Axes.fill_between` method. adaptive : bool, optional The default value is set to ``True``. Set adaptive to ``False`` and specify ``nb_of_points`` if uniform sampling is required. The plotting uses an adaptive algorithm which samples recursively to accurately plot. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence the same plots can appear slightly different. depth : int, optional Recursion depth of the adaptive algorithm. A depth of value `n` samples a maximum of `2^{n}` points. If the ``adaptive`` flag is set to ``False``, this will be ignored. nb_of_points : int, optional Used when the ``adaptive`` is set to ``False``. The function is uniformly sampled at ``nb_of_points`` number of points. If the ``adaptive`` flag is set to ``True``, this will be ignored. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') Single Plot .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot(x**2, (x, -5, 5)) Plot object containing: [0]: cartesian line: x**2 for x over (-5.0, 5.0) Multiple plots with single range. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot(x, x**2, x**3, (x, -5, 5)) Plot object containing: [0]: cartesian line: x for x over (-5.0, 5.0) [1]: cartesian line: x**2 for x over (-5.0, 5.0) [2]: cartesian line: x**3 for x over (-5.0, 5.0) Multiple plots with different ranges. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5))) Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) No adaptive sampling. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot(x**2, adaptive=False, nb_of_points=400) Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) See Also ======== Plot, LineOver1DRangeSeries """ args = list(map(sympify, args)) free = set() for a in args: if isinstance(a, Expr): free |= a.free_symbols if len(free) > 1: raise ValueError( 'The same variable should be used in all ' 'univariate expressions being plotted.') x = free.pop() if free else Symbol('x') kwargs.setdefault('xlabel', x) kwargs.setdefault('ylabel', Function('f')(x)) series = [] plot_expr = check_arguments(args, 1, 1) series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot_parametric(*args, show=True, **kwargs): """ Plots a 2D parametric curve. Parameters ========== args Common specifications are: - Plotting a single parametric curve with a range ``plot_parametric((expr_x, expr_y), range)`` - Plotting multiple parametric curves with the same range ``plot_parametric((expr_x, expr_y), ..., range)`` - Plotting multiple parametric curves with different ranges ``plot_parametric((expr_x, expr_y, range), ...)`` ``expr_x`` is the expression representing $x$ component of the parametric function. ``expr_y`` is the expression representing $y$ component of the parametric function. ``range`` is a 3-tuple denoting the parameter symbol, start and stop. For example, ``(u, 0, 5)``. If the range is not specified, then a default range of (-10, 10) is used. However, if the arguments are specified as ``(expr_x, expr_y, range), ...``, you must specify the ranges for each expressions manually. Default range may change in the future if a more advanced algorithm is implemented. adaptive : bool, optional Specifies whether to use the adaptive sampling or not. The default value is set to ``True``. Set adaptive to ``False`` and specify ``nb_of_points`` if uniform sampling is required. depth : int, optional The recursion depth of the adaptive algorithm. A depth of value $n$ samples a maximum of $2^n$ points. nb_of_points : int, optional Used when the ``adaptive`` flag is set to ``False``. Specifies the number of the points used for the uniform sampling. line_color : string, or float, or function, optional Specifies the color for the plot. See ``Plot`` to see how to set color for the plots. Note that by setting ``line_color``, it would be applied simultaneously to all the series. label : str, optional The label of the expression in the plot. It will be used when called with ``legend``. Default is the name of the expression. e.g. ``sin(x)`` xlabel : str, optional Label for the x-axis. ylabel : str, optional Label for the y-axis. xscale : 'linear' or 'log', optional Sets the scaling of the x-axis. yscale : 'linear' or 'log', optional Sets the scaling of the y-axis. axis_center : (float, float), optional Tuple of two floats denoting the coordinates of the center or {'center', 'auto'} xlim : (float, float), optional Denotes the x-axis limits, ``(min, max)```. ylim : (float, float), optional Denotes the y-axis limits, ``(min, max)```. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import plot_parametric, symbols, cos, sin >>> u = symbols('u') A parametric plot with a single expression: .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot_parametric((cos(u), sin(u)), (u, -5, 5)) Plot object containing: [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0) A parametric plot with multiple expressions with the same range: .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10)) Plot object containing: [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0) [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0) A parametric plot with multiple expressions with different ranges for each curve: .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot_parametric((cos(u), sin(u), (u, -5, 5)), ... (cos(u), u, (u, -5, 5))) Plot object containing: [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0) [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0) Notes ===== The plotting uses an adaptive algorithm which samples recursively to accurately plot the curve. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence, repeating the same plot command can give slightly different results because of the random sampling. If there are multiple plots, then the same optional arguments are applied to all the plots drawn in the same canvas. If you want to set these options separately, you can index the returned ``Plot`` object and set it. For example, when you specify ``line_color`` once, it would be applied simultaneously to both series. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import pi >>> expr1 = (u, cos(2*pi*u)/2 + 1/2) >>> expr2 = (u, sin(2*pi*u)/2 + 1/2) >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue') If you want to specify the line color for the specific series, you should index each item and apply the property manually. .. plot:: :context: close-figs :format: doctest :include-source: True >>> p[0].line_color = 'red' >>> p.show() See Also ======== Plot, Parametric2DLineSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 2, 1) series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot3d_parametric_line(*args, show=True, **kwargs): """ Plots a 3D parametric line plot. Usage ===== Single plot: ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)`` If the range is not specified, then a default range of (-10, 10) is used. Multiple plots. ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= expr_x : Expression representing the function along x. expr_y : Expression representing the function along y. expr_z : Expression representing the function along z. range : (:class:`~.Symbol`, float, float) A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5). Keyword Arguments ================= Arguments for ``Parametric3DLineSeries`` class. nb_of_points : The range is uniformly sampled at ``nb_of_points`` number of points. Aesthetics: line_color : string, or float, or function, optional Specifies the color for the plot. See ``Plot`` to see how to set color for the plots. Note that by setting ``line_color``, it would be applied simultaneously to all the series. label : str The label to the plot. It will be used when called with ``legend=True`` to denote the function with the given label in the plot. If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class. title : str Title of the plot. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols, cos, sin >>> from sympy.plotting import plot3d_parametric_line >>> u = symbols('u') Single plot. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5)) Plot object containing: [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0) Multiple plots. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)), ... (sin(u), u**2, u, (u, -5, 5))) Plot object containing: [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0) [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0) See Also ======== Plot, Parametric3DLineSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 3, 1) series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr] kwargs.setdefault("xlabel", "x") kwargs.setdefault("ylabel", "y") kwargs.setdefault("zlabel", "z") plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot3d(*args, show=True, **kwargs): """ Plots a 3D surface plot. Usage ===== Single plot ``plot3d(expr, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plot with the same range. ``plot3d(expr1, expr2, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plots with different ranges. ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= expr : Expression representing the function along x. range_x : (:class:`~.Symbol`, float, float) A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5). range_y : (:class:`~.Symbol`, float, float) A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5). Keyword Arguments ================= Arguments for ``SurfaceOver2DRangeSeries`` class: nb_of_points_x : int The x range is sampled uniformly at ``nb_of_points_x`` of points. nb_of_points_y : int The y range is sampled uniformly at ``nb_of_points_y`` of points. Aesthetics: surface_color : Function which returns a float Specifies the color for the surface of the plot. See :class:`~.Plot` for more details. If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class: title : str Title of the plot. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot3d >>> x, y = symbols('x y') Single plot .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d(x*y, (x, -5, 5), (y, -5, 5)) Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) Multiple plots with same range .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5)) Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) Multiple plots with different ranges. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)), ... (x*y, (x, -3, 3), (y, -3, 3))) Plot object containing: [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0) [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0) See Also ======== Plot, SurfaceOver2DRangeSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 1, 2) series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr] kwargs.setdefault("xlabel", series[0].var_x) kwargs.setdefault("ylabel", series[0].var_y) kwargs.setdefault("zlabel", Function('f')(series[0].var_x, series[0].var_y)) plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot3d_parametric_surface(*args, show=True, **kwargs): """ Plots a 3D parametric surface plot. Explanation =========== Single plot. ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)`` If the ranges is not specified, then a default range of (-10, 10) is used. Multiple plots. ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= expr_x : Expression representing the function along ``x``. expr_y : Expression representing the function along ``y``. expr_z : Expression representing the function along ``z``. range_u : (:class:`~.Symbol`, float, float) A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5). range_v : (:class:`~.Symbol`, float, float) A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5). Keyword Arguments ================= Arguments for ``ParametricSurfaceSeries`` class: nb_of_points_u : int The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points nb_of_points_y : int The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points Aesthetics: surface_color : Function which returns a float Specifies the color for the surface of the plot. See :class:`~Plot` for more details. If there are multiple plots, then the same series arguments are applied for all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class: title : str Title of the plot. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols, cos, sin >>> from sympy.plotting import plot3d_parametric_surface >>> u, v = symbols('u v') Single plot. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v, ... (u, -5, 5), (v, -5, 5)) Plot object containing: [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0) See Also ======== Plot, ParametricSurfaceSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 3, 2) series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr] kwargs.setdefault("xlabel", "x") kwargs.setdefault("ylabel", "y") kwargs.setdefault("zlabel", "z") plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot_contour(*args, show=True, **kwargs): """ Draws contour plot of a function Usage ===== Single plot ``plot_contour(expr, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plot with the same range. ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plots with different ranges. ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= expr : Expression representing the function along x. range_x : (:class:`Symbol`, float, float) A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5). range_y : (:class:`Symbol`, float, float) A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5). Keyword Arguments ================= Arguments for ``ContourSeries`` class: nb_of_points_x : int The x range is sampled uniformly at ``nb_of_points_x`` of points. nb_of_points_y : int The y range is sampled uniformly at ``nb_of_points_y`` of points. Aesthetics: surface_color : Function which returns a float Specifies the color for the surface of the plot. See :class:`sympy.plotting.Plot` for more details. If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class: title : str Title of the plot. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. See Also ======== Plot, ContourSeries """ args = list(map(sympify, args)) plot_expr = check_arguments(args, 1, 2) series = [ContourSeries(*arg) for arg in plot_expr] plot_contours = Plot(*series, **kwargs) if len(plot_expr[0].free_symbols) > 2: raise ValueError('Contour Plot cannot Plot for more than two variables.') if show: plot_contours.show() return plot_contours def check_arguments(args, expr_len, nb_of_free_symbols): """ Checks the arguments and converts into tuples of the form (exprs, ranges). Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import cos, sin, symbols >>> from sympy.plotting.plot import check_arguments >>> x = symbols('x') >>> check_arguments([cos(x), sin(x)], 2, 1) [(cos(x), sin(x), (x, -10, 10))] >>> check_arguments([x, x**2], 1, 1) [(x, (x, -10, 10)), (x**2, (x, -10, 10))] """ if not args: return [] if expr_len > 1 and isinstance(args[0], Expr): # Multiple expressions same range. # The arguments are tuples when the expression length is # greater than 1. if len(args) < expr_len: raise ValueError("len(args) should not be less than expr_len") for i in range(len(args)): if isinstance(args[i], Tuple): break else: i = len(args) + 1 exprs = Tuple(*args[:i]) free_symbols = list(set().union(*[e.free_symbols for e in exprs])) if len(args) == expr_len + nb_of_free_symbols: #Ranges given plots = [exprs + Tuple(*args[expr_len:])] else: default_range = Tuple(-10, 10) ranges = [] for symbol in free_symbols: ranges.append(Tuple(symbol) + default_range) for i in range(len(free_symbols) - nb_of_free_symbols): ranges.append(Tuple(Dummy()) + default_range) plots = [exprs + Tuple(*ranges)] return plots if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and len(args[0]) == expr_len and expr_len != 3): # Cannot handle expressions with number of expression = 3. It is # not possible to differentiate between expressions and ranges. #Series of plots with same range for i in range(len(args)): if isinstance(args[i], Tuple) and len(args[i]) != expr_len: break if not isinstance(args[i], Tuple): args[i] = Tuple(args[i]) else: i = len(args) + 1 exprs = args[:i] assert all(isinstance(e, Expr) for expr in exprs for e in expr) free_symbols = list(set().union(*[e.free_symbols for expr in exprs for e in expr])) if len(free_symbols) > nb_of_free_symbols: raise ValueError("The number of free_symbols in the expression " "is greater than %d" % nb_of_free_symbols) if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple): ranges = Tuple(*[range_expr for range_expr in args[ i:i + nb_of_free_symbols]]) plots = [expr + ranges for expr in exprs] return plots else: # Use default ranges. default_range = Tuple(-10, 10) ranges = [] for symbol in free_symbols: ranges.append(Tuple(symbol) + default_range) for i in range(nb_of_free_symbols - len(free_symbols)): ranges.append(Tuple(Dummy()) + default_range) ranges = Tuple(*ranges) plots = [expr + ranges for expr in exprs] return plots elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols: # Multiple plots with different ranges. for arg in args: for i in range(expr_len): if not isinstance(arg[i], Expr): raise ValueError("Expected an expression, given %s" % str(arg[i])) for i in range(nb_of_free_symbols): if not len(arg[i + expr_len]) == 3: raise ValueError("The ranges should be a tuple of " "length 3, got %s" % str(arg[i + expr_len])) return args
c08bc1d36bddac8fa71095f74ea227b1fd2ff3bd39248e6571580c26c25bb4ed
""" rewrite of lambdify - This stuff is not stable at all. It is for internal use in the new plotting module. It may (will! see the Q'n'A in the source) be rewritten. It's completely self contained. Especially it does not use lambdarepr. It does not aim to replace the current lambdify. Most importantly it will never ever support anything else than SymPy expressions (no Matrices, dictionaries and so on). """ import re from sympy.core.numbers import (I, NumberSymbol, oo, zoo) from sympy.core.symbol import Symbol from sympy.utilities.iterables import numbered_symbols # We parse the expression string into a tree that identifies functions. Then # we translate the names of the functions and we translate also some strings # that are not names of functions (all this according to translation # dictionaries). # If the translation goes to another module (like numpy) the # module is imported and 'func' is translated to 'module.func'. # If a function can not be translated, the inner nodes of that part of the # tree are not translated. So if we have Integral(sqrt(x)), sqrt is not # translated to np.sqrt and the Integral does not crash. # A namespace for all this is generated by crawling the (func, args) tree of # the expression. The creation of this namespace involves many ugly # workarounds. # The namespace consists of all the names needed for the SymPy expression and # all the name of modules used for translation. Those modules are imported only # as a name (import numpy as np) in order to keep the namespace small and # manageable. # Please, if there is a bug, do not try to fix it here! Rewrite this by using # the method proposed in the last Q'n'A below. That way the new function will # work just as well, be just as simple, but it wont need any new workarounds. # If you insist on fixing it here, look at the workarounds in the function # sympy_expression_namespace and in lambdify. # Q: Why are you not using Python abstract syntax tree? # A: Because it is more complicated and not much more powerful in this case. # Q: What if I have Symbol('sin') or g=Function('f')? # A: You will break the algorithm. We should use srepr to defend against this? # The problem with Symbol('sin') is that it will be printed as 'sin'. The # parser will distinguish it from the function 'sin' because functions are # detected thanks to the opening parenthesis, but the lambda expression won't # understand the difference if we have also the sin function. # The solution (complicated) is to use srepr and maybe ast. # The problem with the g=Function('f') is that it will be printed as 'f' but in # the global namespace we have only 'g'. But as the same printer is used in the # constructor of the namespace there will be no problem. # Q: What if some of the printers are not printing as expected? # A: The algorithm wont work. You must use srepr for those cases. But even # srepr may not print well. All problems with printers should be considered # bugs. # Q: What about _imp_ functions? # A: Those are taken care for by evalf. A special case treatment will work # faster but it's not worth the code complexity. # Q: Will ast fix all possible problems? # A: No. You will always have to use some printer. Even srepr may not work in # some cases. But if the printer does not work, that should be considered a # bug. # Q: Is there same way to fix all possible problems? # A: Probably by constructing our strings ourself by traversing the (func, # args) tree and creating the namespace at the same time. That actually sounds # good. from sympy.external import import_module import warnings #TODO debugging output class vectorized_lambdify: """ Return a sufficiently smart, vectorized and lambdified function. Returns only reals. Explanation =========== This function uses experimental_lambdify to created a lambdified expression ready to be used with numpy. Many of the functions in SymPy are not implemented in numpy so in some cases we resort to Python cmath or even to evalf. The following translations are tried: only numpy complex - on errors raised by SymPy trying to work with ndarray: only Python cmath and then vectorize complex128 When using Python cmath there is no need for evalf or float/complex because Python cmath calls those. This function never tries to mix numpy directly with evalf because numpy does not understand SymPy Float. If this is needed one can use the float_wrap_evalf/complex_wrap_evalf options of experimental_lambdify or better one can be explicit about the dtypes that numpy works with. Check numpy bug http://projects.scipy.org/numpy/ticket/1013 to know what types of errors to expect. """ def __init__(self, args, expr): self.args = args self.expr = expr self.np = import_module('numpy') self.lambda_func_1 = experimental_lambdify( args, expr, use_np=True) self.vector_func_1 = self.lambda_func_1 self.lambda_func_2 = experimental_lambdify( args, expr, use_python_cmath=True) self.vector_func_2 = self.np.vectorize( self.lambda_func_2, otypes=[complex]) self.vector_func = self.vector_func_1 self.failure = False def __call__(self, *args): np = self.np try: temp_args = (np.array(a, dtype=complex) for a in args) results = self.vector_func(*temp_args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False) return results except ValueError: if self.failure: raise self.failure = True self.vector_func = self.vector_func_2 warnings.warn( 'The evaluation of the expression is problematic. ' 'We are trying a failback method that may still work. ' 'Please report this as a bug.') return self.__call__(*args) class lambdify: """Returns the lambdified function. Explanation =========== This function uses experimental_lambdify to create a lambdified expression. It uses cmath to lambdify the expression. If the function is not implemented in Python cmath, Python cmath calls evalf on those functions. """ def __init__(self, args, expr): self.args = args self.expr = expr self.lambda_func_1 = experimental_lambdify( args, expr, use_python_cmath=True, use_evalf=True) self.lambda_func_2 = experimental_lambdify( args, expr, use_python_math=True, use_evalf=True) self.lambda_func_3 = experimental_lambdify( args, expr, use_evalf=True, complex_wrap_evalf=True) self.lambda_func = self.lambda_func_1 self.failure = False def __call__(self, args): try: #The result can be sympy.Float. Hence wrap it with complex type. result = complex(self.lambda_func(args)) if abs(result.imag) > 1e-7 * abs(result): return None return result.real except (ZeroDivisionError, OverflowError): return None except TypeError as e: if self.failure: raise e if self.lambda_func == self.lambda_func_1: self.lambda_func = self.lambda_func_2 return self.__call__(args) self.failure = True self.lambda_func = self.lambda_func_3 warnings.warn( 'The evaluation of the expression is problematic. ' 'We are trying a failback method that may still work. ' 'Please report this as a bug.', stacklevel=2) return self.__call__(args) def experimental_lambdify(*args, **kwargs): l = Lambdifier(*args, **kwargs) return l class Lambdifier: def __init__(self, args, expr, print_lambda=False, use_evalf=False, float_wrap_evalf=False, complex_wrap_evalf=False, use_np=False, use_python_math=False, use_python_cmath=False, use_interval=False): self.print_lambda = print_lambda self.use_evalf = use_evalf self.float_wrap_evalf = float_wrap_evalf self.complex_wrap_evalf = complex_wrap_evalf self.use_np = use_np self.use_python_math = use_python_math self.use_python_cmath = use_python_cmath self.use_interval = use_interval # Constructing the argument string # - check if not all(isinstance(a, Symbol) for a in args): raise ValueError('The arguments must be Symbols.') # - use numbered symbols syms = numbered_symbols(exclude=expr.free_symbols) newargs = [next(syms) for _ in args] expr = expr.xreplace(dict(zip(args, newargs))) argstr = ', '.join([str(a) for a in newargs]) del syms, newargs, args # Constructing the translation dictionaries and making the translation self.dict_str = self.get_dict_str() self.dict_fun = self.get_dict_fun() exprstr = str(expr) newexpr = self.tree2str_translate(self.str2tree(exprstr)) # Constructing the namespaces namespace = {} namespace.update(self.sympy_atoms_namespace(expr)) namespace.update(self.sympy_expression_namespace(expr)) # XXX Workaround # Ugly workaround because Pow(a,Half) prints as sqrt(a) # and sympy_expression_namespace can not catch it. from sympy.functions.elementary.miscellaneous import sqrt namespace.update({'sqrt': sqrt}) namespace.update({'Eq': lambda x, y: x == y}) namespace.update({'Ne': lambda x, y: x != y}) # End workaround. if use_python_math: namespace.update({'math': __import__('math')}) if use_python_cmath: namespace.update({'cmath': __import__('cmath')}) if use_np: try: namespace.update({'np': __import__('numpy')}) except ImportError: raise ImportError( 'experimental_lambdify failed to import numpy.') if use_interval: namespace.update({'imath': __import__( 'sympy.plotting.intervalmath', fromlist=['intervalmath'])}) namespace.update({'math': __import__('math')}) # Construct the lambda if self.print_lambda: print(newexpr) eval_str = 'lambda %s : ( %s )' % (argstr, newexpr) self.eval_str = eval_str exec("MYNEWLAMBDA = %s" % eval_str, namespace) self.lambda_func = namespace['MYNEWLAMBDA'] def __call__(self, *args, **kwargs): return self.lambda_func(*args, **kwargs) ############################################################################## # Dicts for translating from SymPy to other modules ############################################################################## ### # builtins ### # Functions with different names in builtins builtin_functions_different = { 'Min': 'min', 'Max': 'max', 'Abs': 'abs', } # Strings that should be translated builtin_not_functions = { 'I': '1j', # 'oo': '1e400', } ### # numpy ### # Functions that are the same in numpy numpy_functions_same = [ 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'exp', 'log', 'sqrt', 'floor', 'conjugate', ] # Functions with different names in numpy numpy_functions_different = { "acos": "arccos", "acosh": "arccosh", "arg": "angle", "asin": "arcsin", "asinh": "arcsinh", "atan": "arctan", "atan2": "arctan2", "atanh": "arctanh", "ceiling": "ceil", "im": "imag", "ln": "log", "Max": "amax", "Min": "amin", "re": "real", "Abs": "abs", } # Strings that should be translated numpy_not_functions = { 'pi': 'np.pi', 'oo': 'np.inf', 'E': 'np.e', } ### # Python math ### # Functions that are the same in math math_functions_same = [ 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh', 'exp', 'log', 'erf', 'sqrt', 'floor', 'factorial', 'gamma', ] # Functions with different names in math math_functions_different = { 'ceiling': 'ceil', 'ln': 'log', 'loggamma': 'lgamma' } # Strings that should be translated math_not_functions = { 'pi': 'math.pi', 'E': 'math.e', } ### # Python cmath ### # Functions that are the same in cmath cmath_functions_same = [ 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh', 'exp', 'log', 'sqrt', ] # Functions with different names in cmath cmath_functions_different = { 'ln': 'log', 'arg': 'phase', } # Strings that should be translated cmath_not_functions = { 'pi': 'cmath.pi', 'E': 'cmath.e', } ### # intervalmath ### interval_not_functions = { 'pi': 'math.pi', 'E': 'math.e' } interval_functions_same = [ 'sin', 'cos', 'exp', 'tan', 'atan', 'log', 'sqrt', 'cosh', 'sinh', 'tanh', 'floor', 'acos', 'asin', 'acosh', 'asinh', 'atanh', 'Abs', 'And', 'Or' ] interval_functions_different = { 'Min': 'imin', 'Max': 'imax', 'ceiling': 'ceil', } ### # mpmath, etc ### #TODO ### # Create the final ordered tuples of dictionaries ### # For strings def get_dict_str(self): dict_str = dict(self.builtin_not_functions) if self.use_np: dict_str.update(self.numpy_not_functions) if self.use_python_math: dict_str.update(self.math_not_functions) if self.use_python_cmath: dict_str.update(self.cmath_not_functions) if self.use_interval: dict_str.update(self.interval_not_functions) return dict_str # For functions def get_dict_fun(self): dict_fun = dict(self.builtin_functions_different) if self.use_np: for s in self.numpy_functions_same: dict_fun[s] = 'np.' + s for k, v in self.numpy_functions_different.items(): dict_fun[k] = 'np.' + v if self.use_python_math: for s in self.math_functions_same: dict_fun[s] = 'math.' + s for k, v in self.math_functions_different.items(): dict_fun[k] = 'math.' + v if self.use_python_cmath: for s in self.cmath_functions_same: dict_fun[s] = 'cmath.' + s for k, v in self.cmath_functions_different.items(): dict_fun[k] = 'cmath.' + v if self.use_interval: for s in self.interval_functions_same: dict_fun[s] = 'imath.' + s for k, v in self.interval_functions_different.items(): dict_fun[k] = 'imath.' + v return dict_fun ############################################################################## # The translator functions, tree parsers, etc. ############################################################################## def str2tree(self, exprstr): """Converts an expression string to a tree. Explanation =========== Functions are represented by ('func_name(', tree_of_arguments). Other expressions are (head_string, mid_tree, tail_str). Expressions that do not contain functions are directly returned. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy import Integral, sin >>> from sympy.plotting.experimental_lambdify import Lambdifier >>> str2tree = Lambdifier([x], x).str2tree >>> str2tree(str(Integral(x, (x, 1, y)))) ('', ('Integral(', 'x, (x, 1, y)'), ')') >>> str2tree(str(x+y)) 'x + y' >>> str2tree(str(x+y*sin(z)+1)) ('x + y*', ('sin(', 'z'), ') + 1') >>> str2tree('sin(y*(y + 1.1) + (sin(y)))') ('', ('sin(', ('y*(y + 1.1) + (', ('sin(', 'y'), '))')), ')') """ #matches the first 'function_name(' first_par = re.search(r'(\w+\()', exprstr) if first_par is None: return exprstr else: start = first_par.start() end = first_par.end() head = exprstr[:start] func = exprstr[start:end] tail = exprstr[end:] count = 0 for i, c in enumerate(tail): if c == '(': count += 1 elif c == ')': count -= 1 if count == -1: break func_tail = self.str2tree(tail[:i]) tail = self.str2tree(tail[i:]) return (head, (func, func_tail), tail) @classmethod def tree2str(cls, tree): """Converts a tree to string without translations. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy import sin >>> from sympy.plotting.experimental_lambdify import Lambdifier >>> str2tree = Lambdifier([x], x).str2tree >>> tree2str = Lambdifier([x], x).tree2str >>> tree2str(str2tree(str(x+y*sin(z)+1))) 'x + y*sin(z) + 1' """ if isinstance(tree, str): return tree else: return ''.join(map(cls.tree2str, tree)) def tree2str_translate(self, tree): """Converts a tree to string with translations. Explanation =========== Function names are translated by translate_func. Other strings are translated by translate_str. """ if isinstance(tree, str): return self.translate_str(tree) elif isinstance(tree, tuple) and len(tree) == 2: return self.translate_func(tree[0][:-1], tree[1]) else: return ''.join([self.tree2str_translate(t) for t in tree]) def translate_str(self, estr): """Translate substrings of estr using in order the dictionaries in dict_tuple_str.""" for pattern, repl in self.dict_str.items(): estr = re.sub(pattern, repl, estr) return estr def translate_func(self, func_name, argtree): """Translate function names and the tree of arguments. Explanation =========== If the function name is not in the dictionaries of dict_tuple_fun then the function is surrounded by a float((...).evalf()). The use of float is necessary as np.<function>(sympy.Float(..)) raises an error.""" if func_name in self.dict_fun: new_name = self.dict_fun[func_name] argstr = self.tree2str_translate(argtree) return new_name + '(' + argstr elif func_name in ['Eq', 'Ne']: op = {'Eq': '==', 'Ne': '!='} return "(lambda x, y: x {} y)({}".format(op[func_name], self.tree2str_translate(argtree)) else: template = '(%s(%s)).evalf(' if self.use_evalf else '%s(%s' if self.float_wrap_evalf: template = 'float(%s)' % template elif self.complex_wrap_evalf: template = 'complex(%s)' % template # Wrapping should only happen on the outermost expression, which # is the only thing we know will be a number. float_wrap_evalf = self.float_wrap_evalf complex_wrap_evalf = self.complex_wrap_evalf self.float_wrap_evalf = False self.complex_wrap_evalf = False ret = template % (func_name, self.tree2str_translate(argtree)) self.float_wrap_evalf = float_wrap_evalf self.complex_wrap_evalf = complex_wrap_evalf return ret ############################################################################## # The namespace constructors ############################################################################## @classmethod def sympy_expression_namespace(cls, expr): """Traverses the (func, args) tree of an expression and creates a SymPy namespace. All other modules are imported only as a module name. That way the namespace is not polluted and rests quite small. It probably causes much more variable lookups and so it takes more time, but there are no tests on that for the moment.""" if expr is None: return {} else: funcname = str(expr.func) # XXX Workaround # Here we add an ugly workaround because str(func(x)) # is not always the same as str(func). Eg # >>> str(Integral(x)) # "Integral(x)" # >>> str(Integral) # "<class 'sympy.integrals.integrals.Integral'>" # >>> str(sqrt(x)) # "sqrt(x)" # >>> str(sqrt) # "<function sqrt at 0x3d92de8>" # >>> str(sin(x)) # "sin(x)" # >>> str(sin) # "sin" # Either one of those can be used but not all at the same time. # The code considers the sin example as the right one. regexlist = [ r'<class \'sympy[\w.]*?.([\w]*)\'>$', # the example Integral r'<function ([\w]*) at 0x[\w]*>$', # the example sqrt ] for r in regexlist: m = re.match(r, funcname) if m is not None: funcname = m.groups()[0] # End of the workaround # XXX debug: print funcname args_dict = {} for a in expr.args: if (isinstance(a, Symbol) or isinstance(a, NumberSymbol) or a in [I, zoo, oo]): continue else: args_dict.update(cls.sympy_expression_namespace(a)) args_dict.update({funcname: expr.func}) return args_dict @staticmethod def sympy_atoms_namespace(expr): """For no real reason this function is separated from sympy_expression_namespace. It can be moved to it.""" atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo) d = {} for a in atoms: # XXX debug: print 'atom:' + str(a) d[str(a)] = a return d
cec3bbd01ed13631a1b3c03aa6246950acfd0a789893aea02df61b07a8b75f9f
from sympy.concrete.summations import Sum from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.function import Lambda from sympy.core.numbers import (Rational, nan, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (FallingFactorial, binomial) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import DiracDelta from sympy.integrals.integrals import integrate from sympy.logic.boolalg import (And, Or) from sympy.matrices.dense import Matrix from sympy.sets.sets import Interval from sympy.tensor.indexed import Indexed from sympy.stats import (Die, Normal, Exponential, FiniteRV, P, E, H, variance, density, given, independent, dependent, where, pspace, GaussianUnitaryEnsemble, random_symbols, sample, Geometric, factorial_moment, Binomial, Hypergeometric, DiscreteUniform, Poisson, characteristic_function, moment_generating_function, BernoulliProcess, Variance, Expectation, Probability, Covariance, covariance, cmoment, moment, median) from sympy.stats.rv import (IndependentProductPSpace, rs_swap, Density, NamedArgsMixin, RandomSymbol, sample_iter, PSpace, is_random, RandomIndexedSymbol, RandomMatrixSymbol) from sympy.testing.pytest import raises, skip, XFAIL, warns_deprecated_sympy from sympy.external import import_module from sympy.core.numbers import comp from sympy.stats.frv_types import BernoulliDistribution from sympy.core.symbol import Dummy from sympy.functions.elementary.piecewise import Piecewise def test_where(): X, Y = Die('X'), Die('Y') Z = Normal('Z', 0, 1) assert where(Z**2 <= 1).set == Interval(-1, 1) assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol) assert where(And(X > Y, Y > 4)).as_boolean() == And( Eq(X.symbol, 6), Eq(Y.symbol, 5)) assert len(where(X < 3).set) == 2 assert 1 in where(X < 3).set X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) XX = given(X, And(X**2 <= 1, X >= 0)) assert XX.pspace.domain.set == Interval(0, 1) assert XX.pspace.domain.as_boolean() == \ And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo) with raises(TypeError): XX = given(X, X + 3) def test_random_symbols(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert set(random_symbols(2*X + 1)) == {X} assert set(random_symbols(2*X + Y)) == {X, Y} assert set(random_symbols(2*X + Y.symbol)) == {X} assert set(random_symbols(2)) == set() def test_characteristic_function(): # Imports I from sympy from sympy.core.numbers import I X = Normal('X',0,1) Y = DiscreteUniform('Y', [1,2,7]) Z = Poisson('Z', 2) t = symbols('_t') P = Lambda(t, exp(-t**2/2)) Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3) R = Lambda(t, exp(2 * exp(t*I) - 2)) assert characteristic_function(X).dummy_eq(P) assert characteristic_function(Y).dummy_eq(Q) assert characteristic_function(Z).dummy_eq(R) def test_moment_generating_function(): X = Normal('X',0,1) Y = DiscreteUniform('Y', [1,2,7]) Z = Poisson('Z', 2) t = symbols('_t') P = Lambda(t, exp(t**2/2)) Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3)) R = Lambda(t, exp(2 * exp(t) - 2)) assert moment_generating_function(X).dummy_eq(P) assert moment_generating_function(Y).dummy_eq(Q) assert moment_generating_function(Z).dummy_eq(R) def test_sample_iter(): X = Normal('X',0,1) Y = DiscreteUniform('Y', [1, 2, 7]) Z = Poisson('Z', 2) scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') expr = X**2 + 3 iterator = sample_iter(expr) expr2 = Y**2 + 5*Y + 4 iterator2 = sample_iter(expr2) expr3 = Z**3 + 4 iterator3 = sample_iter(expr3) def is_iterator(obj): if ( hasattr(obj, '__iter__') and (hasattr(obj, 'next') or hasattr(obj, '__next__')) and callable(obj.__iter__) and obj.__iter__() is obj ): return True else: return False assert is_iterator(iterator) assert is_iterator(iterator2) assert is_iterator(iterator3) def test_pspace(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) x = Symbol('x') raises(ValueError, lambda: pspace(5 + 3)) raises(ValueError, lambda: pspace(x < 1)) assert pspace(X) == X.pspace assert pspace(2*X + 1) == X.pspace assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace) def test_rs_swap(): X = Normal('x', 0, 1) Y = Exponential('y', 1) XX = Normal('x', 0, 2) YY = Normal('y', 0, 3) expr = 2*X + Y assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY def test_RandomSymbol(): X = Normal('x', 0, 1) Y = Normal('x', 0, 2) assert X.symbol == Y.symbol assert X != Y assert X.name == X.symbol.name X = Normal('lambda', 0, 1) # make sure we can use protected terms X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms def test_RandomSymbol_diff(): X = Normal('x', 0, 1) assert (2*X).diff(X) def test_random_symbol_no_pspace(): x = RandomSymbol(Symbol('x')) assert x.pspace == PSpace() def test_overlap(): X = Normal('x', 0, 1) Y = Normal('x', 0, 2) raises(ValueError, lambda: P(X > Y)) def test_IndependentProductPSpace(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) px = X.pspace py = Y.pspace assert pspace(X + Y) == IndependentProductPSpace(px, py) assert pspace(X + Y) == IndependentProductPSpace(py, px) def test_E(): assert E(5) == 5 def test_H(): X = Normal('X', 0, 1) D = Die('D', sides = 4) G = Geometric('G', 0.5) assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2 assert H(D, D > 2) == log(2) assert comp(H(G).evalf().round(2), 1.39) def test_Sample(): X = Die('X', 6) Y = Normal('Y', 0, 1) z = Symbol('z', integer=True) scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') assert sample(X) in [1, 2, 3, 4, 5, 6] assert isinstance(sample(X + Y), float) assert P(X + Y > 0, Y < 0, numsamples=10).is_number assert E(X + Y, numsamples=10).is_number assert E(X**2 + Y, numsamples=10).is_number assert E((X + Y)**2, numsamples=10).is_number assert variance(X + Y, numsamples=10).is_number raises(TypeError, lambda: P(Y > z, numsamples=5)) assert P(sin(Y) <= 1, numsamples=10) == 1 assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1 assert all(i in range(1, 7) for i in density(X, numsamples=10)) assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10)) numpy = import_module('numpy') if not numpy: skip('Numpy is not installed. Abort tests') #Test Issue #21563: Output of sample must be a float or array assert isinstance(sample(X), (numpy.int32, numpy.int64)) assert isinstance(sample(Y), numpy.float64) assert isinstance(sample(X, size=2), numpy.ndarray) with warns_deprecated_sympy(): sample(X, numsamples=2) @XFAIL def test_samplingE(): scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') Y = Normal('Y', 0, 1) z = Symbol('z', integer=True) assert E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3).is_number def test_given(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) A = given(X, True) B = given(X, Y > 2) assert X == A == B def test_factorial_moment(): X = Poisson('X', 2) Y = Binomial('Y', 2, S.Half) Z = Hypergeometric('Z', 4, 2, 2) assert factorial_moment(X, 2) == 4 assert factorial_moment(Y, 2) == S.Half assert factorial_moment(Z, 2) == Rational(1, 3) x, y, z, l = symbols('x y z l') Y = Binomial('Y', 2, y) Z = Hypergeometric('Z', 10, 2, 3) assert factorial_moment(Y, l) == y**2*FallingFactorial( 2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\ FallingFactorial(0, l) assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\ 15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15 def test_dependence(): X, Y = Die('X'), Die('Y') assert independent(X, 2*Y) assert not dependent(X, 2*Y) X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert independent(X, Y) assert dependent(X, 2*X) # Create a dependency XX, YY = given(Tuple(X, Y), Eq(X + Y, 3)) assert dependent(XX, YY) def test_dependent_finite(): X, Y = Die('X'), Die('Y') # Dependence testing requires symbolic conditions which currently break # finite random variables assert dependent(X, Y + X) XX, YY = given(Tuple(X, Y), X + Y > 5) # Create a dependency assert dependent(XX, YY) def test_normality(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) x = Symbol('x', real=True) z = Symbol('z', real=True) dens = density(X - Y, Eq(X + Y, z)) assert integrate(dens(x), (x, -oo, oo)) == 1 def test_Density(): X = Die('X', 6) d = Density(X) assert d.doit() == density(X) def test_NamedArgsMixin(): class Foo(Basic, NamedArgsMixin): _argnames = 'foo', 'bar' a = Foo(S(1), S(2)) assert a.foo == 1 assert a.bar == 2 raises(AttributeError, lambda: a.baz) class Bar(Basic, NamedArgsMixin): pass raises(AttributeError, lambda: Bar(S(1), S(2)).foo) def test_density_constant(): assert density(3)(2) == 0 assert density(3)(3) == DiracDelta(0) def test_cmoment_constant(): assert variance(3) == 0 assert cmoment(3, 3) == 0 assert cmoment(3, 4) == 0 x = Symbol('x') assert variance(x) == 0 assert cmoment(x, 15) == 0 assert cmoment(x, 0) == 1 def test_moment_constant(): assert moment(3, 0) == 1 assert moment(3, 1) == 3 assert moment(3, 2) == 9 x = Symbol('x') assert moment(x, 2) == x**2 def test_median_constant(): assert median(3) == 3 x = Symbol('x') assert median(x) == x def test_real(): x = Normal('x', 0, 1) assert x.is_real def test_issue_10052(): X = Exponential('X', 3) assert P(X < oo) == 1 assert P(X > oo) == 0 assert P(X < 2, X > oo) == 0 assert P(X < oo, X > oo) == 0 assert P(X < oo, X > 2) == 1 assert P(X < 3, X == 2) == 0 raises(ValueError, lambda: P(1)) raises(ValueError, lambda: P(X < 1, 2)) def test_issue_11934(): density = {0: .5, 1: .5} X = FiniteRV('X', density) assert E(X) == 0.5 assert P( X>= 2) == 0 def test_issue_8129(): X = Exponential('X', 4) assert P(X >= X) == 1 assert P(X > X) == 0 assert P(X > X+1) == 0 def test_issue_12237(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) U = P(X > 0, X) V = P(Y < 0, X) W = P(X + Y > 0, X) assert W == P(X + Y > 0, X) assert U == BernoulliDistribution(S.Half, S.Zero, S.One) assert V == S.Half def test_is_random(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) a, b = symbols('a, b') G = GaussianUnitaryEnsemble('U', 2) B = BernoulliProcess('B', 0.9) assert not is_random(a) assert not is_random(a + b) assert not is_random(a * b) assert not is_random(Matrix([a**2, b**2])) assert is_random(X) assert is_random(X**2 + Y) assert is_random(Y + b**2) assert is_random(Y > 5) assert is_random(B[3] < 1) assert is_random(G) assert is_random(X * Y * B[1]) assert is_random(Matrix([[X, B[2]], [G, Y]])) assert is_random(Eq(X, 4)) def test_issue_12283(): x = symbols('x') X = RandomSymbol(x) Y = RandomSymbol('Y') Z = RandomMatrixSymbol('Z', 2, 1) W = RandomMatrixSymbol('W', 2, 1) RI = RandomIndexedSymbol(Indexed('RI', 3)) assert pspace(Z) == PSpace() assert pspace(RI) == PSpace() assert pspace(X) == PSpace() assert E(X) == Expectation(X) assert P(Y > 3) == Probability(Y > 3) assert variance(X) == Variance(X) assert variance(RI) == Variance(RI) assert covariance(X, Y) == Covariance(X, Y) assert covariance(W, Z) == Covariance(W, Z) def test_issue_6810(): X = Die('X', 6) Y = Normal('Y', 0, 1) assert P(Eq(X, 2)) == S(1)/6 assert P(Eq(Y, 0)) == 0 assert P(Or(X > 2, X < 3)) == 1 assert P(And(X > 3, X > 2)) == S(1)/2 def test_issue_20286(): n, p = symbols('n p') B = Binomial('B', n, p) k = Dummy('k', integer = True) eq = Sum(Piecewise((-p**k*(1 - p)**(-k + n)*log(p**k*(1 - p)**(-k + n)*binomial(n, k))*binomial(n, k), (k >= 0) & (k <= n)), (nan, True)), (k, 0, n)) assert eq.dummy_eq(H(B))
c4a3a6ce5d46652fb0b21e2986306b78a30795aacc5d046429d5966a96eeb3d5
from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.numbers import (Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial) from sympy.functions.elementary.complexes import polar_lift from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.bessel import besselk from sympy.functions.special.gamma_functions import gamma from sympy.matrices.dense import eye from sympy.matrices.expressions.determinant import Determinant from sympy.sets.fancysets import Range from sympy.sets.sets import (Interval, ProductSet) from sympy.simplify.simplify import simplify from sympy.tensor.indexed import (Indexed, IndexedBase) from sympy.core.numbers import comp from sympy.integrals.integrals import integrate from sympy.matrices import Matrix, MatrixSymbol from sympy.matrices.expressions.matexpr import MatrixElement from sympy.stats import density, median, marginal_distribution, Normal, Laplace, E, sample from sympy.stats.joint_rv_types import (JointRV, MultivariateNormalDistribution, JointDistributionHandmade, MultivariateT, NormalGamma, GeneralizedMultivariateLogGammaOmega as GMVLGO, MultivariateBeta, GeneralizedMultivariateLogGamma as GMVLG, MultivariateEwens, Multinomial, NegativeMultinomial, MultivariateNormal, MultivariateLaplace) from sympy.testing.pytest import raises, XFAIL, skip, slow from sympy.external import import_module from sympy.abc import x, y def test_Normal(): m = Normal('A', [1, 2], [[1, 0], [0, 1]]) A = MultivariateNormal('A', [1, 2], [[1, 0], [0, 1]]) assert m == A assert density(m)(1, 2) == 1/(2*pi) assert m.pspace.distribution.set == ProductSet(S.Reals, S.Reals) raises (ValueError, lambda:m[2]) n = Normal('B', [1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) p = Normal('C', Matrix([1, 2]), Matrix([[1, 0], [0, 1]])) assert density(m)(x, y) == density(p)(x, y) assert marginal_distribution(n, 0, 1)(1, 2) == 1/(2*pi) raises(ValueError, lambda: marginal_distribution(m)) assert integrate(density(m)(x, y), (x, -oo, oo), (y, -oo, oo)).evalf() == 1 N = Normal('N', [1, 2], [[x, 0], [0, y]]) assert density(N)(0, 0) == exp(-((4*x + y)/(2*x*y)))/(2*pi*sqrt(x*y)) raises (ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]])) # symbolic n = symbols('n', integer=True, positive=True) mu = MatrixSymbol('mu', n, 1) sigma = MatrixSymbol('sigma', n, n) X = Normal('X', mu, sigma) assert density(X) == MultivariateNormalDistribution(mu, sigma) raises (NotImplementedError, lambda: median(m)) # Below tests should work after issue #17267 is resolved # assert E(X) == mu # assert variance(X) == sigma # test symbolic multivariate normal densities n = 3 Sg = MatrixSymbol('Sg', n, n) mu = MatrixSymbol('mu', n, 1) obs = MatrixSymbol('obs', n, 1) X = MultivariateNormal('X', mu, Sg) density_X = density(X) eval_a = density_X(obs).subs({Sg: eye(3), mu: Matrix([0, 0, 0]), obs: Matrix([0, 0, 0])}).doit() eval_b = density_X(0, 0, 0).subs({Sg: eye(3), mu: Matrix([0, 0, 0])}).doit() assert eval_a == sqrt(2)/(4*pi**Rational(3/2)) assert eval_b == sqrt(2)/(4*pi**Rational(3/2)) n = symbols('n', integer=True, positive=True) Sg = MatrixSymbol('Sg', n, n) mu = MatrixSymbol('mu', n, 1) obs = MatrixSymbol('obs', n, 1) X = MultivariateNormal('X', mu, Sg) density_X_at_obs = density(X)(obs) expected_density = MatrixElement( exp((S(1)/2) * (mu.T - obs.T) * Sg**(-1) * (-mu + obs)) / \ sqrt((2*pi)**n * Determinant(Sg)), 0, 0) assert density_X_at_obs == expected_density def test_MultivariateTDist(): t1 = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2) assert(density(t1))(1, 1) == 1/(8*pi) assert t1.pspace.distribution.set == ProductSet(S.Reals, S.Reals) assert integrate(density(t1)(x, y), (x, -oo, oo), \ (y, -oo, oo)).evalf() == 1 raises(ValueError, lambda: MultivariateT('T', [1, 2], [[1, 1], [1, -1]], 1)) t2 = MultivariateT('t2', [1, 2], [[x, 0], [0, y]], 1) assert density(t2)(1, 2) == 1/(2*pi*sqrt(x*y)) def test_multivariate_laplace(): raises(ValueError, lambda: Laplace('T', [1, 2], [[1, 2], [2, 1]])) L = Laplace('L', [1, 0], [[1, 0], [0, 1]]) L2 = MultivariateLaplace('L2', [1, 0], [[1, 0], [0, 1]]) assert density(L)(2, 3) == exp(2)*besselk(0, sqrt(39))/pi L1 = Laplace('L1', [1, 2], [[x, 0], [0, y]]) assert density(L1)(0, 1) == \ exp(2/y)*besselk(0, sqrt((2 + 4/y + 1/x)/y))/(pi*sqrt(x*y)) assert L.pspace.distribution.set == ProductSet(S.Reals, S.Reals) assert L.pspace.distribution == L2.pspace.distribution def test_NormalGamma(): ng = NormalGamma('G', 1, 2, 3, 4) assert density(ng)(1, 1) == 32*exp(-4)/sqrt(pi) assert ng.pspace.distribution.set == ProductSet(S.Reals, Interval(0, oo)) raises(ValueError, lambda:NormalGamma('G', 1, 2, 3, -1)) assert marginal_distribution(ng, 0)(1) == \ 3*sqrt(10)*gamma(Rational(7, 4))/(10*sqrt(pi)*gamma(Rational(5, 4))) assert marginal_distribution(ng, y)(1) == exp(Rational(-1, 4))/128 assert marginal_distribution(ng,[0,1])(x) == x**2*exp(-x/4)/128 def test_GeneralizedMultivariateLogGammaDistribution(): h = S.Half omega = Matrix([[1, h, h, h], [h, 1, h, h], [h, h, 1, h], [h, h, h, 1]]) v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4]) y_1, y_2, y_3, y_4 = symbols('y_1:5', real=True) delta = symbols('d', positive=True) G = GMVLGO('G', omega, v, l, mu) Gd = GMVLG('Gd', delta, v, l, mu) dend = ("d**4*Sum(4*24**(-n - 4)*(1 - d)**n*exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 " "+ 4*y_4) - exp(y_1) - exp(2*y_2)/2 - exp(3*y_3)/3 - exp(4*y_4)/4)/" "(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))") assert str(density(Gd)(y_1, y_2, y_3, y_4)) == dend den = ("5*2**(2/3)*5**(1/3)*Sum(4*24**(-n - 4)*(-2**(2/3)*5**(1/3)/4 + 1)**n*" "exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 + 4*y_4) - exp(y_1) - exp(2*y_2)/2 - " "exp(3*y_3)/3 - exp(4*y_4)/4)/(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))/64") assert str(density(G)(y_1, y_2, y_3, y_4)) == den marg = ("5*2**(2/3)*5**(1/3)*exp(4*y_1)*exp(-exp(y_1))*Integral(exp(-exp(4*G[3])" "/4)*exp(16*G[3])*Integral(exp(-exp(3*G[2])/3)*exp(12*G[2])*Integral(exp(" "-exp(2*G[1])/2)*exp(8*G[1])*Sum((-1/4)**n*(-4 + 2**(2/3)*5**(1/3" "))**n*exp(n*y_1)*exp(2*n*G[1])*exp(3*n*G[2])*exp(4*n*G[3])/(24**n*gamma(n + 1)" "*gamma(n + 4)**3), (n, 0, oo)), (G[1], -oo, oo)), (G[2], -oo, oo)), (G[3]" ", -oo, oo))/5308416") assert str(marginal_distribution(G, G[0])(y_1)) == marg omega_f1 = Matrix([[1, h, h]]) omega_f2 = Matrix([[1, h, h, h], [h, 1, 2, h], [h, h, 1, h], [h, h, h, 1]]) omega_f3 = Matrix([[6, h, h, h], [h, 1, 2, h], [h, h, 1, h], [h, h, h, 1]]) v_f = symbols("v_f", positive=False, real=True) l_f = [1, 2, v_f, 4] m_f = [v_f, 2, 3, 4] omega_f4 = Matrix([[1, h, h, h, h], [h, 1, h, h, h], [h, h, 1, h, h], [h, h, h, 1, h], [h, h, h, h, 1]]) l_f1 = [1, 2, 3, 4, 5] omega_f5 = Matrix([[1]]) mu_f5 = l_f5 = [1] raises(ValueError, lambda: GMVLGO('G', omega_f1, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega_f2, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega_f3, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v_f, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v, l_f, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v, l, m_f)) raises(ValueError, lambda: GMVLGO('G', omega_f4, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v, l_f1, mu)) raises(ValueError, lambda: GMVLGO('G', omega_f5, v, l_f5, mu_f5)) raises(ValueError, lambda: GMVLG('G', Rational(3, 2), v, l, mu)) def test_MultivariateBeta(): a1, a2 = symbols('a1, a2', positive=True) a1_f, a2_f = symbols('a1, a2', positive=False, real=True) mb = MultivariateBeta('B', [a1, a2]) mb_c = MultivariateBeta('C', a1, a2) assert density(mb)(1, 2) == S(2)**(a2 - 1)*gamma(a1 + a2)/\ (gamma(a1)*gamma(a2)) assert marginal_distribution(mb_c, 0)(3) == S(3)**(a1 - 1)*gamma(a1 + a2)/\ (a2*gamma(a1)*gamma(a2)) raises(ValueError, lambda: MultivariateBeta('b1', [a1_f, a2])) raises(ValueError, lambda: MultivariateBeta('b2', [a1, a2_f])) raises(ValueError, lambda: MultivariateBeta('b3', [0, 0])) raises(ValueError, lambda: MultivariateBeta('b4', [a1_f, a2_f])) assert mb.pspace.distribution.set == ProductSet(Interval(0, 1), Interval(0, 1)) def test_MultivariateEwens(): n, theta, i = symbols('n theta i', positive=True) # tests for integer dimensions theta_f = symbols('t_f', negative=True) a = symbols('a_1:4', positive = True, integer = True) ed = MultivariateEwens('E', 3, theta) assert density(ed)(a[0], a[1], a[2]) == Piecewise((6*2**(-a[1])*3**(-a[2])* theta**a[0]*theta**a[1]*theta**a[2]/ (theta*(theta + 1)*(theta + 2)* factorial(a[0])*factorial(a[1])* factorial(a[2])), Eq(a[0] + 2*a[1] + 3*a[2], 3)), (0, True)) assert marginal_distribution(ed, ed[1])(a[1]) == Piecewise((6*2**(-a[1])* theta**a[1]/((theta + 1)* (theta + 2)*factorial(a[1])), Eq(2*a[1] + 1, 3)), (0, True)) raises(ValueError, lambda: MultivariateEwens('e1', 5, theta_f)) assert ed.pspace.distribution.set == ProductSet(Range(0, 4, 1), Range(0, 2, 1), Range(0, 2, 1)) # tests for symbolic dimensions eds = MultivariateEwens('E', n, theta) a = IndexedBase('a') j, k = symbols('j, k') den = Piecewise((factorial(n)*Product(theta**a[j]*(j + 1)**(-a[j])/ factorial(a[j]), (j, 0, n - 1))/RisingFactorial(theta, n), Eq(n, Sum((k + 1)*a[k], (k, 0, n - 1)))), (0, True)) assert density(eds)(a).dummy_eq(den) def test_Multinomial(): n, x1, x2, x3, x4 = symbols('n, x1, x2, x3, x4', nonnegative=True, integer=True) p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True) p1_f, n_f = symbols('p1_f, n_f', negative=True) M = Multinomial('M', n, [p1, p2, p3, p4]) C = Multinomial('C', 3, p1, p2, p3) f = factorial assert density(M)(x1, x2, x3, x4) == Piecewise((p1**x1*p2**x2*p3**x3*p4**x4* f(n)/(f(x1)*f(x2)*f(x3)*f(x4)), Eq(n, x1 + x2 + x3 + x4)), (0, True)) assert marginal_distribution(C, C[0])(x1).subs(x1, 1) ==\ 3*p1*p2**2 +\ 6*p1*p2*p3 +\ 3*p1*p3**2 raises(ValueError, lambda: Multinomial('b1', 5, [p1, p2, p3, p1_f])) raises(ValueError, lambda: Multinomial('b2', n_f, [p1, p2, p3, p4])) raises(ValueError, lambda: Multinomial('b3', n, 0.5, 0.4, 0.3, 0.1)) def test_NegativeMultinomial(): k0, x1, x2, x3, x4 = symbols('k0, x1, x2, x3, x4', nonnegative=True, integer=True) p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True) p1_f = symbols('p1_f', negative=True) N = NegativeMultinomial('N', 4, [p1, p2, p3, p4]) C = NegativeMultinomial('C', 4, 0.1, 0.2, 0.3) g = gamma f = factorial assert simplify(density(N)(x1, x2, x3, x4) - p1**x1*p2**x2*p3**x3*p4**x4*(-p1 - p2 - p3 - p4 + 1)**4*g(x1 + x2 + x3 + x4 + 4)/(6*f(x1)*f(x2)*f(x3)*f(x4))) is S.Zero assert comp(marginal_distribution(C, C[0])(1).evalf(), 0.33, .01) raises(ValueError, lambda: NegativeMultinomial('b1', 5, [p1, p2, p3, p1_f])) raises(ValueError, lambda: NegativeMultinomial('b2', k0, 0.5, 0.4, 0.3, 0.4)) assert N.pspace.distribution.set == ProductSet(Range(0, oo, 1), Range(0, oo, 1), Range(0, oo, 1), Range(0, oo, 1)) @slow def test_JointPSpace_marginal_distribution(): T = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2) got = marginal_distribution(T, T[1])(x) ans = sqrt(2)*(x**2/2 + 1)/(4*polar_lift(x**2/2 + 1)**(S(5)/2)) assert got == ans, got assert integrate(marginal_distribution(T, 1)(x), (x, -oo, oo)) == 1 t = MultivariateT('T', [0, 0, 0], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 3) assert comp(marginal_distribution(t, 0)(1).evalf(), 0.2, .01) def test_JointRV(): x1, x2 = (Indexed('x', i) for i in (1, 2)) pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi) X = JointRV('x', pdf) assert density(X)(1, 2) == exp(-2)/(2*pi) assert isinstance(X.pspace.distribution, JointDistributionHandmade) assert marginal_distribution(X, 0)(2) == sqrt(2)*exp(Rational(-1, 2))/(2*sqrt(pi)) def test_expectation(): m = Normal('A', [x, y], [[1, 0], [0, 1]]) assert simplify(E(m[1])) == y @XFAIL def test_joint_vector_expectation(): m = Normal('A', [x, y], [[1, 0], [0, 1]]) assert E(m) == (x, y) def test_sample_numpy(): distribs_numpy = [ MultivariateNormal("M", [3, 4], [[2, 1], [1, 2]]), MultivariateBeta("B", [0.4, 5, 15, 50, 203]), Multinomial("N", 50, [0.3, 0.2, 0.1, 0.25, 0.15]) ] size = 3 numpy = import_module('numpy') if not numpy: skip('Numpy is not installed. Abort tests for _sample_numpy.') else: for X in distribs_numpy: samps = sample(X, size=size, library='numpy') for sam in samps: assert tuple(sam) in X.pspace.distribution.set N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) raises(NotImplementedError, lambda: sample(N_c, library='numpy')) def test_sample_scipy(): distribs_scipy = [ MultivariateNormal("M", [0, 0], [[0.1, 0.025], [0.025, 0.1]]), MultivariateBeta("B", [0.4, 5, 15]), Multinomial("N", 8, [0.3, 0.2, 0.1, 0.4]) ] size = 3 scipy = import_module('scipy') if not scipy: skip('Scipy not installed. Abort tests for _sample_scipy.') else: for X in distribs_scipy: samps = sample(X, size=size) samps2 = sample(X, size=(2, 2)) for sam in samps: assert tuple(sam) in X.pspace.distribution.set for i in range(2): for j in range(2): assert tuple(samps2[i][j]) in X.pspace.distribution.set N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) raises(NotImplementedError, lambda: sample(N_c)) def test_sample_pymc3(): distribs_pymc3 = [ MultivariateNormal("M", [5, 2], [[1, 0], [0, 1]]), MultivariateBeta("B", [0.4, 5, 15]), Multinomial("N", 4, [0.3, 0.2, 0.1, 0.4]) ] size = 3 pymc3 = import_module('pymc3') if not pymc3: skip('PyMC3 is not installed. Abort tests for _sample_pymc3.') else: for X in distribs_pymc3: samps = sample(X, size=size, library='pymc3') for sam in samps: assert tuple(sam.flatten()) in X.pspace.distribution.set N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) raises(NotImplementedError, lambda: sample(N_c, library='pymc3')) def test_sample_seed(): x1, x2 = (Indexed('x', i) for i in (1, 2)) pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi) X = JointRV('x', pdf) libraries = ['scipy', 'numpy', 'pymc3'] for lib in libraries: try: imported_lib = import_module(lib) if imported_lib: s0, s1, s2 = [], [], [] s0 = sample(X, size=10, library=lib, seed=0) s1 = sample(X, size=10, library=lib, seed=0) s2 = sample(X, size=10, library=lib, seed=1) assert all(s0 == s1) assert all(s1 != s2) except NotImplementedError: continue def test_issue_21057(): m = Normal("x", [0, 0], [[0, 0], [0, 0]]) n = MultivariateNormal("x", [0, 0], [[0, 0], [0, 0]]) p = Normal("x", [0, 0], [[0, 0], [0, 1]]) assert m == n libraries = ['scipy', 'numpy', 'pymc3'] for library in libraries: try: imported_lib = import_module(library) if imported_lib: s1 = sample(m, size=8) s2 = sample(n, size=8) s3 = sample(p, size=8) assert tuple(s1.flatten()) == tuple(s2.flatten()) for s in s3: assert tuple(s.flatten()) in p.pspace.distribution.set except NotImplementedError: continue
e42c2a2dee05320e6ca7634de6aeb47dc870944e55bb9001b230dff956d0cf4d
from sympy.concrete.summations import Sum from sympy.core.containers import Tuple from sympy.core.function import Lambda from sympy.core.numbers import (Float, Rational, oo, pi) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import (gamma, lowergamma) from sympy.logic.boolalg import (And, Not) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.immutable import ImmutableMatrix from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (FiniteSet, Interval) from sympy.stats import (DiscreteMarkovChain, P, TransitionMatrixOf, E, StochasticStateSpaceOf, variance, ContinuousMarkovChain, BernoulliProcess, PoissonProcess, WienerProcess, GammaProcess, sample_stochastic_process) from sympy.stats.joint_rv import JointDistribution from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.rv import RandomIndexedSymbol from sympy.stats.symbolic_probability import Probability, Expectation from sympy.testing.pytest import (raises, skip, ignore_warnings, warns_deprecated_sympy) from sympy.external import import_module from sympy.stats.frv_types import BernoulliDistribution from sympy.stats.drv_types import PoissonDistribution from sympy.stats.crv_types import NormalDistribution, GammaDistribution from sympy.core.symbol import Str def test_DiscreteMarkovChain(): # pass only the name X = DiscreteMarkovChain("X") assert isinstance(X.state_space, Range) assert X.index_set == S.Naturals0 assert isinstance(X.transition_probabilities, MatrixSymbol) t = symbols('t', positive=True, integer=True) assert isinstance(X[t], RandomIndexedSymbol) assert E(X[0]) == Expectation(X[0]) raises(TypeError, lambda: DiscreteMarkovChain(1)) raises(NotImplementedError, lambda: X(t)) raises(NotImplementedError, lambda: X.communication_classes()) raises(NotImplementedError, lambda: X.canonical_form()) raises(NotImplementedError, lambda: X.decompose()) nz = Symbol('n', integer=True) TZ = MatrixSymbol('M', nz, nz) SZ = Range(nz) YZ = DiscreteMarkovChain('Y', SZ, TZ) assert P(Eq(YZ[2], 1), Eq(YZ[1], 0)) == TZ[0, 1] raises(ValueError, lambda: sample_stochastic_process(t)) raises(ValueError, lambda: next(sample_stochastic_process(X))) # pass name and state_space # any hashable object should be a valid state # states should be valid as a tuple/set/list/Tuple/Range sym, rainy, cloudy, sunny = symbols('a Rainy Cloudy Sunny', real=True) state_spaces = [(1, 2, 3), [Str('Hello'), sym, DiscreteMarkovChain("Y", (1,2,3))], Tuple(S(1), exp(sym), Str('World'), sympify=False), Range(-1, 5, 2), [rainy, cloudy, sunny]] chains = [DiscreteMarkovChain("Y", state_space) for state_space in state_spaces] for i, Y in enumerate(chains): assert isinstance(Y.transition_probabilities, MatrixSymbol) assert Y.state_space == state_spaces[i] or Y.state_space == FiniteSet(*state_spaces[i]) assert Y.number_of_states == 3 with ignore_warnings(UserWarning): # TODO: Restore tests once warnings are removed assert P(Eq(Y[2], 1), Eq(Y[0], 2), evaluate=False) == Probability(Eq(Y[2], 1), Eq(Y[0], 2)) assert E(Y[0]) == Expectation(Y[0]) raises(ValueError, lambda: next(sample_stochastic_process(Y))) raises(TypeError, lambda: DiscreteMarkovChain("Y", dict((1, 1)))) Y = DiscreteMarkovChain("Y", Range(1, t, 2)) assert Y.number_of_states == ceiling((t-1)/2) # pass name and transition_probabilities chains = [DiscreteMarkovChain("Y", trans_probs=Matrix([[]])), DiscreteMarkovChain("Y", trans_probs=Matrix([[0, 1], [1, 0]])), DiscreteMarkovChain("Y", trans_probs=Matrix([[pi, 1-pi], [sym, 1-sym]]))] for Z in chains: assert Z.number_of_states == Z.transition_probabilities.shape[0] assert isinstance(Z.transition_probabilities, ImmutableMatrix) # pass name, state_space and transition_probabilities T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) TS = MatrixSymbol('T', 3, 3) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) YS = DiscreteMarkovChain("Y", ['One', 'Two', 3], TS) assert Y.joint_distribution(1, Y[2], 3) == JointDistribution(Y[1], Y[2], Y[3]) raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol)) assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2) assert (P(Eq(YS[3], 2), Eq(YS[1], 1)) - (TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2])).simplify() == 0 assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1)) assert P(Eq(YS[3], 3), Eq(YS[1], 1)) == TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2] TO = Matrix([[0.25, 0.75, 0],[0, 0.25, 0.75],[0.75, 0, 0.25]]) assert P(Eq(Y[3], 2), Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(0.375, 3) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert E(Y[3], evaluate=False) == Expectation(Y[3]) assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3) TSO = MatrixSymbol('T', 4, 4) raises(ValueError, lambda: str(P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO)))) raises(TypeError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols('M'))) raises(ValueError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol('T', 3, 4))) raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6))) raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1))) # extended tests for probability queries TO1 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Probability(Eq(Y[0], 0)), Rational(1, 4)) & TransitionMatrixOf(Y, TO1)) == Rational(1, 16) assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), TransitionMatrixOf(Y, TO1)) == \ Probability(Eq(Y[0], 0))/4 assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & StochasticStateSpaceOf(X, [S(0), '0', 1]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) is S.Zero assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) & StochasticStateSpaceOf(X, [S(0), '0', 1]) & TransitionMatrixOf(X, TO1)) is S.Zero assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Y[1], 1)) == 0.1*Probability(Eq(Y[0], 0)) # testing properties of Markov chain TO2 = Matrix([[S.One, 0, 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) TO3 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)], [0, Rational(1, 4), Rational(3, 4)]]) Y2 = DiscreteMarkovChain('Y', trans_probs=TO2) Y3 = DiscreteMarkovChain('Y', trans_probs=TO3) assert Y3.fundamental_matrix() == ImmutableMatrix([[176, 81, -132], [36, 141, -52], [-44, -39, 208]])/125 assert Y2.is_absorbing_chain() == True assert Y3.is_absorbing_chain() == False assert Y2.canonical_form() == ([0, 1, 2], TO2) assert Y3.canonical_form() == ([0, 1, 2], TO3) assert Y2.decompose() == ([0, 1, 2], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3]) assert Y3.decompose() == ([0, 1, 2], TO3, Matrix(0, 3, []), Matrix(0, 0, [])) TO4 = Matrix([[Rational(1, 5), Rational(2, 5), Rational(2, 5)], [Rational(1, 10), S.Half, Rational(2, 5)], [Rational(3, 5), Rational(3, 10), Rational(1, 10)]]) Y4 = DiscreteMarkovChain('Y', trans_probs=TO4) w = ImmutableMatrix([[Rational(11, 39), Rational(16, 39), Rational(4, 13)]]) assert Y4.limiting_distribution == w assert Y4.is_regular() == True assert Y4.is_ergodic() == True TS1 = MatrixSymbol('T', 3, 3) Y5 = DiscreteMarkovChain('Y', trans_probs=TS1) assert Y5.limiting_distribution(w, TO4).doit() == True assert Y5.stationary_distribution(condition_set=True).subs(TS1, TO4).contains(w).doit() == S.true TO6 = Matrix([[S.One, 0, 0, 0, 0],[S.Half, 0, S.Half, 0, 0],[0, S.Half, 0, S.Half, 0], [0, 0, S.Half, 0, S.Half], [0, 0, 0, 0, 1]]) Y6 = DiscreteMarkovChain('Y', trans_probs=TO6) assert Y6.fundamental_matrix() == ImmutableMatrix([[Rational(3, 2), S.One, S.Half], [S.One, S(2), S.One], [S.Half, S.One, Rational(3, 2)]]) assert Y6.absorbing_probabilities() == ImmutableMatrix([[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half], [Rational(1, 4), Rational(3, 4)]]) with warns_deprecated_sympy(): Y6.absorbing_probabilites() TO7 = Matrix([[Rational(1, 2), Rational(1, 4), Rational(1, 4)], [Rational(1, 2), 0, Rational(1, 2)], [Rational(1, 4), Rational(1, 4), Rational(1, 2)]]) Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) assert Y7.is_absorbing_chain() == False assert Y7.fundamental_matrix() == ImmutableMatrix([[Rational(86, 75), Rational(1, 25), Rational(-14, 75)], [Rational(2, 25), Rational(21, 25), Rational(2, 25)], [Rational(-14, 75), Rational(1, 25), Rational(86, 75)]]) # test for zero-sized matrix functionality X = DiscreteMarkovChain('X', trans_probs=Matrix([[]])) assert X.number_of_states == 0 assert X.stationary_distribution() == Matrix([[]]) assert X.communication_classes() == [] assert X.canonical_form() == ([], Matrix([[]])) assert X.decompose() == ([], Matrix([[]]), Matrix([[]]), Matrix([[]])) assert X.is_regular() == False assert X.is_ergodic() == False # test communication_class # see https://drive.google.com/drive/folders/1HbxLlwwn2b3U8Lj7eb_ASIUb5vYaNIjg?usp=sharing # tutorial 2.pdf TO7 = Matrix([[0, 5, 5, 0, 0], [0, 0, 0, 10, 0], [5, 0, 5, 0, 0], [0, 10, 0, 0, 0], [0, 3, 0, 3, 4]])/10 Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) tuples = Y7.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([1, 3], [0, 2], [4]) assert recurrence == (True, False, False) assert periods == (2, 1, 1) TO8 = Matrix([[0, 0, 0, 10, 0, 0], [5, 0, 5, 0, 0, 0], [0, 4, 0, 0, 0, 6], [10, 0, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0], [0, 0, 0, 5, 5, 0]])/10 Y8 = DiscreteMarkovChain('Y', trans_probs=TO8) tuples = Y8.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([0, 3], [1, 2, 5, 4]) assert recurrence == (True, False) assert periods == (2, 2) TO9 = Matrix([[2, 0, 0, 3, 0, 0, 3, 2, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0, 0, 0], [0, 2, 2, 0, 0, 0, 0, 0, 3, 3], [0, 0, 0, 3, 0, 0, 6, 1, 0, 0], [0, 0, 0, 0, 5, 5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 10, 0, 0, 0, 0], [4, 0, 0, 5, 0, 0, 1, 0, 0, 0], [2, 0, 0, 4, 0, 0, 2, 2, 0, 0], [3, 0, 1, 0, 0, 0, 0, 0, 4, 2], [0, 0, 4, 0, 0, 0, 0, 0, 3, 3]])/10 Y9 = DiscreteMarkovChain('Y', trans_probs=TO9) tuples = Y9.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([0, 3, 6, 7], [1], [2, 8, 9], [5], [4]) assert recurrence == (True, True, False, True, False) assert periods == (1, 1, 1, 1, 1) # test canonical form # see https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf # example 11.13 T = Matrix([[1, 0, 0, 0, 0], [S(1) / 2, 0, S(1) / 2, 0, 0], [0, S(1) / 2, 0, S(1) / 2, 0], [0, 0, S(1) / 2, 0, S(1) / 2], [0, 0, 0, 0, S(1)]]) DW = DiscreteMarkovChain('DW', [0, 1, 2, 3, 4], T) states, A, B, C = DW.decompose() assert states == [0, 4, 1, 2, 3] assert A == Matrix([[1, 0], [0, 1]]) assert B == Matrix([[S(1)/2, 0], [0, 0], [0, S(1)/2]]) assert C == Matrix([[0, S(1)/2, 0], [S(1)/2, 0, S(1)/2], [0, S(1)/2, 0]]) states, new_matrix = DW.canonical_form() assert states == [0, 4, 1, 2, 3] assert new_matrix == Matrix([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [S(1)/2, 0, 0, S(1)/2, 0], [0, 0, S(1)/2, 0, S(1)/2], [0, S(1)/2, 0, S(1)/2, 0]]) # test regular and ergodic # https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf T = Matrix([[0, 4, 0, 0, 0], [1, 0, 3, 0, 0], [0, 2, 0, 2, 0], [0, 0, 3, 0, 1], [0, 0, 0, 4, 0]])/4 X = DiscreteMarkovChain('X', trans_probs=T) assert not X.is_regular() assert X.is_ergodic() T = Matrix([[0, 1], [1, 0]]) X = DiscreteMarkovChain('X', trans_probs=T) assert not X.is_regular() assert X.is_ergodic() # http://www.math.wisc.edu/~valko/courses/331/MC2.pdf T = Matrix([[2, 1, 1], [2, 0, 2], [1, 1, 2]])/4 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_regular() assert X.is_ergodic() # https://docs.ufpr.br/~lucambio/CE222/1S2014/Kemeny-Snell1976.pdf T = Matrix([[1, 1], [1, 1]])/2 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_regular() assert X.is_ergodic() # test is_absorbing_chain T = Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) X = DiscreteMarkovChain('X', trans_probs=T) assert not X.is_absorbing_chain() # https://en.wikipedia.org/wiki/Absorbing_Markov_chain T = Matrix([[1, 1, 0, 0], [0, 1, 1, 0], [1, 0, 0, 1], [0, 0, 0, 2]])/2 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_absorbing_chain() T = Matrix([[2, 0, 0, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 0, 2]])/2 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_absorbing_chain() # test custom state space Y10 = DiscreteMarkovChain('Y', [1, 2, 3], TO2) tuples = Y10.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([1], [2, 3]) assert recurrence == (True, False) assert periods == (1, 1) assert Y10.canonical_form() == ([1, 2, 3], TO2) assert Y10.decompose() == ([1, 2, 3], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3]) # testing miscellaneous queries T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], [Rational(1, 3), 0, Rational(2, 3)], [S.Half, S.Half, 0]]) X = DiscreteMarkovChain('X', [0, 1, 2], T) assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3) assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9) raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) raises(ValueError, lambda: DiscreteMarkovChain('X', [0, 1], T)) # testing miscellaneous queries with different state space X = DiscreteMarkovChain('X', ['A', 'B', 'C'], T) assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) a = X.state_space.args[0] c = X.state_space.args[2] assert (E(X[1] ** 2, Eq(X[0], 1)) - (a**2/3 + 2*c**2/3)).simplify() == 0 assert (variance(X[1], Eq(X[0], 1)) - (2*(-a/3 + c/3)**2/3 + (2*a/3 - 2*c/3)**2/3)).simplify() == 0 raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) #testing queries with multiple RandomIndexedSymbols T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) assert P(Eq(Y[7], Y[5]), Eq(Y[2], 0)).round(5) == Float(0.44428, 5) assert P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) == Float(0.36, 2) assert P(Le(Y[5], Y[10]), Eq(Y[4], 2)).round(6) == Float(0.583120, 6) assert Float(P(Eq(Y[10], Y[5]), Eq(Y[4], 1)), 14) == Float(1 - P(Ne(Y[10], Y[5]), Eq(Y[4], 1)), 14) assert Float(P(Gt(Y[8], Y[9]), Eq(Y[3], 2)), 14) == Float(1 - P(Le(Y[8], Y[9]), Eq(Y[3], 2)), 14) assert Float(P(Lt(Y[1], Y[4]), Eq(Y[0], 0)), 14) == Float(1 - P(Ge(Y[1], Y[4]), Eq(Y[0], 0)), 14) assert P(Eq(Y[5], Y[10]), Eq(Y[2], 1)) == P(Eq(Y[10], Y[5]), Eq(Y[2], 1)) assert P(Gt(Y[1], Y[2]), Eq(Y[0], 1)) == P(Lt(Y[2], Y[1]), Eq(Y[0], 1)) assert P(Ge(Y[7], Y[6]), Eq(Y[4], 1)) == P(Le(Y[6], Y[7]), Eq(Y[4], 1)) #test symbolic queries a, b, c, d = symbols('a b c d') T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) query = P(Eq(Y[a], b), Eq(Y[c], d)) assert query.subs({a:10, b:2, c:5, d:1}).evalf().round(4) == P(Eq(Y[10], 2), Eq(Y[5], 1)).round(4) assert query.subs({a:15, b:0, c:10, d:1}).evalf().round(4) == P(Eq(Y[15], 0), Eq(Y[10], 1)).round(4) query_gt = P(Gt(Y[a], b), Eq(Y[c], d)) query_le = P(Le(Y[a], b), Eq(Y[c], d)) assert query_gt.subs({a:5, b:2, c:1, d:0}).evalf() + query_le.subs({a:5, b:2, c:1, d:0}).evalf() == 1 query_ge = P(Ge(Y[a], b), Eq(Y[c], d)) query_lt = P(Lt(Y[a], b), Eq(Y[c], d)) assert query_ge.subs({a:4, b:1, c:0, d:2}).evalf() + query_lt.subs({a:4, b:1, c:0, d:2}).evalf() == 1 #test issue 20078 assert (2*Y[1] + 3*Y[1]).simplify() == 5*Y[1] assert (2*Y[1] - 3*Y[1]).simplify() == -Y[1] assert (2*(0.25*Y[1])).simplify() == 0.5*Y[1] assert ((2*Y[1]) * (0.25*Y[1])).simplify() == 0.5*Y[1]**2 assert (Y[1]**2 + Y[1]**3).simplify() == (Y[1] + 1)*Y[1]**2 def test_sample_stochastic_process(): if not import_module('scipy'): skip('SciPy Not installed. Skip sampling tests') import random random.seed(0) numpy = import_module('numpy') if numpy: numpy.random.seed(0) # scipy uses numpy to sample so to set its seed T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) for samps in range(10): assert next(sample_stochastic_process(Y)) in Y.state_space Z = DiscreteMarkovChain("Z", ['1', 1, 0], T) for samps in range(10): assert next(sample_stochastic_process(Z)) in Z.state_space T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], [Rational(1, 3), 0, Rational(2, 3)], [S.Half, S.Half, 0]]) X = DiscreteMarkovChain('X', [0, 1, 2], T) for samps in range(10): assert next(sample_stochastic_process(X)) in X.state_space W = DiscreteMarkovChain('W', [1, pi, oo], T) for samps in range(10): assert next(sample_stochastic_process(W)) in W.state_space def test_ContinuousMarkovChain(): T1 = Matrix([[S(-2), S(2), S.Zero], [S.Zero, S.NegativeOne, S.One], [Rational(3, 2), Rational(3, 2), S(-3)]]) C1 = ContinuousMarkovChain('C', [0, 1, 2], T1) assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]]) T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]]) C2 = ContinuousMarkovChain('C', [0, 1, 2], T2) A, t = C2.generator_matrix, symbols('t', positive=True) assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0], [S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0], [S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]]) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1)) assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half) assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half) + (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2)) raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half))) assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0)) TS1 = MatrixSymbol('G', 3, 3) CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1) A = CS1.generator_matrix assert CS1.transition_probabilities(A)(t) == exp(t*A) C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2) assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half #test probability queries G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) assert P(Eq(C(7.385), C(3.19)), Eq(C(0.862), 0)).round(5) == Float(0.35469, 5) assert P(Gt(C(98.715), C(19.807)), Eq(C(11.314), 2)).round(5) == Float(0.32452, 5) assert P(Le(C(5.9), C(10.112)), Eq(C(4), 1)).round(6) == Float(0.675214, 6) assert Float(P(Eq(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) == Float(1 - P(Ne(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) assert Float(P(Gt(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) == Float(1 - P(Le(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) assert Float(P(Lt(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) == Float(1 - P(Ge(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) assert P(Eq(C(5.243), C(10.912)), Eq(C(2.174), 1)) == P(Eq(C(10.912), C(5.243)), Eq(C(2.174), 1)) assert P(Gt(C(2.344), C(9.9)), Eq(C(1.102), 1)) == P(Lt(C(9.9), C(2.344)), Eq(C(1.102), 1)) assert P(Ge(C(7.87), C(1.008)), Eq(C(0.153), 1)) == P(Le(C(1.008), C(7.87)), Eq(C(0.153), 1)) #test symbolic queries a, b, c, d = symbols('a b c d') query = P(Eq(C(a), b), Eq(C(c), d)) assert query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10) == P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10) query_gt = P(Gt(C(a), b), Eq(C(c), d)) query_le = P(Le(C(a), b), Eq(C(c), d)) assert query_gt.subs({a:13.2, b:0, c:3.29, d:2}).evalf() + query_le.subs({a:13.2, b:0, c:3.29, d:2}).evalf() == 1 query_ge = P(Ge(C(a), b), Eq(C(c), d)) query_lt = P(Lt(C(a), b), Eq(C(c), d)) assert query_ge.subs({a:7.43, b:1, c:1.45, d:0}).evalf() + query_lt.subs({a:7.43, b:1, c:1.45, d:0}).evalf() == 1 #test issue 20078 assert (2*C(1) + 3*C(1)).simplify() == 5*C(1) assert (2*C(1) - 3*C(1)).simplify() == -C(1) assert (2*(0.25*C(1))).simplify() == 0.5*C(1) assert (2*C(1) * 0.25*C(1)).simplify() == 0.5*C(1)**2 assert (C(1)**2 + C(1)**3).simplify() == (C(1) + 1)*C(1)**2 def test_BernoulliProcess(): B = BernoulliProcess("B", p=0.6, success=1, failure=0) assert B.state_space == FiniteSet(0, 1) assert B.index_set == S.Naturals0 assert B.success == 1 assert B.failure == 0 X = BernoulliProcess("X", p=Rational(1,3), success='H', failure='T') assert X.state_space == FiniteSet('H', 'T') H, T = symbols("H,T") assert E(X[1]+X[2]*X[3]) == H**2/9 + 4*H*T/9 + H/3 + 4*T**2/9 + 2*T/3 t, x = symbols('t, x', positive=True, integer=True) assert isinstance(B[t], RandomIndexedSymbol) raises(ValueError, lambda: BernoulliProcess("X", p=1.1, success=1, failure=0)) raises(NotImplementedError, lambda: B(t)) raises(IndexError, lambda: B[-3]) assert B.joint_distribution(B[3], B[9]) == JointDistributionHandmade(Lambda((B[3], B[9]), Piecewise((0.6, Eq(B[3], 1)), (0.4, Eq(B[3], 0)), (0, True)) *Piecewise((0.6, Eq(B[9], 1)), (0.4, Eq(B[9], 0)), (0, True)))) assert B.joint_distribution(2, B[4]) == JointDistributionHandmade(Lambda((B[2], B[4]), Piecewise((0.6, Eq(B[2], 1)), (0.4, Eq(B[2], 0)), (0, True)) *Piecewise((0.6, Eq(B[4], 1)), (0.4, Eq(B[4], 0)), (0, True)))) # Test for the sum distribution of Bernoulli Process RVs Y = B[1] + B[2] + B[3] assert P(Eq(Y, 0)).round(2) == Float(0.06, 1) assert P(Eq(Y, 2)).round(2) == Float(0.43, 2) assert P(Eq(Y, 4)).round(2) == 0 assert P(Gt(Y, 1)).round(2) == Float(0.65, 2) # Test for independency of each Random Indexed variable assert P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) == Float(0.06, 1) assert E(2 * B[1] + B[2]).round(2) == Float(1.80, 3) assert E(2 * B[1] + B[2] + 5).round(2) == Float(6.80, 3) assert E(B[2] * B[4] + B[10]).round(2) == Float(0.96, 2) assert E(B[2] > 0, Eq(B[1],1) & Eq(B[2],1)).round(2) == Float(0.60,2) assert E(B[1]) == 0.6 assert P(B[1] > 0).round(2) == Float(0.60, 2) assert P(B[1] < 1).round(2) == Float(0.40, 2) assert P(B[1] > 0, B[2] <= 1).round(2) == Float(0.60, 2) assert P(B[12] * B[5] > 0).round(2) == Float(0.36, 2) assert P(B[12] * B[5] > 0, B[4] < 1).round(2) == Float(0.36, 2) assert P(Eq(B[2], 1), B[2] > 0) == 1 assert P(Eq(B[5], 3)) == 0 assert P(Eq(B[1], 1), B[1] < 0) == 0 assert P(B[2] > 0, Eq(B[2], 1)) == 1 assert P(B[2] < 0, Eq(B[2], 1)) == 0 assert P(B[2] > 0, B[2]==7) == 0 assert P(B[5] > 0, B[5]) == BernoulliDistribution(0.6, 0, 1) raises(ValueError, lambda: P(3)) raises(ValueError, lambda: P(B[3] > 0, 3)) # test issue 19456 expr = Sum(B[t], (t, 0, 4)) expr2 = Sum(B[t], (t, 1, 3)) expr3 = Sum(B[t]**2, (t, 1, 3)) assert expr.doit() == B[0] + B[1] + B[2] + B[3] + B[4] assert expr2.doit() == Y assert expr3.doit() == B[1]**2 + B[2]**2 + B[3]**2 assert B[2*t].free_symbols == {B[2*t], t} assert B[4].free_symbols == {B[4]} assert B[x*t].free_symbols == {B[x*t], x, t} #test issue 20078 assert (2*B[t] + 3*B[t]).simplify() == 5*B[t] assert (2*B[t] - 3*B[t]).simplify() == -B[t] assert (2*(0.25*B[t])).simplify() == 0.5*B[t] assert (2*B[t] * 0.25*B[t]).simplify() == 0.5*B[t]**2 assert (B[t]**2 + B[t]**3).simplify() == (B[t] + 1)*B[t]**2 def test_PoissonProcess(): X = PoissonProcess("X", 3) assert X.state_space == S.Naturals0 assert X.index_set == Interval(0, oo) assert X.lamda == 3 t, d, x, y = symbols('t d x y', positive=True) assert isinstance(X(t), RandomIndexedSymbol) assert X.distribution(t) == PoissonDistribution(3*t) with warns_deprecated_sympy(): X.distribution(X(t)) raises(ValueError, lambda: PoissonProcess("X", -1)) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-5)) assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade(Lambda((X(2), X(3)), 6**X(2)*9**X(3)*exp(-15)/(factorial(X(2))*factorial(X(3))))) assert X.joint_distribution(4, 6) == JointDistributionHandmade(Lambda((X(4), X(6)), 12**X(4)*18**X(6)*exp(-30)/(factorial(X(4))*factorial(X(6))))) assert P(X(t) < 1) == exp(-3*t) assert P(Eq(X(t), 0), Contains(t, Interval.Lopen(3, 5))) == exp(-6) # exp(-2*lamda) res = P(Eq(X(t), 1), Contains(t, Interval.Lopen(3, 4))) assert res == 3*exp(-3) # Equivalent to P(Eq(X(t), 1))**4 because of non-overlapping intervals assert P(Eq(X(t), 1) & Eq(X(d), 1) & Eq(X(x), 1) & Eq(X(y), 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))) == res**4 # Return Probability because of overlapping intervals assert P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) == \ Probability(Eq(X(d), 3) & Eq(X(t), 2), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) raises(ValueError, lambda: P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 4)) & Contains(d, Interval.Lopen(3, oo)))) # no bound on d assert P(Eq(X(3), 2)) == 81*exp(-9)/2 assert P(Eq(X(t), 2), Contains(t, Interval.Lopen(0, 5))) == 225*exp(-15)/2 # Check that probability works correctly by adding it to 1 res1 = P(X(t) <= 3, Contains(t, Interval.Lopen(0, 5))) res2 = P(X(t) > 3, Contains(t, Interval.Lopen(0, 5))) assert res1 == 691*exp(-15) assert (res1 + res2).simplify() == 1 # Check Not and Or assert P(Not(Eq(X(t), 2) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & \ Contains(d, Interval.Lopen(7, 8))).simplify() == -18*exp(-6) + 234*exp(-9) + 1 assert P(Eq(X(t), 2) | Ne(X(t), 4), Contains(t, Interval.Ropen(2, 4))) == 1 - 36*exp(-6) raises(ValueError, lambda: P(X(t) > 2, X(t) + X(d))) assert E(X(t)) == 3*t # property of the distribution at a given timestamp assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == 75 assert E(X(t)**2, Contains(t, Interval.Lopen(0, 1))) == 12 assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) == \ Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) # Value Error because of infinite time bound raises(ValueError, lambda: E(X(t)**3, Contains(t, Interval.Lopen(1, oo)))) # Equivalent to E(X(t)**2) - E(X(d)**2) == E(X(1)**2) - E(X(1)**2) == 0 assert E((X(t) + X(d))*(X(t) - X(d)), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2))) == 0 assert E(X(2) + x*E(X(5))) == 15*x + 6 assert E(x*X(1) + y) == 3*x + y assert P(Eq(X(1), 2) & Eq(X(t), 3), Contains(t, Interval.Lopen(1, 2))) == 81*exp(-6)/4 Y = PoissonProcess("Y", 6) Z = X + Y assert Z.lamda == X.lamda + Y.lamda == 9 raises(ValueError, lambda: X + 5) # should be added be only PoissonProcess instance N, M = Z.split(4, 5) assert N.lamda == 4 assert M.lamda == 5 raises(ValueError, lambda: Z.split(3, 2)) # 2+3 != 9 raises(ValueError, lambda :P(Eq(X(t), 0), Contains(t, Interval.Lopen(1, 3)) & Eq(X(1), 0))) # check if it handles queries with two random variables in one args res1 = P(Eq(N(3), N(5))) assert res1 == P(Eq(N(t), 0), Contains(t, Interval(3, 5))) res2 = P(N(3) > N(1)) assert res2 == P((N(t) > 0), Contains(t, Interval(1, 3))) assert P(N(3) < N(1)) == 0 # condition is not possible res3 = P(N(3) <= N(1)) # holds only for Eq(N(3), N(1)) assert res3 == P(Eq(N(t), 0), Contains(t, Interval(1, 3))) # tests from https://www.probabilitycourse.com/chapter11/11_1_2_basic_concepts_of_the_poisson_process.php X = PoissonProcess('X', 10) # 11.1 assert P(Eq(X(S(1)/3), 3) & Eq(X(1), 10)) == exp(-10)*Rational(8000000000, 11160261) assert P(Eq(X(1), 1), Eq(X(S(1)/3), 3)) == 0 assert P(Eq(X(1), 10), Eq(X(S(1)/3), 3)) == P(Eq(X(S(2)/3), 7)) X = PoissonProcess('X', 2) # 11.2 assert P(X(S(1)/2) < 1) == exp(-1) assert P(X(3) < 1, Eq(X(1), 0)) == exp(-4) assert P(Eq(X(4), 3), Eq(X(2), 3)) == exp(-4) X = PoissonProcess('X', 3) assert P(Eq(X(2), 5) & Eq(X(1), 2)) == Rational(81, 4)*exp(-6) # check few properties assert P(X(2) <= 3, X(1)>=1) == 3*P(Eq(X(1), 0)) + 2*P(Eq(X(1), 1)) + P(Eq(X(1), 2)) assert P(X(2) <= 3, X(1) > 1) == 2*P(Eq(X(1), 0)) + 1*P(Eq(X(1), 1)) assert P(Eq(X(2), 5) & Eq(X(1), 2)) == P(Eq(X(1), 3))*P(Eq(X(1), 2)) assert P(Eq(X(3), 4), Eq(X(1), 3)) == P(Eq(X(2), 1)) #test issue 20078 assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) assert (2*X(t) - 3*X(t)).simplify() == -X(t) assert (2*(0.25*X(t))).simplify() == 0.5*X(t) assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 def test_WienerProcess(): X = WienerProcess("X") assert X.state_space == S.Reals assert X.index_set == Interval(0, oo) t, d, x, y = symbols('t d x y', positive=True) assert isinstance(X(t), RandomIndexedSymbol) assert X.distribution(t) == NormalDistribution(0, sqrt(t)) with warns_deprecated_sympy(): X.distribution(X(t)) raises(ValueError, lambda: PoissonProcess("X", -1)) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-2)) assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade( Lambda((X(2), X(3)), sqrt(6)*exp(-X(2)**2/4)*exp(-X(3)**2/6)/(12*pi))) assert X.joint_distribution(4, 6) == JointDistributionHandmade( Lambda((X(4), X(6)), sqrt(6)*exp(-X(4)**2/8)*exp(-X(6)**2/12)/(24*pi))) assert P(X(t) < 3).simplify() == erf(3*sqrt(2)/(2*sqrt(t)))/2 + S(1)/2 assert P(X(t) > 2, Contains(t, Interval.Lopen(3, 7))).simplify() == S(1)/2 -\ erf(sqrt(2)/2)/2 # Equivalent to P(X(1)>1)**4 assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() ==\ (1 - erf(sqrt(2)/2))*(1 - erf(sqrt(2)))*(1 - erf(3*sqrt(2)/2))*(1 - erf(2*sqrt(2)))/16 # Contains an overlapping interval so, return Probability assert P((X(t)< 2) & (X(d)> 3), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) == Probability((X(d) > 3) & (X(t) < 2), Contains(d, Interval.Ropen(2, 4)) & Contains(t, Interval.Lopen(0, 2))) assert str(P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & Contains(d, Interval.Lopen(7, 8))).simplify()) == \ '-(1 - erf(3*sqrt(2)/2))*(2 - erfc(5/2))/4 + 1' # Distribution has mean 0 at each timestamp assert E(X(t)) == 0 assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) == Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(d, Interval.Ropen(1, 2)) & Contains(t, Interval.Lopen(0, 1))) assert E(X(t) + x*E(X(3))) == 0 #test issue 20078 assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) assert (2*X(t) - 3*X(t)).simplify() == -X(t) assert (2*(0.25*X(t))).simplify() == 0.5*X(t) assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 def test_GammaProcess_symbolic(): t, d, x, y, g, l = symbols('t d x y g l', positive=True) X = GammaProcess("X", l, g) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-1)) assert isinstance(X(t), RandomIndexedSymbol) assert X.state_space == Interval(0, oo) assert X.distribution(t) == GammaDistribution(g*t, 1/l) with warns_deprecated_sympy(): X.distribution(X(t)) assert X.joint_distribution(5, X(3)) == JointDistributionHandmade(Lambda( (X(5), X(3)), l**(8*g)*exp(-l*X(3))*exp(-l*X(5))*X(3)**(3*g - 1)*X(5)**(5*g - 1)/(gamma(3*g)*gamma(5*g)))) # property of the gamma process at any given timestamp assert E(X(t)) == g*t/l assert variance(X(t)).simplify() == g*t/l**2 # Equivalent to E(2*X(1)) + E(X(1)**2) + E(X(1)**3), where E(X(1)) == g/l assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == \ 2*g/l + (g**2 + g)/l**2 + (g**3 + 3*g**2 + 2*g)/l**3 assert P(X(t) > 3, Contains(t, Interval.Lopen(3, 4))).simplify() == \ 1 - lowergamma(g, 3*l)/gamma(g) # equivalent to P(X(1)>3) #test issue 20078 assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) assert (2*X(t) - 3*X(t)).simplify() == -X(t) assert (2*(0.25*X(t))).simplify() == 0.5*X(t) assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 def test_GammaProcess_numeric(): t, d, x, y = symbols('t d x y', positive=True) X = GammaProcess("X", 1, 2) assert X.state_space == Interval(0, oo) assert X.index_set == Interval(0, oo) assert X.lamda == 1 assert X.gamma == 2 raises(ValueError, lambda: GammaProcess("X", -1, 2)) raises(ValueError, lambda: GammaProcess("X", 0, -2)) raises(ValueError, lambda: GammaProcess("X", -1, -2)) # all are independent because of non-overlapping intervals assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() == \ 120*exp(-10) # Check working with Not and Or assert P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & Contains(d, Interval.Lopen(7, 8))).simplify() == -4*exp(-3) + 472*exp(-8)/3 + 1 assert P((X(t) > 2) | (X(t) < 4), Contains(t, Interval.Ropen(1, 4))).simplify() == \ -643*exp(-4)/15 + 109*exp(-2)/15 + 1 assert E(X(t)) == 2*t # E(X(t)) == gamma*t/l assert E(X(2) + x*E(X(5))) == 10*x + 4
4d33e702095333c717ba26529c5cfd1a523dfc8c0406ec77d244bf218fa894df
from sympy.concrete.summations import Sum from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.bessel import besseli from sympy.functions.special.beta_functions import beta from sympy.functions.special.zeta_functions import zeta from sympy.sets.sets import FiniteSet from sympy.simplify.simplify import simplify from sympy.utilities.lambdify import lambdify from sympy.core.relational import Eq, Ne from sympy.functions.elementary.exponential import exp from sympy.logic.boolalg import Or from sympy.sets.fancysets import Range from sympy.stats import (P, E, variance, density, characteristic_function, where, moment_generating_function, skewness, cdf, kurtosis, coskewness) from sympy.stats.drv_types import (PoissonDistribution, GeometricDistribution, FlorySchulz, Poisson, Geometric, Hermite, Logarithmic, NegativeBinomial, Skellam, YuleSimon, Zeta, DiscreteRV) from sympy.testing.pytest import slow, nocache_fail, raises from sympy.stats.symbolic_probability import Expectation x = Symbol('x') def test_PoissonDistribution(): l = 3 p = PoissonDistribution(l) assert abs(p.cdf(10).evalf() - 1) < .001 assert abs(p.cdf(10.4).evalf() - 1) < .001 assert p.expectation(x, x) == l assert p.expectation(x**2, x) - p.expectation(x, x)**2 == l def test_Poisson(): l = 3 x = Poisson('x', l) assert E(x) == l assert E(2*x) == 2*l assert variance(x) == l assert density(x) == PoissonDistribution(l) assert isinstance(E(x, evaluate=False), Expectation) assert isinstance(E(2*x, evaluate=False), Expectation) # issue 8248 assert x.pspace.compute_expectation(1) == 1 def test_FlorySchulz(): a = Symbol("a") z = Symbol("z") x = FlorySchulz('x', a) assert E(x) == (2 - a)/a assert (variance(x) - 2*(1 - a)/a**2).simplify() == S(0) assert density(x)(z) == a**2*z*(1 - a)**(z - 1) @slow def test_GeometricDistribution(): p = S.One / 5 d = GeometricDistribution(p) assert d.expectation(x, x) == 1/p assert d.expectation(x**2, x) - d.expectation(x, x)**2 == (1-p)/p**2 assert abs(d.cdf(20000).evalf() - 1) < .001 assert abs(d.cdf(20000.8).evalf() - 1) < .001 G = Geometric('G', p=S(1)/4) assert cdf(G)(S(7)/2) == P(G <= S(7)/2) X = Geometric('X', Rational(1, 5)) Y = Geometric('Y', Rational(3, 10)) assert coskewness(X, X + Y, X + 2*Y).simplify() == sqrt(230)*Rational(81, 1150) def test_Hermite(): a1 = Symbol("a1", positive=True) a2 = Symbol("a2", negative=True) raises(ValueError, lambda: Hermite("H", a1, a2)) a1 = Symbol("a1", negative=True) a2 = Symbol("a2", positive=True) raises(ValueError, lambda: Hermite("H", a1, a2)) a1 = Symbol("a1", positive=True) x = Symbol("x") H = Hermite("H", a1, a2) assert moment_generating_function(H)(x) == exp(a1*(exp(x) - 1) + a2*(exp(2*x) - 1)) assert characteristic_function(H)(x) == exp(a1*(exp(I*x) - 1) + a2*(exp(2*I*x) - 1)) assert E(H) == a1 + 2*a2 H = Hermite("H", a1=5, a2=4) assert density(H)(2) == 33*exp(-9)/2 assert E(H) == 13 assert variance(H) == 21 assert kurtosis(H) == Rational(464,147) assert skewness(H) == 37*sqrt(21)/441 def test_Logarithmic(): p = S.Half x = Logarithmic('x', p) assert E(x) == -p / ((1 - p) * log(1 - p)) assert variance(x) == -1/log(2)**2 + 2/log(2) assert E(2*x**2 + 3*x + 4) == 4 + 7 / log(2) assert isinstance(E(x, evaluate=False), Expectation) @nocache_fail def test_negative_binomial(): r = 5 p = S.One / 3 x = NegativeBinomial('x', r, p) assert E(x) == p*r / (1-p) # This hangs when run with the cache disabled: assert variance(x) == p*r / (1-p)**2 assert E(x**5 + 2*x + 3) == Rational(9207, 4) assert isinstance(E(x, evaluate=False), Expectation) def test_skellam(): mu1 = Symbol('mu1') mu2 = Symbol('mu2') z = Symbol('z') X = Skellam('x', mu1, mu2) assert density(X)(z) == (mu1/mu2)**(z/2) * \ exp(-mu1 - mu2)*besseli(z, 2*sqrt(mu1*mu2)) assert skewness(X).expand() == mu1/(mu1*sqrt(mu1 + mu2) + mu2 * sqrt(mu1 + mu2)) - mu2/(mu1*sqrt(mu1 + mu2) + mu2*sqrt(mu1 + mu2)) assert variance(X).expand() == mu1 + mu2 assert E(X) == mu1 - mu2 assert characteristic_function(X)(z) == exp( mu1*exp(I*z) - mu1 - mu2 + mu2*exp(-I*z)) assert moment_generating_function(X)(z) == exp( mu1*exp(z) - mu1 - mu2 + mu2*exp(-z)) def test_yule_simon(): from sympy.core.singleton import S rho = S(3) x = YuleSimon('x', rho) assert simplify(E(x)) == rho / (rho - 1) assert simplify(variance(x)) == rho**2 / ((rho - 1)**2 * (rho - 2)) assert isinstance(E(x, evaluate=False), Expectation) # To test the cdf function assert cdf(x)(x) == Piecewise((-beta(floor(x), 4)*floor(x) + 1, x >= 1), (0, True)) def test_zeta(): s = S(5) x = Zeta('x', s) assert E(x) == zeta(s-1) / zeta(s) assert simplify(variance(x)) == ( zeta(s) * zeta(s-2) - zeta(s-1)**2) / zeta(s)**2 def test_discrete_probability(): X = Geometric('X', Rational(1, 5)) Y = Poisson('Y', 4) G = Geometric('e', x) assert P(Eq(X, 3)) == Rational(16, 125) assert P(X < 3) == Rational(9, 25) assert P(X > 3) == Rational(64, 125) assert P(X >= 3) == Rational(16, 25) assert P(X <= 3) == Rational(61, 125) assert P(Ne(X, 3)) == Rational(109, 125) assert P(Eq(Y, 3)) == 32*exp(-4)/3 assert P(Y < 3) == 13*exp(-4) assert P(Y > 3).equals(32*(Rational(-71, 32) + 3*exp(4)/32)*exp(-4)/3) assert P(Y >= 3).equals(32*(Rational(-39, 32) + 3*exp(4)/32)*exp(-4)/3) assert P(Y <= 3) == 71*exp(-4)/3 assert P(Ne(Y, 3)).equals( 13*exp(-4) + 32*(Rational(-71, 32) + 3*exp(4)/32)*exp(-4)/3) assert P(X < S.Infinity) is S.One assert P(X > S.Infinity) is S.Zero assert P(G < 3) == x*(2-x) assert P(Eq(G, 3)) == x*(-x + 1)**2 def test_DiscreteRV(): p = S(1)/2 x = Symbol('x', integer=True, positive=True) pdf = p*(1 - p)**(x - 1) # pdf of Geometric Distribution D = DiscreteRV(x, pdf, set=S.Naturals, check=True) assert E(D) == E(Geometric('G', S(1)/2)) == 2 assert P(D > 3) == S(1)/8 assert D.pspace.domain.set == S.Naturals raises(ValueError, lambda: DiscreteRV(x, x, FiniteSet(*range(4)), check=True)) # purposeful invalid pmf but it should not raise since check=False # see test_drv_types.test_ContinuousRV for explanation X = DiscreteRV(x, 1/x, S.Naturals) assert P(X < 2) == 1 assert E(X) == oo def test_precomputed_characteristic_functions(): import mpmath def test_cf(dist, support_lower_limit, support_upper_limit): pdf = density(dist) t = S('t') x = S('x') # first function is the hardcoded CF of the distribution cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath') # second function is the Fourier transform of the density function f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath') cf2 = lambda t: mpmath.nsum(lambda x: f(x, t), [ support_lower_limit, support_upper_limit], maxdegree=10) # compare the two functions at various points for test_point in [2, 5, 8, 11]: n1 = cf1(test_point) n2 = cf2(test_point) assert abs(re(n1) - re(n2)) < 1e-12 assert abs(im(n1) - im(n2)) < 1e-12 test_cf(Geometric('g', Rational(1, 3)), 1, mpmath.inf) test_cf(Logarithmic('l', Rational(1, 5)), 1, mpmath.inf) test_cf(NegativeBinomial('n', 5, Rational(1, 7)), 0, mpmath.inf) test_cf(Poisson('p', 5), 0, mpmath.inf) test_cf(YuleSimon('y', 5), 1, mpmath.inf) test_cf(Zeta('z', 5), 1, mpmath.inf) def test_moment_generating_functions(): t = S('t') geometric_mgf = moment_generating_function(Geometric('g', S.Half))(t) assert geometric_mgf.diff(t).subs(t, 0) == 2 logarithmic_mgf = moment_generating_function(Logarithmic('l', S.Half))(t) assert logarithmic_mgf.diff(t).subs(t, 0) == 1/log(2) negative_binomial_mgf = moment_generating_function( NegativeBinomial('n', 5, Rational(1, 3)))(t) assert negative_binomial_mgf.diff(t).subs(t, 0) == Rational(5, 2) poisson_mgf = moment_generating_function(Poisson('p', 5))(t) assert poisson_mgf.diff(t).subs(t, 0) == 5 skellam_mgf = moment_generating_function(Skellam('s', 1, 1))(t) assert skellam_mgf.diff(t).subs( t, 2) == (-exp(-2) + exp(2))*exp(-2 + exp(-2) + exp(2)) yule_simon_mgf = moment_generating_function(YuleSimon('y', 3))(t) assert simplify(yule_simon_mgf.diff(t).subs(t, 0)) == Rational(3, 2) zeta_mgf = moment_generating_function(Zeta('z', 5))(t) assert zeta_mgf.diff(t).subs(t, 0) == pi**4/(90*zeta(5)) def test_Or(): X = Geometric('X', S.Half) assert P(Or(X < 3, X > 4)) == Rational(13, 16) assert P(Or(X > 2, X > 1)) == P(X > 1) assert P(Or(X >= 3, X < 3)) == 1 def test_where(): X = Geometric('X', Rational(1, 5)) Y = Poisson('Y', 4) assert where(X**2 > 4).set == Range(3, S.Infinity, 1) assert where(X**2 >= 4).set == Range(2, S.Infinity, 1) assert where(Y**2 < 9).set == Range(0, 3, 1) assert where(Y**2 <= 9).set == Range(0, 4, 1) def test_conditional(): X = Geometric('X', Rational(2, 3)) Y = Poisson('Y', 3) assert P(X > 2, X > 3) == 1 assert P(X > 3, X > 2) == Rational(1, 3) assert P(Y > 2, Y < 2) == 0 assert P(Eq(Y, 3), Y >= 0) == 9*exp(-3)/2 assert P(Eq(Y, 3), Eq(Y, 2)) == 0 assert P(X < 2, Eq(X, 2)) == 0 assert P(X > 2, Eq(X, 3)) == 1 def test_product_spaces(): X1 = Geometric('X1', S.Half) X2 = Geometric('X2', Rational(1, 3)) assert str(P(X1 + X2 < 3).rewrite(Sum)) == ( "Sum(Piecewise((1/(4*2**n), n >= -1), (0, True)), (n, -oo, -1))/3") assert str(P(X1 + X2 > 3).rewrite(Sum)) == ( "Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, " "X2 - n <= 2), (0, True)), (X2, 1, oo), (n, 1, oo))") assert str(P(X1 + X2 > 3).rewrite(Sum)) == ( "Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, " "X2 - n <= 2), (0, True)), (X2, 1, oo), (n, 1, oo))") assert P(Eq(X1 + X2, 3)) == Rational(1, 12)
8f74850b6fb86ba5f624e6cbdc953cce7424457386c73d9af573e518fa0192ed
from sympy.concrete.summations import Sum from sympy.core.function import (Lambda, diff, expand_func) from sympy.core.mul import Mul from sympy.core import EulerGamma from sympy.core.numbers import (E as e, I, Rational, pi) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.complexes import (Abs, im, re, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (asin, atan, cos, sin, tan) from sympy.functions.special.bessel import (besseli, besselj, besselk) from sympy.functions.special.beta_functions import beta from sympy.functions.special.error_functions import (erf, erfc, erfi, expint) from sympy.functions.special.gamma_functions import (gamma, lowergamma, uppergamma) from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (And, Or) from sympy.sets.sets import Interval from sympy.simplify.simplify import simplify from sympy.utilities.lambdify import lambdify from sympy.functions.special.error_functions import erfinv from sympy.functions.special.hyper import meijerg from sympy.sets.sets import FiniteSet, Complement, Intersection from sympy.stats import (P, E, where, density, variance, covariance, skewness, kurtosis, median, given, pspace, cdf, characteristic_function, moment_generating_function, ContinuousRV, Arcsin, Benini, Beta, BetaNoncentral, BetaPrime, Cauchy, Chi, ChiSquared, ChiNoncentral, Dagum, Erlang, ExGaussian, Exponential, ExponentialPower, FDistribution, FisherZ, Frechet, Gamma, GammaInverse, Gompertz, Gumbel, Kumaraswamy, Laplace, Levy, Logistic, LogCauchy, LogLogistic, LogitNormal, LogNormal, Maxwell, Moyal, Nakagami, Normal, GaussianInverse, Pareto, PowerFunction, QuadraticU, RaisedCosine, Rayleigh, Reciprocal, ShiftedGompertz, StudentT, Trapezoidal, Triangular, Uniform, UniformSum, VonMises, Weibull, coskewness, WignerSemicircle, Wald, correlation, moment, cmoment, smoment, quantile, Lomax, BoundedPareto) from sympy.stats.crv_types import NormalDistribution, ExponentialDistribution, ContinuousDistributionHandmade from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution, MultivariateNormalDistribution from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDomain from sympy.stats.compound_rv import CompoundPSpace from sympy.stats.symbolic_probability import Probability from sympy.testing.pytest import raises, XFAIL, slow, ignore_warnings from sympy.core.random import verify_numerically as tn oo = S.Infinity x, y, z = map(Symbol, 'xyz') def test_single_normal(): mu = Symbol('mu', real=True) sigma = Symbol('sigma', positive=True) X = Normal('x', 0, 1) Y = X*sigma + mu assert E(Y) == mu assert variance(Y) == sigma**2 pdf = density(Y) x = Symbol('x', real=True) assert (pdf(x) == 2**S.Half*exp(-(x - mu)**2/(2*sigma**2))/(2*pi**S.Half*sigma)) assert P(X**2 < 1) == erf(2**S.Half/2) ans = quantile(Y)(x) assert ans == Complement(Intersection(FiniteSet( sqrt(2)*sigma*(sqrt(2)*mu/(2*sigma)+ erfinv(2*x - 1))), Interval(-oo, oo)), FiniteSet(mu)) assert E(X, Eq(X, mu)) == mu assert median(X) == FiniteSet(0) # issue 8248 assert X.pspace.compute_expectation(1).doit() == 1 def test_conditional_1d(): X = Normal('x', 0, 1) Y = given(X, X >= 0) z = Symbol('z') assert density(Y)(z) == 2 * density(X)(z) assert Y.pspace.domain.set == Interval(0, oo) assert E(Y) == sqrt(2) / sqrt(pi) assert E(X**2) == E(Y**2) def test_ContinuousDomain(): X = Normal('x', 0, 1) assert where(X**2 <= 1).set == Interval(-1, 1) assert where(X**2 <= 1).symbol == X.symbol assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) raises(ValueError, lambda: where(sin(X) > 1)) Y = given(X, X >= 0) assert Y.pspace.domain.set == Interval(0, oo) def test_multiple_normal(): X, Y = Normal('x', 0, 1), Normal('y', 0, 1) p = Symbol("p", positive=True) assert E(X + Y) == 0 assert variance(X + Y) == 2 assert variance(X + X) == 4 assert covariance(X, Y) == 0 assert covariance(2*X + Y, -X) == -2*variance(X) assert skewness(X) == 0 assert skewness(X + Y) == 0 assert kurtosis(X) == 3 assert kurtosis(X+Y) == 3 assert correlation(X, Y) == 0 assert correlation(X, X + Y) == correlation(X, X - Y) assert moment(X, 2) == 1 assert cmoment(X, 3) == 0 assert moment(X + Y, 4) == 12 assert cmoment(X, 2) == variance(X) assert smoment(X*X, 2) == 1 assert smoment(X + Y, 3) == skewness(X + Y) assert smoment(X + Y, 4) == kurtosis(X + Y) assert E(X, Eq(X + Y, 0)) == 0 assert variance(X, Eq(X + Y, 0)) == S.Half assert quantile(X)(p) == sqrt(2)*erfinv(2*p - S.One) def test_symbolic(): mu1, mu2 = symbols('mu1 mu2', real=True) s1, s2 = symbols('sigma1 sigma2', positive=True) rate = Symbol('lambda', positive=True) X = Normal('x', mu1, s1) Y = Normal('y', mu2, s2) Z = Exponential('z', rate) a, b, c = symbols('a b c', real=True) assert E(X) == mu1 assert E(X + Y) == mu1 + mu2 assert E(a*X + b) == a*E(X) + b assert variance(X) == s1**2 assert variance(X + a*Y + b) == variance(X) + a**2*variance(Y) assert E(Z) == 1/rate assert E(a*Z + b) == a*E(Z) + b assert E(X + a*Z + b) == mu1 + a/rate + b assert median(X) == FiniteSet(mu1) def test_cdf(): X = Normal('x', 0, 1) d = cdf(X) assert P(X < 1) == d(1).rewrite(erfc) assert d(0) == S.Half d = cdf(X, X > 0) # given X>0 assert d(0) == 0 Y = Exponential('y', 10) d = cdf(Y) assert d(-5) == 0 assert P(Y > 3) == 1 - d(3) raises(ValueError, lambda: cdf(X + Y)) Z = Exponential('z', 1) f = cdf(Z) assert f(z) == Piecewise((1 - exp(-z), z >= 0), (0, True)) def test_characteristic_function(): X = Uniform('x', 0, 1) cf = characteristic_function(X) assert cf(1) == -I*(-1 + exp(I)) Y = Normal('y', 1, 1) cf = characteristic_function(Y) assert cf(0) == 1 assert cf(1) == exp(I - S.Half) Z = Exponential('z', 5) cf = characteristic_function(Z) assert cf(0) == 1 assert cf(1).expand() == Rational(25, 26) + I*5/26 X = GaussianInverse('x', 1, 1) cf = characteristic_function(X) assert cf(0) == 1 assert cf(1) == exp(1 - sqrt(1 - 2*I)) X = ExGaussian('x', 0, 1, 1) cf = characteristic_function(X) assert cf(0) == 1 assert cf(1) == (1 + I)*exp(Rational(-1, 2))/2 L = Levy('x', 0, 1) cf = characteristic_function(L) assert cf(0) == 1 assert cf(1) == exp(-sqrt(2)*sqrt(-I)) def test_moment_generating_function(): t = symbols('t', positive=True) # Symbolic tests a, b, c = symbols('a b c') mgf = moment_generating_function(Beta('x', a, b))(t) assert mgf == hyper((a,), (a + b,), t) mgf = moment_generating_function(Chi('x', a))(t) assert mgf == sqrt(2)*t*gamma(a/2 + S.Half)*\ hyper((a/2 + S.Half,), (Rational(3, 2),), t**2/2)/gamma(a/2) +\ hyper((a/2,), (S.Half,), t**2/2) mgf = moment_generating_function(ChiSquared('x', a))(t) assert mgf == (1 - 2*t)**(-a/2) mgf = moment_generating_function(Erlang('x', a, b))(t) assert mgf == (1 - t/b)**(-a) mgf = moment_generating_function(ExGaussian("x", a, b, c))(t) assert mgf == exp(a*t + b**2*t**2/2)/(1 - t/c) mgf = moment_generating_function(Exponential('x', a))(t) assert mgf == a/(a - t) mgf = moment_generating_function(Gamma('x', a, b))(t) assert mgf == (-b*t + 1)**(-a) mgf = moment_generating_function(Gumbel('x', a, b))(t) assert mgf == exp(b*t)*gamma(-a*t + 1) mgf = moment_generating_function(Gompertz('x', a, b))(t) assert mgf == b*exp(b)*expint(t/a, b) mgf = moment_generating_function(Laplace('x', a, b))(t) assert mgf == exp(a*t)/(-b**2*t**2 + 1) mgf = moment_generating_function(Logistic('x', a, b))(t) assert mgf == exp(a*t)*beta(-b*t + 1, b*t + 1) mgf = moment_generating_function(Normal('x', a, b))(t) assert mgf == exp(a*t + b**2*t**2/2) mgf = moment_generating_function(Pareto('x', a, b))(t) assert mgf == b*(-a*t)**b*uppergamma(-b, -a*t) mgf = moment_generating_function(QuadraticU('x', a, b))(t) assert str(mgf) == ("(3*(t*(-4*b + (a + b)**2) + 4)*exp(b*t) - " "3*(t*(a**2 + 2*a*(b - 2) + b**2) + 4)*exp(a*t))/(t**2*(a - b)**3)") mgf = moment_generating_function(RaisedCosine('x', a, b))(t) assert mgf == pi**2*exp(a*t)*sinh(b*t)/(b*t*(b**2*t**2 + pi**2)) mgf = moment_generating_function(Rayleigh('x', a))(t) assert mgf == sqrt(2)*sqrt(pi)*a*t*(erf(sqrt(2)*a*t/2) + 1)\ *exp(a**2*t**2/2)/2 + 1 mgf = moment_generating_function(Triangular('x', a, b, c))(t) assert str(mgf) == ("(-2*(-a + b)*exp(c*t) + 2*(-a + c)*exp(b*t) + " "2*(b - c)*exp(a*t))/(t**2*(-a + b)*(-a + c)*(b - c))") mgf = moment_generating_function(Uniform('x', a, b))(t) assert mgf == (-exp(a*t) + exp(b*t))/(t*(-a + b)) mgf = moment_generating_function(UniformSum('x', a))(t) assert mgf == ((exp(t) - 1)/t)**a mgf = moment_generating_function(WignerSemicircle('x', a))(t) assert mgf == 2*besseli(1, a*t)/(a*t) # Numeric tests mgf = moment_generating_function(Beta('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == hyper((2,), (3,), 1)/2 mgf = moment_generating_function(Chi('x', 1))(t) assert mgf.diff(t).subs(t, 1) == sqrt(2)*hyper((1,), (Rational(3, 2),), S.Half )/sqrt(pi) + hyper((Rational(3, 2),), (Rational(3, 2),), S.Half) + 2*sqrt(2)*hyper((2,), (Rational(5, 2),), S.Half)/(3*sqrt(pi)) mgf = moment_generating_function(ChiSquared('x', 1))(t) assert mgf.diff(t).subs(t, 1) == I mgf = moment_generating_function(Erlang('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(ExGaussian("x", 0, 1, 1))(t) assert mgf.diff(t).subs(t, 2) == -exp(2) mgf = moment_generating_function(Exponential('x', 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Gamma('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Gumbel('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == EulerGamma + 1 mgf = moment_generating_function(Gompertz('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == -e*meijerg(((), (1, 1)), ((0, 0, 0), ()), 1) mgf = moment_generating_function(Laplace('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Logistic('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == beta(1, 1) mgf = moment_generating_function(Normal('x', 0, 1))(t) assert mgf.diff(t).subs(t, 1) == exp(S.Half) mgf = moment_generating_function(Pareto('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == expint(1, 0) mgf = moment_generating_function(QuadraticU('x', 1, 2))(t) assert mgf.diff(t).subs(t, 1) == -12*e - 3*exp(2) mgf = moment_generating_function(RaisedCosine('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == -2*e*pi**2*sinh(1)/\ (1 + pi**2)**2 + e*pi**2*cosh(1)/(1 + pi**2) mgf = moment_generating_function(Rayleigh('x', 1))(t) assert mgf.diff(t).subs(t, 0) == sqrt(2)*sqrt(pi)/2 mgf = moment_generating_function(Triangular('x', 1, 3, 2))(t) assert mgf.diff(t).subs(t, 1) == -e + exp(3) mgf = moment_generating_function(Uniform('x', 0, 1))(t) assert mgf.diff(t).subs(t, 1) == 1 mgf = moment_generating_function(UniformSum('x', 1))(t) assert mgf.diff(t).subs(t, 1) == 1 mgf = moment_generating_function(WignerSemicircle('x', 1))(t) assert mgf.diff(t).subs(t, 1) == -2*besseli(1, 1) + besseli(2, 1) +\ besseli(0, 1) def test_ContinuousRV(): pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution # X and Y should be equivalent X = ContinuousRV(x, pdf, check=True) Y = Normal('y', 0, 1) assert variance(X) == variance(Y) assert P(X > 0) == P(Y > 0) Z = ContinuousRV(z, exp(-z), set=Interval(0, oo)) assert Z.pspace.domain.set == Interval(0, oo) assert E(Z) == 1 assert P(Z > 5) == exp(-5) raises(ValueError, lambda: ContinuousRV(z, exp(-z), set=Interval(0, 10), check=True)) # the correct pdf for Gamma(k, theta) but the integral in `check` # integrates to something equivalent to 1 and not to 1 exactly _x, k, theta = symbols("x k theta", positive=True) pdf = 1/(gamma(k)*theta**k)*_x**(k-1)*exp(-_x/theta) X = ContinuousRV(_x, pdf, set=Interval(0, oo)) Y = Gamma('y', k, theta) assert (E(X) - E(Y)).simplify() == 0 assert (variance(X) - variance(Y)).simplify() == 0 def test_arcsin(): a = Symbol("a", real=True) b = Symbol("b", real=True) X = Arcsin('x', a, b) assert density(X)(x) == 1/(pi*sqrt((-x + b)*(x - a))) assert cdf(X)(x) == Piecewise((0, a > x), (2*asin(sqrt((-a + x)/(-a + b)))/pi, b >= x), (1, True)) assert pspace(X).domain.set == Interval(a, b) def test_benini(): alpha = Symbol("alpha", positive=True) beta = Symbol("beta", positive=True) sigma = Symbol("sigma", positive=True) X = Benini('x', alpha, beta, sigma) assert density(X)(x) == ((alpha/x + 2*beta*log(x/sigma)/x) *exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2)) assert pspace(X).domain.set == Interval(sigma, oo) raises(NotImplementedError, lambda: moment_generating_function(X)) alpha = Symbol("alpha", nonpositive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) beta = Symbol("beta", nonpositive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) alpha = Symbol("alpha", positive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) beta = Symbol("beta", positive=True) sigma = Symbol("sigma", nonpositive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) def test_beta(): a, b = symbols('alpha beta', positive=True) B = Beta('x', a, b) assert pspace(B).domain.set == Interval(0, 1) assert characteristic_function(B)(x) == hyper((a,), (a + b,), I*x) assert density(B)(x) == x**(a - 1)*(1 - x)**(b - 1)/beta(a, b) assert simplify(E(B)) == a / (a + b) assert simplify(variance(B)) == a*b / (a**3 + 3*a**2*b + a**2 + 3*a*b**2 + 2*a*b + b**3 + b**2) # Full symbolic solution is too much, test with numeric version a, b = 1, 2 B = Beta('x', a, b) assert expand_func(E(B)) == a / S(a + b) assert expand_func(variance(B)) == (a*b) / S((a + b)**2 * (a + b + 1)) assert median(B) == FiniteSet(1 - 1/sqrt(2)) def test_beta_noncentral(): a, b = symbols('a b', positive=True) c = Symbol('c', nonnegative=True) _k = Dummy('k') X = BetaNoncentral('x', a, b, c) assert pspace(X).domain.set == Interval(0, 1) dens = density(X) z = Symbol('z') res = Sum( z**(_k + a - 1)*(c/2)**_k*(1 - z)**(b - 1)*exp(-c/2)/ (beta(_k + a, b)*factorial(_k)), (_k, 0, oo)) assert dens(z).dummy_eq(res) # BetaCentral should not raise if the assumptions # on the symbols can not be determined a, b, c = symbols('a b c') assert BetaNoncentral('x', a, b, c) a = Symbol('a', positive=False, real=True) raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) a = Symbol('a', positive=True) b = Symbol('b', positive=False, real=True) raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) a = Symbol('a', positive=True) b = Symbol('b', positive=True) c = Symbol('c', nonnegative=False, real=True) raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) def test_betaprime(): alpha = Symbol("alpha", positive=True) betap = Symbol("beta", positive=True) X = BetaPrime('x', alpha, betap) assert density(X)(x) == x**(alpha - 1)*(x + 1)**(-alpha - betap)/beta(alpha, betap) alpha = Symbol("alpha", nonpositive=True) raises(ValueError, lambda: BetaPrime('x', alpha, betap)) alpha = Symbol("alpha", positive=True) betap = Symbol("beta", nonpositive=True) raises(ValueError, lambda: BetaPrime('x', alpha, betap)) X = BetaPrime('x', 1, 1) assert median(X) == FiniteSet(1) def test_BoundedPareto(): L, H = symbols('L, H', negative=True) raises(ValueError, lambda: BoundedPareto('X', 1, L, H)) L, H = symbols('L, H', real=False) raises(ValueError, lambda: BoundedPareto('X', 1, L, H)) L, H = symbols('L, H', positive=True) raises(ValueError, lambda: BoundedPareto('X', -1, L, H)) X = BoundedPareto('X', 2, L, H) assert X.pspace.domain.set == Interval(L, H) assert density(X)(x) == 2*L**2/(x**3*(1 - L**2/H**2)) assert cdf(X)(x) == Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) \ + H**2/(H**2 - L**2), L <= x), (0, True)) assert E(X).simplify() == 2*H*L/(H + L) X = BoundedPareto('X', 1, 2, 4) assert E(X).simplify() == log(16) assert median(X) == FiniteSet(Rational(8, 3)) assert variance(X).simplify() == 8 - 16*log(2)**2 def test_cauchy(): x0 = Symbol("x0", real=True) gamma = Symbol("gamma", positive=True) p = Symbol("p", positive=True) X = Cauchy('x', x0, gamma) # Tests the characteristic function assert characteristic_function(X)(x) == exp(-gamma*Abs(x) + I*x*x0) raises(NotImplementedError, lambda: moment_generating_function(X)) assert density(X)(x) == 1/(pi*gamma*(1 + (x - x0)**2/gamma**2)) assert diff(cdf(X)(x), x) == density(X)(x) assert quantile(X)(p) == gamma*tan(pi*(p - S.Half)) + x0 x1 = Symbol("x1", real=False) raises(ValueError, lambda: Cauchy('x', x1, gamma)) gamma = Symbol("gamma", nonpositive=True) raises(ValueError, lambda: Cauchy('x', x0, gamma)) assert median(X) == FiniteSet(x0) def test_chi(): from sympy.core.numbers import I k = Symbol("k", integer=True) X = Chi('x', k) assert density(X)(x) == 2**(-k/2 + 1)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) # Tests the characteristic function assert characteristic_function(X)(x) == sqrt(2)*I*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,), (S(3)/2,), -x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), -x**2/2) # Tests the moment generating function assert moment_generating_function(X)(x) == sqrt(2)*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,), (S(3)/2,), x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), x**2/2) k = Symbol("k", integer=True, positive=False) raises(ValueError, lambda: Chi('x', k)) k = Symbol("k", integer=False, positive=True) raises(ValueError, lambda: Chi('x', k)) def test_chi_noncentral(): k = Symbol("k", integer=True) l = Symbol("l") X = ChiNoncentral("x", k, l) assert density(X)(x) == (x**k*l*(x*l)**(-k/2)* exp(-x**2/2 - l**2/2)*besseli(k/2 - 1, x*l)) k = Symbol("k", integer=True, positive=False) raises(ValueError, lambda: ChiNoncentral('x', k, l)) k = Symbol("k", integer=True, positive=True) l = Symbol("l", nonpositive=True) raises(ValueError, lambda: ChiNoncentral('x', k, l)) k = Symbol("k", integer=False) l = Symbol("l", positive=True) raises(ValueError, lambda: ChiNoncentral('x', k, l)) def test_chi_squared(): k = Symbol("k", integer=True) X = ChiSquared('x', k) # Tests the characteristic function assert characteristic_function(X)(x) == ((-2*I*x + 1)**(-k/2)) assert density(X)(x) == 2**(-k/2)*x**(k/2 - 1)*exp(-x/2)/gamma(k/2) assert cdf(X)(x) == Piecewise((lowergamma(k/2, x/2)/gamma(k/2), x >= 0), (0, True)) assert E(X) == k assert variance(X) == 2*k X = ChiSquared('x', 15) assert cdf(X)(3) == -14873*sqrt(6)*exp(Rational(-3, 2))/(5005*sqrt(pi)) + erf(sqrt(6)/2) k = Symbol("k", integer=True, positive=False) raises(ValueError, lambda: ChiSquared('x', k)) k = Symbol("k", integer=False, positive=True) raises(ValueError, lambda: ChiSquared('x', k)) def test_dagum(): p = Symbol("p", positive=True) b = Symbol("b", positive=True) a = Symbol("a", positive=True) X = Dagum('x', p, a, b) assert density(X)(x) == a*p*(x/b)**(a*p)*((x/b)**a + 1)**(-p - 1)/x assert cdf(X)(x) == Piecewise(((1 + (x/b)**(-a))**(-p), x >= 0), (0, True)) p = Symbol("p", nonpositive=True) raises(ValueError, lambda: Dagum('x', p, a, b)) p = Symbol("p", positive=True) b = Symbol("b", nonpositive=True) raises(ValueError, lambda: Dagum('x', p, a, b)) b = Symbol("b", positive=True) a = Symbol("a", nonpositive=True) raises(ValueError, lambda: Dagum('x', p, a, b)) X = Dagum('x', 1, 1, 1) assert median(X) == FiniteSet(1) def test_erlang(): k = Symbol("k", integer=True, positive=True) l = Symbol("l", positive=True) X = Erlang("x", k, l) assert density(X)(x) == x**(k - 1)*l**k*exp(-x*l)/gamma(k) assert cdf(X)(x) == Piecewise((lowergamma(k, l*x)/gamma(k), x > 0), (0, True)) def test_exgaussian(): m, z = symbols("m, z") s, l = symbols("s, l", positive=True) X = ExGaussian("x", m, s, l) assert density(X)(z) == l*exp(l*(l*s**2 + 2*m - 2*z)/2) *\ erfc(sqrt(2)*(l*s**2 + m - z)/(2*s))/2 # Note: actual_output simplifies to expected_output. # Ideally cdf(X)(z) would return expected_output # expected_output = (erf(sqrt(2)*(l*s**2 + m - z)/(2*s)) - 1)*exp(l*(l*s**2 + 2*m - 2*z)/2)/2 - erf(sqrt(2)*(m - z)/(2*s))/2 + S.Half u = l*(z - m) v = l*s GaussianCDF1 = cdf(Normal('x', 0, v))(u) GaussianCDF2 = cdf(Normal('x', v**2, v))(u) actual_output = GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2)) assert cdf(X)(z) == actual_output # assert simplify(actual_output) == expected_output assert variance(X).expand() == s**2 + l**(-2) assert skewness(X).expand() == 2/(l**3*s**2*sqrt(s**2 + l**(-2)) + l * sqrt(s**2 + l**(-2))) @slow def test_exponential(): rate = Symbol('lambda', positive=True) X = Exponential('x', rate) p = Symbol("p", positive=True, real=True) assert E(X) == 1/rate assert variance(X) == 1/rate**2 assert skewness(X) == 2 assert skewness(X) == smoment(X, 3) assert kurtosis(X) == 9 assert kurtosis(X) == smoment(X, 4) assert smoment(2*X, 4) == smoment(X, 4) assert moment(X, 3) == 3*2*1/rate**3 assert P(X > 0) is S.One assert P(X > 1) == exp(-rate) assert P(X > 10) == exp(-10*rate) assert quantile(X)(p) == -log(1-p)/rate assert where(X <= 1).set == Interval(0, 1) Y = Exponential('y', 1) assert median(Y) == FiniteSet(log(2)) #Test issue 9970 z = Dummy('z') assert P(X > z) == exp(-z*rate) assert P(X < z) == 0 #Test issue 10076 (Distribution with interval(0,oo)) x = Symbol('x') _z = Dummy('_z') b = SingleContinuousPSpace(x, ExponentialDistribution(2)) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed expected1 = Integral(2*exp(-2*_z), (_z, 3, oo)) assert b.probability(x > 3, evaluate=False).rewrite(Integral).dummy_eq(expected1) expected2 = Integral(2*exp(-2*_z), (_z, 0, 4)) assert b.probability(x < 4, evaluate=False).rewrite(Integral).dummy_eq(expected2) Y = Exponential('y', 2*rate) assert coskewness(X, X, X) == skewness(X) assert coskewness(X, Y + rate*X, Y + 2*rate*X) == \ 4/(sqrt(1 + 1/(4*rate**2))*sqrt(4 + 1/(4*rate**2))) assert coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3) == \ sqrt(170)*Rational(9, 85) def test_exponential_power(): mu = Symbol('mu') z = Symbol('z') alpha = Symbol('alpha', positive=True) beta = Symbol('beta', positive=True) X = ExponentialPower('x', mu, alpha, beta) assert density(X)(z) == beta*exp(-(Abs(mu - z)/alpha) ** beta)/(2*alpha*gamma(1/beta)) assert cdf(X)(z) == S.Half + lowergamma(1/beta, (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/\ (2*gamma(1/beta)) def test_f_distribution(): d1 = Symbol("d1", positive=True) d2 = Symbol("d2", positive=True) X = FDistribution("x", d1, d2) assert density(X)(x) == (d2**(d2/2)*sqrt((d1*x)**d1*(d1*x + d2)**(-d1 - d2)) /(x*beta(d1/2, d2/2))) raises(NotImplementedError, lambda: moment_generating_function(X)) d1 = Symbol("d1", nonpositive=True) raises(ValueError, lambda: FDistribution('x', d1, d1)) d1 = Symbol("d1", positive=True, integer=False) raises(ValueError, lambda: FDistribution('x', d1, d1)) d1 = Symbol("d1", positive=True) d2 = Symbol("d2", nonpositive=True) raises(ValueError, lambda: FDistribution('x', d1, d2)) d2 = Symbol("d2", positive=True, integer=False) raises(ValueError, lambda: FDistribution('x', d1, d2)) def test_fisher_z(): d1 = Symbol("d1", positive=True) d2 = Symbol("d2", positive=True) X = FisherZ("x", d1, d2) assert density(X)(x) == (2*d1**(d1/2)*d2**(d2/2)*(d1*exp(2*x) + d2) **(-d1/2 - d2/2)*exp(d1*x)/beta(d1/2, d2/2)) def test_frechet(): a = Symbol("a", positive=True) s = Symbol("s", positive=True) m = Symbol("m", real=True) X = Frechet("x", a, s=s, m=m) assert density(X)(x) == a*((x - m)/s)**(-a - 1)*exp(-((x - m)/s)**(-a))/s assert cdf(X)(x) == Piecewise((exp(-((-m + x)/s)**(-a)), m <= x), (0, True)) @slow def test_gamma(): k = Symbol("k", positive=True) theta = Symbol("theta", positive=True) X = Gamma('x', k, theta) # Tests characteristic function assert characteristic_function(X)(x) == ((-I*theta*x + 1)**(-k)) assert density(X)(x) == x**(k - 1)*theta**(-k)*exp(-x/theta)/gamma(k) assert cdf(X, meijerg=True)(z) == Piecewise( (-k*lowergamma(k, 0)/gamma(k + 1) + k*lowergamma(k, z/theta)/gamma(k + 1), z >= 0), (0, True)) # assert simplify(variance(X)) == k*theta**2 # handled numerically below assert E(X) == moment(X, 1) k, theta = symbols('k theta', positive=True) X = Gamma('x', k, theta) assert E(X) == k*theta assert variance(X) == k*theta**2 assert skewness(X).expand() == 2/sqrt(k) assert kurtosis(X).expand() == 3 + 6/k Y = Gamma('y', 2*k, 3*theta) assert coskewness(X, theta*X + Y, k*X + Y).simplify() == \ 2*531441**(-k)*sqrt(k)*theta*(3*3**(12*k) - 2*531441**k) \ /(sqrt(k**2 + 18)*sqrt(theta**2 + 18)) def test_gamma_inverse(): a = Symbol("a", positive=True) b = Symbol("b", positive=True) X = GammaInverse("x", a, b) assert density(X)(x) == x**(-a - 1)*b**a*exp(-b/x)/gamma(a) assert cdf(X)(x) == Piecewise((uppergamma(a, b/x)/gamma(a), x > 0), (0, True)) assert characteristic_function(X)(x) == 2 * (-I*b*x)**(a/2) \ * besselk(a, 2*sqrt(b)*sqrt(-I*x))/gamma(a) raises(NotImplementedError, lambda: moment_generating_function(X)) def test_gompertz(): b = Symbol("b", positive=True) eta = Symbol("eta", positive=True) X = Gompertz("x", b, eta) assert density(X)(x) == b*eta*exp(eta)*exp(b*x)*exp(-eta*exp(b*x)) assert cdf(X)(x) == 1 - exp(eta)*exp(-eta*exp(b*x)) assert diff(cdf(X)(x), x) == density(X)(x) def test_gumbel(): beta = Symbol("beta", positive=True) mu = Symbol("mu") x = Symbol("x") y = Symbol("y") X = Gumbel("x", beta, mu) Y = Gumbel("y", beta, mu, minimum=True) assert density(X)(x).expand() == \ exp(mu/beta)*exp(-x/beta)*exp(-exp(mu/beta)*exp(-x/beta))/beta assert density(Y)(y).expand() == \ exp(-mu/beta)*exp(y/beta)*exp(-exp(-mu/beta)*exp(y/beta))/beta assert cdf(X)(x).expand() == \ exp(-exp(mu/beta)*exp(-x/beta)) assert characteristic_function(X)(x) == exp(I*mu*x)*gamma(-I*beta*x + 1) def test_kumaraswamy(): a = Symbol("a", positive=True) b = Symbol("b", positive=True) X = Kumaraswamy("x", a, b) assert density(X)(x) == x**(a - 1)*a*b*(-x**a + 1)**(b - 1) assert cdf(X)(x) == Piecewise((0, x < 0), (-(-x**a + 1)**b + 1, x <= 1), (1, True)) def test_laplace(): mu = Symbol("mu") b = Symbol("b", positive=True) X = Laplace('x', mu, b) #Tests characteristic_function assert characteristic_function(X)(x) == (exp(I*mu*x)/(b**2*x**2 + 1)) assert density(X)(x) == exp(-Abs(x - mu)/b)/(2*b) assert cdf(X)(x) == Piecewise((exp((-mu + x)/b)/2, mu > x), (-exp((mu - x)/b)/2 + 1, True)) X = Laplace('x', [1, 2], [[1, 0], [0, 1]]) assert isinstance(pspace(X).distribution, MultivariateLaplaceDistribution) def test_levy(): mu = Symbol("mu", real=True) c = Symbol("c", positive=True) X = Levy('x', mu, c) assert X.pspace.domain.set == Interval(mu, oo) assert density(X)(x) == sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half)) assert cdf(X)(x) == erfc(sqrt(c/(2*(x - mu)))) raises(NotImplementedError, lambda: moment_generating_function(X)) mu = Symbol("mu", real=False) raises(ValueError, lambda: Levy('x',mu,c)) c = Symbol("c", nonpositive=True) raises(ValueError, lambda: Levy('x',mu,c)) mu = Symbol("mu", real=True) raises(ValueError, lambda: Levy('x',mu,c)) def test_logcauchy(): mu = Symbol("mu", positive=True) sigma = Symbol("sigma", positive=True) X = LogCauchy("x", mu, sigma) assert density(X)(x) == sigma/(x*pi*(sigma**2 + (-mu + log(x))**2)) assert cdf(X)(x) == atan((log(x) - mu)/sigma)/pi + S.Half def test_logistic(): mu = Symbol("mu", real=True) s = Symbol("s", positive=True) p = Symbol("p", positive=True) X = Logistic('x', mu, s) #Tests characteristics_function assert characteristic_function(X)(x) == \ (Piecewise((pi*s*x*exp(I*mu*x)/sinh(pi*s*x), Ne(x, 0)), (1, True))) assert density(X)(x) == exp((-x + mu)/s)/(s*(exp((-x + mu)/s) + 1)**2) assert cdf(X)(x) == 1/(exp((mu - x)/s) + 1) assert quantile(X)(p) == mu - s*log(-S.One + 1/p) def test_loglogistic(): a, b = symbols('a b') assert LogLogistic('x', a, b) a = Symbol('a', negative=True) b = Symbol('b', positive=True) raises(ValueError, lambda: LogLogistic('x', a, b)) a = Symbol('a', positive=True) b = Symbol('b', negative=True) raises(ValueError, lambda: LogLogistic('x', a, b)) a, b, z, p = symbols('a b z p', positive=True) X = LogLogistic('x', a, b) assert density(X)(z) == b*(z/a)**(b - 1)/(a*((z/a)**b + 1)**2) assert cdf(X)(z) == 1/(1 + (z/a)**(-b)) assert quantile(X)(p) == a*(p/(1 - p))**(1/b) # Expectation assert E(X) == Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True)) b = symbols('b', prime=True) # b > 1 X = LogLogistic('x', a, b) assert E(X) == pi*a/(b*sin(pi/b)) X = LogLogistic('x', 1, 2) assert median(X) == FiniteSet(1) def test_logitnormal(): mu = Symbol('mu', real=True) s = Symbol('s', positive=True) X = LogitNormal('x', mu, s) x = Symbol('x') assert density(X)(x) == sqrt(2)*exp(-(-mu + log(x/(1 - x)))**2/(2*s**2))/(2*sqrt(pi)*s*x*(1 - x)) assert cdf(X)(x) == erf(sqrt(2)*(-mu + log(x/(1 - x)))/(2*s))/2 + S(1)/2 def test_lognormal(): mean = Symbol('mu', real=True) std = Symbol('sigma', positive=True) X = LogNormal('x', mean, std) # The sympy integrator can't do this too well #assert E(X) == exp(mean+std**2/2) #assert variance(X) == (exp(std**2)-1) * exp(2*mean + std**2) # The sympy integrator can't do this too well #assert E(X) == raises(NotImplementedError, lambda: moment_generating_function(X)) mu = Symbol("mu", real=True) sigma = Symbol("sigma", positive=True) X = LogNormal('x', mu, sigma) assert density(X)(x) == (sqrt(2)*exp(-(-mu + log(x))**2 /(2*sigma**2))/(2*x*sqrt(pi)*sigma)) # Tests cdf assert cdf(X)(x) == Piecewise( (erf(sqrt(2)*(-mu + log(x))/(2*sigma))/2 + S(1)/2, x > 0), (0, True)) X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 assert density(X)(x) == sqrt(2)*exp(-log(x)**2/2)/(2*x*sqrt(pi)) def test_Lomax(): a, l = symbols('a, l', negative=True) raises(ValueError, lambda: Lomax('X', a, l)) a, l = symbols('a, l', real=False) raises(ValueError, lambda: Lomax('X', a, l)) a, l = symbols('a, l', positive=True) X = Lomax('X', a, l) assert X.pspace.domain.set == Interval(0, oo) assert density(X)(x) == a*(1 + x/l)**(-a - 1)/l assert cdf(X)(x) == Piecewise((1 - (1 + x/l)**(-a), x >= 0), (0, True)) a = 3 X = Lomax('X', a, l) assert E(X) == l/2 assert median(X) == FiniteSet(l*(-1 + 2**Rational(1, 3))) assert variance(X) == 3*l**2/4 def test_maxwell(): a = Symbol("a", positive=True) X = Maxwell('x', a) assert density(X)(x) == (sqrt(2)*x**2*exp(-x**2/(2*a**2))/ (sqrt(pi)*a**3)) assert E(X) == 2*sqrt(2)*a/sqrt(pi) assert variance(X) == -8*a**2/pi + 3*a**2 assert cdf(X)(x) == erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a) assert diff(cdf(X)(x), x) == density(X)(x) @slow def test_Moyal(): mu = Symbol('mu',real=False) sigma = Symbol('sigma', positive=True) raises(ValueError, lambda: Moyal('M',mu, sigma)) mu = Symbol('mu', real=True) sigma = Symbol('sigma', negative=True) raises(ValueError, lambda: Moyal('M',mu, sigma)) sigma = Symbol('sigma', positive=True) M = Moyal('M', mu, sigma) assert density(M)(z) == sqrt(2)*exp(-exp((mu - z)/sigma)/2 - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma) assert cdf(M)(z).simplify() == 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2) assert characteristic_function(M)(z) == 2**(-I*sigma*z)*exp(I*mu*z) \ *gamma(-I*sigma*z + Rational(1, 2))/sqrt(pi) assert E(M) == mu + EulerGamma*sigma + sigma*log(2) assert moment_generating_function(M)(z) == 2**(-sigma*z)*exp(mu*z) \ *gamma(-sigma*z + Rational(1, 2))/sqrt(pi) def test_nakagami(): mu = Symbol("mu", positive=True) omega = Symbol("omega", positive=True) X = Nakagami('x', mu, omega) assert density(X)(x) == (2*x**(2*mu - 1)*mu**mu*omega**(-mu) *exp(-x**2*mu/omega)/gamma(mu)) assert simplify(E(X)) == (sqrt(mu)*sqrt(omega) *gamma(mu + S.Half)/gamma(mu + 1)) assert simplify(variance(X)) == ( omega - omega*gamma(mu + S.Half)**2/(gamma(mu)*gamma(mu + 1))) assert cdf(X)(x) == Piecewise( (lowergamma(mu, mu*x**2/omega)/gamma(mu), x > 0), (0, True)) X = Nakagami('x', 1, 1) assert median(X) == FiniteSet(sqrt(log(2))) def test_gaussian_inverse(): # test for symbolic parameters a, b = symbols('a b') assert GaussianInverse('x', a, b) # Inverse Gaussian distribution is also known as Wald distribution # `GaussianInverse` can also be referred by the name `Wald` a, b, z = symbols('a b z') X = Wald('x', a, b) assert density(X)(z) == sqrt(2)*sqrt(b/z**3)*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi)) a, b = symbols('a b', positive=True) z = Symbol('z', positive=True) X = GaussianInverse('x', a, b) assert density(X)(z) == sqrt(2)*sqrt(b)*sqrt(z**(-3))*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi)) assert E(X) == a assert variance(X).expand() == a**3/b assert cdf(X)(z) == (S.Half - erf(sqrt(2)*sqrt(b)*(1 + z/a)/(2*sqrt(z)))/2)*exp(2*b/a) +\ erf(sqrt(2)*sqrt(b)*(-1 + z/a)/(2*sqrt(z)))/2 + S.Half a = symbols('a', nonpositive=True) raises(ValueError, lambda: GaussianInverse('x', a, b)) a = symbols('a', positive=True) b = symbols('b', nonpositive=True) raises(ValueError, lambda: GaussianInverse('x', a, b)) def test_pareto(): xm, beta = symbols('xm beta', positive=True) alpha = beta + 5 X = Pareto('x', xm, alpha) dens = density(X) #Tests cdf function assert cdf(X)(x) == \ Piecewise((-x**(-beta - 5)*xm**(beta + 5) + 1, x >= xm), (0, True)) #Tests characteristic_function assert characteristic_function(X)(x) == \ ((-I*x*xm)**(beta + 5)*(beta + 5)*uppergamma(-beta - 5, -I*x*xm)) assert dens(x) == x**(-(alpha + 1))*xm**(alpha)*(alpha) assert simplify(E(X)) == alpha*xm/(alpha-1) # computation of taylor series for MGF still too slow #assert simplify(variance(X)) == xm**2*alpha / ((alpha-1)**2*(alpha-2)) def test_pareto_numeric(): xm, beta = 3, 2 alpha = beta + 5 X = Pareto('x', xm, alpha) assert E(X) == alpha*xm/S(alpha - 1) assert variance(X) == xm**2*alpha / S((alpha - 1)**2*(alpha - 2)) assert median(X) == FiniteSet(3*2**Rational(1, 7)) # Skewness tests too slow. Try shortcutting function? def test_PowerFunction(): alpha = Symbol("alpha", nonpositive=True) a, b = symbols('a, b', real=True) raises (ValueError, lambda: PowerFunction('x', alpha, a, b)) a, b = symbols('a, b', real=False) raises (ValueError, lambda: PowerFunction('x', alpha, a, b)) alpha = Symbol("alpha", positive=True) a, b = symbols('a, b', real=True) raises (ValueError, lambda: PowerFunction('x', alpha, 5, 2)) X = PowerFunction('X', 2, a, b) assert density(X)(z) == (-2*a + 2*z)/(-a + b)**2 assert cdf(X)(z) == Piecewise((a**2/(a**2 - 2*a*b + b**2) - 2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True)) X = PowerFunction('X', 2, 0, 1) assert density(X)(z) == 2*z assert cdf(X)(z) == Piecewise((z**2, z >= 0), (0,True)) assert E(X) == Rational(2,3) assert P(X < 0) == 0 assert P(X < 1) == 1 assert median(X) == FiniteSet(1/sqrt(2)) def test_raised_cosine(): mu = Symbol("mu", real=True) s = Symbol("s", positive=True) X = RaisedCosine("x", mu, s) assert pspace(X).domain.set == Interval(mu - s, mu + s) #Tests characteristics_function assert characteristic_function(X)(x) == \ Piecewise((exp(-I*pi*mu/s)/2, Eq(x, -pi/s)), (exp(I*pi*mu/s)/2, Eq(x, pi/s)), (pi**2*exp(I*mu*x)*sin(s*x)/(s*x*(-s**2*x**2 + pi**2)), True)) assert density(X)(x) == (Piecewise(((cos(pi*(x - mu)/s) + 1)/(2*s), And(x <= mu + s, mu - s <= x)), (0, True))) def test_rayleigh(): sigma = Symbol("sigma", positive=True) X = Rayleigh('x', sigma) #Tests characteristic_function assert characteristic_function(X)(x) == (-sqrt(2)*sqrt(pi)*sigma*x*(erfi(sqrt(2)*sigma*x/2) - I)*exp(-sigma**2*x**2/2)/2 + 1) assert density(X)(x) == x*exp(-x**2/(2*sigma**2))/sigma**2 assert E(X) == sqrt(2)*sqrt(pi)*sigma/2 assert variance(X) == -pi*sigma**2/2 + 2*sigma**2 assert cdf(X)(x) == 1 - exp(-x**2/(2*sigma**2)) assert diff(cdf(X)(x), x) == density(X)(x) def test_reciprocal(): a = Symbol("a", real=True) b = Symbol("b", real=True) X = Reciprocal('x', a, b) assert density(X)(x) == 1/(x*(-log(a) + log(b))) assert cdf(X)(x) == Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True)) X = Reciprocal('x', 5, 30) assert E(X) == 25/(log(30) - log(5)) assert P(X < 4) == S.Zero assert P(X < 20) == log(20) / (log(30) - log(5)) - log(5) / (log(30) - log(5)) assert cdf(X)(10) == log(10) / (log(30) - log(5)) - log(5) / (log(30) - log(5)) a = symbols('a', nonpositive=True) raises(ValueError, lambda: Reciprocal('x', a, b)) a = symbols('a', positive=True) b = symbols('b', positive=True) raises(ValueError, lambda: Reciprocal('x', a + b, a)) def test_shiftedgompertz(): b = Symbol("b", positive=True) eta = Symbol("eta", positive=True) X = ShiftedGompertz("x", b, eta) assert density(X)(x) == b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x)) def test_studentt(): nu = Symbol("nu", positive=True) X = StudentT('x', nu) assert density(X)(x) == (1 + x**2/nu)**(-nu/2 - S.Half)/(sqrt(nu)*beta(S.Half, nu/2)) assert cdf(X)(x) == S.Half + x*gamma(nu/2 + S.Half)*hyper((S.Half, nu/2 + S.Half), (Rational(3, 2),), -x**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2)) raises(NotImplementedError, lambda: moment_generating_function(X)) def test_trapezoidal(): a = Symbol("a", real=True) b = Symbol("b", real=True) c = Symbol("c", real=True) d = Symbol("d", real=True) X = Trapezoidal('x', a, b, c, d) assert density(X)(x) == Piecewise(((-2*a + 2*x)/((-a + b)*(-a - b + c + d)), (a <= x) & (x < b)), (2/(-a - b + c + d), (b <= x) & (x < c)), ((2*d - 2*x)/((-c + d)*(-a - b + c + d)), (c <= x) & (x <= d)), (0, True)) X = Trapezoidal('x', 0, 1, 2, 3) assert E(X) == Rational(3, 2) assert variance(X) == Rational(5, 12) assert P(X < 2) == Rational(3, 4) assert median(X) == FiniteSet(Rational(3, 2)) def test_triangular(): a = Symbol("a") b = Symbol("b") c = Symbol("c") X = Triangular('x', a, b, c) assert pspace(X).domain.set == Interval(a, b) assert str(density(X)(x)) == ("Piecewise(((-2*a + 2*x)/((-a + b)*(-a + c)), (a <= x) & (c > x)), " "(2/(-a + b), Eq(c, x)), ((2*b - 2*x)/((-a + b)*(b - c)), (b >= x) & (c < x)), (0, True))") #Tests moment_generating_function assert moment_generating_function(X)(x).expand() == \ ((-2*(-a + b)*exp(c*x) + 2*(-a + c)*exp(b*x) + 2*(b - c)*exp(a*x))/(x**2*(-a + b)*(-a + c)*(b - c))).expand() assert str(characteristic_function(X)(x)) == \ '(2*(-a + b)*exp(I*c*x) - 2*(-a + c)*exp(I*b*x) - 2*(b - c)*exp(I*a*x))/(x**2*(-a + b)*(-a + c)*(b - c))' def test_quadratic_u(): a = Symbol("a", real=True) b = Symbol("b", real=True) X = QuadraticU("x", a, b) Y = QuadraticU("x", 1, 2) assert pspace(X).domain.set == Interval(a, b) # Tests _moment_generating_function assert moment_generating_function(Y)(1) == -15*exp(2) + 27*exp(1) assert moment_generating_function(Y)(2) == -9*exp(4)/2 + 21*exp(2)/2 assert characteristic_function(Y)(1) == 3*I*(-1 + 4*I)*exp(I*exp(2*I)) assert density(X)(x) == (Piecewise((12*(x - a/2 - b/2)**2/(-a + b)**3, And(x <= b, a <= x)), (0, True))) def test_uniform(): l = Symbol('l', real=True) w = Symbol('w', positive=True) X = Uniform('x', l, l + w) assert E(X) == l + w/2 assert variance(X).expand() == w**2/12 # With numbers all is well X = Uniform('x', 3, 5) assert P(X < 3) == 0 and P(X > 5) == 0 assert P(X < 4) == P(X > 4) == S.Half assert median(X) == FiniteSet(4) z = Symbol('z') p = density(X)(z) assert p.subs(z, 3.7) == S.Half assert p.subs(z, -1) == 0 assert p.subs(z, 6) == 0 c = cdf(X) assert c(2) == 0 and c(3) == 0 assert c(Rational(7, 2)) == Rational(1, 4) assert c(5) == 1 and c(6) == 1 @XFAIL @slow def test_uniform_P(): """ This stopped working because SingleContinuousPSpace.compute_density no longer calls integrate on a DiracDelta but rather just solves directly. integrate used to call UniformDistribution.expectation which special-cased subsed out the Min and Max terms that Uniform produces I decided to regress on this class for general cleanliness (and I suspect speed) of the algorithm. """ l = Symbol('l', real=True) w = Symbol('w', positive=True) X = Uniform('x', l, l + w) assert P(X < l) == 0 and P(X > l + w) == 0 def test_uniformsum(): n = Symbol("n", integer=True) _k = Dummy("k") x = Symbol("x") X = UniformSum('x', n) res = Sum((-1)**_k*(-_k + x)**(n - 1)*binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1) assert density(X)(x).dummy_eq(res) #Tests set functions assert X.pspace.domain.set == Interval(0, n) #Tests the characteristic_function assert characteristic_function(X)(x) == (-I*(exp(I*x) - 1)/x)**n #Tests the moment_generating_function assert moment_generating_function(X)(x) == ((exp(x) - 1)/x)**n def test_von_mises(): mu = Symbol("mu") k = Symbol("k", positive=True) X = VonMises("x", mu, k) assert density(X)(x) == exp(k*cos(x - mu))/(2*pi*besseli(0, k)) def test_weibull(): a, b = symbols('a b', positive=True) # FIXME: simplify(E(X)) seems to hang without extended_positive=True # On a Linux machine this had a rapid memory leak... # a, b = symbols('a b', positive=True) X = Weibull('x', a, b) assert E(X).expand() == a * gamma(1 + 1/b) assert variance(X).expand() == (a**2 * gamma(1 + 2/b) - E(X)**2).expand() assert simplify(skewness(X)) == (2*gamma(1 + 1/b)**3 - 3*gamma(1 + 1/b)*gamma(1 + 2/b) + gamma(1 + 3/b))/(-gamma(1 + 1/b)**2 + gamma(1 + 2/b))**Rational(3, 2) assert simplify(kurtosis(X)) == (-3*gamma(1 + 1/b)**4 +\ 6*gamma(1 + 1/b)**2*gamma(1 + 2/b) - 4*gamma(1 + 1/b)*gamma(1 + 3/b) + gamma(1 + 4/b))/(gamma(1 + 1/b)**2 - gamma(1 + 2/b))**2 def test_weibull_numeric(): # Test for integers and rationals a = 1 bvals = [S.Half, 1, Rational(3, 2), 5] for b in bvals: X = Weibull('x', a, b) assert simplify(E(X)) == expand_func(a * gamma(1 + 1/S(b))) assert simplify(variance(X)) == simplify( a**2 * gamma(1 + 2/S(b)) - E(X)**2) # Not testing Skew... it's slow with int/frac values > 3/2 def test_wignersemicircle(): R = Symbol("R", positive=True) X = WignerSemicircle('x', R) assert pspace(X).domain.set == Interval(-R, R) assert density(X)(x) == 2*sqrt(-x**2 + R**2)/(pi*R**2) assert E(X) == 0 #Tests ChiNoncentralDistribution assert characteristic_function(X)(x) == \ Piecewise((2*besselj(1, R*x)/(R*x), Ne(x, 0)), (1, True)) def test_input_value_assertions(): a, b = symbols('a b') p, q = symbols('p q', positive=True) m, n = symbols('m n', positive=False, real=True) raises(ValueError, lambda: Normal('x', 3, 0)) raises(ValueError, lambda: Normal('x', m, n)) Normal('X', a, p) # No error raised raises(ValueError, lambda: Exponential('x', m)) Exponential('Ex', p) # No error raised for fn in [Pareto, Weibull, Beta, Gamma]: raises(ValueError, lambda: fn('x', m, p)) raises(ValueError, lambda: fn('x', p, n)) fn('x', p, q) # No error raised def test_unevaluated(): X = Normal('x', 0, 1) k = Dummy('k') expr1 = Integral(sqrt(2)*k*exp(-k**2/2)/(2*sqrt(pi)), (k, -oo, oo)) expr2 = Integral(sqrt(2)*exp(-k**2/2)/(2*sqrt(pi)), (k, 0, oo)) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert E(X, evaluate=False).rewrite(Integral).dummy_eq(expr1) assert E(X + 1, evaluate=False).rewrite(Integral).dummy_eq(expr1 + 1) assert P(X > 0, evaluate=False).rewrite(Integral).dummy_eq(expr2) assert P(X > 0, X**2 < 1) == S.Half def test_probability_unevaluated(): T = Normal('T', 30, 3) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert type(P(T > 33, evaluate=False)) == Probability def test_density_unevaluated(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 2) assert isinstance(density(X+Y, evaluate=False)(z), Integral) def test_NormalDistribution(): nd = NormalDistribution(0, 1) x = Symbol('x') assert nd.cdf(x) == erf(sqrt(2)*x/2)/2 + S.Half assert nd.expectation(1, x) == 1 assert nd.expectation(x, x) == 0 assert nd.expectation(x**2, x) == 1 #Test issue 10076 a = SingleContinuousPSpace(x, NormalDistribution(2, 4)) _z = Dummy('_z') expected1 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, -oo, 1)) assert a.probability(x < 1, evaluate=False).dummy_eq(expected1) is True expected2 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, 1, oo)) assert a.probability(x > 1, evaluate=False).dummy_eq(expected2) is True b = SingleContinuousPSpace(x, NormalDistribution(1, 9)) expected3 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, 6, oo)) assert b.probability(x > 6, evaluate=False).dummy_eq(expected3) is True expected4 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, -oo, 6)) assert b.probability(x < 6, evaluate=False).dummy_eq(expected4) is True def test_random_parameters(): mu = Normal('mu', 2, 3) meas = Normal('T', mu, 1) assert density(meas, evaluate=False)(z) assert isinstance(pspace(meas), CompoundPSpace) X = Normal('x', [1, 2], [[1, 0], [0, 1]]) assert isinstance(pspace(X).distribution, MultivariateNormalDistribution) assert density(meas)(z).simplify() == sqrt(5)*exp(-z**2/20 + z/5 - S(1)/5)/(10*sqrt(pi)) def test_random_parameters_given(): mu = Normal('mu', 2, 3) meas = Normal('T', mu, 1) assert given(meas, Eq(mu, 5)) == Normal('T', 5, 1) def test_conjugate_priors(): mu = Normal('mu', 2, 3) x = Normal('x', mu, 1) assert isinstance(simplify(density(mu, Eq(x, y), evaluate=False)(z)), Mul) def test_difficult_univariate(): """ Since using solve in place of deltaintegrate we're able to perform substantially more complex density computations on single continuous random variables """ x = Normal('x', 0, 1) assert density(x**3) assert density(exp(x**2)) assert density(log(x)) def test_issue_10003(): X = Exponential('x', 3) G = Gamma('g', 1, 2) assert P(X < -1) is S.Zero assert P(G < -1) is S.Zero def test_precomputed_cdf(): x = symbols("x", real=True) mu = symbols("mu", real=True) sigma, xm, alpha = symbols("sigma xm alpha", positive=True) n = symbols("n", integer=True, positive=True) distribs = [ Normal("X", mu, sigma), Pareto("P", xm, alpha), ChiSquared("C", n), Exponential("E", sigma), # LogNormal("L", mu, sigma), ] for X in distribs: compdiff = cdf(X)(x) - simplify(X.pspace.density.compute_cdf()(x)) compdiff = simplify(compdiff.rewrite(erfc)) assert compdiff == 0 @slow def test_precomputed_characteristic_functions(): import mpmath def test_cf(dist, support_lower_limit, support_upper_limit): pdf = density(dist) t = Symbol('t') # first function is the hardcoded CF of the distribution cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath') # second function is the Fourier transform of the density function f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath') cf2 = lambda t: mpmath.quad(lambda x: f(x, t), [support_lower_limit, support_upper_limit], maxdegree=10) # compare the two functions at various points for test_point in [2, 5, 8, 11]: n1 = cf1(test_point) n2 = cf2(test_point) assert abs(re(n1) - re(n2)) < 1e-12 assert abs(im(n1) - im(n2)) < 1e-12 test_cf(Beta('b', 1, 2), 0, 1) test_cf(Chi('c', 3), 0, mpmath.inf) test_cf(ChiSquared('c', 2), 0, mpmath.inf) test_cf(Exponential('e', 6), 0, mpmath.inf) test_cf(Logistic('l', 1, 2), -mpmath.inf, mpmath.inf) test_cf(Normal('n', -1, 5), -mpmath.inf, mpmath.inf) test_cf(RaisedCosine('r', 3, 1), 2, 4) test_cf(Rayleigh('r', 0.5), 0, mpmath.inf) test_cf(Uniform('u', -1, 1), -1, 1) test_cf(WignerSemicircle('w', 3), -3, 3) def test_long_precomputed_cdf(): x = symbols("x", real=True) distribs = [ Arcsin("A", -5, 9), Dagum("D", 4, 10, 3), Erlang("E", 14, 5), Frechet("F", 2, 6, -3), Gamma("G", 2, 7), GammaInverse("GI", 3, 5), Kumaraswamy("K", 6, 8), Laplace("LA", -5, 4), Logistic("L", -6, 7), Nakagami("N", 2, 7), StudentT("S", 4) ] for distr in distribs: for _ in range(5): assert tn(diff(cdf(distr)(x), x), density(distr)(x), x, a=0, b=0, c=1, d=0) US = UniformSum("US", 5) pdf01 = density(US)(x).subs(floor(x), 0).doit() # pdf on (0, 1) cdf01 = cdf(US, evaluate=False)(x).subs(floor(x), 0).doit() # cdf on (0, 1) assert tn(diff(cdf01, x), pdf01, x, a=0, b=0, c=1, d=0) def test_issue_13324(): X = Uniform('X', 0, 1) assert E(X, X > S.Half) == Rational(3, 4) assert E(X, X > 0) == S.Half def test_issue_20756(): X = Uniform('X', -1, +1) Y = Uniform('Y', -1, +1) assert E(X * Y) == S.Zero assert E(X * ((Y + 1) - 1)) == S.Zero assert E(Y * (X*(X + 1) - X*X)) == S.Zero def test_FiniteSet_prob(): E = Exponential('E', 3) N = Normal('N', 5, 7) assert P(Eq(E, 1)) is S.Zero assert P(Eq(N, 2)) is S.Zero assert P(Eq(N, x)) is S.Zero def test_prob_neq(): E = Exponential('E', 4) X = ChiSquared('X', 4) assert P(Ne(E, 2)) == 1 assert P(Ne(X, 4)) == 1 assert P(Ne(X, 4)) == 1 assert P(Ne(X, 5)) == 1 assert P(Ne(E, x)) == 1 def test_union(): N = Normal('N', 3, 2) assert simplify(P(N**2 - N > 2)) == \ -erf(sqrt(2))/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2) assert simplify(P(N**2 - 4 > 0)) == \ -erf(5*sqrt(2)/4)/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2) def test_Or(): N = Normal('N', 0, 1) assert simplify(P(Or(N > 2, N < 1))) == \ -erf(sqrt(2))/2 - erfc(sqrt(2)/2)/2 + Rational(3, 2) assert P(Or(N < 0, N < 1)) == P(N < 1) assert P(Or(N > 0, N < 0)) == 1 def test_conditional_eq(): E = Exponential('E', 1) assert P(Eq(E, 1), Eq(E, 1)) == 1 assert P(Eq(E, 1), Eq(E, 2)) == 0 assert P(E > 1, Eq(E, 2)) == 1 assert P(E < 1, Eq(E, 2)) == 0 def test_ContinuousDistributionHandmade(): x = Symbol('x') z = Dummy('z') dens = Lambda(x, Piecewise((S.Half, (0<=x)&(x<1)), (0, (x>=1)&(x<2)), (S.Half, (x>=2)&(x<3)), (0, True))) dens = ContinuousDistributionHandmade(dens, set=Interval(0, 3)) space = SingleContinuousPSpace(z, dens) assert dens.pdf == Lambda(x, Piecewise((S(1)/2, (x >= 0) & (x < 1)), (0, (x >= 1) & (x < 2)), (S(1)/2, (x >= 2) & (x < 3)), (0, True))) assert median(space.value) == Interval(1, 2) assert E(space.value) == Rational(3, 2) assert variance(space.value) == Rational(13, 12) def test_issue_16318(): # test compute_expectation function of the SingleContinuousDomain N = SingleContinuousDomain(x, Interval(0, 1)) raises(ValueError, lambda: SingleContinuousDomain.compute_expectation(N, x+1, {x, y}))
f696bed55e417529d0491c84225c4a856bb434ab7af16a4add5ed46a138de85e
"""Tests for Gosper's algorithm for hypergeometric summation. """ from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.gamma_functions import gamma from sympy.polys.polytools import Poly from sympy.simplify.simplify import simplify from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term from sympy.abc import a, b, j, k, m, n, r, x def test_gosper_normal(): eq = 4*n + 5, 2*(4*n + 1)*(2*n + 3), n assert gosper_normal(*eq) == \ (Poly(Rational(1, 4), n), Poly(n + Rational(3, 2)), Poly(n + Rational(1, 4))) assert gosper_normal(*eq, polys=False) == \ (Rational(1, 4), n + Rational(3, 2), n + Rational(1, 4)) def test_gosper_term(): assert gosper_term((4*k + 1)*factorial( k)/factorial(2*k + 1), k) == (-k - S.Half)/(k + Rational(1, 4)) def test_gosper_sum(): assert gosper_sum(1, (k, 0, n)) == 1 + n assert gosper_sum(k, (k, 0, n)) == n*(1 + n)/2 assert gosper_sum(k**2, (k, 0, n)) == n*(1 + n)*(1 + 2*n)/6 assert gosper_sum(k**3, (k, 0, n)) == n**2*(1 + n)**2/4 assert gosper_sum(2**k, (k, 0, n)) == 2*2**n - 1 assert gosper_sum(factorial(k), (k, 0, n)) is None assert gosper_sum(binomial(n, k), (k, 0, n)) is None assert gosper_sum(factorial(k)/k**2, (k, 0, n)) is None assert gosper_sum((k - 3)*factorial(k), (k, 0, n)) is None assert gosper_sum(k*factorial(k), k) == factorial(k) assert gosper_sum( k*factorial(k), (k, 0, n)) == n*factorial(n) + factorial(n) - 1 assert gosper_sum((-1)**k*binomial(n, k), (k, 0, n)) == 0 assert gosper_sum(( -1)**k*binomial(n, k), (k, 0, m)) == -(-1)**m*(m - n)*binomial(n, m)/n assert gosper_sum((4*k + 1)*factorial(k)/factorial(2*k + 1), (k, 0, n)) == \ (2*factorial(2*n + 1) - factorial(n))/factorial(2*n + 1) # issue 6033: assert gosper_sum( n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)), \ (n, 0, m)).simplify() == -(a*b)**m*gamma(a + 1) \ *gamma(b + 1)/(gamma(a)*gamma(b)*gamma(a + m + 1)*gamma(b + m + 1)) \ + 1/(gamma(a)*gamma(b)) def test_gosper_sum_indefinite(): assert gosper_sum(k, k) == k*(k - 1)/2 assert gosper_sum(k**2, k) == k*(k - 1)*(2*k - 1)/6 assert gosper_sum(1/(k*(k + 1)), k) == -1/k assert gosper_sum(-(27*k**4 + 158*k**3 + 430*k**2 + 678*k + 445)*gamma(2*k + 4)/(3*(3*k + 7)*gamma(3*k + 6)), k) == \ (3*k + 5)*(k**2 + 2*k + 5)*gamma(2*k + 4)/gamma(3*k + 6) def test_gosper_sum_parametric(): assert gosper_sum(binomial(S.Half, m - j + 1)*binomial(S.Half, m + j), (j, 1, n)) == \ n*(1 + m - n)*(-1 + 2*m + 2*n)*binomial(S.Half, 1 + m - n)* \ binomial(S.Half, m + n)/(m*(1 + 2*m)) def test_gosper_sum_algebraic(): assert gosper_sum( n**2 + sqrt(2), (n, 0, m)) == (m + 1)*(2*m**2 + m + 6*sqrt(2))/6 def test_gosper_sum_iterated(): f1 = binomial(2*k, k)/4**k f2 = (1 + 2*n)*binomial(2*n, n)/4**n f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n) f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n) f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*binomial(2*n, n)/(105*4**n) assert gosper_sum(f1, (k, 0, n)) == f2 assert gosper_sum(f2, (n, 0, n)) == f3 assert gosper_sum(f3, (n, 0, n)) == f4 assert gosper_sum(f4, (n, 0, n)) == f5 # the AeqB tests test expressions given in # www.math.upenn.edu/~wilf/AeqB.pdf def test_gosper_sum_AeqB_part1(): f1a = n**4 f1b = n**3*2**n f1c = 1/(n**2 + sqrt(5)*n - 1) f1d = n**4*4**n/binomial(2*n, n) f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n) f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n)) f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n)) f1h = n*factorial(n - S.Half)**2/factorial(n + 1)**2 g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30 g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13) g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - ( 3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + 5*m**2 - 1)/6 g1d = Rational(-2, 231) + 2*4**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 - 22*m + 3)/(693*binomial(2*m, m)) g1e = Rational(-9, 2) + (81*m**2 + 261*m + 200)*factorial( 3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2)) g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1)) g1g = -binomial(2*m, m)**2/4**(2*m) g1h = 4*pi -(2*m + 1)**2*(3*m + 4)*factorial(m - S.Half)**2/factorial(m + 1)**2 g = gosper_sum(f1a, (n, 0, m)) assert g is not None and simplify(g - g1a) == 0 g = gosper_sum(f1b, (n, 0, m)) assert g is not None and simplify(g - g1b) == 0 g = gosper_sum(f1c, (n, 0, m)) assert g is not None and simplify(g - g1c) == 0 g = gosper_sum(f1d, (n, 0, m)) assert g is not None and simplify(g - g1d) == 0 g = gosper_sum(f1e, (n, 0, m)) assert g is not None and simplify(g - g1e) == 0 g = gosper_sum(f1f, (n, 0, m)) assert g is not None and simplify(g - g1f) == 0 g = gosper_sum(f1g, (n, 0, m)) assert g is not None and simplify(g - g1g) == 0 g = gosper_sum(f1h, (n, 0, m)) # need to call rewrite(gamma) here because we have terms involving # factorial(1/2) assert g is not None and simplify(g - g1h).rewrite(gamma) == 0 def test_gosper_sum_AeqB_part2(): f2a = n**2*a**n f2b = (n - r/2)*binomial(r, n) f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x)) g2a = -a*(a + 1)/(a - 1)**3 + a**( m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3 g2b = (m - r)*binomial(r, m)/2 ff = factorial(1 - x)*factorial(1 + x) g2c = 1/ff*( 1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x)) g = gosper_sum(f2a, (n, 0, m)) assert g is not None and simplify(g - g2a) == 0 g = gosper_sum(f2b, (n, 0, m)) assert g is not None and simplify(g - g2b) == 0 g = gosper_sum(f2c, (n, 1, m)) assert g is not None and simplify(g - g2c) == 0 def test_gosper_nan(): a = Symbol('a', positive=True) b = Symbol('b', positive=True) n = Symbol('n', integer=True) m = Symbol('m', integer=True) f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)) g2d = 1/(factorial(a - 1)*factorial( b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m)) g = gosper_sum(f2d, (n, 0, m)) assert simplify(g - g2d) == 0 def test_gosper_sum_AeqB_part3(): f3a = 1/n**4 f3b = (6*n + 3)/(4*n**4 + 8*n**3 + 8*n**2 + 4*n + 3) f3c = 2**n*(n**2 - 2*n - 1)/(n**2*(n + 1)**2) f3d = n**2*4**n/((n + 1)*(n + 2)) f3e = 2**n/(n + 1) f3f = 4*(n - 1)*(n**2 - 2*n - 1)/(n**2*(n + 1)**2*(n - 2)**2*(n - 3)**2) f3g = (n**4 - 14*n**2 - 24*n - 9)*2**n/(n**2*(n + 1)**2*(n + 2)**2* (n + 3)**2) # g3a -> no closed form g3b = m*(m + 2)/(2*m**2 + 4*m + 3) g3c = 2**m/m**2 - 2 g3d = Rational(2, 3) + 4**(m + 1)*(m - 1)/(m + 2)/3 # g3e -> no closed form g3f = -(Rational(-1, 16) + 1/((m - 2)**2*(m + 1)**2)) # the AeqB key is wrong g3g = Rational(-2, 9) + 2**(m + 1)/((m + 1)**2*(m + 3)**2) g = gosper_sum(f3a, (n, 1, m)) assert g is None g = gosper_sum(f3b, (n, 1, m)) assert g is not None and simplify(g - g3b) == 0 g = gosper_sum(f3c, (n, 1, m - 1)) assert g is not None and simplify(g - g3c) == 0 g = gosper_sum(f3d, (n, 1, m)) assert g is not None and simplify(g - g3d) == 0 g = gosper_sum(f3e, (n, 0, m - 1)) assert g is None g = gosper_sum(f3f, (n, 4, m)) assert g is not None and simplify(g - g3f) == 0 g = gosper_sum(f3g, (n, 1, m)) assert g is not None and simplify(g - g3g) == 0
257a956d2c5996532a9b38459260ac9ad7cf3be55734bfe9e88fc68a8fbe4beb
from sympy.concrete.products import (Product, product) from sympy.concrete.summations import (Sum, summation) from sympy.core.function import (Derivative, Function) from sympy.core.mul import prod from sympy.core import (Catalan, EulerGamma) from sympy.core.numbers import (E, I, Rational, nan, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) from sympy.functions.combinatorial.numbers import harmonic from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (sinh, tanh) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.gamma_functions import (gamma, lowergamma) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And, Or from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import Identity from sympy.sets.fancysets import Range from sympy.sets.sets import Interval from sympy.simplify.combsimp import combsimp from sympy.simplify.simplify import simplify from sympy.tensor.indexed import (Idx, Indexed, IndexedBase) from sympy.concrete.summations import ( telescopic, _dummy_with_inherited_properties_concrete, eval_sum_residue) from sympy.concrete.expr_with_intlimits import ReorderError from sympy.core.facts import InconsistentAssumptions from sympy.testing.pytest import XFAIL, raises, slow from sympy.matrices import (Matrix, SparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix) from sympy.core.mod import Mod from sympy.abc import a, b, c, d, k, m, x, y, z n = Symbol('n', integer=True) f, g = symbols('f g', cls=Function) def test_karr_convention(): # Test the Karr summation convention that we want to hold. # See his paper "Summation in Finite Terms" for a detailed # reasoning why we really want exactly this definition. # The convention is described on page 309 and essentially # in section 1.4, definition 3: # # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n # \sum_{m <= i < n} f(i) = 0 for m = n # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n # # It is important to note that he defines all sums with # the upper limit being *exclusive*. # In contrast, SymPy and the usual mathematical notation has: # # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b) # # with the upper limit *inclusive*. So translating between # the two we find that: # # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i) # # where we intentionally used two different ways to typeset the # sum and its limits. i = Symbol("i", integer=True) k = Symbol("k", integer=True) j = Symbol("j", integer=True) # A simple example with a concrete summand and symbolic limits. # The normal sum: m = k and n = k + j and therefore m < n: m = k n = k + j a = m b = n - 1 S1 = Sum(i**2, (i, a, b)).doit() # The reversed sum: m = k + j and n = k and therefore m > n: m = k + j n = k a = m b = n - 1 S2 = Sum(i**2, (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum: m = k and n = k and therefore m = n: m = k n = k a = m b = n - 1 Sz = Sum(i**2, (i, a, b)).doit() assert Sz == 0 # Another example this time with an unspecified summand and # numeric limits. (We can not do both tests in the same example.) # The normal sum with m < n: m = 2 n = 11 a = m b = n - 1 S1 = Sum(f(i), (i, a, b)).doit() # The reversed sum with m > n: m = 11 n = 2 a = m b = n - 1 S2 = Sum(f(i), (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum with m = n: m = 5 n = 5 a = m b = n - 1 Sz = Sum(f(i), (i, a, b)).doit() assert Sz == 0 e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True)) s = Sum(e, (i, 0, 11)) assert s.n(3) == s.doit().n(3) def test_karr_proposition_2a(): # Test Karr, page 309, proposition 2, part a i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) def test_the_sum(m, n): # g g = i**3 + 2*i**2 - 3*i # f = Delta g f = simplify(g.subs(i, i+1) - g) # The sum a = m b = n - 1 S = Sum(f, (i, a, b)).doit() # Test if Sum_{m <= i < n} f(i) = g(n) - g(m) assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0 # m < n test_the_sum(u, u+v) # m = n test_the_sum(u, u ) # m > n test_the_sum(u+v, u ) def test_karr_proposition_2b(): # Test Karr, page 309, proposition 2, part b i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) w = Symbol("w", integer=True) def test_the_sum(l, n, m): # Summand s = i**3 # First sum a = l b = n - 1 S1 = Sum(s, (i, a, b)).doit() # Second sum a = l b = m - 1 S2 = Sum(s, (i, a, b)).doit() # Third sum a = m b = n - 1 S3 = Sum(s, (i, a, b)).doit() # Test if S1 = S2 + S3 as required assert S1 - (S2 + S3) == 0 # l < m < n test_the_sum(u, u+v, u+v+w) # l < m = n test_the_sum(u, u+v, u+v ) # l < m > n test_the_sum(u, u+v+w, v ) # l = m < n test_the_sum(u, u, u+v ) # l = m = n test_the_sum(u, u, u ) # l = m > n test_the_sum(u+v, u+v, u ) # l > m < n test_the_sum(u+v, u, u+w ) # l > m = n test_the_sum(u+v, u, u ) # l > m > n test_the_sum(u+v+w, u+v, u ) def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b - a + 1 assert Sum(S.NaN, (n, a, b)) is S.NaN assert Sum(x, (n, a, a)).doit() == x assert Sum(x, (x, a, a)).doit() == a assert Sum(x, (n, 1, a)).doit() == a*x assert Sum(x, (x, Range(1, 11))).doit() == 55 assert Sum(x, (x, Range(1, 11, 2))).doit() == 25 assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2))) lo, hi = 1, 2 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 3 and s2.doit() == 0 lo, hi = x, x + 1 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 2*x + 1 and s2.doit() == 0 assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \ y**2 + 2 assert summation(1, (n, 1, 10)) == 10 assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000 assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2 assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1) assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2) assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum) assert summation(k, (k, 0, oo)) is oo assert summation(k, (k, Range(1, 11))) == 55 def test_polynomial_sums(): assert summation(n**2, (n, 3, 8)) == 199 assert summation(n, (n, a, b)) == \ ((a + b)*(b - a + 1)/2).expand() assert summation(n**2, (n, 1, b)) == \ ((2*b**3 + 3*b**2 + b)/6).expand() assert summation(n**3, (n, 1, b)) == \ ((b**4 + 2*b**3 + b**2)/4).expand() assert summation(n**6, (n, 1, b)) == \ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand() def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1 assert summation(S.Half**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1 assert summation(2**n, (n, 1, oo)) is oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54) assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15) assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1) # issue 6664: assert summation(x**n, (n, 0, oo)) == \ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True)) assert summation(-2**n, (n, 0, oo)) is -oo assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo)) # issue 6802: assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1 assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3) assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half assert summation(y**x, (x, a, b)) == \ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True)) assert summation((-2)**(y*x + 2), (x, 0, n)) == \ 4*Piecewise((n + 1, Eq((-2)**y, 1)), ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True)) # issue 8251: assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo #issue 9908: assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2)) #issue 11642: result = Sum(0.5**n, (n, 1, oo)).doit() assert result == 1 assert result.is_Float result = Sum(0.25**n, (n, 1, oo)).doit() assert result == 1/3. assert result.is_Float result = Sum(0.99999**n, (n, 1, oo)).doit() assert result == 99999 assert result.is_Float result = Sum(S.Half**n, (n, 1, oo)).doit() assert result == 1 assert not result.is_Float result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit() assert result == Rational(3, 2) assert not result.is_Float assert Sum(1.0**n, (n, 1, oo)).doit() is oo assert Sum(2.43**n, (n, 1, oo)).doit() is oo # Issue 13979 i, k, q = symbols('i k q', integer=True) result = summation( exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1) ) assert result.simplify() == Piecewise( (1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True) ) def test_harmonic_sums(): assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n)) assert summation(1/k, (k, 1, n)) == harmonic(n) assert summation(n/k, (k, 1, n)) == n*harmonic(n) assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4) def test_composite_sums(): f = S.Half*(7 - 6*n + Rational(1, 7)*n**3) s = summation(f, (n, a, b)) assert not isinstance(s, Sum) A = 0 for i in range(-3, 5): A += f.subs(n, i) B = s.subs(a, -3).subs(b, 4) assert A == B def test_hypergeometric_sums(): assert summation( binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5) def test_other_sums(): f = m**2 + m*exp(m) g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5 assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10) fac = factorial def NS(e, n=15, **options): return str(sympify(e).evalf(n, **options)) def test_evalf_fast_series(): # Euler transformed series for sqrt(1+x) assert NS(Sum( fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100) # Some series for exp(1) estr = NS(E, 100) assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr pistr = NS(pi, 100) # Ramanujan series for pi assert NS(9801/sqrt(8)/Sum(fac( 4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr assert NS(1/Sum( binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr # Machin's formula for pi assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) - 4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr # Apery's constant astr = NS(zeta(3), 100) P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \ n + 12463 assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac( n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 / fac(2*n + 1)**5, (n, 0, oo)), 100) == astr def test_evalf_fast_series_issue_4021(): # Catalan's constant assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3* fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \ NS(Catalan, 100) astr = NS(zeta(3), 100) assert NS(5*Sum( (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1) **3 / fac(3*n), (n, 1, oo))/4, 100) == astr def test_evalf_slow_series(): assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15) assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50) assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15) assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100) assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50) def test_evalf_oo_to_oo(): # There used to be an error in certain cases # Does not evaluate, but at least do not throw an error # Evaluates symbolically to 0, which is not correct assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo)) # This evaluates if from 1 to oo and symbolically assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1)) def test_euler_maclaurin(): # Exact polynomial sums with E-M def check_exact(f, a, b, m, n): A = Sum(f, (k, a, b)) s, e = A.euler_maclaurin(m, n) assert (e == 0) and (s.expand() == A.doit()) check_exact(k**4, a, b, 0, 2) check_exact(k**4 + 2*k, a, b, 1, 2) check_exact(k**4 + k**2, a, b, 1, 5) check_exact(k**5, 2, 6, 1, 2) check_exact(k**5, 2, 6, 1, 3) assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0) # Not exact assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0 # Numerical test for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]: A = Sum(1/k**3, (k, 1, oo)) s, e = A.euler_maclaurin(mi, ni) assert abs((s - zeta(3)).evalf()) < e.evalf() raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin()) @slow def test_evalf_euler_maclaurin(): assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266' assert NS(Sum(1/k**k, (k, 1, oo)), 50) == '1.2912859970626635404072825905956005414986193682745' assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15) assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50) assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844' assert NS(Sum(log(k)/k**2, (k, 1, oo)), 50) == '0.93754825431584375370257409456786497789786028861483' assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008' assert NS(Sum(1/k, (k, 1000000, 2000000)), 50) == '0.69314793056000780941723211364567656807940638436025' def test_evalf_symbolic(): # issue 6328 expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3)) assert expr.evalf() == expr def test_evalf_issue_3273(): assert Sum(0, (k, 1, oo)).evalf() == 0 def test_simple_products(): assert Product(S.NaN, (x, 1, 3)) is S.NaN assert product(S.NaN, (x, 1, 3)) is S.NaN assert Product(x, (n, a, a)).doit() == x assert Product(x, (x, a, a)).doit() == a assert Product(x, (y, 1, a)).doit() == x**a lo, hi = 1, 2 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == 2 assert s2.doit() == 1 lo, hi = x, x + 1 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) s3 = 1 / Product(n, (n, hi + 1, lo - 1)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == x*(x + 1) assert s2.doit() == 1 assert s3.doit() == x*(x + 1) assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \ (y**2 + 1)*(y**2 + 3) assert product(2, (n, a, b)) == 2**(b - a + 1) assert product(n, (n, 1, b)) == factorial(b) assert product(n**3, (n, 1, b)) == factorial(b)**3 assert product(3**(2 + n), (n, a, b)) \ == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2) assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5) assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2) assert isinstance(product(cos(n), (n, x, x + S.Half)), Product) # If Product managed to evaluate this one, it most likely got it wrong! assert isinstance(Product(n**n, (n, 1, b)), Product) def test_rational_products(): assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a) assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1)) assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \ a*gamma(a + 2)/(b + 1)/gamma(b + 3) assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \ b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2)) def test_wallis_product(): # Wallis product, given in two different forms to ensure that Product # can factor simple rational expressions A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b)) B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b)) R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2))) assert simplify(A.doit()) == R assert simplify(B.doit()) == R # This one should eventually also be doable (Euler's product formula for sin) # assert Product(1+x/n**2, (n, 1, b)) == ... def test_telescopic_sums(): #checks also input 2 of comment 1 issue 4127 assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n) assert Sum( f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m) assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \ cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3) # dummy variable shouldn't matter assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \ telescopic(1/k, -k/(1 + k), (k, n - 1, n)) assert Sum(1/x/(x - 1), (x, a, b)).doit() == 1/(a - 1) - 1/b eq = 1/((5*n + 2)*(5*(n + 1) + 2)) assert Sum(eq, (n, 0, oo)).doit() == S(1)/10 nz = symbols('nz', nonzero=True) v = Sum(eq.subs(5, nz), (n, 0, oo)).doit() assert v.subs(nz, 5).simplify() == S(1)/10 # check that apart is being used in non-symbolic case s = Sum(eq, (n, 0, k)).doit() v = Sum(eq, (n, 0, 10**100)).doit() assert v == s.subs(k, 10**100) def test_sum_reconstruct(): s = Sum(n**2, (n, -1, 1)) assert s == Sum(*s.args) raises(ValueError, lambda: Sum(x, x)) raises(ValueError, lambda: Sum(x, (x, 1))) def test_limit_subs(): for F in (Sum, Product, Integral): assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2) assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \ F(a, (a, c, 4)) assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1)) def test_function_subs(): S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) assert S.subs(f(x),x) == S raises(ValueError, lambda: S.subs(f(y),x+y) ) S = Sum(x*log(y),(x,0,oo),(y,0,oo)) assert S.subs(log(y),y) == S S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) def test_equality(): # if this fails remove special handling below raises(ValueError, lambda: Sum(x, x)) r = symbols('x', real=True) for F in (Sum, Product, Integral): try: assert F(x, x) != F(y, y) assert F(x, (x, 1, 2)) != F(x, x) assert F(x, (x, x)) != F(x, x) # or else they print the same assert F(1, x) != F(1, y) except ValueError: pass assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit assert F(a, (x, 1, x)) != F(a, (y, 1, y)) assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x))) # issue 5265 assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a)) def test_Sum_doit(): assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3 assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \ 3*Integral(a**2) assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2) # test nested sum evaluation s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n)) assert 0 == (s.doit() - n*(n+1)*(n-1)).factor() # Integer assumes finite assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True)) assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1 assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True)) assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3 assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \ 3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True)) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \ f(1) + f(2) + f(3) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \ Sum(f(n), (n, 1, oo)) # issue 2597 nmax = symbols('N', integer=True, positive=True) pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True)) assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n), (0, True)), (n, 1, nmax)) q, s = symbols('q, s') assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1), (Sum(n**(-2*s), (n, 1, oo)), True)) assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1), (Sum((n + 1)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise( (zeta(s, q), And(q > 0, s > 1)), (Sum((n + q)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise( (zeta(s, 2*q), And(2*q > 0, s > 1)), (Sum((n + q)**(-s), (n, q, oo)), True)) assert summation(1/n**2, (n, 1, oo)) == zeta(2) assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo)) def test_Product_doit(): assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9 assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \ 6*Integral(a**2)**3 assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3 def test_Sum_interface(): assert isinstance(Sum(0, (n, 0, 2)), Sum) assert Sum(nan, (n, 0, 2)) is nan assert Sum(nan, (n, 0, oo)) is nan assert Sum(0, (n, 0, 2)).doit() == 0 assert isinstance(Sum(0, (n, 0, oo)), Sum) assert Sum(0, (n, 0, oo)).doit() == 0 raises(ValueError, lambda: Sum(1)) raises(ValueError, lambda: summation(1)) def test_diff(): assert Sum(x, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2)) e = Sum(x*y, (x, 1, a)) assert e.diff(a) == Derivative(e, a) assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \ Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24 assert Sum(x, (x, 1, 2)).diff(y) == 0 def test_hypersum(): assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m def test_issue_4170(): assert summation(1/factorial(k), (k, 0, oo)) == E def test_is_commutative(): from sympy.physics.secondquant import NO, F, Fd m = Symbol('m', commutative=False) for f in (Sum, Product, Integral): assert f(z, (z, 1, 1)).is_commutative is True assert f(z*y, (z, 1, 6)).is_commutative is True assert f(m*x, (x, 1, 2)).is_commutative is False assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False def test_is_zero(): for func in [Sum, Product]: assert func(0, (x, 1, 1)).is_zero is True assert func(x, (x, 1, 1)).is_zero is None assert Sum(0, (x, 1, 0)).is_zero is True assert Product(0, (x, 1, 0)).is_zero is False def test_is_number(): # is number should not rely on evaluation or assumptions, # it should be equivalent to `not foo.free_symbols` assert Sum(1, (x, 1, 1)).is_number is True assert Sum(1, (x, 1, x)).is_number is False assert Sum(0, (x, y, z)).is_number is False assert Sum(x, (y, 1, 2)).is_number is False assert Sum(x, (y, 1, 1)).is_number is False assert Sum(x, (x, 1, 2)).is_number is True assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Product(2, (x, 1, 1)).is_number is True assert Product(2, (x, 1, y)).is_number is False assert Product(0, (x, y, z)).is_number is False assert Product(1, (x, y, z)).is_number is False assert Product(x, (y, 1, x)).is_number is False assert Product(x, (y, 1, 2)).is_number is False assert Product(x, (y, 1, 1)).is_number is False assert Product(x, (x, 1, 2)).is_number is True def test_free_symbols(): for func in [Sum, Product]: assert func(1, (x, 1, 2)).free_symbols == set() assert func(0, (x, 1, y)).free_symbols == {y} assert func(2, (x, 1, y)).free_symbols == {y} assert func(x, (x, 1, 2)).free_symbols == set() assert func(x, (x, 1, y)).free_symbols == {y} assert func(x, (y, 1, y)).free_symbols == {x, y} assert func(x, (y, 1, 2)).free_symbols == {x} assert func(x, (y, 1, 1)).free_symbols == {x} assert func(x, (y, 1, z)).free_symbols == {x, z} assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set() assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z} assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y} assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z} assert Sum(1, (x, 1, y)).free_symbols == {y} # free_symbols answers whether the object *as written* has free symbols, # not whether the evaluated expression has free symbols assert Product(1, (x, 1, y)).free_symbols == {y} # don't count free symbols that are not independent of integration # variable(s) assert func(f(x), (f(x), 1, 2)).free_symbols == set() assert func(f(x), (f(x), 1, x)).free_symbols == {x} assert func(f(x), (f(x), 1, y)).free_symbols == {y} assert func(f(x), (z, 1, y)).free_symbols == {x, y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Sum(A*B**n, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() p = Sum(B**n*A, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_noncommutativity_honoured(): A, B = symbols("A B", commutative=False) M = symbols('M', integer=True, positive=True) p = Sum(A*B**n, (n, 1, M)) assert p.doit() == A*Piecewise((M, Eq(B, 1)), ((B - B**(M + 1))*(1 - B)**(-1), True)) p = Sum(B**n*A, (n, 1, M)) assert p.doit() == Piecewise((M, Eq(B, 1)), ((B - B**(M + 1))*(1 - B)**(-1), True))*A p = Sum(B**n*A*B**n, (n, 1, M)) assert p.doit() == p def test_issue_4171(): assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo assert summation(2*k + 1, (k, 0, oo)) is oo def test_issue_6273(): assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == 1 def test_issue_6274(): assert Sum(x, (x, 1, 0)).doit() == 0 assert NS(Sum(x, (x, 1, 0))) == '0' assert Sum(n, (n, 10, 5)).doit() == -30 assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000' def test_simplify_sum(): y, t, v = symbols('y, t, v') _simplify = lambda e: simplify(e, doit=False) assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \ Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k)) assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \ Sum(x, (x, n, a)) assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \ Sum(x, (x, n, a)) assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \ Sum(x, (x, n, a)) + Sum(1, (x, n, k)) assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \ 4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6)) assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \ Sum(x*(3*x + 1), (x, a, b)) assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \ 4 * y * Sum(z, (z, n, k))) + 1 == \ 4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1 assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \ 1 + Sum(x, (x, a, c)) assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \ Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \ Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \ _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c))) assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \ Sum(x, (x, a, b)) * Sum(x**2, (x, a, b)) assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \ == (x + y + z) * Sum(1, (t, a, b)) # issue 8596 assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \ Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596 assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \ (Sum(x, (x, a, b)) / 3) assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \ == Sum(f(x), (x, a, b)) assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0 assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b))) assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \ c * (y + 1) * Sum(x, (x, a, b)) assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum(x, (x, a, b), (y, a, b)) assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b)) assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \ c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b)) assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \ Sum(d * t, (x, b, c)), (t, a, b))) == \ d * Sum(1, (x, a, c)) * Sum(t, (t, a, b)) def test_change_index(): b, v, w = symbols('b, v, w', integer = True) assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \ Sum(y - 1, (y, a + 1, b + 1)) assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \ Sum((x+1)**2, (x, a - 1, b - 1)) assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \ Sum((-y)**2, (y, -b, -a)) assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \ Sum(-x - 1, (x, -b - 1, -a - 1)) assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \ Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d)) assert Sum(x, (x, a, b)).change_index( x, x + v) == \ Sum(-v + x, (x, a + v, b + v)) assert Sum(x, (x, a, b)).change_index( x, -x - v) == \ Sum(-v - x, (x, -b - v, -a - v)) assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \ Sum(v/w, (v, b*w, a*w)) raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x)) def test_reorder(): b, y, c, d, z = symbols('b, y, c, d, z', integer = True) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \ Sum(x*y, (y, c, d), (x, a, b)) assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \ Sum(x, (x, c, d), (x, a, b)) assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\ (2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b)) assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \ Sum(x*y, (y, c, d), (x, a, b)) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \ Sum(x*y, (y, c, d), (x, a, b)) def test_reverse_order(): assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1)) assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \ Sum(x*y, (x, 6, 0), (y, 7, -1)) assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0)) assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0)) assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0)) assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1)) assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \ Sum(-x, (x, a + 6, a)) assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \ Sum(-x, (x, a + 3, a)) assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \ Sum(-x, (x, a + 2, a)) assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1)) assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1)) assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) def test_issue_7097(): assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400)) def test_factor_expand_subs(): # test factoring assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y)) assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y)) assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y)) assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y)) # test expand assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y)) assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y)) assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand() \ == Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo)) assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \ == Sum(n*x**(n+1), (n, -1, oo)) + Sum(x**(n+1), (n, -1, oo)) assert Sum(a*n+a*n**2,(n,0,4)).expand() \ == Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4)) assert Sum(x**a*x**n,(x,0,3)) \ == Sum(x**(a+n),(x,0,3)).expand(power_exp=True) assert Sum(x**(a+n),(x,0,3)) \ == Sum(x**(a+n),(x,0,3)).expand(power_exp=False) # test subs assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3)) assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3)) assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10)) assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10)) assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10)) def test_distribution_over_equality(): assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3)) assert Sum(Eq(f(x), x**2), (x, 0, y)) == \ Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y))) def test_issue_2787(): n, k = symbols('n k', positive=True, integer=True) p = symbols('p', positive=True) binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k) s = Sum(binomial_dist*k, (k, 0, n)) res = s.doit().simplify() ans = Piecewise( (n*p, x), ((1 - p)**n*Sum(k*p**k*binomial(n, k)/(1 - p)**k, (k, 0, n)), True)) assert res == ans.subs(x, p/Abs(p - 1) <= 1) # Issue #17165: make sure that another simplify does not complicate # the result (but why didn't first simplify handle this?) assert res.simplify() == ans.subs(x, p <= S.Half) def test_issue_4668(): assert summation(1/n, (n, 2, oo)) is oo def test_matrix_sum(): A = Matrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result == Matrix([[0, 4], [6, 0]]) assert result.__class__ == ImmutableDenseMatrix A = SparseMatrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result.__class__ == ImmutableSparseMatrix def test_failing_matrix_sum(): n = Symbol('n') # TODO Implement matrix geometric series summation. A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]]) assert Sum(A ** n, (n, 1, 4)).doit() == \ Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) # issue sympy/sympy#16989 assert summation(A**n, (n, 1, 1)) == A def test_indexed_idx_sum(): i = symbols('i', cls=Idx) r = Indexed('r', i) assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)]) assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)]) j = symbols('j', integer=True) assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)]) assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)]) k = Idx('k', range=(1, 3)) A = IndexedBase('A') assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)]) assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)]) raises(ValueError, lambda: Sum(A[k], (k, 1, 4))) raises(ValueError, lambda: Sum(A[k], (k, 0, 3))) raises(ValueError, lambda: Sum(A[k], (k, 2, oo))) raises(ValueError, lambda: Product(A[k], (k, 1, 4))) raises(ValueError, lambda: Product(A[k], (k, 0, 3))) raises(ValueError, lambda: Product(A[k], (k, 2, oo))) @slow def test_is_convergent(): # divergence tests -- assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false # Raabe's test -- assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true # root test -- assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false # integral test -- # p-series test -- assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false # comparison test -- assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true # alternating series tests -- assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true # with -negativeInfinite Limits assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true # piecewise functions f = Piecewise((n**(-2), n <= 1), (n**2, n > 1)) assert Sum(f, (n, 1, oo)).is_convergent() is S.false assert Sum(f, (n, -oo, oo)).is_convergent() is S.false assert Sum(f, (n, 1, 100)).is_convergent() is S.true #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true # integral test assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true # the following function has maxima located at (x, y) = # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050) eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x) assert Sum(eq, (x, 1, oo)).is_convergent() is S.true assert Sum(eq, (x, 1, 2)).is_convergent() is S.true assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false # issue 19545 assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true # issue 19836 assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true def test_is_absolutely_convergent(): assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true @XFAIL def test_convergent_failing(): # dirichlet tests assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true def test_issue_6966(): i, k, m = symbols('i k m', integer=True) z_i, q_i = symbols('z_i q_i') a_k = Sum(-q_i*z_i/k,(i,1,m)) b_k = a_k.diff(z_i) assert isinstance(b_k, Sum) assert b_k == Sum(-q_i/k,(i,1,m)) def test_issue_10156(): cx = Sum(2*y**2*x, (x, 1,3)) e = 2*y*Sum(2*cx*x**2, (x, 1, 9)) assert e.factor() == \ 8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9)) def test_issue_10973(): assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true def test_issue_14129(): assert Sum( k*x**k, (k, 0, n-1)).doit() == \ Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n - n*x**n - x*x**n + x)/(x - 1)**2, True)) assert Sum( x**k, (k, 0, n-1)).doit() == \ Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True)) assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \ Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))), (x*(y + 1)*(n*x*y*(x + x/y)**n/(x + x/y) + n*x*(x + x/y)**n/(x + x/y) - n*y*(x + x/y)**n/(x + x/y) - x*y*(x + x/y)**n/(x + x/y) - x*(x + x/y)**n/(x + x/y) + y)/(x*y + x - y)**2, True)) def test_issue_14112(): assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false def test_sin_times_absolutely_convergent(): assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true def test_issue_14111(): assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false def test_issue_14484(): assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false def test_issue_14640(): i, n = symbols("i n", integer=True) a, b, c = symbols("a b c") assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum( 1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise( (n + 1, Eq(1/a, 1)), ((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b) assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise( (n + 1, Eq(a**(-2), 1)), ((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2 s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit() assert not s.has(Sum) assert s.subs({a: 2, b: 3, n: 5}) == 122 def test_issue_15943(): s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma) assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2 ) + E*gamma(n + 1) assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1)) def test_Sum_dummy_eq(): assert not Sum(x, (x, a, b)).dummy_eq(1) assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2))) assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c))) assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b))) d = Dummy() assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c) assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c))) assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c))) assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c) assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c))) def test_issue_15852(): assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo)) def test_exceptions(): S = Sum(x, (x, a, b)) raises(ValueError, lambda: S.change_index(x, x**2, y)) S = Sum(x, (x, a, b), (x, 1, 4)) raises(ValueError, lambda: S.index(x)) S = Sum(x, (x, a, b), (y, 1, 4)) raises(ValueError, lambda: S.reorder([x])) S = Sum(x, (x, y, b), (y, 1, 4)) raises(ReorderError, lambda: S.reorder_limit(0, 1)) S = Sum(x*y, (x, a, b), (y, 1, 4)) raises(NotImplementedError, lambda: S.is_convergent()) def test_sumproducts_assumptions(): M = Symbol('M', integer=True, positive=True) m = Symbol('m', integer=True) for func in [Sum, Product]: assert func(m, (m, -M, M)).is_positive is None assert func(m, (m, -M, M)).is_nonpositive is None assert func(m, (m, -M, M)).is_negative is None assert func(m, (m, -M, M)).is_nonnegative is None assert func(m, (m, -M, M)).is_finite is True m = Symbol('m', integer=True, nonnegative=True) for func in [Sum, Product]: assert func(m, (m, 0, M)).is_positive is None assert func(m, (m, 0, M)).is_nonpositive is None assert func(m, (m, 0, M)).is_negative is False assert func(m, (m, 0, M)).is_nonnegative is True assert func(m, (m, 0, M)).is_finite is True m = Symbol('m', integer=True, positive=True) for func in [Sum, Product]: assert func(m, (m, 1, M)).is_positive is True assert func(m, (m, 1, M)).is_nonpositive is False assert func(m, (m, 1, M)).is_negative is False assert func(m, (m, 1, M)).is_nonnegative is True assert func(m, (m, 1, M)).is_finite is True m = Symbol('m', integer=True, negative=True) assert Sum(m, (m, -M, -1)).is_positive is False assert Sum(m, (m, -M, -1)).is_nonpositive is True assert Sum(m, (m, -M, -1)).is_negative is True assert Sum(m, (m, -M, -1)).is_nonnegative is False assert Sum(m, (m, -M, -1)).is_finite is True assert Product(m, (m, -M, -1)).is_positive is None assert Product(m, (m, -M, -1)).is_nonpositive is None assert Product(m, (m, -M, -1)).is_negative is None assert Product(m, (m, -M, -1)).is_nonnegative is None assert Product(m, (m, -M, -1)).is_finite is True m = Symbol('m', integer=True, nonpositive=True) assert Sum(m, (m, -M, 0)).is_positive is False assert Sum(m, (m, -M, 0)).is_nonpositive is True assert Sum(m, (m, -M, 0)).is_negative is None assert Sum(m, (m, -M, 0)).is_nonnegative is None assert Sum(m, (m, -M, 0)).is_finite is True assert Product(m, (m, -M, 0)).is_positive is None assert Product(m, (m, -M, 0)).is_nonpositive is None assert Product(m, (m, -M, 0)).is_negative is None assert Product(m, (m, -M, 0)).is_nonnegative is None assert Product(m, (m, -M, 0)).is_finite is True m = Symbol('m', integer=True) assert Sum(2, (m, 0, oo)).is_positive is None assert Sum(2, (m, 0, oo)).is_nonpositive is None assert Sum(2, (m, 0, oo)).is_negative is None assert Sum(2, (m, 0, oo)).is_nonnegative is None assert Sum(2, (m, 0, oo)).is_finite is None assert Product(2, (m, 0, oo)).is_positive is None assert Product(2, (m, 0, oo)).is_nonpositive is None assert Product(2, (m, 0, oo)).is_negative is False assert Product(2, (m, 0, oo)).is_nonnegative is None assert Product(2, (m, 0, oo)).is_finite is None assert Product(0, (x, M, M-1)).is_positive is True assert Product(0, (x, M, M-1)).is_finite is True def test_expand_with_assumptions(): M = Symbol('M', integer=True, positive=True) x = Symbol('x', positive=True) m = Symbol('m', nonnegative=True) assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M)) assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M)) assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M)) assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M)) n = Symbol('n', nonnegative=True) i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \ == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) m = Symbol('m', nonnegative=True, integer=True) s = Sum(x**m, (m, 0, M)) s_as_product = s.rewrite(Product) assert s_as_product.has(Product) assert s_as_product == log(Product(exp(x**m), (m, 0, M))) assert s_as_product.expand() == s s5 = s.subs(M, 5) s5_as_product = s5.rewrite(Product) assert s5_as_product.has(Product) assert s5_as_product.doit().expand() == s5.doit() def test_has_finite_limits(): x = Symbol('x') assert Sum(1, (x, 1, 9)).has_finite_limits is True assert Sum(1, (x, 1, oo)).has_finite_limits is False M = Symbol('M') assert Sum(1, (x, 1, M)).has_finite_limits is None M = Symbol('M', positive=True) assert Sum(1, (x, 1, M)).has_finite_limits is True x = Symbol('x', positive=True) M = Symbol('M') assert Sum(1, (x, 1, M)).has_finite_limits is True assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False def test_has_reversed_limits(): assert Sum(1, (x, 1, 1)).has_reversed_limits is False assert Sum(1, (x, 1, 9)).has_reversed_limits is False assert Sum(1, (x, 1, -9)).has_reversed_limits is True assert Sum(1, (x, 1, 0)).has_reversed_limits is True assert Sum(1, (x, 1, oo)).has_reversed_limits is False M = Symbol('M') assert Sum(1, (x, 1, M)).has_reversed_limits is None M = Symbol('M', positive=True, integer=True) assert Sum(1, (x, 1, M)).has_reversed_limits is False assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False M = Symbol('M', negative=True) assert Sum(1, (x, 1, M)).has_reversed_limits is True assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True assert Sum(1, (x, oo, oo)).has_reversed_limits is None def test_has_empty_sequence(): assert Sum(1, (x, 1, 1)).has_empty_sequence is False assert Sum(1, (x, 1, 9)).has_empty_sequence is False assert Sum(1, (x, 1, -9)).has_empty_sequence is False assert Sum(1, (x, 1, 0)).has_empty_sequence is True assert Sum(1, (x, y, y - 1)).has_empty_sequence is True assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True assert Sum(1, (x, oo, oo)).has_empty_sequence is False def test_empty_sequence(): assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1 assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1 assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0 assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0 def test_issue_8016(): k = Symbol('k', integer=True) n, m = symbols('n, m', integer=True, positive=True) s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n)) assert s.doit().simplify() == \ cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1) def test_issue_14313(): assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent() def test_issue_14563(): # The assertion was failing due to no assumptions methods in Sums and Product assert 1 % Sum(1, (x, 0, 1)) == 1 def test_issue_16735(): assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true def test_issue_14871(): assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1 def test_issue_17165(): n = symbols("n", integer=True) x = symbols('x') s = (x*Sum(x**n, (n, -1, oo))) ssimp = s.doit().simplify() assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)), (x*Sum(x**n, (n, -1, oo)), True)), ssimp assert ssimp.simplify() == ssimp def test_issue_19379(): assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true def test_issue_20777(): assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m)) def test__dummy_with_inherited_properties_concrete(): x = Symbol('x') from sympy.core.containers import Tuple d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5)) assert d.is_real assert d.is_integer assert d.is_nonnegative assert d.is_extended_nonnegative d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9)) assert d.is_real assert d.is_integer assert d.is_positive assert d.is_odd is None d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5)) assert d.is_real assert d.is_integer assert d.is_positive is None assert d.is_extended_nonnegative is None assert d.is_odd is None d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5)) assert d.is_real assert d.is_integer is None assert d.is_positive is None assert d.is_extended_nonnegative is None N = Symbol('N', integer=True, positive=True) d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N)) assert d.is_real assert d.is_positive assert d.is_integer # Return None if no assumptions are added N = Symbol('N', integer=True, positive=True) d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4)) assert d is None x = Symbol('x', negative=True) raises(InconsistentAssumptions, lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5))) def test_matrixsymbol_summation_numerical_limits(): A = MatrixSymbol('A', 3, 3) n = Symbol('n', integer=True) assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2 assert Sum(A, (n, 0, 2)).doit() == 3*A assert Sum(n*A, (n, 0, 2)).doit() == 3*A B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]]) ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A assert Sum(A+B, (n, 0, 3)).doit() == ans ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) assert Sum(A*B, (n, 0, 3)).doit() == ans ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) + A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) + A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]])) assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans def test_issue_21651(): i = Symbol('i') a = Sum(floor(2*2**(-i)), (i, S.One, 2)) assert a.doit() == S.One @XFAIL def test_matrixsymbol_summation_symbolic_limits(): N = Symbol('N', integer=True, positive=True) A = MatrixSymbol('A', 3, 3) n = Symbol('n', integer=True) assert Sum(A, (n, 0, N)).doit() == (N+1)*A assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A def test_summation_by_residues(): x = Symbol('x') # Examples from Nakhle H. Asmar, Loukas Grafakos, # Complex Analysis with Applications assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi) assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945 assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi)) assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \ (-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2) assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \ (-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2) assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0 assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2 assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8 assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi) assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6 assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90 assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \ -pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2 # Some examples made from 1 / (x**2 + 1) assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \ S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \ -S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \ 1 + pi/(2*tanh(pi)) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \ pi/sinh(pi) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \ pi/(2*sinh(pi)) + S(1)/2 assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \ -S(1)/2 + pi/(2*sinh(pi)) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \ pi/(2*sinh(pi)) # Some examples made from shifting of 1 / (x**2 + 1) assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi)) assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi)) # Some examples made from 1 / x**2 assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6 assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6 assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12 assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12 @slow def test_summation_by_residues_failing(): x = Symbol('x') # Failing because of the bug in residue computation assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo)) assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0 def test_process_limits(): from sympy.concrete.expr_with_limits import _process_limits # these should be (x, Range(3)) not Range(3) raises(ValueError, lambda: _process_limits( Range(3), discrete=True)) raises(ValueError, lambda: _process_limits( Range(3), discrete=False)) # these should be (x, union) not union # (but then we would get a TypeError because we don't # handle non-contiguous sets: see below use of `union`) union = Or(x < 1, x > 3).as_set() raises(ValueError, lambda: _process_limits( union, discrete=True)) raises(ValueError, lambda: _process_limits( union, discrete=False)) # error not triggered if not needed assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1) # this equivalence is used to detect Reals in _process_limits assert isinstance(S.Reals, Interval) C = Integral # continuous limits assert C(x, x >= 5) == C(x, (x, 5, oo)) assert C(x, x < 3) == C(x, (x, -oo, 3)) ans = C(x, (x, 0, 3)) assert C(x, And(x >= 0, x < 3)) == ans assert C(x, (x, Interval.Ropen(0, 3))) == ans raises(TypeError, lambda: C(x, (x, Range(3)))) # discrete limits for D in (Sum, Product): r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans raises(TypeError, lambda: D(x, x > 0)) raises(ValueError, lambda: D(x, Interval(1, 3))) raises(NotImplementedError, lambda: D(x, (x, union))) def test_pr_22677(): b = Symbol('b', integer=True, positive=True) assert Sum(1/x**2,(x, 0, b)).doit() == Sum(x**(-2), (x, 0, b)) assert Sum(1/(x - b)**2,(x, 0, b-1)).doit() == Sum( (-b + x)**(-2), (x, 0, b - 1))
4d0245d8140afa3ecc92bf77b00f8c77876df99fe7dfe6bc8d7fbcd66e856949
from sympy.core.evalf import N from sympy.core.function import (Derivative, Function, PoleError, Subs) from sympy.core.numbers import (E, Rational, oo, pi, I) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, cos, sin) from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.series.series import series from sympy.abc import x, y, n, k from sympy.testing.pytest import raises from sympy.series.gruntz import calculate_series def test_sin(): e1 = sin(x).series(x, 0) e2 = series(sin(x), x, 0) assert e1 == e2 def test_cos(): e1 = cos(x).series(x, 0) e2 = series(cos(x), x, 0) assert e1 == e2 def test_exp(): e1 = exp(x).series(x, 0) e2 = series(exp(x), x, 0) assert e1 == e2 def test_exp2(): e1 = exp(cos(x)).series(x, 0) e2 = series(exp(cos(x)), x, 0) assert e1 == e2 def test_issue_5223(): assert series(1, x) == 1 assert next(S.Zero.lseries(x)) == 0 assert cos(x).series() == cos(x).series(x) raises(ValueError, lambda: cos(x + y).series()) raises(ValueError, lambda: x.series(dir="")) assert (cos(x).series(x, 1) - cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0 e = cos(x).series(x, 1, n=None) assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))] e = cos(x).series(x, 1, n=None, dir='-') assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)] # the following test is exact so no need for x -> x - 1 replacement assert abs(x).series(x, 1, dir='-') == x assert exp(x).series(x, 1, dir='-', n=3).removeO() == \ E - E*(-x + 1) + E*(-x + 1)**2/2 D = Derivative assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y assert next(D(cos(x), x).lseries()) == D(1, x) assert D( exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3) assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x assert (1 + x + O(x**2)).getn() == 2 assert (1 + x).getn() is None raises(PoleError, lambda: ((1/sin(x))**oo).series()) logx = Symbol('logx') assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \ exp(y*logx) + O(x*exp(y*logx), x) assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo)) assert abs(x).series(x, oo, n=5, dir='+') == x assert abs(x).series(x, -oo, n=5, dir='-') == -x assert abs(-x).series(x, oo, n=5, dir='+') == x assert abs(-x).series(x, -oo, n=5, dir='-') == -x assert exp(x*log(x)).series(n=3) == \ 1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3) # XXX is this right? If not, fix "ngot > n" handling in expr. p = Symbol('p', positive=True) assert exp(sqrt(p)**3*log(p)).series(n=3) == \ 1 + p**S('3/2')*log(p) + O(p**3*log(p)**3) assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2) def test_issue_11313(): assert Integral(cos(x), x).series(x) == sin(x).series(x) assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3) assert Derivative(x**3, x).as_leading_term(x) == 3*x**2 assert Derivative(x**3, y).as_leading_term(x) == 0 assert Derivative(sin(x), x).as_leading_term(x) == 1 assert Derivative(cos(x), x).as_leading_term(x) == -x # This result is equivalent to zero, zero is not return because # `Expr.series` doesn't currently detect an `x` in its `free_symbol`s. assert Derivative(1, x).as_leading_term(x) == Derivative(1, x) assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x) assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x) assert Derivative(log(x), x).series(x).doit() == (1/x).series(x) assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO() def test_series_of_Subs(): from sympy.abc import z subs1 = Subs(sin(x), x, y) subs2 = Subs(sin(x) * cos(z), x, y) subs3 = Subs(sin(x * z), (x, z), (y, x)) assert subs1.series(x) == subs1 subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) + Subs(x**5/120, x, y) + O(y**6)) assert subs1.series() == subs1_series assert subs1.series(y) == subs1_series assert subs1.series(z) == subs1 assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) + Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6)) assert subs3.series(x).doit() == subs3.doit().series(x) assert subs3.series(z).doit() == sin(x*y) raises(ValueError, lambda: Subs(x + 2*y, y, z).series()) assert Subs(x + y, y, z).series(x).doit() == x + z def test_issue_3978(): f = Function('f') assert f(x).series(x, 0, 3, dir='-') == \ f(0) + x*Subs(Derivative(f(x), x), x, 0) + \ x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3) assert f(x).series(x, 0, 3) == \ f(0) + x*Subs(Derivative(f(x), x), x, 0) + \ x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3) assert f(x**2).series(x, 0, 3) == \ f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3) assert f(x**2+1).series(x, 0, 3) == \ f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3) class TestF(Function): pass assert TestF(x).series(x, 0, 3) == TestF(0) + \ x*Subs(Derivative(TestF(x), x), x, 0) + \ x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3) from sympy.series.acceleration import richardson, shanks from sympy.concrete.summations import Sum from sympy.core.numbers import Integer def test_acceleration(): e = (1 + 1/n)**n assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10) A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n)) assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4) assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10) def test_issue_5852(): assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \ 5*x**4/(24*log(x)**4) + O(x**6) def test_issue_4583(): assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \ x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \ x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5) def test_issue_6318(): eq = (1/x)**Rational(2, 3) assert (eq + 1).as_leading_term(x) == eq def test_x_is_base_detection(): eq = (x**2)**Rational(2, 3) assert eq.series() == x**Rational(4, 3) def test_sin_power(): e = sin(x)**1.2 assert calculate_series(e, x) == x**1.2 def test_issue_7203(): assert series(cos(x), x, pi, 3) == \ -1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi)) def test_exp_product_positive_factors(): a, b = symbols('a, b', positive=True) x = a * b assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \ a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \ a**7*b**7/5040 + O(a**8*b**8, a, b) def test_issue_8805(): assert series(1, n=8) == 1 def test_issue_9549(): y = (x**2 + x + 1) / (x**3 + x**2) assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo)) def test_issue_10761(): assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6) def test_issue_12578(): y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8) assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \ 3472*x**14 - 17318*x**16 + O(x**17) def test_issue_12791(): beta = symbols('beta', positive=True) theta, varphi = symbols('theta varphi', real=True) expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \ beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2 sol = 0.5/(0.5*cos(theta) - 1.0)**2 - 0.25*cos(theta)/(0.5*cos(theta)\ - 1.0)**2 + (beta - 0.5)*(-0.25*varphi*sin(2*theta) - 1.5*cos(theta)\ + 0.25*cos(2*theta) + 1.25)/(0.5*cos(theta) - 1.0)**3\ + 0.25*varphi*sin(theta)/(0.5*cos(theta) - 1.0)**2 + O((beta - S.Half)**2, (beta, S.Half)) assert expr.series(beta, 0.5, 2).trigsimp() == sol def test_issue_14384(): x, a = symbols('x a') assert series(x**a, x) == x**a assert series(x**(-2*a), x) == x**(-2*a) assert series(exp(a*log(x)), x) == exp(a*log(x)) assert series(x**I, x) == x**I assert series(x**(I + 1), x) == x**(1 + I) assert series(exp(I*log(x)), x) == exp(I*log(x)) def test_issue_14885(): assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) + sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 + x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6)) def test_issue_15539(): assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(x**(-6), (x, -oo))) assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(x**(-6), (x, oo))) def test_issue_7259(): assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6) assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8) assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4) def test_issue_11884(): assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1)) def test_issue_18008(): y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x)) assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \ O(x**(-4), (x, oo)) def test_issue_18842(): f = log(x/(1 - x)) assert f.series(x, 0.491, n=1).removeO().nsimplify() == \ -S(180019443780011)/5000000000000000 def test_issue_19534(): dt = symbols('dt', real=True) expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \ 49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \ dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \ 0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + \ 2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \ 1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \ dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \ 6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) - \ 7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \ 0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \ 0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + \ 2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \ 0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1 assert N(expr.series(dt, 0, 8), 20) == -0.00092592592592592596126*dt**7 + 0.0027777777777777783175*dt**6 + \ 0.016666666666666656027*dt**5 + 0.083333333333333300952*dt**4 + 0.33333333333333337034*dt**3 + \ 1.0*dt**2 + 1.0*dt + 1.0 def test_issue_11407(): a, b, c, x = symbols('a b c x') assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x) assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x) def test_issue_14037(): assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x) def test_issue_20551(): expr = (exp(x)/x).series(x, n=None) terms = [ next(expr) for i in range(3) ] assert terms == [1/x, 1, x/2] def test_issue_20697(): p_0, p_1, p_2, p_3, b_0, b_1, b_2 = symbols('p_0 p_1 p_2 p_3 b_0 b_1 b_2') Q = (p_0 + (p_1 + (p_2 + p_3/y)/y)/y)/(1 + ((p_3/(b_0*y) + (b_0*p_2\ - b_1*p_3)/b_0**2)/y + (b_0**2*p_1 - b_0*b_1*p_2 - p_3*(b_0*b_2\ - b_1**2))/b_0**3)/y) assert Q.series(y, n=3).ratsimp() == b_2*y**2 + b_1*y + b_0 + O(y**3) def test_issue_21245(): fi = (1 + sqrt(5))/2 assert (1/(1 - x - x**2)).series(x, 1/fi, 1).factor() == \ (-4812 - 2152*sqrt(5) + 1686*x + 754*sqrt(5)*x\ + O((x - 2/(1 + sqrt(5)))**2, (x, 2/(1 + sqrt(5)))))/((1 + sqrt(5))\ *(20 + 9*sqrt(5))**2*(x + sqrt(5)*x - 2)) def test_issue_21938(): expr = sin(1/x + exp(-x)) - sin(1/x) assert expr.series(x, oo) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
3e12e6ba608df24e39cdf34a51efb75a59463a470f52dec4666691af2a205405
from sympy.core.add import Add from sympy.core.function import (Function, expand) from sympy.core.numbers import (I, Rational, nan, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (conjugate, transpose) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.integrals.integrals import Integral from sympy.series.order import O, Order from sympy.core.expr import unchanged from sympy.testing.pytest import raises from sympy.abc import w, x, y, z def test_caching_bug(): #needs to be a first test, so that all caches are clean #cache it O(w) #and test that this won't raise an exception O(w**(-1/x/log(3)*log(5)), w) def test_free_symbols(): assert Order(1).free_symbols == set() assert Order(x).free_symbols == {x} assert Order(1, x).free_symbols == {x} assert Order(x*y).free_symbols == {x, y} assert Order(x, x, y).free_symbols == {x, y} def test_simple_1(): o = Rational(0) assert Order(2*x) == Order(x) assert Order(x)*3 == Order(x) assert -28*Order(x) == Order(x) assert Order(Order(x)) == Order(x) assert Order(Order(x), y) == Order(Order(x), x, y) assert Order(-23) == Order(1) assert Order(exp(x)) == Order(1, x) assert Order(exp(1/x)).expr == exp(1/x) assert Order(x*exp(1/x)).expr == x*exp(1/x) assert Order(x**(o/3)).expr == x**(o/3) assert Order(x**(o*Rational(5, 3))).expr == x**(o*Rational(5, 3)) assert Order(x**2 + x + y, x) == O(1, x) assert Order(x**2 + x + y, y) == O(1, y) raises(ValueError, lambda: Order(exp(x), x, x)) raises(TypeError, lambda: Order(x, 2 - x)) def test_simple_2(): assert Order(2*x)*x == Order(x**2) assert Order(2*x)/x == Order(1, x) assert Order(2*x)*x*exp(1/x) == Order(x**2*exp(1/x)) assert (Order(2*x)*x*exp(1/x)/log(x)**3).expr == x**2*exp(1/x)*log(x)**-3 def test_simple_3(): assert Order(x) + x == Order(x) assert Order(x) + 2 == 2 + Order(x) assert Order(x) + x**2 == Order(x) assert Order(x) + 1/x == 1/x + Order(x) assert Order(1/x) + 1/x**2 == 1/x**2 + Order(1/x) assert Order(x) + exp(1/x) == Order(x) + exp(1/x) def test_simple_4(): assert Order(x)**2 == Order(x**2) def test_simple_5(): assert Order(x) + Order(x**2) == Order(x) assert Order(x) + Order(x**-2) == Order(x**-2) assert Order(x) + Order(1/x) == Order(1/x) def test_simple_6(): assert Order(x) - Order(x) == Order(x) assert Order(x) + Order(1) == Order(1) assert Order(x) + Order(x**2) == Order(x) assert Order(1/x) + Order(1) == Order(1/x) assert Order(x) + Order(exp(1/x)) == Order(exp(1/x)) assert Order(x**3) + Order(exp(2/x)) == Order(exp(2/x)) assert Order(x**-3) + Order(exp(2/x)) == Order(exp(2/x)) def test_simple_7(): assert 1 + O(1) == O(1) assert 2 + O(1) == O(1) assert x + O(1) == O(1) assert 1/x + O(1) == 1/x + O(1) def test_simple_8(): assert O(sqrt(-x)) == O(sqrt(x)) assert O(x**2*sqrt(x)) == O(x**Rational(5, 2)) assert O(x**3*sqrt(-(-x)**3)) == O(x**Rational(9, 2)) assert O(x**Rational(3, 2)*sqrt((-x)**3)) == O(x**3) assert O(x*(-2*x)**(I/2)) == O(x*(-x)**(I/2)) def test_as_expr_variables(): assert Order(x).as_expr_variables(None) == (x, ((x, 0),)) assert Order(x).as_expr_variables(((x, 0),)) == (x, ((x, 0),)) assert Order(y).as_expr_variables(((x, 0),)) == (y, ((x, 0), (y, 0))) assert Order(y).as_expr_variables(((x, 0), (y, 0))) == (y, ((x, 0), (y, 0))) def test_contains_0(): assert Order(1, x).contains(Order(1, x)) assert Order(1, x).contains(Order(1)) assert Order(1).contains(Order(1, x)) is False def test_contains_1(): assert Order(x).contains(Order(x)) assert Order(x).contains(Order(x**2)) assert not Order(x**2).contains(Order(x)) assert not Order(x).contains(Order(1/x)) assert not Order(1/x).contains(Order(exp(1/x))) assert not Order(x).contains(Order(exp(1/x))) assert Order(1/x).contains(Order(x)) assert Order(exp(1/x)).contains(Order(x)) assert Order(exp(1/x)).contains(Order(1/x)) assert Order(exp(1/x)).contains(Order(exp(1/x))) assert Order(exp(2/x)).contains(Order(exp(1/x))) assert not Order(exp(1/x)).contains(Order(exp(2/x))) def test_contains_2(): assert Order(x).contains(Order(y)) is None assert Order(x).contains(Order(y*x)) assert Order(y*x).contains(Order(x)) assert Order(y).contains(Order(x*y)) assert Order(x).contains(Order(y**2*x)) def test_contains_3(): assert Order(x*y**2).contains(Order(x**2*y)) is None assert Order(x**2*y).contains(Order(x*y**2)) is None def test_contains_4(): assert Order(sin(1/x**2)).contains(Order(cos(1/x**2))) is True assert Order(cos(1/x**2)).contains(Order(sin(1/x**2))) is True def test_contains(): assert Order(1, x) not in Order(1) assert Order(1) in Order(1, x) raises(TypeError, lambda: Order(x*y**2) in Order(x**2*y)) def test_add_1(): assert Order(x + x) == Order(x) assert Order(3*x - 2*x**2) == Order(x) assert Order(1 + x) == Order(1, x) assert Order(1 + 1/x) == Order(1/x) assert Order(log(x) + 1/log(x)) == Order(log(x)) assert Order(exp(1/x) + x) == Order(exp(1/x)) assert Order(exp(1/x) + 1/x**20) == Order(exp(1/x)) def test_ln_args(): assert O(log(x)) + O(log(2*x)) == O(log(x)) assert O(log(x)) + O(log(x**3)) == O(log(x)) assert O(log(x*y)) + O(log(x) + log(y)) == O(log(x*y)) def test_multivar_0(): assert Order(x*y).expr == x*y assert Order(x*y**2).expr == x*y**2 assert Order(x*y, x).expr == x assert Order(x*y**2, y).expr == y**2 assert Order(x*y*z).expr == x*y*z assert Order(x/y).expr == x/y assert Order(x*exp(1/y)).expr == x*exp(1/y) assert Order(exp(x)*exp(1/y)).expr == exp(x)*exp(1/y) def test_multivar_0a(): assert Order(exp(1/x)*exp(1/y)).expr == exp(1/x)*exp(1/y) def test_multivar_1(): assert Order(x + y).expr == x + y assert Order(x + 2*y).expr == x + y assert (Order(x + y) + x).expr == (x + y) assert (Order(x + y) + x**2) == Order(x + y) assert (Order(x + y) + 1/x) == 1/x + Order(x + y) assert Order(x**2 + y*x).expr == x**2 + y*x def test_multivar_2(): assert Order(x**2*y + y**2*x, x, y).expr == x**2*y + y**2*x def test_multivar_mul_1(): assert Order(x + y)*x == Order(x**2 + y*x, x, y) def test_multivar_3(): assert (Order(x) + Order(y)).args in [ (Order(x), Order(y)), (Order(y), Order(x))] assert Order(x) + Order(y) + Order(x + y) == Order(x + y) assert (Order(x**2*y) + Order(y**2*x)).args in [ (Order(x*y**2), Order(y*x**2)), (Order(y*x**2), Order(x*y**2))] assert (Order(x**2*y) + Order(y*x)) == Order(x*y) def test_issue_3468(): y = Symbol('y', negative=True) z = Symbol('z', complex=True) # check that Order does not modify assumptions about symbols Order(x) Order(y) Order(z) assert x.is_positive is None assert y.is_positive is False assert z.is_positive is None def test_leading_order(): assert (x + 1 + 1/x**5).extract_leading_order(x) == ((1/x**5, O(1/x**5)),) assert (1 + 1/x).extract_leading_order(x) == ((1/x, O(1/x)),) assert (1 + x).extract_leading_order(x) == ((1, O(1, x)),) assert (1 + x**2).extract_leading_order(x) == ((1, O(1, x)),) assert (2 + x**2).extract_leading_order(x) == ((2, O(1, x)),) assert (x + x**2).extract_leading_order(x) == ((x, O(x)),) def test_leading_order2(): assert set((2 + pi + x**2).extract_leading_order(x)) == {(pi, O(1, x)), (S(2), O(1, x))} assert set((2*x + pi*x + x**2).extract_leading_order(x)) == {(2*x, O(x)), (x*pi, O(x))} def test_order_leadterm(): assert O(x**2)._eval_as_leading_term(x) == O(x**2) def test_order_symbols(): e = x*y*sin(x)*Integral(x, (x, 1, 2)) assert O(e) == O(x**2*y, x, y) assert O(e, x) == O(x**2) def test_nan(): assert O(nan) is nan assert not O(x).contains(nan) def test_O1(): assert O(1, x) * x == O(x) assert O(1, y) * x == O(1, y) def test_getn(): # other lines are tested incidentally by the suite assert O(x).getn() == 1 assert O(x/log(x)).getn() == 1 assert O(x**2/log(x)**2).getn() == 2 assert O(x*log(x)).getn() == 1 raises(NotImplementedError, lambda: (O(x) + O(y)).getn()) def test_diff(): assert O(x**2).diff(x) == O(x) def test_getO(): assert (x).getO() is None assert (x).removeO() == x assert (O(x)).getO() == O(x) assert (O(x)).removeO() == 0 assert (z + O(x) + O(y)).getO() == O(x) + O(y) assert (z + O(x) + O(y)).removeO() == z raises(NotImplementedError, lambda: (O(x) + O(y)).getn()) def test_leading_term(): from sympy.functions.special.gamma_functions import digamma assert O(1/digamma(1/x)) == O(1/log(x)) def test_eval(): assert Order(x).subs(Order(x), 1) == 1 assert Order(x).subs(x, y) == Order(y) assert Order(x).subs(y, x) == Order(x) assert Order(x).subs(x, x + y) == Order(x + y, (x, -y)) assert (O(1)**x).is_Pow def test_issue_4279(): a, b = symbols('a b') assert O(a, a, b) + O(1, a, b) == O(1, a, b) assert O(b, a, b) + O(1, a, b) == O(1, a, b) assert O(a + b, a, b) + O(1, a, b) == O(1, a, b) assert O(1, a, b) + O(a, a, b) == O(1, a, b) assert O(1, a, b) + O(b, a, b) == O(1, a, b) assert O(1, a, b) + O(a + b, a, b) == O(1, a, b) def test_issue_4855(): assert 1/O(1) != O(1) assert 1/O(x) != O(1/x) assert 1/O(x, (x, oo)) != O(1/x, (x, oo)) f = Function('f') assert 1/O(f(x)) != O(1/x) def test_order_conjugate_transpose(): x = Symbol('x', real=True) y = Symbol('y', imaginary=True) assert conjugate(Order(x)) == Order(conjugate(x)) assert conjugate(Order(y)) == Order(conjugate(y)) assert conjugate(Order(x**2)) == Order(conjugate(x)**2) assert conjugate(Order(y**2)) == Order(conjugate(y)**2) assert transpose(Order(x)) == Order(transpose(x)) assert transpose(Order(y)) == Order(transpose(y)) assert transpose(Order(x**2)) == Order(transpose(x)**2) assert transpose(Order(y**2)) == Order(transpose(y)**2) def test_order_noncommutative(): A = Symbol('A', commutative=False) assert Order(A + A*x, x) == Order(1, x) assert (A + A*x)*Order(x) == Order(x) assert (A*x)*Order(x) == Order(x**2, x) assert expand((1 + Order(x))*A*A*x) == A*A*x + Order(x**2, x) assert expand((A*A + Order(x))*x) == A*A*x + Order(x**2, x) assert expand((A + Order(x))*A*x) == A*A*x + Order(x**2, x) def test_issue_6753(): assert (1 + x**2)**10000*O(x) == O(x) def test_order_at_infinity(): assert Order(1 + x, (x, oo)) == Order(x, (x, oo)) assert Order(3*x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo))*3 == Order(x, (x, oo)) assert -28*Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(Order(x, (x, oo)), (x, oo)) == Order(x, (x, oo)) assert Order(Order(x, (x, oo)), (y, oo)) == Order(x, (x, oo), (y, oo)) assert Order(3, (x, oo)) == Order(1, (x, oo)) assert Order(x**2 + x + y, (x, oo)) == O(x**2, (x, oo)) assert Order(x**2 + x + y, (y, oo)) == O(y, (y, oo)) assert Order(2*x, (x, oo))*x == Order(x**2, (x, oo)) assert Order(2*x, (x, oo))/x == Order(1, (x, oo)) assert Order(2*x, (x, oo))*x*exp(1/x) == Order(x**2*exp(1/x), (x, oo)) assert Order(2*x, (x, oo))*x*exp(1/x)/log(x)**3 == Order(x**2*exp(1/x)*log(x)**-3, (x, oo)) assert Order(x, (x, oo)) + 1/x == 1/x + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + 1 == 1 + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + x == x + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + x**2 == x**2 + Order(x, (x, oo)) assert Order(1/x, (x, oo)) + 1/x**2 == 1/x**2 + Order(1/x, (x, oo)) == Order(1/x, (x, oo)) assert Order(x, (x, oo)) + exp(1/x) == exp(1/x) + Order(x, (x, oo)) assert Order(x, (x, oo))**2 == Order(x**2, (x, oo)) assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo)) assert Order(x, (x, oo)) + Order(x**-2, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(1/x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) - Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(1, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo)) assert Order(1/x, (x, oo)) + Order(1, (x, oo)) == Order(1, (x, oo)) assert Order(x, (x, oo)) + Order(exp(1/x), (x, oo)) == Order(x, (x, oo)) assert Order(x**3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(x**3, (x, oo)) assert Order(x**-3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(exp(2/x), (x, oo)) # issue 7207 assert Order(exp(x), (x, oo)).expr == Order(2*exp(x), (x, oo)).expr == exp(x) assert Order(y**x, (x, oo)).expr == Order(2*y**x, (x, oo)).expr == exp(x*log(y)) # issue 19545 assert Order(1/x - 3/(3*x + 2), (x, oo)).expr == x**(-2) def test_mixing_order_at_zero_and_infinity(): assert (Order(x, (x, 0)) + Order(x, (x, oo))).is_Add assert Order(x, (x, 0)) + Order(x, (x, oo)) == Order(x, (x, oo)) + Order(x, (x, 0)) assert Order(Order(x, (x, oo))) == Order(x, (x, oo)) # not supported (yet) raises(NotImplementedError, lambda: Order(x, (x, 0))*Order(x, (x, oo))) raises(NotImplementedError, lambda: Order(x, (x, oo))*Order(x, (x, 0))) raises(NotImplementedError, lambda: Order(Order(x, (x, oo)), y)) raises(NotImplementedError, lambda: Order(Order(x), (x, oo))) def test_order_at_some_point(): assert Order(x, (x, 1)) == Order(1, (x, 1)) assert Order(2*x - 2, (x, 1)) == Order(x - 1, (x, 1)) assert Order(-x + 1, (x, 1)) == Order(x - 1, (x, 1)) assert Order(x - 1, (x, 1))**2 == Order((x - 1)**2, (x, 1)) assert Order(x - 2, (x, 2)) - O(x - 2, (x, 2)) == Order(x - 2, (x, 2)) def test_order_subs_limits(): # issue 3333 assert (1 + Order(x)).subs(x, 1/x) == 1 + Order(1/x, (x, oo)) assert (1 + Order(x)).limit(x, 0) == 1 # issue 5769 assert ((x + Order(x**2))/x).limit(x, 0) == 1 assert Order(x**2).subs(x, y - 1) == Order((y - 1)**2, (y, 1)) assert Order(10*x**2, (x, 2)).subs(x, y - 1) == Order(1, (y, 3)) def test_issue_9351(): assert exp(x).series(x, 10, 1) == exp(10) + Order(x - 10, (x, 10)) def test_issue_9192(): assert O(1)*O(1) == O(1) assert O(1)**O(1) == O(1) def test_issue_9910(): assert O(x*log(x) + sin(x), (x, oo)) == O(x*log(x), (x, oo)) def test_performance_of_adding_order(): l = list(x**i for i in range(1000)) l.append(O(x**1001)) assert Add(*l).subs(x,1) == O(1) def test_issue_14622(): assert (x**(-4) + x**(-3) + x**(-1) + O(x**(-6), (x, oo))).as_numer_denom() == ( x**4 + x**5 + x**7 + O(x**2, (x, oo)), x**8) assert (x**3 + O(x**2, (x, oo))).is_Add assert O(x**2, (x, oo)).contains(x**3) is False assert O(x, (x, oo)).contains(O(x, (x, 0))) is None assert O(x, (x, 0)).contains(O(x, (x, oo))) is None raises(NotImplementedError, lambda: O(x**3).contains(x**w)) def test_issue_15539(): assert O(1/x**2 + 1/x**4, (x, -oo)) == O(1/x**2, (x, -oo)) assert O(1/x**4 + exp(x), (x, -oo)) == O(1/x**4, (x, -oo)) assert O(1/x**4 + exp(-x), (x, -oo)) == O(exp(-x), (x, -oo)) assert O(1/x, (x, oo)).subs(x, -x) == O(-1/x, (x, -oo)) def test_issue_18606(): assert unchanged(Order, 0) def test_issue_22165(): assert O(log(x)).contains(2) def test_issue_23231(): # This test checks Order for expressions having # arguments containing variables in exponents/powers. assert O(x**x + 2**x, (x, oo)) == O(exp(x*log(x)), (x, oo)) assert O(x**x + x**2, (x, oo)) == O(exp(x*log(x)), (x, oo)) assert O(x**x + 1/x**2, (x, oo)) == O(exp(x*log(x)), (x, oo)) assert O(2**x + 3**x , (x, oo)) == O(exp(x*log(3)), (x, oo)) def test_issue_9917(): assert O(x*sin(x) + 1, (x, oo)) == O(x, (x, oo))
91353299d6f6a067b57cf581c27400a0428d35d84d11dd5369a1e479a69abe22
from itertools import product from sympy.concrete.summations import Sum from sympy.core.function import (Function, diff) from sympy.core import EulerGamma from sympy.core.numbers import (E, I, Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial) from sympy.functions.elementary.complexes import (Abs, re, sign) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (acoth, atanh, sinh) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import (cbrt, real_root, sqrt) from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, cos, cot, csc, sec, sin, tan) from sympy.functions.special.bessel import (besselj, besselk) from sympy.functions.special.error_functions import (Ei, erf, erfc, erfi, fresnelc, fresnels) from sympy.functions.special.gamma_functions import (digamma, gamma, uppergamma) from sympy.integrals.integrals import (Integral, integrate) from sympy.series.limits import (Limit, limit) from sympy.simplify.simplify import simplify from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.mul import Mul from sympy.series.limits import heuristics from sympy.series.order import Order from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y, z, k n = Symbol('n', integer=True, positive=True) def test_basic1(): assert limit(x, x, oo) is oo assert limit(x, x, -oo) is -oo assert limit(-x, x, oo) is -oo assert limit(x**2, x, -oo) is oo assert limit(-x**2, x, oo) is -oo assert limit(x*log(x), x, 0, dir="+") == 0 assert limit(1/x, x, oo) == 0 assert limit(exp(x), x, oo) is oo assert limit(-exp(x), x, oo) is -oo assert limit(exp(x)/x, x, oo) is oo assert limit(1/x - exp(-x), x, oo) == 0 assert limit(x + 1/x, x, oo) is oo assert limit(x - x**2, x, oo) is -oo assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1 assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0) assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-') assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((1 + x + y)**oo, x, 0, dir='-') assert limit(y/x/log(x), x, 0) == -oo*sign(y) assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo assert limit(gamma(1/x + 3), x, oo) == 2 assert limit(S.NaN, x, -oo) is S.NaN assert limit(Order(2)*x, x, S.NaN) is S.NaN assert limit(1/(x - 1), x, 1, dir="+") is oo assert limit(1/(x - 1), x, 1, dir="-") is -oo assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo assert limit(1/(5 - x)**3, x, 5, dir="-") is oo assert limit(1/sin(x), x, pi, dir="+") is -oo assert limit(1/sin(x), x, pi, dir="-") is oo assert limit(1/cos(x), x, pi/2, dir="+") is -oo assert limit(1/cos(x), x, pi/2, dir="-") is oo assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo assert limit(tan(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(sec(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) # test bi-directional limits assert limit(sin(x)/x, x, 0, dir="+-") == 1 assert limit(x**2, x, 0, dir="+-") == 0 assert limit(1/x**2, x, 0, dir="+-") is oo # test failing bi-directional limits assert limit(1/x, x, 0, dir="+-") is zoo # approaching 0 # from dir="+" assert limit(1 + 1/x, x, 0) is oo # from dir='-' # Add assert limit(1 + 1/x, x, 0, dir='-') is -oo # Pow assert limit(x**(-2), x, 0, dir='-') is oo assert limit(x**(-3), x, 0, dir='-') is -oo assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I assert limit(x**2, x, 0, dir='-') == 0 assert limit(sqrt(x), x, 0, dir='-') == 0 assert limit(x**-pi, x, 0, dir='-') == oo/(-1)**pi assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0) # test pull request 22491 assert limit(1/asin(x), x, 0, dir = '+') == oo assert limit(1/asin(x), x, 0, dir = '-') == -oo assert limit(1/sinh(x), x, 0, dir = '+') == oo assert limit(1/sinh(x), x, 0, dir = '-') == -oo assert limit(log(1/x) + 1/sin(x), x, 0, dir = '+') == oo assert limit(log(1/x) + 1/x, x, 0, dir = '+') == oo def test_basic2(): assert limit(x**x, x, 0, dir="+") == 1 assert limit((exp(x) - 1)/x, x, 0) == 1 assert limit(1 + 1/x, x, oo) == 1 assert limit(-exp(1/x), x, oo) == -1 assert limit(x + exp(-x), x, oo) is oo assert limit(x + exp(-x**2), x, oo) is oo assert limit(x + exp(-exp(x)), x, oo) is oo assert limit(13 + 1/x - exp(-x), x, oo) == 13 def test_basic3(): assert limit(1/x, x, 0, dir="+") is oo assert limit(1/x, x, 0, dir="-") is -oo def test_basic4(): assert limit(2*x + y*x, x, 0) == 0 assert limit(2*x + y*x, x, 1) == 2 + y assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8 assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0 assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9 def test_log(): # https://github.com/sympy/sympy/issues/21598 a, b, c = symbols('a b c', positive=True) A = log(a/b) - (log(a) - log(b)) assert A.limit(a, oo) == 0 assert (A * c).limit(a, oo) == 0 tau, x = symbols('tau x', positive=True) # The value of manualintegrate in the issue expr = tau**2*((tau - 1)*(tau + 1)*log(x + 1)/(tau**2 + 1)**2 + 1/((tau**2\ + 1)*(x + 1)) - (-2*tau*atan(x/tau) + (tau**2/2 - 1/2)*log(tau**2\ + x**2))/(tau**2 + 1)**2) assert limit(expr, x, oo) == pi*tau**3/(tau**2 + 1)**2 def test_piecewise(): # https://github.com/sympy/sympy/issues/18363 assert limit((real_root(x - 6, 3) + 2)/(x + 2), x, -2, '+') == Rational(1, 12) def test_basic5(): class my(Function): @classmethod def eval(cls, arg): if arg is S.Infinity: return S.NaN assert limit(my(x), x, oo) == Limit(my(x), x, oo) def test_issue_3885(): assert limit(x*y + x*z, z, 2) == x*y + 2*x def test_Limit(): assert Limit(sin(x)/x, x, 0) != 1 assert Limit(sin(x)/x, x, 0).doit() == 1 assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-')) def test_floor(): assert limit(floor(x), x, -2, "+") == -2 assert limit(floor(x), x, -2, "-") == -3 assert limit(floor(x), x, -1, "+") == -1 assert limit(floor(x), x, -1, "-") == -2 assert limit(floor(x), x, 0, "+") == 0 assert limit(floor(x), x, 0, "-") == -1 assert limit(floor(x), x, 1, "+") == 1 assert limit(floor(x), x, 1, "-") == 0 assert limit(floor(x), x, 2, "+") == 2 assert limit(floor(x), x, 2, "-") == 1 assert limit(floor(x), x, 248, "+") == 248 assert limit(floor(x), x, 248, "-") == 247 # https://github.com/sympy/sympy/issues/14478 assert limit(x*floor(3/x)/2, x, 0, '+') == Rational(3, 2) assert limit(floor(x + 1/2) - floor(x), x, oo) == AccumBounds(-S.Half, S(3)/2) def test_floor_requires_robust_assumptions(): assert limit(floor(sin(x)), x, 0, "+") == 0 assert limit(floor(sin(x)), x, 0, "-") == -1 assert limit(floor(cos(x)), x, 0, "+") == 0 assert limit(floor(cos(x)), x, 0, "-") == 0 assert limit(floor(5 + sin(x)), x, 0, "+") == 5 assert limit(floor(5 + sin(x)), x, 0, "-") == 4 assert limit(floor(5 + cos(x)), x, 0, "+") == 5 assert limit(floor(5 + cos(x)), x, 0, "-") == 5 def test_ceiling(): assert limit(ceiling(x), x, -2, "+") == -1 assert limit(ceiling(x), x, -2, "-") == -2 assert limit(ceiling(x), x, -1, "+") == 0 assert limit(ceiling(x), x, -1, "-") == -1 assert limit(ceiling(x), x, 0, "+") == 1 assert limit(ceiling(x), x, 0, "-") == 0 assert limit(ceiling(x), x, 1, "+") == 2 assert limit(ceiling(x), x, 1, "-") == 1 assert limit(ceiling(x), x, 2, "+") == 3 assert limit(ceiling(x), x, 2, "-") == 2 assert limit(ceiling(x), x, 248, "+") == 249 assert limit(ceiling(x), x, 248, "-") == 248 # https://github.com/sympy/sympy/issues/14478 assert limit(x*ceiling(3/x)/2, x, 0, '+') == Rational(3, 2) assert limit(ceiling(x + 1/2) - ceiling(x), x, oo) == AccumBounds(-S.Half, S(3)/2) def test_ceiling_requires_robust_assumptions(): assert limit(ceiling(sin(x)), x, 0, "+") == 1 assert limit(ceiling(sin(x)), x, 0, "-") == 0 assert limit(ceiling(cos(x)), x, 0, "+") == 1 assert limit(ceiling(cos(x)), x, 0, "-") == 1 assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6 assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5 assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6 assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6 def test_atan(): x = Symbol("x", real=True) assert limit(atan(x)*sin(1/x), x, 0) == 0 assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2 def test_set_signs(): assert limit(abs(x), x, 0) == 0 assert limit(abs(sin(x)), x, 0) == 0 assert limit(abs(cos(x)), x, 0) == 1 assert limit(abs(sin(x + 1)), x, 0) == sin(1) # https://github.com/sympy/sympy/issues/9449 assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y) # https://github.com/sympy/sympy/issues/12398 assert limit(Abs(log(x)/x**3), x, oo) == 0 assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3 # https://github.com/sympy/sympy/issues/18501 assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo # https://github.com/sympy/sympy/issues/18997 assert limit(Abs(log(x)), x, 0) == oo assert limit(Abs(log(Abs(x))), x, 0) == oo # https://github.com/sympy/sympy/issues/19026 z = Symbol('z', positive=True) assert limit(Abs(log(z) + 1)/log(z), z, oo) == 1 # https://github.com/sympy/sympy/issues/20704 assert limit(z*(Abs(1/z + y) - Abs(y - 1/z))/2, z, 0) == 0 # https://github.com/sympy/sympy/issues/21606 assert limit(cos(z)/sign(z), z, pi, '-') == -1 def test_heuristic(): x = Symbol("x", real=True) assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1) assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2) def test_issue_3871(): z = Symbol("z", positive=True) f = -1/z*exp(-z*x) assert limit(f, x, oo) == 0 assert f.limit(x, oo) == 0 def test_exponential(): n = Symbol('n') x = Symbol('x', real=True) assert limit((1 + x/n)**n, n, oo) == exp(x) assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2) assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2) assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2) assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1 assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3')) def test_exponential2(): n = Symbol('n') assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x) def test_doit(): f = Integral(2 * x, x) l = Limit(f, x, oo) assert l.doit() is oo def test_series_AccumBounds(): assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2) assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3) # not the exact bound assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2) # test for issue #9934 lo = (-3 + cos(1))/2 hi = (1 + cos(1))/2 t1 = Mul(AccumBounds(lo, hi), 1/(-1 + cos(1)), evaluate=False) assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1 t2 = Mul(AccumBounds(-1 + sin(1)/2, sin(1)/2 + 1), 1/(1 - cos(1))) assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2 assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo) # wolfram gives (0, 1) assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo) # wolfram says 0 # https://github.com/sympy/sympy/issues/12312 e = 2**(-x)*(sin(x) + 1)**x assert limit(e, x, oo) == AccumBounds(0, oo) @XFAIL def test_doit2(): f = Integral(2 * x, x) l = Limit(f, x, oo) # limit() breaks on the contained Integral. assert l.doit(deep=False) == l def test_issue_2929(): assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0 def test_issue_3792(): assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half) assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1)) assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1) def test_issue_4090(): assert limit(1/(x + 3), x, 2) == Rational(1, 5) assert limit(1/(x + pi), x, 2) == S.One/(2 + pi) assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7 assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi) def test_issue_4547(): assert limit(cot(x), x, 0, dir='+') is oo assert limit(cot(x), x, pi/2, dir='+') == 0 def test_issue_5164(): assert limit(x**0.5, x, oo) == oo**0.5 is oo assert limit(x**0.5, x, 16) == S(16)**0.5 assert limit(x**0.5, x, 0) == 0 assert limit(x**(-0.5), x, oo) == 0 assert limit(x**(-0.5), x, 4) == S(4)**(-0.5) def test_issue_5383(): func = (1.0 * 1 + 1.0 * x)**(1.0 * 1 / x) assert limit(func, x, 0) == E def test_issue_14793(): expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \ log(factorial(x)) + S(1)/(12*x))*x**3 assert limit(expr, x, oo) == S(1)/360 def test_issue_5183(): # using list(...) so py.test can recalculate values tests = list(product([x, -x], [-1, 1], [2, 3, S.Half, Rational(2, 3)], ['-', '+'])) results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo, 0, 0, 0, 0, 0, 0, 0, 0, oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), 0, 0, 0, 0, 0, 0, 0, 0) assert len(tests) == len(results) for i, (args, res) in enumerate(zip(tests, results)): y, s, e, d = args eq = y**(s*e) try: assert limit(eq, x, 0, dir=d) == res except AssertionError: if 0: # change to 1 if you want to see the failing tests print() print(i, res, eq, d, limit(eq, x, 0, dir=d)) else: assert None def test_issue_5184(): assert limit(sin(x)/x, x, oo) == 0 assert limit(atan(x), x, oo) == pi/2 assert limit(gamma(x), x, oo) is oo assert limit(cos(x)/x, x, oo) == 0 assert limit(gamma(x), x, S.Half) == sqrt(pi) r = Symbol('r', real=True) assert limit(r*sin(1/r), r, 0) == 0 def test_issue_5229(): assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0 def test_issue_4546(): # using list(...) so py.test can recalculate values tests = list(product([cot, tan], [-pi/2, 0, pi/2, pi, pi*Rational(3, 2)], ['-', '+'])) results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0, oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo) assert len(tests) == len(results) for i, (args, res) in enumerate(zip(tests, results)): f, l, d = args eq = f(x) try: assert limit(eq, x, l, dir=d) == res except AssertionError: if 0: # change to 1 if you want to see the failing tests print() print(i, res, eq, l, d, limit(eq, x, l, dir=d)) else: assert None def test_issue_3934(): assert limit((1 + x**log(3))**(1/x), x, 0) == 1 assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5 def test_calculate_series(): # needs gruntz calculate_series to go to n = 32 assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1 # needs gruntz calculate_series to go to n = 128 assert limit(x**101.1/(1 + x**101.1), x, oo) == 1 def test_issue_5955(): assert limit((x**16)/(1 + x**16), x, oo) == 1 assert limit((x**100)/(1 + x**100), x, oo) == 1 assert limit((x**1885)/(1 + x**1885), x, oo) == 1 assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1 def test_newissue(): assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1 def test_extended_real_line(): assert limit(x - oo, x, oo) == Limit(x - oo, x, oo) assert limit(1/(x + sin(x)) - oo, x, 0) == Limit(1/(x + sin(x)) - oo, x, 0) assert limit(oo/x, x, oo) == Limit(oo/x, x, oo) assert limit(x - oo + 1/x, x, oo) == Limit(x - oo + 1/x, x, oo) @XFAIL def test_order_oo(): x = Symbol('x', positive=True) assert Order(x)*oo != Order(1, x) assert limit(oo/(x**2 - 4), x, oo) is oo def test_issue_5436(): raises(NotImplementedError, lambda: limit(exp(x*y), x, oo)) raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo)) def test_Limit_dir(): raises(TypeError, lambda: Limit(x, x, 0, dir=0)) raises(ValueError, lambda: Limit(x, x, 0, dir='0')) def test_polynomial(): assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1 assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1 def test_rational(): assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z) assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z) def test_issue_5740(): assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z) def test_issue_6366(): n = Symbol('n', integer=True, positive=True) r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1) assert limit(r, x, 1).cancel() == n/2 def test_factorial(): f = factorial(x) assert limit(f, x, oo) is oo assert limit(x/f, x, oo) == 0 # see Stirling's approximation: # https://en.wikipedia.org/wiki/Stirling's_approximation assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1 assert limit(f, x, -oo) == factorial(-oo) def test_issue_6560(): e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) + 35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1))) assert limit(e, y, oo) == 5*x**3/4 + 3*x**2/4 - 3*x/4 - Rational(1, 4) @XFAIL def test_issue_5172(): n = Symbol('n') r = Symbol('r', positive=True) c = Symbol('c') p = Symbol('p', positive=True) m = Symbol('m', negative=True) expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c + (r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n) expr = expr.subs(c, c + 1) raises(NotImplementedError, lambda: limit(expr, n, oo)) assert limit(expr.subs(c, m), n, oo) == 1 assert limit(expr.subs(c, p), n, oo).simplify() == \ (2**(p + 1) + r - 1)/(r + 1)**(p + 1) def test_issue_7088(): a = Symbol('a') assert limit(sqrt(x/(x + a)), x, oo) == 1 def test_branch_cuts(): assert limit(asin(I*x + 2), x, 0) == pi - asin(2) assert limit(asin(I*x + 2), x, 0, '-') == asin(2) assert limit(asin(I*x - 2), x, 0) == -asin(2) assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2) assert limit(acos(I*x + 2), x, 0) == -acos(2) assert limit(acos(I*x + 2), x, 0, '-') == acos(2) assert limit(acos(I*x - 2), x, 0) == acos(-2) assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2) assert limit(atan(x + 2*I), x, 0) == I*atanh(2) assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2) assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2) assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2) assert limit(atan(1/x), x, 0) == pi/2 assert limit(atan(1/x), x, 0, '-') == -pi/2 assert limit(atan(x), x, oo) == pi/2 assert limit(atan(x), x, -oo) == -pi/2 assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2) assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2) assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2) assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2) assert limit(acot(x), x, 0) == pi/2 assert limit(acot(x), x, 0, '-') == -pi/2 assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2) assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2) assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2) assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2) assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2) assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2) assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2) assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2) assert limit(log(I*x - 1), x, 0) == I*pi assert limit(log(I*x - 1), x, 0, '-') == -I*pi assert limit(log(-I*x - 1), x, 0) == -I*pi assert limit(log(-I*x - 1), x, 0, '-') == I*pi assert limit(sqrt(I*x - 1), x, 0) == I assert limit(sqrt(I*x - 1), x, 0, '-') == -I assert limit(sqrt(-I*x - 1), x, 0) == -I assert limit(sqrt(-I*x - 1), x, 0, '-') == I assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3) assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3) assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3) assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3) def test_issue_6364(): a = Symbol('a') e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2) assert limit(e, z, 0) == 1/(cos(a)**2 - S.Half) def test_issue_4099(): a = Symbol('a') assert limit(a/x, x, 0) == oo*sign(a) assert limit(-a/x, x, 0) == -oo*sign(a) assert limit(-a*x, x, oo) == -oo*sign(a) assert limit(a*x, x, oo) == oo*sign(a) def test_issue_4503(): dx = Symbol('dx') assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \ exp(x)/(2*sqrt(exp(x) + 1)) def test_issue_8208(): assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0 def test_issue_8229(): assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0 def test_issue_8433(): d, t = symbols('d t', positive=True) assert limit(erf(1 - t/d), t, oo) == -1 def test_issue_8481(): k = Symbol('k', integer=True, nonnegative=True) lamda = Symbol('lamda', positive=True) assert limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0 def test_issue_8635_18176(): x = Symbol('x', real=True) k = Symbol('k', positive=True) assert limit(x**n - x**(n - 0), x, oo) == 0 assert limit(x**n - x**(n - 5), x, oo) == oo assert limit(x**n - x**(n - 2.5), x, oo) == oo assert limit(x**n - x**(n - k - 1), x, oo) == oo x = Symbol('x', positive=True) assert limit(x**n - x**(n - 1), x, oo) == oo assert limit(x**n - x**(n + 2), x, oo) == -oo def test_issue_8730(): assert limit(subfactorial(x), x, oo) is oo def test_issue_9252(): n = Symbol('n', integer=True) c = Symbol('c', positive=True) assert limit((log(n))**(n/log(n)) / (1 + c)**n, n, oo) == 0 # limit should depend on the value of c raises(NotImplementedError, lambda: limit((log(n))**(n/log(n)) / c**n, n, oo)) def test_issue_9558(): assert limit(sin(x)**15, x, 0, '-') == 0 def test_issue_10801(): # make sure limits work with binomial assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi def test_issue_10976(): s, x = symbols('s x', real=True) assert limit(erf(s*x)/erf(s), s, 0) == x def test_issue_9041(): assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1 def test_issue_9205(): x, y, a = symbols('x, y, a') assert Limit(x, x, a).free_symbols == {a} assert Limit(x, x, a, '-').free_symbols == {a} assert Limit(x + y, x + y, a).free_symbols == {a} assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a} def test_issue_9471(): assert limit(((27**(log(n,3)))/n**3),n,oo) == 1 assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27 def test_issue_11496(): assert limit(erfc(log(1/x)), x, oo) == 2 def test_issue_11879(): assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1) def test_limit_with_Float(): k = symbols("k") assert limit(1.0 ** k, k, oo) == 1 assert limit(0.3*1.0**k, k, oo) == Rational(3, 10) def test_issue_10610(): assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3) def test_issue_6599(): assert limit((n + cos(n))/n, n, oo) == 1 def test_issue_12555(): assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2 assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo def test_issue_12769(): r, z, x = symbols('r z x', real=True) a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True) fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \ F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \ 2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b + 1) + \ 2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \ 2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r - b - r + 1) assert fx.subs(K, F0).factor(deep=True) == limit(fx, K, F0).factor(deep=True) def test_issue_13332(): assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) * (6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36) def test_issue_12564(): assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo assert limit(((x + cos(x))**2).expand(), x, oo) is oo assert limit(((x + sin(x))**2).expand(), x, oo) is oo assert limit(((x + cos(x))**2).expand(), x, -oo) is oo assert limit(((x + sin(x))**2).expand(), x, -oo) is oo def test_issue_14456(): raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit()) raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit()) def test_issue_14411(): assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo def test_issue_13382(): assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2 def test_issue_13403(): assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x, oo) == 1 def test_issue_13416(): assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x, oo) == 1 def test_issue_13462(): assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x**3/24 - x**2/8 + x/12 def test_issue_13750(): a = Symbol('a') assert limit(erf(a - x), x, oo) == -1 assert limit(erf(sqrt(x) - x), x, oo) == -1 def test_issue_14514(): assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1 def test_issues_14525(): assert limit(sin(x)**2 - cos(x) + tan(x)*csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(sin(x)**2 - cos(x) + sin(x)*cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(cot(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(cos(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One) assert limit(sin(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One) assert limit(cos(x)**2 - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One) assert limit(tan(x)**2 + sin(x)**2 - cos(x), x, oo) == AccumBounds(-S.One, S.Infinity) def test_issue_14574(): assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0 def test_issue_10102(): assert limit(fresnels(x), x, oo) == S.Half assert limit(3 + fresnels(x), x, oo) == 3 + S.Half assert limit(5*fresnels(x), x, oo) == Rational(5, 2) assert limit(fresnelc(x), x, oo) == S.Half assert limit(fresnels(x), x, -oo) == Rational(-1, 2) assert limit(4*fresnelc(x), x, -oo) == -2 def test_issue_14377(): raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo)) def test_issue_15146(): e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \ 2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3) assert limit(e, x, oo) == S(1)/3 def test_issue_15202(): e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1) assert limit(e, x, oo) == exp(1) e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x) assert limit(e, x, oo) == 10 def test_issue_15282(): assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000 def test_issue_15984(): assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-') == 0 def test_issue_13571(): assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1 def test_issue_13575(): assert limit(acos(erfi(x)), x, 1) == acos(erfi(S.One)) def test_issue_17325(): assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1 assert Limit(x**2, x, 0, dir="+-").doit() == 0 assert Limit(1/x**2, x, 0, dir="+-").doit() is oo assert Limit(1/x, x, 0, dir="+-").doit() is zoo def test_issue_10978(): assert LambertW(x).limit(x, 0) == 0 def test_issue_14313_comment(): assert limit(floor(n/2), n, oo) is oo @XFAIL def test_issue_15323(): d = ((1 - 1/x)**x).diff(x) assert limit(d, x, 1, dir='+') == 1 def test_issue_12571(): assert limit(-LambertW(-log(x))/log(x), x, 1) == 1 def test_issue_14590(): assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1) def test_issue_14393(): a, b = symbols('a b') assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a + b)/a def test_issue_14556(): assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1) def test_issue_14811(): assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo def test_issue_14874(): assert limit(besselk(0, x), x, oo) == 0 def test_issue_16222(): assert limit(exp(x), x, 1000000000) == exp(1000000000) def test_issue_16714(): assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1)) def test_issue_16722(): z = symbols('z', positive=True) assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1) z = symbols('z', positive=True, integer=True) assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1) def test_issue_17431(): assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) * (n + 2) * factorial(n) / (n + 1), n, oo) == 0 assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1)) , n, oo) == 0 assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0 def test_issue_17671(): assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma def test_issue_17751(): a, b, c, x = symbols('a b c x', positive=True) assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2) def test_issue_17792(): assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi) def test_issue_18118(): assert limit(sign(sin(x)), x, 0, "-") == -1 assert limit(sign(sin(x)), x, 0, "+") == 1 def test_issue_18306(): assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1 def test_issue_18378(): assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3 def test_issue_18399(): assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo assert limit((-x)**x, x, oo) is zoo def test_issue_18442(): assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') def test_issue_18452(): assert limit(abs(log(x))**x, x, 0) == 1 assert limit(abs(log(x))**x, x, 0, "-") == 1 def test_issue_18473(): assert limit(sin(x)**(1/x), x, oo) == Limit(sin(x)**(1/x), x, oo, dir='-') assert limit(cos(x)**(1/x), x, oo) == Limit(cos(x)**(1/x), x, oo, dir='-') assert limit(tan(x)**(1/x), x, oo) == Limit(tan(x)**(1/x), x, oo, dir='-') assert limit((cos(x) + 2)**(1/x), x, oo) == 1 assert limit((sin(x) + 10)**(1/x), x, oo) == 1 assert limit((cos(x) - 2)**(1/x), x, oo) == Limit((cos(x) - 2)**(1/x), x, oo, dir='-') assert limit((cos(x) + 1)**(1/x), x, oo) == AccumBounds(0, 1) assert limit((tan(x)**2)**(2/x) , x, oo) == AccumBounds(0, oo) assert limit((sin(x)**2)**(1/x), x, oo) == AccumBounds(0, 1) def test_issue_18482(): assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1) def test_issue_18508(): assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2) assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2) assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2) def test_issue_18521(): raises(NotImplementedError, lambda: limit(exp((2 - n) * x), x, oo)) def test_issue_18969(): a, b = symbols('a b', positive=True) assert limit(LambertW(a), a, b) == LambertW(b) assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b)) def test_issue_18992(): assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1) def test_issue_19067(): x = Symbol('x') assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1 def test_issue_19586(): assert limit(x**(2**x*3**(-x)), x, oo) == 1 def test_issue_13715(): n = Symbol('n') p = Symbol('p', zero=True) assert limit(n + p, n, 0) == 0 def test_issue_15055(): assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1 def test_issue_16708(): m, vi = symbols('m vi', positive=True) B, ti, d = symbols('B ti d') assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi def test_issue_19453(): beta = Symbol("beta", positive=True) h = Symbol("h", positive=True) m = Symbol("m", positive=True) w = Symbol("omega", positive=True) g = Symbol("g", positive=True) e = exp(1) q = 3*h**2*beta*g*e**(0.5*h*beta*w) p = m**2*w**2 s = e**(h*beta*w) - 1 Z = -q/(4*p*s) - q/(2*p*s**2) - q*(e**(h*beta*w) + 1)/(2*p*s**3)\ + e**(0.5*h*beta*w)/s E = -diff(log(Z), beta) assert limit(E - 0.5*h*w, beta, oo) == 0 assert limit(E.simplify() - 0.5*h*w, beta, oo) == 0 def test_issue_19739(): assert limit((-S(1)/4)**x, x, oo) == 0 def test_issue_19766(): assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2 def test_issue_19770(): m = Symbol('m') # the result is not 0 for non-real m assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-') m = Symbol('m', real=True) # can be improved to give the correct result 0 assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-') m = Symbol('m', nonzero=True) assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1) assert limit(cos(m*x)/x, x, oo) == 0 def test_issue_7535(): assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+') assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1) assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo) assert oo*(1/sin(oo)) == AccumBounds(-oo, oo) assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo) assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo) def test_issue_20365(): assert limit(((x + 1)**(1/x) - E)/x, x, 0) == -E/2 def test_issue_21031(): assert limit(((1 + x)**(1/x) - (1 + 2*x)**(1/(2*x)))/asin(x), x, 0) == E/2 def test_issue_21038(): assert limit(sin(pi*x)/(3*x - 12), x, 4) == pi/3 def test_issue_20578(): expr = abs(x) * sin(1/x) assert limit(expr,x,0,'+') == 0 assert limit(expr,x,0,'-') == 0 assert limit(expr,x,0,'+-') == 0 def test_issue_21415(): exp = (x-1)*cos(1/(x-1)) assert exp.limit(x,1) == 0 assert exp.expand().limit(x,1) == 0 def test_issue_21530(): assert limit(sinh(n + 1)/sinh(n), n, oo) == E def test_issue_21550(): r = (sqrt(5) - 1)/2 assert limit((x - r)/(x**2 + x - 1), x, r) == sqrt(5)/5 def test_issue_21661(): out = limit((x**(x + 1) * (log(x) + 1) + 1) / x, x, 11) assert out == S(3138428376722)/11 + 285311670611*log(11) def test_issue_21701(): assert limit((besselj(z, x)/x**z).subs(z, 7), x, 0) == S(1)/645120 def test_issue_21721(): a = Symbol('a', real=True) I = integrate(1/(pi*(1 + (x - a)**2)), x) assert I.limit(x, oo) == S.Half def test_issue_21756(): term = (1 - exp(-2*I*pi*z))/(1 - exp(-2*I*pi*z/5)) assert term.limit(z, 0) == 5 assert re(term).limit(z, 0) == 5 def test_issue_21785(): a = Symbol('a') assert sqrt((-a**2 + x**2)/(1 - x**2)).limit(a, 1, '-') == I def test_issue_22181(): assert limit((-1)**x * 2**(-x), x, oo) == 0 def test_issue_23231(): f = (2**x - 2**(-x))/(2**x + 2**(-x)) assert limit(f, x, -oo) == -1
466ff1f7801f885d7ebd9b167196058aff88f88fd61741aece5e602781cc532b
from sympy.core.function import diff from sympy.core.numbers import (E, I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, conjugate, im, re, sign) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, cos, sin, atan2, atan) from sympy.integrals.integrals import integrate from sympy.matrices.dense import Matrix from sympy.simplify.trigsimp import trigsimp from sympy.algebras.quaternion import Quaternion from sympy.testing.pytest import raises w, x, y, z = symbols('w:z') phi = symbols('phi') def test_quaternion_construction(): q = Quaternion(w, x, y, z) assert q + q == Quaternion(2*w, 2*x, 2*y, 2*z) q2 = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*Rational(2, 3)) assert q2 == Quaternion(S.Half, S.Half, S.Half, S.Half) M = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) q3 = trigsimp(Quaternion.from_rotation_matrix(M)) assert q3 == Quaternion(sqrt(2)*sqrt(cos(phi) + 1)/2, 0, 0, sqrt(2 - 2*cos(phi))*sign(sin(phi))/2) nc = Symbol('nc', commutative=False) raises(ValueError, lambda: Quaternion(w, x, nc, z)) def test_quaternion_axis_angle(): test_data = [ # axis, angle, expected_quaternion ((1, 0, 0), 0, (1, 0, 0, 0)), ((1, 0, 0), pi/2, (sqrt(2)/2, sqrt(2)/2, 0, 0)), ((0, 1, 0), pi/2, (sqrt(2)/2, 0, sqrt(2)/2, 0)), ((0, 0, 1), pi/2, (sqrt(2)/2, 0, 0, sqrt(2)/2)), ((1, 0, 0), pi, (0, 1, 0, 0)), ((0, 1, 0), pi, (0, 0, 1, 0)), ((0, 0, 1), pi, (0, 0, 0, 1)), ((1, 1, 1), pi, (0, 1/sqrt(3),1/sqrt(3),1/sqrt(3))), ((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*2/3, (S.Half, S.Half, S.Half, S.Half)) ] for axis, angle, expected in test_data: assert Quaternion.from_axis_angle(axis, angle) == Quaternion(*expected) def test_quaternion_axis_angle_simplification(): result = Quaternion.from_axis_angle((1, 2, 3), asin(4)) assert result.a == cos(asin(4)/2) assert result.b == sqrt(14)*sin(asin(4)/2)/14 assert result.c == sqrt(14)*sin(asin(4)/2)/7 assert result.d == 3*sqrt(14)*sin(asin(4)/2)/14 def test_quaternion_complex_real_addition(): a = symbols("a", complex=True) b = symbols("b", real=True) # This symbol is not complex: c = symbols("c", commutative=False) q = Quaternion(w, x, y, z) assert a + q == Quaternion(w + re(a), x + im(a), y, z) assert 1 + q == Quaternion(1 + w, x, y, z) assert I + q == Quaternion(w, 1 + x, y, z) assert b + q == Quaternion(w + b, x, y, z) raises(ValueError, lambda: c + q) raises(ValueError, lambda: q * c) raises(ValueError, lambda: c * q) assert -q == Quaternion(-w, -x, -y, -z) q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) q2 = Quaternion(1, 4, 7, 8) assert q1 + (2 + 3*I) == Quaternion(5 + 7*I, 2 + 5*I, 0, 7 + 8*I) assert q2 + (2 + 3*I) == Quaternion(3, 7, 7, 8) assert q1 * (2 + 3*I) == \ Quaternion((2 + 3*I)*(3 + 4*I), (2 + 3*I)*(2 + 5*I), 0, (2 + 3*I)*(7 + 8*I)) assert q2 * (2 + 3*I) == Quaternion(-10, 11, 38, -5) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert q1 + q0 == q1 assert q1 - q0 == q1 assert q1 - q1 == q0 def test_quaternion_evalf(): assert Quaternion(sqrt(2), 0, 0, sqrt(3)).evalf() == Quaternion(sqrt(2).evalf(), 0, 0, sqrt(3).evalf()) assert Quaternion(1/sqrt(2), 0, 0, 1/sqrt(2)).evalf() == Quaternion((1/sqrt(2)).evalf(), 0, 0, (1/sqrt(2)).evalf()) def test_quaternion_functions(): q = Quaternion(w, x, y, z) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert conjugate(q) == Quaternion(w, -x, -y, -z) assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) assert q.normalize() == Quaternion(w, x, y, z) / sqrt(w**2 + x**2 + y**2 + z**2) assert q.inverse() == Quaternion(w, -x, -y, -z) / (w**2 + x**2 + y**2 + z**2) assert q.inverse() == q.pow(-1) raises(ValueError, lambda: q0.inverse()) assert q.pow(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) assert q**(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) assert q1.pow(-2) == Quaternion(Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) assert q1**(-2) == Quaternion(Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) assert q1.pow(-0.5) == NotImplemented raises(TypeError, lambda: q1**(-0.5)) assert q1.exp() == \ Quaternion(E * cos(sqrt(29)), 2 * sqrt(29) * E * sin(sqrt(29)) / 29, 3 * sqrt(29) * E * sin(sqrt(29)) / 29, 4 * sqrt(29) * E * sin(sqrt(29)) / 29) assert q1._ln() == \ Quaternion(log(sqrt(30)), 2 * sqrt(29) * acos(sqrt(30)/30) / 29, 3 * sqrt(29) * acos(sqrt(30)/30) / 29, 4 * sqrt(29) * acos(sqrt(30)/30) / 29) assert q1.pow_cos_sin(2) == \ Quaternion(30 * cos(2 * acos(sqrt(30)/30)), 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) assert integrate(Quaternion(x, x, x, x), x) == \ Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) assert Quaternion.rotate_point((1, 1, 1), q1) == (S.One / 5, 1, S(7) / 5) n = Symbol('n') raises(TypeError, lambda: q1**n) n = Symbol('n', integer=True) raises(TypeError, lambda: q1**n) assert Quaternion(22, 23, 55, 8).scalar_part() == 22 assert Quaternion(w, x, y, z).scalar_part() == w assert Quaternion(22, 23, 55, 8).vector_part() == Quaternion(0, 23, 55, 8) assert Quaternion(w, x, y, z).vector_part() == Quaternion(0, x, y, z) assert q1.axis() == Quaternion(0, 2*sqrt(29)/29, 3*sqrt(29)/29, 4*sqrt(29)/29) assert q1.axis().pow(2) == Quaternion(-1, 0, 0, 0) assert q0.axis().scalar_part() == 0 assert q.axis() == Quaternion(0, x/sqrt(x**2 + y**2 + z**2), y/sqrt(x**2 + y**2 + z**2), z/sqrt(x**2 + y**2 + z**2)) assert q0.is_pure() == True assert q1.is_pure() == False assert Quaternion(0, 0, 0, 3).is_pure() == True assert Quaternion(0, 2, 10, 3).is_pure() == True assert Quaternion(w, 2, 10, 3).is_pure() == None assert q1.angle() == atan(sqrt(29)) assert q.angle() == atan2(sqrt(x**2 + y**2 + z**2), w) assert Quaternion.arc_coplanar(q1, Quaternion(2, 4, 6, 8)) == True assert Quaternion.arc_coplanar(q1, Quaternion(1, -2, -3, -4)) == True assert Quaternion.arc_coplanar(q1, Quaternion(1, 8, 12, 16)) == True assert Quaternion.arc_coplanar(q1, Quaternion(1, 2, 3, 4)) == True assert Quaternion.arc_coplanar(q1, Quaternion(w, 4, 6, 8)) == True assert Quaternion.arc_coplanar(q1, Quaternion(2, 7, 4, 1)) == False assert Quaternion.arc_coplanar(q1, Quaternion(w, x, y, z)) == None raises(ValueError, lambda: Quaternion.arc_coplanar(q1, q0)) assert Quaternion.vector_coplanar(Quaternion(0, 8, 12, 16), Quaternion(0, 4, 6, 8), Quaternion(0, 2, 3, 4)) == True assert Quaternion.vector_coplanar(Quaternion(0, 0, 0, 0), Quaternion(0, 4, 6, 8), Quaternion(0, 2, 3, 4)) == True assert Quaternion.vector_coplanar(Quaternion(0, 8, 2, 6), Quaternion(0, 1, 6, 6), Quaternion(0, 0, 3, 4)) == False assert Quaternion.vector_coplanar(Quaternion(0, 1, 3, 4), Quaternion(0, 4, w, 6), Quaternion(0, 6, 8, 1)) == None raises(ValueError, lambda: Quaternion.vector_coplanar(q0, Quaternion(0, 4, 6, 8), q1)) assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 4, 6)) == True assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 2, 6)) == False assert Quaternion(0, 1, 2, 3).parallel(Quaternion(w, x, y, 6)) == None raises(ValueError, lambda: q0.parallel(q1)) assert Quaternion(0, 1, 2, 3).orthogonal(Quaternion(0, -2, 1, 0)) == True assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(0, 2, 2, 6)) == False assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(w, x, y, 6)) == None raises(ValueError, lambda: q0.orthogonal(q1)) assert q1.index_vector() == Quaternion(0, 2*sqrt(870)/29, 3*sqrt(870)/29, 4*sqrt(870)/29) assert Quaternion(0, 3, 9, 4).index_vector() == Quaternion(0, 3, 9, 4) assert Quaternion(4, 3, 9, 4).mensor() == log(sqrt(122)) assert Quaternion(3, 3, 0, 2).mensor() == log(sqrt(22)) assert q0.is_zero_quaternion() == True assert q1.is_zero_quaternion() == False assert Quaternion(w, 0, 0, 0).is_zero_quaternion() == None def test_quaternion_conversions(): q1 = Quaternion(1, 2, 3, 4) assert q1.to_axis_angle() == ((2 * sqrt(29)/29, 3 * sqrt(29)/29, 4 * sqrt(29)/29), 2 * acos(sqrt(30)/30)) assert q1.to_rotation_matrix() == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], [Rational(1, 3), Rational(14, 15), Rational(2, 15)]]) assert q1.to_rotation_matrix((1, 1, 1)) == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15), Rational(4, 5)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3), S.Zero], [Rational(1, 3), Rational(14, 15), Rational(2, 15), Rational(-2, 5)], [S.Zero, S.Zero, S.Zero, S.One]]) theta = symbols("theta", real=True) q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) assert trigsimp(q2.to_rotation_matrix()) == Matrix([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]) assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))), 2*acos(cos(theta/2))) assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([ [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1], [sin(theta), cos(theta), 0, -sin(theta) - cos(theta) + 1], [0, 0, 1, 0], [0, 0, 0, 1]]) def test_quaternion_rotation_iss1593(): """ There was a sign mistake in the definition, of the rotation matrix. This tests that particular sign mistake. See issue 1593 for reference. See wikipedia https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix for the correct definition """ q = Quaternion(cos(phi/2), sin(phi/2), 0, 0) assert(trigsimp(q.to_rotation_matrix()) == Matrix([ [1, 0, 0], [0, cos(phi), -sin(phi)], [0, sin(phi), cos(phi)]])) def test_quaternion_multiplication(): q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) q2 = Quaternion(1, 2, 3, 5) q3 = Quaternion(1, 1, 1, y) assert Quaternion._generic_mul(4, 1) == 4 assert Quaternion._generic_mul(4, q1) == Quaternion(12 + 16*I, 8 + 20*I, 0, 28 + 32*I) assert q2.mul(2) == Quaternion(2, 4, 6, 10) assert q2.mul(q3) == Quaternion(-5*y - 4, 3*y - 2, 9 - 2*y, y + 4) assert q2.mul(q3) == q2*q3 z = symbols('z', complex=True) z_quat = Quaternion(re(z), im(z), 0, 0) q = Quaternion(*symbols('q:4', real=True)) assert z * q == z_quat * q assert q * z == q * z_quat def test_issue_16318(): #for rtruediv q0 = Quaternion(0, 0, 0, 0) raises(ValueError, lambda: 1/q0) #for rotate_point q = Quaternion(1, 2, 3, 4) (axis, angle) = q.to_axis_angle() assert Quaternion.rotate_point((1, 1, 1), (axis, angle)) == (S.One / 5, 1, S(7) / 5) #test for to_axis_angle q = Quaternion(-1, 1, 1, 1) axis = (-sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3) angle = 2*pi/3 assert (axis, angle) == q.to_axis_angle()
dc17a90abea779dfb80bfde67b8cd272ed3a1d71bd431fdd041c48a625c0bf2e
from sympy.core import Lambda, Symbol, symbols from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin from sympy.diffgeom import (Manifold, Patch, CoordSystem, Commutator, Differential, TensorProduct, WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative, covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st, metric_to_Christoffel_2nd, metric_to_Riemann_components, metric_to_Ricci_components, intcurve_diffequ, intcurve_series) from sympy.simplify import trigsimp, simplify from sympy.functions import sqrt, atan2, sin from sympy.matrices import Matrix from sympy.testing.pytest import raises, nocache_fail from sympy.testing.pytest import warns_deprecated_sympy TP = TensorProduct def test_coordsys_transform(): # test inverse transforms p, q, r, s = symbols('p q r s') rel = {('first', 'second'): [(p, q), (q, -p)]} R2_pq = CoordSystem('first', R2_origin, [p, q], rel) R2_rs = CoordSystem('second', R2_origin, [r, s], rel) r, s = R2_rs.symbols assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]]) # inverse transform impossible case a, b = symbols('a b', positive=True) rel = {('first', 'second'): [(a,), (-a,)]} R2_a = CoordSystem('first', R2_origin, [a], rel) R2_b = CoordSystem('second', R2_origin, [b], rel) # This transformation is uninvertible because there is no positive a, b satisfying a = -b with raises(NotImplementedError): R2_b.transform(R2_a) # inverse transform ambiguous case c, d = symbols('c d') rel = {('first', 'second'): [(c,), (c**2,)]} R2_c = CoordSystem('first', R2_origin, [c], rel) R2_d = CoordSystem('second', R2_origin, [d], rel) # The transform method should throw if it finds multiple inverses for a coordinate transformation. with raises(ValueError): R2_d.transform(R2_c) # test indirect transformation a, b, c, d, e, f = symbols('a, b, c, d, e, f') rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)], ('C2', 'C3'): [(c, d), (3*c, 2*d)]} C1 = CoordSystem('C1', R2_origin, (a, b), rel) C2 = CoordSystem('C2', R2_origin, (c, d), rel) C3 = CoordSystem('C3', R2_origin, (e, f), rel) a, b = C1.symbols c, d = C2.symbols e, f = C3.symbols assert C2.transform(C1) == Matrix([c/2, d/3]) assert C1.transform(C3) == Matrix([6*a, 6*b]) assert C3.transform(C1) == Matrix([e/6, f/6]) assert C3.transform(C2) == Matrix([e/3, f/2]) a, b, c, d, e, f = symbols('a, b, c, d, e, f') rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)], ('C3', 'C2'): [(e, f), (-e - 2, 2*f)]} C1 = CoordSystem('C1', R2_origin, (a, b), rel) C2 = CoordSystem('C2', R2_origin, (c, d), rel) C3 = CoordSystem('C3', R2_origin, (e, f), rel) a, b = C1.symbols c, d = C2.symbols e, f = C3.symbols assert C2.transform(C1) == Matrix([c/2, (d - 1)/3]) assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2]) assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3]) assert C3.transform(C2) == Matrix([-e - 2, 2*f]) # old signature uses Lambda a, b, c, d, e, f = symbols('a, b, c, d, e, f') rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)), ('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))} C1 = CoordSystem('C1', R2_origin, (a, b), rel) C2 = CoordSystem('C2', R2_origin, (c, d), rel) C3 = CoordSystem('C3', R2_origin, (e, f), rel) a, b = C1.symbols c, d = C2.symbols e, f = C3.symbols assert C2.transform(C1) == Matrix([c/2, (d - 1)/3]) assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2]) assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3]) assert C3.transform(C2) == Matrix([-e - 2, 2*f]) def test_R2(): x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True) point_r = R2_r.point([x0, y0]) point_p = R2_p.point([r0, theta0]) # r**2 = x**2 + y**2 assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0 assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0 assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0 # polar->rect->polar == Id a, b = symbols('a b', positive=True) m = Matrix([[a], [b]]) #TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify) assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify) # deprecated method with warns_deprecated_sympy(): assert m == R2_p.coord_tuple_transform_to( R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify) def test_R3(): a, b, c = symbols('a b c', positive=True) m = Matrix([[a], [b], [c]]) assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify) #TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify) assert m == R3_s.transform( R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify) assert m == R3_s.transform( R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify) with warns_deprecated_sympy(): assert m == R3_c.coord_tuple_transform_to( R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify) #TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify) assert m == R3_s.coord_tuple_transform_to( R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify) assert m == R3_s.coord_tuple_transform_to( R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify) def test_CoordinateSymbol(): x, y = R2_r.symbols r, theta = R2_p.symbols assert y.rewrite(R2_p) == r*sin(theta) def test_point(): x, y = symbols('x, y') p = R2_r.point([x, y]) assert p.free_symbols == {x, y} assert p.coords(R2_r) == p.coords() == Matrix([x, y]) assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)]) def test_commutator(): assert Commutator(R2.e_x, R2.e_y) == 0 assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0 assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y c = Commutator(R2.e_x, R2.e_r) assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta) def test_differential(): xdy = R2.x*R2.dy dxdy = Differential(xdy) assert xdy.rcall(None) == xdy assert dxdy(R2.e_x, R2.e_y) == 1 assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x assert Differential(dxdy) == 0 def test_products(): assert TensorProduct( R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1 assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx assert TensorProduct( R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1 assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x assert TensorProduct( R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1 assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x assert TensorProduct( R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1 assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1 assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1 def test_lie_derivative(): assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0 assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1 assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0 assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r) assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1 assert LieDerivative( R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0 @nocache_fail def test_covar_deriv(): ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) cvd = BaseCovarDerivativeOp(R2_r, 0, ch) assert cvd(R2.x) == 1 # This line fails if the cache is disabled: assert cvd(R2.x*R2.e_x) == R2.e_x cvd = CovarDerivativeOp(R2.x*R2.e_x, ch) assert cvd(R2.x) == R2.x assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x def test_intcurve_diffequ(): t = symbols('t') start_point = R2_r.point([1, 0]) vector_field = -R2.y*R2.e_x + R2.x*R2.e_y equations, init_cond = intcurve_diffequ(vector_field, t, start_point) assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]' assert str(init_cond) == '[f_0(0) - 1, f_1(0)]' equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p) assert str( equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]' assert str(init_cond) == '[f_0(0) - 1, f_1(0)]' def test_helpers_and_coordinate_dependent(): one_form = R2.dr + R2.dx two_form = Differential(R2.x*R2.dr + R2.r*R2.dx) three_form = Differential( R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr)) metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy) metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr) misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr misform_b = R2.dr**4 misform_c = R2.dx*R2.dy twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy) twoform_not_TP = WedgeProduct(R2.dx, R2.dy) one_vector = R2.e_x + R2.e_y two_vector = TensorProduct(R2.e_x, R2.e_y) three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x) two_wp = WedgeProduct(R2.e_x,R2.e_y) assert covariant_order(one_form) == 1 assert covariant_order(two_form) == 2 assert covariant_order(three_form) == 3 assert covariant_order(two_form + metric) == 2 assert covariant_order(two_form + metric_ambig) == 2 assert covariant_order(two_form + twoform_not_sym) == 2 assert covariant_order(two_form + twoform_not_TP) == 2 assert contravariant_order(one_vector) == 1 assert contravariant_order(two_vector) == 2 assert contravariant_order(three_vector) == 3 assert contravariant_order(two_vector + two_wp) == 2 raises(ValueError, lambda: covariant_order(misform_a)) raises(ValueError, lambda: covariant_order(misform_b)) raises(ValueError, lambda: covariant_order(misform_c)) assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]]) assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]]) assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]]) raises(ValueError, lambda: twoform_to_matrix(one_form)) raises(ValueError, lambda: twoform_to_matrix(three_form)) raises(ValueError, lambda: twoform_to_matrix(metric_ambig)) raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym)) raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym)) raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym)) raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym)) def test_correct_arguments(): raises(ValueError, lambda: R2.e_x(R2.e_x)) raises(ValueError, lambda: R2.e_x(R2.dx)) raises(ValueError, lambda: Commutator(R2.e_x, R2.x)) raises(ValueError, lambda: Commutator(R2.dx, R2.e_x)) raises(ValueError, lambda: Differential(Differential(R2.e_x))) raises(ValueError, lambda: R2.dx(R2.x)) raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx)) raises(ValueError, lambda: LieDerivative(R2.x, R2.dx)) raises(ValueError, lambda: CovarDerivativeOp(R2.dx, [])) raises(ValueError, lambda: CovarDerivativeOp(R2.x, [])) a = Symbol('a') raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2]))) raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2]))) raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2]))) raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2]))) raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx)) raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx)) raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y)) raises(ValueError, lambda: covariant_order(R2.dx*R2.dy)) def test_simplify(): x, y = R2_r.coord_functions() dx, dy = R2_r.base_oneforms() ex, ey = R2_r.base_vectors() assert simplify(x) == x assert simplify(x*y) == x*y assert simplify(dx*dy) == dx*dy assert simplify(ex*ey) == ex*ey assert ((1-x)*dx)/(1-x)**2 == dx/(1-x) def test_issue_17917(): X = R2.x*R2.e_x - R2.y*R2.e_y Y = (R2.x**2 + R2.y**2)*R2.e_x - R2.x*R2.y*R2.e_y assert LieDerivative(X, Y).expand() == ( R2.x**2*R2.e_x - 3*R2.y**2*R2.e_x - R2.x*R2.y*R2.e_y) def test_deprecations(): m = Manifold('M', 2) p = Patch('P', m) with warns_deprecated_sympy(): CoordSystem('Car2d', p, names=['x', 'y']) with warns_deprecated_sympy(): c = CoordSystem('Car2d', p, ['x', 'y']) with warns_deprecated_sympy(): list(m.patches) with warns_deprecated_sympy(): list(c.transforms)
6bf18a7f716978d37ccdf31cf95f00692ad0b44235a222df24e728d952a248a2
from sympy.core.symbol import symbols from sympy.codegen.abstract_nodes import List def test_List(): l = List(2, 3, 4) assert l == List(2, 3, 4) assert str(l) == "[2, 3, 4]" x, y, z = symbols('x y z') l = List(x**2,y**3,z**4) # contrary to python's built-in list, we can call e.g. "replace" on List. m = l.replace(lambda arg: arg.is_Pow and arg.exp>2, lambda p: p.base-p.exp) assert m == [x**2, y-3, z-4] hash(m)
b16fef8b0db174ef4a96a7f7d71dd89587069618118f9d875752459b0ae0b5be
""" This module defines base class for handlers and some core handlers: ``Q.commutative`` and ``Q.is_true``. """ from sympy.assumptions import Q, ask, AppliedPredicate from sympy.core import Basic, Symbol from sympy.core.logic import _fuzzy_group from sympy.core.numbers import NaN, Number from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts, Equivalent, Implies, Not, Or) from sympy.utilities.exceptions import sympy_deprecation_warning from ..predicates.common import CommutativePredicate, IsTruePredicate class AskHandler: """Base class that all Ask Handlers must inherit.""" def __new__(cls, *args, **kwargs): sympy_deprecation_warning( """ The AskHandler system is deprecated. The AskHandler class should be replaced with the multipledispatch handler of Predicate """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) return super().__new__(cls, *args, **kwargs) class CommonHandler(AskHandler): # Deprecated """Defines some useful methods common to most Handlers. """ @staticmethod def AlwaysTrue(expr, assumptions): return True @staticmethod def AlwaysFalse(expr, assumptions): return False @staticmethod def AlwaysNone(expr, assumptions): return None NaN = AlwaysFalse # CommutativePredicate @CommutativePredicate.register(Symbol) def _(expr, assumptions): """Objects are expected to be commutative unless otherwise stated""" assumps = conjuncts(assumptions) if expr.is_commutative is not None: return expr.is_commutative and not ~Q.commutative(expr) in assumps if Q.commutative(expr) in assumps: return True elif ~Q.commutative(expr) in assumps: return False return True @CommutativePredicate.register(Basic) def _(expr, assumptions): for arg in expr.args: if not ask(Q.commutative(arg), assumptions): return False return True @CommutativePredicate.register(Number) def _(expr, assumptions): return True @CommutativePredicate.register(NaN) def _(expr, assumptions): return True # IsTruePredicate @IsTruePredicate.register(bool) def _(expr, assumptions): return expr @IsTruePredicate.register(BooleanTrue) def _(expr, assumptions): return True @IsTruePredicate.register(BooleanFalse) def _(expr, assumptions): return False @IsTruePredicate.register(AppliedPredicate) def _(expr, assumptions): return ask(expr, assumptions) @IsTruePredicate.register(Not) def _(expr, assumptions): arg = expr.args[0] if arg.is_Symbol: # symbol used as abstract boolean object return None value = ask(arg, assumptions=assumptions) if value in (True, False): return not value else: return None @IsTruePredicate.register(Or) def _(expr, assumptions): result = False for arg in expr.args: p = ask(arg, assumptions=assumptions) if p is True: return True if p is None: result = None return result @IsTruePredicate.register(And) def _(expr, assumptions): result = True for arg in expr.args: p = ask(arg, assumptions=assumptions) if p is False: return False if p is None: result = None return result @IsTruePredicate.register(Implies) def _(expr, assumptions): p, q = expr.args return ask(~p | q, assumptions=assumptions) @IsTruePredicate.register(Equivalent) def _(expr, assumptions): p, q = expr.args pt = ask(p, assumptions=assumptions) if pt is None: return None qt = ask(q, assumptions=assumptions) if qt is None: return None return pt == qt #### Helper methods def test_closed_group(expr, assumptions, key): """ Test for membership in a group with respect to the current operation. """ return _fuzzy_group( (ask(key(a), assumptions) for a in expr.args), quick_exit=True)
19d6ae936c64d6128f46be22e91a6f38c1ed0e7c950f7e31d4eca12fe3a1f077
""" This module contains query handlers responsible for Matrices queries: Square, Symmetric, Invertible etc. """ from sympy.logic.boolalg import conjuncts from sympy.assumptions import Q, ask from sympy.assumptions.handlers import test_closed_group from sympy.matrices import MatrixBase from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant, DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose, ZeroMatrix) from sympy.matrices.expressions.blockmatrix import reblock_2x2 from sympy.matrices.expressions.factorizations import Factorization from sympy.matrices.expressions.fourier import DFT from sympy.core.logic import fuzzy_and from sympy.utilities.iterables import sift from sympy.core import Basic from ..predicates.matrices import (SquarePredicate, SymmetricPredicate, InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate, FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate, LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate, RealElementsPredicate, ComplexElementsPredicate) def _Factorization(predicate, expr, assumptions): if predicate in expr.predicates: return True # SquarePredicate @SquarePredicate.register(MatrixExpr) def _(expr, assumptions): return expr.shape[0] == expr.shape[1] # SymmetricPredicate @SymmetricPredicate.register(MatMul) def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args): return True # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T: if len(mmul.args) == 2: return True return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions) @SymmetricPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.symmetric(base), assumptions) return None @SymmetricPredicate.register(MatAdd) def _(expr, assumptions): return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args) @SymmetricPredicate.register(MatrixSymbol) def _(expr, assumptions): if not expr.is_square: return False # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if Q.symmetric(expr) in conjuncts(assumptions): return True @SymmetricPredicate.register_many(OneMatrix, ZeroMatrix) def _(expr, assumptions): return ask(Q.square(expr), assumptions) @SymmetricPredicate.register_many(Inverse, Transpose) def _(expr, assumptions): return ask(Q.symmetric(expr.arg), assumptions) @SymmetricPredicate.register(MatrixSlice) def _(expr, assumptions): # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if not expr.on_diag: return None else: return ask(Q.symmetric(expr.parent), assumptions) @SymmetricPredicate.register(Identity) def _(expr, assumptions): return True # InvertiblePredicate @InvertiblePredicate.register(MatMul) def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @InvertiblePredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None if exp.is_negative == False: return ask(Q.invertible(base), assumptions) return None @InvertiblePredicate.register(MatAdd) def _(expr, assumptions): return None @InvertiblePredicate.register(MatrixSymbol) def _(expr, assumptions): if not expr.is_square: return False if Q.invertible(expr) in conjuncts(assumptions): return True @InvertiblePredicate.register_many(Identity, Inverse) def _(expr, assumptions): return True @InvertiblePredicate.register(ZeroMatrix) def _(expr, assumptions): return False @InvertiblePredicate.register(OneMatrix) def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @InvertiblePredicate.register(Transpose) def _(expr, assumptions): return ask(Q.invertible(expr.arg), assumptions) @InvertiblePredicate.register(MatrixSlice) def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.invertible(expr.parent), assumptions) @InvertiblePredicate.register(MatrixBase) def _(expr, assumptions): if not expr.is_square: return False return expr.rank() == expr.rows @InvertiblePredicate.register(MatrixExpr) def _(expr, assumptions): if not expr.is_square: return False return None @InvertiblePredicate.register(BlockMatrix) def _(expr, assumptions): if not expr.is_square: return False if expr.blockshape == (1, 1): return ask(Q.invertible(expr.blocks[0, 0]), assumptions) expr = reblock_2x2(expr) if expr.blockshape == (2, 2): [[A, B], [C, D]] = expr.blocks.tolist() if ask(Q.invertible(A), assumptions) == True: invertible = ask(Q.invertible(D - C * A.I * B), assumptions) if invertible is not None: return invertible if ask(Q.invertible(B), assumptions) == True: invertible = ask(Q.invertible(C - D * B.I * A), assumptions) if invertible is not None: return invertible if ask(Q.invertible(C), assumptions) == True: invertible = ask(Q.invertible(B - A * C.I * D), assumptions) if invertible is not None: return invertible if ask(Q.invertible(D), assumptions) == True: invertible = ask(Q.invertible(A - B * D.I * C), assumptions) if invertible is not None: return invertible return None @InvertiblePredicate.register(BlockDiagMatrix) def _(expr, assumptions): if expr.rowblocksizes != expr.colblocksizes: return None return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag]) # OrthogonalPredicate @OrthogonalPredicate.register(MatMul) def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and factor == 1): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @OrthogonalPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if int_exp: return ask(Q.orthogonal(base), assumptions) return None @OrthogonalPredicate.register(MatAdd) def _(expr, assumptions): if (len(expr.args) == 1 and ask(Q.orthogonal(expr.args[0]), assumptions)): return True @OrthogonalPredicate.register(MatrixSymbol) def _(expr, assumptions): if (not expr.is_square or ask(Q.invertible(expr), assumptions) is False): return False if Q.orthogonal(expr) in conjuncts(assumptions): return True @OrthogonalPredicate.register(Identity) def _(expr, assumptions): return True @OrthogonalPredicate.register(ZeroMatrix) def _(expr, assumptions): return False @OrthogonalPredicate.register_many(Inverse, Transpose) def _(expr, assumptions): return ask(Q.orthogonal(expr.arg), assumptions) @OrthogonalPredicate.register(MatrixSlice) def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.orthogonal(expr.parent), assumptions) @OrthogonalPredicate.register(Factorization) def _(expr, assumptions): return _Factorization(Q.orthogonal, expr, assumptions) # UnitaryPredicate @UnitaryPredicate.register(MatMul) def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and abs(factor) == 1): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @UnitaryPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if int_exp: return ask(Q.unitary(base), assumptions) return None @UnitaryPredicate.register(MatrixSymbol) def _(expr, assumptions): if (not expr.is_square or ask(Q.invertible(expr), assumptions) is False): return False if Q.unitary(expr) in conjuncts(assumptions): return True @UnitaryPredicate.register_many(Inverse, Transpose) def _(expr, assumptions): return ask(Q.unitary(expr.arg), assumptions) @UnitaryPredicate.register(MatrixSlice) def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.unitary(expr.parent), assumptions) @UnitaryPredicate.register_many(DFT, Identity) def _(expr, assumptions): return True @UnitaryPredicate.register(ZeroMatrix) def _(expr, assumptions): return False @UnitaryPredicate.register(Factorization) def _(expr, assumptions): return _Factorization(Q.unitary, expr, assumptions) # FullRankPredicate @FullRankPredicate.register(MatMul) def _(expr, assumptions): if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args): return True @FullRankPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if int_exp and ask(~Q.negative(exp), assumptions): return ask(Q.fullrank(base), assumptions) return None @FullRankPredicate.register(Identity) def _(expr, assumptions): return True @FullRankPredicate.register(ZeroMatrix) def _(expr, assumptions): return False @FullRankPredicate.register(OneMatrix) def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @FullRankPredicate.register_many(Inverse, Transpose) def _(expr, assumptions): return ask(Q.fullrank(expr.arg), assumptions) @FullRankPredicate.register(MatrixSlice) def _(expr, assumptions): if ask(Q.orthogonal(expr.parent), assumptions): return True # PositiveDefinitePredicate @PositiveDefinitePredicate.register(MatMul) def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.positive_definite(arg), assumptions) for arg in mmul.args) and factor > 0): return True if (len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T and ask(Q.fullrank(mmul.args[0]), assumptions)): return ask(Q.positive_definite( MatMul(*mmul.args[1:-1])), assumptions) @PositiveDefinitePredicate.register(MatPow) def _(expr, assumptions): # a power of a positive definite matrix is positive definite if ask(Q.positive_definite(expr.args[0]), assumptions): return True @PositiveDefinitePredicate.register(MatAdd) def _(expr, assumptions): if all(ask(Q.positive_definite(arg), assumptions) for arg in expr.args): return True @PositiveDefinitePredicate.register(MatrixSymbol) def _(expr, assumptions): if not expr.is_square: return False if Q.positive_definite(expr) in conjuncts(assumptions): return True @PositiveDefinitePredicate.register(Identity) def _(expr, assumptions): return True @PositiveDefinitePredicate.register(ZeroMatrix) def _(expr, assumptions): return False @PositiveDefinitePredicate.register(OneMatrix) def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @PositiveDefinitePredicate.register_many(Inverse, Transpose) def _(expr, assumptions): return ask(Q.positive_definite(expr.arg), assumptions) @PositiveDefinitePredicate.register(MatrixSlice) def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.positive_definite(expr.parent), assumptions) # UpperTriangularPredicate @UpperTriangularPredicate.register(MatMul) def _(expr, assumptions): factor, matrices = expr.as_coeff_matrices() if all(ask(Q.upper_triangular(m), assumptions) for m in matrices): return True @UpperTriangularPredicate.register(MatAdd) def _(expr, assumptions): if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args): return True @UpperTriangularPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.upper_triangular(base), assumptions) return None @UpperTriangularPredicate.register(MatrixSymbol) def _(expr, assumptions): if Q.upper_triangular(expr) in conjuncts(assumptions): return True @UpperTriangularPredicate.register_many(Identity, ZeroMatrix) def _(expr, assumptions): return True @UpperTriangularPredicate.register(OneMatrix) def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @UpperTriangularPredicate.register(Transpose) def _(expr, assumptions): return ask(Q.lower_triangular(expr.arg), assumptions) @UpperTriangularPredicate.register(Inverse) def _(expr, assumptions): return ask(Q.upper_triangular(expr.arg), assumptions) @UpperTriangularPredicate.register(MatrixSlice) def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.upper_triangular(expr.parent), assumptions) @UpperTriangularPredicate.register(Factorization) def _(expr, assumptions): return _Factorization(Q.upper_triangular, expr, assumptions) # LowerTriangularPredicate @LowerTriangularPredicate.register(MatMul) def _(expr, assumptions): factor, matrices = expr.as_coeff_matrices() if all(ask(Q.lower_triangular(m), assumptions) for m in matrices): return True @LowerTriangularPredicate.register(MatAdd) def _(expr, assumptions): if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args): return True @LowerTriangularPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.lower_triangular(base), assumptions) return None @LowerTriangularPredicate.register(MatrixSymbol) def _(expr, assumptions): if Q.lower_triangular(expr) in conjuncts(assumptions): return True @LowerTriangularPredicate.register_many(Identity, ZeroMatrix) def _(expr, assumptions): return True @LowerTriangularPredicate.register(OneMatrix) def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @LowerTriangularPredicate.register(Transpose) def _(expr, assumptions): return ask(Q.upper_triangular(expr.arg), assumptions) @LowerTriangularPredicate.register(Inverse) def _(expr, assumptions): return ask(Q.lower_triangular(expr.arg), assumptions) @LowerTriangularPredicate.register(MatrixSlice) def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.lower_triangular(expr.parent), assumptions) @LowerTriangularPredicate.register(Factorization) def _(expr, assumptions): return _Factorization(Q.lower_triangular, expr, assumptions) # DiagonalPredicate def _is_empty_or_1x1(expr): return expr.shape in ((0, 0), (1, 1)) @DiagonalPredicate.register(MatMul) def _(expr, assumptions): if _is_empty_or_1x1(expr): return True factor, matrices = expr.as_coeff_matrices() if all(ask(Q.diagonal(m), assumptions) for m in matrices): return True @DiagonalPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.diagonal(base), assumptions) return None @DiagonalPredicate.register(MatAdd) def _(expr, assumptions): if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args): return True @DiagonalPredicate.register(MatrixSymbol) def _(expr, assumptions): if _is_empty_or_1x1(expr): return True if Q.diagonal(expr) in conjuncts(assumptions): return True @DiagonalPredicate.register(OneMatrix) def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @DiagonalPredicate.register_many(Inverse, Transpose) def _(expr, assumptions): return ask(Q.diagonal(expr.arg), assumptions) @DiagonalPredicate.register(MatrixSlice) def _(expr, assumptions): if _is_empty_or_1x1(expr): return True if not expr.on_diag: return None else: return ask(Q.diagonal(expr.parent), assumptions) @DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix) def _(expr, assumptions): return True @DiagonalPredicate.register(Factorization) def _(expr, assumptions): return _Factorization(Q.diagonal, expr, assumptions) # IntegerElementsPredicate def BM_elements(predicate, expr, assumptions): """ Block Matrix elements. """ return all(ask(predicate(b), assumptions) for b in expr.blocks) def MS_elements(predicate, expr, assumptions): """ Matrix Slice elements. """ return ask(predicate(expr.parent), assumptions) def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions): d = sift(expr.args, lambda x: isinstance(x, MatrixExpr)) factors, matrices = d[False], d[True] return fuzzy_and([ test_closed_group(Basic(*factors), assumptions, scalar_predicate), test_closed_group(Basic(*matrices), assumptions, matrix_predicate)]) @IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd, Trace, Transpose) def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.integer_elements) @IntegerElementsPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None if exp.is_negative == False: return ask(Q.integer_elements(base), assumptions) return None @IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix) def _(expr, assumptions): return True @IntegerElementsPredicate.register(MatMul) def _(expr, assumptions): return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions) @IntegerElementsPredicate.register(MatrixSlice) def _(expr, assumptions): return MS_elements(Q.integer_elements, expr, assumptions) @IntegerElementsPredicate.register(BlockMatrix) def _(expr, assumptions): return BM_elements(Q.integer_elements, expr, assumptions) # RealElementsPredicate @RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, MatAdd, Trace, Transpose) def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.real_elements) @RealElementsPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.real_elements(base), assumptions) return None @RealElementsPredicate.register(MatMul) def _(expr, assumptions): return MatMul_elements(Q.real_elements, Q.real, expr, assumptions) @RealElementsPredicate.register(MatrixSlice) def _(expr, assumptions): return MS_elements(Q.real_elements, expr, assumptions) @RealElementsPredicate.register(BlockMatrix) def _(expr, assumptions): return BM_elements(Q.real_elements, expr, assumptions) # ComplexElementsPredicate @ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, Inverse, MatAdd, Trace, Transpose) def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.complex_elements) @ComplexElementsPredicate.register(MatPow) def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.complex_elements(base), assumptions) return None @ComplexElementsPredicate.register(MatMul) def _(expr, assumptions): return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions) @ComplexElementsPredicate.register(MatrixSlice) def _(expr, assumptions): return MS_elements(Q.complex_elements, expr, assumptions) @ComplexElementsPredicate.register(BlockMatrix) def _(expr, assumptions): return BM_elements(Q.complex_elements, expr, assumptions) @ComplexElementsPredicate.register(DFT) def _(expr, assumptions): return True
b5e1ec5d37cfc3fab8d7deed5dccf63affac715c431cff93fcba5c10b98e3272
from sympy.abc import t, w, x, y, z, n, k, m, p, i from sympy.assumptions import (ask, AssumptionsContext, Q, register_handler, remove_handler) from sympy.assumptions.assume import assuming, global_assumptions, Predicate from sympy.assumptions.cnf import CNF, Literal from sympy.assumptions.facts import (single_fact_lookup, get_known_facts, generate_known_facts_dict, get_known_facts_keys) from sympy.assumptions.handlers import AskHandler from sympy.assumptions.ask_generated import (get_all_known_facts, get_known_facts_dict) from sympy.core.add import Add from sympy.core.numbers import (I, Integer, Rational, oo, zoo, pi) from sympy.core.singleton import S from sympy.core.power import Pow from sympy.core.symbol import Str, symbols, Symbol from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, im, re, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import ( acos, acot, asin, atan, cos, cot, sin, tan) from sympy.logic.boolalg import Equivalent, Implies, Xor, And, to_cnf from sympy.matrices import Matrix, SparseMatrix from sympy.testing.pytest import (XFAIL, slow, raises, warns_deprecated_sympy, _both_exp_pow) import math def test_int_1(): z = 1 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is True assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_int_11(): z = 11 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is True assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is True assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_int_12(): z = 12 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is True assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is True assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_float_1(): z = 1.0 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is None assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is None assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = 7.2123 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is None assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is None assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False # test for issue #12168 assert ask(Q.rational(math.pi)) is None def test_zero_0(): z = Integer(0) assert ask(Q.nonzero(z)) is False assert ask(Q.zero(z)) is True assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is True assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is True def test_negativeone(): z = Integer(-1) assert ask(Q.nonzero(z)) is True assert ask(Q.zero(z)) is False assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is True assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is True assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_infinity(): assert ask(Q.commutative(oo)) is True assert ask(Q.integer(oo)) is False assert ask(Q.rational(oo)) is False assert ask(Q.algebraic(oo)) is False assert ask(Q.real(oo)) is False assert ask(Q.extended_real(oo)) is True assert ask(Q.complex(oo)) is False assert ask(Q.irrational(oo)) is False assert ask(Q.imaginary(oo)) is False assert ask(Q.positive(oo)) is False assert ask(Q.extended_positive(oo)) is True assert ask(Q.negative(oo)) is False assert ask(Q.even(oo)) is False assert ask(Q.odd(oo)) is False assert ask(Q.finite(oo)) is False assert ask(Q.infinite(oo)) is True assert ask(Q.prime(oo)) is False assert ask(Q.composite(oo)) is False assert ask(Q.hermitian(oo)) is False assert ask(Q.antihermitian(oo)) is False assert ask(Q.positive_infinite(oo)) is True assert ask(Q.negative_infinite(oo)) is False def test_neg_infinity(): mm = S.NegativeInfinity assert ask(Q.commutative(mm)) is True assert ask(Q.integer(mm)) is False assert ask(Q.rational(mm)) is False assert ask(Q.algebraic(mm)) is False assert ask(Q.real(mm)) is False assert ask(Q.extended_real(mm)) is True assert ask(Q.complex(mm)) is False assert ask(Q.irrational(mm)) is False assert ask(Q.imaginary(mm)) is False assert ask(Q.positive(mm)) is False assert ask(Q.negative(mm)) is False assert ask(Q.extended_negative(mm)) is True assert ask(Q.even(mm)) is False assert ask(Q.odd(mm)) is False assert ask(Q.finite(mm)) is False assert ask(Q.infinite(oo)) is True assert ask(Q.prime(mm)) is False assert ask(Q.composite(mm)) is False assert ask(Q.hermitian(mm)) is False assert ask(Q.antihermitian(mm)) is False assert ask(Q.positive_infinite(-oo)) is False assert ask(Q.negative_infinite(-oo)) is True def test_complex_infinity(): assert ask(Q.commutative(zoo)) is True assert ask(Q.integer(zoo)) is False assert ask(Q.rational(zoo)) is False assert ask(Q.algebraic(zoo)) is False assert ask(Q.real(zoo)) is False assert ask(Q.extended_real(zoo)) is False assert ask(Q.complex(zoo)) is False assert ask(Q.irrational(zoo)) is False assert ask(Q.imaginary(zoo)) is False assert ask(Q.positive(zoo)) is False assert ask(Q.negative(zoo)) is False assert ask(Q.zero(zoo)) is False assert ask(Q.nonzero(zoo)) is False assert ask(Q.even(zoo)) is False assert ask(Q.odd(zoo)) is False assert ask(Q.finite(zoo)) is False assert ask(Q.infinite(zoo)) is True assert ask(Q.prime(zoo)) is False assert ask(Q.composite(zoo)) is False assert ask(Q.hermitian(zoo)) is False assert ask(Q.antihermitian(zoo)) is False assert ask(Q.positive_infinite(zoo)) is False assert ask(Q.negative_infinite(zoo)) is False def test_nan(): nan = S.NaN assert ask(Q.commutative(nan)) is True assert ask(Q.integer(nan)) is None assert ask(Q.rational(nan)) is None assert ask(Q.algebraic(nan)) is None assert ask(Q.real(nan)) is None assert ask(Q.extended_real(nan)) is None assert ask(Q.complex(nan)) is None assert ask(Q.irrational(nan)) is None assert ask(Q.imaginary(nan)) is None assert ask(Q.positive(nan)) is None assert ask(Q.nonzero(nan)) is None assert ask(Q.zero(nan)) is None assert ask(Q.even(nan)) is None assert ask(Q.odd(nan)) is None assert ask(Q.finite(nan)) is None assert ask(Q.infinite(nan)) is None assert ask(Q.prime(nan)) is None assert ask(Q.composite(nan)) is None assert ask(Q.hermitian(nan)) is None assert ask(Q.antihermitian(nan)) is None def test_Rational_number(): r = Rational(3, 4) assert ask(Q.commutative(r)) is True assert ask(Q.integer(r)) is False assert ask(Q.rational(r)) is True assert ask(Q.real(r)) is True assert ask(Q.complex(r)) is True assert ask(Q.irrational(r)) is False assert ask(Q.imaginary(r)) is False assert ask(Q.positive(r)) is True assert ask(Q.negative(r)) is False assert ask(Q.even(r)) is False assert ask(Q.odd(r)) is False assert ask(Q.finite(r)) is True assert ask(Q.prime(r)) is False assert ask(Q.composite(r)) is False assert ask(Q.hermitian(r)) is True assert ask(Q.antihermitian(r)) is False r = Rational(1, 4) assert ask(Q.positive(r)) is True assert ask(Q.negative(r)) is False r = Rational(5, 4) assert ask(Q.negative(r)) is False assert ask(Q.positive(r)) is True r = Rational(5, 3) assert ask(Q.positive(r)) is True assert ask(Q.negative(r)) is False r = Rational(-3, 4) assert ask(Q.positive(r)) is False assert ask(Q.negative(r)) is True r = Rational(-1, 4) assert ask(Q.positive(r)) is False assert ask(Q.negative(r)) is True r = Rational(-5, 4) assert ask(Q.negative(r)) is True assert ask(Q.positive(r)) is False r = Rational(-5, 3) assert ask(Q.positive(r)) is False assert ask(Q.negative(r)) is True def test_sqrt_2(): z = sqrt(2) assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_pi(): z = S.Pi assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = S.Pi + 1 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = 2*S.Pi assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = S.Pi ** 2 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = (1 + S.Pi) ** 2 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_E(): z = S.Exp1 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_GoldenRatio(): z = S.GoldenRatio assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_TribonacciConstant(): z = S.TribonacciConstant assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_I(): z = I assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is False assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is True assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is False assert ask(Q.antihermitian(z)) is True z = 1 + I assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is False assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is False assert ask(Q.antihermitian(z)) is False z = I*(1 + I) assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is False assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is False assert ask(Q.antihermitian(z)) is False z = I**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (-I)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (3*I)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is False z = (1)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (-1)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (1+I)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is False z = (I)**(I+3) assert ask(Q.imaginary(z)) is True assert ask(Q.real(z)) is False z = (I)**(I+2) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (I)**(2) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (I)**(3) assert ask(Q.imaginary(z)) is True assert ask(Q.real(z)) is False z = (3)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is False z = (I)**(0) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True def test_bounded(): x, y, z = symbols('x,y,z') assert ask(Q.finite(x)) is None assert ask(Q.finite(x), Q.finite(x)) is True assert ask(Q.finite(x), Q.finite(y)) is None assert ask(Q.finite(x), Q.complex(x)) is True assert ask(Q.finite(x), Q.extended_real(x)) is None assert ask(Q.finite(x + 1)) is None assert ask(Q.finite(x + 1), Q.finite(x)) is True a = x + y x, y = a.args # B + B assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True assert ask(Q.finite(a), Q.positive(x) & Q.finite(y)) is True assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is True assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is True assert ask(Q.finite(a), Q.positive(x) & Q.finite(y) & ~Q.positive(y)) is True assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.positive(y)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.positive(x) & ~Q.positive(y)) is True # B + U assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & ~Q.positive(y)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.finite(y) & ~Q.positive(y)) is False # B + ? assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), Q.positive(x)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.positive(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.positive(y)) is None # U + U assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.positive_infinite(x) & ~Q.finite(y) & ~Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.extended_positive(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.extended_positive(x) & ~Q.extended_positive(y)) is False # U + ? assert ask(Q.finite(a), ~Q.finite(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.extended_positive(x) & ~Q.finite(y) & ~Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & ~Q.finite(y) & ~Q.extended_positive(y)) is False # ? + ? assert ask(Q.finite(a)) is None assert ask(Q.finite(a), Q.extended_positive(x)) is None assert ask(Q.finite(a), Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & ~Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & ~Q.extended_positive(y)) is None x, y, z = symbols('x,y,z') a = x + y + z x, y, z = a.args assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.negative(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y) & Q.finite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) & Q.negative_infinite(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y)& Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(z) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_negative(x)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a)) is None assert ask(Q.finite(a), Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_positive(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(2*x)) is None assert ask(Q.finite(2*x), Q.finite(x)) is True x, y, z = symbols('x,y,z') a = x*y x, y = a.args assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is False assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), ~Q.finite(x)) is None assert ask(Q.finite(a), Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(y)) is None assert ask(Q.finite(a)) is None a = x*y*z x, y, z = a.args assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) & Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x)) is None assert ask(Q.finite(a), Q.finite(y) & Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(y) & Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(z) & Q.extended_nonzero(x) & Q.extended_nonzero(y) & Q.extended_nonzero(z)) is None assert ask(Q.finite(a), Q.extended_nonzero(x) & ~Q.finite(y) & Q.extended_nonzero(y) & ~Q.finite(z) & Q.extended_nonzero(z)) is False x, y, z = symbols('x,y,z') assert ask(Q.finite(x**2)) is None assert ask(Q.finite(2**x)) is None assert ask(Q.finite(2**x), Q.finite(x)) is True assert ask(Q.finite(x**x)) is None assert ask(Q.finite(S.Half ** x)) is None assert ask(Q.finite(S.Half ** x), Q.extended_positive(x)) is True assert ask(Q.finite(S.Half ** x), Q.extended_negative(x)) is None assert ask(Q.finite(2**x), Q.extended_negative(x)) is True assert ask(Q.finite(sqrt(x))) is None assert ask(Q.finite(2**x), ~Q.finite(x)) is False assert ask(Q.finite(x**2), ~Q.finite(x)) is False # sign function assert ask(Q.finite(sign(x))) is True assert ask(Q.finite(sign(x)), ~Q.finite(x)) is True # exponential functions assert ask(Q.finite(log(x))) is None assert ask(Q.finite(log(x)), Q.finite(x)) is None assert ask(Q.finite(log(x)), ~Q.zero(x)) is True assert ask(Q.finite(log(x)), Q.infinite(x)) is False assert ask(Q.finite(log(x)), Q.zero(x)) is False assert ask(Q.finite(exp(x))) is None assert ask(Q.finite(exp(x)), Q.finite(x)) is True assert ask(Q.finite(exp(2))) is True # trigonometric functions assert ask(Q.finite(sin(x))) is True assert ask(Q.finite(sin(x)), ~Q.finite(x)) is True assert ask(Q.finite(cos(x))) is True assert ask(Q.finite(cos(x)), ~Q.finite(x)) is True assert ask(Q.finite(2*sin(x))) is True assert ask(Q.finite(sin(x)**2)) is True assert ask(Q.finite(cos(x)**2)) is True assert ask(Q.finite(cos(x) + sin(x))) is True @XFAIL def test_bounded_xfail(): """We need to support relations in ask for this to work""" assert ask(Q.finite(sin(x)**x)) is True assert ask(Q.finite(cos(x)**x)) is True def test_commutative(): """By default objects are Q.commutative that is why it returns True for both key=True and key=False""" assert ask(Q.commutative(x)) is True assert ask(Q.commutative(x), ~Q.commutative(x)) is False assert ask(Q.commutative(x), Q.complex(x)) is True assert ask(Q.commutative(x), Q.imaginary(x)) is True assert ask(Q.commutative(x), Q.real(x)) is True assert ask(Q.commutative(x), Q.positive(x)) is True assert ask(Q.commutative(x), ~Q.commutative(y)) is True assert ask(Q.commutative(2*x)) is True assert ask(Q.commutative(2*x), ~Q.commutative(x)) is False assert ask(Q.commutative(x + 1)) is True assert ask(Q.commutative(x + 1), ~Q.commutative(x)) is False assert ask(Q.commutative(x**2)) is True assert ask(Q.commutative(x**2), ~Q.commutative(x)) is False assert ask(Q.commutative(log(x))) is True @_both_exp_pow def test_complex(): assert ask(Q.complex(x)) is None assert ask(Q.complex(x), Q.complex(x)) is True assert ask(Q.complex(x), Q.complex(y)) is None assert ask(Q.complex(x), ~Q.complex(x)) is False assert ask(Q.complex(x), Q.real(x)) is True assert ask(Q.complex(x), ~Q.real(x)) is None assert ask(Q.complex(x), Q.rational(x)) is True assert ask(Q.complex(x), Q.irrational(x)) is True assert ask(Q.complex(x), Q.positive(x)) is True assert ask(Q.complex(x), Q.imaginary(x)) is True assert ask(Q.complex(x), Q.algebraic(x)) is True # a+b assert ask(Q.complex(x + 1), Q.complex(x)) is True assert ask(Q.complex(x + 1), Q.real(x)) is True assert ask(Q.complex(x + 1), Q.rational(x)) is True assert ask(Q.complex(x + 1), Q.irrational(x)) is True assert ask(Q.complex(x + 1), Q.imaginary(x)) is True assert ask(Q.complex(x + 1), Q.integer(x)) is True assert ask(Q.complex(x + 1), Q.even(x)) is True assert ask(Q.complex(x + 1), Q.odd(x)) is True assert ask(Q.complex(x + y), Q.complex(x) & Q.complex(y)) is True assert ask(Q.complex(x + y), Q.real(x) & Q.imaginary(y)) is True # a*x +b assert ask(Q.complex(2*x + 1), Q.complex(x)) is True assert ask(Q.complex(2*x + 1), Q.real(x)) is True assert ask(Q.complex(2*x + 1), Q.positive(x)) is True assert ask(Q.complex(2*x + 1), Q.rational(x)) is True assert ask(Q.complex(2*x + 1), Q.irrational(x)) is True assert ask(Q.complex(2*x + 1), Q.imaginary(x)) is True assert ask(Q.complex(2*x + 1), Q.integer(x)) is True assert ask(Q.complex(2*x + 1), Q.even(x)) is True assert ask(Q.complex(2*x + 1), Q.odd(x)) is True # x**2 assert ask(Q.complex(x**2), Q.complex(x)) is True assert ask(Q.complex(x**2), Q.real(x)) is True assert ask(Q.complex(x**2), Q.positive(x)) is True assert ask(Q.complex(x**2), Q.rational(x)) is True assert ask(Q.complex(x**2), Q.irrational(x)) is True assert ask(Q.complex(x**2), Q.imaginary(x)) is True assert ask(Q.complex(x**2), Q.integer(x)) is True assert ask(Q.complex(x**2), Q.even(x)) is True assert ask(Q.complex(x**2), Q.odd(x)) is True # 2**x assert ask(Q.complex(2**x), Q.complex(x)) is True assert ask(Q.complex(2**x), Q.real(x)) is True assert ask(Q.complex(2**x), Q.positive(x)) is True assert ask(Q.complex(2**x), Q.rational(x)) is True assert ask(Q.complex(2**x), Q.irrational(x)) is True assert ask(Q.complex(2**x), Q.imaginary(x)) is True assert ask(Q.complex(2**x), Q.integer(x)) is True assert ask(Q.complex(2**x), Q.even(x)) is True assert ask(Q.complex(2**x), Q.odd(x)) is True assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) is True # trigonometric expressions assert ask(Q.complex(sin(x))) is True assert ask(Q.complex(sin(2*x + 1))) is True assert ask(Q.complex(cos(x))) is True assert ask(Q.complex(cos(2*x + 1))) is True # exponential assert ask(Q.complex(exp(x))) is True assert ask(Q.complex(exp(x))) is True # Q.complexes assert ask(Q.complex(Abs(x))) is True assert ask(Q.complex(re(x))) is True assert ask(Q.complex(im(x))) is True def test_even_query(): assert ask(Q.even(x)) is None assert ask(Q.even(x), Q.integer(x)) is None assert ask(Q.even(x), ~Q.integer(x)) is False assert ask(Q.even(x), Q.rational(x)) is None assert ask(Q.even(x), Q.positive(x)) is None assert ask(Q.even(2*x)) is None assert ask(Q.even(2*x), Q.integer(x)) is True assert ask(Q.even(2*x), Q.even(x)) is True assert ask(Q.even(2*x), Q.irrational(x)) is False assert ask(Q.even(2*x), Q.odd(x)) is True assert ask(Q.even(2*x), ~Q.integer(x)) is None assert ask(Q.even(3*x), Q.integer(x)) is None assert ask(Q.even(3*x), Q.even(x)) is True assert ask(Q.even(3*x), Q.odd(x)) is False assert ask(Q.even(x + 1), Q.odd(x)) is True assert ask(Q.even(x + 1), Q.even(x)) is False assert ask(Q.even(x + 2), Q.odd(x)) is False assert ask(Q.even(x + 2), Q.even(x)) is True assert ask(Q.even(7 - x), Q.odd(x)) is True assert ask(Q.even(7 + x), Q.odd(x)) is True assert ask(Q.even(x + y), Q.odd(x) & Q.odd(y)) is True assert ask(Q.even(x + y), Q.odd(x) & Q.even(y)) is False assert ask(Q.even(x + y), Q.even(x) & Q.even(y)) is True assert ask(Q.even(2*x + 1), Q.integer(x)) is False assert ask(Q.even(2*x*y), Q.rational(x) & Q.rational(x)) is None assert ask(Q.even(2*x*y), Q.irrational(x) & Q.irrational(x)) is None assert ask(Q.even(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is True assert ask(Q.even(x + y + z + t), Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None assert ask(Q.even(Abs(x)), Q.even(x)) is True assert ask(Q.even(Abs(x)), ~Q.even(x)) is None assert ask(Q.even(re(x)), Q.even(x)) is True assert ask(Q.even(re(x)), ~Q.even(x)) is None assert ask(Q.even(im(x)), Q.even(x)) is True assert ask(Q.even(im(x)), Q.real(x)) is True assert ask(Q.even((-1)**n), Q.integer(n)) is False assert ask(Q.even(k**2), Q.even(k)) is True assert ask(Q.even(n**2), Q.odd(n)) is False assert ask(Q.even(2**k), Q.even(k)) is None assert ask(Q.even(x**2)) is None assert ask(Q.even(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.even(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is False assert ask(Q.even(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is True assert ask(Q.even(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is False assert ask(Q.even(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.even(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.even(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.even(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.even(k**x), Q.even(k)) is None assert ask(Q.even(n**x), Q.odd(n)) is None assert ask(Q.even(x*y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.even(x*x), Q.integer(x)) is None assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.odd(y)) is True assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.even(y)) is None @XFAIL def test_evenness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True assert ask(Q.even(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True def test_evenness_in_ternary_integer_product_with_even(): assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None def test_extended_real(): assert ask(Q.extended_real(x), Q.positive_infinite(x)) is True assert ask(Q.extended_real(x), Q.positive(x)) is True assert ask(Q.extended_real(x), Q.zero(x)) is True assert ask(Q.extended_real(x), Q.negative(x)) is True assert ask(Q.extended_real(x), Q.negative_infinite(x)) is True assert ask(Q.extended_real(-x), Q.positive(x)) is True assert ask(Q.extended_real(-x), Q.negative(x)) is True assert ask(Q.extended_real(x + S.Infinity), Q.real(x)) is True assert ask(Q.extended_real(x), Q.infinite(x)) is None @_both_exp_pow def test_rational(): assert ask(Q.rational(x), Q.integer(x)) is True assert ask(Q.rational(x), Q.irrational(x)) is False assert ask(Q.rational(x), Q.real(x)) is None assert ask(Q.rational(x), Q.positive(x)) is None assert ask(Q.rational(x), Q.negative(x)) is None assert ask(Q.rational(x), Q.nonzero(x)) is None assert ask(Q.rational(x), ~Q.algebraic(x)) is False assert ask(Q.rational(2*x), Q.rational(x)) is True assert ask(Q.rational(2*x), Q.integer(x)) is True assert ask(Q.rational(2*x), Q.even(x)) is True assert ask(Q.rational(2*x), Q.odd(x)) is True assert ask(Q.rational(2*x), Q.irrational(x)) is False assert ask(Q.rational(x/2), Q.rational(x)) is True assert ask(Q.rational(x/2), Q.integer(x)) is True assert ask(Q.rational(x/2), Q.even(x)) is True assert ask(Q.rational(x/2), Q.odd(x)) is True assert ask(Q.rational(x/2), Q.irrational(x)) is False assert ask(Q.rational(1/x), Q.rational(x)) is True assert ask(Q.rational(1/x), Q.integer(x)) is True assert ask(Q.rational(1/x), Q.even(x)) is True assert ask(Q.rational(1/x), Q.odd(x)) is True assert ask(Q.rational(1/x), Q.irrational(x)) is False assert ask(Q.rational(2/x), Q.rational(x)) is True assert ask(Q.rational(2/x), Q.integer(x)) is True assert ask(Q.rational(2/x), Q.even(x)) is True assert ask(Q.rational(2/x), Q.odd(x)) is True assert ask(Q.rational(2/x), Q.irrational(x)) is False assert ask(Q.rational(x), ~Q.algebraic(x)) is False # with multiple symbols assert ask(Q.rational(x*y), Q.irrational(x) & Q.irrational(y)) is None assert ask(Q.rational(y/x), Q.rational(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.integer(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.even(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.odd(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.irrational(x) & Q.rational(y)) is False for f in [exp, sin, tan, asin, atan, cos]: assert ask(Q.rational(f(7))) is False assert ask(Q.rational(f(7, evaluate=False))) is False assert ask(Q.rational(f(0, evaluate=False))) is True assert ask(Q.rational(f(x)), Q.rational(x)) is None assert ask(Q.rational(f(x)), Q.rational(x) & Q.nonzero(x)) is False for g in [log, acos]: assert ask(Q.rational(g(7))) is False assert ask(Q.rational(g(7, evaluate=False))) is False assert ask(Q.rational(g(1, evaluate=False))) is True assert ask(Q.rational(g(x)), Q.rational(x)) is None assert ask(Q.rational(g(x)), Q.rational(x) & Q.nonzero(x - 1)) is False for h in [cot, acot]: assert ask(Q.rational(h(7))) is False assert ask(Q.rational(h(7, evaluate=False))) is False assert ask(Q.rational(h(x)), Q.rational(x)) is False def test_hermitian(): assert ask(Q.hermitian(x)) is None assert ask(Q.hermitian(x), Q.antihermitian(x)) is None assert ask(Q.hermitian(x), Q.imaginary(x)) is False assert ask(Q.hermitian(x), Q.prime(x)) is True assert ask(Q.hermitian(x), Q.real(x)) is True assert ask(Q.hermitian(x), Q.zero(x)) is True assert ask(Q.hermitian(x + 1), Q.antihermitian(x)) is None assert ask(Q.hermitian(x + 1), Q.complex(x)) is None assert ask(Q.hermitian(x + 1), Q.hermitian(x)) is True assert ask(Q.hermitian(x + 1), Q.imaginary(x)) is False assert ask(Q.hermitian(x + 1), Q.real(x)) is True assert ask(Q.hermitian(x + I), Q.antihermitian(x)) is None assert ask(Q.hermitian(x + I), Q.complex(x)) is None assert ask(Q.hermitian(x + I), Q.hermitian(x)) is False assert ask(Q.hermitian(x + I), Q.imaginary(x)) is None assert ask(Q.hermitian(x + I), Q.real(x)) is False assert ask( Q.hermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)) is None assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None assert ask( Q.hermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is None assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.real(y)) is None assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.hermitian(y)) is True assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is False assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.real(y)) is True assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is None assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.real(y)) is False assert ask(Q.hermitian(x + y), Q.real(x) & Q.complex(y)) is None assert ask(Q.hermitian(x + y), Q.real(x) & Q.real(y)) is True assert ask(Q.hermitian(I*x), Q.antihermitian(x)) is True assert ask(Q.hermitian(I*x), Q.complex(x)) is None assert ask(Q.hermitian(I*x), Q.hermitian(x)) is False assert ask(Q.hermitian(I*x), Q.imaginary(x)) is True assert ask(Q.hermitian(I*x), Q.real(x)) is False assert ask(Q.hermitian(x*y), Q.hermitian(x) & Q.real(y)) is True assert ask( Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True assert ask(Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is False assert ask(Q.hermitian(x + y + z), Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is None assert ask(Q.hermitian(x + y + z), Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is None assert ask(Q.antihermitian(x)) is None assert ask(Q.antihermitian(x), Q.real(x)) is False assert ask(Q.antihermitian(x), Q.prime(x)) is False assert ask(Q.antihermitian(x + 1), Q.antihermitian(x)) is False assert ask(Q.antihermitian(x + 1), Q.complex(x)) is None assert ask(Q.antihermitian(x + 1), Q.hermitian(x)) is None assert ask(Q.antihermitian(x + 1), Q.imaginary(x)) is False assert ask(Q.antihermitian(x + 1), Q.real(x)) is None assert ask(Q.antihermitian(x + I), Q.antihermitian(x)) is True assert ask(Q.antihermitian(x + I), Q.complex(x)) is None assert ask(Q.antihermitian(x + I), Q.hermitian(x)) is None assert ask(Q.antihermitian(x + I), Q.imaginary(x)) is True assert ask(Q.antihermitian(x + I), Q.real(x)) is False assert ask(Q.antihermitian(x), Q.zero(x)) is True assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y) ) is True assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is True assert ask(Q.antihermitian(x + y), Q.antihermitian(x) & Q.real(y) ) is False assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.hermitian(y) ) is None assert ask( Q.antihermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is None assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.real(y)) is None assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is True assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.real(y)) is False assert ask(Q.antihermitian(x + y), Q.real(x) & Q.complex(y)) is None assert ask(Q.antihermitian(x + y), Q.real(x) & Q.real(y)) is None assert ask(Q.antihermitian(I*x), Q.real(x)) is True assert ask(Q.antihermitian(I*x), Q.antihermitian(x)) is False assert ask(Q.antihermitian(I*x), Q.complex(x)) is None assert ask(Q.antihermitian(x*y), Q.antihermitian(x) & Q.real(y)) is True assert ask(Q.antihermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is None assert ask(Q.antihermitian(x + y + z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is None assert ask(Q.antihermitian(x + y + z), Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False assert ask(Q.antihermitian(x + y + z), Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is True @_both_exp_pow def test_imaginary(): assert ask(Q.imaginary(x)) is None assert ask(Q.imaginary(x), Q.real(x)) is False assert ask(Q.imaginary(x), Q.prime(x)) is False assert ask(Q.imaginary(x + 1), Q.real(x)) is False assert ask(Q.imaginary(x + 1), Q.imaginary(x)) is False assert ask(Q.imaginary(x + I), Q.real(x)) is False assert ask(Q.imaginary(x + I), Q.imaginary(x)) is True assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.imaginary(y)) is True assert ask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.real(y)) is False assert ask(Q.imaginary(x + y), Q.complex(x) & Q.real(y)) is None assert ask( Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is False assert ask(Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is None assert ask(Q.imaginary(x + y + z), Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False assert ask(Q.imaginary(I*x), Q.real(x)) is True assert ask(Q.imaginary(I*x), Q.imaginary(x)) is False assert ask(Q.imaginary(I*x), Q.complex(x)) is None assert ask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True assert ask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False assert ask(Q.imaginary(I**x), Q.negative(x)) is None assert ask(Q.imaginary(I**x), Q.positive(x)) is None assert ask(Q.imaginary(I**x), Q.even(x)) is False assert ask(Q.imaginary(I**x), Q.odd(x)) is True assert ask(Q.imaginary(I**x), Q.imaginary(x)) is False assert ask(Q.imaginary((2*I)**x), Q.imaginary(x)) is False assert ask(Q.imaginary(x**0), Q.imaginary(x)) is False assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.imaginary(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.real(y)) is None assert ask(Q.imaginary(x**y), Q.real(x) & Q.imaginary(y)) is None assert ask(Q.imaginary(x**y), Q.real(x) & Q.real(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.integer(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(y) & Q.integer(x)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.odd(y)) is True assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.rational(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.even(y)) is False assert ask(Q.imaginary(x**y), Q.real(x) & Q.integer(y)) is False assert ask(Q.imaginary(x**y), Q.positive(x) & Q.real(y)) is False assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y)) is None assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y) & ~Q.rational(y)) is False assert ask(Q.imaginary(x**y), Q.integer(x) & Q.imaginary(y)) is None assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & Q.integer(2*y)) is True assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & ~Q.integer(2*y)) is False assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y)) is None assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & ~Q.integer(2*y)) is False assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & Q.integer(2*y)) is None # logarithm assert ask(Q.imaginary(log(I))) is True assert ask(Q.imaginary(log(2*I))) is False assert ask(Q.imaginary(log(I + 1))) is False assert ask(Q.imaginary(log(x)), Q.complex(x)) is None assert ask(Q.imaginary(log(x)), Q.imaginary(x)) is None assert ask(Q.imaginary(log(x)), Q.positive(x)) is False assert ask(Q.imaginary(log(exp(x))), Q.complex(x)) is None assert ask(Q.imaginary(log(exp(x))), Q.imaginary(x)) is None # zoo/I/a+I*b assert ask(Q.imaginary(log(exp(I)))) is True # exponential assert ask(Q.imaginary(exp(x)**x), Q.imaginary(x)) is False eq = Pow(exp(pi*I*x, evaluate=False), x, evaluate=False) assert ask(Q.imaginary(eq), Q.even(x)) is False eq = Pow(exp(pi*I*x/2, evaluate=False), x, evaluate=False) assert ask(Q.imaginary(eq), Q.odd(x)) is True assert ask(Q.imaginary(exp(3*I*pi*x)**x), Q.integer(x)) is False assert ask(Q.imaginary(exp(2*pi*I, evaluate=False))) is False assert ask(Q.imaginary(exp(pi*I/2, evaluate=False))) is True # issue 7886 assert ask(Q.imaginary(Pow(x, Rational(1, 4))), Q.real(x) & Q.negative(x)) is False def test_integer(): assert ask(Q.integer(x)) is None assert ask(Q.integer(x), Q.integer(x)) is True assert ask(Q.integer(x), ~Q.integer(x)) is False assert ask(Q.integer(x), ~Q.real(x)) is False assert ask(Q.integer(x), ~Q.positive(x)) is None assert ask(Q.integer(x), Q.even(x) | Q.odd(x)) is True assert ask(Q.integer(2*x), Q.integer(x)) is True assert ask(Q.integer(2*x), Q.even(x)) is True assert ask(Q.integer(2*x), Q.prime(x)) is True assert ask(Q.integer(2*x), Q.rational(x)) is None assert ask(Q.integer(2*x), Q.real(x)) is None assert ask(Q.integer(sqrt(2)*x), Q.integer(x)) is False assert ask(Q.integer(sqrt(2)*x), Q.irrational(x)) is None assert ask(Q.integer(x/2), Q.odd(x)) is False assert ask(Q.integer(x/2), Q.even(x)) is True assert ask(Q.integer(x/3), Q.odd(x)) is None assert ask(Q.integer(x/3), Q.even(x)) is None def test_negative(): assert ask(Q.negative(x), Q.negative(x)) is True assert ask(Q.negative(x), Q.positive(x)) is False assert ask(Q.negative(x), ~Q.real(x)) is False assert ask(Q.negative(x), Q.prime(x)) is False assert ask(Q.negative(x), ~Q.prime(x)) is None assert ask(Q.negative(-x), Q.positive(x)) is True assert ask(Q.negative(-x), ~Q.positive(x)) is None assert ask(Q.negative(-x), Q.negative(x)) is False assert ask(Q.negative(-x), Q.positive(x)) is True assert ask(Q.negative(x - 1), Q.negative(x)) is True assert ask(Q.negative(x + y)) is None assert ask(Q.negative(x + y), Q.negative(x)) is None assert ask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True assert ask(Q.negative(x + y), Q.negative(x) & Q.nonpositive(y)) is True assert ask(Q.negative(2 + I)) is False # although this could be False, it is representative of expressions # that don't evaluate to a zero with precision assert ask(Q.negative(cos(I)**2 + sin(I)**2 - 1)) is None assert ask(Q.negative(-I + I*(cos(2)**2 + sin(2)**2))) is None assert ask(Q.negative(x**2)) is None assert ask(Q.negative(x**2), Q.real(x)) is False assert ask(Q.negative(x**1.4), Q.real(x)) is None assert ask(Q.negative(x**I), Q.positive(x)) is None assert ask(Q.negative(x*y)) is None assert ask(Q.negative(x*y), Q.positive(x) & Q.positive(y)) is False assert ask(Q.negative(x*y), Q.positive(x) & Q.negative(y)) is True assert ask(Q.negative(x*y), Q.complex(x) & Q.complex(y)) is None assert ask(Q.negative(x**y)) is None assert ask(Q.negative(x**y), Q.negative(x) & Q.even(y)) is False assert ask(Q.negative(x**y), Q.negative(x) & Q.odd(y)) is True assert ask(Q.negative(x**y), Q.positive(x) & Q.integer(y)) is False assert ask(Q.negative(Abs(x))) is False def test_nonzero(): assert ask(Q.nonzero(x)) is None assert ask(Q.nonzero(x), Q.real(x)) is None assert ask(Q.nonzero(x), Q.positive(x)) is True assert ask(Q.nonzero(x), Q.negative(x)) is True assert ask(Q.nonzero(x), Q.negative(x) | Q.positive(x)) is True assert ask(Q.nonzero(x + y)) is None assert ask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True assert ask(Q.nonzero(x + y), Q.positive(x) & Q.negative(y)) is None assert ask(Q.nonzero(x + y), Q.negative(x) & Q.negative(y)) is True assert ask(Q.nonzero(2*x)) is None assert ask(Q.nonzero(2*x), Q.positive(x)) is True assert ask(Q.nonzero(2*x), Q.negative(x)) is True assert ask(Q.nonzero(x*y), Q.nonzero(x)) is None assert ask(Q.nonzero(x*y), Q.nonzero(x) & Q.nonzero(y)) is True assert ask(Q.nonzero(x**y), Q.nonzero(x)) is True assert ask(Q.nonzero(Abs(x))) is None assert ask(Q.nonzero(Abs(x)), Q.nonzero(x)) is True assert ask(Q.nonzero(log(exp(2*I)))) is False # although this could be False, it is representative of expressions # that don't evaluate to a zero with precision assert ask(Q.nonzero(cos(1)**2 + sin(1)**2 - 1)) is None def test_zero(): assert ask(Q.zero(x)) is None assert ask(Q.zero(x), Q.real(x)) is None assert ask(Q.zero(x), Q.positive(x)) is False assert ask(Q.zero(x), Q.negative(x)) is False assert ask(Q.zero(x), Q.negative(x) | Q.positive(x)) is False assert ask(Q.zero(x), Q.nonnegative(x) & Q.nonpositive(x)) is True assert ask(Q.zero(x + y)) is None assert ask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False assert ask(Q.zero(x + y), Q.positive(x) & Q.negative(y)) is None assert ask(Q.zero(x + y), Q.negative(x) & Q.negative(y)) is False assert ask(Q.zero(2*x)) is None assert ask(Q.zero(2*x), Q.positive(x)) is False assert ask(Q.zero(2*x), Q.negative(x)) is False assert ask(Q.zero(x*y), Q.nonzero(x)) is None assert ask(Q.zero(Abs(x))) is None assert ask(Q.zero(Abs(x)), Q.zero(x)) is True assert ask(Q.integer(x), Q.zero(x)) is True assert ask(Q.even(x), Q.zero(x)) is True assert ask(Q.odd(x), Q.zero(x)) is False assert ask(Q.zero(x), Q.even(x)) is None assert ask(Q.zero(x), Q.odd(x)) is False assert ask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True def test_odd_query(): assert ask(Q.odd(x)) is None assert ask(Q.odd(x), Q.odd(x)) is True assert ask(Q.odd(x), Q.integer(x)) is None assert ask(Q.odd(x), ~Q.integer(x)) is False assert ask(Q.odd(x), Q.rational(x)) is None assert ask(Q.odd(x), Q.positive(x)) is None assert ask(Q.odd(-x), Q.odd(x)) is True assert ask(Q.odd(2*x)) is None assert ask(Q.odd(2*x), Q.integer(x)) is False assert ask(Q.odd(2*x), Q.odd(x)) is False assert ask(Q.odd(2*x), Q.irrational(x)) is False assert ask(Q.odd(2*x), ~Q.integer(x)) is None assert ask(Q.odd(3*x), Q.integer(x)) is None assert ask(Q.odd(x/3), Q.odd(x)) is None assert ask(Q.odd(x/3), Q.even(x)) is None assert ask(Q.odd(x + 1), Q.even(x)) is True assert ask(Q.odd(x + 2), Q.even(x)) is False assert ask(Q.odd(x + 2), Q.odd(x)) is True assert ask(Q.odd(3 - x), Q.odd(x)) is False assert ask(Q.odd(3 - x), Q.even(x)) is True assert ask(Q.odd(3 + x), Q.odd(x)) is False assert ask(Q.odd(3 + x), Q.even(x)) is True assert ask(Q.odd(x + y), Q.odd(x) & Q.odd(y)) is False assert ask(Q.odd(x + y), Q.odd(x) & Q.even(y)) is True assert ask(Q.odd(x - y), Q.even(x) & Q.odd(y)) is True assert ask(Q.odd(x - y), Q.odd(x) & Q.odd(y)) is False assert ask(Q.odd(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is False assert ask(Q.odd(x + y + z + t), Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None assert ask(Q.odd(2*x + 1), Q.integer(x)) is True assert ask(Q.odd(2*x + y), Q.integer(x) & Q.odd(y)) is True assert ask(Q.odd(2*x + y), Q.integer(x) & Q.even(y)) is False assert ask(Q.odd(2*x + y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.odd(x*y), Q.odd(x) & Q.even(y)) is False assert ask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True assert ask(Q.odd(2*x*y), Q.rational(x) & Q.rational(x)) is None assert ask(Q.odd(2*x*y), Q.irrational(x) & Q.irrational(x)) is None assert ask(Q.odd(Abs(x)), Q.odd(x)) is True assert ask(Q.odd((-1)**n), Q.integer(n)) is True assert ask(Q.odd(k**2), Q.even(k)) is False assert ask(Q.odd(n**2), Q.odd(n)) is True assert ask(Q.odd(3**k), Q.even(k)) is None assert ask(Q.odd(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.odd(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is True assert ask(Q.odd(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is False assert ask(Q.odd(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is True assert ask(Q.odd(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.odd(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.odd(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.odd(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.odd(k**x), Q.even(k)) is None assert ask(Q.odd(n**x), Q.odd(n)) is None assert ask(Q.odd(x*y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.odd(x*x), Q.integer(x)) is None assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.odd(y)) is False assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.even(y)) is None @XFAIL def test_oddness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False assert ask(Q.odd(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False def test_oddness_in_ternary_integer_product_with_even(): assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None def test_prime(): assert ask(Q.prime(x), Q.prime(x)) is True assert ask(Q.prime(x), ~Q.prime(x)) is False assert ask(Q.prime(x), Q.integer(x)) is None assert ask(Q.prime(x), ~Q.integer(x)) is False assert ask(Q.prime(2*x), Q.integer(x)) is None assert ask(Q.prime(x*y)) is None assert ask(Q.prime(x*y), Q.prime(x)) is None assert ask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.prime(4*x), Q.integer(x)) is False assert ask(Q.prime(4*x)) is None assert ask(Q.prime(x**2), Q.integer(x)) is False assert ask(Q.prime(x**2), Q.prime(x)) is False assert ask(Q.prime(x**y), Q.integer(x) & Q.integer(y)) is False @_both_exp_pow def test_positive(): assert ask(Q.positive(x), Q.positive(x)) is True assert ask(Q.positive(x), Q.negative(x)) is False assert ask(Q.positive(x), Q.nonzero(x)) is None assert ask(Q.positive(-x), Q.positive(x)) is False assert ask(Q.positive(-x), Q.negative(x)) is True assert ask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True assert ask(Q.positive(x + y), Q.positive(x) & Q.nonnegative(y)) is True assert ask(Q.positive(x + y), Q.positive(x) & Q.negative(y)) is None assert ask(Q.positive(x + y), Q.positive(x) & Q.imaginary(y)) is False assert ask(Q.positive(2*x), Q.positive(x)) is True assumptions = Q.positive(x) & Q.negative(y) & Q.negative(z) & Q.positive(w) assert ask(Q.positive(x*y*z)) is None assert ask(Q.positive(x*y*z), assumptions) is True assert ask(Q.positive(-x*y*z), assumptions) is False assert ask(Q.positive(x**I), Q.positive(x)) is None assert ask(Q.positive(x**2), Q.positive(x)) is True assert ask(Q.positive(x**2), Q.negative(x)) is True assert ask(Q.positive(x**3), Q.negative(x)) is False assert ask(Q.positive(1/(1 + x**2)), Q.real(x)) is True assert ask(Q.positive(2**I)) is False assert ask(Q.positive(2 + I)) is False # although this could be False, it is representative of expressions # that don't evaluate to a zero with precision assert ask(Q.positive(cos(I)**2 + sin(I)**2 - 1)) is None assert ask(Q.positive(-I + I*(cos(2)**2 + sin(2)**2))) is None #exponential assert ask(Q.positive(exp(x)), Q.real(x)) is True assert ask(~Q.negative(exp(x)), Q.real(x)) is True assert ask(Q.positive(x + exp(x)), Q.real(x)) is None assert ask(Q.positive(exp(x)), Q.imaginary(x)) is None assert ask(Q.positive(exp(2*pi*I, evaluate=False)), Q.imaginary(x)) is True assert ask(Q.negative(exp(pi*I, evaluate=False)), Q.imaginary(x)) is True assert ask(Q.positive(exp(x*pi*I)), Q.even(x)) is True assert ask(Q.positive(exp(x*pi*I)), Q.odd(x)) is False assert ask(Q.positive(exp(x*pi*I)), Q.real(x)) is None # logarithm assert ask(Q.positive(log(x)), Q.imaginary(x)) is False assert ask(Q.positive(log(x)), Q.negative(x)) is False assert ask(Q.positive(log(x)), Q.positive(x)) is None assert ask(Q.positive(log(x + 2)), Q.positive(x)) is True # factorial assert ask(Q.positive(factorial(x)), Q.integer(x) & Q.positive(x)) assert ask(Q.positive(factorial(x)), Q.integer(x)) is None #absolute value assert ask(Q.positive(Abs(x))) is None # Abs(0) = 0 assert ask(Q.positive(Abs(x)), Q.positive(x)) is True def test_nonpositive(): assert ask(Q.nonpositive(-1)) assert ask(Q.nonpositive(0)) assert ask(Q.nonpositive(1)) is False assert ask(~Q.positive(x), Q.nonpositive(x)) assert ask(Q.nonpositive(x), Q.positive(x)) is False assert ask(Q.nonpositive(sqrt(-1))) is False assert ask(Q.nonpositive(x), Q.imaginary(x)) is False def test_nonnegative(): assert ask(Q.nonnegative(-1)) is False assert ask(Q.nonnegative(0)) assert ask(Q.nonnegative(1)) assert ask(~Q.negative(x), Q.nonnegative(x)) assert ask(Q.nonnegative(x), Q.negative(x)) is False assert ask(Q.nonnegative(sqrt(-1))) is False assert ask(Q.nonnegative(x), Q.imaginary(x)) is False def test_real_basic(): assert ask(Q.real(x)) is None assert ask(Q.real(x), Q.real(x)) is True assert ask(Q.real(x), Q.nonzero(x)) is True assert ask(Q.real(x), Q.positive(x)) is True assert ask(Q.real(x), Q.negative(x)) is True assert ask(Q.real(x), Q.integer(x)) is True assert ask(Q.real(x), Q.even(x)) is True assert ask(Q.real(x), Q.prime(x)) is True assert ask(Q.real(x/sqrt(2)), Q.real(x)) is True assert ask(Q.real(x/sqrt(-2)), Q.real(x)) is False assert ask(Q.real(x + 1), Q.real(x)) is True assert ask(Q.real(x + I), Q.real(x)) is False assert ask(Q.real(x + I), Q.complex(x)) is None assert ask(Q.real(2*x), Q.real(x)) is True assert ask(Q.real(I*x), Q.real(x)) is False assert ask(Q.real(I*x), Q.imaginary(x)) is True assert ask(Q.real(I*x), Q.complex(x)) is None def test_real_pow(): assert ask(Q.real(x**2), Q.real(x)) is True assert ask(Q.real(sqrt(x)), Q.negative(x)) is False assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) is None assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True assert ask(Q.real(x**y), Q.imaginary(x) & Q.imaginary(y)) is None # I**I or (2*I)**I assert ask(Q.real(x**y), Q.imaginary(x) & Q.real(y)) is None # I**1 or I**0 assert ask(Q.real(x**y), Q.real(x) & Q.imaginary(y)) is None # could be exp(2*pi*I) or 2**I assert ask(Q.real(x**0), Q.imaginary(x)) is True assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True assert ask(Q.real(x**y), Q.real(x) & Q.rational(y)) is None assert ask(Q.real(x**y), Q.imaginary(x) & Q.integer(y)) is None assert ask(Q.real(x**y), Q.imaginary(x) & Q.odd(y)) is False assert ask(Q.real(x**y), Q.imaginary(x) & Q.even(y)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.rational(y/z) & Q.even(z) & Q.positive(x)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.rational(y/z) & Q.even(z) & Q.negative(x)) is False assert ask(Q.real(x**(y/z)), Q.real(x) & Q.integer(y/z)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.positive(x)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.negative(x)) is False assert ask(Q.real((-I)**i), Q.imaginary(i)) is True assert ask(Q.real(I**i), Q.imaginary(i)) is True assert ask(Q.real(i**i), Q.imaginary(i)) is None # i might be 2*I assert ask(Q.real(x**i), Q.imaginary(i)) is None # x could be 0 assert ask(Q.real(x**(I*pi/log(x))), Q.real(x)) is True @_both_exp_pow def test_real_functions(): # trigonometric functions assert ask(Q.real(sin(x))) is None assert ask(Q.real(cos(x))) is None assert ask(Q.real(sin(x)), Q.real(x)) is True assert ask(Q.real(cos(x)), Q.real(x)) is True # exponential function assert ask(Q.real(exp(x))) is None assert ask(Q.real(exp(x)), Q.real(x)) is True assert ask(Q.real(x + exp(x)), Q.real(x)) is True assert ask(Q.real(exp(2*pi*I, evaluate=False))) is True assert ask(Q.real(exp(pi*I, evaluate=False))) is True assert ask(Q.real(exp(pi*I/2, evaluate=False))) is False # logarithm assert ask(Q.real(log(I))) is False assert ask(Q.real(log(2*I))) is False assert ask(Q.real(log(I + 1))) is False assert ask(Q.real(log(x)), Q.complex(x)) is None assert ask(Q.real(log(x)), Q.imaginary(x)) is False assert ask(Q.real(log(exp(x))), Q.imaginary(x)) is None # exp(2*pi*I) is 1, log(exp(pi*I)) is pi*I (disregarding periodicity) assert ask(Q.real(log(exp(x))), Q.complex(x)) is None eq = Pow(exp(2*pi*I*x, evaluate=False), x, evaluate=False) assert ask(Q.real(eq), Q.integer(x)) is True assert ask(Q.real(exp(x)**x), Q.imaginary(x)) is True assert ask(Q.real(exp(x)**x), Q.complex(x)) is None # Q.complexes assert ask(Q.real(re(x))) is True assert ask(Q.real(im(x))) is True def test_matrix(): # hermitian assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 - I, 3, I], [4, -I, 1]]))) == True assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 + I, 3, I], [4, -I, 1]]))) == False z = symbols('z', complex=True) assert ask(Q.hermitian(Matrix([[2, 2 + I, z], [2 - I, 3, I], [4, -I, 1]]))) == None assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))))) == True assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, I, 0), (-5, 0, 11))))) == False assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, z, 0), (-5, 0, 11))))) == None # antihermitian A = Matrix([[0, -2 - I, 0], [2 - I, 0, -I], [0, -I, 0]]) B = Matrix([[-I, 2 + I, 0], [-2 + I, 0, 2 + I], [0, -2 + I, -I]]) assert ask(Q.antihermitian(A)) is True assert ask(Q.antihermitian(B)) is True assert ask(Q.antihermitian(A**2)) is False C = (B**3) C.simplify() assert ask(Q.antihermitian(C)) is True _A = Matrix([[0, -2 - I, 0], [z, 0, -I], [0, -I, 0]]) assert ask(Q.antihermitian(_A)) is None @_both_exp_pow def test_algebraic(): assert ask(Q.algebraic(x)) is None assert ask(Q.algebraic(I)) is True assert ask(Q.algebraic(2*I)) is True assert ask(Q.algebraic(I/3)) is True assert ask(Q.algebraic(sqrt(7))) is True assert ask(Q.algebraic(2*sqrt(7))) is True assert ask(Q.algebraic(sqrt(7)/3)) is True assert ask(Q.algebraic(I*sqrt(3))) is True assert ask(Q.algebraic(sqrt(1 + I*sqrt(3)))) is True assert ask(Q.algebraic(1 + I*sqrt(3)**Rational(17, 31))) is True assert ask(Q.algebraic(1 + I*sqrt(3)**(17/pi))) is False for f in [exp, sin, tan, asin, atan, cos]: assert ask(Q.algebraic(f(7))) is False assert ask(Q.algebraic(f(7, evaluate=False))) is False assert ask(Q.algebraic(f(0, evaluate=False))) is True assert ask(Q.algebraic(f(x)), Q.algebraic(x)) is None assert ask(Q.algebraic(f(x)), Q.algebraic(x) & Q.nonzero(x)) is False for g in [log, acos]: assert ask(Q.algebraic(g(7))) is False assert ask(Q.algebraic(g(7, evaluate=False))) is False assert ask(Q.algebraic(g(1, evaluate=False))) is True assert ask(Q.algebraic(g(x)), Q.algebraic(x)) is None assert ask(Q.algebraic(g(x)), Q.algebraic(x) & Q.nonzero(x - 1)) is False for h in [cot, acot]: assert ask(Q.algebraic(h(7))) is False assert ask(Q.algebraic(h(7, evaluate=False))) is False assert ask(Q.algebraic(h(x)), Q.algebraic(x)) is False assert ask(Q.algebraic(sqrt(sin(7)))) is False assert ask(Q.algebraic(sqrt(y + I*sqrt(7)))) is None assert ask(Q.algebraic(2.47)) is True assert ask(Q.algebraic(x), Q.transcendental(x)) is False assert ask(Q.transcendental(x), Q.algebraic(x)) is False def test_global(): """Test ask with global assumptions""" assert ask(Q.integer(x)) is None global_assumptions.add(Q.integer(x)) assert ask(Q.integer(x)) is True global_assumptions.clear() assert ask(Q.integer(x)) is None def test_custom_context(): """Test ask with custom assumptions context""" assert ask(Q.integer(x)) is None local_context = AssumptionsContext() local_context.add(Q.integer(x)) assert ask(Q.integer(x), context=local_context) is True assert ask(Q.integer(x)) is None def test_functions_in_assumptions(): assert ask(Q.negative(x), Q.real(x) >> Q.positive(x)) is False assert ask(Q.negative(x), Equivalent(Q.real(x), Q.positive(x))) is False assert ask(Q.negative(x), Xor(Q.real(x), Q.negative(x))) is False def test_composite_ask(): assert ask(Q.negative(x) & Q.integer(x), assumptions=Q.real(x) >> Q.positive(x)) is False def test_composite_proposition(): assert ask(True) is True assert ask(False) is False assert ask(~Q.negative(x), Q.positive(x)) is True assert ask(~Q.real(x), Q.commutative(x)) is None assert ask(Q.negative(x) & Q.integer(x), Q.positive(x)) is False assert ask(Q.negative(x) & Q.integer(x)) is None assert ask(Q.real(x) | Q.integer(x), Q.positive(x)) is True assert ask(Q.real(x) | Q.integer(x)) is None assert ask(Q.real(x) >> Q.positive(x), Q.negative(x)) is False assert ask(Implies( Q.real(x), Q.positive(x), evaluate=False), Q.negative(x)) is False assert ask(Implies(Q.real(x), Q.positive(x), evaluate=False)) is None assert ask(Equivalent(Q.integer(x), Q.even(x)), Q.even(x)) is True assert ask(Equivalent(Q.integer(x), Q.even(x))) is None assert ask(Equivalent(Q.positive(x), Q.integer(x)), Q.integer(x)) is None assert ask(Q.real(x) | Q.integer(x), Q.real(x) | Q.integer(x)) is True def test_tautology(): assert ask(Q.real(x) | ~Q.real(x)) is True assert ask(Q.real(x) & ~Q.real(x)) is False def test_composite_assumptions(): assert ask(Q.real(x), Q.real(x) & Q.real(y)) is True assert ask(Q.positive(x), Q.positive(x) | Q.positive(y)) is None assert ask(Q.positive(x), Q.real(x) >> Q.positive(y)) is None assert ask(Q.real(x), ~(Q.real(x) >> Q.real(y))) is True def test_key_extensibility(): """test that you can add keys to the ask system at runtime""" # make sure the key is not defined raises(AttributeError, lambda: ask(Q.my_key(x))) # Old handler system class MyAskHandler(AskHandler): @staticmethod def Symbol(expr, assumptions): return True try: with warns_deprecated_sympy(): register_handler('my_key', MyAskHandler) with warns_deprecated_sympy(): assert ask(Q.my_key(x)) is True with warns_deprecated_sympy(): assert ask(Q.my_key(x + 1)) is None finally: # We have to disable the stacklevel testing here because this raises # the warning twice from two different places with warns_deprecated_sympy(): remove_handler('my_key', MyAskHandler) del Q.my_key raises(AttributeError, lambda: ask(Q.my_key(x))) # New handler system class MyPredicate(Predicate): pass try: Q.my_key = MyPredicate() @Q.my_key.register(Symbol) def _(expr, assumptions): return True assert ask(Q.my_key(x)) is True assert ask(Q.my_key(x+1)) is None finally: del Q.my_key raises(AttributeError, lambda: ask(Q.my_key(x))) def test_type_extensibility(): """test that new types can be added to the ask system at runtime """ from sympy.core import Basic class MyType(Basic): pass @Q.prime.register(MyType) def _(expr, assumptions): return True assert ask(Q.prime(MyType())) is True def test_single_fact_lookup(): known_facts = And(Implies(Q.integer, Q.rational), Implies(Q.rational, Q.real), Implies(Q.real, Q.complex)) known_facts_keys = {Q.integer, Q.rational, Q.real, Q.complex} known_facts_cnf = to_cnf(known_facts) mapping = single_fact_lookup(known_facts_keys, known_facts_cnf) assert mapping[Q.rational] == {Q.real, Q.rational, Q.complex} def test_generate_known_facts_dict(): known_facts = And(Implies(Q.integer(x), Q.rational(x)), Implies(Q.rational(x), Q.real(x)), Implies(Q.real(x), Q.complex(x))) known_facts_keys = {Q.integer(x), Q.rational(x), Q.real(x), Q.complex(x)} assert generate_known_facts_dict(known_facts_keys, known_facts) == \ {Q.complex: ({Q.complex}, set()), Q.integer: ({Q.complex, Q.integer, Q.rational, Q.real}, set()), Q.rational: ({Q.complex, Q.rational, Q.real}, set()), Q.real: ({Q.complex, Q.real}, set())} @slow def test_known_facts_consistent(): """"Test that ask_generated.py is up-to-date""" x = Symbol('x') fact = get_known_facts(x) # test cnf clauses of fact between unary predicates cnf = CNF.to_CNF(fact) clauses = set() for cl in cnf.clauses: clauses.add(frozenset(Literal(lit.arg.function, lit.is_Not) for lit in sorted(cl, key=str))) assert get_all_known_facts() == clauses # test dictionary of fact between unary predicates keys = [pred(x) for pred in get_known_facts_keys()] mapping = generate_known_facts_dict(keys, fact) assert get_known_facts_dict() == mapping def test_Add_queries(): assert ask(Q.prime(12345678901234567890 + (cos(1)**2 + sin(1)**2))) is True assert ask(Q.even(Add(S(2), S(2), evaluate=0))) is True assert ask(Q.prime(Add(S(2), S(2), evaluate=0))) is False assert ask(Q.integer(Add(S(2), S(2), evaluate=0))) is True def test_positive_assuming(): with assuming(Q.positive(x + 1)): assert not ask(Q.positive(x)) def test_issue_5421(): raises(TypeError, lambda: ask(pi/log(x), Q.real)) def test_issue_3906(): raises(TypeError, lambda: ask(Q.positive)) def test_issue_5833(): assert ask(Q.positive(log(x)**2), Q.positive(x)) is None assert ask(~Q.negative(log(x)**2), Q.positive(x)) is True def test_issue_6732(): raises(ValueError, lambda: ask(Q.positive(x), Q.positive(x) & Q.negative(x))) raises(ValueError, lambda: ask(Q.negative(x), Q.positive(x) & Q.negative(x))) def test_issue_7246(): assert ask(Q.positive(atan(p)), Q.positive(p)) is True assert ask(Q.positive(atan(p)), Q.negative(p)) is False assert ask(Q.positive(atan(p)), Q.zero(p)) is False assert ask(Q.positive(atan(x))) is None assert ask(Q.positive(asin(p)), Q.positive(p)) is None assert ask(Q.positive(asin(p)), Q.zero(p)) is None assert ask(Q.positive(asin(Rational(1, 7)))) is True assert ask(Q.positive(asin(x)), Q.positive(x) & Q.nonpositive(x - 1)) is True assert ask(Q.positive(asin(x)), Q.negative(x) & Q.nonnegative(x + 1)) is False assert ask(Q.positive(acos(p)), Q.positive(p)) is None assert ask(Q.positive(acos(Rational(1, 7)))) is True assert ask(Q.positive(acos(x)), Q.nonnegative(x + 1) & Q.nonpositive(x - 1)) is True assert ask(Q.positive(acos(x)), Q.nonnegative(x - 1)) is None assert ask(Q.positive(acot(x)), Q.positive(x)) is True assert ask(Q.positive(acot(x)), Q.real(x)) is True assert ask(Q.positive(acot(x)), Q.imaginary(x)) is False assert ask(Q.positive(acot(x))) is None @XFAIL def test_issue_7246_failing(): #Move this test to test_issue_7246 once #the new assumptions module is improved. assert ask(Q.positive(acos(x)), Q.zero(x)) is True def test_check_old_assumption(): x = symbols('x', real=True) assert ask(Q.real(x)) is True assert ask(Q.imaginary(x)) is False assert ask(Q.complex(x)) is True x = symbols('x', imaginary=True) assert ask(Q.real(x)) is False assert ask(Q.imaginary(x)) is True assert ask(Q.complex(x)) is True x = symbols('x', complex=True) assert ask(Q.real(x)) is None assert ask(Q.complex(x)) is True x = symbols('x', positive=True) assert ask(Q.positive(x)) is True assert ask(Q.negative(x)) is False assert ask(Q.real(x)) is True x = symbols('x', commutative=False) assert ask(Q.commutative(x)) is False x = symbols('x', negative=True) assert ask(Q.positive(x)) is False assert ask(Q.negative(x)) is True x = symbols('x', nonnegative=True) assert ask(Q.negative(x)) is False assert ask(Q.positive(x)) is None assert ask(Q.zero(x)) is None x = symbols('x', finite=True) assert ask(Q.finite(x)) is True x = symbols('x', prime=True) assert ask(Q.prime(x)) is True assert ask(Q.composite(x)) is False x = symbols('x', composite=True) assert ask(Q.prime(x)) is False assert ask(Q.composite(x)) is True x = symbols('x', even=True) assert ask(Q.even(x)) is True assert ask(Q.odd(x)) is False x = symbols('x', odd=True) assert ask(Q.even(x)) is False assert ask(Q.odd(x)) is True x = symbols('x', nonzero=True) assert ask(Q.nonzero(x)) is True assert ask(Q.zero(x)) is False x = symbols('x', zero=True) assert ask(Q.zero(x)) is True x = symbols('x', integer=True) assert ask(Q.integer(x)) is True x = symbols('x', rational=True) assert ask(Q.rational(x)) is True assert ask(Q.irrational(x)) is False x = symbols('x', irrational=True) assert ask(Q.irrational(x)) is True assert ask(Q.rational(x)) is False def test_issue_9636(): assert ask(Q.integer(1.0)) is False assert ask(Q.prime(3.0)) is False assert ask(Q.composite(4.0)) is False assert ask(Q.even(2.0)) is False assert ask(Q.odd(3.0)) is False def test_autosimp_used_to_fail(): # See issue #9807 assert ask(Q.imaginary(0**I)) is None assert ask(Q.imaginary(0**(-I))) is None assert ask(Q.real(0**I)) is None assert ask(Q.real(0**(-I))) is None def test_custom_AskHandler(): from sympy.logic.boolalg import conjuncts # Old handler system class MersenneHandler(AskHandler): @staticmethod def Integer(expr, assumptions): if ask(Q.integer(log(expr + 1, 2))): return True @staticmethod def Symbol(expr, assumptions): if expr in conjuncts(assumptions): return True try: with warns_deprecated_sympy(): register_handler('mersenne', MersenneHandler) n = Symbol('n', integer=True) with warns_deprecated_sympy(): assert ask(Q.mersenne(7)) with warns_deprecated_sympy(): assert ask(Q.mersenne(n), Q.mersenne(n)) finally: del Q.mersenne # New handler system class MersennePredicate(Predicate): pass try: Q.mersenne = MersennePredicate() @Q.mersenne.register(Integer) def _(expr, assumptions): if ask(Q.integer(log(expr + 1, 2))): return True @Q.mersenne.register(Symbol) def _(expr, assumptions): if expr in conjuncts(assumptions): return True assert ask(Q.mersenne(7)) assert ask(Q.mersenne(n), Q.mersenne(n)) finally: del Q.mersenne def test_polyadic_predicate(): class SexyPredicate(Predicate): pass try: Q.sexyprime = SexyPredicate() @Q.sexyprime.register(Integer, Integer) def _(int1, int2, assumptions): args = sorted([int1, int2]) if not all(ask(Q.prime(a), assumptions) for a in args): return False return args[1] - args[0] == 6 @Q.sexyprime.register(Integer, Integer, Integer) def _(int1, int2, int3, assumptions): args = sorted([int1, int2, int3]) if not all(ask(Q.prime(a), assumptions) for a in args): return False return args[2] - args[1] == 6 and args[1] - args[0] == 6 assert ask(Q.sexyprime(5, 11)) assert ask(Q.sexyprime(7, 13, 19)) finally: del Q.sexyprime def test_Predicate_handler_is_unique(): # Undefined predicate does not have a handler assert Predicate('mypredicate').handler is None # Handler of defined predicate is unique to the class class MyPredicate(Predicate): pass mp1 = MyPredicate(Str('mp1')) mp2 = MyPredicate(Str('mp2')) assert mp1.handler is mp2.handler def test_relational(): assert ask(Q.eq(x, 0), Q.zero(x)) assert not ask(Q.eq(x, 0), Q.nonzero(x)) assert not ask(Q.ne(x, 0), Q.zero(x)) assert ask(Q.ne(x, 0), Q.nonzero(x))
3f56af6b8279672f77dced379bd4194d557b4854094ac95a25ed044176a76f75
""" This module implements some special functions that commonly appear in combinatorial contexts (e.g. in power series); in particular, sequences of rational numbers such as Bernoulli and Fibonacci numbers. Factorials, binomial coefficients and related functions are located in the separate 'factorials' module. """ from collections import defaultdict from typing import Callable, Dict as tDict, Tuple as tTuple from sympy.core import S, Symbol, Add, Dummy from sympy.core.cache import cacheit from sympy.core.evalf import pure_complex from sympy.core.expr import Expr from sympy.core.function import Function, expand_mul from sympy.core.logic import fuzzy_not from sympy.core.mul import Mul, prod from sympy.core.numbers import E, pi, oo, Rational, Integer from sympy.core.relational import is_le, is_gt from sympy.external.gmpy import SYMPY_INTS from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial) from sympy.ntheory.primetest import isprime, is_square from sympy.utilities.enumerative import MultisetPartitionTraverser from sympy.utilities.iterables import multiset, multiset_derangements, iterable from sympy.utilities.memoization import recurrence_memo from sympy.utilities.misc import as_int from mpmath import bernfrac, workprec from mpmath.libmp import ifib as _ifib def _product(a, b): p = 1 for k in range(a, b + 1): p *= k return p # Dummy symbol used for computing polynomial sequences _sym = Symbol('x') #----------------------------------------------------------------------------# # # # Carmichael numbers # # # #----------------------------------------------------------------------------# def _divides(p, n): return n % p == 0 class carmichael(Function): """ Carmichael Numbers: Certain cryptographic algorithms make use of big prime numbers. However, checking whether a big number is prime is not so easy. Randomized prime number checking tests exist that offer a high degree of confidence of accurate determination at low cost, such as the Fermat test. Let 'a' be a random number between 2 and n - 1, where n is the number whose primality we are testing. Then, n is probably prime if it satisfies the modular arithmetic congruence relation : a^(n-1) = 1(mod n). (where mod refers to the modulo operation) If a number passes the Fermat test several times, then it is prime with a high probability. Unfortunately, certain composite numbers (non-primes) still pass the Fermat test with every number smaller than themselves. These numbers are called Carmichael numbers. A Carmichael number will pass a Fermat primality test to every base b relatively prime to the number, even though it is not actually prime. This makes tests based on Fermat's Little Theorem less effective than strong probable prime tests such as the Baillie-PSW primality test and the Miller-Rabin primality test. mr functions given in sympy/sympy/ntheory/primetest.py will produce wrong results for each and every carmichael number. Examples ======== >>> from sympy import carmichael >>> carmichael.find_first_n_carmichaels(5) [561, 1105, 1729, 2465, 2821] >>> carmichael.is_prime(2465) False >>> carmichael.is_prime(1729) False >>> carmichael.find_carmichael_numbers_in_range(0, 562) [561] >>> carmichael.find_carmichael_numbers_in_range(0,1000) [561] >>> carmichael.find_carmichael_numbers_in_range(0,2000) [561, 1105, 1729] References ========== .. [1] https://en.wikipedia.org/wiki/Carmichael_number .. [2] https://en.wikipedia.org/wiki/Fermat_primality_test .. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents """ @staticmethod def is_perfect_square(n): return is_square(n) @staticmethod def divides(p, n): return n % p == 0 @staticmethod def is_prime(n): return isprime(n) @staticmethod def is_carmichael(n): if n >= 0: if (n == 1) or isprime(n) or (n % 2 == 0): return False divisors = list([1, n]) # get divisors for i in range(3, n // 2 + 1, 2): if n % i == 0: divisors.append(i) for i in divisors: if is_square(i) and i != 1: return False if isprime(i): if not _divides(i - 1, n - 1): return False return True else: raise ValueError('The provided number must be greater than or equal to 0') @staticmethod def find_carmichael_numbers_in_range(x, y): if 0 <= x <= y: if x % 2 == 0: return list([i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]) else: return list([i for i in range(x, y, 2) if carmichael.is_carmichael(i)]) else: raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y') @staticmethod def find_first_n_carmichaels(n): i = 1 carmichaels = list() while len(carmichaels) < n: if carmichael.is_carmichael(i): carmichaels.append(i) i += 2 return carmichaels #----------------------------------------------------------------------------# # # # Fibonacci numbers # # # #----------------------------------------------------------------------------# class fibonacci(Function): r""" Fibonacci numbers / Fibonacci polynomials The Fibonacci numbers are the integer sequence defined by the initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence relation `F_n = F_{n-1} + F_{n-2}`. This definition extended to arbitrary real and complex arguments using the formula .. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5} The Fibonacci polynomials are defined by `F_1(x) = 1`, `F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`. For all positive integers `n`, `F_n(1) = F_n`. * ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n` * ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)` Examples ======== >>> from sympy import fibonacci, Symbol >>> [fibonacci(x) for x in range(11)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fibonacci(5, Symbol('t')) t**4 + 3*t**2 + 1 See Also ======== bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Fibonacci_number .. [2] http://mathworld.wolfram.com/FibonacciNumber.html """ @staticmethod def _fib(n): return _ifib(n) @staticmethod @recurrence_memo([None, S.One, _sym]) def _fibpoly(n, prev): return (prev[-2] + _sym*prev[-1]).expand() @classmethod def eval(cls, n, sym=None): if n is S.Infinity: return S.Infinity if n.is_Integer: if sym is None: n = int(n) if n < 0: return S.NegativeOne**(n + 1) * fibonacci(-n) else: return Integer(cls._fib(n)) else: if n < 1: raise ValueError("Fibonacci polynomials are defined " "only for positive integer indices.") return cls._fibpoly(n).subs(_sym, sym) def _eval_rewrite_as_sqrt(self, n, **kwargs): from sympy.functions.elementary.miscellaneous import sqrt return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5 def _eval_rewrite_as_GoldenRatio(self,n, **kwargs): return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1) #----------------------------------------------------------------------------# # # # Lucas numbers # # # #----------------------------------------------------------------------------# class lucas(Function): """ Lucas numbers Lucas numbers satisfy a recurrence relation similar to that of the Fibonacci sequence, in which each term is the sum of the preceding two. They are generated by choosing the initial values `L_0 = 2` and `L_1 = 1`. * ``lucas(n)`` gives the `n^{th}` Lucas number Examples ======== >>> from sympy import lucas >>> [lucas(x) for x in range(11)] [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123] See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Lucas_number .. [2] http://mathworld.wolfram.com/LucasNumber.html """ @classmethod def eval(cls, n): if n is S.Infinity: return S.Infinity if n.is_Integer: return fibonacci(n + 1) + fibonacci(n - 1) def _eval_rewrite_as_sqrt(self, n, **kwargs): from sympy.functions.elementary.miscellaneous import sqrt return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n) #----------------------------------------------------------------------------# # # # Tribonacci numbers # # # #----------------------------------------------------------------------------# class tribonacci(Function): r""" Tribonacci numbers / Tribonacci polynomials The Tribonacci numbers are the integer sequence defined by the initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`. The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`, `T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)` for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`. * ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n` * ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)` Examples ======== >>> from sympy import tribonacci, Symbol >>> [tribonacci(x) for x in range(11)] [0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149] >>> tribonacci(5, Symbol('t')) t**8 + 3*t**5 + 3*t**2 See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition References ========== .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers .. [2] http://mathworld.wolfram.com/TribonacciNumber.html .. [3] https://oeis.org/A000073 """ @staticmethod @recurrence_memo([S.Zero, S.One, S.One]) def _trib(n, prev): return (prev[-3] + prev[-2] + prev[-1]) @staticmethod @recurrence_memo([S.Zero, S.One, _sym**2]) def _tribpoly(n, prev): return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand() @classmethod def eval(cls, n, sym=None): if n is S.Infinity: return S.Infinity if n.is_Integer: n = int(n) if n < 0: raise ValueError("Tribonacci polynomials are defined " "only for non-negative integer indices.") if sym is None: return Integer(cls._trib(n)) else: return cls._tribpoly(n).subs(_sym, sym) def _eval_rewrite_as_sqrt(self, n, **kwargs): from sympy.functions.elementary.miscellaneous import cbrt, sqrt w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2 a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3 b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3 c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3 Tn = (a**(n + 1)/((a - b)*(a - c)) + b**(n + 1)/((b - a)*(b - c)) + c**(n + 1)/((c - a)*(c - b))) return Tn def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs): from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import cbrt, sqrt b = cbrt(586 + 102*sqrt(33)) Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4) return floor(Tn + S.Half) #----------------------------------------------------------------------------# # # # Bernoulli numbers # # # #----------------------------------------------------------------------------# class bernoulli(Function): r""" Bernoulli numbers / Bernoulli polynomials The Bernoulli numbers are a sequence of rational numbers defined by `B_0 = 1` and the recursive relation (`n > 0`): .. math :: 0 = \sum_{k=0}^n \binom{n+1}{k} B_k They are also commonly defined by their exponential generating function, which is `\frac{x}{e^x - 1}`. For odd indices > 1, the Bernoulli numbers are zero. The Bernoulli polynomials satisfy the analogous formula: .. math :: B_n(x) = \sum_{k=0}^n \binom{n}{k} B_k x^{n-k} Bernoulli numbers and Bernoulli polynomials are related as `B_n(0) = B_n`. We compute Bernoulli numbers using Ramanujan's formula: .. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}} where: .. math :: A(n) = \begin{cases} \frac{n+3}{3} & n \equiv 0\ \text{or}\ 2 \pmod{6} \\ -\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases} and: .. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k} This formula is similar to the sum given in the definition, but cuts 2/3 of the terms. For Bernoulli polynomials, we use the formula in the definition. * ``bernoulli(n)`` gives the nth Bernoulli number, `B_n` * ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)` Examples ======== >>> from sympy import bernoulli >>> [bernoulli(n) for n in range(11)] [1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66] >>> bernoulli(1000001) 0 See Also ======== bell, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_number .. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial .. [3] http://mathworld.wolfram.com/BernoulliNumber.html .. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html """ args: tTuple[Integer] # Calculates B_n for positive even n @staticmethod def _calc_bernoulli(n): s = 0 a = int(binomial(n + 3, n - 6)) for j in range(1, n//6 + 1): s += a * bernoulli(n - 6*j) # Avoid computing each binomial coefficient from scratch a *= _product(n - 6 - 6*j + 1, n - 6*j) a //= _product(6*j + 4, 6*j + 9) if n % 6 == 4: s = -Rational(n + 3, 6) - s else: s = Rational(n + 3, 3) - s return s / binomial(n + 3, n) # We implement a specialized memoization scheme to handle each # case modulo 6 separately _cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)} _highest = {0: 0, 2: 2, 4: 4} @classmethod def eval(cls, n, sym=None): if n.is_Number: if n.is_Integer and n.is_nonnegative: if n.is_zero: return S.One elif n is S.One: if sym is None: return Rational(-1, 2) else: return sym - S.Half # Bernoulli numbers elif sym is None: if n.is_odd: return S.Zero n = int(n) # Use mpmath for enormous Bernoulli numbers if n > 500: p, q = bernfrac(n) return Rational(int(p), int(q)) case = n % 6 highest_cached = cls._highest[case] if n <= highest_cached: return cls._cache[n] # To avoid excessive recursion when, say, bernoulli(1000) is # requested, calculate and cache the entire sequence ... B_988, # B_994, B_1000 in increasing order for i in range(highest_cached + 6, n + 6, 6): b = cls._calc_bernoulli(i) cls._cache[i] = b cls._highest[case] = i return b # Bernoulli polynomials else: n, result = int(n), [] for k in range(n + 1): result.append(binomial(n, k)*cls(k)*sym**(n - k)) return Add(*result) else: raise ValueError("Bernoulli numbers are defined only" " for nonnegative integer indices.") if sym is None: if n.is_odd and (n - 1).is_positive: return S.Zero #----------------------------------------------------------------------------# # # # Bell numbers # # # #----------------------------------------------------------------------------# class bell(Function): r""" Bell numbers / Bell polynomials The Bell numbers satisfy `B_0 = 1` and .. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k. They are also given by: .. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}. The Bell polynomials are given by `B_0(x) = 1` and .. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x). The second kind of Bell polynomials (are sometimes called "partial" Bell polynomials or incomplete Bell polynomials) are defined as .. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) = \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n} \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!} \left(\frac{x_1}{1!} \right)^{j_1} \left(\frac{x_2}{2!} \right)^{j_2} \dotsb \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}. * ``bell(n)`` gives the `n^{th}` Bell number, `B_n`. * ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`. * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind, `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`. Notes ===== Not to be confused with Bernoulli numbers and Bernoulli polynomials, which use the same notation. Examples ======== >>> from sympy import bell, Symbol, symbols >>> [bell(n) for n in range(11)] [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975] >>> bell(30) 846749014511809332450147 >>> bell(4, Symbol('t')) t**4 + 6*t**3 + 7*t**2 + t >>> bell(6, 2, symbols('x:6')[1:]) 6*x1*x5 + 15*x2*x4 + 10*x3**2 See Also ======== bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Bell_number .. [2] http://mathworld.wolfram.com/BellNumber.html .. [3] http://mathworld.wolfram.com/BellPolynomial.html """ @staticmethod @recurrence_memo([1, 1]) def _bell(n, prev): s = 1 a = 1 for k in range(1, n): a = a * (n - k) // k s += a * prev[k] return s @staticmethod @recurrence_memo([S.One, _sym]) def _bell_poly(n, prev): s = 1 a = 1 for k in range(2, n + 1): a = a * (n - k + 1) // (k - 1) s += a * prev[k - 1] return expand_mul(_sym * s) @staticmethod def _bell_incomplete_poly(n, k, symbols): r""" The second kind of Bell polynomials (incomplete Bell polynomials). Calculated by recurrence formula: .. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) = \sum_{m=1}^{n-k+1} \x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k}) where `B_{0,0} = 1;` `B_{n,0} = 0; for n \ge 1` `B_{0,k} = 0; for k \ge 1` """ if (n == 0) and (k == 0): return S.One elif (n == 0) or (k == 0): return S.Zero s = S.Zero a = S.One for m in range(1, n - k + 2): s += a * bell._bell_incomplete_poly( n - m, k - 1, symbols) * symbols[m - 1] a = a * (n - m) / m return expand_mul(s) @classmethod def eval(cls, n, k_sym=None, symbols=None): if n is S.Infinity: if k_sym is None: return S.Infinity else: raise ValueError("Bell polynomial is not defined") if n.is_negative or n.is_integer is False: raise ValueError("a non-negative integer expected") if n.is_Integer and n.is_nonnegative: if k_sym is None: return Integer(cls._bell(int(n))) elif symbols is None: return cls._bell_poly(int(n)).subs(_sym, k_sym) else: r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols) return r def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs): from sympy.concrete.summations import Sum if (k_sym is not None) or (symbols is not None): return self # Dobinski's formula if not n.is_nonnegative: return self k = Dummy('k', integer=True, nonnegative=True) return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity)) #----------------------------------------------------------------------------# # # # Harmonic numbers # # # #----------------------------------------------------------------------------# class harmonic(Function): r""" Harmonic numbers The nth harmonic number is given by `\operatorname{H}_{n} = 1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`. More generally: .. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m} As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`, the Riemann zeta function. * ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n` * ``harmonic(n, m)`` gives the nth generalized harmonic number of order `m`, `\operatorname{H}_{n,m}`, where ``harmonic(n) == harmonic(n, 1)`` Examples ======== >>> from sympy import harmonic, oo >>> [harmonic(n) for n in range(6)] [0, 1, 3/2, 11/6, 25/12, 137/60] >>> [harmonic(n, 2) for n in range(6)] [0, 1, 5/4, 49/36, 205/144, 5269/3600] >>> harmonic(oo, 2) pi**2/6 >>> from sympy import Symbol, Sum >>> n = Symbol("n") >>> harmonic(n).rewrite(Sum) Sum(1/_k, (_k, 1, n)) We can evaluate harmonic numbers for all integral and positive rational arguments: >>> from sympy import S, expand_func, simplify >>> harmonic(8) 761/280 >>> harmonic(11) 83711/27720 >>> H = harmonic(1/S(3)) >>> H harmonic(1/3) >>> He = expand_func(H) >>> He -log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1)) + 3*Sum(1/(3*_k + 1), (_k, 0, 0)) >>> He.doit() -log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3 >>> H = harmonic(25/S(7)) >>> He = simplify(expand_func(H).doit()) >>> He log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900 >>> He.n(40) 1.983697455232980674869851942390639915940 >>> harmonic(25/S(7)).n(40) 1.983697455232980674869851942390639915940 We can rewrite harmonic numbers in terms of polygamma functions: >>> from sympy import digamma, polygamma >>> m = Symbol("m") >>> harmonic(n).rewrite(digamma) polygamma(0, n + 1) + EulerGamma >>> harmonic(n).rewrite(polygamma) polygamma(0, n + 1) + EulerGamma >>> harmonic(n,3).rewrite(polygamma) polygamma(2, n + 1)/2 - polygamma(2, 1)/2 >>> harmonic(n,m).rewrite(polygamma) (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1) Integer offsets in the argument can be pulled out: >>> from sympy import expand_func >>> expand_func(harmonic(n+4)) harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1) >>> expand_func(harmonic(n-4)) harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n Some limits can be computed as well: >>> from sympy import limit, oo >>> limit(harmonic(n), n, oo) oo >>> limit(harmonic(n, 2), n, oo) pi**2/6 >>> limit(harmonic(n, 3), n, oo) -polygamma(2, 1)/2 However we cannot compute the general relation yet: >>> limit(harmonic(n, m), n, oo) harmonic(oo, m) which equals ``zeta(m)`` for ``m > 1``. See Also ======== bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Harmonic_number .. [2] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber/ .. [3] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/ """ # Generate one memoized Harmonic number-generating function for each # order and store it in a dictionary _functions = {} # type: tDict[Integer, Callable[[int], Rational]] @classmethod def eval(cls, n, m=None): from sympy.functions.special.zeta_functions import zeta if m is S.One: return cls(n) if m is None: m = S.One if m.is_zero: return n if n is S.Infinity: if m.is_negative: return S.NaN elif is_le(m, S.One): return S.Infinity elif is_gt(m, S.One): return zeta(m) else: return if n == 0: return S.Zero if n.is_Integer and n.is_nonnegative and m.is_Integer: if m not in cls._functions: @recurrence_memo([0]) def f(n, prev): return prev[-1] + S.One / n**m cls._functions[m] = f return cls._functions[m](int(n)) def _eval_rewrite_as_polygamma(self, n, m=1, **kwargs): from sympy.functions.special.gamma_functions import polygamma return S.NegativeOne**m/factorial(m - 1) * (polygamma(m - 1, 1) - polygamma(m - 1, n + 1)) def _eval_rewrite_as_digamma(self, n, m=1, **kwargs): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma) def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma) def _eval_rewrite_as_Sum(self, n, m=None, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k", integer=True) if m is None: m = S.One return Sum(k**(-m), (k, 1, n)) def _eval_expand_func(self, **hints): from sympy.concrete.summations import Sum n = self.args[0] m = self.args[1] if len(self.args) == 2 else 1 if m == S.One: if n.is_Add: off = n.args[0] nnew = n - off if off.is_Integer and off.is_positive: result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)] return Add(*result) elif off.is_Integer and off.is_negative: result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)] return Add(*result) if n.is_Rational: # Expansions for harmonic numbers at general rational arguments (u + p/q) # Split n as u + p/q with p < q p, q = n.as_numer_denom() u = p // q p = p - u * q if u.is_nonnegative and p.is_positive and q.is_positive and p < q: from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor from sympy.functions.elementary.trigonometric import sin, cos, cot k = Dummy("k") t1 = q * Sum(1 / (q * k + p), (k, 0, u)) t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) * log(sin((pi * k) / S(q))), (k, 1, floor((q - 1) / S(2)))) t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q) return t1 + t2 - t3 return self def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma).rewrite("tractable", deep=True) def _eval_evalf(self, prec): from sympy.functions.special.gamma_functions import polygamma if all(i.is_number for i in self.args): return self.rewrite(polygamma)._eval_evalf(prec) #----------------------------------------------------------------------------# # # # Euler numbers # # # #----------------------------------------------------------------------------# class euler(Function): r""" Euler numbers / Euler polynomials The Euler numbers are given by: .. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j} \frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k} .. math:: E_{2n+1} = 0 Euler numbers and Euler polynomials are related by .. math:: E_n = 2^n E_n\left(\frac{1}{2}\right). We compute symbolic Euler polynomials using [5]_ .. math:: E_n(x) = \sum_{k=0}^n \binom{n}{k} \frac{E_k}{2^k} \left(x - \frac{1}{2}\right)^{n-k}. However, numerical evaluation of the Euler polynomial is computed more efficiently (and more accurately) using the mpmath library. * ``euler(n)`` gives the `n^{th}` Euler number, `E_n`. * ``euler(n, x)`` gives the `n^{th}` Euler polynomial, `E_n(x)`. Examples ======== >>> from sympy import euler, Symbol, S >>> [euler(n) for n in range(10)] [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0] >>> n = Symbol("n") >>> euler(n + 2*n) euler(3*n) >>> x = Symbol("x") >>> euler(n, x) euler(n, x) >>> euler(0, x) 1 >>> euler(1, x) x - 1/2 >>> euler(2, x) x**2 - x >>> euler(3, x) x**3 - 3*x**2/2 + 1/4 >>> euler(4, x) x**4 - 2*x**3 + x >>> euler(12, S.Half) 2702765/4096 >>> euler(12) 2702765 See Also ======== bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Euler_numbers .. [2] http://mathworld.wolfram.com/EulerNumber.html .. [3] https://en.wikipedia.org/wiki/Alternating_permutation .. [4] http://mathworld.wolfram.com/AlternatingPermutation.html .. [5] http://dlmf.nist.gov/24.2#ii """ @classmethod def eval(cls, m, sym=None): if m.is_Number: if m.is_Integer and m.is_nonnegative: # Euler numbers if sym is None: if m.is_odd: return S.Zero from mpmath import mp m = m._to_mpmath(mp.prec) res = mp.eulernum(m, exact=True) return Integer(res) # Euler polynomial else: reim = pure_complex(sym, or_real=True) # Evaluate polynomial numerically using mpmath if reim and all(a.is_Float or a.is_Integer for a in reim) \ and any(a.is_Float for a in reim): from mpmath import mp m = int(m) # XXX ComplexFloat (#12192) would be nice here, above prec = min([a._prec for a in reim if a.is_Float]) with workprec(prec): res = mp.eulerpoly(m, sym) return Expr._from_mpmath(res, prec) # Construct polynomial symbolically from definition m, result = int(m), [] for k in range(m + 1): result.append(binomial(m, k)*cls(k)/(2**k)*(sym - S.Half)**(m - k)) return Add(*result).expand() else: raise ValueError("Euler numbers are defined only" " for nonnegative integer indices.") if sym is None: if m.is_odd and m.is_positive: return S.Zero def _eval_rewrite_as_Sum(self, n, x=None, **kwargs): from sympy.concrete.summations import Sum if x is None and n.is_even: k = Dummy("k", integer=True) j = Dummy("j", integer=True) n = n / 2 Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j * (k - 2*j)**(2*n + 1)) / (2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1))) return Em if x: k = Dummy("k", integer=True) return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n)) def _eval_evalf(self, prec): m, x = (self.args[0], None) if len(self.args) == 1 else self.args if x is None and m.is_Integer and m.is_nonnegative: from mpmath import mp m = m._to_mpmath(prec) with workprec(prec): res = mp.eulernum(m) return Expr._from_mpmath(res, prec) if x and x.is_number and m.is_Integer and m.is_nonnegative: from mpmath import mp m = int(m) x = x._to_mpmath(prec) with workprec(prec): res = mp.eulerpoly(m, x) return Expr._from_mpmath(res, prec) #----------------------------------------------------------------------------# # # # Catalan numbers # # # #----------------------------------------------------------------------------# class catalan(Function): r""" Catalan numbers The `n^{th}` catalan number is given by: .. math :: C_n = \frac{1}{n+1} \binom{2n}{n} * ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n` Examples ======== >>> from sympy import (Symbol, binomial, gamma, hyper, ... catalan, diff, combsimp, Rational, I) >>> [catalan(i) for i in range(1,10)] [1, 2, 5, 14, 42, 132, 429, 1430, 4862] >>> n = Symbol("n", integer=True) >>> catalan(n) catalan(n) Catalan numbers can be transformed into several other, identical expressions involving other mathematical functions >>> catalan(n).rewrite(binomial) binomial(2*n, n)/(n + 1) >>> catalan(n).rewrite(gamma) 4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2)) >>> catalan(n).rewrite(hyper) hyper((1 - n, -n), (2,), 1) For some non-integer values of n we can get closed form expressions by rewriting in terms of gamma functions: >>> catalan(Rational(1, 2)).rewrite(gamma) 8/(3*pi) We can differentiate the Catalan numbers C(n) interpreted as a continuous real function in n: >>> diff(catalan(n), n) (polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n) As a more advanced example consider the following ratio between consecutive numbers: >>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial)) 2*(2*n + 1)/(n + 2) The Catalan numbers can be generalized to complex numbers: >>> catalan(I).rewrite(gamma) 4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I)) and evaluated with arbitrary precision: >>> catalan(I).evalf(20) 0.39764993382373624267 - 0.020884341620842555705*I See Also ======== bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci sympy.functions.combinatorial.factorials.binomial References ========== .. [1] https://en.wikipedia.org/wiki/Catalan_number .. [2] http://mathworld.wolfram.com/CatalanNumber.html .. [3] http://functions.wolfram.com/GammaBetaErf/CatalanNumber/ .. [4] http://geometer.org/mathcircles/catalan.pdf """ @classmethod def eval(cls, n): from sympy.functions.special.gamma_functions import gamma if (n.is_Integer and n.is_nonnegative) or \ (n.is_noninteger and n.is_negative): return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2)) if (n.is_integer and n.is_negative): if (n + 1).is_negative: return S.Zero if (n + 1).is_zero: return Rational(-1, 2) def fdiff(self, argindex=1): from sympy.functions.elementary.exponential import log from sympy.functions.special.gamma_functions import polygamma n = self.args[0] return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4)) def _eval_rewrite_as_binomial(self, n, **kwargs): return binomial(2*n, n)/(n + 1) def _eval_rewrite_as_factorial(self, n, **kwargs): return factorial(2*n) / (factorial(n+1) * factorial(n)) def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): from sympy.functions.special.gamma_functions import gamma # The gamma function allows to generalize Catalan numbers to complex n return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2)) def _eval_rewrite_as_hyper(self, n, **kwargs): from sympy.functions.special.hyper import hyper return hyper([1 - n, -n], [2], 1) def _eval_rewrite_as_Product(self, n, **kwargs): from sympy.concrete.products import Product if not (n.is_integer and n.is_nonnegative): return self k = Dummy('k', integer=True, positive=True) return Product((n + k) / k, (k, 2, n)) def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_is_positive(self): if self.args[0].is_nonnegative: return True def _eval_is_composite(self): if self.args[0].is_integer and (self.args[0] - 3).is_positive: return True def _eval_evalf(self, prec): from sympy.functions.special.gamma_functions import gamma if self.args[0].is_number: return self.rewrite(gamma)._eval_evalf(prec) #----------------------------------------------------------------------------# # # # Genocchi numbers # # # #----------------------------------------------------------------------------# class genocchi(Function): r""" Genocchi numbers The Genocchi numbers are a sequence of integers `G_n` that satisfy the relation: .. math:: \frac{2t}{e^t + 1} = \sum_{n=1}^\infty \frac{G_n t^n}{n!} Examples ======== >>> from sympy import genocchi, Symbol >>> [genocchi(n) for n in range(1, 9)] [1, -1, 0, 1, 0, -3, 0, 17] >>> n = Symbol('n', integer=True, positive=True) >>> genocchi(2*n + 1) 0 See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Genocchi_number .. [2] http://mathworld.wolfram.com/GenocchiNumber.html """ @classmethod def eval(cls, n): if n.is_Number: if (not n.is_Integer) or n.is_nonpositive: raise ValueError("Genocchi numbers are defined only for " + "positive integers") return 2 * (1 - S(2) ** n) * bernoulli(n) if n.is_odd and (n - 1).is_positive: return S.Zero if (n - 1).is_zero: return S.One def _eval_rewrite_as_bernoulli(self, n, **kwargs): if n.is_integer and n.is_nonnegative: return (1 - S(2) ** n) * bernoulli(n) * 2 def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_positive: return True def _eval_is_negative(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_odd: return False return (n / 2).is_odd def _eval_is_positive(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_odd: return fuzzy_not((n - 1).is_positive) return (n / 2).is_even def _eval_is_even(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_even: return False return (n - 1).is_positive def _eval_is_odd(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_even: return True return fuzzy_not((n - 1).is_positive) def _eval_is_prime(self): n = self.args[0] # only G_6 = -3 and G_8 = 17 are prime, # but SymPy does not consider negatives as prime # so only n=8 is tested return (n - 8).is_zero #----------------------------------------------------------------------------# # # # Partition numbers # # # #----------------------------------------------------------------------------# _npartition = [1, 1] class partition(Function): r""" Partition numbers The Partition numbers are a sequence of integers `p_n` that represent the number of distinct ways of representing `n` as a sum of natural numbers (with order irrelevant). The generating function for `p_n` is given by: .. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1} Examples ======== >>> from sympy import partition, Symbol >>> [partition(n) for n in range(9)] [1, 1, 2, 3, 5, 7, 11, 15, 22] >>> n = Symbol('n', integer=True, negative=True) >>> partition(n) 0 See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29 .. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem """ @staticmethod def _partition(n): L = len(_npartition) if n < L: return _npartition[n] # lengthen cache for _n in range(L, n + 1): v, p, i = 0, 0, 0 while 1: s = 0 p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ... if _n >= p: s += _npartition[_n - p] i += 1 gp = p + i # gp = generalized pentagonal: 2, 7, 15, ... if _n >= gp: s += _npartition[_n - gp] if s == 0: break else: v += s if i%2 == 1 else -s _npartition.append(v) return v @classmethod def eval(cls, n): is_int = n.is_integer if is_int == False: raise ValueError("Partition numbers are defined only for " "integers") elif is_int: if n.is_negative: return S.Zero if n.is_zero or (n - 1).is_zero: return S.One if n.is_Integer: return Integer(cls._partition(n)) def _eval_is_integer(self): if self.args[0].is_integer: return True def _eval_is_negative(self): if self.args[0].is_integer: return False def _eval_is_positive(self): n = self.args[0] if n.is_nonnegative and n.is_integer: return True ####################################################################### ### ### Functions for enumerating partitions, permutations and combinations ### ####################################################################### class _MultisetHistogram(tuple): pass _N = -1 _ITEMS = -2 _M = slice(None, _ITEMS) def _multiset_histogram(n): """Return tuple used in permutation and combination counting. Input is a dictionary giving items with counts as values or a sequence of items (which need not be sorted). The data is stored in a class deriving from tuple so it is easily recognized and so it can be converted easily to a list. """ if isinstance(n, dict): # item: count if not all(isinstance(v, int) and v >= 0 for v in n.values()): raise ValueError tot = sum(n.values()) items = sum(1 for k in n if n[k] > 0) return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot]) else: n = list(n) s = set(n) lens = len(s) lenn = len(n) if lens == lenn: n = [1]*lenn + [lenn, lenn] return _MultisetHistogram(n) m = dict(zip(s, range(lens))) d = dict(zip(range(lens), (0,)*lens)) for i in n: d[m[i]] += 1 return _multiset_histogram(d) def nP(n, k=None, replacement=False): """Return the number of permutations of ``n`` items taken ``k`` at a time. Possible values for ``n``: integer - set of length ``n`` sequence - converted to a multiset internally multiset - {element: multiplicity} If ``k`` is None then the total of all permutations of length 0 through the number of items represented by ``n`` will be returned. If ``replacement`` is True then a given item can appear more than once in the ``k`` items. (For example, for 'ab' permutations of 2 would include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in ``n`` is ignored when ``replacement`` is True but the total number of elements is considered since no element can appear more times than the number of elements in ``n``. Examples ======== >>> from sympy.functions.combinatorial.numbers import nP >>> from sympy.utilities.iterables import multiset_permutations, multiset >>> nP(3, 2) 6 >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6 True >>> nP('aab', 2) 3 >>> nP([1, 2, 2], 2) 3 >>> [nP(3, i) for i in range(4)] [1, 3, 6, 6] >>> nP(3) == sum(_) True When ``replacement`` is True, each item can have multiplicity equal to the length represented by ``n``: >>> nP('aabc', replacement=True) 121 >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)] [1, 3, 9, 27, 81] >>> sum(_) 121 See Also ======== sympy.utilities.iterables.multiset_permutations References ========== .. [1] https://en.wikipedia.org/wiki/Permutation """ try: n = as_int(n) except ValueError: return Integer(_nP(_multiset_histogram(n), k, replacement)) return Integer(_nP(n, k, replacement)) @cacheit def _nP(n, k=None, replacement=False): if k == 0: return 1 if isinstance(n, SYMPY_INTS): # n different items # assert n >= 0 if k is None: return sum(_nP(n, i, replacement) for i in range(n + 1)) elif replacement: return n**k elif k > n: return 0 elif k == n: return factorial(k) elif k == 1: return n else: # assert k >= 0 return _product(n - k + 1, n) elif isinstance(n, _MultisetHistogram): if k is None: return sum(_nP(n, i, replacement) for i in range(n[_N] + 1)) elif replacement: return n[_ITEMS]**k elif k == n[_N]: return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1]) elif k > n[_N]: return 0 elif k == 1: return n[_ITEMS] else: # assert k >= 0 tot = 0 n = list(n) for i in range(len(n[_M])): if not n[i]: continue n[_N] -= 1 if n[i] == 1: n[i] = 0 n[_ITEMS] -= 1 tot += _nP(_MultisetHistogram(n), k - 1) n[_ITEMS] += 1 n[i] = 1 else: n[i] -= 1 tot += _nP(_MultisetHistogram(n), k - 1) n[i] += 1 n[_N] += 1 return tot @cacheit def _AOP_product(n): """for n = (m1, m2, .., mk) return the coefficients of the polynomial, prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients of the product of AOPs (all-one polynomials) or order given in n. The resulting coefficient corresponding to x**r is the number of r-length combinations of sum(n) elements with multiplicities given in n. The coefficients are given as a default dictionary (so if a query is made for a key that is not present, 0 will be returned). Examples ======== >>> from sympy.functions.combinatorial.numbers import _AOP_product >>> from sympy.abc import x >>> n = (2, 2, 3) # e.g. aabbccc >>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand() >>> c = _AOP_product(n); dict(c) {0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1} >>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)] True The generating poly used here is the same as that listed in http://tinyurl.com/cep849r, but in a refactored form. """ n = list(n) ord = sum(n) need = (ord + 2)//2 rv = [1]*(n.pop() + 1) rv.extend((0,) * (need - len(rv))) rv = rv[:need] while n: ni = n.pop() N = ni + 1 was = rv[:] for i in range(1, min(N, len(rv))): rv[i] += rv[i - 1] for i in range(N, need): rv[i] += rv[i - 1] - was[i - N] rev = list(reversed(rv)) if ord % 2: rv = rv + rev else: rv[-1:] = rev d = defaultdict(int) for i in range(len(rv)): d[i] = rv[i] return d def nC(n, k=None, replacement=False): """Return the number of combinations of ``n`` items taken ``k`` at a time. Possible values for ``n``: integer - set of length ``n`` sequence - converted to a multiset internally multiset - {element: multiplicity} If ``k`` is None then the total of all combinations of length 0 through the number of items represented in ``n`` will be returned. If ``replacement`` is True then a given item can appear more than once in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa', 'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when ``replacement`` is True but the total number of elements is considered since no element can appear more times than the number of elements in ``n``. Examples ======== >>> from sympy.functions.combinatorial.numbers import nC >>> from sympy.utilities.iterables import multiset_combinations >>> nC(3, 2) 3 >>> nC('abc', 2) 3 >>> nC('aab', 2) 2 When ``replacement`` is True, each item can have multiplicity equal to the length represented by ``n``: >>> nC('aabc', replacement=True) 35 >>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)] [1, 3, 6, 10, 15] >>> sum(_) 35 If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k`` then the total of all combinations of length 0 through ``k`` is the product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity of each item is 1 (i.e., k unique items) then there are 2**k combinations. For example, if there are 4 unique items, the total number of combinations is 16: >>> sum(nC(4, i) for i in range(5)) 16 See Also ======== sympy.utilities.iterables.multiset_combinations References ========== .. [1] https://en.wikipedia.org/wiki/Combination .. [2] http://tinyurl.com/cep849r """ if isinstance(n, SYMPY_INTS): if k is None: if not replacement: return 2**n return sum(nC(n, i, replacement) for i in range(n + 1)) if k < 0: raise ValueError("k cannot be negative") if replacement: return binomial(n + k - 1, k) return binomial(n, k) if isinstance(n, _MultisetHistogram): N = n[_N] if k is None: if not replacement: return prod(m + 1 for m in n[_M]) return sum(nC(n, i, replacement) for i in range(N + 1)) elif replacement: return nC(n[_ITEMS], k, replacement) # assert k >= 0 elif k in (1, N - 1): return n[_ITEMS] elif k in (0, N): return 1 return _AOP_product(tuple(n[_M]))[k] else: return nC(_multiset_histogram(n), k, replacement) def _eval_stirling1(n, k): if n == k == 0: return S.One if 0 in (n, k): return S.Zero # some special values if n == k: return S.One elif k == n - 1: return binomial(n, 2) elif k == n - 2: return (3*n - 1)*binomial(n, 3)/4 elif k == n - 3: return binomial(n, 2)*binomial(n, 4) return _stirling1(n, k) @cacheit def _stirling1(n, k): row = [0, 1]+[0]*(k-1) # for n = 1 for i in range(2, n+1): for j in range(min(k,i), 0, -1): row[j] = (i-1) * row[j] + row[j-1] return Integer(row[k]) def _eval_stirling2(n, k): if n == k == 0: return S.One if 0 in (n, k): return S.Zero # some special values if n == k: return S.One elif k == n - 1: return binomial(n, 2) elif k == 1: return S.One elif k == 2: return Integer(2**(n - 1) - 1) return _stirling2(n, k) @cacheit def _stirling2(n, k): row = [0, 1]+[0]*(k-1) # for n = 1 for i in range(2, n+1): for j in range(min(k,i), 0, -1): row[j] = j * row[j] + row[j-1] return Integer(row[k]) def stirling(n, k, d=None, kind=2, signed=False): r"""Return Stirling number $S(n, k)$ of the first or second (default) kind. The sum of all Stirling numbers of the second kind for $k = 1$ through $n$ is ``bell(n)``. The recurrence relationship for these numbers is: .. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0; .. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}} where $j$ is: $n$ for Stirling numbers of the first kind, $-n$ for signed Stirling numbers of the first kind, $k$ for Stirling numbers of the second kind. The first kind of Stirling number counts the number of permutations of ``n`` distinct items that have ``k`` cycles; the second kind counts the ways in which ``n`` distinct items can be partitioned into ``k`` parts. If ``d`` is given, the "reduced Stirling number of the second kind" is returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$. (This counts the ways to partition $n$ consecutive integers into $k$ groups with no pairwise difference less than $d$. See example below.) To obtain the signed Stirling numbers of the first kind, use keyword ``signed=True``. Using this keyword automatically sets ``kind`` to 1. Examples ======== >>> from sympy.functions.combinatorial.numbers import stirling, bell >>> from sympy.combinatorics import Permutation >>> from sympy.utilities.iterables import multiset_partitions, permutations First kind (unsigned by default): >>> [stirling(6, i, kind=1) for i in range(7)] [0, 120, 274, 225, 85, 15, 1] >>> perms = list(permutations(range(4))) >>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)] [0, 6, 11, 6, 1] >>> [stirling(4, i, kind=1) for i in range(5)] [0, 6, 11, 6, 1] First kind (signed): >>> [stirling(4, i, signed=True) for i in range(5)] [0, -6, 11, -6, 1] Second kind: >>> [stirling(10, i) for i in range(12)] [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0] >>> sum(_) == bell(10) True >>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2) True Reduced second kind: >>> from sympy import subsets, oo >>> def delta(p): ... if len(p) == 1: ... return oo ... return min(abs(i[0] - i[1]) for i in subsets(p, 2)) >>> parts = multiset_partitions(range(5), 3) >>> d = 2 >>> sum(1 for p in parts if all(delta(i) >= d for i in p)) 7 >>> stirling(5, 3, 2) 7 See Also ======== sympy.utilities.iterables.multiset_partitions References ========== .. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind .. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind """ # TODO: make this a class like bell() n = as_int(n) k = as_int(k) if n < 0: raise ValueError('n must be nonnegative') if k > n: return S.Zero if d: # assert k >= d # kind is ignored -- only kind=2 is supported return _eval_stirling2(n - d + 1, k - d + 1) elif signed: # kind is ignored -- only kind=1 is supported return S.NegativeOne**(n - k)*_eval_stirling1(n, k) if kind == 1: return _eval_stirling1(n, k) elif kind == 2: return _eval_stirling2(n, k) else: raise ValueError('kind must be 1 or 2, not %s' % k) @cacheit def _nT(n, k): """Return the partitions of ``n`` items into ``k`` parts. This is used by ``nT`` for the case when ``n`` is an integer.""" # really quick exits if k > n or k < 0: return 0 if k in (1, n): return 1 if k == 0: return 0 # exits that could be done below but this is quicker if k == 2: return n//2 d = n - k if d <= 3: return d # quick exit if 3*k >= n: # or, equivalently, 2*k >= d # all the information needed in this case # will be in the cache needed to calculate # partition(d), so... # update cache tot = partition._partition(d) # and correct for values not needed if d - k > 0: tot -= sum(_npartition[:d - k]) return tot # regular exit # nT(n, k) = Sum(nT(n - k, m), (m, 1, k)); # calculate needed nT(i, j) values p = [1]*d for i in range(2, k + 1): for m in range(i + 1, d): p[m] += p[m - i] d -= 1 # if p[0] were appended to the end of p then the last # k values of p are the nT(n, j) values for 0 < j < k in reverse # order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of # putting the 1 from p[0] there, however, it is simply added to # the sum below which is valid for 1 < k <= n//2 return (1 + sum(p[1 - k:])) def nT(n, k=None): """Return the number of ``k``-sized partitions of ``n`` items. Possible values for ``n``: integer - ``n`` identical items sequence - converted to a multiset internally multiset - {element: multiplicity} Note: the convention for ``nT`` is different than that of ``nC`` and ``nP`` in that here an integer indicates ``n`` *identical* items instead of a set of length ``n``; this is in keeping with the ``partitions`` function which treats its integer-``n`` input like a list of ``n`` 1s. One can use ``range(n)`` for ``n`` to indicate ``n`` distinct items. If ``k`` is None then the total number of ways to partition the elements represented in ``n`` will be returned. Examples ======== >>> from sympy.functions.combinatorial.numbers import nT Partitions of the given multiset: >>> [nT('aabbc', i) for i in range(1, 7)] [1, 8, 11, 5, 1, 0] >>> nT('aabbc') == sum(_) True >>> [nT("mississippi", i) for i in range(1, 12)] [1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1] Partitions when all items are identical: >>> [nT(5, i) for i in range(1, 6)] [1, 2, 2, 1, 1] >>> nT('1'*5) == sum(_) True When all items are different: >>> [nT(range(5), i) for i in range(1, 6)] [1, 15, 25, 10, 1] >>> nT(range(5)) == sum(_) True Partitions of an integer expressed as a sum of positive integers: >>> from sympy import partition >>> partition(4) 5 >>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4) 5 >>> nT('1'*4) 5 See Also ======== sympy.utilities.iterables.partitions sympy.utilities.iterables.multiset_partitions sympy.functions.combinatorial.numbers.partition References ========== .. [1] http://undergraduate.csse.uwa.edu.au/units/CITS7209/partition.pdf """ if isinstance(n, SYMPY_INTS): # n identical items if k is None: return partition(n) if isinstance(k, SYMPY_INTS): n = as_int(n) k = as_int(k) return Integer(_nT(n, k)) if not isinstance(n, _MultisetHistogram): try: # if n contains hashable items there is some # quick handling that can be done u = len(set(n)) if u <= 1: return nT(len(n), k) elif u == len(n): n = range(u) raise TypeError except TypeError: n = _multiset_histogram(n) N = n[_N] if k is None and N == 1: return 1 if k in (1, N): return 1 if k == 2 or N == 2 and k is None: m, r = divmod(N, 2) rv = sum(nC(n, i) for i in range(1, m + 1)) if not r: rv -= nC(n, m)//2 if k is None: rv += 1 # for k == 1 return rv if N == n[_ITEMS]: # all distinct if k is None: return bell(N) return stirling(N, k) m = MultisetPartitionTraverser() if k is None: return m.count_partitions(n[_M]) # MultisetPartitionTraverser does not have a range-limited count # method, so need to enumerate and count tot = 0 for discard in m.enum_range(n[_M], k-1, k): tot += 1 return tot #-----------------------------------------------------------------------------# # # # Motzkin numbers # # # #-----------------------------------------------------------------------------# class motzkin(Function): """ The nth Motzkin number is the number of ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). The Motzkin numbers are named after Theodore Motzkin and have diverse applications in geometry, combinatorics and number theory. Motzkin numbers are the integer sequence defined by the initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation `M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`. Examples ======== >>> from sympy import motzkin >>> motzkin.is_motzkin(5) False >>> motzkin.find_motzkin_numbers_in_range(2,300) [2, 4, 9, 21, 51, 127] >>> motzkin.find_motzkin_numbers_in_range(2,900) [2, 4, 9, 21, 51, 127, 323, 835] >>> motzkin.find_first_n_motzkins(10) [1, 1, 2, 4, 9, 21, 51, 127, 323, 835] References ========== .. [1] https://en.wikipedia.org/wiki/Motzkin_number .. [2] https://mathworld.wolfram.com/MotzkinNumber.html """ @staticmethod def is_motzkin(n): try: n = as_int(n) except ValueError: return False if n > 0: if n in (1, 2): return True tn1 = 1 tn = 2 i = 3 while tn < n: a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2) i += 1 tn1 = tn tn = a if tn == n: return True else: return False else: return False @staticmethod def find_motzkin_numbers_in_range(x, y): if 0 <= x <= y: motzkins = list() if x <= 1 <= y: motzkins.append(1) tn1 = 1 tn = 2 i = 3 while tn <= y: if tn >= x: motzkins.append(tn) a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2) i += 1 tn1 = tn tn = int(a) return motzkins else: raise ValueError('The provided range is not valid. This condition should satisfy x <= y') @staticmethod def find_first_n_motzkins(n): try: n = as_int(n) except ValueError: raise ValueError('The provided number must be a positive integer') if n < 0: raise ValueError('The provided number must be a positive integer') motzkins = [1] if n >= 1: motzkins.append(1) tn1 = 1 tn = 2 i = 3 while i <= n: motzkins.append(tn) a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2) i += 1 tn1 = tn tn = int(a) return motzkins @staticmethod @recurrence_memo([S.One, S.One]) def _motzkin(n, prev): return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2) @classmethod def eval(cls, n): try: n = as_int(n) except ValueError: raise ValueError('The provided number must be a positive integer') if n < 0: raise ValueError('The provided number must be a positive integer') return Integer(cls._motzkin(n - 1)) def nD(i=None, brute=None, *, n=None, m=None): """return the number of derangements for: ``n`` unique items, ``i`` items (as a sequence or multiset), or multiplicities, ``m`` given as a sequence or multiset. Examples ======== >>> from sympy.utilities.iterables import generate_derangements as enum >>> from sympy.functions.combinatorial.numbers import nD A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``: >>> set([''.join(i) for i in enum('abc')]) {'bca', 'cab'} >>> nD('abc') 2 Input as iterable or dictionary (multiset form) is accepted: >>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3}) By default, a brute-force enumeration and count of multiset permutations is only done if there are fewer than 9 elements. There may be cases when there is high multiplicty with few unique elements that will benefit from a brute-force enumeration, too. For this reason, the `brute` keyword (default None) is provided. When False, the brute-force enumeration will never be used. When True, it will always be used. >>> nD('1111222233', brute=True) 44 For convenience, one may specify ``n`` distinct items using the ``n`` keyword: >>> assert nD(n=3) == nD('abc') == 2 Since the number of derangments depends on the multiplicity of the elements and not the elements themselves, it may be more convenient to give a list or multiset of multiplicities using keyword ``m``: >>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2 """ from sympy.integrals.integrals import integrate from sympy.functions.special.polynomials import laguerre from sympy.abc import x def ok(x): if not isinstance(x, SYMPY_INTS): raise TypeError('expecting integer values') if x < 0: raise ValueError('value must not be negative') return True if (i, n, m).count(None) != 2: raise ValueError('enter only 1 of i, n, or m') if i is not None: if isinstance(i, SYMPY_INTS): raise TypeError('items must be a list or dictionary') if not i: return S.Zero if type(i) is not dict: s = list(i) ms = multiset(s) elif type(i) is dict: all(ok(_) for _ in i.values()) ms = {k: v for k, v in i.items() if v} s = None if not ms: return S.Zero N = sum(ms.values()) counts = multiset(ms.values()) nkey = len(ms) elif n is not None: ok(n) if not n: return S.Zero return subfactorial(n) elif m is not None: if isinstance(m, dict): all(ok(i) and ok(j) for i, j in m.items()) counts = {k: v for k, v in m.items() if k*v} elif iterable(m) or isinstance(m, str): m = list(m) all(ok(i) for i in m) counts = multiset([i for i in m if i]) else: raise TypeError('expecting iterable') if not counts: return S.Zero N = sum(k*v for k, v in counts.items()) nkey = sum(counts.values()) s = None big = int(max(counts)) if big == 1: # no repetition return subfactorial(nkey) nval = len(counts) if big*2 > N: return S.Zero if big*2 == N: if nkey == 2 and nval == 1: return S.One # aaabbb if nkey - 1 == big: # one element repeated return factorial(big) # e.g. abc part of abcddd if N < 9 and brute is None or brute: # for all possibilities, this was found to be faster if s is None: s = [] i = 0 for m, v in counts.items(): for j in range(v): s.extend([i]*m) i += 1 return Integer(sum(1 for i in multiset_derangements(s))) from sympy.functions.elementary.exponential import exp return Integer(abs(integrate(exp(-x)*Mul(*[ laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))
9ed3716463347f61fc54397119e6056670a534ffb2d494b3a9705a7a199fba28
from typing import List from functools import reduce from sympy.core import S, sympify, Dummy, Mod from sympy.core.cache import cacheit from sympy.core.function import Function, ArgumentIndexError, PoleError from sympy.core.logic import fuzzy_and from sympy.core.numbers import Integer, pi, I from sympy.core.relational import Eq from sympy.external.gmpy import HAS_GMPY, gmpy from sympy.ntheory import sieve from sympy.polys.polytools import Poly from math import sqrt as _sqrt class CombinatorialFunction(Function): """Base class for combinatorial functions. """ def _eval_simplify(self, **kwargs): from sympy.simplify.combsimp import combsimp # combinatorial function with non-integer arguments is # automatically passed to gammasimp expr = combsimp(self) measure = kwargs['measure'] if measure(expr) <= kwargs['ratio']*measure(self): return expr return self ############################################################################### ######################## FACTORIAL and MULTI-FACTORIAL ######################## ############################################################################### class factorial(CombinatorialFunction): r"""Implementation of factorial function over nonnegative integers. By convention (consistent with the gamma function and the binomial coefficients), factorial of a negative integer is complex infinity. The factorial is very important in combinatorics where it gives the number of ways in which `n` objects can be permuted. It also arises in calculus, probability, number theory, etc. There is strict relation of factorial with gamma function. In fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this kind is very useful in case of combinatorial simplification. Computation of the factorial is done using two algorithms. For small arguments a precomputed look up table is used. However for bigger input algorithm Prime-Swing is used. It is the fastest algorithm known and computes `n!` via prime factorization of special class of numbers, called here the 'Swing Numbers'. Examples ======== >>> from sympy import Symbol, factorial, S >>> n = Symbol('n', integer=True) >>> factorial(0) 1 >>> factorial(7) 5040 >>> factorial(-2) zoo >>> factorial(n) factorial(n) >>> factorial(2*n) factorial(2*n) >>> factorial(S(1)/2) factorial(1/2) See Also ======== factorial2, RisingFactorial, FallingFactorial """ def fdiff(self, argindex=1): from sympy.functions.special.gamma_functions import (gamma, polygamma) if argindex == 1: return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1) else: raise ArgumentIndexError(self, argindex) _small_swing = [ 1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395, 12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075, 35102025, 5014575, 145422675, 9694845, 300540195, 300540195 ] _small_factorials = [] # type: List[int] @classmethod def _swing(cls, n): if n < 33: return cls._small_swing[n] else: N, primes = int(_sqrt(n)), [] for prime in sieve.primerange(3, N + 1): p, q = 1, n while True: q //= prime if q > 0: if q & 1 == 1: p *= prime else: break if p > 1: primes.append(p) for prime in sieve.primerange(N + 1, n//3 + 1): if (n // prime) & 1 == 1: primes.append(prime) L_product = R_product = 1 for prime in sieve.primerange(n//2 + 1, n + 1): L_product *= prime for prime in primes: R_product *= prime return L_product*R_product @classmethod def _recursive(cls, n): if n < 2: return 1 else: return (cls._recursive(n//2)**2)*cls._swing(n) @classmethod def eval(cls, n): n = sympify(n) if n.is_Number: if n.is_zero: return S.One elif n is S.Infinity: return S.Infinity elif n.is_Integer: if n.is_negative: return S.ComplexInfinity else: n = n.p if n < 20: if not cls._small_factorials: result = 1 for i in range(1, 20): result *= i cls._small_factorials.append(result) result = cls._small_factorials[n-1] # GMPY factorial is faster, use it when available elif HAS_GMPY: result = gmpy.fac(n) else: bits = bin(n).count('1') result = cls._recursive(n)*2**(n - bits) return Integer(result) def _facmod(self, n, q): res, N = 1, int(_sqrt(n)) # Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ... # for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m, # occur consecutively and are grouped together in pw[m] for # simultaneous exponentiation at a later stage pw = [1]*N m = 2 # to initialize the if condition below for prime in sieve.primerange(2, n + 1): if m > 1: m, y = 0, n // prime while y: m += y y //= prime if m < N: pw[m] = pw[m]*prime % q else: res = res*pow(prime, m, q) % q for ex, bs in enumerate(pw): if ex == 0 or bs == 1: continue if bs == 0: return 0 res = res*pow(bs, ex, q) % q return res def _eval_Mod(self, q): n = self.args[0] if n.is_integer and n.is_nonnegative and q.is_integer: aq = abs(q) d = aq - n if d.is_nonpositive: return S.Zero else: isprime = aq.is_prime if d == 1: # Apply Wilson's theorem (if a natural number n > 1 # is a prime number, then (n-1)! = -1 mod n) and # its inverse (if n > 4 is a composite number, then # (n-1)! = 0 mod n) if isprime: return -1 % q elif isprime is False and (aq - 6).is_nonnegative: return S.Zero elif n.is_Integer and q.is_Integer: n, d, aq = map(int, (n, d, aq)) if isprime and (d - 1 < n): fc = self._facmod(d - 1, aq) fc = pow(fc, aq - 2, aq) if d%2: fc = -fc else: fc = self._facmod(n, aq) return fc % q def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): from sympy.functions.special.gamma_functions import gamma return gamma(n + 1) def _eval_rewrite_as_Product(self, n, **kwargs): from sympy.concrete.products import Product if n.is_nonnegative and n.is_integer: i = Dummy('i', integer=True) return Product(i, (i, 1, n)) def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_is_positive(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_is_even(self): x = self.args[0] if x.is_integer and x.is_nonnegative: return (x - 2).is_nonnegative def _eval_is_composite(self): x = self.args[0] if x.is_integer and x.is_nonnegative: return (x - 3).is_nonnegative def _eval_is_real(self): x = self.args[0] if x.is_nonnegative or x.is_noninteger: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x) arg0 = arg.subs(x, 0) if arg0.is_zero: return S.One elif not arg0.is_infinite: return self.func(arg) raise PoleError("Cannot expand %s around 0" % (self)) class MultiFactorial(CombinatorialFunction): pass class subfactorial(CombinatorialFunction): r"""The subfactorial counts the derangements of $n$ items and is defined for non-negative integers as: .. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\ (n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases} It can also be written as ``int(round(n!/exp(1)))`` but the recursive definition with caching is implemented for this function. An interesting analytic expression is the following [2]_ .. math:: !x = \Gamma(x + 1, -1)/e which is valid for non-negative integers `x`. The above formula is not very useful in case of non-integers. `\Gamma(x + 1, -1)` is single-valued only for integral arguments `x`, elsewhere on the positive real axis it has an infinite number of branches none of which are real. References ========== .. [1] https://en.wikipedia.org/wiki/Subfactorial .. [2] http://mathworld.wolfram.com/Subfactorial.html Examples ======== >>> from sympy import subfactorial >>> from sympy.abc import n >>> subfactorial(n + 1) subfactorial(n + 1) >>> subfactorial(5) 44 See Also ======== factorial, uppergamma, sympy.utilities.iterables.generate_derangements """ @classmethod @cacheit def _eval(self, n): if not n: return S.One elif n == 1: return S.Zero else: z1, z2 = 1, 0 for i in range(2, n + 1): z1, z2 = z2, (i - 1)*(z2 + z1) return z2 @classmethod def eval(cls, arg): if arg.is_Number: if arg.is_Integer and arg.is_nonnegative: return cls._eval(arg) elif arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity def _eval_is_even(self): if self.args[0].is_odd and self.args[0].is_nonnegative: return True def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_rewrite_as_factorial(self, arg, **kwargs): from sympy.concrete.summations import summation i = Dummy('i') f = S.NegativeOne**i / factorial(i) return factorial(arg) * summation(f, (i, 0, arg)) def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs): from sympy.functions.elementary.exponential import exp from sympy.functions.special.gamma_functions import (gamma, lowergamma) return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1) + gamma(arg + 1))*exp(-1) def _eval_rewrite_as_uppergamma(self, arg, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return uppergamma(arg + 1, -1)/S.Exp1 def _eval_is_nonnegative(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_is_odd(self): if self.args[0].is_even and self.args[0].is_nonnegative: return True class factorial2(CombinatorialFunction): r"""The double factorial `n!!`, not to be confused with `(n!)!` The double factorial is defined for nonnegative integers and for odd negative integers as: .. math:: n!! = \begin{cases} 1 & n = 0 \\ n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\ n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\ (n+2)!!/(n+2) & n\ \text{negative odd} \end{cases} References ========== .. [1] https://en.wikipedia.org/wiki/Double_factorial Examples ======== >>> from sympy import factorial2, var >>> n = var('n') >>> n n >>> factorial2(n + 1) factorial2(n + 1) >>> factorial2(5) 15 >>> factorial2(-1) 1 >>> factorial2(-5) 1/3 See Also ======== factorial, RisingFactorial, FallingFactorial """ @classmethod def eval(cls, arg): # TODO: extend this to complex numbers? if arg.is_Number: if not arg.is_Integer: raise ValueError("argument must be nonnegative integer " "or negative odd integer") # This implementation is faster than the recursive one # It also avoids "maximum recursion depth exceeded" runtime error if arg.is_nonnegative: if arg.is_even: k = arg / 2 return 2**k * factorial(k) return factorial(arg) / factorial2(arg - 1) if arg.is_odd: return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg) raise ValueError("argument must be nonnegative integer " "or negative odd integer") def _eval_is_even(self): # Double factorial is even for every positive even input n = self.args[0] if n.is_integer: if n.is_odd: return False if n.is_even: if n.is_positive: return True if n.is_zero: return False def _eval_is_integer(self): # Double factorial is an integer for every nonnegative input, and for # -1 and -3 n = self.args[0] if n.is_integer: if (n + 1).is_nonnegative: return True if n.is_odd: return (n + 3).is_nonnegative def _eval_is_odd(self): # Double factorial is odd for every odd input not smaller than -3, and # for 0 n = self.args[0] if n.is_odd: return (n + 3).is_nonnegative if n.is_even: if n.is_positive: return False if n.is_zero: return True def _eval_is_positive(self): # Double factorial is positive for every nonnegative input, and for # every odd negative input which is of the form -1-4k for an # nonnegative integer k n = self.args[0] if n.is_integer: if (n + 1).is_nonnegative: return True if n.is_odd: return ((n + 1) / 2).is_even def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import gamma return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2/pi), Eq(Mod(n, 2), 1))) ############################################################################### ######################## RISING and FALLING FACTORIALS ######################## ############################################################################### class RisingFactorial(CombinatorialFunction): r""" Rising factorial (also called Pochhammer symbol [1]_) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by: .. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1) where `x` can be arbitrary expression and `k` is an integer. For more information check "Concrete mathematics" by Graham, pp. 66 or visit http://mathworld.wolfram.com/RisingFactorial.html page. When `x` is a `~.Poly` instance of degree $\ge 1$ with a single variable, `(x)^k = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the variable of `x`. This is as described in [2]_. Examples ======== >>> from sympy import rf, Poly >>> from sympy.abc import x >>> rf(x, 0) 1 >>> rf(1, 5) 120 >>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x) True >>> rf(Poly(x**3, x), 2) Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ') Rewriting is complicated unless the relationship between the arguments is known, but rising factorial can be rewritten in terms of gamma, factorial, binomial, and falling factorial. >>> from sympy import Symbol, factorial, ff, binomial, gamma >>> n = Symbol('n', integer=True, positive=True) >>> R = rf(n, n + 2) >>> for i in (rf, ff, factorial, binomial, gamma): ... R.rewrite(i) ... RisingFactorial(n, n + 2) FallingFactorial(2*n + 1, n + 2) factorial(2*n + 1)/factorial(n - 1) binomial(2*n + 1, n + 2)*factorial(n + 2) gamma(2*n + 2)/gamma(n) See Also ======== factorial, factorial2, FallingFactorial References ========== .. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol .. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268, 1995. """ @classmethod def eval(cls, x, k): x = sympify(x) k = sympify(k) if x is S.NaN or k is S.NaN: return S.NaN elif x is S.One: return factorial(k) elif k.is_Integer: if k.is_zero: return S.One else: if k.is_positive: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: if k.is_odd: return S.NegativeInfinity else: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("rf only defined for " "polynomials on one generator") else: return reduce(lambda r, i: r*(x.shift(i)), range(0, int(k)), 1) else: return reduce(lambda r, i: r*(x + i), range(0, int(k)), 1) else: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("rf only defined for " "polynomials on one generator") else: return 1/reduce(lambda r, i: r*(x.shift(-i)), range(1, abs(int(k)) + 1), 1) else: return 1/reduce(lambda r, i: r*(x - i), range(1, abs(int(k)) + 1), 1) if k.is_integer == False: if x.is_integer and x.is_negative: return S.Zero def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs): from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import gamma if not piecewise: if (x <= 0) == True: return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1) return gamma(x + k) / gamma(x) return Piecewise( (gamma(x + k) / gamma(x), x > 0), (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True)) def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs): return FallingFactorial(x + k - 1, k) def _eval_rewrite_as_factorial(self, x, k, **kwargs): from sympy.functions.elementary.piecewise import Piecewise if x.is_integer and k.is_integer: return Piecewise( (factorial(k + x - 1)/factorial(x - 1), x > 0), (S.NegativeOne**k*factorial(-x)/factorial(-k - x), True)) def _eval_rewrite_as_binomial(self, x, k, **kwargs): if k.is_integer: return factorial(k) * binomial(x + k - 1, k) def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs): from sympy.functions.special.gamma_functions import gamma if limitvar: k_lim = k.subs(limitvar, S.Infinity) if k_lim is S.Infinity: return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x)) elif k_lim is S.NegativeInfinity: return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True)) return self.rewrite(gamma).rewrite('tractable', deep=True) def _eval_is_integer(self): return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer, self.args[1].is_nonnegative)) class FallingFactorial(CombinatorialFunction): r""" Falling factorial (related to rising factorial) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by .. math:: \texttt{ff(x, k)} = (x)_k = x \cdot (x-1) \cdots (x-k+1) where `x` can be arbitrary expression and `k` is an integer. For more information check "Concrete mathematics" by Graham, pp. 66 or [1]_. When `x` is a `~.Poly` instance of degree $\ge 1$ with single variable, `(x)_k = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the variable of `x`. This is as described in >>> from sympy import ff, Poly, Symbol >>> from sympy.abc import x >>> n = Symbol('n', integer=True) >>> ff(x, 0) 1 >>> ff(5, 5) 120 >>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4) True >>> ff(Poly(x**2, x), 2) Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ') >>> ff(n, n) factorial(n) Rewriting is complicated unless the relationship between the arguments is known, but falling factorial can be rewritten in terms of gamma, factorial and binomial and rising factorial. >>> from sympy import factorial, rf, gamma, binomial, Symbol >>> n = Symbol('n', integer=True, positive=True) >>> F = ff(n, n - 2) >>> for i in (rf, ff, factorial, binomial, gamma): ... F.rewrite(i) ... RisingFactorial(3, n - 2) FallingFactorial(n, n - 2) factorial(n)/2 binomial(n, n - 2)*factorial(n - 2) gamma(n + 1)/2 See Also ======== factorial, factorial2, RisingFactorial References ========== .. [1] http://mathworld.wolfram.com/FallingFactorial.html .. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268, 1995. """ @classmethod def eval(cls, x, k): x = sympify(x) k = sympify(k) if x is S.NaN or k is S.NaN: return S.NaN elif k.is_integer and x == k: return factorial(x) elif k.is_Integer: if k.is_zero: return S.One else: if k.is_positive: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: if k.is_odd: return S.NegativeInfinity else: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("ff only defined for " "polynomials on one generator") else: return reduce(lambda r, i: r*(x.shift(-i)), range(0, int(k)), 1) else: return reduce(lambda r, i: r*(x - i), range(0, int(k)), 1) else: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("rf only defined for " "polynomials on one generator") else: return 1/reduce(lambda r, i: r*(x.shift(i)), range(1, abs(int(k)) + 1), 1) else: return 1/reduce(lambda r, i: r*(x + i), range(1, abs(int(k)) + 1), 1) def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs): from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import gamma if not piecewise: if (x < 0) == True: return S.NegativeOne**k*gamma(k - x) / gamma(-x) return gamma(x + 1) / gamma(x - k + 1) return Piecewise( (gamma(x + 1) / gamma(x - k + 1), x >= 0), (S.NegativeOne**k*gamma(k - x) / gamma(-x), True)) def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs): return rf(x - k + 1, k) def _eval_rewrite_as_binomial(self, x, k, **kwargs): if k.is_integer: return factorial(k) * binomial(x, k) def _eval_rewrite_as_factorial(self, x, k, **kwargs): from sympy.functions.elementary.piecewise import Piecewise if x.is_integer and k.is_integer: return Piecewise( (factorial(x)/factorial(-k + x), x >= 0), (S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True)) def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs): from sympy.functions.special.gamma_functions import gamma if limitvar: k_lim = k.subs(limitvar, S.Infinity) if k_lim is S.Infinity: return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x)) elif k_lim is S.NegativeInfinity: return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True)) return self.rewrite(gamma).rewrite('tractable', deep=True) def _eval_is_integer(self): return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer, self.args[1].is_nonnegative)) rf = RisingFactorial ff = FallingFactorial ############################################################################### ########################### BINOMIAL COEFFICIENTS ############################# ############################################################################### class binomial(CombinatorialFunction): r"""Implementation of the binomial coefficient. It can be defined in two ways depending on its desired interpretation: .. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\ \binom{n}{k} = \frac{(n)_k}{k!} First, in a strict combinatorial sense it defines the number of ways we can choose `k` elements from a set of `n` elements. In this case both arguments are nonnegative integers and binomial is computed using an efficient algorithm based on prime factorization. The other definition is generalization for arbitrary `n`, however `k` must also be nonnegative. This case is very useful when evaluating summations. For the sake of convenience, for negative integer `k` this function will return zero no matter the other argument. To expand the binomial when `n` is a symbol, use either ``expand_func()`` or ``expand(func=True)``. The former will keep the polynomial in factored form while the latter will expand the polynomial itself. See examples for details. Examples ======== >>> from sympy import Symbol, Rational, binomial, expand_func >>> n = Symbol('n', integer=True, positive=True) >>> binomial(15, 8) 6435 >>> binomial(n, -1) 0 Rows of Pascal's triangle can be generated with the binomial function: >>> for N in range(8): ... print([binomial(N, i) for i in range(N + 1)]) ... [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] As can a given diagonal, e.g. the 4th diagonal: >>> N = -4 >>> [binomial(N, i) for i in range(1 - N)] [1, -4, 10, -20, 35] >>> binomial(Rational(5, 4), 3) -5/128 >>> binomial(Rational(-5, 4), 3) -195/128 >>> binomial(n, 3) binomial(n, 3) >>> binomial(n, 3).expand(func=True) n**3/6 - n**2/2 + n/3 >>> expand_func(binomial(n, 3)) n*(n - 2)*(n - 1)/6 References ========== .. [1] https://www.johndcook.com/blog/binomial_coefficients/ """ def fdiff(self, argindex=1): from sympy.functions.special.gamma_functions import polygamma if argindex == 1: # http://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/ n, k = self.args return binomial(n, k)*(polygamma(0, n + 1) - \ polygamma(0, n - k + 1)) elif argindex == 2: # http://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/ n, k = self.args return binomial(n, k)*(polygamma(0, n - k + 1) - \ polygamma(0, k + 1)) else: raise ArgumentIndexError(self, argindex) @classmethod def _eval(self, n, k): # n.is_Number and k.is_Integer and k != 1 and n != k if k.is_Integer: if n.is_Integer and n >= 0: n, k = int(n), int(k) if k > n: return S.Zero elif k > n // 2: k = n - k if HAS_GMPY: return Integer(gmpy.bincoef(n, k)) d, result = n - k, 1 for i in range(1, k + 1): d += 1 result = result * d // i return Integer(result) else: d, result = n - k, 1 for i in range(1, k + 1): d += 1 result *= d result /= i return result @classmethod def eval(cls, n, k): n, k = map(sympify, (n, k)) d = n - k n_nonneg, n_isint = n.is_nonnegative, n.is_integer if k.is_zero or ((n_nonneg or n_isint is False) and d.is_zero): return S.One if (k - 1).is_zero or ((n_nonneg or n_isint is False) and (d - 1).is_zero): return n if k.is_integer: if k.is_negative or (n_nonneg and n_isint and d.is_negative): return S.Zero elif n.is_number: res = cls._eval(n, k) return res.expand(basic=True) if res else res elif n_nonneg is False and n_isint: # a special case when binomial evaluates to complex infinity return S.ComplexInfinity elif k.is_number: from sympy.functions.special.gamma_functions import gamma return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) def _eval_Mod(self, q): n, k = self.args if any(x.is_integer is False for x in (n, k, q)): raise ValueError("Integers expected for binomial Mod") if all(x.is_Integer for x in (n, k, q)): n, k = map(int, (n, k)) aq, res = abs(q), 1 # handle negative integers k or n if k < 0: return S.Zero if n < 0: n = -n + k - 1 res = -1 if k%2 else 1 # non negative integers k and n if k > n: return S.Zero isprime = aq.is_prime aq = int(aq) if isprime: if aq < n: # use Lucas Theorem N, K = n, k while N or K: res = res*binomial(N % aq, K % aq) % aq N, K = N // aq, K // aq else: # use Factorial Modulo d = n - k if k > d: k, d = d, k kf = 1 for i in range(2, k + 1): kf = kf*i % aq df = kf for i in range(k + 1, d + 1): df = df*i % aq res *= df for i in range(d + 1, n + 1): res = res*i % aq res *= pow(kf*df % aq, aq - 2, aq) res %= aq else: # Binomial Factorization is performed by calculating the # exponents of primes <= n in `n! /(k! (n - k)!)`, # for non-negative integers n and k. As the exponent of # prime in n! is e_p(n) = [n/p] + [n/p**2] + ... # the exponent of prime in binomial(n, k) would be # e_p(n) - e_p(k) - e_p(n - k) M = int(_sqrt(n)) for prime in sieve.primerange(2, n + 1): if prime > n - k: res = res*prime % aq elif prime > n // 2: continue elif prime > M: if n % prime < k % prime: res = res*prime % aq else: N, K = n, k exp = a = 0 while N > 0: a = int((N % prime) < (K % prime + a)) N, K = N // prime, K // prime exp += a if exp > 0: res *= pow(prime, exp, aq) res %= aq return S(res % q) def _eval_expand_func(self, **hints): """ Function to expand binomial(n, k) when m is positive integer Also, n is self.args[0] and k is self.args[1] while using binomial(n, k) """ n = self.args[0] if n.is_Number: return binomial(*self.args) k = self.args[1] if (n-k).is_Integer: k = n - k if k.is_Integer: if k.is_zero: return S.One elif k.is_negative: return S.Zero else: n, result = self.args[0], 1 for i in range(1, k + 1): result *= n - k + i result /= i return result else: return binomial(*self.args) def _eval_rewrite_as_factorial(self, n, k, **kwargs): return factorial(n)/(factorial(k)*factorial(n - k)) def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs): from sympy.functions.special.gamma_functions import gamma return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs): return self._eval_rewrite_as_gamma(n, k).rewrite('tractable') def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs): if k.is_integer: return ff(n, k) / factorial(k) def _eval_is_integer(self): n, k = self.args if n.is_integer and k.is_integer: return True elif k.is_integer is False: return False def _eval_is_nonnegative(self): n, k = self.args if n.is_integer and k.is_integer: if n.is_nonnegative or k.is_negative or k.is_even: return True elif k.is_even is False: return False def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.special.gamma_functions import gamma return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir)
9974af6ba7b89fe11eef98ee3e7d21902222e0bbd0812932bf35fce00e4e81d5
from typing import Tuple as tTuple from sympy.core.add import Add from sympy.core.basic import sympify, cacheit from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, PoleError, expand_mul from sympy.core.logic import fuzzy_not, fuzzy_or, FuzzyBool, fuzzy_and from sympy.core.numbers import igcdex, Rational, pi, Integer from sympy.core.relational import Ne from sympy.core.singleton import S from sympy.core.symbol import Symbol, Dummy from sympy.functions.combinatorial.factorials import factorial, RisingFactorial from sympy.functions.combinatorial.numbers import bernoulli, euler from sympy.functions.elementary.complexes import arg, im, re from sympy.functions.elementary.exponential import log, exp from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt, Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.ntheory import factorint from sympy.polys.specialpolys import symmetric_poly from sympy.utilities.iterables import numbered_symbols ############################################################################### ########################## TRIGONOMETRIC FUNCTIONS ############################ ############################################################################### class TrigonometricFunction(Function): """Base class for trigonometric functions. """ unbranched = True _singularities = (S.ComplexInfinity,) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational and fuzzy_not(s.args[0].is_zero): return False else: return s.is_rational def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic: return False pi_coeff = _pi_coeff(self.args[0]) if pi_coeff is not None and pi_coeff.is_rational: return True else: return s.is_algebraic def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.args[0].expand(deep, **hints), S.Zero) else: return (self.args[0], S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (re, im) def _period(self, general_period, symbol=None): f = expand_mul(self.args[0]) if symbol is None: symbol = tuple(f.free_symbols)[0] if not f.has(symbol): return S.Zero if f == symbol: return general_period if symbol in f.free_symbols: if f.is_Mul: g, h = f.as_independent(symbol) if h == symbol: return general_period/abs(g) if f.is_Add: a, h = f.as_independent(symbol) g, h = h.as_independent(symbol, as_Add=False) if h == symbol: return general_period/abs(g) raise NotImplementedError("Use the periodicity function instead.") def _peeloff_pi(arg): r""" Split ARG into two parts, a "rest" and a multiple of $\pi$. This assumes ARG to be an Add. The multiple of $\pi$ returned in the second position is always a Rational. Examples ======== >>> from sympy.functions.elementary.trigonometric import _peeloff_pi >>> from sympy import pi >>> from sympy.abc import x, y >>> _peeloff_pi(x + pi/2) (x, 1/2) >>> _peeloff_pi(x + 2*pi/3 + pi*y) (x + pi*y + pi/6, 1/2) """ pi_coeff = S.Zero rest_terms = [] for a in Add.make_args(arg): K = a.coeff(S.Pi) if K and K.is_rational: pi_coeff += K else: rest_terms.append(a) if pi_coeff is S.Zero: return arg, S.Zero m1 = (pi_coeff % S.Half) m2 = pi_coeff - m1 if m2.is_integer or ((2*m2).is_integer and m2.is_even is False): return Add(*(rest_terms + [m1*pi])), m2 return arg, S.Zero def _pi_coeff(arg, cycles=1): r""" When arg is a Number times $\pi$ (e.g. $3\pi/2$) then return the Number normalized to be in the range $[0, 2]$, else `None`. When an even multiple of $\pi$ is encountered, if it is multiplying something with known parity then the multiple is returned as 0 otherwise as 2. Examples ======== >>> from sympy.functions.elementary.trigonometric import _pi_coeff >>> from sympy import pi, Dummy >>> from sympy.abc import x >>> _pi_coeff(3*x*pi) 3*x >>> _pi_coeff(11*pi/7) 11/7 >>> _pi_coeff(-11*pi/7) 3/7 >>> _pi_coeff(4*pi) 0 >>> _pi_coeff(5*pi) 1 >>> _pi_coeff(5.0*pi) 1 >>> _pi_coeff(5.5*pi) 3/2 >>> _pi_coeff(2 + pi) >>> _pi_coeff(2*Dummy(integer=True)*pi) 2 >>> _pi_coeff(2*Dummy(even=True)*pi) 0 """ arg = sympify(arg) if arg is S.Pi: return S.One elif not arg: return S.Zero elif arg.is_Mul: cx = arg.coeff(S.Pi) if cx: c, x = cx.as_coeff_Mul() # pi is not included as coeff if c.is_Float: # recast exact binary fractions to Rationals f = abs(c) % 1 if f != 0: p = -int(round(log(f, 2).evalf())) m = 2**p cm = c*m i = int(cm) if i == cm: c = Rational(i, m) cx = c*x else: c = Rational(int(c)) cx = c*x if x.is_integer: c2 = c % 2 if c2 == 1: return x elif not c2: if x.is_even is not None: # known parity return S.Zero return Integer(2) else: return c2*x return cx elif arg.is_zero: return S.Zero class sin(TrigonometricFunction): r""" The sine function. Returns the sine of x (measured in radians). Explanation =========== This function will evaluate automatically in the case $x/\pi$ is some rational number [4]_. For example, if $x$ is a multiple of $\pi$, $\pi/2$, $\pi/3$, $\pi/4$, and $\pi/6$. Examples ======== >>> from sympy import sin, pi >>> from sympy.abc import x >>> sin(x**2).diff(x) 2*x*cos(x**2) >>> sin(1).diff(x) 0 >>> sin(pi) 0 >>> sin(pi/2) 1 >>> sin(pi/6) 1/2 >>> sin(pi/12) -sqrt(2)/4 + sqrt(6)/4 See Also ======== csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Sin .. [4] http://mathworld.wolfram.com/TrigonometryAngles.html """ def period(self, symbol=None): return self._period(2*pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return cos(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds from sympy.sets.setexpr import SetExpr if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(-1, 1) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): from sympy.sets.sets import FiniteSet min, max = arg.min, arg.max d = floor(min/(2*S.Pi)) if min is not S.NegativeInfinity: min = min - d*2*S.Pi if max is not S.Infinity: max = max - d*2*S.Pi if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(5, 2))) \ is not S.EmptySet and \ AccumBounds(min, max).intersection(FiniteSet(S.Pi*Rational(3, 2), S.Pi*Rational(7, 2))) is not S.EmptySet: return AccumBounds(-1, 1) elif AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(5, 2))) \ is not S.EmptySet: return AccumBounds(Min(sin(min), sin(max)), 1) elif AccumBounds(min, max).intersection(FiniteSet(S.Pi*Rational(3, 2), S.Pi*Rational(8, 2))) \ is not S.EmptySet: return AccumBounds(-1, Max(sin(min), sin(max))) else: return AccumBounds(Min(sin(min), sin(max)), Max(sin(min), sin(max))) elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import sinh return S.ImaginaryUnit*sinh(i_coeff) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: return S.Zero if (2*pi_coeff).is_integer: # is_even-case handled above as then pi_coeff.is_integer, # so check if known to be not even if pi_coeff.is_even is False: return S.NegativeOne**(pi_coeff - S.Half) if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None # https://github.com/sympy/sympy/issues/6048 # transform a sine to a cosine, to avoid redundant code if pi_coeff.is_Rational: x = pi_coeff % 2 if x > 1: return -cls((x % 1)*S.Pi) if 2*x > 1: return cls((1 - x)*S.Pi) narg = ((pi_coeff + Rational(3, 2)) % 2)*S.Pi result = cos(narg) if not isinstance(result, cos): return result if pi_coeff*S.Pi != arg: return cls(pi_coeff*S.Pi) return None if arg.is_Add: x, m = _peeloff_pi(arg) if m: m = m*S.Pi return sin(m)*cos(x) + cos(m)*sin(x) if arg.is_zero: return S.Zero if isinstance(arg, asin): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return x/sqrt(1 + x**2) if isinstance(arg, atan2): y, x = arg.args return y/sqrt(x**2 + y**2) if isinstance(arg, acos): x = arg.args[0] return sqrt(1 - x**2) if isinstance(arg, acot): x = arg.args[0] return 1/(sqrt(1 + 1/x**2)*x) if isinstance(arg, acsc): x = arg.args[0] return 1/x if isinstance(arg, asec): x = arg.args[0] return sqrt(1 - 1/x**2) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return -p*x**2/(n*(n - 1)) else: return S.NegativeOne**(n//2)*x**n/factorial(n) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] if logx is not None: arg = arg.subs(log(x), logx) if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity): raise PoleError("Cannot expand %s around 0" % (self)) return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir) def _eval_rewrite_as_exp(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import HyperbolicFunction I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) - exp(-arg*I))/(2*I) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return I*x**-I/2 - I*x**I /2 def _eval_rewrite_as_cos(self, arg, **kwargs): return cos(arg - S.Pi/2, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): tan_half = tan(S.Half*arg) return 2*tan_half/(1 + tan_half**2) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)*cos(arg)/cos(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(S.Half*arg) return 2*cot_half/(1 + cot_half**2) def _eval_rewrite_as_pow(self, arg, **kwargs): return self.rewrite(cos).rewrite(pow) def _eval_rewrite_as_sqrt(self, arg, **kwargs): return self.rewrite(cos).rewrite(sqrt) def _eval_rewrite_as_csc(self, arg, **kwargs): return 1/csc(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): return 1/sec(arg - S.Pi/2, evaluate=False) def _eval_rewrite_as_sinc(self, arg, **kwargs): return arg*sinc(arg) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.hyperbolic import cosh, sinh re, im = self._as_real_imag(deep=deep, **hints) return (sin(re)*cosh(im), cos(re)*sinh(im)) def _eval_expand_trig(self, **hints): from sympy.functions.special.polynomials import chebyshevt, chebyshevu arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here # TODO: Do this more efficiently for more than two terms x, y = arg.as_two_terms() sx = sin(x, evaluate=False)._eval_expand_trig() sy = sin(y, evaluate=False)._eval_expand_trig() cx = cos(x, evaluate=False)._eval_expand_trig() cy = cos(y, evaluate=False)._eval_expand_trig() return sx*cy + sy*cx elif arg.is_Mul: n, x = arg.as_coeff_Mul(rational=True) if n.is_Integer: # n will be positive because of .eval # canonicalization # See http://mathworld.wolfram.com/Multiple-AngleFormulas.html if n.is_odd: return S.NegativeOne**((n - 1)/2)*chebyshevt(n, sin(x)) else: return expand_mul(S.NegativeOne**(n/2 - 1)*cos(x)* chebyshevu(n - 1, sin(x)), deep=False) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_Rational: return self.rewrite(sqrt) return sin(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi).as_leading_term(x) return (S.NegativeOne**n)*lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in [S.Infinity, S.NegativeInfinity]: return AccumBounds(-1, 1) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_extended_real: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return pi_mult.is_integer def _eval_is_complex(self): if self.args[0].is_extended_real \ or self.args[0].is_complex: return True class cos(TrigonometricFunction): """ The cosine function. Returns the cosine of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import cos, pi >>> from sympy.abc import x >>> cos(x**2).diff(x) -2*x*sin(x**2) >>> cos(1).diff(x) 0 >>> cos(pi) -1 >>> cos(pi/2) 0 >>> cos(2*pi/3) -1/2 >>> cos(pi/12) sqrt(2)/4 + sqrt(6)/4 See Also ======== sin, csc, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Cos """ def period(self, symbol=None): return self._period(2*pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return -sin(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.special.polynomials import chebyshevt from sympy.calculus.accumulationbounds import AccumBounds from sympy.sets.setexpr import SetExpr if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.One elif arg in (S.Infinity, S.NegativeInfinity): # In this case it is better to return AccumBounds(-1, 1) # rather than returning S.NaN, since AccumBounds(-1, 1) # preserves the information that sin(oo) is between # -1 and 1, where S.NaN does not do that. return AccumBounds(-1, 1) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): return sin(arg + S.Pi/2) elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.is_extended_real and arg.is_finite is False: return AccumBounds(-1, 1) if arg.could_extract_minus_sign(): return cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import cosh return cosh(i_coeff) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: return (S.NegativeOne)**pi_coeff if (2*pi_coeff).is_integer: # is_even-case handled above as then pi_coeff.is_integer, # so check if known to be not even if pi_coeff.is_even is False: return S.Zero if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None # cosine formula ##################### # https://github.com/sympy/sympy/issues/6048 # explicit calculations are performed for # cos(k pi/n) for n = 8,10,12,15,20,24,30,40,60,120 # Some other exact values like cos(k pi/240) can be # calculated using a partial-fraction decomposition # by calling cos( X ).rewrite(sqrt) cst_table_some = { 3: S.Half, 5: (sqrt(5) + 1)/4, } if pi_coeff.is_Rational: q = pi_coeff.q p = pi_coeff.p % (2*q) if p > q: narg = (pi_coeff - 1)*S.Pi return -cls(narg) if 2*p > q: narg = (1 - pi_coeff)*S.Pi return -cls(narg) # If nested sqrt's are worse than un-evaluation # you can require q to be in (1, 2, 3, 4, 6, 12) # q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return # expressions with 2 or fewer sqrt nestings. table2 = { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } if q in table2: a, b = p*S.Pi/table2[q][0], p*S.Pi/table2[q][1] nvala, nvalb = cls(a), cls(b) if None in (nvala, nvalb): return None return nvala*nvalb + cls(S.Pi/2 - a)*cls(S.Pi/2 - b) if q > 12: return None if q in cst_table_some: cts = cst_table_some[pi_coeff.q] return chebyshevt(pi_coeff.p, cts).expand() if 0 == q % 2: narg = (pi_coeff*2)*S.Pi nval = cls(narg) if None == nval: return None x = (2*pi_coeff + 1)/2 sign_cos = (-1)**((-1 if x < 0 else 1)*int(abs(x))) return sign_cos*sqrt( (1 + nval)/2 ) return None if arg.is_Add: x, m = _peeloff_pi(arg) if m: m = m*S.Pi return cos(m)*cos(x) - sin(m)*sin(x) if arg.is_zero: return S.One if isinstance(arg, acos): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return 1/sqrt(1 + x**2) if isinstance(arg, atan2): y, x = arg.args return x/sqrt(x**2 + y**2) if isinstance(arg, asin): x = arg.args[0] return sqrt(1 - x ** 2) if isinstance(arg, acot): x = arg.args[0] return 1/sqrt(1 + 1/x**2) if isinstance(arg, acsc): x = arg.args[0] return sqrt(1 - 1/x**2) if isinstance(arg, asec): x = arg.args[0] return 1/x @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return -p*x**2/(n*(n - 1)) else: return S.NegativeOne**(n//2)*x**n/factorial(n) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] if logx is not None: arg = arg.subs(log(x), logx) if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity): raise PoleError("Cannot expand %s around 0" % (self)) return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit from sympy.functions.elementary.hyperbolic import HyperbolicFunction if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) + exp(-arg*I))/2 def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return x**I/2 + x**-I/2 def _eval_rewrite_as_sin(self, arg, **kwargs): return sin(arg + S.Pi/2, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): tan_half = tan(S.Half*arg)**2 return (1 - tan_half)/(1 + tan_half) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)*cos(arg)/sin(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(S.Half*arg)**2 return (cot_half - 1)/(cot_half + 1) def _eval_rewrite_as_pow(self, arg, **kwargs): return self._eval_rewrite_as_sqrt(arg) def _eval_rewrite_as_sqrt(self, arg, **kwargs): from sympy.functions.special.polynomials import chebyshevt def migcdex(x): # recursive calcuation of gcd and linear combination # for a sequence of integers. # Given (x1, x2, x3) # Returns (y1, y1, y3, g) # such that g is the gcd and x1*y1+x2*y2+x3*y3 - g = 0 # Note, that this is only one such linear combination. if len(x) == 1: return (1, x[0]) if len(x) == 2: return igcdex(x[0], x[-1]) g = migcdex(x[1:]) u, v, h = igcdex(x[0], g[-1]) return tuple([u] + [v*i for i in g[0:-1] ] + [h]) def ipartfrac(r, factors=None): if isinstance(r, int): return r if not isinstance(r, Rational): raise TypeError("r is not rational") n = r.q if 2 > r.q*r.q: return r.q if None == factors: a = [n//x**y for x, y in factorint(r.q).items()] else: a = [n//x for x in factors] if len(a) == 1: return [ r ] h = migcdex(a) ans = [ r.p*Rational(i*j, r.q) for i, j in zip(h[:-1], a) ] assert r == sum(ans) return ans pi_coeff = _pi_coeff(arg) if pi_coeff is None: return None if pi_coeff.is_integer: # it was unevaluated return self.func(pi_coeff*S.Pi) if not pi_coeff.is_Rational: return None def _cospi257(): """ Express cos(pi/257) explicitly as a function of radicals Based upon the equations in http://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals See also http://www.susqu.edu/brakke/constructions/257-gon.m.txt """ def f1(a, b): return (a + sqrt(a**2 + b))/2, (a - sqrt(a**2 + b))/2 def f2(a, b): return (a - sqrt(a**2 + b))/2 t1, t2 = f1(-1, 256) z1, z3 = f1(t1, 64) z2, z4 = f1(t2, 64) y1, y5 = f1(z1, 4*(5 + t1 + 2*z1)) y6, y2 = f1(z2, 4*(5 + t2 + 2*z2)) y3, y7 = f1(z3, 4*(5 + t1 + 2*z3)) y8, y4 = f1(z4, 4*(5 + t2 + 2*z4)) x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6)) x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7)) x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8)) x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1)) x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2)) x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3)) x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4)) x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5)) v1 = f2(x1, -4*(x1 + x2 + x3 + x6)) v2 = f2(x2, -4*(x2 + x3 + x4 + x7)) v3 = f2(x8, -4*(x8 + x9 + x10 + x13)) v4 = f2(x9, -4*(x9 + x10 + x11 + x14)) v5 = f2(x10, -4*(x10 + x11 + x12 + x15)) v6 = f2(x16, -4*(x16 + x1 + x2 + x5)) u1 = -f2(-v1, -4*(v2 + v3)) u2 = -f2(-v4, -4*(v5 + v6)) w1 = -2*f2(-u1, -4*u2) return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half) cst_table_some = { 3: S.Half, 5: (sqrt(5) + 1)/4, 17: sqrt((15 + sqrt(17))/32 + sqrt(2)*(sqrt(17 - sqrt(17)) + sqrt(sqrt(2)*(-8*sqrt(17 + sqrt(17)) - (1 - sqrt(17)) *sqrt(17 - sqrt(17))) + 6*sqrt(17) + 34))/32), 257: _cospi257() # 65537 is the only other known Fermat prime and the very # large expression is intentionally omitted from SymPy; see # http://www.susqu.edu/brakke/constructions/65537-gon.m.txt } def _fermatCoords(n): # if n can be factored in terms of Fermat primes with # multiplicity of each being 1, return those primes, else # False primes = [] for p_i in cst_table_some: quotient, remainder = divmod(n, p_i) if remainder == 0: n = quotient primes.append(p_i) if n == 1: return tuple(primes) return False if pi_coeff.q in cst_table_some: rv = chebyshevt(pi_coeff.p, cst_table_some[pi_coeff.q]) if pi_coeff.q < 257: rv = rv.expand() return rv if not pi_coeff.q % 2: # recursively remove factors of 2 pico2 = pi_coeff*2 nval = cos(pico2*S.Pi).rewrite(sqrt) x = (pico2 + 1)/2 sign_cos = -1 if int(x) % 2 else 1 return sign_cos*sqrt( (1 + nval)/2 ) FC = _fermatCoords(pi_coeff.q) if FC: decomp = ipartfrac(pi_coeff, FC) X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))] pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X) return pcls.rewrite(sqrt) else: decomp = ipartfrac(pi_coeff) X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))] pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X) return pcls def _eval_rewrite_as_sec(self, arg, **kwargs): return 1/sec(arg) def _eval_rewrite_as_csc(self, arg, **kwargs): return 1/sec(arg).rewrite(csc) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.hyperbolic import cosh, sinh re, im = self._as_real_imag(deep=deep, **hints) return (cos(re)*cosh(im), -sin(re)*sinh(im)) def _eval_expand_trig(self, **hints): from sympy.functions.special.polynomials import chebyshevt arg = self.args[0] x = None if arg.is_Add: # TODO: Do this more efficiently for more than two terms x, y = arg.as_two_terms() sx = sin(x, evaluate=False)._eval_expand_trig() sy = sin(y, evaluate=False)._eval_expand_trig() cx = cos(x, evaluate=False)._eval_expand_trig() cy = cos(y, evaluate=False)._eval_expand_trig() return cx*cy - sx*sy elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer: return chebyshevt(coeff, cos(terms)) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_Rational: return self.rewrite(sqrt) return cos(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = (x0 + S.Pi/2)/S.Pi if n.is_integer: lt = (arg - n*S.Pi + S.Pi/2).as_leading_term(x) return (S.NegativeOne**n)*lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in [S.Infinity, S.NegativeInfinity]: return AccumBounds(-1, 1) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_extended_real: return True def _eval_is_complex(self): if self.args[0].is_extended_real \ or self.args[0].is_complex: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if pi_mult: return fuzzy_and([(pi_mult - S.Half).is_integer, rest.is_zero]) else: return rest.is_zero class tan(TrigonometricFunction): """ The tangent function. Returns the tangent of x (measured in radians). Explanation =========== See :class:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import tan, pi >>> from sympy.abc import x >>> tan(x**2).diff(x) 2*x*(tan(x**2)**2 + 1) >>> tan(1).diff(x) 0 >>> tan(pi/8).expand() -1 + sqrt(2) See Also ======== sin, csc, cos, sec, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Tan """ def period(self, symbol=None): return self._period(pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return S.One + self**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return atan @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): min, max = arg.min, arg.max d = floor(min/S.Pi) if min is not S.NegativeInfinity: min = min - d*S.Pi if max is not S.Infinity: max = max - d*S.Pi from sympy.sets.sets import FiniteSet if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(3, 2))): return AccumBounds(S.NegativeInfinity, S.Infinity) else: return AccumBounds(tan(min), tan(max)) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import tanh return S.ImaginaryUnit*tanh(i_coeff) pi_coeff = _pi_coeff(arg, 2) if pi_coeff is not None: if pi_coeff.is_integer: return S.Zero if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None if pi_coeff.is_Rational: q = pi_coeff.q p = pi_coeff.p % q # ensure simplified results are returned for n*pi/5, n*pi/10 table10 = { 1: sqrt(1 - 2*sqrt(5)/5), 2: sqrt(5 - 2*sqrt(5)), 3: sqrt(1 + 2*sqrt(5)/5), 4: sqrt(5 + 2*sqrt(5)) } if q in (5, 10): n = 10*p/q if n > 5: n = 10 - n return -table10[n] else: return table10[n] if not pi_coeff.q % 2: narg = pi_coeff*S.Pi*2 cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if sresult == 0: return S.ComplexInfinity return 1/sresult - cresult/sresult table2 = { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } if q in table2: nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1]) if None in (nvala, nvalb): return None return (nvala - nvalb)/(1 + nvala*nvalb) narg = ((pi_coeff + S.Half) % 1 - S.Half)*S.Pi # see cos() to specify which expressions should be # expanded automatically in terms of radicals cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if cresult == 0: return S.ComplexInfinity return (sresult/cresult) if narg != arg: return cls(narg) if arg.is_Add: x, m = _peeloff_pi(arg) if m: tanm = tan(m*S.Pi) if tanm is S.ComplexInfinity: return -cot(x) else: # tanm == 0 return tan(x) if arg.is_zero: return S.Zero if isinstance(arg, atan): return arg.args[0] if isinstance(arg, atan2): y, x = arg.args return y/x if isinstance(arg, asin): x = arg.args[0] return x/sqrt(1 - x**2) if isinstance(arg, acos): x = arg.args[0] return sqrt(1 - x**2)/x if isinstance(arg, acot): x = arg.args[0] return 1/x if isinstance(arg, acsc): x = arg.args[0] return 1/(sqrt(1 - 1/x**2)*x) if isinstance(arg, asec): x = arg.args[0] return sqrt(1 - 1/x**2)*x @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) a, b = ((n - 1)//2), 2**(n + 1) B = bernoulli(n + 1) F = factorial(n + 1) return S.NegativeOne**a*b*(b - 1)*B/F*x**n def _eval_nseries(self, x, n, logx, cdir=0): i = self.args[0].limit(x, 0)*2/S.Pi if i and i.is_Integer: return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx) return Function._eval_nseries(self, x, n=n, logx=logx) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return I*(x**-I - x**I)/(x**-I + x**I) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) if im: from sympy.functions.elementary.hyperbolic import cosh, sinh denom = cos(2*re) + cosh(2*im) return (sin(2*re)/denom, sinh(2*im)/denom) else: return (self.func(re), S.Zero) def _eval_expand_trig(self, **hints): arg = self.args[0] x = None if arg.is_Add: n = len(arg.args) TX = [] for x in arg.args: tx = tan(x, evaluate=False)._eval_expand_trig() TX.append(tx) Yg = numbered_symbols('Y') Y = [ next(Yg) for i in range(n) ] p = [0, 0] for i in range(n + 1): p[1 - i % 2] += symmetric_poly(i, Y)*(-1)**((i % 4)//2) return (p[0]/p[1]).subs(list(zip(Y, TX))) elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: I = S.ImaginaryUnit z = Symbol('dummy', real=True) P = ((1 + I*z)**coeff).expand() return (im(P)/re(P)).subs([(z, tan(terms))]) return tan(arg) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit from sympy.functions.elementary.hyperbolic import HyperbolicFunction if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(neg_exp - pos_exp)/(neg_exp + pos_exp) def _eval_rewrite_as_sin(self, x, **kwargs): return 2*sin(x)**2/sin(2*x) def _eval_rewrite_as_cos(self, x, **kwargs): return cos(x - S.Pi/2, evaluate=False)/cos(x) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)/cos(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): return 1/cot(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): sin_in_sec_form = sin(arg).rewrite(sec) cos_in_sec_form = cos(arg).rewrite(sec) return sin_in_sec_form/cos_in_sec_form def _eval_rewrite_as_csc(self, arg, **kwargs): sin_in_csc_form = sin(arg).rewrite(csc) cos_in_csc_form = cos(arg).rewrite(csc) return sin_in_csc_form/cos_in_csc_form def _eval_rewrite_as_pow(self, arg, **kwargs): y = self.rewrite(cos).rewrite(pow) if y.has(cos): return None return y def _eval_rewrite_as_sqrt(self, arg, **kwargs): y = self.rewrite(cos).rewrite(sqrt) if y.has(cos): return None return y def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = 2*x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi/2).as_leading_term(x) return lt if n.is_even else -1/lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): # FIXME: currently tan(pi/2) return zoo return self.args[0].is_extended_real def _eval_is_real(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True if arg.is_imaginary: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return pi_mult.is_integer def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True class cot(TrigonometricFunction): """ The cotangent function. Returns the cotangent of x (measured in radians). Explanation =========== See :class:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import cot, pi >>> from sympy.abc import x >>> cot(x**2).diff(x) 2*x*(-cot(x**2)**2 - 1) >>> cot(1).diff(x) 0 >>> cot(pi/12) sqrt(3) + 2 See Also ======== sin, csc, cos, sec, tan asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Cot """ def period(self, symbol=None): return self._period(pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return S.NegativeOne - self**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return acot @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN if arg.is_zero: return S.ComplexInfinity elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): return -tan(arg + S.Pi/2) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import coth return -S.ImaginaryUnit*coth(i_coeff) pi_coeff = _pi_coeff(arg, 2) if pi_coeff is not None: if pi_coeff.is_integer: return S.ComplexInfinity if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None if pi_coeff.is_Rational: if pi_coeff.q in (5, 10): return tan(S.Pi/2 - arg) if pi_coeff.q > 2 and not pi_coeff.q % 2: narg = pi_coeff*S.Pi*2 cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): return 1/sresult + cresult/sresult table2 = { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } q = pi_coeff.q p = pi_coeff.p % q if q in table2: nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1]) if None in (nvala, nvalb): return None return (1 + nvala*nvalb)/(nvalb - nvala) narg = (((pi_coeff + S.Half) % 1) - S.Half)*S.Pi # see cos() to specify which expressions should be # expanded automatically in terms of radicals cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if sresult == 0: return S.ComplexInfinity return cresult/sresult if narg != arg: return cls(narg) if arg.is_Add: x, m = _peeloff_pi(arg) if m: cotm = cot(m*S.Pi) if cotm is S.ComplexInfinity: return cot(x) else: # cotm == 0 return -tan(x) if arg.is_zero: return S.ComplexInfinity if isinstance(arg, acot): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return 1/x if isinstance(arg, atan2): y, x = arg.args return x/y if isinstance(arg, asin): x = arg.args[0] return sqrt(1 - x**2)/x if isinstance(arg, acos): x = arg.args[0] return x/sqrt(1 - x**2) if isinstance(arg, acsc): x = arg.args[0] return sqrt(1 - 1/x**2)*x if isinstance(arg, asec): x = arg.args[0] return 1/(sqrt(1 - 1/x**2)*x) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return S.NegativeOne**((n + 1)//2)*2**(n + 1)*B/F*x**n def _eval_nseries(self, x, n, logx, cdir=0): i = self.args[0].limit(x, 0)/S.Pi if i and i.is_Integer: return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx) return self.rewrite(tan)._eval_nseries(x, n=n, logx=logx) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) if im: from sympy.functions.elementary.hyperbolic import cosh, sinh denom = cos(2*re) - cosh(2*im) return (-sin(2*re)/denom, sinh(2*im)/denom) else: return (self.func(re), S.Zero) def _eval_rewrite_as_exp(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import HyperbolicFunction I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return -I*(x**-I + x**I)/(x**-I - x**I) def _eval_rewrite_as_sin(self, x, **kwargs): return sin(2*x)/(2*(sin(x)**2)) def _eval_rewrite_as_cos(self, x, **kwargs): return cos(x)/cos(x - S.Pi/2, evaluate=False) def _eval_rewrite_as_sincos(self, arg, **kwargs): return cos(arg)/sin(arg) def _eval_rewrite_as_tan(self, arg, **kwargs): return 1/tan(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): cos_in_sec_form = cos(arg).rewrite(sec) sin_in_sec_form = sin(arg).rewrite(sec) return cos_in_sec_form/sin_in_sec_form def _eval_rewrite_as_csc(self, arg, **kwargs): cos_in_csc_form = cos(arg).rewrite(csc) sin_in_csc_form = sin(arg).rewrite(csc) return cos_in_csc_form/sin_in_csc_form def _eval_rewrite_as_pow(self, arg, **kwargs): y = self.rewrite(cos).rewrite(pow) if y.has(cos): return None return y def _eval_rewrite_as_sqrt(self, arg, **kwargs): y = self.rewrite(cos).rewrite(sqrt) if y.has(cos): return None return y def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = 2*x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi/2).as_leading_term(x) return 1/lt if n.is_even else -lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): return self.args[0].is_extended_real def _eval_expand_trig(self, **hints): arg = self.args[0] x = None if arg.is_Add: n = len(arg.args) CX = [] for x in arg.args: cx = cot(x, evaluate=False)._eval_expand_trig() CX.append(cx) Yg = numbered_symbols('Y') Y = [ next(Yg) for i in range(n) ] p = [0, 0] for i in range(n, -1, -1): p[(n - i) % 2] += symmetric_poly(i, Y)*(-1)**(((n - i) % 4)//2) return (p[0]/p[1]).subs(list(zip(Y, CX))) elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: I = S.ImaginaryUnit z = Symbol('dummy', real=True) P = ((z + I)**coeff).expand() return (re(P)/im(P)).subs([(z, cot(terms))]) return cot(arg) # XXX sec and csc return 1/cos and 1/sin def _eval_is_finite(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True if arg.is_imaginary: return True def _eval_is_real(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True def _eval_is_zero(self): rest, pimult = _peeloff_pi(self.args[0]) if pimult and rest.is_zero: return (pimult - S.Half).is_integer def _eval_subs(self, old, new): arg = self.args[0] argnew = arg.subs(old, new) if arg != argnew and (argnew/S.Pi).is_integer: return S.ComplexInfinity return cot(argnew) class ReciprocalTrigonometricFunction(TrigonometricFunction): """Base class for reciprocal functions of trigonometric functions. """ _reciprocal_of = None # mandatory, to be defined in subclass _singularities = (S.ComplexInfinity,) # _is_even and _is_odd are used for correct evaluation of csc(-x), sec(-x) # TODO refactor into TrigonometricFunction common parts of # trigonometric functions eval() like even/odd, func(x+2*k*pi), etc. # optional, to be defined in subclasses: _is_even = None # type: FuzzyBool _is_odd = None # type: FuzzyBool @classmethod def eval(cls, arg): if arg.could_extract_minus_sign(): if cls._is_even: return cls(-arg) if cls._is_odd: return -cls(-arg) pi_coeff = _pi_coeff(arg) if (pi_coeff is not None and not (2*pi_coeff).is_integer and pi_coeff.is_Rational): q = pi_coeff.q p = pi_coeff.p % (2*q) if p > q: narg = (pi_coeff - 1)*S.Pi return -cls(narg) if 2*p > q: narg = (1 - pi_coeff)*S.Pi if cls._is_odd: return cls(narg) elif cls._is_even: return -cls(narg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] t = cls._reciprocal_of.eval(arg) if t is None: return t elif any(isinstance(i, cos) for i in (t, -t)): return (1/t).rewrite(sec) elif any(isinstance(i, sin) for i in (t, -t)): return (1/t).rewrite(csc) else: return 1/t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of o = self._reciprocal_of(self.args[0]) return getattr(o, method_name)(*args, **kwargs) def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) if t is not None and t != self._reciprocal_of(arg): return 1/t def _period(self, symbol): f = expand_mul(self.args[0]) return self._reciprocal_of(f).period(symbol) def fdiff(self, argindex=1): return -self._calculate_reciprocal("fdiff", argindex)/self**2 def _eval_rewrite_as_exp(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg) def _eval_rewrite_as_Pow(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_Pow", arg) def _eval_rewrite_as_sin(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_sin", arg) def _eval_rewrite_as_cos(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_cos", arg) def _eval_rewrite_as_tan(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tan", arg) def _eval_rewrite_as_pow(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_pow", arg) def _eval_rewrite_as_sqrt(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_sqrt", arg) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): return (1/self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints) def _eval_expand_trig(self, **hints): return self._calculate_reciprocal("_eval_expand_trig", **hints) def _eval_is_extended_real(self): return self._reciprocal_of(self.args[0])._eval_is_extended_real() def _eval_as_leading_term(self, x, logx=None, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x) def _eval_is_finite(self): return (1/self._reciprocal_of(self.args[0])).is_finite def _eval_nseries(self, x, n, logx, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_nseries(x, n, logx) class sec(ReciprocalTrigonometricFunction): """ The secant function. Returns the secant of x (measured in radians). Explanation =========== See :class:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import sec >>> from sympy.abc import x >>> sec(x**2).diff(x) 2*x*tan(x**2)*sec(x**2) >>> sec(1).diff(x) 0 See Also ======== sin, csc, cos, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Sec """ _reciprocal_of = cos _is_even = True def period(self, symbol=None): return self._period(symbol) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half_sq = cot(arg/2)**2 return (cot_half_sq + 1)/(cot_half_sq - 1) def _eval_rewrite_as_cos(self, arg, **kwargs): return (1/cos(arg)) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)/(cos(arg)*sin(arg)) def _eval_rewrite_as_sin(self, arg, **kwargs): return (1/cos(arg).rewrite(sin)) def _eval_rewrite_as_tan(self, arg, **kwargs): return (1/cos(arg).rewrite(tan)) def _eval_rewrite_as_csc(self, arg, **kwargs): return csc(pi/2 - arg, evaluate=False) def fdiff(self, argindex=1): if argindex == 1: return tan(self.args[0])*sec(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_is_complex(self): arg = self.args[0] if arg.is_complex and (arg/pi - S.Half).is_integer is False: return True @staticmethod @cacheit def taylor_term(n, x, *previous_terms): # Reference Formula: # http://functions.wolfram.com/ElementaryFunctions/Sec/06/01/02/01/ if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) k = n//2 return S.NegativeOne**k*euler(2*k)/factorial(2*k)*x**(2*k) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = (x0 + S.Pi/2)/S.Pi if n.is_integer: lt = (arg - n*S.Pi + S.Pi/2).as_leading_term(x) return (S.NegativeOne**n)/lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self class csc(ReciprocalTrigonometricFunction): """ The cosecant function. Returns the cosecant of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import csc >>> from sympy.abc import x >>> csc(x**2).diff(x) -2*x*cot(x**2)*csc(x**2) >>> csc(1).diff(x) 0 See Also ======== sin, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Csc """ _reciprocal_of = sin _is_odd = True def period(self, symbol=None): return self._period(symbol) def _eval_rewrite_as_sin(self, arg, **kwargs): return (1/sin(arg)) def _eval_rewrite_as_sincos(self, arg, **kwargs): return cos(arg)/(sin(arg)*cos(arg)) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(arg/2) return (1 + cot_half**2)/(2*cot_half) def _eval_rewrite_as_cos(self, arg, **kwargs): return 1/sin(arg).rewrite(cos) def _eval_rewrite_as_sec(self, arg, **kwargs): return sec(pi/2 - arg, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): return (1/sin(arg).rewrite(tan)) def fdiff(self, argindex=1): if argindex == 1: return -cot(self.args[0])*csc(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = n//2 + 1 return (S.NegativeOne**(k - 1)*2*(2**(2*k - 1) - 1)* bernoulli(2*k)*x**(2*k - 1)/factorial(2*k)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi).as_leading_term(x) return (S.NegativeOne**n)/lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self class sinc(Function): r""" Represents an unnormalized sinc function: .. math:: \operatorname{sinc}(x) = \begin{cases} \frac{\sin x}{x} & \qquad x \neq 0 \\ 1 & \qquad x = 0 \end{cases} Examples ======== >>> from sympy import sinc, oo, jn >>> from sympy.abc import x >>> sinc(x) sinc(x) * Automated Evaluation >>> sinc(0) 1 >>> sinc(oo) 0 * Differentiation >>> sinc(x).diff() cos(x)/x - sin(x)/x**2 * Series Expansion >>> sinc(x).series() 1 - x**2/6 + x**4/120 + O(x**6) * As zero'th order spherical Bessel Function >>> sinc(x).rewrite(jn) jn(0, x) See also ======== sin References ========== .. [1] https://en.wikipedia.org/wiki/Sinc_function """ _singularities = (S.ComplexInfinity,) def fdiff(self, argindex=1): x = self.args[0] if argindex == 1: # We would like to return the Piecewise here, but Piecewise.diff # currently can't handle removable singularities, meaning things # like sinc(x).diff(x, 2) give the wrong answer at x = 0. See # https://github.com/sympy/sympy/issues/11402. # # return Piecewise(((x*cos(x) - sin(x))/x**2, Ne(x, S.Zero)), (S.Zero, S.true)) return cos(x)/x - sin(x)/x**2 else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_zero: return S.One if arg.is_Number: if arg in [S.Infinity, S.NegativeInfinity]: return S.Zero elif arg is S.NaN: return S.NaN if arg is S.ComplexInfinity: return S.NaN if arg.could_extract_minus_sign(): return cls(-arg) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: if fuzzy_not(arg.is_zero): return S.Zero elif (2*pi_coeff).is_integer: return S.NegativeOne**(pi_coeff - S.Half)/arg def _eval_nseries(self, x, n, logx, cdir=0): x = self.args[0] return (sin(x)/x)._eval_nseries(x, n, logx) def _eval_rewrite_as_jn(self, arg, **kwargs): from sympy.functions.special.bessel import jn return jn(0, arg) def _eval_rewrite_as_sin(self, arg, **kwargs): return Piecewise((sin(arg)/arg, Ne(arg, S.Zero)), (S.One, S.true)) def _eval_is_zero(self): if self.args[0].is_infinite: return True rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return fuzzy_and([pi_mult.is_integer, pi_mult.is_nonzero]) if rest.is_Number and pi_mult.is_integer: return False def _eval_is_real(self): if self.args[0].is_extended_real or self.args[0].is_imaginary: return True _eval_is_finite = _eval_is_real ############################################################################### ########################### TRIGONOMETRIC INVERSES ############################ ############################################################################### class InverseTrigonometricFunction(Function): """Base class for inverse trigonometric functions.""" _singularities = (S.One, S.NegativeOne, S.Zero, S.ComplexInfinity) # type: tTuple[Expr, ...] @staticmethod def _asin_table(): # Only keys with could_extract_minus_sign() == False # are actually needed. return { sqrt(3)/2: S.Pi/3, sqrt(2)/2: S.Pi/4, 1/sqrt(2): S.Pi/4, sqrt((5 - sqrt(5))/8): S.Pi/5, sqrt(2)*sqrt(5 - sqrt(5))/4: S.Pi/5, sqrt((5 + sqrt(5))/8): S.Pi*Rational(2, 5), sqrt(2)*sqrt(5 + sqrt(5))/4: S.Pi*Rational(2, 5), S.Half: S.Pi/6, sqrt(2 - sqrt(2))/2: S.Pi/8, sqrt(S.Half - sqrt(2)/4): S.Pi/8, sqrt(2 + sqrt(2))/2: S.Pi*Rational(3, 8), sqrt(S.Half + sqrt(2)/4): S.Pi*Rational(3, 8), (sqrt(5) - 1)/4: S.Pi/10, (1 - sqrt(5))/4: -S.Pi/10, (sqrt(5) + 1)/4: S.Pi*Rational(3, 10), sqrt(6)/4 - sqrt(2)/4: S.Pi/12, -sqrt(6)/4 + sqrt(2)/4: -S.Pi/12, (sqrt(3) - 1)/sqrt(8): S.Pi/12, (1 - sqrt(3))/sqrt(8): -S.Pi/12, sqrt(6)/4 + sqrt(2)/4: S.Pi*Rational(5, 12), (1 + sqrt(3))/sqrt(8): S.Pi*Rational(5, 12) } @staticmethod def _atan_table(): # Only keys with could_extract_minus_sign() == False # are actually needed. return { sqrt(3)/3: S.Pi/6, 1/sqrt(3): S.Pi/6, sqrt(3): S.Pi/3, sqrt(2) - 1: S.Pi/8, 1 - sqrt(2): -S.Pi/8, 1 + sqrt(2): S.Pi*Rational(3, 8), sqrt(5 - 2*sqrt(5)): S.Pi/5, sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5), sqrt(1 - 2*sqrt(5)/5): S.Pi/10, sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10), 2 - sqrt(3): S.Pi/12, -2 + sqrt(3): -S.Pi/12, 2 + sqrt(3): S.Pi*Rational(5, 12) } @staticmethod def _acsc_table(): # Keys for which could_extract_minus_sign() # will obviously return True are omitted. return { 2*sqrt(3)/3: S.Pi/3, sqrt(2): S.Pi/4, sqrt(2 + 2*sqrt(5)/5): S.Pi/5, 1/sqrt(Rational(5, 8) - sqrt(5)/8): S.Pi/5, sqrt(2 - 2*sqrt(5)/5): S.Pi*Rational(2, 5), 1/sqrt(Rational(5, 8) + sqrt(5)/8): S.Pi*Rational(2, 5), 2: S.Pi/6, sqrt(4 + 2*sqrt(2)): S.Pi/8, 2/sqrt(2 - sqrt(2)): S.Pi/8, sqrt(4 - 2*sqrt(2)): S.Pi*Rational(3, 8), 2/sqrt(2 + sqrt(2)): S.Pi*Rational(3, 8), 1 + sqrt(5): S.Pi/10, sqrt(5) - 1: S.Pi*Rational(3, 10), -(sqrt(5) - 1): S.Pi*Rational(-3, 10), sqrt(6) + sqrt(2): S.Pi/12, sqrt(6) - sqrt(2): S.Pi*Rational(5, 12), -(sqrt(6) - sqrt(2)): S.Pi*Rational(-5, 12) } class asin(InverseTrigonometricFunction): r""" The inverse sine function. Returns the arcsine of x in radians. Explanation =========== ``asin(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the ``eval`` class method). A purely imaginary argument will lead to an asinh expression. Examples ======== >>> from sympy import asin, oo >>> asin(1) pi/2 >>> asin(-1) -pi/2 >>> asin(-oo) oo*I >>> asin(oo) -oo*I See Also ======== sin, csc, cos, sec, tan, cot acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSin """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self._eval_is_extended_real() and self.args[0].is_positive def _eval_is_negative(self): return self._eval_is_extended_real() and self.args[0].is_negative @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.NegativeInfinity*S.ImaginaryUnit elif arg is S.NegativeInfinity: return S.Infinity*S.ImaginaryUnit elif arg.is_zero: return S.Zero elif arg is S.One: return S.Pi/2 elif arg is S.NegativeOne: return -S.Pi/2 if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: asin_table = cls._asin_table() if arg in asin_table: return asin_table[arg] i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import asinh return S.ImaginaryUnit*asinh(i_coeff) if arg.is_zero: return S.Zero if isinstance(arg, sin): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to (-pi,pi] ang = pi - ang # restrict to [-pi/2,pi/2] if ang > pi/2: ang = pi - ang if ang < -pi/2: ang = -pi - ang return ang if isinstance(arg, cos): # acos(x) + asin(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - acos(arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p*(n - 2)**2/(n*(n - 1))*x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return R/F*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) if x0 is S.ComplexInfinity: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 < S.NegativeOne: return -S.Pi - self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 > S.One: return S.Pi - self.func(x0) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asin from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = asin(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else S.Pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asin(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else -S.Pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 < S.NegativeOne: return -S.Pi - res elif im(cdir) > 0 and arg0.is_real and arg0 > S.One: return S.Pi - res return res def _eval_rewrite_as_acos(self, x, **kwargs): return S.Pi/2 - acos(x) def _eval_rewrite_as_atan(self, x, **kwargs): return 2*atan(x/(1 + sqrt(1 - x**2))) def _eval_rewrite_as_log(self, x, **kwargs): return -S.ImaginaryUnit*log(S.ImaginaryUnit*x + sqrt(1 - x**2)) def _eval_rewrite_as_acot(self, arg, **kwargs): return 2*acot((1 + sqrt(1 - arg**2))/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return S.Pi/2 - asec(1/arg) def _eval_rewrite_as_acsc(self, arg, **kwargs): return acsc(1/arg) def _eval_is_extended_real(self): x = self.args[0] return x.is_extended_real and (1 - abs(x)).is_nonnegative def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sin class acos(InverseTrigonometricFunction): r""" The inverse cosine function. Returns the arc cosine of x (measured in radians). Examples ======== ``acos(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). ``acos(zoo)`` evaluates to ``zoo`` (see note in :class:`sympy.functions.elementary.trigonometric.asec`) A purely imaginary argument will be rewritten to asinh. Examples ======== >>> from sympy import acos, oo >>> acos(1) 0 >>> acos(0) pi/2 >>> acos(oo) oo*I See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCos """ def fdiff(self, argindex=1): if argindex == 1: return -1/sqrt(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity*S.ImaginaryUnit elif arg is S.NegativeInfinity: return S.NegativeInfinity*S.ImaginaryUnit elif arg.is_zero: return S.Pi/2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_number: asin_table = cls._asin_table() if arg in asin_table: return pi/2 - asin_table[arg] elif -arg in asin_table: return pi/2 + asin_table[-arg] i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return pi/2 - asin(arg) if isinstance(arg, cos): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(arg, sin): # acos(x) + asin(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - asin(arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi/2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p*(n - 2)**2/(n*(n - 1))*x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return -R/F*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 == 1: return sqrt(2)*sqrt((S.One - arg).as_leading_term(x)) if x0 is S.ComplexInfinity: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 < S.NegativeOne: return 2*S.Pi - self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 > S.One: return -self.func(x0) return self.func(x0) def _eval_is_extended_real(self): x = self.args[0] return x.is_extended_real and (1 - abs(x)).is_nonnegative def _eval_is_nonnegative(self): return self._eval_is_extended_real() def _eval_nseries(self, x, n, logx, cdir=0): # acos from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = acos(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = acos(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else S.Pi + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 < S.NegativeOne: return 2*S.Pi - res elif im(cdir) > 0 and arg0.is_real and arg0 > S.One: return -res return res def _eval_rewrite_as_log(self, x, **kwargs): return S.Pi/2 + S.ImaginaryUnit*\ log(S.ImaginaryUnit*x + sqrt(1 - x**2)) def _eval_rewrite_as_asin(self, x, **kwargs): return S.Pi/2 - asin(x) def _eval_rewrite_as_atan(self, x, **kwargs): return atan(sqrt(1 - x**2)/x) + (S.Pi/2)*(1 - x*sqrt(1/x**2)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cos def _eval_rewrite_as_acot(self, arg, **kwargs): return S.Pi/2 - 2*acot((1 + sqrt(1 - arg**2))/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return asec(1/arg) def _eval_rewrite_as_acsc(self, arg, **kwargs): return S.Pi/2 - acsc(1/arg) def _eval_conjugate(self): z = self.args[0] r = self.func(self.args[0].conjugate()) if z.is_extended_real is False: return r elif z.is_extended_real and (z + 1).is_nonnegative and (z - 1).is_nonpositive: return r class atan(InverseTrigonometricFunction): r""" The inverse tangent function. Returns the arc tangent of x (measured in radians). Explanation =========== ``atan(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). Examples ======== >>> from sympy import atan, oo >>> atan(0) 0 >>> atan(1) pi/4 >>> atan(oo) pi/2 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan """ args: tTuple[Expr] _singularities = (S.ImaginaryUnit, -S.ImaginaryUnit) def fdiff(self, argindex=1): if argindex == 1: return 1/(1 + self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self.args[0].is_extended_positive def _eval_is_nonnegative(self): return self.args[0].is_extended_nonnegative def _eval_is_zero(self): return self.args[0].is_zero def _eval_is_real(self): return self.args[0].is_extended_real @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Pi/2 elif arg is S.NegativeInfinity: return -S.Pi/2 elif arg.is_zero: return S.Zero elif arg is S.One: return S.Pi/4 elif arg is S.NegativeOne: return -S.Pi/4 if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return AccumBounds(-S.Pi/2, S.Pi/2) if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: atan_table = cls._atan_table() if arg in atan_table: return atan_table[arg] i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import atanh return S.ImaginaryUnit*atanh(i_coeff) if arg.is_zero: return S.Zero if isinstance(arg, tan): ang = arg.args[0] if ang.is_comparable: ang %= pi # restrict to [0,pi) if ang > pi/2: # restrict to [-pi/2,pi/2] ang -= pi return ang if isinstance(arg, cot): # atan(x) + acot(x) = pi/2 ang = arg.args[0] if ang.is_comparable: ang = pi/2 - acot(arg) if ang > pi/2: # restrict to [-pi/2,pi/2] ang -= pi return ang @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return S.NegativeOne**((n - 1)//2)*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) if x0 is S.ComplexInfinity: return acot(1/arg)._eval_as_leading_term(x, cdir=cdir) if cdir != 0: cdir = arg.dir(x, cdir) if re(cdir) < 0 and re(x0).is_zero and im(x0) > S.One: return self.func(x0) - S.Pi elif re(cdir) > 0 and re(x0).is_zero and im(x0) < S.NegativeOne: return self.func(x0) + S.Pi return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # atan arg0 = self.args[0].subs(x, 0) res = Function._eval_nseries(self, x, n=n, logx=logx) if cdir != 0: cdir = self.args[0].dir(x, cdir) if arg0 is S.ComplexInfinity: if re(cdir) > 0: return res - S.Pi return res if re(cdir) < 0 and re(arg0).is_zero and im(arg0) > S.One: return res - S.Pi elif re(cdir) > 0 and re(arg0).is_zero and im(arg0) < S.NegativeOne: return res + S.Pi return res def _eval_rewrite_as_log(self, x, **kwargs): return S.ImaginaryUnit/2*(log(S.One - S.ImaginaryUnit*x) - log(S.One + S.ImaginaryUnit*x)) def _eval_aseries(self, n, args0, x, logx): if args0[0] is S.Infinity: return (S.Pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx) elif args0[0] is S.NegativeInfinity: return (-S.Pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx) else: return super()._eval_aseries(n, args0, x, logx) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return tan def _eval_rewrite_as_asin(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - asin(1/sqrt(1 + arg**2))) def _eval_rewrite_as_acos(self, arg, **kwargs): return sqrt(arg**2)/arg*acos(1/sqrt(1 + arg**2)) def _eval_rewrite_as_acot(self, arg, **kwargs): return acot(1/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return sqrt(arg**2)/arg*asec(sqrt(1 + arg**2)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - acsc(sqrt(1 + arg**2))) class acot(InverseTrigonometricFunction): r""" The inverse cotangent function. Returns the arc cotangent of x (measured in radians). Explanation =========== ``acot(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, \tilde{\infty}, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). A purely imaginary argument will lead to an ``acoth`` expression. ``acot(x)`` has a branch cut along $(-i, i)$, hence it is discontinuous at 0. Its range for real $x$ is $(-\frac{\pi}{2}, \frac{\pi}{2}]$. Examples ======== >>> from sympy import acot, sqrt >>> acot(0) pi/2 >>> acot(1) pi/4 >>> acot(sqrt(3) - 2) -5*pi/12 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, atan2 References ========== .. [1] http://dlmf.nist.gov/4.23 .. [2] http://functions.wolfram.com/ElementaryFunctions/ArcCot """ _singularities = (S.ImaginaryUnit, -S.ImaginaryUnit) def fdiff(self, argindex=1): if argindex == 1: return -1/(1 + self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self.args[0].is_nonnegative def _eval_is_negative(self): return self.args[0].is_negative def _eval_is_extended_real(self): return self.args[0].is_extended_real @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.Pi/ 2 elif arg is S.One: return S.Pi/4 elif arg is S.NegativeOne: return -S.Pi/4 if arg is S.ComplexInfinity: return S.Zero if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: atan_table = cls._atan_table() if arg in atan_table: ang = pi/2 - atan_table[arg] if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi return ang i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import acoth return -S.ImaginaryUnit*acoth(i_coeff) if arg.is_zero: return S.Pi*S.Half if isinstance(arg, cot): ang = arg.args[0] if ang.is_comparable: ang %= pi # restrict to [0,pi) if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi; return ang if isinstance(arg, tan): # atan(x) + acot(x) = pi/2 ang = arg.args[0] if ang.is_comparable: ang = pi/2 - atan(arg) if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi return ang @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi/2 # FIX THIS elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return S.NegativeOne**((n + 1)//2)*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 is S.ComplexInfinity: return (1/arg).as_leading_term(x) if cdir != 0: cdir = arg.dir(x, cdir) if x0.is_zero: if re(cdir) < 0: return self.func(x0) - S.Pi return self.func(x0) if re(cdir) > 0 and re(x0).is_zero and im(x0) > S.Zero and im(x0) < S.One: return self.func(x0) + S.Pi if re(cdir) < 0 and re(x0).is_zero and im(x0) < S.Zero and im(x0) > S.NegativeOne: return self.func(x0) - S.Pi return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acot arg0 = self.args[0].subs(x, 0) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if arg0.is_zero: if re(cdir) < 0: return res - S.Pi return res if re(cdir) > 0 and re(arg0).is_zero and im(arg0) > S.Zero and im(arg0) < S.One: return res + S.Pi if re(cdir) < 0 and re(arg0).is_zero and im(arg0) < S.Zero and im(arg0) > S.NegativeOne: return res - S.Pi return res def _eval_aseries(self, n, args0, x, logx): if args0[0] is S.Infinity: return (S.Pi/2 - acot(1/self.args[0]))._eval_nseries(x, n, logx) elif args0[0] is S.NegativeInfinity: return (S.Pi*Rational(3, 2) - acot(1/self.args[0]))._eval_nseries(x, n, logx) else: return super(atan, self)._eval_aseries(n, args0, x, logx) def _eval_rewrite_as_log(self, x, **kwargs): return S.ImaginaryUnit/2*(log(1 - S.ImaginaryUnit/x) - log(1 + S.ImaginaryUnit/x)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cot def _eval_rewrite_as_asin(self, arg, **kwargs): return (arg*sqrt(1/arg**2)* (S.Pi/2 - asin(sqrt(-arg**2)/sqrt(-arg**2 - 1)))) def _eval_rewrite_as_acos(self, arg, **kwargs): return arg*sqrt(1/arg**2)*acos(sqrt(-arg**2)/sqrt(-arg**2 - 1)) def _eval_rewrite_as_atan(self, arg, **kwargs): return atan(1/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return arg*sqrt(1/arg**2)*asec(sqrt((1 + arg**2)/arg**2)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return arg*sqrt(1/arg**2)*(S.Pi/2 - acsc(sqrt((1 + arg**2)/arg**2))) class asec(InverseTrigonometricFunction): r""" The inverse secant function. Returns the arc secant of x (measured in radians). Explanation =========== ``asec(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). ``asec(x)`` has branch cut in the interval $[-1, 1]$. For complex arguments, it can be defined [4]_ as .. math:: \operatorname{sec^{-1}}(z) = -i\frac{\log\left(\sqrt{1 - z^2} + 1\right)}{z} At ``x = 0``, for positive branch cut, the limit evaluates to ``zoo``. For negative branch cut, the limit .. math:: \lim_{z \to 0}-i\frac{\log\left(-\sqrt{1 - z^2} + 1\right)}{z} simplifies to :math:`-i\log\left(z/2 + O\left(z^3\right)\right)` which ultimately evaluates to ``zoo``. As ``acos(x) = asec(1/x)``, a similar argument can be given for ``acos(x)``. Examples ======== >>> from sympy import asec, oo >>> asec(1) 0 >>> asec(-1) pi >>> asec(0) zoo >>> asec(-oo) pi/2 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSec .. [4] http://reference.wolfram.com/language/ref/ArcSec.html """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return S.Pi/2 if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return pi/2 - acsc_table[arg] elif -arg in acsc_table: return pi/2 + acsc_table[-arg] if isinstance(arg, sec): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(arg, csc): # asec(x) + acsc(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - acsc(arg) def fdiff(self, argindex=1): if argindex == 1: return 1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sec def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 == 1: return sqrt(2)*sqrt((arg - S.One).as_leading_term(x)) if x0.is_zero: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 > S.Zero and x0 < S.One: return -self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 < S.Zero and x0 > S.NegativeOne: return 2*S.Pi - self.func(x0) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asec from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = asec(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asec(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 > S.Zero and arg0 < S.One: return -res elif im(cdir) > 0 and arg0.is_real and arg0 < S.Zero and arg0 > S.NegativeOne: return 2*S.Pi - res return res def _eval_is_extended_real(self): x = self.args[0] if x.is_extended_real is False: return False return fuzzy_or(((x - 1).is_nonnegative, (-x - 1).is_nonnegative)) def _eval_rewrite_as_log(self, arg, **kwargs): return S.Pi/2 + S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) def _eval_rewrite_as_asin(self, arg, **kwargs): return S.Pi/2 - asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return acos(1/arg) def _eval_rewrite_as_atan(self, arg, **kwargs): return sqrt(arg**2)/arg*(-S.Pi/2 + 2*atan(arg + sqrt(arg**2 - 1))) def _eval_rewrite_as_acot(self, arg, **kwargs): return sqrt(arg**2)/arg*(-S.Pi/2 + 2*acot(arg - sqrt(arg**2 - 1))) def _eval_rewrite_as_acsc(self, arg, **kwargs): return S.Pi/2 - acsc(arg) class acsc(InverseTrigonometricFunction): r""" The inverse cosecant function. Returns the arc cosecant of x (measured in radians). Explanation =========== ``acsc(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$` and for some instances when the result is a rational multiple of $\pi$ (see the ``eval`` class method). Examples ======== >>> from sympy import acsc, oo >>> acsc(1) pi/2 >>> acsc(-1) -pi/2 >>> acsc(oo) 0 >>> acsc(-oo) == acsc(oo) True >>> acsc(0) zoo See Also ======== sin, csc, cos, sec, tan, cot asin, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsc """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return S.Pi/2 elif arg is S.NegativeOne: return -S.Pi/2 if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return S.Zero if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return acsc_table[arg] if isinstance(arg, csc): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to (-pi,pi] ang = pi - ang # restrict to [-pi/2,pi/2] if ang > pi/2: ang = pi - ang if ang < -pi/2: ang = -pi - ang return ang if isinstance(arg, sec): # asec(x) + acsc(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - asec(arg) def fdiff(self, argindex=1): if argindex == 1: return -1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return csc def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if x0 is S.ComplexInfinity: return arg.as_leading_term(x) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 > S.Zero and x0 < S.One: return S.Pi - self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 < S.Zero and x0 > S.NegativeOne: return -S.Pi - self.func(x0) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acsc from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = acsc(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = acsc(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 > S.Zero and arg0 < S.One: return S.Pi - res elif im(cdir) > 0 and arg0.is_real and arg0 < S.Zero and arg0 > S.NegativeOne: return -S.Pi - res return res def _eval_rewrite_as_log(self, arg, **kwargs): return -S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) def _eval_rewrite_as_asin(self, arg, **kwargs): return asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return S.Pi/2 - acos(1/arg) def _eval_rewrite_as_atan(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - atan(sqrt(arg**2 - 1))) def _eval_rewrite_as_acot(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - acot(1/sqrt(arg**2 - 1))) def _eval_rewrite_as_asec(self, arg, **kwargs): return S.Pi/2 - asec(arg) class atan2(InverseTrigonometricFunction): r""" The function ``atan2(y, x)`` computes `\operatorname{atan}(y/x)` taking two arguments `y` and `x`. Signs of both `y` and `x` are considered to determine the appropriate quadrant of `\operatorname{atan}(y/x)`. The range is `(-\pi, \pi]`. The complete definition reads as follows: .. math:: \operatorname{atan2}(y, x) = \begin{cases} \arctan\left(\frac y x\right) & \qquad x > 0 \\ \arctan\left(\frac y x\right) + \pi& \qquad y \ge 0, x < 0 \\ \arctan\left(\frac y x\right) - \pi& \qquad y < 0, x < 0 \\ +\frac{\pi}{2} & \qquad y > 0, x = 0 \\ -\frac{\pi}{2} & \qquad y < 0, x = 0 \\ \text{undefined} & \qquad y = 0, x = 0 \end{cases} Attention: Note the role reversal of both arguments. The `y`-coordinate is the first argument and the `x`-coordinate the second. If either `x` or `y` is complex: .. math:: \operatorname{atan2}(y, x) = -i\log\left(\frac{x + iy}{\sqrt{x^2 + y^2}}\right) Examples ======== Going counter-clock wise around the origin we find the following angles: >>> from sympy import atan2 >>> atan2(0, 1) 0 >>> atan2(1, 1) pi/4 >>> atan2(1, 0) pi/2 >>> atan2(1, -1) 3*pi/4 >>> atan2(0, -1) pi >>> atan2(-1, -1) -3*pi/4 >>> atan2(-1, 0) -pi/2 >>> atan2(-1, 1) -pi/4 which are all correct. Compare this to the results of the ordinary `\operatorname{atan}` function for the point `(x, y) = (-1, 1)` >>> from sympy import atan, S >>> atan(S(1)/-1) -pi/4 >>> atan2(1, -1) 3*pi/4 where only the `\operatorname{atan2}` function reurns what we expect. We can differentiate the function with respect to both arguments: >>> from sympy import diff >>> from sympy.abc import x, y >>> diff(atan2(y, x), x) -y/(x**2 + y**2) >>> diff(atan2(y, x), y) x/(x**2 + y**2) We can express the `\operatorname{atan2}` function in terms of complex logarithms: >>> from sympy import log >>> atan2(y, x).rewrite(log) -I*log((x + I*y)/sqrt(x**2 + y**2)) and in terms of `\operatorname(atan)`: >>> from sympy import atan >>> atan2(y, x).rewrite(atan) Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) but note that this form is undefined on the negative real axis. See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] https://en.wikipedia.org/wiki/Atan2 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan2 """ @classmethod def eval(cls, y, x): from sympy.functions.special.delta_functions import Heaviside if x is S.NegativeInfinity: if y.is_zero: # Special case y = 0 because we define Heaviside(0) = 1/2 return S.Pi return 2*S.Pi*(Heaviside(re(y))) - S.Pi elif x is S.Infinity: return S.Zero elif x.is_imaginary and y.is_imaginary and x.is_number and y.is_number: x = im(x) y = im(y) if x.is_extended_real and y.is_extended_real: if x.is_positive: return atan(y/x) elif x.is_negative: if y.is_negative: return atan(y/x) - S.Pi elif y.is_nonnegative: return atan(y/x) + S.Pi elif x.is_zero: if y.is_positive: return S.Pi/2 elif y.is_negative: return -S.Pi/2 elif y.is_zero: return S.NaN if y.is_zero: if x.is_extended_nonzero: return S.Pi*(S.One - Heaviside(x)) if x.is_number: return Piecewise((S.Pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) if x.is_number and y.is_number: return -S.ImaginaryUnit*log( (x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_log(self, y, x, **kwargs): return -S.ImaginaryUnit*log((x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_atan(self, y, x, **kwargs): return Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) def _eval_rewrite_as_arg(self, y, x, **kwargs): if x.is_extended_real and y.is_extended_real: return arg(x + y*S.ImaginaryUnit) n = x + S.ImaginaryUnit*y d = x**2 + y**2 return arg(n/sqrt(d)) - S.ImaginaryUnit*log(abs(n)/sqrt(abs(d))) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def fdiff(self, argindex): y, x = self.args if argindex == 1: # Diff wrt y return x/(x**2 + y**2) elif argindex == 2: # Diff wrt x return -y/(x**2 + y**2) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): y, x = self.args if x.is_extended_real and y.is_extended_real: return super()._eval_evalf(prec)
0ad0c64805521b57fb37c134ea56774f7a968a944e09564e999ff10457d2f56c
from sympy.core import S, Function, diff, Tuple, Dummy from sympy.core.basic import Basic, as_Basic from sympy.core.numbers import Rational, NumberSymbol, _illegal from sympy.core.parameters import global_parameters from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational, _canonical, _canonical_coeff) from sympy.core.sorting import ordered from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not, true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and) from sympy.utilities.iterables import uniq, sift, common_prefix from sympy.utilities.misc import filldedent, func_name from itertools import product Undefined = S.NaN # Piecewise() class ExprCondPair(Tuple): """Represents an expression, condition pair.""" def __new__(cls, expr, cond): expr = as_Basic(expr) if cond == True: return Tuple.__new__(cls, expr, true) elif cond == False: return Tuple.__new__(cls, expr, false) elif isinstance(cond, Basic) and cond.has(Piecewise): cond = piecewise_fold(cond) if isinstance(cond, Piecewise): cond = cond.rewrite(ITE) if not isinstance(cond, Boolean): raise TypeError(filldedent(''' Second argument must be a Boolean, not `%s`''' % func_name(cond))) return Tuple.__new__(cls, expr, cond) @property def expr(self): """ Returns the expression of this pair. """ return self.args[0] @property def cond(self): """ Returns the condition of this pair. """ return self.args[1] @property def is_commutative(self): return self.expr.is_commutative def __iter__(self): yield self.expr yield self.cond def _eval_simplify(self, **kwargs): return self.func(*[a.simplify(**kwargs) for a in self.args]) class Piecewise(Function): """ Represents a piecewise function. Usage: Piecewise( (expr,cond), (expr,cond), ... ) - Each argument is a 2-tuple defining an expression and condition - The conds are evaluated in turn returning the first that is True. If any of the evaluated conds are not explicitly False, e.g. ``x < 1``, the function is returned in symbolic form. - If the function is evaluated at a place where all conditions are False, nan will be returned. - Pairs where the cond is explicitly False, will be removed and no pair appearing after a True condition will ever be retained. If a single pair with a True condition remains, it will be returned, even when evaluation is False. Examples ======== >>> from sympy import Piecewise, log, piecewise_fold >>> from sympy.abc import x, y >>> f = x**2 >>> g = log(x) >>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True)) >>> p.subs(x,1) 1 >>> p.subs(x,5) log(5) Booleans can contain Piecewise elements: >>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond Piecewise((2, x < 0), (3, True)) < y The folded version of this results in a Piecewise whose expressions are Booleans: >>> folded_cond = piecewise_fold(cond); folded_cond Piecewise((2 < y, x < 0), (3 < y, True)) When a Boolean containing Piecewise (like cond) or a Piecewise with Boolean expressions (like folded_cond) is used as a condition, it is converted to an equivalent :class:`~.ITE` object: >>> Piecewise((1, folded_cond)) Piecewise((1, ITE(x < 0, y > 2, y > 3))) When a condition is an ``ITE``, it will be converted to a simplified Boolean expression: >>> piecewise_fold(_) Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0)))) See Also ======== piecewise_fold, ITE """ nargs = None is_Piecewise = True def __new__(cls, *args, **options): if len(args) == 0: raise TypeError("At least one (expr, cond) pair expected.") # (Try to) sympify args first newargs = [] for ec in args: # ec could be a ExprCondPair or a tuple pair = ExprCondPair(*getattr(ec, 'args', ec)) cond = pair.cond if cond is false: continue newargs.append(pair) if cond is true: break eval = options.pop('evaluate', global_parameters.evaluate) if eval: r = cls.eval(*newargs) if r is not None: return r elif len(newargs) == 1 and newargs[0].cond == True: return newargs[0].expr return Basic.__new__(cls, *newargs, **options) @classmethod def eval(cls, *_args): """Either return a modified version of the args or, if no modifications were made, return None. Modifications that are made here: 1. relationals are made canonical 2. any False conditions are dropped 3. any repeat of a previous condition is ignored 4. any args past one with a true condition are dropped If there are no args left, nan will be returned. If there is a single arg with a True condition, its corresponding expression will be returned. EXAMPLES ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> cond = -x < -1 >>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)] >>> Piecewise(*args, evaluate=False) Piecewise((1, -x < -1), (4, -x < -1), (2, True)) >>> Piecewise(*args) Piecewise((1, x > 1), (2, True)) """ if not _args: return Undefined if len(_args) == 1 and _args[0][-1] == True: return _args[0][0] newargs = [] # the unevaluated conditions current_cond = set() # the conditions up to a given e, c pair for expr, cond in _args: cond = cond.replace( lambda _: _.is_Relational, _canonical_coeff) # Check here if expr is a Piecewise and collapse if one of # the conds in expr matches cond. This allows the collapsing # of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)). # This is important when using piecewise_fold to simplify # multiple Piecewise instances having the same conds. # Eventually, this code should be able to collapse Piecewise's # having different intervals, but this will probably require # using the new assumptions. if isinstance(expr, Piecewise): unmatching = [] for i, (e, c) in enumerate(expr.args): if c in current_cond: # this would already have triggered continue if c == cond: if c != True: # nothing past this condition will ever # trigger and only those args before this # that didn't match a previous condition # could possibly trigger if unmatching: expr = Piecewise(*( unmatching + [(e, c)])) else: expr = e break else: unmatching.append((e, c)) # check for condition repeats got = False # -- if an And contains a condition that was # already encountered, then the And will be # False: if the previous condition was False # then the And will be False and if the previous # condition is True then then we wouldn't get to # this point. In either case, we can skip this condition. for i in ([cond] + (list(cond.args) if isinstance(cond, And) else [])): if i in current_cond: got = True break if got: continue # -- if not(c) is already in current_cond then c is # a redundant condition in an And. This does not # apply to Or, however: (e1, c), (e2, Or(~c, d)) # is not (e1, c), (e2, d) because if c and d are # both False this would give no results when the # true answer should be (e2, True) if isinstance(cond, And): nonredundant = [] for c in cond.args: if isinstance(c, Relational): if c.negated.canonical in current_cond: continue # if a strict inequality appears after # a non-strict one, then the condition is # redundant if isinstance(c, (Lt, Gt)) and ( c.weak in current_cond): cond = False break nonredundant.append(c) else: cond = cond.func(*nonredundant) elif isinstance(cond, Relational): if cond.negated.canonical in current_cond: cond = S.true current_cond.add(cond) # collect successive e,c pairs when exprs or cond match if newargs: if newargs[-1].expr == expr: orcond = Or(cond, newargs[-1].cond) if isinstance(orcond, (And, Or)): orcond = distribute_and_over_or(orcond) newargs[-1] = ExprCondPair(expr, orcond) continue elif newargs[-1].cond == cond: newargs[-1] = ExprCondPair(expr, cond) continue newargs.append(ExprCondPair(expr, cond)) # some conditions may have been redundant missing = len(newargs) != len(_args) # some conditions may have changed same = all(a == b for a, b in zip(newargs, _args)) # if either change happened we return the expr with the # updated args if not newargs: raise ValueError(filldedent(''' There are no conditions (or none that are not trivially false) to define an expression.''')) if missing or not same: return cls(*newargs) def doit(self, **hints): """ Evaluate this piecewise function. """ newargs = [] for e, c in self.args: if hints.get('deep', True): if isinstance(e, Basic): newe = e.doit(**hints) if newe != self: e = newe if isinstance(c, Basic): c = c.doit(**hints) newargs.append((e, c)) return self.func(*newargs) def _eval_simplify(self, **kwargs): return piecewise_simplify(self, **kwargs) def _eval_as_leading_term(self, x, logx=None, cdir=0): for e, c in self.args: if c == True or c.subs(x, 0) == True: return e.as_leading_term(x) def _eval_adjoint(self): return self.func(*[(e.adjoint(), c) for e, c in self.args]) def _eval_conjugate(self): return self.func(*[(e.conjugate(), c) for e, c in self.args]) def _eval_derivative(self, x): return self.func(*[(diff(e, x), c) for e, c in self.args]) def _eval_evalf(self, prec): return self.func(*[(e._evalf(prec), c) for e, c in self.args]) def piecewise_integrate(self, x, **kwargs): """Return the Piecewise with each expression being replaced with its antiderivative. To obtain a continuous antiderivative, use the :func:`~.integrate` function or method. Examples ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True)) >>> p.piecewise_integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x, True)) Note that this does not give a continuous function, e.g. at x = 1 the 3rd condition applies and the antiderivative there is 2*x so the value of the antiderivative is 2: >>> anti = _ >>> anti.subs(x, 1) 2 The continuous derivative accounts for the integral *up to* the point of interest, however: >>> p.integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True)) >>> _.subs(x, 1) 1 See Also ======== Piecewise._eval_integral """ from sympy.integrals import integrate return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args]) def _handle_irel(self, x, handler): """Return either None (if the conditions of self depend only on x) else a Piecewise expression whose expressions (handled by the handler that was passed) are paired with the governing x-independent relationals, e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) -> Piecewise( (handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)), (handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)), (handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)), (handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True)) """ # identify governing relationals rel = self.atoms(Relational) irel = list(ordered([r for r in rel if x not in r.free_symbols and r not in (S.true, S.false)])) if irel: args = {} exprinorder = [] for truth in product((1, 0), repeat=len(irel)): reps = dict(zip(irel, truth)) # only store the true conditions since the false are implied # when they appear lower in the Piecewise args if 1 not in truth: cond = None # flag this one so it doesn't get combined else: andargs = Tuple(*[i for i in reps if reps[i]]) free = list(andargs.free_symbols) if len(free) == 1: from sympy.solvers.inequalities import ( reduce_inequalities, _solve_inequality) try: t = reduce_inequalities(andargs, free[0]) # ValueError when there are potentially # nonvanishing imaginary parts except (ValueError, NotImplementedError): # at least isolate free symbol on left t = And(*[_solve_inequality( a, free[0], linear=True) for a in andargs]) else: t = And(*andargs) if t is S.false: continue # an impossible combination cond = t expr = handler(self.xreplace(reps)) if isinstance(expr, self.func) and len(expr.args) == 1: expr, econd = expr.args[0] cond = And(econd, True if cond is None else cond) # the ec pairs are being collected since all possibilities # are being enumerated, but don't put the last one in since # its expr might match a previous expression and it # must appear last in the args if cond is not None: args.setdefault(expr, []).append(cond) # but since we only store the true conditions we must maintain # the order so that the expression with the most true values # comes first exprinorder.append(expr) # convert collected conditions as args of Or for k in args: args[k] = Or(*args[k]) # take them in the order obtained args = [(e, args[e]) for e in uniq(exprinorder)] # add in the last arg args.append((expr, True)) return Piecewise(*args) def _eval_integral(self, x, _first=True, **kwargs): """Return the indefinite integral of the Piecewise such that subsequent substitution of x with a value will give the value of the integral (not including the constant of integration) up to that point. To only integrate the individual parts of Piecewise, use the ``piecewise_integrate`` method. Examples ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True)) >>> p.integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True)) >>> p.piecewise_integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x, True)) See Also ======== Piecewise.piecewise_integrate """ from sympy.integrals.integrals import integrate if _first: def handler(ipw): if isinstance(ipw, self.func): return ipw._eval_integral(x, _first=False, **kwargs) else: return ipw.integrate(x, **kwargs) irv = self._handle_irel(x, handler) if irv is not None: return irv # handle a Piecewise from -oo to oo with and no x-independent relationals # ----------------------------------------------------------------------- ok, abei = self._intervals(x) if not ok: from sympy.integrals.integrals import Integral return Integral(self, x) # unevaluated pieces = [(a, b) for a, b, _, _ in abei] oo = S.Infinity done = [(-oo, oo, -1)] for k, p in enumerate(pieces): if p == (-oo, oo): # all undone intervals will get this key for j, (a, b, i) in enumerate(done): if i == -1: done[j] = a, b, k break # nothing else to consider N = len(done) - 1 for j, (a, b, i) in enumerate(reversed(done)): if i == -1: j = N - j done[j: j + 1] = _clip(p, (a, b), k) done = [(a, b, i) for a, b, i in done if a != b] # append an arg if there is a hole so a reference to # argument -1 will give Undefined if any(i == -1 for (a, b, i) in done): abei.append((-oo, oo, Undefined, -1)) # return the sum of the intervals args = [] sum = None for a, b, i in done: anti = integrate(abei[i][-2], x, **kwargs) if sum is None: sum = anti else: sum = sum.subs(x, a) e = anti._eval_interval(x, a, x) if sum.has(*_illegal) or e.has(*_illegal): sum = anti else: sum += e # see if we know whether b is contained in original # condition if b is S.Infinity: cond = True elif self.args[abei[i][-1]].cond.subs(x, b) == False: cond = (x < b) else: cond = (x <= b) args.append((sum, cond)) return Piecewise(*args) def _eval_interval(self, sym, a, b, _first=True): """Evaluates the function along the sym in a given interval [a, b]""" # FIXME: Currently complex intervals are not supported. A possible # replacement algorithm, discussed in issue 5227, can be found in the # following papers; # http://portal.acm.org/citation.cfm?id=281649 # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf if a is None or b is None: # In this case, it is just simple substitution return super()._eval_interval(sym, a, b) else: x, lo, hi = map(as_Basic, (sym, a, b)) if _first: # get only x-dependent relationals def handler(ipw): if isinstance(ipw, self.func): return ipw._eval_interval(x, lo, hi, _first=None) else: return ipw._eval_interval(x, lo, hi) irv = self._handle_irel(x, handler) if irv is not None: return irv if (lo < hi) is S.false or ( lo is S.Infinity or hi is S.NegativeInfinity): rv = self._eval_interval(x, hi, lo, _first=False) if isinstance(rv, Piecewise): rv = Piecewise(*[(-e, c) for e, c in rv.args]) else: rv = -rv return rv if (lo < hi) is S.true or ( hi is S.Infinity or lo is S.NegativeInfinity): pass else: _a = Dummy('lo') _b = Dummy('hi') a = lo if lo.is_comparable else _a b = hi if hi.is_comparable else _b pos = self._eval_interval(x, a, b, _first=False) if a == _a and b == _b: # it's purely symbolic so just swap lo and hi and # change the sign to get the value for when lo > hi neg, pos = (-pos.xreplace({_a: hi, _b: lo}), pos.xreplace({_a: lo, _b: hi})) else: # at least one of the bounds was comparable, so allow # _eval_interval to use that information when computing # the interval with lo and hi reversed neg, pos = (-self._eval_interval(x, hi, lo, _first=False), pos.xreplace({_a: lo, _b: hi})) # allow simplification based on ordering of lo and hi p = Dummy('', positive=True) if lo.is_Symbol: pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo}) neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi}) elif hi.is_Symbol: pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo}) neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi}) # evaluate limits that may have unevaluate Min/Max touch = lambda _: _.replace( lambda x: isinstance(x, (Min, Max)), lambda x: x.func(*x.args)) neg = touch(neg) pos = touch(pos) # assemble return expression; make the first condition be Lt # b/c then the first expression will look the same whether # the lo or hi limit is symbolic if a == _a: # the lower limit was symbolic rv = Piecewise( (pos, lo < hi), (neg, True)) else: rv = Piecewise( (neg, hi < lo), (pos, True)) if rv == Undefined: raise ValueError("Can't integrate across undefined region.") if any(isinstance(i, Piecewise) for i in (pos, neg)): rv = piecewise_fold(rv) return rv # handle a Piecewise with lo <= hi and no x-independent relationals # ----------------------------------------------------------------- ok, abei = self._intervals(x) if not ok: from sympy.integrals.integrals import Integral # not being able to do the interval of f(x) can # be stated as not being able to do the integral # of f'(x) over the same range return Integral(self.diff(x), (x, lo, hi)) # unevaluated pieces = [(a, b) for a, b, _, _ in abei] done = [(lo, hi, -1)] oo = S.Infinity for k, p in enumerate(pieces): if p[:2] == (-oo, oo): # all undone intervals will get this key for j, (a, b, i) in enumerate(done): if i == -1: done[j] = a, b, k break # nothing else to consider N = len(done) - 1 for j, (a, b, i) in enumerate(reversed(done)): if i == -1: j = N - j done[j: j + 1] = _clip(p, (a, b), k) done = [(a, b, i) for a, b, i in done if a != b] # return the sum of the intervals sum = S.Zero upto = None for a, b, i in done: if i == -1: if upto is None: return Undefined # TODO simplify hi <= upto return Piecewise((sum, hi <= upto), (Undefined, True)) sum += abei[i][-2]._eval_interval(x, a, b) upto = b return sum def _intervals(self, sym, err_on_Eq=False): r"""Return a bool and a message (when bool is False), else a list of unique tuples, (a, b, e, i), where a and b are the lower and upper bounds in which the expression e of argument i in self is defined and $a < b$ (when involving numbers) or $a \le b$ when involving symbols. If there are any relationals not involving sym, or any relational cannot be solved for sym, the bool will be False a message be given as the second return value. The calling routine should have removed such relationals before calling this routine. The evaluated conditions will be returned as ranges. Discontinuous ranges will be returned separately with identical expressions. The first condition that evaluates to True will be returned as the last tuple with a, b = -oo, oo. """ from sympy.solvers.inequalities import _solve_inequality assert isinstance(self, Piecewise) def nonsymfail(cond): return False, filldedent(''' A condition not involving %s appeared: %s''' % (sym, cond)) def _solve_relational(r): if sym not in r.free_symbols: return nonsymfail(r) try: rv = _solve_inequality(r, sym) except NotImplementedError: return False, 'Unable to solve relational %s for %s.' % (r, sym) if isinstance(rv, Relational): free = rv.args[1].free_symbols if rv.args[0] != sym or sym in free: return False, 'Unable to solve relational %s for %s.' % (r, sym) if rv.rel_op == '==': # this equality has been affirmed to have the form # Eq(sym, rhs) where rhs is sym-free; it represents # a zero-width interval which will be ignored # whether it is an isolated condition or contained # within an And or an Or rv = S.false elif rv.rel_op == '!=': try: rv = Or(sym < rv.rhs, sym > rv.rhs) except TypeError: # e.g. x != I ==> all real x satisfy rv = S.true elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity): rv = S.true return True, rv args = list(self.args) # make self canonical wrt Relationals keys = self.atoms(Relational) reps = {} for r in keys: ok, s = _solve_relational(r) if ok != True: return False, ok reps[r] = s # process args individually so if any evaluate, their position # in the original Piecewise will be known args = [i.xreplace(reps) for i in self.args] # precondition args expr_cond = [] default = idefault = None for i, (expr, cond) in enumerate(args): if cond is S.false: continue if cond is S.true: default = expr idefault = i break if isinstance(cond, Eq): # unanticipated condition, but it is here in case a # replacement caused an Eq to appear if err_on_Eq: return False, 'encountered Eq condition: %s' % cond continue # zero width interval cond = to_cnf(cond) if isinstance(cond, And): cond = distribute_or_over_and(cond) if isinstance(cond, Or): expr_cond.extend( [(i, expr, o) for o in cond.args if not isinstance(o, Eq)]) elif cond is not S.false: expr_cond.append((i, expr, cond)) elif cond is S.true: default = expr idefault = i break # determine intervals represented by conditions int_expr = [] for iarg, expr, cond in expr_cond: if isinstance(cond, And): lower = S.NegativeInfinity upper = S.Infinity exclude = [] for cond2 in cond.args: if not isinstance(cond2, Relational): return False, 'expecting only Relationals' if isinstance(cond2, Eq): lower = upper # ignore if err_on_Eq: return False, 'encountered secondary Eq condition' break elif isinstance(cond2, Ne): l, r = cond2.args if l == sym: exclude.append(r) elif r == sym: exclude.append(l) else: return nonsymfail(cond2) continue elif cond2.lts == sym: upper = Min(cond2.gts, upper) elif cond2.gts == sym: lower = Max(cond2.lts, lower) else: return nonsymfail(cond2) # should never get here if exclude: exclude = list(ordered(exclude)) newcond = [] for i, e in enumerate(exclude): if e < lower == True or e > upper == True: continue if not newcond: newcond.append((None, lower)) # add a primer newcond.append((newcond[-1][1], e)) newcond.append((newcond[-1][1], upper)) newcond.pop(0) # remove the primer expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond]) continue elif isinstance(cond, Relational) and cond.rel_op != '!=': lower, upper = cond.lts, cond.gts # part 1: initialize with givens if cond.lts == sym: # part 1a: expand the side ... lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0 elif cond.gts == sym: # part 1a: ... that can be expanded upper = S.Infinity # e.g. x >= 0 ---> oo >= 0 else: return nonsymfail(cond) else: return False, 'unrecognized condition: %s' % cond lower, upper = lower, Max(lower, upper) if err_on_Eq and lower == upper: return False, 'encountered Eq condition' if (lower >= upper) is not S.true: int_expr.append((lower, upper, expr, iarg)) if default is not None: int_expr.append( (S.NegativeInfinity, S.Infinity, default, idefault)) return True, list(uniq(int_expr)) def _eval_nseries(self, x, n, logx, cdir=0): args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args] return self.func(*args) def _eval_power(self, s): return self.func(*[(e**s, c) for e, c in self.args]) def _eval_subs(self, old, new): # this is strictly not necessary, but we can keep track # of whether True or False conditions arise and be # somewhat more efficient by avoiding other substitutions # and avoiding invalid conditions that appear after a # True condition args = list(self.args) args_exist = False for i, (e, c) in enumerate(args): c = c._subs(old, new) if c != False: args_exist = True e = e._subs(old, new) args[i] = (e, c) if c == True: break if not args_exist: args = ((Undefined, True),) return self.func(*args) def _eval_transpose(self): return self.func(*[(e.transpose(), c) for e, c in self.args]) def _eval_template_is_attr(self, is_attr): b = None for expr, _ in self.args: a = getattr(expr, is_attr) if a is None: return if b is None: b = a elif b is not a: return return b _eval_is_finite = lambda self: self._eval_template_is_attr( 'is_finite') _eval_is_complex = lambda self: self._eval_template_is_attr('is_complex') _eval_is_even = lambda self: self._eval_template_is_attr('is_even') _eval_is_imaginary = lambda self: self._eval_template_is_attr( 'is_imaginary') _eval_is_integer = lambda self: self._eval_template_is_attr('is_integer') _eval_is_irrational = lambda self: self._eval_template_is_attr( 'is_irrational') _eval_is_negative = lambda self: self._eval_template_is_attr('is_negative') _eval_is_nonnegative = lambda self: self._eval_template_is_attr( 'is_nonnegative') _eval_is_nonpositive = lambda self: self._eval_template_is_attr( 'is_nonpositive') _eval_is_nonzero = lambda self: self._eval_template_is_attr( 'is_nonzero') _eval_is_odd = lambda self: self._eval_template_is_attr('is_odd') _eval_is_polar = lambda self: self._eval_template_is_attr('is_polar') _eval_is_positive = lambda self: self._eval_template_is_attr('is_positive') _eval_is_extended_real = lambda self: self._eval_template_is_attr( 'is_extended_real') _eval_is_extended_positive = lambda self: self._eval_template_is_attr( 'is_extended_positive') _eval_is_extended_negative = lambda self: self._eval_template_is_attr( 'is_extended_negative') _eval_is_extended_nonzero = lambda self: self._eval_template_is_attr( 'is_extended_nonzero') _eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr( 'is_extended_nonpositive') _eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr( 'is_extended_nonnegative') _eval_is_real = lambda self: self._eval_template_is_attr('is_real') _eval_is_zero = lambda self: self._eval_template_is_attr( 'is_zero') @classmethod def __eval_cond(cls, cond): """Return the truth value of the condition.""" if cond == True: return True if isinstance(cond, Eq): try: diff = cond.lhs - cond.rhs if diff.is_commutative: return diff.is_zero except TypeError: pass def as_expr_set_pairs(self, domain=None): """Return tuples for each argument of self that give the expression and the interval in which it is valid which is contained within the given domain. If a condition cannot be converted to a set, an error will be raised. The variable of the conditions is assumed to be real; sets of real values are returned. Examples ======== >>> from sympy import Piecewise, Interval >>> from sympy.abc import x >>> p = Piecewise( ... (1, x < 2), ... (2,(x > 0) & (x < 4)), ... (3, True)) >>> p.as_expr_set_pairs() [(1, Interval.open(-oo, 2)), (2, Interval.Ropen(2, 4)), (3, Interval(4, oo))] >>> p.as_expr_set_pairs(Interval(0, 3)) [(1, Interval.Ropen(0, 2)), (2, Interval(2, 3))] """ if domain is None: domain = S.Reals exp_sets = [] U = domain complex = not domain.is_subset(S.Reals) cond_free = set() for expr, cond in self.args: cond_free |= cond.free_symbols if len(cond_free) > 1: raise NotImplementedError(filldedent(''' multivariate conditions are not handled.''')) if complex: for i in cond.atoms(Relational): if not isinstance(i, (Eq, Ne)): raise ValueError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) cond_int = U.intersect(cond.as_set()) U = U - cond_int if cond_int != S.EmptySet: exp_sets.append((expr, cond_int)) return exp_sets def _eval_rewrite_as_ITE(self, *args, **kwargs): byfree = {} args = list(args) default = any(c == True for b, c in args) for i, (b, c) in enumerate(args): if not isinstance(b, Boolean) and b != True: raise TypeError(filldedent(''' Expecting Boolean or bool but got `%s` ''' % func_name(b))) if c == True: break # loop over independent conditions for this b for c in c.args if isinstance(c, Or) else [c]: free = c.free_symbols x = free.pop() try: byfree[x] = byfree.setdefault( x, S.EmptySet).union(c.as_set()) except NotImplementedError: if not default: raise NotImplementedError(filldedent(''' A method to determine whether a multivariate conditional is consistent with a complete coverage of all variables has not been implemented so the rewrite is being stopped after encountering `%s`. This error would not occur if a default expression like `(foo, True)` were given. ''' % c)) if byfree[x] in (S.UniversalSet, S.Reals): # collapse the ith condition to True and break args[i] = list(args[i]) c = args[i][1] = True break if c == True: break if c != True: raise ValueError(filldedent(''' Conditions must cover all reals or a final default condition `(foo, True)` must be given. ''')) last, _ = args[i] # ignore all past ith arg for a, c in reversed(args[:i]): last = ITE(c, a, last) return _canonical(last) def _eval_rewrite_as_KroneckerDelta(self, *args): from sympy.functions.special.tensor_functions import KroneckerDelta rules = { And: [False, False], Or: [True, True], Not: [True, False], Eq: [None, None], Ne: [None, None] } class UnrecognizedCondition(Exception): pass def rewrite(cond): if isinstance(cond, Eq): return KroneckerDelta(*cond.args) if isinstance(cond, Ne): return 1 - KroneckerDelta(*cond.args) cls, args = type(cond), cond.args if cls not in rules: raise UnrecognizedCondition(cls) b1, b2 = rules[cls] k = 1 for c in args: if b1: k *= 1 - rewrite(c) else: k *= rewrite(c) if b2: return 1 - k return k conditions = [] true_value = None for value, cond in args: if type(cond) in rules: conditions.append((value, cond)) elif cond is S.true: if true_value is None: true_value = value else: return if true_value is not None: result = true_value for value, cond in conditions[::-1]: try: k = rewrite(cond) result = k * value + (1 - k) * result except UnrecognizedCondition: return return result def piecewise_fold(expr, evaluate=True): """ Takes an expression containing a piecewise function and returns the expression in piecewise form. In addition, any ITE conditions are rewritten in negation normal form and simplified. The final Piecewise is evaluated (default) but if the raw form is desired, send ``evaluate=False``; if trivial evaluation is desired, send ``evaluate=None`` and duplicate conditions and processing of True and False will be handled. Examples ======== >>> from sympy import Piecewise, piecewise_fold, S >>> from sympy.abc import x >>> p = Piecewise((x, x < 1), (1, S(1) <= x)) >>> piecewise_fold(x*p) Piecewise((x**2, x < 1), (x, True)) See Also ======== Piecewise """ if not isinstance(expr, Basic) or not expr.has(Piecewise): return expr new_args = [] if isinstance(expr, (ExprCondPair, Piecewise)): for e, c in expr.args: if not isinstance(e, Piecewise): e = piecewise_fold(e) # we don't keep Piecewise in condition because # it has to be checked to see that it's complete # and we convert it to ITE at that time assert not c.has(Piecewise) # pragma: no cover if isinstance(c, ITE): c = c.to_nnf() c = simplify_logic(c, form='cnf') if isinstance(e, Piecewise): new_args.extend([(piecewise_fold(ei), And(ci, c)) for ei, ci in e.args]) else: new_args.append((e, c)) else: # Given # P1 = Piecewise((e11, c1), (e12, c2), A) # P2 = Piecewise((e21, c1), (e22, c2), B) # ... # the folding of f(P1, P2) is trivially # Piecewise( # (f(e11, e21), c1), # (f(e12, e22), c2), # (f(Piecewise(A), Piecewise(B)), True)) # Certain objects end up rewriting themselves as thus, so # we do that grouping before the more generic folding. # The following applies this idea when f = Add or f = Mul # (and the expression is commutative). if expr.is_Add or expr.is_Mul and expr.is_commutative: p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True) pc = sift(p, lambda x: tuple([c for e,c in x.args])) for c in list(ordered(pc)): if len(pc[c]) > 1: pargs = [list(i.args) for i in pc[c]] # the first one is the same; there may be more com = common_prefix(*[ [i.cond for i in j] for j in pargs]) n = len(com) collected = [] for i in range(n): collected.append(( expr.func(*[ai[i].expr for ai in pargs]), com[i])) remains = [] for a in pargs: if n == len(a): # no more args continue if a[n].cond == True: # no longer Piecewise remains.append(a[n].expr) else: # restore the remaining Piecewise remains.append( Piecewise(*a[n:], evaluate=False)) if remains: collected.append((expr.func(*remains), True)) args.append(Piecewise(*collected, evaluate=False)) continue args.extend(pc[c]) else: args = expr.args # fold folded = list(map(piecewise_fold, args)) for ec in product(*[ (i.args if isinstance(i, Piecewise) else [(i, true)]) for i in folded]): e, c = zip(*ec) new_args.append((expr.func(*e), And(*c))) if evaluate is None: # don't return duplicate conditions, otherwise don't evaluate new_args = list(reversed([(e, c) for c, e in { c: e for e, c in reversed(new_args)}.items()])) rv = Piecewise(*new_args, evaluate=evaluate) if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True: return rv.args[0].expr return rv def _clip(A, B, k): """Return interval B as intervals that are covered by A (keyed to k) and all other intervals of B not covered by A keyed to -1. The reference point of each interval is the rhs; if the lhs is greater than the rhs then an interval of zero width interval will result, e.g. (4, 1) is treated like (1, 1). Examples ======== >>> from sympy.functions.elementary.piecewise import _clip >>> from sympy import Tuple >>> A = Tuple(1, 3) >>> B = Tuple(2, 4) >>> _clip(A, B, 0) [(2, 3, 0), (3, 4, -1)] Interpretation: interval portion (2, 3) of interval (2, 4) is covered by interval (1, 3) and is keyed to 0 as requested; interval (3, 4) was not covered by (1, 3) and is keyed to -1. """ a, b = B c, d = A c, d = Min(Max(c, a), b), Min(Max(d, a), b) a, b = Min(a, b), b p = [] if a != c: p.append((a, c, -1)) else: pass if c != d: p.append((c, d, k)) else: pass if b != d: if d == c and p and p[-1][-1] == -1: p[-1] = p[-1][0], b, -1 else: p.append((d, b, -1)) else: pass return p def piecewise_simplify_arguments(expr, **kwargs): from sympy.simplify.simplify import simplify # simplify conditions f1 = expr.args[0].cond.free_symbols args = None if len(f1) == 1 and not expr.atoms(Eq): x = f1.pop() # this won't return intervals involving Eq # and it won't handle symbols treated as # booleans ok, abe_ = expr._intervals(x, err_on_Eq=True) def include(c, x, a): "return True if c.subs(x, a) is True, else False" try: return c.subs(x, a) == True except TypeError: return False if ok: args = [] covered = S.EmptySet from sympy.sets.sets import Interval for a, b, e, i in abe_: c = expr.args[i].cond incl_a = include(c, x, a) incl_b = include(c, x, b) iv = Interval(a, b, not incl_a, not incl_b) cset = iv - covered if not cset: continue if incl_a and incl_b: if a.is_infinite and b.is_infinite: c = S.true elif b.is_infinite: c = (x >= a) elif a in covered or a.is_infinite: c = (x <= b) else: c = And(a <= x, x <= b) elif incl_a: if a in covered or a.is_infinite: c = (x < b) else: c = And(a <= x, x < b) elif incl_b: if b.is_infinite: c = (x > a) else: c = (x <= b) else: if a in covered: c = (x < b) else: c = And(a < x, x < b) covered |= iv if a is S.NegativeInfinity and incl_a: covered |= {S.NegativeInfinity} if b is S.Infinity and incl_b: covered |= {S.Infinity} args.append((e, c)) if not S.Reals.is_subset(covered): args.append((Undefined, True)) if args is None: args = list(expr.args) for i in range(len(args)): e, c = args[i] if isinstance(c, Basic): c = simplify(c, **kwargs) args[i] = (e, c) # simplify expressions doit = kwargs.pop('doit', None) for i in range(len(args)): e, c = args[i] if isinstance(e, Basic): # Skip doit to avoid growth at every call for some integrals # and sums, see sympy/sympy#17165 newe = simplify(e, doit=False, **kwargs) if newe != e: e = newe args[i] = (e, c) # restore kwargs flag if doit is not None: kwargs['doit'] = doit return Piecewise(*args) def piecewise_simplify(expr, **kwargs): expr = piecewise_simplify_arguments(expr, **kwargs) if not isinstance(expr, Piecewise): return expr args = list(expr.args) _blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and ( getattr(e.rhs, '_diff_wrt', None) or isinstance(e.rhs, (Rational, NumberSymbol))) for i, (expr, cond) in enumerate(args): # try to simplify conditions and the expression for # equalities that are part of the condition, e.g. # Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True)) # -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True)) if isinstance(cond, And): eqs, other = sift(cond.args, lambda i: isinstance(i, Eq), binary=True) elif isinstance(cond, Eq): eqs, other = [cond], [] else: eqs = other = [] if eqs: eqs = list(ordered(eqs)) for j, e in enumerate(eqs): # these blessed lhs objects behave like Symbols # and the rhs are simple replacements for the "symbols" if _blessed(e): expr = expr.subs(*e.args) eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]] other = [ei.subs(*e.args) for ei in other] cond = And(*(eqs + other)) args[i] = args[i].func(expr, cond) # See if expressions valid for an Equal expression happens to evaluate # to the same function as in the next piecewise segment, see: # https://github.com/sympy/sympy/issues/8458 prevexpr = None for i, (expr, cond) in reversed(list(enumerate(args))): if prevexpr is not None: if isinstance(cond, And): eqs, other = sift(cond.args, lambda i: isinstance(i, Eq), binary=True) elif isinstance(cond, Eq): eqs, other = [cond], [] else: eqs = other = [] _prevexpr = prevexpr _expr = expr if eqs and not other: eqs = list(ordered(eqs)) for e in eqs: # allow 2 args to collapse into 1 for any e # otherwise limit simplification to only simple-arg # Eq instances if len(args) == 2 or _blessed(e): _prevexpr = _prevexpr.subs(*e.args) _expr = _expr.subs(*e.args) # Did it evaluate to the same? if _prevexpr == _expr: # Set the expression for the Not equal section to the same # as the next. These will be merged when creating the new # Piecewise args[i] = args[i].func(args[i+1][0], cond) else: # Update the expression that we compare against prevexpr = expr else: prevexpr = expr return Piecewise(*args)
eb9b04d1b95a9e81f78a68b5cfa6dd8e5937223ab9b48a4c1b5e96a63a76c1f3
from typing import Tuple as tTuple from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core import Add, S from sympy.core.evalf import get_integer_part, PrecisionExhausted from sympy.core.function import Function from sympy.core.logic import fuzzy_or from sympy.core.numbers import Integer from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq from sympy.core.symbol import Symbol from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import im from sympy.multipledispatch import dispatch ############################################################################### ######################### FLOOR and CEILING FUNCTIONS ######################### ############################################################################### class RoundFunction(Function): """Abstract base class for rounding functions.""" args: tTuple[Expr] @classmethod def eval(cls, arg): v = cls._eval_number(arg) if v is not None: return v if arg.is_integer or arg.is_finite is False: return arg if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real: i = im(arg) if not i.has(S.ImaginaryUnit): return cls(i)*S.ImaginaryUnit return cls(arg, evaluate=False) # Integral, numerical, symbolic part ipart = npart = spart = S.Zero # Extract integral (or complex integral) terms terms = Add.make_args(arg) for t in terms: if t.is_integer or (t.is_imaginary and im(t).is_integer): ipart += t elif t.has(Symbol): spart += t else: npart += t if not (npart or spart): return ipart # Evaluate npart numerically if independent of spart if npart and ( not spart or npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or npart.is_imaginary and spart.is_real): try: r, i = get_integer_part( npart, cls._dir, {}, return_ints=True) ipart += Integer(r) + Integer(i)*S.ImaginaryUnit npart = S.Zero except (PrecisionExhausted, NotImplementedError): pass spart += npart if not spart: return ipart elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real: return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit elif isinstance(spart, (floor, ceiling)): return ipart + spart else: return ipart + cls(spart, evaluate=False) @classmethod def _eval_number(cls, arg): raise NotImplementedError() def _eval_is_finite(self): return self.args[0].is_finite def _eval_is_real(self): return self.args[0].is_real def _eval_is_integer(self): return self.args[0].is_real class floor(RoundFunction): """ Floor is a univariate function which returns the largest integer value not greater than its argument. This implementation generalizes floor to complex numbers by taking the floor of the real and imaginary parts separately. Examples ======== >>> from sympy import floor, E, I, S, Float, Rational >>> floor(17) 17 >>> floor(Rational(23, 10)) 2 >>> floor(2*E) 5 >>> floor(-Float(0.567)) -1 >>> floor(-I/2) -I >>> floor(S(5)/2 + 5*I/2) 2 + 2*I See Also ======== sympy.functions.elementary.integers.ceiling References ========== .. [1] "Concrete mathematics" by Graham, pp. 87 .. [2] http://mathworld.wolfram.com/FloorFunction.html """ _dir = -1 @classmethod def _eval_number(cls, arg): if arg.is_Number: return arg.floor() elif any(isinstance(i, j) for i in (arg, -arg) for j in (floor, ceiling)): return arg if arg.is_NumberSymbol: return arg.approximation_interval(Integer)[0] def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) r = self.subs(x, 0) if arg0.is_finite: if arg0 == r: if cdir == 0: ndirl = arg.dir(x, cdir=-1) ndir = arg.dir(x, cdir=1) if ndir != ndirl: raise ValueError("Two sided limit of %s around 0" "does not exist" % self) else: ndir = arg.dir(x, cdir=cdir) return r - 1 if ndir.is_negative else r else: return r return arg.as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) if arg0.is_infinite: from sympy.calculus.accumulationbounds import AccumBounds from sympy.series.order import Order s = arg._eval_nseries(x, n, logx, cdir) o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0) return s + o r = self.subs(x, 0) if arg0 == r: ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1) return r - 1 if ndir.is_negative else r else: return r def _eval_is_negative(self): return self.args[0].is_negative def _eval_is_nonnegative(self): return self.args[0].is_nonnegative def _eval_rewrite_as_ceiling(self, arg, **kwargs): return -ceiling(-arg) def _eval_rewrite_as_frac(self, arg, **kwargs): return arg - frac(arg) def __le__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] < other + 1 if other.is_number and other.is_real: return self.args[0] < ceiling(other) if self.args[0] == other and other.is_real: return S.true if other is S.Infinity and self.is_finite: return S.true return Le(self, other, evaluate=False) def __ge__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] >= other if other.is_number and other.is_real: return self.args[0] >= ceiling(other) if self.args[0] == other and other.is_real: return S.false if other is S.NegativeInfinity and self.is_finite: return S.true return Ge(self, other, evaluate=False) def __gt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] >= other + 1 if other.is_number and other.is_real: return self.args[0] >= ceiling(other) if self.args[0] == other and other.is_real: return S.false if other is S.NegativeInfinity and self.is_finite: return S.true return Gt(self, other, evaluate=False) def __lt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] < other if other.is_number and other.is_real: return self.args[0] < ceiling(other) if self.args[0] == other and other.is_real: return S.false if other is S.Infinity and self.is_finite: return S.true return Lt(self, other, evaluate=False) @dispatch(floor, Expr) def _eval_is_eq(lhs, rhs): # noqa:F811 return is_eq(lhs.rewrite(ceiling), rhs) or \ is_eq(lhs.rewrite(frac),rhs) class ceiling(RoundFunction): """ Ceiling is a univariate function which returns the smallest integer value not less than its argument. This implementation generalizes ceiling to complex numbers by taking the ceiling of the real and imaginary parts separately. Examples ======== >>> from sympy import ceiling, E, I, S, Float, Rational >>> ceiling(17) 17 >>> ceiling(Rational(23, 10)) 3 >>> ceiling(2*E) 6 >>> ceiling(-Float(0.567)) 0 >>> ceiling(I/2) I >>> ceiling(S(5)/2 + 5*I/2) 3 + 3*I See Also ======== sympy.functions.elementary.integers.floor References ========== .. [1] "Concrete mathematics" by Graham, pp. 87 .. [2] http://mathworld.wolfram.com/CeilingFunction.html """ _dir = 1 @classmethod def _eval_number(cls, arg): if arg.is_Number: return arg.ceiling() elif any(isinstance(i, j) for i in (arg, -arg) for j in (floor, ceiling)): return arg if arg.is_NumberSymbol: return arg.approximation_interval(Integer)[1] def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) r = self.subs(x, 0) if arg0.is_finite: if arg0 == r: if cdir == 0: ndirl = arg.dir(x, cdir=-1) ndir = arg.dir(x, cdir=1) if ndir != ndirl: raise ValueError("Two sided limit of %s around 0" "does not exist" % self) else: ndir = arg.dir(x, cdir=cdir) return r if ndir.is_negative else r + 1 else: return r return arg.as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) if arg0.is_infinite: from sympy.calculus.accumulationbounds import AccumBounds from sympy.series.order import Order s = arg._eval_nseries(x, n, logx, cdir) o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) return s + o r = self.subs(x, 0) if arg0 == r: ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1) return r if ndir.is_negative else r + 1 else: return r def _eval_rewrite_as_floor(self, arg, **kwargs): return -floor(-arg) def _eval_rewrite_as_frac(self, arg, **kwargs): return arg + frac(-arg) def _eval_is_positive(self): return self.args[0].is_positive def _eval_is_nonpositive(self): return self.args[0].is_nonpositive def __lt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] <= other - 1 if other.is_number and other.is_real: return self.args[0] <= floor(other) if self.args[0] == other and other.is_real: return S.false if other is S.Infinity and self.is_finite: return S.true return Lt(self, other, evaluate=False) def __gt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] > other if other.is_number and other.is_real: return self.args[0] > floor(other) if self.args[0] == other and other.is_real: return S.false if other is S.NegativeInfinity and self.is_finite: return S.true return Gt(self, other, evaluate=False) def __ge__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] > other - 1 if other.is_number and other.is_real: return self.args[0] > floor(other) if self.args[0] == other and other.is_real: return S.true if other is S.NegativeInfinity and self.is_finite: return S.true return Ge(self, other, evaluate=False) def __le__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] <= other if other.is_number and other.is_real: return self.args[0] <= floor(other) if self.args[0] == other and other.is_real: return S.false if other is S.Infinity and self.is_finite: return S.true return Le(self, other, evaluate=False) @dispatch(ceiling, Basic) # type:ignore def _eval_is_eq(lhs, rhs): # noqa:F811 return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs) class frac(Function): r"""Represents the fractional part of x For real numbers it is defined [1]_ as .. math:: x - \left\lfloor{x}\right\rfloor Examples ======== >>> from sympy import Symbol, frac, Rational, floor, I >>> frac(Rational(4, 3)) 1/3 >>> frac(-Rational(4, 3)) 2/3 returns zero for integer arguments >>> n = Symbol('n', integer=True) >>> frac(n) 0 rewrite as floor >>> x = Symbol('x') >>> frac(x).rewrite(floor) x - floor(x) for complex arguments >>> r = Symbol('r', real=True) >>> t = Symbol('t', real=True) >>> frac(t + I*r) I*frac(r) + frac(t) See Also ======== sympy.functions.elementary.integers.floor sympy.functions.elementary.integers.ceiling References =========== .. [1] https://en.wikipedia.org/wiki/Fractional_part .. [2] http://mathworld.wolfram.com/FractionalPart.html """ @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds def _eval(arg): if arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(0, 1) if arg.is_integer: return S.Zero if arg.is_number: if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN else: return arg - floor(arg) return cls(arg, evaluate=False) terms = Add.make_args(arg) real, imag = S.Zero, S.Zero for t in terms: # Two checks are needed for complex arguments # see issue-7649 for details if t.is_imaginary or (S.ImaginaryUnit*t).is_real: i = im(t) if not i.has(S.ImaginaryUnit): imag += i else: real += t else: real += t real = _eval(real) imag = _eval(imag) return real + S.ImaginaryUnit*imag def _eval_rewrite_as_floor(self, arg, **kwargs): return arg - floor(arg) def _eval_rewrite_as_ceiling(self, arg, **kwargs): return arg + ceiling(-arg) def _eval_is_finite(self): return True def _eval_is_real(self): return self.args[0].is_extended_real def _eval_is_imaginary(self): return self.args[0].is_imaginary def _eval_is_integer(self): return self.args[0].is_integer def _eval_is_zero(self): return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer]) def _eval_is_negative(self): return False def __ge__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other <= 0 if other.is_extended_nonpositive: return S.true # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return not(res) return Ge(self, other, evaluate=False) def __gt__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other < 0 res = self._value_one_or_more(other) if res is not None: return not(res) # Check if other >= 1 if other.is_extended_negative: return S.true return Gt(self, other, evaluate=False) def __le__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other < 0 if other.is_extended_negative: return S.false # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return res return Le(self, other, evaluate=False) def __lt__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other <= 0 if other.is_extended_nonpositive: return S.false # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return res return Lt(self, other, evaluate=False) def _value_one_or_more(self, other): if other.is_extended_real: if other.is_number: res = other >= 1 if res and not isinstance(res, Relational): return S.true if other.is_integer and other.is_positive: return S.true @dispatch(frac, Basic) # type:ignore def _eval_is_eq(lhs, rhs): # noqa:F811 if (lhs.rewrite(floor) == rhs) or \ (lhs.rewrite(ceiling) == rhs): return True # Check if other < 0 if rhs.is_extended_negative: return False # Check if other >= 1 res = lhs._value_one_or_more(rhs) if res is not None: return False
76049c291c835fcbe43df3ac9345da5b194809cdafaa27f96e0ed1741325833e
from itertools import product from typing import Tuple as tTuple from sympy.core.expr import Expr from sympy.core import sympify from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.function import (Function, ArgumentIndexError, expand_log, expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex) from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or from sympy.core.mul import Mul from sympy.core.numbers import Integer, Rational, pi, I, ImaginaryUnit from sympy.core.parameters import global_parameters from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Wild, Dummy from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory import multiplicity, perfect_power from sympy.ntheory.factor_ import factorint from sympy.polys.polytools import cancel # NOTE IMPORTANT # The series expansion code in this file is an important part of the gruntz # algorithm for determining limits. _eval_nseries has to return a generalized # power series with coefficients in C(log(x), log). # In more detail, the result of _eval_nseries(self, x, n) must be # c_0*x**e_0 + ... (finitely many terms) # where e_i are numbers (not necessarily integers) and c_i involve only # numbers, the function log, and log(x). [This also means it must not contain # log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and # p.is_positive.] class ExpBase(Function): unbranched = True _singularities = (S.ComplexInfinity,) @property def kind(self): return self.exp.kind def inverse(self, argindex=1): """ Returns the inverse function of ``exp(x)``. """ return log def as_numer_denom(self): """ Returns this with a positive exponent as a 2-tuple (a fraction). Examples ======== >>> from sympy import exp >>> from sympy.abc import x >>> exp(-x).as_numer_denom() (1, exp(x)) >>> exp(x).as_numer_denom() (exp(x), 1) """ # this should be the same as Pow.as_numer_denom wrt # exponent handling exp = self.exp neg_exp = exp.is_negative if not neg_exp and not (-exp).is_negative: neg_exp = exp.could_extract_minus_sign() if neg_exp: return S.One, self.func(-exp) return self, S.One @property def exp(self): """ Returns the exponent of the function. """ return self.args[0] def as_base_exp(self): """ Returns the 2-tuple (base, exponent). """ return self.func(1), Mul(*self.args) def _eval_adjoint(self): return self.func(self.exp.adjoint()) def _eval_conjugate(self): return self.func(self.exp.conjugate()) def _eval_transpose(self): return self.func(self.exp.transpose()) def _eval_is_finite(self): arg = self.exp if arg.is_infinite: if arg.is_extended_negative: return True if arg.is_extended_positive: return False if arg.is_finite: return True def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: z = s.exp.is_zero if z: return True elif s.exp.is_rational and fuzzy_not(z): return False else: return s.is_rational def _eval_is_zero(self): return self.exp is S.NegativeInfinity def _eval_power(self, other): """exp(arg)**e -> exp(arg*e) if assumptions allow it. """ b, e = self.as_base_exp() return Pow._eval_power(Pow(b, e, evaluate=False), other) def _eval_expand_power_exp(self, **hints): from sympy.concrete.products import Product from sympy.concrete.summations import Sum arg = self.args[0] if arg.is_Add and arg.is_commutative: return Mul.fromiter(self.func(x) for x in arg.args) elif isinstance(arg, Sum) and arg.is_commutative: return Product(self.func(arg.function), *arg.limits) return self.func(arg) class exp_polar(ExpBase): r""" Represent a *polar number* (see g-function Sphinx documentation). Explanation =========== ``exp_polar`` represents the function `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of the main functions to construct polar numbers. Examples ======== >>> from sympy import exp_polar, pi, I, exp The main difference is that polar numbers do not "wrap around" at `2 \pi`: >>> exp(2*pi*I) 1 >>> exp_polar(2*pi*I) exp_polar(2*I*pi) apart from that they behave mostly like classical complex numbers: >>> exp_polar(2)*exp_polar(3) exp_polar(5) See Also ======== sympy.simplify.powsimp.powsimp polar_lift periodic_argument principal_branch """ is_polar = True is_comparable = False # cannot be evalf'd def _eval_Abs(self): # Abs is never a polar number return exp(re(self.args[0])) def _eval_evalf(self, prec): """ Careful! any evalf of polar numbers is flaky """ i = im(self.args[0]) try: bad = (i <= -pi or i > pi) except TypeError: bad = True if bad: return self # cannot evalf for this argument res = exp(self.args[0])._eval_evalf(prec) if i > 0 and im(res) < 0: # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi return re(res) return res def _eval_power(self, other): return self.func(self.args[0]*other) def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def as_base_exp(self): # XXX exp_polar(0) is special! if self.args[0] == 0: return self, S.One return ExpBase.as_base_exp(self) class ExpMeta(FunctionClass): def __instancecheck__(cls, instance): if exp in instance.__class__.__mro__: return True return isinstance(instance, Pow) and instance.base is S.Exp1 class exp(ExpBase, metaclass=ExpMeta): """ The exponential function, :math:`e^x`. Examples ======== >>> from sympy import exp, I, pi >>> from sympy.abc import x >>> exp(x) exp(x) >>> exp(x).diff(x) exp(x) >>> exp(I*pi) -1 Parameters ========== arg : Expr See Also ======== log """ def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return self else: raise ArgumentIndexError(self, argindex) def _eval_refine(self, assumptions): from sympy.assumptions import ask, Q arg = self.args[0] if arg.is_Mul: Ioo = S.ImaginaryUnit*S.Infinity if arg in [Ioo, -Ioo]: return S.NaN coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit) if coeff: if ask(Q.integer(2*coeff)): if ask(Q.even(coeff)): return S.One elif ask(Q.odd(coeff)): return S.NegativeOne elif ask(Q.even(coeff + S.Half)): return -S.ImaginaryUnit elif ask(Q.odd(coeff + S.Half)): return S.ImaginaryUnit @classmethod def eval(cls, arg): from sympy.calculus import AccumBounds from sympy.matrices.matrices import MatrixBase from sympy.sets.setexpr import SetExpr from sympy.simplify.simplify import logcombine if isinstance(arg, MatrixBase): return arg.exp() elif global_parameters.exp_is_pow: return Pow(S.Exp1, arg) elif arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.One elif arg is S.One: return S.Exp1 elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg is S.ComplexInfinity: return S.NaN elif isinstance(arg, log): return arg.args[0] elif isinstance(arg, AccumBounds): return AccumBounds(exp(arg.min), exp(arg.max)) elif isinstance(arg, SetExpr): return arg._eval_func(cls) elif arg.is_Mul: coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit) if coeff: if (2*coeff).is_integer: if coeff.is_even: return S.One elif coeff.is_odd: return S.NegativeOne elif (coeff + S.Half).is_even: return -S.ImaginaryUnit elif (coeff + S.Half).is_odd: return S.ImaginaryUnit elif coeff.is_Rational: ncoeff = coeff % 2 # restrict to [0, 2pi) if ncoeff > 1: # restrict to (-pi, pi] ncoeff -= 2 if ncoeff != coeff: return cls(ncoeff*S.Pi*S.ImaginaryUnit) # Warning: code in risch.py will be very sensitive to changes # in this (see DifferentialExtension). # look for a single log factor coeff, terms = arg.as_coeff_Mul() # but it can't be multiplied by oo if coeff in [S.NegativeInfinity, S.Infinity]: if terms.is_number: if coeff is S.NegativeInfinity: terms = -terms if re(terms).is_zero and terms is not S.Zero: return S.NaN if re(terms).is_positive and im(terms) is not S.Zero: return S.ComplexInfinity if re(terms).is_negative: return S.Zero return None coeffs, log_term = [coeff], None for term in Mul.make_args(terms): term_ = logcombine(term) if isinstance(term_, log): if log_term is None: log_term = term_.args[0] else: return None elif term.is_comparable: coeffs.append(term) else: return None return log_term**Mul(*coeffs) if log_term else None elif arg.is_Add: out = [] add = [] argchanged = False for a in arg.args: if a is S.One: add.append(a) continue newa = cls(a) if isinstance(newa, cls): if newa.args[0] != a: add.append(newa.args[0]) argchanged = True else: add.append(a) else: out.append(newa) if out or argchanged: return Mul(*out)*cls(Add(*add), evaluate=False) if arg.is_zero: return S.One @property def base(self): """ Returns the base of the exponential function. """ return S.Exp1 @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Calculates the next term in the Taylor series expansion. """ if n < 0: return S.Zero if n == 0: return S.One x = sympify(x) if previous_terms: p = previous_terms[-1] if p is not None: return p * x / n return x**n/factorial(n) def as_real_imag(self, deep=True, **hints): """ Returns this function as a 2-tuple representing a complex number. Examples ======== >>> from sympy import exp, I >>> from sympy.abc import x >>> exp(x).as_real_imag() (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x))) >>> exp(1).as_real_imag() (E, 0) >>> exp(I).as_real_imag() (cos(1), sin(1)) >>> exp(1+I).as_real_imag() (E*cos(1), E*sin(1)) See Also ======== sympy.functions.elementary.complexes.re sympy.functions.elementary.complexes.im """ from sympy.functions.elementary.trigonometric import cos, sin re, im = self.args[0].as_real_imag() if deep: re = re.expand(deep, **hints) im = im.expand(deep, **hints) cos, sin = cos(im), sin(im) return (exp(re)*cos, exp(re)*sin) def _eval_subs(self, old, new): # keep processing of power-like args centralized in Pow if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2) old = exp(old.exp*log(old.base)) elif old is S.Exp1 and new.is_Function: old = exp if isinstance(old, exp) or old is S.Exp1: f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if ( a.is_Pow or isinstance(a, exp)) else a return Pow._eval_subs(f(self), f(old), new) if old is exp and not new.is_Function: return new**self.exp._subs(old, new) return Function._eval_subs(self, old, new) def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True elif self.args[0].is_imaginary: arg2 = -S(2) * S.ImaginaryUnit * self.args[0] / S.Pi return arg2.is_even def _eval_is_complex(self): def complex_extended_negative(arg): yield arg.is_complex yield arg.is_extended_negative return fuzzy_or(complex_extended_negative(self.args[0])) def _eval_is_algebraic(self): if (self.exp / S.Pi / S.ImaginaryUnit).is_rational: return True if fuzzy_not(self.exp.is_zero): if self.exp.is_algebraic: return False elif (self.exp / S.Pi).is_rational: return False def _eval_is_extended_positive(self): if self.exp.is_extended_real: return self.args[0] is not S.NegativeInfinity elif self.exp.is_imaginary: arg2 = -S.ImaginaryUnit * self.args[0] / S.Pi return arg2.is_even def _eval_nseries(self, x, n, logx, cdir=0): # NOTE Please see the comment at the beginning of this file, labelled # IMPORTANT. from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.integers import ceiling from sympy.series.limits import limit from sympy.series.order import Order from sympy.simplify.powsimp import powsimp arg = self.exp arg_series = arg._eval_nseries(x, n=n, logx=logx) if arg_series.is_Order: return 1 + arg_series arg0 = limit(arg_series.removeO(), x, 0) if arg0 is S.NegativeInfinity: return Order(x**n, x) if arg0 is S.Infinity: return self # checking for indecisiveness/ sign terms in arg0 if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args): return self t = Dummy("t") nterms = n try: cf = Order(arg.as_leading_term(x, logx=logx), x).getn() except (NotImplementedError, PoleError): cf = 0 if cf and cf > 0: nterms = ceiling(n/cf) exp_series = exp(t)._taylor(t, nterms) r = exp(arg0)*exp_series.subs(t, arg_series - arg0) if cf and cf > 1: r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n) else: r += Order((arg_series - arg0)**n, x) r = r.expand() r = powsimp(r, deep=True, combine='exp') # powsimp may introduce unexpanded (-1)**Rational; see PR #17201 simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6] w = Wild('w', properties=[simplerat]) r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w)) return r def _taylor(self, x, n): l = [] g = None for i in range(n): g = self.taylor_term(i, self.args[0], g) g = g.nseries(x, n=n) l.append(g.removeO()) return Add(*l) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.util import AccumBounds arg = self.args[0].cancel().as_leading_term(x, logx=logx) arg0 = arg.subs(x, 0) if arg is S.NaN: return S.NaN if isinstance(arg0, AccumBounds): # This check addresses a corner case involving AccumBounds. # if isinstance(arg, AccumBounds) is True, then arg0 can either be 0, # AccumBounds(-oo, 0) or AccumBounds(-oo, oo). # Check out function: test_issue_18473() in test_exponential.py and # test_limits.py for more information. return exp(arg0) if arg0 is S.NaN: arg0 = arg.limit(x, 0) if arg0.is_infinite is False: return exp(arg0) raise PoleError("Cannot expand %s around 0" % (self)) def _eval_rewrite_as_sin(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import sin I = S.ImaginaryUnit return sin(I*arg + S.Pi/2) - I*sin(I*arg) def _eval_rewrite_as_cos(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import cos I = S.ImaginaryUnit return cos(I*arg) + I*cos(I*arg + S.Pi/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import tanh return (1 + tanh(arg/2))/(1 - tanh(arg/2)) def _eval_rewrite_as_sqrt(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import sin, cos if arg.is_Mul: coeff = arg.coeff(S.Pi*S.ImaginaryUnit) if coeff and coeff.is_number: cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff) if not isinstance(cosine, cos) and not isinstance (sine, sin): return cosine + S.ImaginaryUnit*sine def _eval_rewrite_as_Pow(self, arg, **kwargs): if arg.is_Mul: logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1] if logs: return Pow(logs[0].args[0], arg.coeff(logs[0])) def match_real_imag(expr): r""" Try to match expr with $a + Ib$ for real $a$ and $b$. ``match_real_imag`` returns a tuple containing the real and imaginary parts of expr or ``(None, None)`` if direct matching is not possible. Contrary to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things by returning expressions themselves containing ``re()`` or ``im()`` and it does not expand its argument either. """ r_, i_ = expr.as_independent(S.ImaginaryUnit, as_Add=True) if i_ == 0 and r_.is_real: return (r_, i_) i_ = i_.as_coefficient(S.ImaginaryUnit) if i_ and i_.is_real and r_.is_real: return (r_, i_) else: return (None, None) # simpler to check for than None class log(Function): r""" The natural logarithm function `\ln(x)` or `\log(x)`. Explanation =========== Logarithms are taken with the natural base, `e`. To get a logarithm of a different base ``b``, use ``log(x, b)``, which is essentially short-hand for ``log(x)/log(b)``. ``log`` represents the principal branch of the natural logarithm. As such it has a branch cut along the negative real axis and returns values having a complex argument in `(-\pi, \pi]`. Examples ======== >>> from sympy import log, sqrt, S, I >>> log(8, 2) 3 >>> log(S(8)/3, 2) -log(3)/log(2) + 3 >>> log(-1 + I*sqrt(3)) log(2) + 2*I*pi/3 See Also ======== exp """ args: tTuple[Expr] _singularities = (S.Zero, S.ComplexInfinity) def fdiff(self, argindex=1): """ Returns the first derivative of the function. """ if argindex == 1: return 1/self.args[0] else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): r""" Returns `e^x`, the inverse function of `\log(x)`. """ return exp @classmethod def eval(cls, arg, base=None): from sympy.calculus import AccumBounds from sympy.sets.setexpr import SetExpr arg = sympify(arg) if base is not None: base = sympify(base) if base == 1: if arg == 1: return S.NaN else: return S.ComplexInfinity try: # handle extraction of powers of the base now # or else expand_log in Mul would have to handle this n = multiplicity(base, arg) if n: return n + log(arg / base**n) / log(base) else: return log(arg)/log(base) except ValueError: pass if base is not S.Exp1: return cls(arg)/cls(base) else: return cls(arg) if arg.is_Number: if arg.is_zero: return S.ComplexInfinity elif arg is S.One: return S.Zero elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg is S.NaN: return S.NaN elif arg.is_Rational and arg.p == 1: return -cls(arg.q) if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real: return arg.exp I = S.ImaginaryUnit if isinstance(arg, exp) and arg.exp.is_extended_real: return arg.exp elif isinstance(arg, exp) and arg.exp.is_number: r_, i_ = match_real_imag(arg.exp) if i_ and i_.is_comparable: i_ %= 2*S.Pi if i_ > S.Pi: i_ -= 2*S.Pi return r_ + expand_mul(i_ * I, deep=False) elif isinstance(arg, exp_polar): return unpolarify(arg.exp) elif isinstance(arg, AccumBounds): if arg.min.is_positive: return AccumBounds(log(arg.min), log(arg.max)) elif arg.min.is_zero: return AccumBounds(S.NegativeInfinity, log(arg.max)) else: return S.NaN elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.is_number: if arg.is_negative: return S.Pi * I + cls(-arg) elif arg is S.ComplexInfinity: return S.ComplexInfinity elif arg is S.Exp1: return S.One if arg.is_zero: return S.ComplexInfinity # don't autoexpand Pow or Mul (see the issue 3351): if not arg.is_Add: coeff = arg.as_coefficient(I) if coeff is not None: if coeff is S.Infinity: return S.Infinity elif coeff is S.NegativeInfinity: return S.Infinity elif coeff.is_Rational: if coeff.is_nonnegative: return S.Pi * I * S.Half + cls(coeff) else: return -S.Pi * I * S.Half + cls(-coeff) if arg.is_number and arg.is_algebraic: # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real. coeff, arg_ = arg.as_independent(I, as_Add=False) if coeff.is_negative: coeff *= -1 arg_ *= -1 arg_ = expand_mul(arg_, deep=False) r_, i_ = arg_.as_independent(I, as_Add=True) i_ = i_.as_coefficient(I) if coeff.is_real and i_ and i_.is_real and r_.is_real: if r_.is_zero: if i_.is_positive: return S.Pi * I * S.Half + cls(coeff * i_) elif i_.is_negative: return -S.Pi * I * S.Half + cls(coeff * -i_) else: from sympy.simplify import ratsimp # Check for arguments involving rational multiples of pi t = (i_/r_).cancel() t1 = (-t).cancel() atan_table = { # first quadrant only sqrt(3): S.Pi/3, 1: S.Pi/4, sqrt(5 - 2*sqrt(5)): S.Pi/5, sqrt(2)*sqrt(5 - sqrt(5))/(1 + sqrt(5)): S.Pi/5, sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5), sqrt(2)*sqrt(sqrt(5) + 5)/(-1 + sqrt(5)): S.Pi*Rational(2, 5), sqrt(3)/3: S.Pi/6, sqrt(2) - 1: S.Pi/8, sqrt(2 - sqrt(2))/sqrt(sqrt(2) + 2): S.Pi/8, sqrt(2) + 1: S.Pi*Rational(3, 8), sqrt(sqrt(2) + 2)/sqrt(2 - sqrt(2)): S.Pi*Rational(3, 8), sqrt(1 - 2*sqrt(5)/5): S.Pi/10, (-sqrt(2) + sqrt(10))/(2*sqrt(sqrt(5) + 5)): S.Pi/10, sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10), (sqrt(2) + sqrt(10))/(2*sqrt(5 - sqrt(5))): S.Pi*Rational(3, 10), 2 - sqrt(3): S.Pi/12, (-1 + sqrt(3))/(1 + sqrt(3)): S.Pi/12, 2 + sqrt(3): S.Pi*Rational(5, 12), (1 + sqrt(3))/(-1 + sqrt(3)): S.Pi*Rational(5, 12) } if t in atan_table: modulus = ratsimp(coeff * Abs(arg_)) if r_.is_positive: return cls(modulus) + I * atan_table[t] else: return cls(modulus) + I * (atan_table[t] - S.Pi) elif t1 in atan_table: modulus = ratsimp(coeff * Abs(arg_)) if r_.is_positive: return cls(modulus) + I * (-atan_table[t1]) else: return cls(modulus) + I * (S.Pi - atan_table[t1]) def as_base_exp(self): """ Returns this function in the form (base, exponent). """ return self, S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): # of log(1+x) r""" Returns the next term in the Taylor series expansion of `\log(1+x)`. """ from sympy.simplify.powsimp import powsimp if n < 0: return S.Zero x = sympify(x) if n == 0: return x if previous_terms: p = previous_terms[-1] if p is not None: return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp') return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1) def _eval_expand_log(self, deep=True, **hints): from sympy.concrete import Sum, Product force = hints.get('force', False) factor = hints.get('factor', False) if (len(self.args) == 2): return expand_log(self.func(*self.args), deep=deep, force=force) arg = self.args[0] if arg.is_Integer: # remove perfect powers p = perfect_power(arg) logarg = None coeff = 1 if p is not False: arg, coeff = p logarg = self.func(arg) # expand as product of its prime factors if factor=True if factor: p = factorint(arg) if arg not in p.keys(): logarg = sum(n*log(val) for val, n in p.items()) if logarg is not None: return coeff*logarg elif arg.is_Rational: return log(arg.p) - log(arg.q) elif arg.is_Mul: expr = [] nonpos = [] for x in arg.args: if force or x.is_positive or x.is_polar: a = self.func(x) if isinstance(a, log): expr.append(self.func(x)._eval_expand_log(**hints)) else: expr.append(a) elif x.is_negative: a = self.func(-x) expr.append(a) nonpos.append(S.NegativeOne) else: nonpos.append(x) return Add(*expr) + log(Mul(*nonpos)) elif arg.is_Pow or isinstance(arg, exp): if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1) .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar: b = arg.base e = arg.exp a = self.func(b) if isinstance(a, log): return unpolarify(e) * a._eval_expand_log(**hints) else: return unpolarify(e) * a elif isinstance(arg, Product): if force or arg.function.is_positive: return Sum(log(arg.function), *arg.limits) return self.func(arg) def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import expand_log, simplify, inversecombine if len(self.args) == 2: # it's unevaluated return simplify(self.func(*self.args), **kwargs) expr = self.func(simplify(self.args[0], **kwargs)) if kwargs['inverse']: expr = inversecombine(expr) expr = expand_log(expr, deep=True) return min([expr, self], key=kwargs['measure']) def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. Examples ======== >>> from sympy import I, log >>> from sympy.abc import x >>> log(x).as_real_imag() (log(Abs(x)), arg(x)) >>> log(I).as_real_imag() (0, pi/2) >>> log(1 + I).as_real_imag() (log(sqrt(2)), pi/4) >>> log(I*x).as_real_imag() (log(Abs(x)), arg(I*x)) """ sarg = self.args[0] if deep: sarg = self.args[0].expand(deep, **hints) sarg_abs = Abs(sarg) if sarg_abs == sarg: return self, S.Zero sarg_arg = arg(sarg) if hints.get('log', False): # Expand the log hints['complex'] = False return (log(sarg_abs).expand(deep, **hints), sarg_arg) else: return log(sarg_abs), sarg_arg def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if (self.args[0] - 1).is_zero: return True if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero): return False else: return s.is_rational def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if (self.args[0] - 1).is_zero: return True elif fuzzy_not((self.args[0] - 1).is_zero): if self.args[0].is_algebraic: return False else: return s.is_algebraic def _eval_is_extended_real(self): return self.args[0].is_extended_positive def _eval_is_complex(self): z = self.args[0] return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)]) def _eval_is_finite(self): arg = self.args[0] if arg.is_zero: return False return arg.is_finite def _eval_is_extended_positive(self): return (self.args[0] - 1).is_extended_positive def _eval_is_zero(self): return (self.args[0] - 1).is_zero def _eval_is_extended_nonnegative(self): return (self.args[0] - 1).is_extended_nonnegative def _eval_nseries(self, x, n, logx, cdir=0): # NOTE Please see the comment at the beginning of this file, labelled # IMPORTANT. from sympy.series.order import Order from sympy.simplify.simplify import logcombine if not logx: logx = log(x) if self.args[0] == x: return logx arg = self.args[0] k, l = Wild("k"), Wild("l") r = arg.match(k*x**l) if r is not None: k, l = r[k], r[l] if l != 0 and not l.has(x) and not k.has(x): r = log(k) + l*logx # XXX true regardless of assumptions? return r def coeff_exp(term, x): coeff, exp = S.One, S.Zero for factor in Mul.make_args(term): if factor.has(x): base, exp = factor.as_base_exp() if base != x: try: return term.leadterm(x) except ValueError: return term, S.Zero else: coeff *= factor return coeff, exp # TODO new and probably slow try: a, b = arg.leadterm(x) s = arg.nseries(x, n=n+b, logx=logx) except (ValueError, NotImplementedError, PoleError): s = arg.nseries(x, n=n, logx=logx) while s.is_Order: n += 1 s = arg.nseries(x, n=n, logx=logx) a, b = s.removeO().leadterm(x) p = cancel(s/(a*x**b) - 1).expand().powsimp() if p.has(exp): p = logcombine(p) if isinstance(p, Order): n = p.getn() _, d = coeff_exp(p, x) if not d.is_positive: return log(a) + b*logx + Order(x**n, x) def mul(d1, d2): res = {} for e1, e2 in product(d1, d2): ex = e1 + e2 if ex < n: res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2] return res pterms = {} for term in Add.make_args(p): co1, e1 = coeff_exp(term, x) pterms[e1] = pterms.get(e1, S.Zero) + co1.removeO() k = S.One terms = {} pk = pterms while k*d < n: coeff = -S.NegativeOne**k/k for ex in pk: terms[ex] = terms.get(ex, S.Zero) + coeff*pk[ex] pk = mul(pk, pterms) k += S.One res = log(a) + b*logx for ex in terms: res += terms[ex]*x**(ex) if cdir != 0: cdir = self.args[0].dir(x, cdir) if a.is_real and a.is_negative and im(cdir) < 0: res -= 2*I*S.Pi return res + Order(x**n, x) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.util import AccumBounds arg0 = self.args[0].together() arg = arg0.as_leading_term(x, cdir=cdir) x0 = arg0.subs(x, 0) if (x0 is S.NaN and logx is None): x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.NegativeInfinity, S.Infinity): raise PoleError("Cannot expand %s around 0" % (self)) if x0 == 1: return (arg0 - S.One).as_leading_term(x) if cdir != 0: cdir = arg0.dir(x, cdir) if x0.is_real and x0.is_negative and im(cdir).is_negative: return self.func(x0) - 2*I*S.Pi if isinstance(arg, AccumBounds): return log(arg) return self.func(arg) class LambertW(Function): r""" The Lambert W function $W(z)$ is defined as the inverse function of $w \exp(w)$ [1]_. Explanation =========== In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$ for any complex number $z$. The Lambert W function is a multivalued function with infinitely many branches $W_k(z)$, indexed by $k \in \mathbb{Z}$. Each branch gives a different solution $w$ of the equation $z = w \exp(w)$. The Lambert W function has two partially real branches: the principal branch ($k = 0$) is real for real $z > -1/e$, and the $k = -1$ branch is real for $-1/e < z < 0$. All branches except $k = 0$ have a logarithmic singularity at $z = 0$. Examples ======== >>> from sympy import LambertW >>> LambertW(1.2) 0.635564016364870 >>> LambertW(1.2, -1).n() -1.34747534407696 - 4.41624341514535*I >>> LambertW(-1).is_real False References ========== .. [1] https://en.wikipedia.org/wiki/Lambert_W_function """ _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity) @classmethod def eval(cls, x, k=None): if k == S.Zero: return cls(x) elif k is None: k = S.Zero if k.is_zero: if x.is_zero: return S.Zero if x is S.Exp1: return S.One if x == -1/S.Exp1: return S.NegativeOne if x == -log(2)/2: return -log(2) if x == 2*log(2): return log(2) if x == -S.Pi/2: return S.ImaginaryUnit*S.Pi/2 if x == exp(1 + S.Exp1): return S.Exp1 if x is S.Infinity: return S.Infinity if x.is_zero: return S.Zero if fuzzy_not(k.is_zero): if x.is_zero: return S.NegativeInfinity if k is S.NegativeOne: if x == -S.Pi/2: return -S.ImaginaryUnit*S.Pi/2 elif x == -1/S.Exp1: return S.NegativeOne elif x == -2*exp(-2): return -Integer(2) def fdiff(self, argindex=1): """ Return the first derivative of this function. """ x = self.args[0] if len(self.args) == 1: if argindex == 1: return LambertW(x)/(x*(1 + LambertW(x))) else: k = self.args[1] if argindex == 1: return LambertW(x, k)/(x*(1 + LambertW(x, k))) raise ArgumentIndexError(self, argindex) def _eval_is_extended_real(self): x = self.args[0] if len(self.args) == 1: k = S.Zero else: k = self.args[1] if k.is_zero: if (x + 1/S.Exp1).is_positive: return True elif (x + 1/S.Exp1).is_nonpositive: return False elif (k + 1).is_zero: if x.is_negative and (x + 1/S.Exp1).is_positive: return True elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative: return False elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero): if x.is_extended_real: return False def _eval_is_finite(self): return self.args[0].is_finite def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic: return False else: return s.is_algebraic def _eval_as_leading_term(self, x, logx=None, cdir=0): if len(self.args) == 1: arg = self.args[0] arg0 = arg.subs(x, 0).cancel() if not arg0.is_zero: return self.func(arg0) return arg.as_leading_term(x) def _eval_nseries(self, x, n, logx, cdir=0): if len(self.args) == 1: from sympy.functions.elementary.integers import ceiling from sympy.series.order import Order arg = self.args[0].nseries(x, n=n, logx=logx) lt = arg.compute_leading_term(x, logx=logx) lte = 1 if lt.is_Pow: lte = lt.exp if ceiling(n/lte) >= 1: s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/ factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))]) s = expand_multinomial(s) else: s = S.Zero return s + Order(x**n, x) return super()._eval_nseries(x, n, logx) def _eval_is_zero(self): x = self.args[0] if len(self.args) == 1: return x.is_zero else: return fuzzy_and([x.is_zero, self.args[1].is_zero])
7380ba572e5562ef0a3199eaf681fcd863b666557241c2e734a306f86f3db22d
from sympy.core.logic import FuzzyBool from sympy.core import S, sympify, cacheit, pi, I, Rational from sympy.core.add import Add from sympy.core.function import Function, ArgumentIndexError from sympy.core.logic import fuzzy_or, fuzzy_and from sympy.functions.combinatorial.factorials import (binomial, factorial, RisingFactorial) from sympy.functions.combinatorial.numbers import bernoulli, euler, nC from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp, log, match_real_imag from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.integers import floor from sympy.functions.elementary.trigonometric import (acot, asin, atan, cos, cot, sin, tan) from sympy.polys.specialpolys import symmetric_poly def _rewrite_hyperbolics_as_exp(expr): expr = sympify(expr) return expr.xreplace({h: h.rewrite(exp) for h in expr.atoms(HyperbolicFunction)}) ############################################################################### ########################### HYPERBOLIC FUNCTIONS ############################## ############################################################################### class HyperbolicFunction(Function): """ Base class for hyperbolic functions. See Also ======== sinh, cosh, tanh, coth """ unbranched = True def _peeloff_ipi(arg): r""" Split ARG into two parts, a "rest" and a multiple of $I\pi$. This assumes ARG to be an ``Add``. The multiple of $I\pi$ returned in the second position is always a ``Rational``. Examples ======== >>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel >>> from sympy import pi, I >>> from sympy.abc import x, y >>> peel(x + I*pi/2) (x, 1/2) >>> peel(x + I*2*pi/3 + I*pi*y) (x + I*pi*y + I*pi/6, 1/2) """ ipi = S.Pi*S.ImaginaryUnit for a in Add.make_args(arg): if a == ipi: K = S.One break elif a.is_Mul: K, p = a.as_two_terms() if p == ipi and K.is_Rational: break else: return arg, S.Zero m1 = (K % S.Half) m2 = K - m1 return arg - m2*ipi, m2 class sinh(HyperbolicFunction): r""" ``sinh(x)`` is the hyperbolic sine of ``x``. The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$. Examples ======== >>> from sympy import sinh >>> from sympy.abc import x >>> sinh(x) sinh(x) See Also ======== cosh, tanh, asinh """ def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return cosh(self.args[0]) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return asinh @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * sin(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: m = m*S.Pi*S.ImaginaryUnit return sinh(m)*cosh(x) + cosh(m)*sinh(x) if arg.is_zero: return S.Zero if arg.func == asinh: return arg.args[0] if arg.func == acosh: x = arg.args[0] return sqrt(x - 1) * sqrt(x + 1) if arg.func == atanh: x = arg.args[0] return x/sqrt(1 - x**2) if arg.func == acoth: x = arg.args[0] return 1/(sqrt(x - 1) * sqrt(x + 1)) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Returns the next term in the Taylor series expansion. """ if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return p * x**2 / (n*(n - 1)) else: return x**(n) / factorial(n) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. """ if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (sinh(re)*cos(im), cosh(re)*sin(im)) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _eval_expand_trig(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One and coeff.is_Integer and terms is not S.One: x = terms y = (coeff - 1)*x if x is not None: return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True) return sinh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return (exp(arg) - exp(-arg)) / 2 def _eval_rewrite_as_exp(self, arg, **kwargs): return (exp(arg) - exp(-arg)) / 2 def _eval_rewrite_as_cosh(self, arg, **kwargs): return -S.ImaginaryUnit*cosh(arg + S.Pi*S.ImaginaryUnit/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): tanh_half = tanh(S.Half*arg) return 2*tanh_half/(1 - tanh_half**2) def _eval_rewrite_as_coth(self, arg, **kwargs): coth_half = coth(S.Half*arg) return 2*coth_half/(coth_half**2 - 1) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+') if arg0.is_zero: return arg elif arg0.is_finite: return self.func(arg0) else: return self def _eval_is_real(self): arg = self.args[0] if arg.is_real: return True # if `im` is of the form n*pi # else, check if it is a number re, im = arg.as_real_imag() return (im%pi).is_zero def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_is_finite(self): arg = self.args[0] return arg.is_finite def _eval_is_zero(self): rest, ipi_mult = _peeloff_ipi(self.args[0]) if rest.is_zero: return ipi_mult.is_integer class cosh(HyperbolicFunction): r""" ``cosh(x)`` is the hyperbolic cosine of ``x``. The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$. Examples ======== >>> from sympy import cosh >>> from sympy.abc import x >>> cosh(x) cosh(x) See Also ======== sinh, tanh, acosh """ def fdiff(self, argindex=1): if argindex == 1: return sinh(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import cos arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg.is_zero: return S.One elif arg.is_negative: return cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return cos(i_coeff) else: if arg.could_extract_minus_sign(): return cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: m = m*S.Pi*S.ImaginaryUnit return cosh(m)*cosh(x) + sinh(m)*sinh(x) if arg.is_zero: return S.One if arg.func == asinh: return sqrt(1 + arg.args[0]**2) if arg.func == acosh: return arg.args[0] if arg.func == atanh: return 1/sqrt(1 - arg.args[0]**2) if arg.func == acoth: x = arg.args[0] return x/(sqrt(x - 1) * sqrt(x + 1)) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return p * x**2 / (n*(n - 1)) else: return x**(n)/factorial(n) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (cosh(re)*cos(im), sinh(re)*sin(im)) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _eval_expand_trig(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One and coeff.is_Integer and terms is not S.One: x = terms y = (coeff - 1)*x if x is not None: return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True) return cosh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return (exp(arg) + exp(-arg)) / 2 def _eval_rewrite_as_exp(self, arg, **kwargs): return (exp(arg) + exp(-arg)) / 2 def _eval_rewrite_as_sinh(self, arg, **kwargs): return -S.ImaginaryUnit*sinh(arg + S.Pi*S.ImaginaryUnit/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): tanh_half = tanh(S.Half*arg)**2 return (1 + tanh_half)/(1 - tanh_half) def _eval_rewrite_as_coth(self, arg, **kwargs): coth_half = coth(S.Half*arg)**2 return (coth_half + 1)/(coth_half - 1) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+') if arg0.is_zero: return S.One elif arg0.is_finite: return self.func(arg0) else: return self def _eval_is_real(self): arg = self.args[0] # `cosh(x)` is real for real OR purely imaginary `x` if arg.is_real or arg.is_imaginary: return True # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a) # the imaginary part can be an expression like n*pi # if not, check if the imaginary part is a number re, im = arg.as_real_imag() return (im%pi).is_zero def _eval_is_positive(self): # cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x) # cosh(z) is positive iff it is real and the real part is positive. # So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi # Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even # Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive z = self.args[0] x, y = z.as_real_imag() ymod = y % (2*pi) yzero = ymod.is_zero # shortcut if ymod is zero if yzero: return True xzero = x.is_zero # shortcut x is not zero if xzero is False: return yzero return fuzzy_or([ # Case 1: yzero, # Case 2: fuzzy_and([ xzero, fuzzy_or([ymod < pi/2, ymod > 3*pi/2]) ]) ]) def _eval_is_nonnegative(self): z = self.args[0] x, y = z.as_real_imag() ymod = y % (2*pi) yzero = ymod.is_zero # shortcut if ymod is zero if yzero: return True xzero = x.is_zero # shortcut x is not zero if xzero is False: return yzero return fuzzy_or([ # Case 1: yzero, # Case 2: fuzzy_and([ xzero, fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2]) ]) ]) def _eval_is_finite(self): arg = self.args[0] return arg.is_finite def _eval_is_zero(self): rest, ipi_mult = _peeloff_ipi(self.args[0]) if ipi_mult and rest.is_zero: return (ipi_mult - S.Half).is_integer class tanh(HyperbolicFunction): r""" ``tanh(x)`` is the hyperbolic tangent of ``x``. The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$. Examples ======== >>> from sympy import tanh >>> from sympy.abc import x >>> tanh(x) tanh(x) See Also ======== sinh, cosh, atanh """ def fdiff(self, argindex=1): if argindex == 1: return S.One - tanh(self.args[0])**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return atanh @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.Zero elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: if i_coeff.could_extract_minus_sign(): return -S.ImaginaryUnit * tan(-i_coeff) return S.ImaginaryUnit * tan(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: tanhm = tanh(m*S.Pi*S.ImaginaryUnit) if tanhm is S.ComplexInfinity: return coth(x) else: # tanhm == 0 return tanh(x) if arg.is_zero: return S.Zero if arg.func == asinh: x = arg.args[0] return x/sqrt(1 + x**2) if arg.func == acosh: x = arg.args[0] return sqrt(x - 1) * sqrt(x + 1) / x if arg.func == atanh: return arg.args[0] if arg.func == acoth: return 1/arg.args[0] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) a = 2**(n + 1) B = bernoulli(n + 1) F = factorial(n + 1) return a*(a - 1) * B/F * x**n def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() denom = sinh(re)**2 + cos(im)**2 return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom) def _eval_expand_trig(self, **hints): arg = self.args[0] if arg.is_Add: n = len(arg.args) TX = [tanh(x, evaluate=False)._eval_expand_trig() for x in arg.args] p = [0, 0] # [den, num] for i in range(n + 1): p[i % 2] += symmetric_poly(i, TX) return p[1]/p[0] elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul() if coeff.is_Integer and coeff > 1: n = [] d = [] T = tanh(terms) for k in range(1, coeff + 1, 2): n.append(nC(range(coeff), k)*T**k) for k in range(0, coeff + 1, 2): d.append(nC(range(coeff), k)*T**k) return Add(*n)/Add(*d) return tanh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp - neg_exp)/(pos_exp + neg_exp) def _eval_rewrite_as_exp(self, arg, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp - neg_exp)/(pos_exp + neg_exp) def _eval_rewrite_as_sinh(self, arg, **kwargs): return S.ImaginaryUnit*sinh(arg)/sinh(S.Pi*S.ImaginaryUnit/2 - arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return S.ImaginaryUnit*cosh(S.Pi*S.ImaginaryUnit/2 - arg)/cosh(arg) def _eval_rewrite_as_coth(self, arg, **kwargs): return 1/coth(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_is_real(self): arg = self.args[0] if arg.is_real: return True re, im = arg.as_real_imag() # if denom = 0, tanh(arg) = zoo if re == 0 and im % pi == pi/2: return None # check if im is of the form n*pi/2 to make sin(2*im) = 0 # if not, im could be a number, return False in that case return (im % (pi/2)).is_zero def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_is_finite(self): arg = self.args[0] re, im = arg.as_real_imag() denom = cos(im)**2 + sinh(re)**2 if denom == 0: return False elif denom.is_number: return True if arg.is_extended_real: return True def _eval_is_zero(self): arg = self.args[0] if arg.is_zero: return True class coth(HyperbolicFunction): r""" ``coth(x)`` is the hyperbolic cotangent of ``x``. The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$. Examples ======== >>> from sympy import coth >>> from sympy.abc import x >>> coth(x) coth(x) See Also ======== sinh, cosh, acoth """ def fdiff(self, argindex=1): if argindex == 1: return -1/sinh(self.args[0])**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return acoth @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.ComplexInfinity elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: if i_coeff.could_extract_minus_sign(): return S.ImaginaryUnit * cot(-i_coeff) return -S.ImaginaryUnit * cot(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: cothm = coth(m*S.Pi*S.ImaginaryUnit) if cothm is S.ComplexInfinity: return coth(x) else: # cothm == 0 return tanh(x) if arg.is_zero: return S.ComplexInfinity if arg.func == asinh: x = arg.args[0] return sqrt(1 + x**2)/x if arg.func == acosh: x = arg.args[0] return x/(sqrt(x - 1) * sqrt(x + 1)) if arg.func == atanh: return 1/arg.args[0] if arg.func == acoth: return arg.args[0] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return 1 / sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return 2**(n + 1) * B/F * x**n def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() denom = sinh(re)**2 + sin(im)**2 return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_exp(self, arg, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_sinh(self, arg, **kwargs): return -S.ImaginaryUnit*sinh(S.Pi*S.ImaginaryUnit/2 - arg)/sinh(arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return -S.ImaginaryUnit*cosh(arg)/cosh(S.Pi*S.ImaginaryUnit/2 - arg) def _eval_rewrite_as_tanh(self, arg, **kwargs): return 1/tanh(arg) def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return 1/arg else: return self.func(arg) def _eval_expand_trig(self, **hints): arg = self.args[0] if arg.is_Add: CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args] p = [[], []] n = len(arg.args) for i in range(n, -1, -1): p[(n - i) % 2].append(symmetric_poly(i, CX)) return Add(*p[0])/Add(*p[1]) elif arg.is_Mul: coeff, x = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: c = coth(x, evaluate=False) p = [[], []] for i in range(coeff, -1, -1): p[(coeff - i) % 2].append(binomial(coeff, i)*c**i) return Add(*p[0])/Add(*p[1]) return coth(arg) class ReciprocalHyperbolicFunction(HyperbolicFunction): """Base class for reciprocal functions of hyperbolic functions. """ #To be defined in class _reciprocal_of = None _is_even = None # type: FuzzyBool _is_odd = None # type: FuzzyBool @classmethod def eval(cls, arg): if arg.could_extract_minus_sign(): if cls._is_even: return cls(-arg) if cls._is_odd: return -cls(-arg) t = cls._reciprocal_of.eval(arg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] return 1/t if t is not None else t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of o = self._reciprocal_of(self.args[0]) return getattr(o, method_name)(*args, **kwargs) def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) if t is not None and t != self._reciprocal_of(arg): return 1/t def _eval_rewrite_as_exp(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg) def _eval_rewrite_as_tanh(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg) def _eval_rewrite_as_coth(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg) def as_real_imag(self, deep = True, **hints): return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=True, **hints) return re_part + S.ImaginaryUnit*im_part def _eval_expand_trig(self, **hints): return self._calculate_reciprocal("_eval_expand_trig", **hints) def _eval_as_leading_term(self, x, logx=None, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x) def _eval_is_extended_real(self): return self._reciprocal_of(self.args[0]).is_extended_real def _eval_is_finite(self): return (1/self._reciprocal_of(self.args[0])).is_finite class csch(ReciprocalHyperbolicFunction): r""" ``csch(x)`` is the hyperbolic cosecant of ``x``. The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$ Examples ======== >>> from sympy import csch >>> from sympy.abc import x >>> csch(x) csch(x) See Also ======== sinh, cosh, tanh, sech, asinh, acosh """ _reciprocal_of = sinh _is_odd = True def fdiff(self, argindex=1): """ Returns the first derivative of this function """ if argindex == 1: return -coth(self.args[0]) * csch(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Returns the next term in the Taylor series expansion """ if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return 2 * (1 - 2**n) * B/F * x**n def _eval_rewrite_as_cosh(self, arg, **kwargs): return S.ImaginaryUnit / cosh(arg + S.ImaginaryUnit * S.Pi / 2) def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative class sech(ReciprocalHyperbolicFunction): r""" ``sech(x)`` is the hyperbolic secant of ``x``. The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$ Examples ======== >>> from sympy import sech >>> from sympy.abc import x >>> sech(x) sech(x) See Also ======== sinh, cosh, tanh, coth, csch, asinh, acosh """ _reciprocal_of = cosh _is_even = True def fdiff(self, argindex=1): if argindex == 1: return - tanh(self.args[0])*sech(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) return euler(n) / factorial(n) * x**(n) def _eval_rewrite_as_sinh(self, arg, **kwargs): return S.ImaginaryUnit / sinh(arg + S.ImaginaryUnit * S.Pi /2) def _eval_is_positive(self): if self.args[0].is_extended_real: return True ############################################################################### ############################# HYPERBOLIC INVERSES ############################# ############################################################################### class InverseHyperbolicFunction(Function): """Base class for inverse hyperbolic functions.""" pass class asinh(InverseHyperbolicFunction): """ ``asinh(x)`` is the inverse hyperbolic sine of ``x``. The inverse hyperbolic sine function. Examples ======== >>> from sympy import asinh >>> from sympy.abc import x >>> asinh(x).diff(x) 1/sqrt(x**2 + 1) >>> asinh(1) log(1 + sqrt(2)) See Also ======== acosh, atanh, sinh """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(self.args[0]**2 + 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg is S.One: return log(sqrt(2) + 1) elif arg is S.NegativeOne: return log(sqrt(2) - 1) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_zero: return S.Zero i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * asin(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if isinstance(arg, sinh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor((i + pi/2)/pi) m = z - I*pi*f even = f.is_even if even is True: return m elif even is False: return -m @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return -p * (n - 2)**2/(n*(n - 1)) * x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return S.NegativeOne**k * R / F * x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return log(x + sqrt(x**2 + 1)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sinh def _eval_is_zero(self): return self.args[0].is_zero class acosh(InverseHyperbolicFunction): """ ``acosh(x)`` is the inverse hyperbolic cosine of ``x``. The inverse hyperbolic cosine function. Examples ======== >>> from sympy import acosh >>> from sympy.abc import x >>> acosh(x).diff(x) 1/sqrt(x**2 - 1) >>> acosh(1) 0 See Also ======== asinh, atanh, cosh """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(self.args[0]**2 - 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg.is_zero: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi*S.ImaginaryUnit if arg.is_number: cst_table = { S.ImaginaryUnit: log(S.ImaginaryUnit*(1 + sqrt(2))), -S.ImaginaryUnit: log(-S.ImaginaryUnit*(1 + sqrt(2))), S.Half: S.Pi/3, Rational(-1, 2): S.Pi*Rational(2, 3), sqrt(2)/2: S.Pi/4, -sqrt(2)/2: S.Pi*Rational(3, 4), 1/sqrt(2): S.Pi/4, -1/sqrt(2): S.Pi*Rational(3, 4), sqrt(3)/2: S.Pi/6, -sqrt(3)/2: S.Pi*Rational(5, 6), (sqrt(3) - 1)/sqrt(2**3): S.Pi*Rational(5, 12), -(sqrt(3) - 1)/sqrt(2**3): S.Pi*Rational(7, 12), sqrt(2 + sqrt(2))/2: S.Pi/8, -sqrt(2 + sqrt(2))/2: S.Pi*Rational(7, 8), sqrt(2 - sqrt(2))/2: S.Pi*Rational(3, 8), -sqrt(2 - sqrt(2))/2: S.Pi*Rational(5, 8), (1 + sqrt(3))/(2*sqrt(2)): S.Pi/12, -(1 + sqrt(3))/(2*sqrt(2)): S.Pi*Rational(11, 12), (sqrt(5) + 1)/4: S.Pi/5, -(sqrt(5) + 1)/4: S.Pi*Rational(4, 5) } if arg in cst_table: if arg.is_extended_real: return cst_table[arg]*S.ImaginaryUnit return cst_table[arg] if arg is S.ComplexInfinity: return S.ComplexInfinity if arg == S.ImaginaryUnit*S.Infinity: return S.Infinity + S.ImaginaryUnit*S.Pi/2 if arg == -S.ImaginaryUnit*S.Infinity: return S.Infinity - S.ImaginaryUnit*S.Pi/2 if arg.is_zero: return S.Pi*S.ImaginaryUnit*S.Half if isinstance(arg, cosh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return Abs(z) r, i = match_real_imag(z) if r is not None and i is not None: f = floor(i/pi) m = z - I*pi*f even = f.is_even if even is True: if r.is_nonnegative: return m elif r.is_negative: return -m elif even is False: m -= I*pi if r.is_nonpositive: return -m elif r.is_positive: return m @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi*S.ImaginaryUnit / 2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p * (n - 2)**2/(n*(n - 1)) * x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return -R / F * S.ImaginaryUnit * x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return S.ImaginaryUnit*S.Pi/2 else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return log(x + sqrt(x + 1) * sqrt(x - 1)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cosh def _eval_is_zero(self): if (self.args[0] - 1).is_zero: return True class atanh(InverseHyperbolicFunction): """ ``atanh(x)`` is the inverse hyperbolic tangent of ``x``. The inverse hyperbolic tangent function. Examples ======== >>> from sympy import atanh >>> from sympy.abc import x >>> atanh(x).diff(x) 1/(1 - x**2) See Also ======== asinh, acosh, tanh """ def fdiff(self, argindex=1): if argindex == 1: return 1/(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg is S.Infinity: return -S.ImaginaryUnit * atan(arg) elif arg is S.NegativeInfinity: return S.ImaginaryUnit * atan(-arg) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return S.ImaginaryUnit*AccumBounds(-S.Pi/2, S.Pi/2) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * atan(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_zero: return S.Zero if isinstance(arg, tanh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor(2*i/pi) even = f.is_even m = z - I*f*pi/2 if even is True: return m elif even is False: return m - I*pi/2 @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return (log(1 + x) - log(1 - x)) / 2 def _eval_is_zero(self): if self.args[0].is_zero: return True def _eval_is_imaginary(self): return self.args[0].is_imaginary def inverse(self, argindex=1): """ Returns the inverse of this function. """ return tanh class acoth(InverseHyperbolicFunction): """ ``acoth(x)`` is the inverse hyperbolic cotangent of ``x``. The inverse hyperbolic cotangent function. Examples ======== >>> from sympy import acoth >>> from sympy.abc import x >>> acoth(x).diff(x) 1/(1 - x**2) See Also ======== asinh, acosh, coth """ def fdiff(self, argindex=1): if argindex == 1: return 1/(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.Zero i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return -S.ImaginaryUnit * acot(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_zero: return S.Pi*S.ImaginaryUnit*S.Half @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi*S.ImaginaryUnit / 2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return S.ImaginaryUnit*S.Pi/2 else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return (log(1 + 1/x) - log(1 - 1/x)) / 2 def inverse(self, argindex=1): """ Returns the inverse of this function. """ return coth class asech(InverseHyperbolicFunction): """ ``asech(x)`` is the inverse hyperbolic secant of ``x``. The inverse hyperbolic secant function. Examples ======== >>> from sympy import asech, sqrt, S >>> from sympy.abc import x >>> asech(x).diff(x) -1/(x*sqrt(1 - x**2)) >>> asech(1).diff(x) 0 >>> asech(1) 0 >>> asech(S(2)) I*pi/3 >>> asech(-sqrt(2)) 3*I*pi/4 >>> asech((sqrt(6) - sqrt(2))) I*pi/12 See Also ======== asinh, atanh, cosh, acoth References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function .. [2] http://dlmf.nist.gov/4.37 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSech/ """ def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -1/(z*sqrt(1 - z**2)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.NegativeInfinity: return S.Pi*S.ImaginaryUnit / 2 elif arg.is_zero: return S.Infinity elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi*S.ImaginaryUnit if arg.is_number: cst_table = { S.ImaginaryUnit: - (S.Pi*S.ImaginaryUnit / 2) + log(1 + sqrt(2)), -S.ImaginaryUnit: (S.Pi*S.ImaginaryUnit / 2) + log(1 + sqrt(2)), (sqrt(6) - sqrt(2)): S.Pi / 12, (sqrt(2) - sqrt(6)): 11*S.Pi / 12, sqrt(2 - 2/sqrt(5)): S.Pi / 10, -sqrt(2 - 2/sqrt(5)): 9*S.Pi / 10, 2 / sqrt(2 + sqrt(2)): S.Pi / 8, -2 / sqrt(2 + sqrt(2)): 7*S.Pi / 8, 2 / sqrt(3): S.Pi / 6, -2 / sqrt(3): 5*S.Pi / 6, (sqrt(5) - 1): S.Pi / 5, (1 - sqrt(5)): 4*S.Pi / 5, sqrt(2): S.Pi / 4, -sqrt(2): 3*S.Pi / 4, sqrt(2 + 2/sqrt(5)): 3*S.Pi / 10, -sqrt(2 + 2/sqrt(5)): 7*S.Pi / 10, S(2): S.Pi / 3, -S(2): 2*S.Pi / 3, sqrt(2*(2 + sqrt(2))): 3*S.Pi / 8, -sqrt(2*(2 + sqrt(2))): 5*S.Pi / 8, (1 + sqrt(5)): 2*S.Pi / 5, (-1 - sqrt(5)): 3*S.Pi / 5, (sqrt(6) + sqrt(2)): 5*S.Pi / 12, (-sqrt(6) - sqrt(2)): 7*S.Pi / 12, } if arg in cst_table: if arg.is_extended_real: return cst_table[arg]*S.ImaginaryUnit return cst_table[arg] if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return S.ImaginaryUnit*AccumBounds(-S.Pi/2, S.Pi/2) if arg.is_zero: return S.Infinity @staticmethod @cacheit def expansion_term(n, x, *previous_terms): if n == 0: return log(2 / x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return p * (n - 1)**2 // (n // 2)**2 * x**2 / 4 else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return -1 * R / F * x**n / 4 def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sech def _eval_rewrite_as_log(self, arg, **kwargs): return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1)) class acsch(InverseHyperbolicFunction): """ ``acsch(x)`` is the inverse hyperbolic cosecant of ``x``. The inverse hyperbolic cosecant function. Examples ======== >>> from sympy import acsch, sqrt, S >>> from sympy.abc import x >>> acsch(x).diff(x) -1/(x**2*sqrt(1 + x**(-2))) >>> acsch(1).diff(x) 0 >>> acsch(1) log(1 + sqrt(2)) >>> acsch(S.ImaginaryUnit) -I*pi/2 >>> acsch(-2*S.ImaginaryUnit) I*pi/6 >>> acsch(S.ImaginaryUnit*(sqrt(6) - sqrt(2))) -5*I*pi/12 See Also ======== asinh References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function .. [2] http://dlmf.nist.gov/4.37 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsch/ """ def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -1/(z**2*sqrt(1 + 1/z**2)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.ComplexInfinity elif arg is S.One: return log(1 + sqrt(2)) elif arg is S.NegativeOne: return - log(1 + sqrt(2)) if arg.is_number: cst_table = { S.ImaginaryUnit: -S.Pi / 2, S.ImaginaryUnit*(sqrt(2) + sqrt(6)): -S.Pi / 12, S.ImaginaryUnit*(1 + sqrt(5)): -S.Pi / 10, S.ImaginaryUnit*2 / sqrt(2 - sqrt(2)): -S.Pi / 8, S.ImaginaryUnit*2: -S.Pi / 6, S.ImaginaryUnit*sqrt(2 + 2/sqrt(5)): -S.Pi / 5, S.ImaginaryUnit*sqrt(2): -S.Pi / 4, S.ImaginaryUnit*(sqrt(5)-1): -3*S.Pi / 10, S.ImaginaryUnit*2 / sqrt(3): -S.Pi / 3, S.ImaginaryUnit*2 / sqrt(2 + sqrt(2)): -3*S.Pi / 8, S.ImaginaryUnit*sqrt(2 - 2/sqrt(5)): -2*S.Pi / 5, S.ImaginaryUnit*(sqrt(6) - sqrt(2)): -5*S.Pi / 12, S(2): -S.ImaginaryUnit*log((1+sqrt(5))/2), } if arg in cst_table: return cst_table[arg]*S.ImaginaryUnit if arg is S.ComplexInfinity: return S.Zero if arg.is_zero: return S.ComplexInfinity if arg.could_extract_minus_sign(): return -cls(-arg) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return csch def _eval_rewrite_as_log(self, arg, **kwargs): return log(1/arg + sqrt(1/arg**2 + 1)) def _eval_is_zero(self): return self.args[0].is_infinite
cf554de0fd3ac3cfa9fbdcd00ee88566e8ee3610d8bd26a0e7e1a62169295105
from typing import Tuple as tTuple from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic from sympy.core.expr import Expr from sympy.core.exprtools import factor_terms from sympy.core.function import (Function, Derivative, ArgumentIndexError, AppliedUndef, expand_mul) from sympy.core.logic import fuzzy_not, fuzzy_or from sympy.core.numbers import pi, I, oo from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise ############################################################################### ######################### REAL and IMAGINARY PARTS ############################ ############################################################################### class re(Function): """ Returns real part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use ``Basic.as_real_imag()`` or perform complex expansion on instance of this function. Examples ======== >>> from sympy import re, im, I, E, symbols >>> x, y = symbols('x y', real=True) >>> re(2*E) 2*E >>> re(2*I + 17) 17 >>> re(2*I) 0 >>> re(im(x) + x*I + 2) 2 >>> re(5 + I + 2) 7 Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Real part of expression. See Also ======== im """ args: tTuple[Expr] is_extended_real = True unbranched = True # implicitly works on the projection to C _singularities = True # non-holomorphic @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN elif arg.is_extended_real: return arg elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real: return S.Zero elif arg.is_Matrix: return arg.as_real_imag()[0] elif arg.is_Function and isinstance(arg, conjugate): return re(arg.args[0]) else: included, reverted, excluded = [], [], [] args = Add.make_args(arg) for term in args: coeff = term.as_coefficient(S.ImaginaryUnit) if coeff is not None: if not coeff.is_extended_real: reverted.append(coeff) elif not term.has(S.ImaginaryUnit) and term.is_extended_real: excluded.append(term) else: # Try to do some advanced expansion. If # impossible, don't try to do re(arg) again # (because this is what we are trying to do now). real_imag = term.as_real_imag(ignore=arg) if real_imag: excluded.append(real_imag[0]) else: included.append(term) if len(args) != len(included): a, b, c = (Add(*xs) for xs in [included, reverted, excluded]) return cls(a) - im(b) + c def as_real_imag(self, deep=True, **hints): """ Returns the real number with a zero imaginary part. """ return (self, S.Zero) def _eval_derivative(self, x): if x.is_extended_real or self.args[0].is_extended_real: return re(Derivative(self.args[0], x, evaluate=True)) if x.is_imaginary or self.args[0].is_imaginary: return -S.ImaginaryUnit \ * im(Derivative(self.args[0], x, evaluate=True)) def _eval_rewrite_as_im(self, arg, **kwargs): return self.args[0] - S.ImaginaryUnit*im(self.args[0]) def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_is_zero(self): # is_imaginary implies nonzero return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero]) def _eval_is_finite(self): if self.args[0].is_finite: return True def _eval_is_complex(self): if self.args[0].is_finite: return True class im(Function): """ Returns imaginary part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use ``Basic.as_real_imag()`` or perform complex expansion on instance of this function. Examples ======== >>> from sympy import re, im, E, I >>> from sympy.abc import x, y >>> im(2*E) 0 >>> im(2*I + 17) 2 >>> im(x*I) re(x) >>> im(re(x) + y) im(y) >>> im(2 + 3*I) 3 Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Imaginary part of expression. See Also ======== re """ args: tTuple[Expr] is_extended_real = True unbranched = True # implicitly works on the projection to C _singularities = True # non-holomorphic @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN elif arg.is_extended_real: return S.Zero elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real: return -S.ImaginaryUnit * arg elif arg.is_Matrix: return arg.as_real_imag()[1] elif arg.is_Function and isinstance(arg, conjugate): return -im(arg.args[0]) else: included, reverted, excluded = [], [], [] args = Add.make_args(arg) for term in args: coeff = term.as_coefficient(S.ImaginaryUnit) if coeff is not None: if not coeff.is_extended_real: reverted.append(coeff) else: excluded.append(coeff) elif term.has(S.ImaginaryUnit) or not term.is_extended_real: # Try to do some advanced expansion. If # impossible, don't try to do im(arg) again # (because this is what we are trying to do now). real_imag = term.as_real_imag(ignore=arg) if real_imag: excluded.append(real_imag[1]) else: included.append(term) if len(args) != len(included): a, b, c = (Add(*xs) for xs in [included, reverted, excluded]) return cls(a) + re(b) + c def as_real_imag(self, deep=True, **hints): """ Return the imaginary part with a zero real part. """ return (self, S.Zero) def _eval_derivative(self, x): if x.is_extended_real or self.args[0].is_extended_real: return im(Derivative(self.args[0], x, evaluate=True)) if x.is_imaginary or self.args[0].is_imaginary: return -S.ImaginaryUnit \ * re(Derivative(self.args[0], x, evaluate=True)) def _eval_rewrite_as_re(self, arg, **kwargs): return -S.ImaginaryUnit*(self.args[0] - re(self.args[0])) def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_is_zero(self): return self.args[0].is_extended_real def _eval_is_finite(self): if self.args[0].is_finite: return True def _eval_is_complex(self): if self.args[0].is_finite: return True ############################################################################### ############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################ ############################################################################### class sign(Function): """ Returns the complex sign of an expression: Explanation =========== If the expression is real the sign will be: * $1$ if expression is positive * $0$ if expression is equal to zero * $-1$ if expression is negative If the expression is imaginary the sign will be: * $I$ if im(expression) is positive * $-I$ if im(expression) is negative Otherwise an unevaluated expression will be returned. When evaluated, the result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``. Examples ======== >>> from sympy import sign, I >>> sign(-1) -1 >>> sign(0) 0 >>> sign(-3*I) -I >>> sign(1 + I) sign(1 + I) >>> _.evalf() 0.707106781186548 + 0.707106781186548*I Parameters ========== arg : Expr Real or imaginary expression. Returns ======= expr : Expr Complex sign of expression. See Also ======== Abs, conjugate """ is_complex = True _singularities = True def doit(self, **hints): s = super().doit() if s == self and self.args[0].is_zero is False: return self.args[0] / Abs(self.args[0]) return s @classmethod def eval(cls, arg): # handle what we can if arg.is_Mul: c, args = arg.as_coeff_mul() unk = [] s = sign(c) for a in args: if a.is_extended_negative: s = -s elif a.is_extended_positive: pass else: if a.is_imaginary: ai = im(a) if ai.is_comparable: # i.e. a = I*real s *= S.ImaginaryUnit if ai.is_extended_negative: # can't use sign(ai) here since ai might not be # a Number s = -s else: unk.append(a) else: unk.append(a) if c is S.One and len(unk) == len(args): return None return s * cls(arg._new_rawargs(*unk)) if arg is S.NaN: return S.NaN if arg.is_zero: # it may be an Expr that is zero return S.Zero if arg.is_extended_positive: return S.One if arg.is_extended_negative: return S.NegativeOne if arg.is_Function: if isinstance(arg, sign): return arg if arg.is_imaginary: if arg.is_Pow and arg.exp is S.Half: # we catch this because non-trivial sqrt args are not expanded # e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1) return S.ImaginaryUnit arg2 = -S.ImaginaryUnit * arg if arg2.is_extended_positive: return S.ImaginaryUnit if arg2.is_extended_negative: return -S.ImaginaryUnit def _eval_Abs(self): if fuzzy_not(self.args[0].is_zero): return S.One def _eval_conjugate(self): return sign(conjugate(self.args[0])) def _eval_derivative(self, x): if self.args[0].is_extended_real: from sympy.functions.special.delta_functions import DiracDelta return 2 * Derivative(self.args[0], x, evaluate=True) \ * DiracDelta(self.args[0]) elif self.args[0].is_imaginary: from sympy.functions.special.delta_functions import DiracDelta return 2 * Derivative(self.args[0], x, evaluate=True) \ * DiracDelta(-S.ImaginaryUnit * self.args[0]) def _eval_is_nonnegative(self): if self.args[0].is_nonnegative: return True def _eval_is_nonpositive(self): if self.args[0].is_nonpositive: return True def _eval_is_imaginary(self): return self.args[0].is_imaginary def _eval_is_integer(self): return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_power(self, other): if ( fuzzy_not(self.args[0].is_zero) and other.is_integer and other.is_even ): return S.One def _eval_nseries(self, x, n, logx, cdir=0): arg0 = self.args[0] x0 = arg0.subs(x, 0) if x0 != 0: return self.func(x0) if cdir != 0: cdir = arg0.dir(x, cdir) return -S.One if re(cdir) < 0 else S.One def _eval_rewrite_as_Piecewise(self, arg, **kwargs): if arg.is_extended_real: return Piecewise((1, arg > 0), (-1, arg < 0), (0, True)) def _eval_rewrite_as_Heaviside(self, arg, **kwargs): from sympy.functions.special.delta_functions import Heaviside if arg.is_extended_real: return Heaviside(arg) * 2 - 1 def _eval_rewrite_as_Abs(self, arg, **kwargs): return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True)) def _eval_simplify(self, **kwargs): return self.func(factor_terms(self.args[0])) # XXX include doit? class Abs(Function): """ Return the absolute value of the argument. Explanation =========== This is an extension of the built-in function ``abs()`` to accept symbolic values. If you pass a SymPy expression to the built-in ``abs()``, it will pass it automatically to ``Abs()``. Examples ======== >>> from sympy import Abs, Symbol, S, I >>> Abs(-1) 1 >>> x = Symbol('x', real=True) >>> Abs(-x) Abs(x) >>> Abs(x**2) x**2 >>> abs(-x) # The Python built-in Abs(x) >>> Abs(3*x + 2*I) sqrt(9*x**2 + 4) >>> Abs(8*I) 8 Note that the Python built-in will return either an Expr or int depending on the argument:: >>> type(abs(-1)) <... 'int'> >>> type(abs(S.NegativeOne)) <class 'sympy.core.numbers.One'> Abs will always return a SymPy object. Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Absolute value returned can be an expression or integer depending on input arg. See Also ======== sign, conjugate """ args: tTuple[Expr] is_extended_real = True is_extended_negative = False is_extended_nonnegative = True unbranched = True _singularities = True # non-holomorphic def fdiff(self, argindex=1): """ Get the first derivative of the argument to Abs(). """ if argindex == 1: return sign(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.simplify.simplify import signsimp if hasattr(arg, '_eval_Abs'): obj = arg._eval_Abs() if obj is not None: return obj if not isinstance(arg, Expr): raise TypeError("Bad argument type for Abs(): %s" % type(arg)) # handle what we can arg = signsimp(arg, evaluate=False) n, d = arg.as_numer_denom() if d.free_symbols and not n.free_symbols: return cls(n)/cls(d) if arg.is_Mul: known = [] unk = [] for t in arg.args: if t.is_Pow and t.exp.is_integer and t.exp.is_negative: bnew = cls(t.base) if isinstance(bnew, cls): unk.append(t) else: known.append(Pow(bnew, t.exp)) else: tnew = cls(t) if isinstance(tnew, cls): unk.append(t) else: known.append(tnew) known = Mul(*known) unk = cls(Mul(*unk), evaluate=False) if unk else S.One return known*unk if arg is S.NaN: return S.NaN if arg is S.ComplexInfinity: return S.Infinity from sympy.functions.elementary.exponential import exp, log if arg.is_Pow: base, exponent = arg.as_base_exp() if base.is_extended_real: if exponent.is_integer: if exponent.is_even: return arg if base is S.NegativeOne: return S.One return Abs(base)**exponent if base.is_extended_nonnegative: return base**re(exponent) if base.is_extended_negative: return (-base)**re(exponent)*exp(-S.Pi*im(exponent)) return elif not base.has(Symbol): # complex base # express base**exponent as exp(exponent*log(base)) a, b = log(base).as_real_imag() z = a + I*b return exp(re(exponent*z)) if isinstance(arg, exp): return exp(re(arg.args[0])) if isinstance(arg, AppliedUndef): if arg.is_positive: return arg elif arg.is_negative: return -arg return if arg.is_Add and arg.has(S.Infinity, S.NegativeInfinity): if any(a.is_infinite for a in arg.as_real_imag()): return S.Infinity if arg.is_zero: return S.Zero if arg.is_extended_nonnegative: return arg if arg.is_extended_nonpositive: return -arg if arg.is_imaginary: arg2 = -S.ImaginaryUnit * arg if arg2.is_extended_nonnegative: return arg2 if arg.is_extended_real: return # reject result if all new conjugates are just wrappers around # an expression that was already in the arg conj = signsimp(arg.conjugate(), evaluate=False) new_conj = conj.atoms(conjugate) - arg.atoms(conjugate) if new_conj and all(arg.has(i.args[0]) for i in new_conj): return if arg != conj and arg != -conj: ignore = arg.atoms(Abs) abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore}) unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None] if not unk or not all(conj.has(conjugate(u)) for u in unk): return sqrt(expand_mul(arg*conj)) def _eval_is_real(self): if self.args[0].is_finite: return True def _eval_is_integer(self): if self.args[0].is_extended_real: return self.args[0].is_integer def _eval_is_extended_nonzero(self): return fuzzy_not(self._args[0].is_zero) def _eval_is_zero(self): return self._args[0].is_zero def _eval_is_extended_positive(self): is_z = self.is_zero if is_z is not None: return not is_z def _eval_is_rational(self): if self.args[0].is_extended_real: return self.args[0].is_rational def _eval_is_even(self): if self.args[0].is_extended_real: return self.args[0].is_even def _eval_is_odd(self): if self.args[0].is_extended_real: return self.args[0].is_odd def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_power(self, exponent): if self.args[0].is_extended_real and exponent.is_integer: if exponent.is_even: return self.args[0]**exponent elif exponent is not S.NegativeOne and exponent.is_Integer: return self.args[0]**(exponent - 1)*self return def _eval_nseries(self, x, n, logx, cdir=0): from sympy.functions.elementary.exponential import log direction = self.args[0].leadterm(x)[0] if direction.has(log(x)): direction = direction.subs(log(x), logx) s = self.args[0]._eval_nseries(x, n=n, logx=logx) return (sign(direction)*s).expand() def _eval_derivative(self, x): if self.args[0].is_extended_real or self.args[0].is_imaginary: return Derivative(self.args[0], x, evaluate=True) \ * sign(conjugate(self.args[0])) rv = (re(self.args[0]) * Derivative(re(self.args[0]), x, evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]), x, evaluate=True)) / Abs(self.args[0]) return rv.rewrite(sign) def _eval_rewrite_as_Heaviside(self, arg, **kwargs): # Note this only holds for real arg (since Heaviside is not defined # for complex arguments). from sympy.functions.special.delta_functions import Heaviside if arg.is_extended_real: return arg*(Heaviside(arg) - Heaviside(-arg)) def _eval_rewrite_as_Piecewise(self, arg, **kwargs): if arg.is_extended_real: return Piecewise((arg, arg >= 0), (-arg, True)) elif arg.is_imaginary: return Piecewise((I*arg, I*arg >= 0), (-I*arg, True)) def _eval_rewrite_as_sign(self, arg, **kwargs): return arg/sign(arg) def _eval_rewrite_as_conjugate(self, arg, **kwargs): return sqrt(arg*conjugate(arg)) class arg(Function): r""" Returns the argument (in radians) of a complex number. The argument is evaluated in consistent convention with ``atan2`` where the branch-cut is taken along the negative real axis and ``arg(z)`` is in the interval $(-\pi,\pi]$. For a positive number, the argument is always 0; the argument of a negative number is $\pi$; and the argument of 0 is undefined and returns ``nan``. So the ``arg`` function will never nest greater than 3 levels since at the 4th application, the result must be nan; for a real number, nan is returned on the 3rd application. Examples ======== >>> from sympy import arg, I, sqrt, Dummy >>> from sympy.abc import x >>> arg(2.0) 0 >>> arg(I) pi/2 >>> arg(sqrt(2) + I*sqrt(2)) pi/4 >>> arg(sqrt(3)/2 + I/2) pi/6 >>> arg(4 + 3*I) atan(3/4) >>> arg(0.8 + 0.6*I) 0.643501108793284 >>> arg(arg(arg(arg(x)))) nan >>> real = Dummy(real=True) >>> arg(arg(arg(real))) nan Parameters ========== arg : Expr Real or complex expression. Returns ======= value : Expr Returns arc tangent of arg measured in radians. """ is_extended_real = True is_real = True is_finite = True _singularities = True # non-holomorphic @classmethod def eval(cls, arg): a = arg for i in range(3): if isinstance(a, cls): a = a.args[0] else: if i == 2 and a.is_extended_real: return S.NaN break else: return S.NaN from sympy.functions.elementary.exponential import exp_polar if isinstance(arg, exp_polar): return periodic_argument(arg, oo) if not arg.is_Atom: c, arg_ = factor_terms(arg).as_coeff_Mul() if arg_.is_Mul: arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else sign(a) for a in arg_.args]) arg_ = sign(c)*arg_ else: arg_ = arg if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)): return from sympy.functions.elementary.trigonometric import atan2 x, y = arg_.as_real_imag() rv = atan2(y, x) if rv.is_number: return rv if arg_ != arg: return cls(arg_, evaluate=False) def _eval_derivative(self, t): x, y = self.args[0].as_real_imag() return (x * Derivative(y, t, evaluate=True) - y * Derivative(x, t, evaluate=True)) / (x**2 + y**2) def _eval_rewrite_as_atan2(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import atan2 x, y = self.args[0].as_real_imag() return atan2(y, x) class conjugate(Function): """ Returns the *complex conjugate* [1]_ of an argument. In mathematics, the complex conjugate of a complex number is given by changing the sign of the imaginary part. Thus, the conjugate of the complex number :math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib` Examples ======== >>> from sympy import conjugate, I >>> conjugate(2) 2 >>> conjugate(I) -I >>> conjugate(3 + 2*I) 3 - 2*I >>> conjugate(5 - I) 5 + I Parameters ========== arg : Expr Real or complex expression. Returns ======= arg : Expr Complex conjugate of arg as real, imaginary or mixed expression. See Also ======== sign, Abs References ========== .. [1] https://en.wikipedia.org/wiki/Complex_conjugation """ _singularities = True # non-holomorphic @classmethod def eval(cls, arg): obj = arg._eval_conjugate() if obj is not None: return obj def inverse(self): return conjugate def _eval_Abs(self): return Abs(self.args[0], evaluate=True) def _eval_adjoint(self): return transpose(self.args[0]) def _eval_conjugate(self): return self.args[0] def _eval_derivative(self, x): if x.is_real: return conjugate(Derivative(self.args[0], x, evaluate=True)) elif x.is_imaginary: return -conjugate(Derivative(self.args[0], x, evaluate=True)) def _eval_transpose(self): return adjoint(self.args[0]) def _eval_is_algebraic(self): return self.args[0].is_algebraic class transpose(Function): """ Linear map transposition. Examples ======== >>> from sympy import transpose, Matrix, MatrixSymbol >>> A = MatrixSymbol('A', 25, 9) >>> transpose(A) A.T >>> B = MatrixSymbol('B', 9, 22) >>> transpose(B) B.T >>> transpose(A*B) B.T*A.T >>> M = Matrix([[4, 5], [2, 1], [90, 12]]) >>> M Matrix([ [ 4, 5], [ 2, 1], [90, 12]]) >>> transpose(M) Matrix([ [4, 2, 90], [5, 1, 12]]) Parameters ========== arg : Matrix Matrix or matrix expression to take the transpose of. Returns ======= value : Matrix Transpose of arg. """ @classmethod def eval(cls, arg): obj = arg._eval_transpose() if obj is not None: return obj def _eval_adjoint(self): return conjugate(self.args[0]) def _eval_conjugate(self): return adjoint(self.args[0]) def _eval_transpose(self): return self.args[0] class adjoint(Function): """ Conjugate transpose or Hermite conjugation. Examples ======== >>> from sympy import adjoint, MatrixSymbol >>> A = MatrixSymbol('A', 10, 5) >>> adjoint(A) Adjoint(A) Parameters ========== arg : Matrix Matrix or matrix expression to take the adjoint of. Returns ======= value : Matrix Represents the conjugate transpose or Hermite conjugation of arg. """ @classmethod def eval(cls, arg): obj = arg._eval_adjoint() if obj is not None: return obj obj = arg._eval_transpose() if obj is not None: return conjugate(obj) def _eval_adjoint(self): return self.args[0] def _eval_conjugate(self): return transpose(self.args[0]) def _eval_transpose(self): return conjugate(self.args[0]) def _latex(self, printer, exp=None, *args): arg = printer._print(self.args[0]) tex = r'%s^{\dagger}' % arg if exp: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if printer._use_unicode: pform = pform**prettyForm('\N{DAGGER}') else: pform = pform**prettyForm('+') return pform ############################################################################### ############### HANDLING OF POLAR NUMBERS ##################################### ############################################################################### class polar_lift(Function): """ Lift argument to the Riemann surface of the logarithm, using the standard branch. Examples ======== >>> from sympy import Symbol, polar_lift, I >>> p = Symbol('p', polar=True) >>> x = Symbol('x') >>> polar_lift(4) 4*exp_polar(0) >>> polar_lift(-4) 4*exp_polar(I*pi) >>> polar_lift(-I) exp_polar(-I*pi/2) >>> polar_lift(I + 2) polar_lift(2 + I) >>> polar_lift(4*x) 4*polar_lift(x) >>> polar_lift(4*p) 4*p Parameters ========== arg : Expr Real or complex expression. See Also ======== sympy.functions.elementary.exponential.exp_polar periodic_argument """ is_polar = True is_comparable = False # Cannot be evalf'd. @classmethod def eval(cls, arg): from sympy.functions.elementary.complexes import arg as argument if arg.is_number: ar = argument(arg) # In general we want to affirm that something is known, # e.g. `not ar.has(argument) and not ar.has(atan)` # but for now we will just be more restrictive and # see that it has evaluated to one of the known values. if ar in (0, pi/2, -pi/2, pi): from sympy.functions.elementary.exponential import exp_polar return exp_polar(I*ar)*abs(arg) if arg.is_Mul: args = arg.args else: args = [arg] included = [] excluded = [] positive = [] for arg in args: if arg.is_polar: included += [arg] elif arg.is_positive: positive += [arg] else: excluded += [arg] if len(excluded) < len(args): if excluded: return Mul(*(included + positive))*polar_lift(Mul(*excluded)) elif included: return Mul(*(included + positive)) else: from sympy.functions.elementary.exponential import exp_polar return Mul(*positive)*exp_polar(0) def _eval_evalf(self, prec): """ Careful! any evalf of polar numbers is flaky """ return self.args[0]._eval_evalf(prec) def _eval_Abs(self): return Abs(self.args[0], evaluate=True) class periodic_argument(Function): r""" Represent the argument on a quotient of the Riemann surface of the logarithm. That is, given a period $P$, always return a value in $(-P/2, P/2]$, by using $\exp(PI) = 1$. Examples ======== >>> from sympy import exp_polar, periodic_argument >>> from sympy import I, pi >>> periodic_argument(exp_polar(10*I*pi), 2*pi) 0 >>> periodic_argument(exp_polar(5*I*pi), 4*pi) pi >>> from sympy import exp_polar, periodic_argument >>> from sympy import I, pi >>> periodic_argument(exp_polar(5*I*pi), 2*pi) pi >>> periodic_argument(exp_polar(5*I*pi), 3*pi) -pi >>> periodic_argument(exp_polar(5*I*pi), pi) 0 Parameters ========== ar : Expr A polar number. period : Expr The period $P$. See Also ======== sympy.functions.elementary.exponential.exp_polar polar_lift : Lift argument to the Riemann surface of the logarithm principal_branch """ @classmethod def _getunbranched(cls, ar): from sympy.functions.elementary.exponential import exp_polar, log if ar.is_Mul: args = ar.args else: args = [ar] unbranched = 0 for a in args: if not a.is_polar: unbranched += arg(a) elif isinstance(a, exp_polar): unbranched += a.exp.as_real_imag()[1] elif a.is_Pow: re, im = a.exp.as_real_imag() unbranched += re*unbranched_argument( a.base) + im*log(abs(a.base)) elif isinstance(a, polar_lift): unbranched += arg(a.args[0]) else: return None return unbranched @classmethod def eval(cls, ar, period): # Our strategy is to evaluate the argument on the Riemann surface of the # logarithm, and then reduce. # NOTE evidently this means it is a rather bad idea to use this with # period != 2*pi and non-polar numbers. if not period.is_extended_positive: return None if period == oo and isinstance(ar, principal_branch): return periodic_argument(*ar.args) if isinstance(ar, polar_lift) and period >= 2*pi: return periodic_argument(ar.args[0], period) if ar.is_Mul: newargs = [x for x in ar.args if not x.is_positive] if len(newargs) != len(ar.args): return periodic_argument(Mul(*newargs), period) unbranched = cls._getunbranched(ar) if unbranched is None: return None from sympy.functions.elementary.trigonometric import atan, atan2 if unbranched.has(periodic_argument, atan2, atan): return None if period == oo: return unbranched if period != oo: from sympy.functions.elementary.integers import ceiling n = ceiling(unbranched/period - S.Half)*period if not n.has(ceiling): return unbranched - n def _eval_evalf(self, prec): z, period = self.args if period == oo: unbranched = periodic_argument._getunbranched(z) if unbranched is None: return self return unbranched._eval_evalf(prec) ub = periodic_argument(z, oo)._eval_evalf(prec) from sympy.functions.elementary.integers import ceiling return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec) def unbranched_argument(arg): ''' Returns periodic argument of arg with period as infinity. Examples ======== >>> from sympy import exp_polar, unbranched_argument >>> from sympy import I, pi >>> unbranched_argument(exp_polar(15*I*pi)) 15*pi >>> unbranched_argument(exp_polar(7*I*pi)) 7*pi See also ======== periodic_argument ''' return periodic_argument(arg, oo) class principal_branch(Function): """ Represent a polar number reduced to its principal branch on a quotient of the Riemann surface of the logarithm. Explanation =========== This is a function of two arguments. The first argument is a polar number `z`, and the second one a positive real number or infinity, `p`. The result is ``z mod exp_polar(I*p)``. Examples ======== >>> from sympy import exp_polar, principal_branch, oo, I, pi >>> from sympy.abc import z >>> principal_branch(z, oo) z >>> principal_branch(exp_polar(2*pi*I)*3, 2*pi) 3*exp_polar(0) >>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi) 3*principal_branch(z, 2*pi) Parameters ========== x : Expr A polar number. period : Expr Positive real number or infinity. See Also ======== sympy.functions.elementary.exponential.exp_polar polar_lift : Lift argument to the Riemann surface of the logarithm periodic_argument """ is_polar = True is_comparable = False # cannot always be evalf'd @classmethod def eval(self, x, period): from sympy.functions.elementary.exponential import exp_polar if isinstance(x, polar_lift): return principal_branch(x.args[0], period) if period == oo: return x ub = periodic_argument(x, oo) barg = periodic_argument(x, period) if ub != barg and not ub.has(periodic_argument) \ and not barg.has(periodic_argument): pl = polar_lift(x) def mr(expr): if not isinstance(expr, Symbol): return polar_lift(expr) return expr pl = pl.replace(polar_lift, mr) # Recompute unbranched argument ub = periodic_argument(pl, oo) if not pl.has(polar_lift): if ub != barg: res = exp_polar(I*(barg - ub))*pl else: res = pl if not res.is_polar and not res.has(exp_polar): res *= exp_polar(0) return res if not x.free_symbols: c, m = x, () else: c, m = x.as_coeff_mul(*x.free_symbols) others = [] for y in m: if y.is_positive: c *= y else: others += [y] m = tuple(others) arg = periodic_argument(c, period) if arg.has(periodic_argument): return None if arg.is_number and (unbranched_argument(c) != arg or (arg == 0 and m != () and c != 1)): if arg == 0: return abs(c)*principal_branch(Mul(*m), period) return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c) if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \ and m == (): return exp_polar(arg*I)*abs(c) def _eval_evalf(self, prec): z, period = self.args p = periodic_argument(z, period)._eval_evalf(prec) if abs(p) > pi or p == -pi: return self # Cannot evalf for this argument. from sympy.functions.elementary.exponential import exp return (abs(z)*exp(I*p))._eval_evalf(prec) def _polarify(eq, lift, pause=False): from sympy.integrals.integrals import Integral if eq.is_polar: return eq if eq.is_number and not pause: return polar_lift(eq) if isinstance(eq, Symbol) and not pause and lift: return polar_lift(eq) elif eq.is_Atom: return eq elif eq.is_Add: r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args]) if lift: return polar_lift(r) return r elif eq.is_Pow and eq.base == S.Exp1: return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False)) elif eq.is_Function: return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args]) elif isinstance(eq, Integral): # Don't lift the integration variable func = _polarify(eq.function, lift, pause=pause) limits = [] for limit in eq.args[1:]: var = _polarify(limit[0], lift=False, pause=pause) rest = _polarify(limit[1:], lift=lift, pause=pause) limits.append((var,) + rest) return Integral(*((func,) + tuple(limits))) else: return eq.func(*[_polarify(arg, lift, pause=pause) if isinstance(arg, Expr) else arg for arg in eq.args]) def polarify(eq, subs=True, lift=False): """ Turn all numbers in eq into their polar equivalents (under the standard choice of argument). Note that no attempt is made to guess a formal convention of adding polar numbers, expressions like $1 + x$ will generally not be altered. Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``. If ``subs`` is ``True``, all symbols which are not already polar will be substituted for polar dummies; in this case the function behaves much like :func:`~.posify`. If ``lift`` is ``True``, both addition statements and non-polar symbols are changed to their ``polar_lift()``ed versions. Note that ``lift=True`` implies ``subs=False``. Examples ======== >>> from sympy import polarify, sin, I >>> from sympy.abc import x, y >>> expr = (-x)**y >>> expr.expand() (-x)**y >>> polarify(expr) ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y}) >>> polarify(expr)[0].expand() _x**_y*exp_polar(_y*I*pi) >>> polarify(x, lift=True) polar_lift(x) >>> polarify(x*(1+y), lift=True) polar_lift(x)*polar_lift(y + 1) Adds are treated carefully: >>> polarify(1 + sin((1 + I)*x)) (sin(_x*polar_lift(1 + I)) + 1, {_x: x}) """ if lift: subs = False eq = _polarify(sympify(eq), lift) if not subs: return eq reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols} eq = eq.subs(reps) return eq, {r: s for s, r in reps.items()} def _unpolarify(eq, exponents_only, pause=False): if not isinstance(eq, Basic) or eq.is_Atom: return eq if not pause: from sympy.functions.elementary.exponential import exp, exp_polar if isinstance(eq, exp_polar): return exp(_unpolarify(eq.exp, exponents_only)) if isinstance(eq, principal_branch) and eq.args[1] == 2*pi: return _unpolarify(eq.args[0], exponents_only) if ( eq.is_Add or eq.is_Mul or eq.is_Boolean or eq.is_Relational and ( eq.rel_op in ('==', '!=') and 0 in eq.args or eq.rel_op not in ('==', '!=')) ): return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args]) if isinstance(eq, polar_lift): return _unpolarify(eq.args[0], exponents_only) if eq.is_Pow: expo = _unpolarify(eq.exp, exponents_only) base = _unpolarify(eq.base, exponents_only, not (expo.is_integer and not pause)) return base**expo if eq.is_Function and getattr(eq.func, 'unbranched', False): return eq.func(*[_unpolarify(x, exponents_only, exponents_only) for x in eq.args]) return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args]) def unpolarify(eq, subs=None, exponents_only=False): """ If `p` denotes the projection from the Riemann surface of the logarithm to the complex line, return a simplified version `eq'` of `eq` such that `p(eq') = p(eq)`. Also apply the substitution subs in the end. (This is a convenience, since ``unpolarify``, in a certain sense, undoes :func:`polarify`.) Examples ======== >>> from sympy import unpolarify, polar_lift, sin, I >>> unpolarify(polar_lift(I + 2)) 2 + I >>> unpolarify(sin(polar_lift(I + 7))) sin(7 + I) """ if isinstance(eq, bool): return eq eq = sympify(eq) if subs is not None: return unpolarify(eq.subs(subs)) changed = True pause = False if exponents_only: pause = True while changed: changed = False res = _unpolarify(eq, exponents_only, pause) if res != eq: changed = True eq = res if isinstance(res, bool): return res # Finally, replacing Exp(0) by 1 is always correct. # So is polar_lift(0) -> 0. from sympy.functions.elementary.exponential import exp_polar return res.subs({exp_polar(0): 1, polar_lift(0): 0})
6c1d3da38577202151cb396d07aa0acfe49e7397e638529952b816ae0f4684b5
"""Hypergeometric and Meijer G-functions""" from functools import reduce from sympy.core import S, I, pi, oo, zoo, ilcm, Mod from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.function import Function, Derivative, ArgumentIndexError from sympy.core.containers import Tuple from sympy.core.mul import Mul from sympy.core.relational import Ne from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan, sinh, cosh, asinh, acosh, atanh, acoth) from sympy.functions import factorial, RisingFactorial from sympy.functions.elementary.complexes import Abs, re, unpolarify from sympy.functions.elementary.exponential import exp_polar from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.piecewise import Piecewise from sympy.logic.boolalg import (And, Or) class TupleArg(Tuple): def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args]) # TODO should __new__ accept **options? # TODO should constructors should check if parameters are sensible? def _prep_tuple(v): """ Turn an iterable argument *v* into a tuple and unpolarify, since both hypergeometric and meijer g-functions are unbranched in their parameters. Examples ======== >>> from sympy.functions.special.hyper import _prep_tuple >>> _prep_tuple([1, 2, 3]) (1, 2, 3) >>> _prep_tuple((4, 5)) (4, 5) >>> _prep_tuple((7, 8, 9)) (7, 8, 9) """ return TupleArg(*[unpolarify(x) for x in v]) class TupleParametersBase(Function): """ Base class that takes care of differentiation, when some of the arguments are actually tuples. """ # This is not deduced automatically since there are Tuples as arguments. is_commutative = True def _eval_derivative(self, s): try: res = 0 if self.args[0].has(s) or self.args[1].has(s): for i, p in enumerate(self._diffargs): m = self._diffargs[i].diff(s) if m != 0: res += self.fdiff((1, i))*m return res + self.fdiff(3)*self.args[2].diff(s) except (ArgumentIndexError, NotImplementedError): return Derivative(self, s) class hyper(TupleParametersBase): r""" The generalized hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain. Explanation =========== The hypergeometric function depends on two vectors of parameters, called the numerator parameters $a_p$, and the denominator parameters $b_q$. It also has an argument $z$. The series definition is .. math :: {}_pF_q\left(\begin{matrix} a_1, \cdots, a_p \\ b_1, \cdots, b_q \end{matrix} \middle| z \right) = \sum_{n=0}^\infty \frac{(a_1)_n \cdots (a_p)_n}{(b_1)_n \cdots (b_q)_n} \frac{z^n}{n!}, where $(a)_n = (a)(a+1)\cdots(a+n-1)$ denotes the rising factorial. If one of the $b_q$ is a non-positive integer then the series is undefined unless one of the $a_p$ is a larger (i.e., smaller in magnitude) non-positive integer. If none of the $b_q$ is a non-positive integer and one of the $a_p$ is a non-positive integer, then the series reduces to a polynomial. To simplify the following discussion, we assume that none of the $a_p$ or $b_q$ is a non-positive integer. For more details, see the references. The series converges for all $z$ if $p \le q$, and thus defines an entire single-valued function in this case. If $p = q+1$ the series converges for $|z| < 1$, and can be continued analytically into a half-plane. If $p > q+1$ the series is divergent for all $z$. Please note the hypergeometric function constructor currently does *not* check if the parameters actually yield a well-defined function. Examples ======== The parameters $a_p$ and $b_q$ can be passed as arbitrary iterables, for example: >>> from sympy import hyper >>> from sympy.abc import x, n, a >>> hyper((1, 2, 3), [3, 4], x) hyper((1, 2, 3), (3, 4), x) There is also pretty printing (it looks better using Unicode): >>> from sympy import pprint >>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False) _ |_ /1, 2, 3 | \ | | | x| 3 2 \ 3, 4 | / The parameters must always be iterables, even if they are vectors of length one or zero: >>> hyper((1, ), [], x) hyper((1,), (), x) But of course they may be variables (but if they depend on $x$ then you should not expect much implemented functionality): >>> hyper((n, a), (n**2,), x) hyper((n, a), (n**2,), x) The hypergeometric function generalizes many named special functions. The function ``hyperexpand()`` tries to express a hypergeometric function using named special functions. For example: >>> from sympy import hyperexpand >>> hyperexpand(hyper([], [], x)) exp(x) You can also use ``expand_func()``: >>> from sympy import expand_func >>> expand_func(x*hyper([1, 1], [2], -x)) log(x + 1) More examples: >>> from sympy import S >>> hyperexpand(hyper([], [S(1)/2], -x**2/4)) cos(x) >>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2)) asin(x) We can also sometimes ``hyperexpand()`` parametric functions: >>> from sympy.abc import a >>> hyperexpand(hyper([-a], [], x)) (1 - x)**a See Also ======== sympy.simplify.hyperexpand gamma meijerg References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] https://en.wikipedia.org/wiki/Generalized_hypergeometric_function """ def __new__(cls, ap, bq, z, **kwargs): # TODO should we check convergence conditions? return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z, **kwargs) @classmethod def eval(cls, ap, bq, z): if len(ap) <= len(bq) or (len(ap) == len(bq) + 1 and (Abs(z) <= 1) == True): nz = unpolarify(z) if z != nz: return hyper(ap, bq, nz) def fdiff(self, argindex=3): if argindex != 3: raise ArgumentIndexError(self, argindex) nap = Tuple(*[a + 1 for a in self.ap]) nbq = Tuple(*[b + 1 for b in self.bq]) fac = Mul(*self.ap)/Mul(*self.bq) return fac*hyper(nap, nbq, self.argument) def _eval_expand_func(self, **hints): from sympy.functions.special.gamma_functions import gamma from sympy.simplify.hyperexpand import hyperexpand if len(self.ap) == 2 and len(self.bq) == 1 and self.argument == 1: a, b = self.ap c = self.bq[0] return gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) return hyperexpand(self) def _eval_rewrite_as_Sum(self, ap, bq, z, **kwargs): from sympy.concrete.summations import Sum n = Dummy("n", integer=True) rfap = Tuple(*[RisingFactorial(a, n) for a in ap]) rfbq = Tuple(*[RisingFactorial(b, n) for b in bq]) coeff = Mul(*rfap) / Mul(*rfbq) return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)), self.convergence_statement), (self, True)) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[2] x0 = arg.subs(x, 0) if x0 is S.NaN: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 is S.Zero: return S.One return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order arg = self.args[2] x0 = arg.limit(x, 0) ap = self.args[0] bq = self.args[1] if x0 != 0: return super()._eval_nseries(x, n, logx) terms = [] for i in range(n): num = 1 den = 1 for a in ap: num *= RisingFactorial(a, i) for b in bq: den *= RisingFactorial(b, i) terms.append(((num/den) * (arg**i)) / factorial(i)) return (Add(*terms) + Order(x**n,x)) @property def argument(self): """ Argument of the hypergeometric function. """ return self.args[2] @property def ap(self): """ Numerator parameters of the hypergeometric function. """ return Tuple(*self.args[0]) @property def bq(self): """ Denominator parameters of the hypergeometric function. """ return Tuple(*self.args[1]) @property def _diffargs(self): return self.ap + self.bq @property def eta(self): """ A quantity related to the convergence of the series. """ return sum(self.ap) - sum(self.bq) @property def radius_of_convergence(self): """ Compute the radius of convergence of the defining series. Explanation =========== Note that even if this is not ``oo``, the function may still be evaluated outside of the radius of convergence by analytic continuation. But if this is zero, then the function is not actually defined anywhere else. Examples ======== >>> from sympy import hyper >>> from sympy.abc import z >>> hyper((1, 2), [3], z).radius_of_convergence 1 >>> hyper((1, 2, 3), [4], z).radius_of_convergence 0 >>> hyper((1, 2), (3, 4), z).radius_of_convergence oo """ if any(a.is_integer and (a <= 0) == True for a in self.ap + self.bq): aints = [a for a in self.ap if a.is_Integer and (a <= 0) == True] bints = [a for a in self.bq if a.is_Integer and (a <= 0) == True] if len(aints) < len(bints): return S.Zero popped = False for b in bints: cancelled = False while aints: a = aints.pop() if a >= b: cancelled = True break popped = True if not cancelled: return S.Zero if aints or popped: # There are still non-positive numerator parameters. # This is a polynomial. return oo if len(self.ap) == len(self.bq) + 1: return S.One elif len(self.ap) <= len(self.bq): return oo else: return S.Zero @property def convergence_statement(self): """ Return a condition on z under which the series converges. """ R = self.radius_of_convergence if R == 0: return False if R == oo: return True # The special functions and their approximations, page 44 e = self.eta z = self.argument c1 = And(re(e) < 0, abs(z) <= 1) c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1)) c3 = And(re(e) >= 1, abs(z) < 1) return Or(c1, c2, c3) def _eval_simplify(self, **kwargs): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) class meijerg(TupleParametersBase): r""" The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalizes the hypergeometric functions. Explanation =========== The Meijer G-function depends on four sets of parameters. There are "*numerator parameters*" $a_1, \ldots, a_n$ and $a_{n+1}, \ldots, a_p$, and there are "*denominator parameters*" $b_1, \ldots, b_m$ and $b_{m+1}, \ldots, b_q$. Confusingly, it is traditionally denoted as follows (note the position of $m$, $n$, $p$, $q$, and how they relate to the lengths of the four parameter vectors): .. math :: G_{p,q}^{m,n} \left(\begin{matrix}a_1, \cdots, a_n & a_{n+1}, \cdots, a_p \\ b_1, \cdots, b_m & b_{m+1}, \cdots, b_q \end{matrix} \middle| z \right). However, in SymPy the four parameter vectors are always available separately (see examples), so that there is no need to keep track of the decorating sub- and super-scripts on the G symbol. The G function is defined as the following integral: .. math :: \frac{1}{2 \pi i} \int_L \frac{\prod_{j=1}^m \Gamma(b_j - s) \prod_{j=1}^n \Gamma(1 - a_j + s)}{\prod_{j=m+1}^q \Gamma(1- b_j +s) \prod_{j=n+1}^p \Gamma(a_j - s)} z^s \mathrm{d}s, where $\Gamma(z)$ is the gamma function. There are three possible contours which we will not describe in detail here (see the references). If the integral converges along more than one of them, the definitions agree. The contours all separate the poles of $\Gamma(1-a_j+s)$ from the poles of $\Gamma(b_k-s)$, so in particular the G function is undefined if $a_j - b_k \in \mathbb{Z}_{>0}$ for some $j \le n$ and $k \le m$. The conditions under which one of the contours yields a convergent integral are complicated and we do not state them here, see the references. Please note currently the Meijer G-function constructor does *not* check any convergence conditions. Examples ======== You can pass the parameters either as four separate vectors: >>> from sympy import meijerg, Tuple, pprint >>> from sympy.abc import x, a >>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False) __1, 2 /1, 2 a, 4 | \ /__ | | x| \_|4, 1 \ 5 | / Or as two nested vectors: >>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False) __1, 2 /1, 2 3, 4 | \ /__ | | x| \_|4, 1 \ 5 | / As with the hypergeometric function, the parameters may be passed as arbitrary iterables. Vectors of length zero and one also have to be passed as iterables. The parameters need not be constants, but if they depend on the argument then not much implemented functionality should be expected. All the subvectors of parameters are available: >>> from sympy import pprint >>> g = meijerg([1], [2], [3], [4], x) >>> pprint(g, use_unicode=False) __1, 1 /1 2 | \ /__ | | x| \_|2, 2 \3 4 | / >>> g.an (1,) >>> g.ap (1, 2) >>> g.aother (2,) >>> g.bm (3,) >>> g.bq (3, 4) >>> g.bother (4,) The Meijer G-function generalizes the hypergeometric functions. In some cases it can be expressed in terms of hypergeometric functions, using Slater's theorem. For example: >>> from sympy import hyperexpand >>> from sympy.abc import a, b, c >>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True) x**c*gamma(-a + c + 1)*hyper((-a + c + 1,), (-b + c + 1,), -x)/gamma(-b + c + 1) Thus the Meijer G-function also subsumes many named functions as special cases. You can use ``expand_func()`` or ``hyperexpand()`` to (try to) rewrite a Meijer G-function in terms of named special functions. For example: >>> from sympy import expand_func, S >>> expand_func(meijerg([[],[]], [[0],[]], -x)) exp(x) >>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2)) sin(x)/sqrt(pi) See Also ======== hyper sympy.simplify.hyperexpand References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] https://en.wikipedia.org/wiki/Meijer_G-function """ def __new__(cls, *args, **kwargs): if len(args) == 5: args = [(args[0], args[1]), (args[2], args[3]), args[4]] if len(args) != 3: raise TypeError("args must be either as, as', bs, bs', z or " "as, bs, z") def tr(p): if len(p) != 2: raise TypeError("wrong argument") return TupleArg(_prep_tuple(p[0]), _prep_tuple(p[1])) arg0, arg1 = tr(args[0]), tr(args[1]) if Tuple(arg0, arg1).has(oo, zoo, -oo): raise ValueError("G-function parameters must be finite") if any((a - b).is_Integer and a - b > 0 for a in arg0[0] for b in arg1[0]): raise ValueError("no parameter a1, ..., an may differ from " "any b1, ..., bm by a positive integer") # TODO should we check convergence conditions? return Function.__new__(cls, arg0, arg1, args[2], **kwargs) def fdiff(self, argindex=3): if argindex != 3: return self._diff_wrt_parameter(argindex[1]) if len(self.an) >= 1: a = list(self.an) a[0] -= 1 G = meijerg(a, self.aother, self.bm, self.bother, self.argument) return 1/self.argument * ((self.an[0] - 1)*self + G) elif len(self.bm) >= 1: b = list(self.bm) b[0] += 1 G = meijerg(self.an, self.aother, b, self.bother, self.argument) return 1/self.argument * (self.bm[0]*self - G) else: return S.Zero def _diff_wrt_parameter(self, idx): # Differentiation wrt a parameter can only be done in very special # cases. In particular, if we want to differentiate with respect to # `a`, all other gamma factors have to reduce to rational functions. # # Let MT denote mellin transform. Suppose T(-s) is the gamma factor # appearing in the definition of G. Then # # MT(log(z)G(z)) = d/ds T(s) = d/da T(s) + ... # # Thus d/da G(z) = log(z)G(z) - ... # The ... can be evaluated as a G function under the above conditions, # the formula being most easily derived by using # # d Gamma(s + n) Gamma(s + n) / 1 1 1 \ # -- ------------ = ------------ | - + ---- + ... + --------- | # ds Gamma(s) Gamma(s) \ s s + 1 s + n - 1 / # # which follows from the difference equation of the digamma function. # (There is a similar equation for -n instead of +n). # We first figure out how to pair the parameters. an = list(self.an) ap = list(self.aother) bm = list(self.bm) bq = list(self.bother) if idx < len(an): an.pop(idx) else: idx -= len(an) if idx < len(ap): ap.pop(idx) else: idx -= len(ap) if idx < len(bm): bm.pop(idx) else: bq.pop(idx - len(bm)) pairs1 = [] pairs2 = [] for l1, l2, pairs in [(an, bq, pairs1), (ap, bm, pairs2)]: while l1: x = l1.pop() found = None for i, y in enumerate(l2): if not Mod((x - y).simplify(), 1): found = i break if found is None: raise NotImplementedError('Derivative not expressible ' 'as G-function?') y = l2[i] l2.pop(i) pairs.append((x, y)) # Now build the result. res = log(self.argument)*self for a, b in pairs1: sign = 1 n = a - b base = b if n < 0: sign = -1 n = b - a base = a for k in range(n): res -= sign*meijerg(self.an + (base + k + 1,), self.aother, self.bm, self.bother + (base + k + 0,), self.argument) for a, b in pairs2: sign = 1 n = b - a base = a if n < 0: sign = -1 n = a - b base = b for k in range(n): res -= sign*meijerg(self.an, self.aother + (base + k + 1,), self.bm + (base + k + 0,), self.bother, self.argument) return res def get_period(self): """ Return a number $P$ such that $G(x*exp(I*P)) == G(x)$. Examples ======== >>> from sympy import meijerg, pi, S >>> from sympy.abc import z >>> meijerg([1], [], [], [], z).get_period() 2*pi >>> meijerg([pi], [], [], [], z).get_period() oo >>> meijerg([1, 2], [], [], [], z).get_period() oo >>> meijerg([1,1], [2], [1, S(1)/2, S(1)/3], [1], z).get_period() 12*pi """ # This follows from slater's theorem. def compute(l): # first check that no two differ by an integer for i, b in enumerate(l): if not b.is_Rational: return oo for j in range(i + 1, len(l)): if not Mod((b - l[j]).simplify(), 1): return oo return reduce(ilcm, (x.q for x in l), 1) beta = compute(self.bm) alpha = compute(self.an) p, q = len(self.ap), len(self.bq) if p == q: if oo in (alpha, beta): return oo return 2*pi*ilcm(alpha, beta) elif p < q: return 2*pi*beta else: return 2*pi*alpha def _eval_expand_func(self, **hints): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) def _eval_evalf(self, prec): # The default code is insufficient for polar arguments. # mpmath provides an optional argument "r", which evaluates # G(z**(1/r)). I am not sure what its intended use is, but we hijack it # here in the following way: to evaluate at a number z of |argument| # less than (say) n*pi, we put r=1/n, compute z' = root(z, n) # (carefully so as not to loose the branch information), and evaluate # G(z'**(1/r)) = G(z'**n) = G(z). import mpmath znum = self.argument._eval_evalf(prec) if znum.has(exp_polar): znum, branch = znum.as_coeff_mul(exp_polar) if len(branch) != 1: return branch = branch[0].args[0]/I else: branch = S.Zero n = ceiling(abs(branch/S.Pi)) + 1 znum = znum**(S.One/n)*exp(I*branch / n) # Convert all args to mpf or mpc try: [z, r, ap, bq] = [arg._to_mpmath(prec) for arg in [znum, 1/n, self.args[0], self.args[1]]] except ValueError: return with mpmath.workprec(prec): v = mpmath.meijerg(ap, bq, z, r) return Expr._from_mpmath(v, prec) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self).as_leading_term(x, logx=logx, cdir=cdir) def integrand(self, s): """ Get the defining integrand D(s). """ from sympy.functions.special.gamma_functions import gamma return self.argument**s \ * Mul(*(gamma(b - s) for b in self.bm)) \ * Mul(*(gamma(1 - a + s) for a in self.an)) \ / Mul(*(gamma(1 - b + s) for b in self.bother)) \ / Mul(*(gamma(a - s) for a in self.aother)) @property def argument(self): """ Argument of the Meijer G-function. """ return self.args[2] @property def an(self): """ First set of numerator parameters. """ return Tuple(*self.args[0][0]) @property def ap(self): """ Combined numerator parameters. """ return Tuple(*(self.args[0][0] + self.args[0][1])) @property def aother(self): """ Second set of numerator parameters. """ return Tuple(*self.args[0][1]) @property def bm(self): """ First set of denominator parameters. """ return Tuple(*self.args[1][0]) @property def bq(self): """ Combined denominator parameters. """ return Tuple(*(self.args[1][0] + self.args[1][1])) @property def bother(self): """ Second set of denominator parameters. """ return Tuple(*self.args[1][1]) @property def _diffargs(self): return self.ap + self.bq @property def nu(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return sum(self.bq) - sum(self.ap) @property def delta(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return len(self.bm) + len(self.an) - S(len(self.ap) + len(self.bq))/2 @property def is_number(self): """ Returns true if expression has numeric data only. """ return not self.free_symbols class HyperRep(Function): """ A base class for "hyper representation functions". This is used exclusively in ``hyperexpand()``, but fits more logically here. pFq is branched at 1 if p == q+1. For use with slater-expansion, we want define an "analytic continuation" to all polar numbers, which is continuous on circles and on the ray t*exp_polar(I*pi). Moreover, we want a "nice" expression for the various cases. This base class contains the core logic, concrete derived classes only supply the actual functions. """ @classmethod def eval(cls, *args): newargs = tuple(map(unpolarify, args[:-1])) + args[-1:] if args != newargs: return cls(*newargs) @classmethod def _expr_small(cls, x): """ An expression for F(x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_small_minus(cls, x): """ An expression for F(-x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_big(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n)*x), |x| > 1. """ raise NotImplementedError @classmethod def _expr_big_minus(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n + pi*I)*x), |x| > 1. """ raise NotImplementedError def _eval_rewrite_as_nonrep(self, *args, **kwargs): x, n = self.args[-1].extract_branch_factor(allow_half=True) minus = False newargs = self.args[:-1] + (x,) if not n.is_Integer: minus = True n -= S.Half newerargs = newargs + (n,) if minus: small = self._expr_small_minus(*newargs) big = self._expr_big_minus(*newerargs) else: small = self._expr_small(*newargs) big = self._expr_big(*newerargs) if big == small: return small return Piecewise((big, abs(x) > 1), (small, True)) def _eval_rewrite_as_nonrepsmall(self, *args, **kwargs): x, n = self.args[-1].extract_branch_factor(allow_half=True) args = self.args[:-1] + (x,) if not n.is_Integer: return self._expr_small_minus(*args) return self._expr_small(*args) class HyperRep_power1(HyperRep): """ Return a representative for hyper([-a], [], z) == (1 - z)**a. """ @classmethod def _expr_small(cls, a, x): return (1 - x)**a @classmethod def _expr_small_minus(cls, a, x): return (1 + x)**a @classmethod def _expr_big(cls, a, x, n): if a.is_integer: return cls._expr_small(a, x) return (x - 1)**a*exp((2*n - 1)*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): if a.is_integer: return cls._expr_small_minus(a, x) return (1 + x)**a*exp(2*n*pi*I*a) class HyperRep_power2(HyperRep): """ Return a representative for hyper([a, a - 1/2], [2*a], z). """ @classmethod def _expr_small(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a) @classmethod def _expr_small_minus(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a) @classmethod def _expr_big(cls, a, x, n): sgn = -1 if n.is_odd: sgn = 1 n -= 1 return 2**(2*a - 1)*(1 + sgn*I*sqrt(x - 1))**(1 - 2*a) \ *exp(-2*n*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): sgn = 1 if n.is_odd: sgn = -1 return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n) class HyperRep_log1(HyperRep): """ Represent -z*hyper([1, 1], [2], z) == log(1 - z). """ @classmethod def _expr_small(cls, x): return log(1 - x) @classmethod def _expr_small_minus(cls, x): return log(1 + x) @classmethod def _expr_big(cls, x, n): return log(x - 1) + (2*n - 1)*pi*I @classmethod def _expr_big_minus(cls, x, n): return log(1 + x) + 2*n*pi*I class HyperRep_atanh(HyperRep): """ Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, x): return atanh(sqrt(x))/sqrt(x) def _expr_small_minus(cls, x): return atan(sqrt(x))/sqrt(x) def _expr_big(cls, x, n): if n.is_even: return (acoth(sqrt(x)) + I*pi/2)/sqrt(x) else: return (acoth(sqrt(x)) - I*pi/2)/sqrt(x) def _expr_big_minus(cls, x, n): if n.is_even: return atan(sqrt(x))/sqrt(x) else: return (atan(sqrt(x)) - pi)/sqrt(x) class HyperRep_asin1(HyperRep): """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cls, z, n): return S.NegativeOne**n*((S.Half - n)*pi/sqrt(z) + I*acosh(sqrt(z))/sqrt(z)) @classmethod def _expr_big_minus(cls, z, n): return S.NegativeOne**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z)) class HyperRep_asin2(HyperRep): """ Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """ # TODO this can be nicer @classmethod def _expr_small(cls, z): return HyperRep_asin1._expr_small(z) \ /HyperRep_power1._expr_small(S.Half, z) @classmethod def _expr_small_minus(cls, z): return HyperRep_asin1._expr_small_minus(z) \ /HyperRep_power1._expr_small_minus(S.Half, z) @classmethod def _expr_big(cls, z, n): return HyperRep_asin1._expr_big(z, n) \ /HyperRep_power1._expr_big(S.Half, z, n) @classmethod def _expr_big_minus(cls, z, n): return HyperRep_asin1._expr_big_minus(z, n) \ /HyperRep_power1._expr_big_minus(S.Half, z, n) class HyperRep_sqrts1(HyperRep): """ Return a representative for hyper([-a, 1/2 - a], [1/2], z). """ @classmethod def _expr_small(cls, a, z): return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return (1 + z)**a*cos(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return ((sqrt(z) + 1)**(2*a)*exp(2*pi*I*n*a) + (sqrt(z) - 1)**(2*a)*exp(2*pi*I*(n - 1)*a))/2 else: n -= 1 return ((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) + (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))/2 @classmethod def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_sqrts2(HyperRep): """ Return a representative for sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a] == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)""" @classmethod def _expr_small(cls, a, z): return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return sqrt(z)*(1 + z)**a*sin(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n - 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) else: n -= 1 return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \ *sin(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_log2(HyperRep): """ Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """ @classmethod def _expr_small(cls, z): return log(S.Half + sqrt(1 - z)/2) @classmethod def _expr_small_minus(cls, z): return log(S.Half + sqrt(1 + z)/2) @classmethod def _expr_big(cls, z, n): if n.is_even: return (n - S.Half)*pi*I + log(sqrt(z)/2) + I*asin(1/sqrt(z)) else: return (n - S.Half)*pi*I + log(sqrt(z)/2) - I*asin(1/sqrt(z)) def _expr_big_minus(cls, z, n): if n.is_even: return pi*I*n + log(S.Half + sqrt(1 + z)/2) else: return pi*I*n + log(sqrt(1 + z)/2 - S.Half) class HyperRep_cosasin(HyperRep): """ Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """ # Note there are many alternative expressions, e.g. as powers of a sum of # square roots. @classmethod def _expr_small(cls, a, z): return cos(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return cosh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return cosh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class HyperRep_sinasin(HyperRep): """ Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return -1/sqrt(1 - 1/z)*sinh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return -1/sqrt(1 + 1/z)*sinh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class appellf1(Function): r""" This is the Appell hypergeometric function of two variables as: .. math :: F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}} \frac{x^m y^n}{m! n!}. Examples ======== >>> from sympy import appellf1, symbols >>> x, y, a, b1, b2, c = symbols('x y a b1 b2 c') >>> appellf1(2., 1., 6., 4., 5., 6.) 0.0063339426292673 >>> appellf1(12., 12., 6., 4., 0.5, 0.12) 172870711.659936 >>> appellf1(40, 2, 6, 4, 15, 60) appellf1(40, 2, 6, 4, 15, 60) >>> appellf1(20., 12., 10., 3., 0.5, 0.12) 15605338197184.4 >>> appellf1(40, 2, 6, 4, x, y) appellf1(40, 2, 6, 4, x, y) >>> appellf1(a, b1, b2, c, x, y) appellf1(a, b1, b2, c, x, y) References ========== .. [1] https://en.wikipedia.org/wiki/Appell_series .. [2] http://functions.wolfram.com/HypergeometricFunctions/AppellF1/ """ @classmethod def eval(cls, a, b1, b2, c, x, y): if default_sort_key(b1) > default_sort_key(b2): b1, b2 = b2, b1 x, y = y, x return cls(a, b1, b2, c, x, y) elif b1 == b2 and default_sort_key(x) > default_sort_key(y): x, y = y, x return cls(a, b1, b2, c, x, y) if x == 0 and y == 0: return S.One def fdiff(self, argindex=5): a, b1, b2, c, x, y = self.args if argindex == 5: return (a*b1/c)*appellf1(a + 1, b1 + 1, b2, c + 1, x, y) elif argindex == 6: return (a*b2/c)*appellf1(a + 1, b1, b2 + 1, c + 1, x, y) elif argindex in (1, 2, 3, 4): return Derivative(self, self.args[argindex-1]) else: raise ArgumentIndexError(self, argindex)
16532185521a37a6340c1e091f7af2fc544da45c99cf29205ea0ca0370aa7c76
from sympy.core import S, sympify, diff from sympy.core.function import Function, ArgumentIndexError from sympy.core.logic import fuzzy_not from sympy.core.relational import Eq, Ne from sympy.functions.elementary.complexes import im, sign from sympy.functions.elementary.piecewise import Piecewise from sympy.polys.polyerrors import PolynomialError from sympy.polys.polyroots import roots from sympy.utilities.misc import filldedent ############################################################################### ################################ DELTA FUNCTION ############################### ############################################################################### class DiracDelta(Function): r""" The DiracDelta function and its derivatives. Explanation =========== DiracDelta is not an ordinary function. It can be rigorously defined either as a distribution or as a measure. DiracDelta only makes sense in definite integrals, and in particular, integrals of the form ``Integral(f(x)*DiracDelta(x - x0), (x, a, b))``, where it equals ``f(x0)`` if ``a <= x0 <= b`` and ``0`` otherwise. Formally, DiracDelta acts in some ways like a function that is ``0`` everywhere except at ``0``, but in many ways it also does not. It can often be useful to treat DiracDelta in formal ways, building up and manipulating expressions with delta functions (which may eventually be integrated), but care must be taken to not treat it as a real function. SymPy's ``oo`` is similar. It only truly makes sense formally in certain contexts (such as integration limits), but SymPy allows its use everywhere, and it tries to be consistent with operations on it (like ``1/oo``), but it is easy to get into trouble and get wrong results if ``oo`` is treated too much like a number. Similarly, if DiracDelta is treated too much like a function, it is easy to get wrong or nonsensical results. DiracDelta function has the following properties: 1) $\frac{d}{d x} \theta(x) = \delta(x)$ 2) $\int_{-\infty}^\infty \delta(x - a)f(x)\, dx = f(a)$ and $\int_{a- \epsilon}^{a+\epsilon} \delta(x - a)f(x)\, dx = f(a)$ 3) $\delta(x) = 0$ for all $x \neq 0$ 4) $\delta(g(x)) = \sum_i \frac{\delta(x - x_i)}{\|g'(x_i)\|}$ where $x_i$ are the roots of $g$ 5) $\delta(-x) = \delta(x)$ Derivatives of ``k``-th order of DiracDelta have the following properties: 6) $\delta(x, k) = 0$ for all $x \neq 0$ 7) $\delta(-x, k) = -\delta(x, k)$ for odd $k$ 8) $\delta(-x, k) = \delta(x, k)$ for even $k$ Examples ======== >>> from sympy import DiracDelta, diff, pi >>> from sympy.abc import x, y >>> DiracDelta(x) DiracDelta(x) >>> DiracDelta(1) 0 >>> DiracDelta(-1) 0 >>> DiracDelta(pi) 0 >>> DiracDelta(x - 4).subs(x, 4) DiracDelta(0) >>> diff(DiracDelta(x)) DiracDelta(x, 1) >>> diff(DiracDelta(x - 1),x,2) DiracDelta(x - 1, 2) >>> diff(DiracDelta(x**2 - 1),x,2) 2*(2*x**2*DiracDelta(x**2 - 1, 2) + DiracDelta(x**2 - 1, 1)) >>> DiracDelta(3*x).is_simple(x) True >>> DiracDelta(x**2).is_simple(x) False >>> DiracDelta((x**2 - 1)*y).expand(diracdelta=True, wrt=x) DiracDelta(x - 1)/(2*Abs(y)) + DiracDelta(x + 1)/(2*Abs(y)) See Also ======== Heaviside sympy.simplify.simplify.simplify, is_simple sympy.functions.special.tensor_functions.KroneckerDelta References ========== .. [1] http://mathworld.wolfram.com/DeltaFunction.html """ is_real = True def fdiff(self, argindex=1): """ Returns the first derivative of a DiracDelta Function. Explanation =========== The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the user-level function and ``fdiff()`` is an object method. ``fdiff()`` is a convenience method available in the ``Function`` class. It returns the derivative of the function without considering the chain rule. ``diff(function, x)`` calls ``Function._eval_derivative`` which in turn calls ``fdiff()`` internally to compute the derivative of the function. Examples ======== >>> from sympy import DiracDelta, diff >>> from sympy.abc import x >>> DiracDelta(x).fdiff() DiracDelta(x, 1) >>> DiracDelta(x, 1).fdiff() DiracDelta(x, 2) >>> DiracDelta(x**2 - 1).fdiff() DiracDelta(x**2 - 1, 1) >>> diff(DiracDelta(x, 1)).fdiff() DiracDelta(x, 3) Parameters ========== argindex : integer degree of derivative """ if argindex == 1: #I didn't know if there is a better way to handle default arguments k = 0 if len(self.args) > 1: k = self.args[1] return self.func(self.args[0], k + 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg, k=0): """ Returns a simplified form or a value of DiracDelta depending on the argument passed by the DiracDelta object. Explanation =========== The ``eval()`` method is automatically called when the ``DiracDelta`` class is about to be instantiated and it returns either some simplified instance or the unevaluated instance depending on the argument passed. In other words, ``eval()`` method is not needed to be called explicitly, it is being called and evaluated once the object is called. Examples ======== >>> from sympy import DiracDelta, S >>> from sympy.abc import x >>> DiracDelta(x) DiracDelta(x) >>> DiracDelta(-x, 1) -DiracDelta(x, 1) >>> DiracDelta(1) 0 >>> DiracDelta(5, 1) 0 >>> DiracDelta(0) DiracDelta(0) >>> DiracDelta(-1) 0 >>> DiracDelta(S.NaN) nan >>> DiracDelta(x).eval(1) 0 >>> DiracDelta(x - 100).subs(x, 5) 0 >>> DiracDelta(x - 100).subs(x, 100) DiracDelta(0) Parameters ========== k : integer order of derivative arg : argument passed to DiracDelta """ k = sympify(k) if not k.is_Integer or k.is_negative: raise ValueError("Error: the second argument of DiracDelta must be \ a non-negative integer, %s given instead." % (k,)) arg = sympify(arg) if arg is S.NaN: return S.NaN if arg.is_nonzero: return S.Zero if fuzzy_not(im(arg).is_zero): raise ValueError(filldedent(''' Function defined only for Real Values. Complex part: %s found in %s .''' % ( repr(im(arg)), repr(arg)))) c, nc = arg.args_cnc() if c and c[0] is S.NegativeOne: # keep this fast and simple instead of using # could_extract_minus_sign if k.is_odd: return -cls(-arg, k) elif k.is_even: return cls(-arg, k) if k else cls(-arg) def _eval_expand_diracdelta(self, **hints): """ Compute a simplified representation of the function using property number 4. Pass ``wrt`` as a hint to expand the expression with respect to a particular variable. Explanation =========== ``wrt`` is: - a variable with respect to which a DiracDelta expression will get expanded. Examples ======== >>> from sympy import DiracDelta >>> from sympy.abc import x, y >>> DiracDelta(x*y).expand(diracdelta=True, wrt=x) DiracDelta(x)/Abs(y) >>> DiracDelta(x*y).expand(diracdelta=True, wrt=y) DiracDelta(y)/Abs(x) >>> DiracDelta(x**2 + x - 2).expand(diracdelta=True, wrt=x) DiracDelta(x - 1)/3 + DiracDelta(x + 2)/3 See Also ======== is_simple, Diracdelta """ wrt = hints.get('wrt', None) if wrt is None: free = self.free_symbols if len(free) == 1: wrt = free.pop() else: raise TypeError(filldedent(''' When there is more than 1 free symbol or variable in the expression, the 'wrt' keyword is required as a hint to expand when using the DiracDelta hint.''')) if not self.args[0].has(wrt) or (len(self.args) > 1 and self.args[1] != 0 ): return self try: argroots = roots(self.args[0], wrt) result = 0 valid = True darg = abs(diff(self.args[0], wrt)) for r, m in argroots.items(): if r.is_real is not False and m == 1: result += self.func(wrt - r)/darg.subs(wrt, r) else: # don't handle non-real and if m != 1 then # a polynomial will have a zero in the derivative (darg) # at r valid = False break if valid: return result except PolynomialError: pass return self def is_simple(self, x): """ Tells whether the argument(args[0]) of DiracDelta is a linear expression in *x*. Examples ======== >>> from sympy import DiracDelta, cos >>> from sympy.abc import x, y >>> DiracDelta(x*y).is_simple(x) True >>> DiracDelta(x*y).is_simple(y) True >>> DiracDelta(x**2 + x - 2).is_simple(x) False >>> DiracDelta(cos(x)).is_simple(x) False Parameters ========== x : can be a symbol See Also ======== sympy.simplify.simplify.simplify, DiracDelta """ p = self.args[0].as_poly(x) if p: return p.degree() == 1 return False def _eval_rewrite_as_Piecewise(self, *args, **kwargs): """ Represents DiracDelta in a piecewise form. Examples ======== >>> from sympy import DiracDelta, Piecewise, Symbol >>> x = Symbol('x') >>> DiracDelta(x).rewrite(Piecewise) Piecewise((DiracDelta(0), Eq(x, 0)), (0, True)) >>> DiracDelta(x - 5).rewrite(Piecewise) Piecewise((DiracDelta(0), Eq(x, 5)), (0, True)) >>> DiracDelta(x**2 - 5).rewrite(Piecewise) Piecewise((DiracDelta(0), Eq(x**2, 5)), (0, True)) >>> DiracDelta(x - 5, 4).rewrite(Piecewise) DiracDelta(x - 5, 4) """ if len(args) == 1: return Piecewise((DiracDelta(0), Eq(args[0], 0)), (0, True)) def _eval_rewrite_as_SingularityFunction(self, *args, **kwargs): """ Returns the DiracDelta expression written in the form of Singularity Functions. """ from sympy.solvers import solve from sympy.functions.special.singularity_functions import SingularityFunction if self == DiracDelta(0): return SingularityFunction(0, 0, -1) if self == DiracDelta(0, 1): return SingularityFunction(0, 0, -2) free = self.free_symbols if len(free) == 1: x = (free.pop()) if len(args) == 1: return SingularityFunction(x, solve(args[0], x)[0], -1) return SingularityFunction(x, solve(args[0], x)[0], -args[1] - 1) else: # I don't know how to handle the case for DiracDelta expressions # having arguments with more than one variable. raise TypeError(filldedent(''' rewrite(SingularityFunction) does not support arguments with more that one variable.''')) ############################################################################### ############################## HEAVISIDE FUNCTION ############################# ############################################################################### class Heaviside(Function): r""" Heaviside step function. Explanation =========== The Heaviside step function has the following properties: 1) $\frac{d}{d x} \theta(x) = \delta(x)$ 2) $\theta(x) = \begin{cases} 0 & \text{for}\: x < 0 \\ \frac{1}{2} & \text{for}\: x = 0 \\1 & \text{for}\: x > 0 \end{cases}$ 3) $\frac{d}{d x} \max(x, 0) = \theta(x)$ Heaviside(x) is printed as $\theta(x)$ with the SymPy LaTeX printer. The value at 0 is set differently in different fields. SymPy uses 1/2, which is a convention from electronics and signal processing, and is consistent with solving improper integrals by Fourier transform and convolution. To specify a different value of Heaviside at ``x=0``, a second argument can be given. Using ``Heaviside(x, nan)`` gives an expression that will evaluate to nan for x=0. .. versionchanged:: 1.9 ``Heaviside(0)`` now returns 1/2 (before: undefined) Examples ======== >>> from sympy import Heaviside, nan >>> from sympy.abc import x >>> Heaviside(9) 1 >>> Heaviside(-9) 0 >>> Heaviside(0) 1/2 >>> Heaviside(0, nan) nan >>> (Heaviside(x) + 1).replace(Heaviside(x), Heaviside(x, 1)) Heaviside(x, 1) + 1 See Also ======== DiracDelta References ========== .. [1] http://mathworld.wolfram.com/HeavisideStepFunction.html .. [2] http://dlmf.nist.gov/1.16#iv """ is_real = True def fdiff(self, argindex=1): """ Returns the first derivative of a Heaviside Function. Examples ======== >>> from sympy import Heaviside, diff >>> from sympy.abc import x >>> Heaviside(x).fdiff() DiracDelta(x) >>> Heaviside(x**2 - 1).fdiff() DiracDelta(x**2 - 1) >>> diff(Heaviside(x)).fdiff() DiracDelta(x, 1) Parameters ========== argindex : integer order of derivative """ if argindex == 1: return DiracDelta(self.args[0]) else: raise ArgumentIndexError(self, argindex) def __new__(cls, arg, H0=S.Half, **options): if isinstance(H0, Heaviside) and len(H0.args) == 1: H0 = S.Half return super(cls, cls).__new__(cls, arg, H0, **options) @property def pargs(self): """Args without default S.Half""" args = self.args if args[1] is S.Half: args = args[:1] return args @classmethod def eval(cls, arg, H0=S.Half): """ Returns a simplified form or a value of Heaviside depending on the argument passed by the Heaviside object. Explanation =========== The ``eval()`` method is automatically called when the ``Heaviside`` class is about to be instantiated and it returns either some simplified instance or the unevaluated instance depending on the argument passed. In other words, ``eval()`` method is not needed to be called explicitly, it is being called and evaluated once the object is called. Examples ======== >>> from sympy import Heaviside, S >>> from sympy.abc import x >>> Heaviside(x) Heaviside(x) >>> Heaviside(19) 1 >>> Heaviside(0) 1/2 >>> Heaviside(0, 1) 1 >>> Heaviside(-5) 0 >>> Heaviside(S.NaN) nan >>> Heaviside(x).eval(42) 1 >>> Heaviside(x - 100).subs(x, 5) 0 >>> Heaviside(x - 100).subs(x, 105) 1 Parameters ========== arg : argument passed by Heaviside object H0 : value of Heaviside(0) """ H0 = sympify(H0) arg = sympify(arg) if arg.is_extended_negative: return S.Zero elif arg.is_extended_positive: return S.One elif arg.is_zero: return H0 elif arg is S.NaN: return S.NaN elif fuzzy_not(im(arg).is_zero): raise ValueError("Function defined only for Real Values. Complex part: %s found in %s ." % (repr(im(arg)), repr(arg)) ) def _eval_rewrite_as_Piecewise(self, arg, H0=None, **kwargs): """ Represents Heaviside in a Piecewise form. Examples ======== >>> from sympy import Heaviside, Piecewise, Symbol, nan >>> x = Symbol('x') >>> Heaviside(x).rewrite(Piecewise) Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0)) >>> Heaviside(x,nan).rewrite(Piecewise) Piecewise((0, x < 0), (nan, Eq(x, 0)), (1, x > 0)) >>> Heaviside(x - 5).rewrite(Piecewise) Piecewise((0, x < 5), (1/2, Eq(x, 5)), (1, x > 5)) >>> Heaviside(x**2 - 1).rewrite(Piecewise) Piecewise((0, x**2 < 1), (1/2, Eq(x**2, 1)), (1, x**2 > 1)) """ if H0 == 0: return Piecewise((0, arg <= 0), (1, arg > 0)) if H0 == 1: return Piecewise((0, arg < 0), (1, arg >= 0)) return Piecewise((0, arg < 0), (H0, Eq(arg, 0)), (1, arg > 0)) def _eval_rewrite_as_sign(self, arg, H0=S.Half, **kwargs): """ Represents the Heaviside function in the form of sign function. Explanation =========== The value of Heaviside(0) must be 1/2 for rewritting as sign to be strictly equivalent. For easier usage, we also allow this rewriting when Heaviside(0) is undefined. Examples ======== >>> from sympy import Heaviside, Symbol, sign, nan >>> x = Symbol('x', real=True) >>> y = Symbol('y') >>> Heaviside(x).rewrite(sign) sign(x)/2 + 1/2 >>> Heaviside(x, 0).rewrite(sign) Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (0, True)) >>> Heaviside(x, nan).rewrite(sign) Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (nan, True)) >>> Heaviside(x - 2).rewrite(sign) sign(x - 2)/2 + 1/2 >>> Heaviside(x**2 - 2*x + 1).rewrite(sign) sign(x**2 - 2*x + 1)/2 + 1/2 >>> Heaviside(y).rewrite(sign) Heaviside(y) >>> Heaviside(y**2 - 2*y + 1).rewrite(sign) Heaviside(y**2 - 2*y + 1) See Also ======== sign """ if arg.is_extended_real: pw1 = Piecewise( ((sign(arg) + 1)/2, Ne(arg, 0)), (Heaviside(0, H0=H0), True)) pw2 = Piecewise( ((sign(arg) + 1)/2, Eq(Heaviside(0, H0=H0), S.Half)), (pw1, True)) return pw2 def _eval_rewrite_as_SingularityFunction(self, args, H0=S.Half, **kwargs): """ Returns the Heaviside expression written in the form of Singularity Functions. """ from sympy.solvers import solve from sympy.functions.special.singularity_functions import SingularityFunction if self == Heaviside(0): return SingularityFunction(0, 0, 0) free = self.free_symbols if len(free) == 1: x = (free.pop()) return SingularityFunction(x, solve(args, x)[0], 0) # TODO # ((x - 5)**3*Heaviside(x - 5)).rewrite(SingularityFunction) should output # SingularityFunction(x, 5, 0) instead of (x - 5)**3*SingularityFunction(x, 5, 0) else: # I don't know how to handle the case for Heaviside expressions # having arguments with more than one variable. raise TypeError(filldedent(''' rewrite(SingularityFunction) does not support arguments with more that one variable.'''))
2223194f38f59a95aeafb394008b0aeca1d8a6bc0b45fdbc5a3b45a80e770e26
from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError from sympy.core.numbers import I, pi from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions import assoc_legendre from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import Abs, conjugate from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin, cos, cot _x = Dummy("x") class Ynm(Function): r""" Spherical harmonics defined as .. math:: Y_n^m(\theta, \varphi) := \sqrt{\frac{(2n+1)(n-m)!}{4\pi(n+m)!}} \exp(i m \varphi) \mathrm{P}_n^m\left(\cos(\theta)\right) Explanation =========== ``Ynm()`` gives the spherical harmonic function of order $n$ and $m$ in $\theta$ and $\varphi$, $Y_n^m(\theta, \varphi)$. The four parameters are as follows: $n \geq 0$ an integer and $m$ an integer such that $-n \leq m \leq n$ holds. The two angles are real-valued with $\theta \in [0, \pi]$ and $\varphi \in [0, 2\pi]$. Examples ======== >>> from sympy import Ynm, Symbol, simplify >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> Ynm(n, m, theta, phi) Ynm(n, m, theta, phi) Several symmetries are known, for the order: >>> Ynm(n, -m, theta, phi) (-1)**m*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) As well as for the angles: >>> Ynm(n, m, -theta, phi) Ynm(n, m, theta, phi) >>> Ynm(n, m, theta, -phi) exp(-2*I*m*phi)*Ynm(n, m, theta, phi) For specific integers $n$ and $m$ we can evaluate the harmonics to more useful expressions: >>> simplify(Ynm(0, 0, theta, phi).expand(func=True)) 1/(2*sqrt(pi)) >>> simplify(Ynm(1, -1, theta, phi).expand(func=True)) sqrt(6)*exp(-I*phi)*sin(theta)/(4*sqrt(pi)) >>> simplify(Ynm(1, 0, theta, phi).expand(func=True)) sqrt(3)*cos(theta)/(2*sqrt(pi)) >>> simplify(Ynm(1, 1, theta, phi).expand(func=True)) -sqrt(6)*exp(I*phi)*sin(theta)/(4*sqrt(pi)) >>> simplify(Ynm(2, -2, theta, phi).expand(func=True)) sqrt(30)*exp(-2*I*phi)*sin(theta)**2/(8*sqrt(pi)) >>> simplify(Ynm(2, -1, theta, phi).expand(func=True)) sqrt(30)*exp(-I*phi)*sin(2*theta)/(8*sqrt(pi)) >>> simplify(Ynm(2, 0, theta, phi).expand(func=True)) sqrt(5)*(3*cos(theta)**2 - 1)/(4*sqrt(pi)) >>> simplify(Ynm(2, 1, theta, phi).expand(func=True)) -sqrt(30)*exp(I*phi)*sin(2*theta)/(8*sqrt(pi)) >>> simplify(Ynm(2, 2, theta, phi).expand(func=True)) sqrt(30)*exp(2*I*phi)*sin(theta)**2/(8*sqrt(pi)) We can differentiate the functions with respect to both angles: >>> from sympy import Ynm, Symbol, diff >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> diff(Ynm(n, m, theta, phi), theta) m*cot(theta)*Ynm(n, m, theta, phi) + sqrt((-m + n)*(m + n + 1))*exp(-I*phi)*Ynm(n, m + 1, theta, phi) >>> diff(Ynm(n, m, theta, phi), phi) I*m*Ynm(n, m, theta, phi) Further we can compute the complex conjugation: >>> from sympy import Ynm, Symbol, conjugate >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> conjugate(Ynm(n, m, theta, phi)) (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) To get back the well known expressions in spherical coordinates, we use full expansion: >>> from sympy import Ynm, Symbol, expand_func >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> expand_func(Ynm(n, m, theta, phi)) sqrt((2*n + 1)*factorial(-m + n)/factorial(m + n))*exp(I*m*phi)*assoc_legendre(n, m, cos(theta))/(2*sqrt(pi)) See Also ======== Ynm_c, Znm References ========== .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/ .. [4] http://dlmf.nist.gov/14.30 """ @classmethod def eval(cls, n, m, theta, phi): n, m, theta, phi = [sympify(x) for x in (n, m, theta, phi)] # Handle negative index m and arguments theta, phi if m.could_extract_minus_sign(): m = -m return S.NegativeOne**m * exp(-2*I*m*phi) * Ynm(n, m, theta, phi) if theta.could_extract_minus_sign(): theta = -theta return Ynm(n, m, theta, phi) if phi.could_extract_minus_sign(): phi = -phi return exp(-2*I*m*phi) * Ynm(n, m, theta, phi) # TODO Add more simplififcation here def _eval_expand_func(self, **hints): n, m, theta, phi = self.args rv = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) * exp(I*m*phi) * assoc_legendre(n, m, cos(theta))) # We can do this because of the range of theta return rv.subs(sqrt(-cos(theta)**2 + 1), sin(theta)) def fdiff(self, argindex=4): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt m raise ArgumentIndexError(self, argindex) elif argindex == 3: # Diff wrt theta n, m, theta, phi = self.args return (m * cot(theta) * Ynm(n, m, theta, phi) + sqrt((n - m)*(n + m + 1)) * exp(-I*phi) * Ynm(n, m + 1, theta, phi)) elif argindex == 4: # Diff wrt phi n, m, theta, phi = self.args return I * m * Ynm(n, m, theta, phi) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, m, theta, phi, **kwargs): # TODO: Make sure n \in N # TODO: Assert |m| <= n ortherwise we should return 0 return self.expand(func=True) def _eval_rewrite_as_sin(self, n, m, theta, phi, **kwargs): return self.rewrite(cos) def _eval_rewrite_as_cos(self, n, m, theta, phi, **kwargs): # This method can be expensive due to extensive use of simplification! from sympy.simplify import simplify, trigsimp # TODO: Make sure n \in N # TODO: Assert |m| <= n ortherwise we should return 0 term = simplify(self.expand(func=True)) # We can do this because of the range of theta term = term.xreplace({Abs(sin(theta)):sin(theta)}) return simplify(trigsimp(term)) def _eval_conjugate(self): # TODO: Make sure theta \in R and phi \in R n, m, theta, phi = self.args return S.NegativeOne**m * self.func(n, -m, theta, phi) def as_real_imag(self, deep=True, **hints): # TODO: Handle deep and hints n, m, theta, phi = self.args re = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) * cos(m*phi) * assoc_legendre(n, m, cos(theta))) im = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) * sin(m*phi) * assoc_legendre(n, m, cos(theta))) return (re, im) def _eval_evalf(self, prec): # Note: works without this function by just calling # mpmath for Legendre polynomials. But using # the dedicated function directly is cleaner. from mpmath import mp, workprec n = self.args[0]._to_mpmath(prec) m = self.args[1]._to_mpmath(prec) theta = self.args[2]._to_mpmath(prec) phi = self.args[3]._to_mpmath(prec) with workprec(prec): res = mp.spherharm(n, m, theta, phi) return Expr._from_mpmath(res, prec) def Ynm_c(n, m, theta, phi): r""" Conjugate spherical harmonics defined as .. math:: \overline{Y_n^m(\theta, \varphi)} := (-1)^m Y_n^{-m}(\theta, \varphi). Examples ======== >>> from sympy import Ynm_c, Symbol, simplify >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> Ynm_c(n, m, theta, phi) (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) >>> Ynm_c(n, m, -theta, phi) (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) For specific integers $n$ and $m$ we can evaluate the harmonics to more useful expressions: >>> simplify(Ynm_c(0, 0, theta, phi).expand(func=True)) 1/(2*sqrt(pi)) >>> simplify(Ynm_c(1, -1, theta, phi).expand(func=True)) sqrt(6)*exp(I*(-phi + 2*conjugate(phi)))*sin(theta)/(4*sqrt(pi)) See Also ======== Ynm, Znm References ========== .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/ """ return conjugate(Ynm(n, m, theta, phi)) class Znm(Function): r""" Real spherical harmonics defined as .. math:: Z_n^m(\theta, \varphi) := \begin{cases} \frac{Y_n^m(\theta, \varphi) + \overline{Y_n^m(\theta, \varphi)}}{\sqrt{2}} &\quad m > 0 \\ Y_n^m(\theta, \varphi) &\quad m = 0 \\ \frac{Y_n^m(\theta, \varphi) - \overline{Y_n^m(\theta, \varphi)}}{i \sqrt{2}} &\quad m < 0 \\ \end{cases} which gives in simplified form .. math:: Z_n^m(\theta, \varphi) = \begin{cases} \frac{Y_n^m(\theta, \varphi) + (-1)^m Y_n^{-m}(\theta, \varphi)}{\sqrt{2}} &\quad m > 0 \\ Y_n^m(\theta, \varphi) &\quad m = 0 \\ \frac{Y_n^m(\theta, \varphi) - (-1)^m Y_n^{-m}(\theta, \varphi)}{i \sqrt{2}} &\quad m < 0 \\ \end{cases} Examples ======== >>> from sympy import Znm, Symbol, simplify >>> from sympy.abc import n, m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> Znm(n, m, theta, phi) Znm(n, m, theta, phi) For specific integers n and m we can evaluate the harmonics to more useful expressions: >>> simplify(Znm(0, 0, theta, phi).expand(func=True)) 1/(2*sqrt(pi)) >>> simplify(Znm(1, 1, theta, phi).expand(func=True)) -sqrt(3)*sin(theta)*cos(phi)/(2*sqrt(pi)) >>> simplify(Znm(2, 1, theta, phi).expand(func=True)) -sqrt(15)*sin(2*theta)*cos(phi)/(4*sqrt(pi)) See Also ======== Ynm, Ynm_c References ========== .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/ """ @classmethod def eval(cls, n, m, theta, phi): n, m, th, ph = [sympify(x) for x in (n, m, theta, phi)] if m.is_positive: zz = (Ynm(n, m, th, ph) + Ynm_c(n, m, th, ph)) / sqrt(2) return zz elif m.is_zero: return Ynm(n, m, th, ph) elif m.is_negative: zz = (Ynm(n, m, th, ph) - Ynm_c(n, m, th, ph)) / (sqrt(2)*I) return zz
b7e6f4cab9a9d784062b6bc2de41e0351af6779b0092730e80bb3a4046851463
from sympy.core import S, sympify from sympy.core.symbol import (Dummy, symbols) from sympy.functions import Piecewise, piecewise_fold from sympy.logic.boolalg import And from sympy.sets.sets import Interval from functools import lru_cache def _ivl(cond, x): """return the interval corresponding to the condition Conditions in spline's Piecewise give the range over which an expression is valid like (lo <= x) & (x <= hi). This function returns (lo, hi). """ if isinstance(cond, And) and len(cond.args) == 2: a, b = cond.args if a.lts == x: a, b = b, a return a.lts, b.gts raise TypeError('unexpected cond type: %s' % cond) def _add_splines(c, b1, d, b2, x): """Construct c*b1 + d*b2.""" if S.Zero in (b1, c): rv = piecewise_fold(d * b2) elif S.Zero in (b2, d): rv = piecewise_fold(c * b1) else: new_args = [] # Just combining the Piecewise without any fancy optimization p1 = piecewise_fold(c * b1) p2 = piecewise_fold(d * b2) # Search all Piecewise arguments except (0, True) p2args = list(p2.args[:-1]) # This merging algorithm assumes the conditions in # p1 and p2 are sorted for arg in p1.args[:-1]: expr = arg.expr cond = arg.cond lower = _ivl(cond, x)[0] # Check p2 for matching conditions that can be merged for i, arg2 in enumerate(p2args): expr2 = arg2.expr cond2 = arg2.cond lower_2, upper_2 = _ivl(cond2, x) if cond2 == cond: # Conditions match, join expressions expr += expr2 # Remove matching element del p2args[i] # No need to check the rest break elif lower_2 < lower and upper_2 <= lower: # Check if arg2 condition smaller than arg1, # add to new_args by itself (no match expected # in p1) new_args.append(arg2) del p2args[i] break # Checked all, add expr and cond new_args.append((expr, cond)) # Add remaining items from p2args new_args.extend(p2args) # Add final (0, True) new_args.append((0, True)) rv = Piecewise(*new_args, evaluate=False) return rv.expand() @lru_cache(maxsize=128) def bspline_basis(d, knots, n, x): """ The $n$-th B-spline at $x$ of degree $d$ with knots. Explanation =========== B-Splines are piecewise polynomials of degree $d$. They are defined on a set of knots, which is a sequence of integers or floats. Examples ======== The 0th degree splines have a value of 1 on a single interval: >>> from sympy import bspline_basis >>> from sympy.abc import x >>> d = 0 >>> knots = tuple(range(5)) >>> bspline_basis(d, knots, 0, x) Piecewise((1, (x >= 0) & (x <= 1)), (0, True)) For a given ``(d, knots)`` there are ``len(knots)-d-1`` B-splines defined, that are indexed by ``n`` (starting at 0). Here is an example of a cubic B-spline: >>> bspline_basis(3, tuple(range(5)), 0, x) Piecewise((x**3/6, (x >= 0) & (x <= 1)), (-x**3/2 + 2*x**2 - 2*x + 2/3, (x >= 1) & (x <= 2)), (x**3/2 - 4*x**2 + 10*x - 22/3, (x >= 2) & (x <= 3)), (-x**3/6 + 2*x**2 - 8*x + 32/3, (x >= 3) & (x <= 4)), (0, True)) By repeating knot points, you can introduce discontinuities in the B-splines and their derivatives: >>> d = 1 >>> knots = (0, 0, 2, 3, 4) >>> bspline_basis(d, knots, 0, x) Piecewise((1 - x/2, (x >= 0) & (x <= 2)), (0, True)) It is quite time consuming to construct and evaluate B-splines. If you need to evaluate a B-spline many times, it is best to lambdify them first: >>> from sympy import lambdify >>> d = 3 >>> knots = tuple(range(10)) >>> b0 = bspline_basis(d, knots, 0, x) >>> f = lambdify(x, b0) >>> y = f(0.5) Parameters ========== d : integer degree of bspline knots : list of integer values list of knots points of bspline n : integer $n$-th B-spline x : symbol See Also ======== bspline_basis_set References ========== .. [1] https://en.wikipedia.org/wiki/B-spline """ # make sure x has no assumptions so conditions don't evaluate xvar = x x = Dummy() knots = tuple(sympify(k) for k in knots) d = int(d) n = int(n) n_knots = len(knots) n_intervals = n_knots - 1 if n + d + 1 > n_intervals: raise ValueError("n + d + 1 must not exceed len(knots) - 1") if d == 0: result = Piecewise( (S.One, Interval(knots[n], knots[n + 1]).contains(x)), (0, True) ) elif d > 0: denom = knots[n + d + 1] - knots[n + 1] if denom != S.Zero: B = (knots[n + d + 1] - x) / denom b2 = bspline_basis(d - 1, knots, n + 1, x) else: b2 = B = S.Zero denom = knots[n + d] - knots[n] if denom != S.Zero: A = (x - knots[n]) / denom b1 = bspline_basis(d - 1, knots, n, x) else: b1 = A = S.Zero result = _add_splines(A, b1, B, b2, x) else: raise ValueError("degree must be non-negative: %r" % n) # return result with user-given x return result.xreplace({x: xvar}) def bspline_basis_set(d, knots, x): """ Return the ``len(knots)-d-1`` B-splines at *x* of degree *d* with *knots*. Explanation =========== This function returns a list of piecewise polynomials that are the ``len(knots)-d-1`` B-splines of degree *d* for the given knots. This function calls ``bspline_basis(d, knots, n, x)`` for different values of *n*. Examples ======== >>> from sympy import bspline_basis_set >>> from sympy.abc import x >>> d = 2 >>> knots = range(5) >>> splines = bspline_basis_set(d, knots, x) >>> splines [Piecewise((x**2/2, (x >= 0) & (x <= 1)), (-x**2 + 3*x - 3/2, (x >= 1) & (x <= 2)), (x**2/2 - 3*x + 9/2, (x >= 2) & (x <= 3)), (0, True)), Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x <= 2)), (-x**2 + 5*x - 11/2, (x >= 2) & (x <= 3)), (x**2/2 - 4*x + 8, (x >= 3) & (x <= 4)), (0, True))] Parameters ========== d : integer degree of bspline knots : list of integers list of knots points of bspline x : symbol See Also ======== bspline_basis """ n_splines = len(knots) - d - 1 return [bspline_basis(d, tuple(knots), i, x) for i in range(n_splines)] def interpolating_spline(d, x, X, Y): """ Return spline of degree *d*, passing through the given *X* and *Y* values. Explanation =========== This function returns a piecewise function such that each part is a polynomial of degree not greater than *d*. The value of *d* must be 1 or greater and the values of *X* must be strictly increasing. Examples ======== >>> from sympy import interpolating_spline >>> from sympy.abc import x >>> interpolating_spline(1, x, [1, 2, 4, 7], [3, 6, 5, 7]) Piecewise((3*x, (x >= 1) & (x <= 2)), (7 - x/2, (x >= 2) & (x <= 4)), (2*x/3 + 7/3, (x >= 4) & (x <= 7))) >>> interpolating_spline(3, x, [-2, 0, 1, 3, 4], [4, 2, 1, 1, 3]) Piecewise((7*x**3/117 + 7*x**2/117 - 131*x/117 + 2, (x >= -2) & (x <= 1)), (10*x**3/117 - 2*x**2/117 - 122*x/117 + 77/39, (x >= 1) & (x <= 4))) Parameters ========== d : integer Degree of Bspline strictly greater than equal to one x : symbol X : list of strictly increasing integer values list of X coordinates through which the spline passes Y : list of strictly increasing integer values list of Y coordinates through which the spline passes See Also ======== bspline_basis_set, interpolating_poly """ from sympy.solvers.solveset import linsolve from sympy.matrices.dense import Matrix # Input sanitization d = sympify(d) if not (d.is_Integer and d.is_positive): raise ValueError("Spline degree must be a positive integer, not %s." % d) if len(X) != len(Y): raise ValueError("Number of X and Y coordinates must be the same.") if len(X) < d + 1: raise ValueError("Degree must be less than the number of control points.") if not all(a < b for a, b in zip(X, X[1:])): raise ValueError("The x-coordinates must be strictly increasing.") X = [sympify(i) for i in X] # Evaluating knots value if d.is_odd: j = (d + 1) // 2 interior_knots = X[j:-j] else: j = d // 2 interior_knots = [ (a + b)/2 for a, b in zip(X[j : -j - 1], X[j + 1 : -j]) ] knots = [X[0]] * (d + 1) + list(interior_knots) + [X[-1]] * (d + 1) basis = bspline_basis_set(d, knots, x) A = [[b.subs(x, v) for b in basis] for v in X] coeff = linsolve((Matrix(A), Matrix(Y)), symbols("c0:{}".format(len(X)), cls=Dummy)) coeff = list(coeff)[0] intervals = {c for b in basis for (e, c) in b.args if c != True} # Sorting the intervals # ival contains the end-points of each interval ival = [_ivl(c, x) for c in intervals] com = zip(ival, intervals) com = sorted(com, key=lambda x: x[0]) intervals = [y for x, y in com] basis_dicts = [{c: e for (e, c) in b.args} for b in basis] spline = [] for i in intervals: piece = sum( [c * d.get(i, S.Zero) for (c, d) in zip(coeff, basis_dicts)], S.Zero ) spline.append((piece, i)) return Piecewise(*spline)
6d504d410662793b73083ebb22e8427e0aab28d1970a0048a840555b2db90ec7
""" Riemann zeta and related function. """ from sympy.core.add import Add from sympy.core import Function, S, sympify, pi, I from sympy.core.function import ArgumentIndexError, expand_mul from sympy.core.symbol import Dummy from sympy.functions.combinatorial.numbers import bernoulli, factorial, harmonic from sympy.functions.elementary.complexes import re, unpolarify, Abs, polar_lift from sympy.functions.elementary.exponential import log, exp_polar, exp from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys.polytools import Poly ############################################################################### ###################### LERCH TRANSCENDENT ##################################### ############################################################################### class lerchphi(Function): r""" Lerch transcendent (Lerch phi function). Explanation =========== For $\operatorname{Re}(a) > 0$, $|z| < 1$ and $s \in \mathbb{C}$, the Lerch transcendent is defined as .. math :: \Phi(z, s, a) = \sum_{n=0}^\infty \frac{z^n}{(n + a)^s}, where the standard branch of the argument is used for $n + a$, and by analytic continuation for other values of the parameters. A commonly used related function is the Lerch zeta function, defined by .. math:: L(q, s, a) = \Phi(e^{2\pi i q}, s, a). **Analytic Continuation and Branching Behavior** It can be shown that .. math:: \Phi(z, s, a) = z\Phi(z, s, a+1) + a^{-s}. This provides the analytic continuation to $\operatorname{Re}(a) \le 0$. Assume now $\operatorname{Re}(a) > 0$. The integral representation .. math:: \Phi_0(z, s, a) = \int_0^\infty \frac{t^{s-1} e^{-at}}{1 - ze^{-t}} \frac{\mathrm{d}t}{\Gamma(s)} provides an analytic continuation to $\mathbb{C} - [1, \infty)$. Finally, for $x \in (1, \infty)$ we find .. math:: \lim_{\epsilon \to 0^+} \Phi_0(x + i\epsilon, s, a) -\lim_{\epsilon \to 0^+} \Phi_0(x - i\epsilon, s, a) = \frac{2\pi i \log^{s-1}{x}}{x^a \Gamma(s)}, using the standard branch for both $\log{x}$ and $\log{\log{x}}$ (a branch of $\log{\log{x}}$ is needed to evaluate $\log{x}^{s-1}$). This concludes the analytic continuation. The Lerch transcendent is thus branched at $z \in \{0, 1, \infty\}$ and $a \in \mathbb{Z}_{\le 0}$. For fixed $z, a$ outside these branch points, it is an entire function of $s$. Examples ======== The Lerch transcendent is a fairly general function, for this reason it does not automatically evaluate to simpler functions. Use ``expand_func()`` to achieve this. If $z=1$, the Lerch transcendent reduces to the Hurwitz zeta function: >>> from sympy import lerchphi, expand_func >>> from sympy.abc import z, s, a >>> expand_func(lerchphi(1, s, a)) zeta(s, a) More generally, if $z$ is a root of unity, the Lerch transcendent reduces to a sum of Hurwitz zeta functions: >>> expand_func(lerchphi(-1, s, a)) zeta(s, a/2)/2**s - zeta(s, a/2 + 1/2)/2**s If $a=1$, the Lerch transcendent reduces to the polylogarithm: >>> expand_func(lerchphi(z, s, 1)) polylog(s, z)/z More generally, if $a$ is rational, the Lerch transcendent reduces to a sum of polylogarithms: >>> from sympy import S >>> expand_func(lerchphi(z, s, S(1)/2)) 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z)) >>> expand_func(lerchphi(z, s, S(3)/2)) -2**s/z + 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))/z The derivatives with respect to $z$ and $a$ can be computed in closed form: >>> lerchphi(z, s, a).diff(z) (-a*lerchphi(z, s, a) + lerchphi(z, s - 1, a))/z >>> lerchphi(z, s, a).diff(a) -s*lerchphi(z, s + 1, a) See Also ======== polylog, zeta References ========== .. [1] Bateman, H.; Erdelyi, A. (1953), Higher Transcendental Functions, Vol. I, New York: McGraw-Hill. Section 1.11. .. [2] http://dlmf.nist.gov/25.14 .. [3] https://en.wikipedia.org/wiki/Lerch_transcendent """ def _eval_expand_func(self, **hints): z, s, a = self.args if z == 1: return zeta(s, a) if s.is_Integer and s <= 0: t = Dummy('t') p = Poly((t + a)**(-s), t) start = 1/(1 - t) res = S.Zero for c in reversed(p.all_coeffs()): res += c*start start = t*start.diff(t) return res.subs(t, z) if a.is_Rational: # See section 18 of # Kelly B. Roach. Hypergeometric Function Representations. # In: Proceedings of the 1997 International Symposium on Symbolic and # Algebraic Computation, pages 205-211, New York, 1997. ACM. # TODO should something be polarified here? add = S.Zero mul = S.One # First reduce a to the interaval (0, 1] if a > 1: n = floor(a) if n == a: n -= 1 a -= n mul = z**(-n) add = Add(*[-z**(k - n)/(a + k)**s for k in range(n)]) elif a <= 0: n = floor(-a) + 1 a += n mul = z**n add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in range(n)]) m, n = S([a.p, a.q]) zet = exp_polar(2*pi*I/n) root = z**(1/n) return add + mul*n**(s - 1)*Add( *[polylog(s, zet**k*root)._eval_expand_func(**hints) / (unpolarify(zet)**k*root)**m for k in range(n)]) # TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed if isinstance(z, exp) and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]: # TODO reference? if z == -1: p, q = S([1, 2]) elif z == I: p, q = S([1, 4]) elif z == -I: p, q = S([-1, 4]) else: arg = z.args[0]/(2*pi*I) p, q = S([arg.p, arg.q]) return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q) for k in range(q)]) return lerchphi(z, s, a) def fdiff(self, argindex=1): z, s, a = self.args if argindex == 3: return -s*lerchphi(z, s + 1, a) elif argindex == 1: return (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z else: raise ArgumentIndexError def _eval_rewrite_helper(self, z, s, a, target): res = self._eval_expand_func() if res.has(target): return res else: return self def _eval_rewrite_as_zeta(self, z, s, a, **kwargs): return self._eval_rewrite_helper(z, s, a, zeta) def _eval_rewrite_as_polylog(self, z, s, a, **kwargs): return self._eval_rewrite_helper(z, s, a, polylog) ############################################################################### ###################### POLYLOGARITHM ########################################## ############################################################################### class polylog(Function): r""" Polylogarithm function. Explanation =========== For $|z| < 1$ and $s \in \mathbb{C}$, the polylogarithm is defined by .. math:: \operatorname{Li}_s(z) = \sum_{n=1}^\infty \frac{z^n}{n^s}, where the standard branch of the argument is used for $n$. It admits an analytic continuation which is branched at $z=1$ (notably not on the sheet of initial definition), $z=0$ and $z=\infty$. The name polylogarithm comes from the fact that for $s=1$, the polylogarithm is related to the ordinary logarithm (see examples), and that .. math:: \operatorname{Li}_{s+1}(z) = \int_0^z \frac{\operatorname{Li}_s(t)}{t} \mathrm{d}t. The polylogarithm is a special case of the Lerch transcendent: .. math:: \operatorname{Li}_{s}(z) = z \Phi(z, s, 1). Examples ======== For $z \in \{0, 1, -1\}$, the polylogarithm is automatically expressed using other functions: >>> from sympy import polylog >>> from sympy.abc import s >>> polylog(s, 0) 0 >>> polylog(s, 1) zeta(s) >>> polylog(s, -1) -dirichlet_eta(s) If $s$ is a negative integer, $0$ or $1$, the polylogarithm can be expressed using elementary functions. This can be done using ``expand_func()``: >>> from sympy import expand_func >>> from sympy.abc import z >>> expand_func(polylog(1, z)) -log(1 - z) >>> expand_func(polylog(0, z)) z/(1 - z) The derivative with respect to $z$ can be computed in closed form: >>> polylog(s, z).diff(z) polylog(s - 1, z)/z The polylogarithm can be expressed in terms of the lerch transcendent: >>> from sympy import lerchphi >>> polylog(s, z).rewrite(lerchphi) z*lerchphi(z, s, 1) See Also ======== zeta, lerchphi """ @classmethod def eval(cls, s, z): s, z = sympify((s, z)) if z is S.One: return zeta(s) elif z is S.NegativeOne: return -dirichlet_eta(s) elif z is S.Zero: return S.Zero elif s == 2: if z == S.Half: return pi**2/12 - log(2)**2/2 elif z == 2: return pi**2/4 - I*pi*log(2) elif z == -(sqrt(5) - 1)/2: return -pi**2/15 + log((sqrt(5)-1)/2)**2/2 elif z == -(sqrt(5) + 1)/2: return -pi**2/10 - log((sqrt(5)+1)/2)**2 elif z == (3 - sqrt(5))/2: return pi**2/15 - log((sqrt(5)-1)/2)**2 elif z == (sqrt(5) - 1)/2: return pi**2/10 - log((sqrt(5)-1)/2)**2 if z.is_zero: return S.Zero # Make an effort to determine if z is 1 to avoid replacing into # expression with singularity zone = z.equals(S.One) if zone: return zeta(s) elif zone is False: # For s = 0 or -1 use explicit formulas to evaluate, but # automatically expanding polylog(1, z) to -log(1-z) seems # undesirable for summation methods based on hypergeometric # functions if s is S.Zero: return z/(1 - z) elif s is S.NegativeOne: return z/(1 - z)**2 if s.is_zero: return z/(1 - z) # polylog is branched, but not over the unit disk if z.has(exp_polar, polar_lift) and (zone or (Abs(z) <= S.One) == True): return cls(s, unpolarify(z)) def fdiff(self, argindex=1): s, z = self.args if argindex == 2: return polylog(s - 1, z)/z raise ArgumentIndexError def _eval_rewrite_as_lerchphi(self, s, z, **kwargs): return z*lerchphi(z, s, 1) def _eval_expand_func(self, **hints): s, z = self.args if s == 1: return -log(1 - z) if s.is_Integer and s <= 0: u = Dummy('u') start = u/(1 - u) for _ in range(-s): start = u*start.diff(u) return expand_mul(start).subs(u, z) return polylog(s, z) def _eval_is_zero(self): z = self.args[1] if z.is_zero: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order nu, z = self.args z0 = z.subs(x, 0) if z0 is S.NaN: z0 = z.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if z0.is_zero: # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = z._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o term = r s = [term] for k in range(2, newn): term *= r s.append(term/k**nu) return Add(*s) + o return super(polylog, self)._eval_nseries(x, n, logx, cdir) ############################################################################### ###################### HURWITZ GENERALIZED ZETA FUNCTION ###################### ############################################################################### class zeta(Function): r""" Hurwitz zeta function (or Riemann zeta function). Explanation =========== For $\operatorname{Re}(a) > 0$ and $\operatorname{Re}(s) > 1$, this function is defined as .. math:: \zeta(s, a) = \sum_{n=0}^\infty \frac{1}{(n + a)^s}, where the standard choice of argument for $n + a$ is used. For fixed $a$ with $\operatorname{Re}(a) > 0$ the Hurwitz zeta function admits a meromorphic continuation to all of $\mathbb{C}$, it is an unbranched function with a simple pole at $s = 1$. Analytic continuation to other $a$ is possible under some circumstances, but this is not typically done. The Hurwitz zeta function is a special case of the Lerch transcendent: .. math:: \zeta(s, a) = \Phi(1, s, a). This formula defines an analytic continuation for all possible values of $s$ and $a$ (also $\operatorname{Re}(a) < 0$), see the documentation of :class:`lerchphi` for a description of the branching behavior. If no value is passed for $a$, by this function assumes a default value of $a = 1$, yielding the Riemann zeta function. Examples ======== For $a = 1$ the Hurwitz zeta function reduces to the famous Riemann zeta function: .. math:: \zeta(s, 1) = \zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}. >>> from sympy import zeta >>> from sympy.abc import s >>> zeta(s, 1) zeta(s) >>> zeta(s) zeta(s) The Riemann zeta function can also be expressed using the Dirichlet eta function: >>> from sympy import dirichlet_eta >>> zeta(s).rewrite(dirichlet_eta) dirichlet_eta(s)/(1 - 2**(1 - s)) The Riemann zeta function at positive even integer and negative odd integer values is related to the Bernoulli numbers: >>> zeta(2) pi**2/6 >>> zeta(4) pi**4/90 >>> zeta(-1) -1/12 The specific formulae are: .. math:: \zeta(2n) = (-1)^{n+1} \frac{B_{2n} (2\pi)^{2n}}{2(2n)!} .. math:: \zeta(-n) = -\frac{B_{n+1}}{n+1} At negative even integers the Riemann zeta function is zero: >>> zeta(-4) 0 No closed-form expressions are known at positive odd integers, but numerical evaluation is possible: >>> zeta(3).n() 1.20205690315959 The derivative of $\zeta(s, a)$ with respect to $a$ can be computed: >>> from sympy.abc import a >>> zeta(s, a).diff(a) -s*zeta(s + 1, a) However the derivative with respect to $s$ has no useful closed form expression: >>> zeta(s, a).diff(s) Derivative(zeta(s, a), s) The Hurwitz zeta function can be expressed in terms of the Lerch transcendent, :class:`~.lerchphi`: >>> from sympy import lerchphi >>> zeta(s, a).rewrite(lerchphi) lerchphi(1, s, a) See Also ======== dirichlet_eta, lerchphi, polylog References ========== .. [1] http://dlmf.nist.gov/25.11 .. [2] https://en.wikipedia.org/wiki/Hurwitz_zeta_function """ @classmethod def eval(cls, z, a_=None): if a_ is None: z, a = list(map(sympify, (z, 1))) else: z, a = list(map(sympify, (z, a_))) if a.is_Number: if a is S.NaN: return S.NaN elif a is S.One and a_ is not None: return cls(z) # TODO Should a == 0 return S.NaN as well? if z.is_Number: if z is S.NaN: return S.NaN elif z is S.Infinity: return S.One elif z.is_zero: return S.Half - a elif z is S.One: return S.ComplexInfinity if z.is_integer: if a.is_Integer: if z.is_negative: zeta = S.NegativeOne**z * bernoulli(-z + 1)/(-z + 1) elif z.is_even and z.is_positive: B, F = bernoulli(z), factorial(z) zeta = (S.NegativeOne**(z/2+1) * 2**(z - 1) * B * pi**z) / F else: return if a.is_negative: return zeta + harmonic(abs(a), z) else: return zeta - harmonic(a - 1, z) if z.is_zero: return S.Half - a def _eval_rewrite_as_dirichlet_eta(self, s, a=1, **kwargs): if a != 1: return self s = self.args[0] return dirichlet_eta(s)/(1 - 2**(1 - s)) def _eval_rewrite_as_lerchphi(self, s, a=1, **kwargs): return lerchphi(1, s, a) def _eval_is_finite(self): arg_is_one = (self.args[0] - 1).is_zero if arg_is_one is not None: return not arg_is_one def fdiff(self, argindex=1): if len(self.args) == 2: s, a = self.args else: s, a = self.args + (1,) if argindex == 2: return -s*zeta(s + 1, a) else: raise ArgumentIndexError class dirichlet_eta(Function): r""" Dirichlet eta function. Explanation =========== For $\operatorname{Re}(s) > 0$, this function is defined as .. math:: \eta(s) = \sum_{n=1}^\infty \frac{(-1)^{n-1}}{n^s}. It admits a unique analytic continuation to all of $\mathbb{C}$. It is an entire, unbranched function. Examples ======== The Dirichlet eta function is closely related to the Riemann zeta function: >>> from sympy import dirichlet_eta, zeta >>> from sympy.abc import s >>> dirichlet_eta(s).rewrite(zeta) (1 - 2**(1 - s))*zeta(s) See Also ======== zeta References ========== .. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function """ @classmethod def eval(cls, s): if s == 1: return log(2) z = zeta(s) if not z.has(zeta): return (1 - 2**(1 - s))*z def _eval_rewrite_as_zeta(self, s, **kwargs): return (1 - 2**(1 - s)) * zeta(s) class riemann_xi(Function): r""" Riemann Xi function. Examples ======== The Riemann Xi function is closely related to the Riemann zeta function. The zeros of Riemann Xi function are precisely the non-trivial zeros of the zeta function. >>> from sympy import riemann_xi, zeta >>> from sympy.abc import s >>> riemann_xi(s).rewrite(zeta) s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Riemann_Xi_function """ @classmethod def eval(cls, s): from sympy.functions.special.gamma_functions import gamma z = zeta(s) if s in (S.Zero, S.One): return S.Half if not isinstance(z, zeta): return s*(s - 1)*gamma(s/2)*z/(2*pi**(s/2)) def _eval_rewrite_as_zeta(self, s, **kwargs): from sympy.functions.special.gamma_functions import gamma return s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2)) class stieltjes(Function): r""" Represents Stieltjes constants, $\gamma_{k}$ that occur in Laurent Series expansion of the Riemann zeta function. Examples ======== >>> from sympy import stieltjes >>> from sympy.abc import n, m >>> stieltjes(n) stieltjes(n) The zero'th stieltjes constant: >>> stieltjes(0) EulerGamma >>> stieltjes(0, 1) EulerGamma For generalized stieltjes constants: >>> stieltjes(n, m) stieltjes(n, m) Constants are only defined for integers >= 0: >>> stieltjes(-1) zoo References ========== .. [1] https://en.wikipedia.org/wiki/Stieltjes_constants """ @classmethod def eval(cls, n, a=None): n = sympify(n) if a is not None: a = sympify(a) if a is S.NaN: return S.NaN if a.is_Integer and a.is_nonpositive: return S.ComplexInfinity if n.is_Number: if n is S.NaN: return S.NaN elif n < 0: return S.ComplexInfinity elif not n.is_Integer: return S.ComplexInfinity elif n is S.Zero and a in [None, 1]: return S.EulerGamma if n.is_extended_negative: return S.ComplexInfinity if n.is_zero and a in [None, 1]: return S.EulerGamma if n.is_integer == False: return S.ComplexInfinity
3b2190017084f8d15b9d5a9f18264dd88c7d2fe88672dc68a55e7d4f0691e238
from functools import wraps from sympy.core import S from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, _mexpand from sympy.core.logic import fuzzy_or, fuzzy_not from sympy.core.numbers import Rational, pi, I from sympy.core.power import Pow from sympy.core.symbol import Dummy, Wild from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.trigonometric import sin, cos, csc, cot from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import cbrt, sqrt, root from sympy.functions.elementary.complexes import (Abs, re, im, polar_lift, unpolarify) from sympy.functions.special.gamma_functions import gamma, digamma, uppergamma from sympy.functions.special.hyper import hyper from sympy.polys.orthopolys import spherical_bessel_fn from mpmath import mp, workprec # TODO # o Scorer functions G1 and G2 # o Asymptotic expansions # These are possible, e.g. for fixed order, but since the bessel type # functions are oscillatory they are not actually tractable at # infinity, so this is not particularly useful right now. # o Nicer series expansions. # o More rewriting. # o Add solvers to ode.py (or rather add solvers for the hypergeometric equation). class BesselBase(Function): """ Abstract base class for Bessel-type functions. This class is meant to reduce code duplication. All Bessel-type functions can 1) be differentiated, with the derivatives expressed in terms of similar functions, and 2) be rewritten in terms of other Bessel-type functions. Here, Bessel-type functions are assumed to have one complex parameter. To use this base class, define class attributes ``_a`` and ``_b`` such that ``2*F_n' = -_a*F_{n+1} + b*F_{n-1}``. """ @property def order(self): """ The order of the Bessel-type function. """ return self.args[0] @property def argument(self): """ The argument of the Bessel-type function. """ return self.args[1] @classmethod def eval(cls, nu, z): return def fdiff(self, argindex=2): if argindex != 2: raise ArgumentIndexError(self, argindex) return (self._b/2 * self.__class__(self.order - 1, self.argument) - self._a/2 * self.__class__(self.order + 1, self.argument)) def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return self.__class__(self.order.conjugate(), z.conjugate()) def _eval_is_meromorphic(self, x, a): nu, z = self.order, self.argument if nu.has(x): return False if not z._eval_is_meromorphic(x, a): return None z0 = z.subs(x, a) if nu.is_integer: if isinstance(self, (besselj, besseli, hn1, hn2, jn, yn)) or not nu.is_zero: return fuzzy_not(z0.is_infinite) return fuzzy_not(fuzzy_or([z0.is_zero, z0.is_infinite])) def _eval_expand_func(self, **hints): nu, z, f = self.order, self.argument, self.__class__ if nu.is_real: if (nu - 1).is_positive: return (-self._a*self._b*f(nu - 2, z)._eval_expand_func() + 2*self._a*(nu - 1)*f(nu - 1, z)._eval_expand_func()/z) elif (nu + 1).is_negative: return (2*self._b*(nu + 1)*f(nu + 1, z)._eval_expand_func()/z - self._a*self._b*f(nu + 2, z)._eval_expand_func()) return self def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import besselsimp return besselsimp(self) class besselj(BesselBase): r""" Bessel function of the first kind. Explanation =========== The Bessel $J$ function of order $\nu$ is defined to be the function satisfying Bessel's differential equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu^2) w = 0, with Laurent expansion .. math :: J_\nu(z) = z^\nu \left(\frac{1}{\Gamma(\nu + 1) 2^\nu} + O(z^2) \right), if $\nu$ is not a negative integer. If $\nu=-n \in \mathbb{Z}_{<0}$ *is* a negative integer, then the definition is .. math :: J_{-n}(z) = (-1)^n J_n(z). Examples ======== Create a Bessel function object: >>> from sympy import besselj, jn >>> from sympy.abc import z, n >>> b = besselj(n, z) Differentiate it: >>> b.diff(z) besselj(n - 1, z)/2 - besselj(n + 1, z)/2 Rewrite in terms of spherical Bessel functions: >>> b.rewrite(jn) sqrt(2)*sqrt(z)*jn(n - 1/2, z)/sqrt(pi) Access the parameter and argument: >>> b.order n >>> b.argument z See Also ======== bessely, besseli, besselk References ========== .. [1] Abramowitz, Milton; Stegun, Irene A., eds. (1965), "Chapter 9", Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [2] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [3] https://en.wikipedia.org/wiki/Bessel_function .. [4] http://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/ """ _a = S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive: return S.Zero elif re(nu).is_negative and not (nu.is_integer is True): return S.ComplexInfinity elif nu.is_imaginary: return S.NaN if z in (S.Infinity, S.NegativeInfinity): return S.Zero if z.could_extract_minus_sign(): return (z)**nu*(-z)**(-nu)*besselj(nu, -z) if nu.is_integer: if nu.could_extract_minus_sign(): return S.NegativeOne**(-nu)*besselj(-nu, z) newz = z.extract_multiplicatively(I) if newz: # NOTE we don't want to change the function if z==0 return I**(nu)*besseli(nu, newz) # branch handling: if nu.is_integer: newz = unpolarify(z) if newz != z: return besselj(nu, newz) else: newz, n = z.extract_branch_factor() if n != 0: return exp(2*n*pi*nu*I)*besselj(nu, newz) nnu = unpolarify(nu) if nu != nnu: return besselj(nnu, z) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): return exp(I*pi*nu/2)*besseli(nu, polar_lift(-I)*z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): if nu.is_integer is False: return csc(pi*nu)*bessely(-nu, z) - cot(pi*nu)*bessely(nu, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return sqrt(2*z/pi)*jn(nu - S.Half, self.argument) def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args arg = z.as_leading_term(x) if x in arg.free_symbols: return arg**nu/(2**nu*gamma(nu + 1)) else: return self.func(nu, z.subs(x, 0)) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_extended_real: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() term = r**nu/gamma(nu + 1) s = [term] for k in range(1, (newn + 1)//2): term *= -t/(k*(nu + k)) term = (_mexpand(term) + o).removeO() s.append(term) return Add(*s) + o return super(besselj, self)._eval_nseries(x, n, logx, cdir) class bessely(BesselBase): r""" Bessel function of the second kind. Explanation =========== The Bessel $Y$ function of order $\nu$ is defined as .. math :: Y_\nu(z) = \lim_{\mu \to \nu} \frac{J_\mu(z) \cos(\pi \mu) - J_{-\mu}(z)}{\sin(\pi \mu)}, where $J_\mu(z)$ is the Bessel function of the first kind. It is a solution to Bessel's equation, and linearly independent from $J_\nu$. Examples ======== >>> from sympy import bessely, yn >>> from sympy.abc import z, n >>> b = bessely(n, z) >>> b.diff(z) bessely(n - 1, z)/2 - bessely(n + 1, z)/2 >>> b.rewrite(yn) sqrt(2)*sqrt(z)*yn(n - 1/2, z)/sqrt(pi) See Also ======== besselj, besseli, besselk References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselY/ """ _a = S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.NegativeInfinity elif re(nu).is_zero is False: return S.ComplexInfinity elif re(nu).is_zero: return S.NaN if z in (S.Infinity, S.NegativeInfinity): return S.Zero if nu.is_integer: if nu.could_extract_minus_sign(): return S.NegativeOne**(-nu)*bessely(-nu, z) def _eval_rewrite_as_besselj(self, nu, z, **kwargs): if nu.is_integer is False: return csc(pi*nu)*(cos(pi*nu)*besselj(nu, z) - besselj(-nu, z)) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(besseli) def _eval_rewrite_as_yn(self, nu, z, **kwargs): return sqrt(2*z/pi) * yn(nu - S.Half, self.argument) def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args term_one = ((2/pi)*log(z/2)*besselj(nu, z)) term_two = (z/2)**(-nu)*factorial(nu - 1)/pi if (nu - 1).is_positive else S.Zero term_three = (z/2)**nu/(pi*factorial(nu))*(digamma(nu + 1) - S.EulerGamma) arg = Add(*[term_one, term_two, term_three]).as_leading_term(x) if x in arg.free_symbols: return arg else: return self.func(nu, z.subs(x, 0).cancel()) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_positive: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive and nu.is_integer: newn = ceiling(n/exp) bn = besselj(nu, z) a = ((2/pi)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir) b, c = [], [] o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() if nu > S.One: term = r**(-nu)*factorial(nu - 1)/pi b.append(term) for k in range(1, nu - 1): term *= t*(nu - k - 1)/k term = (_mexpand(term) + o).removeO() b.append(term) p = r**nu/(pi*factorial(nu)) term = p*(digamma(nu + 1) - S.EulerGamma) c.append(term) for k in range(1, (newn + 1)//2): p *= -t/(k*(k + nu)) p = (_mexpand(p) + o).removeO() term = p*(digamma(k + nu + 1) + digamma(k + 1)) c.append(term) return a - Add(*b) - Add(*c) # Order term comes from a return super(bessely, self)._eval_nseries(x, n, logx, cdir) class besseli(BesselBase): r""" Modified Bessel function of the first kind. Explanation =========== The Bessel $I$ function is a solution to the modified Bessel equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 + \nu^2)^2 w = 0. It can be defined as .. math :: I_\nu(z) = i^{-\nu} J_\nu(iz), where $J_\nu(z)$ is the Bessel function of the first kind. Examples ======== >>> from sympy import besseli >>> from sympy.abc import z, n >>> besseli(n, z).diff(z) besseli(n - 1, z)/2 + besseli(n + 1, z)/2 See Also ======== besselj, bessely, besselk References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselI/ """ _a = -S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive: return S.Zero elif re(nu).is_negative and not (nu.is_integer is True): return S.ComplexInfinity elif nu.is_imaginary: return S.NaN if im(z) in (S.Infinity, S.NegativeInfinity): return S.Zero if z.could_extract_minus_sign(): return (z)**nu*(-z)**(-nu)*besseli(nu, -z) if nu.is_integer: if nu.could_extract_minus_sign(): return besseli(-nu, z) newz = z.extract_multiplicatively(I) if newz: # NOTE we don't want to change the function if z==0 return I**(-nu)*besselj(nu, -newz) # branch handling: if nu.is_integer: newz = unpolarify(z) if newz != z: return besseli(nu, newz) else: newz, n = z.extract_branch_factor() if n != 0: return exp(2*n*pi*nu*I)*besseli(nu, newz) nnu = unpolarify(nu) if nu != nnu: return besseli(nnu, z) def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return exp(-I*pi*nu/2)*besselj(nu, polar_lift(I)*z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(bessely) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return self._eval_rewrite_as_besselj(*self.args).rewrite(jn) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_extended_real: return True class besselk(BesselBase): r""" Modified Bessel function of the second kind. Explanation =========== The Bessel $K$ function of order $\nu$ is defined as .. math :: K_\nu(z) = \lim_{\mu \to \nu} \frac{\pi}{2} \frac{I_{-\mu}(z) -I_\mu(z)}{\sin(\pi \mu)}, where $I_\mu(z)$ is the modified Bessel function of the first kind. It is a solution of the modified Bessel equation, and linearly independent from $Y_\nu$. Examples ======== >>> from sympy import besselk >>> from sympy.abc import z, n >>> besselk(n, z).diff(z) -besselk(n - 1, z)/2 - besselk(n + 1, z)/2 See Also ======== besselj, besseli, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselK/ """ _a = S.One _b = -S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.Infinity elif re(nu).is_zero is False: return S.ComplexInfinity elif re(nu).is_zero: return S.NaN if z in (S.Infinity, I*S.Infinity, I*S.NegativeInfinity): return S.Zero if nu.is_integer: if nu.could_extract_minus_sign(): return besselk(-nu, z) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): if nu.is_integer is False: return pi*csc(pi*nu)*(besseli(-nu, z) - besseli(nu, z))/2 def _eval_rewrite_as_besselj(self, nu, z, **kwargs): ai = self._eval_rewrite_as_besseli(*self.args) if ai: return ai.rewrite(besselj) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(bessely) def _eval_rewrite_as_yn(self, nu, z, **kwargs): ay = self._eval_rewrite_as_bessely(*self.args) if ay: return ay.rewrite(yn) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_positive: return True class hankel1(BesselBase): r""" Hankel function of the first kind. Explanation =========== This function is defined as .. math :: H_\nu^{(1)} = J_\nu(z) + iY_\nu(z), where $J_\nu(z)$ is the Bessel function of the first kind, and $Y_\nu(z)$ is the Bessel function of the second kind. It is a solution to Bessel's equation. Examples ======== >>> from sympy import hankel1 >>> from sympy.abc import z, n >>> hankel1(n, z).diff(z) hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2 See Also ======== hankel2, besselj, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH1/ """ _a = S.One _b = S.One def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return hankel2(self.order.conjugate(), z.conjugate()) class hankel2(BesselBase): r""" Hankel function of the second kind. Explanation =========== This function is defined as .. math :: H_\nu^{(2)} = J_\nu(z) - iY_\nu(z), where $J_\nu(z)$ is the Bessel function of the first kind, and $Y_\nu(z)$ is the Bessel function of the second kind. It is a solution to Bessel's equation, and linearly independent from $H_\nu^{(1)}$. Examples ======== >>> from sympy import hankel2 >>> from sympy.abc import z, n >>> hankel2(n, z).diff(z) hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2 See Also ======== hankel1, besselj, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH2/ """ _a = S.One _b = S.One def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return hankel1(self.order.conjugate(), z.conjugate()) def assume_integer_order(fn): @wraps(fn) def g(self, nu, z): if nu.is_integer: return fn(self, nu, z) return g class SphericalBesselBase(BesselBase): """ Base class for spherical Bessel functions. These are thin wrappers around ordinary Bessel functions, since spherical Bessel functions differ from the ordinary ones just by a slight change in order. To use this class, define the ``_eval_evalf()`` and ``_expand()`` methods. """ def _expand(self, **hints): """ Expand self into a polynomial. Nu is guaranteed to be Integer. """ raise NotImplementedError('expansion') def _eval_expand_func(self, **hints): if self.order.is_Integer: return self._expand(**hints) return self def fdiff(self, argindex=2): if argindex != 2: raise ArgumentIndexError(self, argindex) return self.__class__(self.order - 1, self.argument) - \ self * (self.order + 1)/self.argument def _jn(n, z): return (spherical_bessel_fn(n, z)*sin(z) + S.NegativeOne**(n + 1)*spherical_bessel_fn(-n - 1, z)*cos(z)) def _yn(n, z): # (-1)**(n + 1) * _jn(-n - 1, z) return (S.NegativeOne**(n + 1) * spherical_bessel_fn(-n - 1, z)*sin(z) - spherical_bessel_fn(n, z)*cos(z)) class jn(SphericalBesselBase): r""" Spherical Bessel function of the first kind. Explanation =========== This function is a solution to the spherical Bessel equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu + 1)) w = 0. It can be defined as .. math :: j_\nu(z) = \sqrt{\frac{\pi}{2z}} J_{\nu + \frac{1}{2}}(z), where $J_\nu(z)$ is the Bessel function of the first kind. The spherical Bessel functions of integral order are calculated using the formula: .. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z}, where the coefficients $f_n(z)$ are available as :func:`sympy.polys.orthopolys.spherical_bessel_fn`. Examples ======== >>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(jn(0, z))) sin(z)/z >>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z True >>> expand_func(jn(3, z)) (-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z) >>> jn(nu, z).rewrite(besselj) sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2 >>> jn(nu, z).rewrite(bessely) (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2 >>> jn(2, 5.2+0.3j).evalf(20) 0.099419756723640344491 - 0.054525080242173562897*I See Also ======== besselj, bessely, besselk, yn References ========== .. [1] http://dlmf.nist.gov/10.47 """ @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif nu.is_integer: if nu.is_positive: return S.Zero else: return S.ComplexInfinity if z in (S.NegativeInfinity, S.Infinity): return S.Zero def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return sqrt(pi/(2*z)) * besselj(nu + S.Half, z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): return S.NegativeOne**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z) def _eval_rewrite_as_yn(self, nu, z, **kwargs): return S.NegativeOne**(nu) * yn(-nu - 1, z) def _expand(self, **hints): return _jn(self.order, self.argument) def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(besselj)._eval_evalf(prec) class yn(SphericalBesselBase): r""" Spherical Bessel function of the second kind. Explanation =========== This function is another solution to the spherical Bessel equation, and linearly independent from $j_n$. It can be defined as .. math :: y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z), where $Y_\nu(z)$ is the Bessel function of the second kind. For integral orders $n$, $y_n$ is calculated using the formula: .. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(yn(0, z))) -cos(z)/z >>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z True >>> yn(nu, z).rewrite(besselj) (-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2 >>> yn(nu, z).rewrite(bessely) sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2 >>> yn(2, 5.2+0.3j).evalf(20) 0.18525034196069722536 + 0.014895573969924817587*I See Also ======== besselj, bessely, besselk, jn References ========== .. [1] http://dlmf.nist.gov/10.47 """ @assume_integer_order def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return S.NegativeOne**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z) @assume_integer_order def _eval_rewrite_as_bessely(self, nu, z, **kwargs): return sqrt(pi/(2*z)) * bessely(nu + S.Half, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return S.NegativeOne**(nu + 1) * jn(-nu - 1, z) def _expand(self, **hints): return _yn(self.order, self.argument) def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(bessely)._eval_evalf(prec) class SphericalHankelBase(SphericalBesselBase): @assume_integer_order def _eval_rewrite_as_besselj(self, nu, z, **kwargs): # jn +- I*yn # jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z) # yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z) hks = self._hankel_kind_sign return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) + hks*I*S.NegativeOne**(nu+1)*besselj(-nu - S.Half, z)) @assume_integer_order def _eval_rewrite_as_bessely(self, nu, z, **kwargs): # jn +- I*yn # jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z) # yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z) hks = self._hankel_kind_sign return sqrt(pi/(2*z))*(S.NegativeOne**nu*bessely(-nu - S.Half, z) + hks*I*bessely(nu + S.Half, z)) def _eval_rewrite_as_yn(self, nu, z, **kwargs): hks = self._hankel_kind_sign return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): hks = self._hankel_kind_sign return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn) def _eval_expand_func(self, **hints): if self.order.is_Integer: return self._expand(**hints) else: nu = self.order z = self.argument hks = self._hankel_kind_sign return jn(nu, z) + hks*I*yn(nu, z) def _expand(self, **hints): n = self.order z = self.argument hks = self._hankel_kind_sign # fully expanded version # return ((fn(n, z) * sin(z) + # (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn # (hks * I * (-1)**(n + 1) * # (fn(-n - 1, z) * hk * I * sin(z) + # (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn # ) return (_jn(n, z) + hks*I*_yn(n, z)).expand() def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(besselj)._eval_evalf(prec) class hn1(SphericalHankelBase): r""" Spherical Hankel function of the first kind. Explanation =========== This function is defined as .. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. For integral orders $n$, $h_n^(1)$ is calculated using the formula: .. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(hn1(nu, z))) jn(nu, z) + I*yn(nu, z) >>> print(expand_func(hn1(0, z))) sin(z)/z - I*cos(z)/z >>> print(expand_func(hn1(1, z))) -I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2 >>> hn1(nu, z).rewrite(jn) (-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z) >>> hn1(nu, z).rewrite(yn) (-1)**nu*yn(-nu - 1, z) + I*yn(nu, z) >>> hn1(nu, z).rewrite(hankel1) sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2 See Also ======== hn2, jn, yn, hankel1, hankel2 References ========== .. [1] http://dlmf.nist.gov/10.47 """ _hankel_kind_sign = S.One @assume_integer_order def _eval_rewrite_as_hankel1(self, nu, z, **kwargs): return sqrt(pi/(2*z))*hankel1(nu, z) class hn2(SphericalHankelBase): r""" Spherical Hankel function of the second kind. Explanation =========== This function is defined as .. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. For integral orders $n$, $h_n^(2)$ is calculated using the formula: .. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(hn2(nu, z))) jn(nu, z) - I*yn(nu, z) >>> print(expand_func(hn2(0, z))) sin(z)/z + I*cos(z)/z >>> print(expand_func(hn2(1, z))) I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2 >>> hn2(nu, z).rewrite(hankel2) sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2 >>> hn2(nu, z).rewrite(jn) -(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z) >>> hn2(nu, z).rewrite(yn) (-1)**nu*yn(-nu - 1, z) - I*yn(nu, z) See Also ======== hn1, jn, yn, hankel1, hankel2 References ========== .. [1] http://dlmf.nist.gov/10.47 """ _hankel_kind_sign = -S.One @assume_integer_order def _eval_rewrite_as_hankel2(self, nu, z, **kwargs): return sqrt(pi/(2*z))*hankel2(nu, z) def jn_zeros(n, k, method="sympy", dps=15): """ Zeros of the spherical Bessel function of the first kind. Explanation =========== This returns an array of zeros of $jn$ up to the $k$-th zero. * method = "sympy": uses `mpmath.besseljzero <http://mpmath.org/doc/current/functions/bessel.html#mpmath.besseljzero>`_ * method = "scipy": uses the `SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_ and `newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_ to find all roots, which is faster than computing the zeros using a general numerical solver, but it requires SciPy and only works with low precision floating point numbers. (The function used with method="sympy" is a recent addition to mpmath; before that a general solver was used.) Examples ======== >>> from sympy import jn_zeros >>> jn_zeros(2, 4, dps=5) [5.7635, 9.095, 12.323, 15.515] See Also ======== jn, yn, besselj, besselk, bessely Parameters ========== n : integer order of Bessel function k : integer number of zeros to return """ from math import pi as math_pi if method == "sympy": from mpmath import besseljzero from mpmath.libmp.libmpf import dps_to_prec prec = dps_to_prec(dps) return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec), int(l)), prec) for l in range(1, k + 1)] elif method == "scipy": from scipy.optimize import newton try: from scipy.special import spherical_jn f = lambda x: spherical_jn(n, x) except ImportError: from scipy.special import sph_jn f = lambda x: sph_jn(n, x)[0][-1] else: raise NotImplementedError("Unknown method.") def solver(f, x): if method == "scipy": root = newton(f, x) else: raise NotImplementedError("Unknown method.") return root # we need to approximate the position of the first root: root = n + math_pi # determine the first root exactly: root = solver(f, root) roots = [root] for i in range(k - 1): # estimate the position of the next root using the last root + pi: root = solver(f, root + math_pi) roots.append(root) return roots class AiryBase(Function): """ Abstract base class for Airy functions. This class is meant to reduce code duplication. """ def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real def as_real_imag(self, deep=True, **hints): z = self.args[0] zc = z.conjugate() f = self.func u = (f(z)+f(zc))/2 v = I*(f(zc)-f(z))/2 return u, v def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit class airyai(AiryBase): r""" The Airy function $\operatorname{Ai}$ of the first kind. Explanation =========== The Airy function $\operatorname{Ai}(z)$ is defined to be the function satisfying Airy's differential equation .. math:: \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0. Equivalently, for real $z$ .. math:: \operatorname{Ai}(z) := \frac{1}{\pi} \int_0^\infty \cos\left(\frac{t^3}{3} + z t\right) \mathrm{d}t. Examples ======== Create an Airy function object: >>> from sympy import airyai >>> from sympy.abc import z >>> airyai(z) airyai(z) Several special values are known: >>> airyai(0) 3**(1/3)/(3*gamma(2/3)) >>> from sympy import oo >>> airyai(oo) 0 >>> airyai(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airyai(z)) airyai(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airyai(z), z) airyaiprime(z) >>> diff(airyai(z), z, 2) z*airyai(z) Series expansion is also supported: >>> from sympy import series >>> series(airyai(z), z, 0, 3) 3**(5/6)*gamma(1/3)/(6*pi) - 3**(1/6)*z*gamma(2/3)/(2*pi) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airyai(-2).evalf(50) 0.22740742820168557599192443603787379946077222541710 Rewrite $\operatorname{Ai}(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airyai(z).rewrite(hyper) -3**(2/3)*z*hyper((), (4/3,), z**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3)) See Also ======== airybi: Airy function of the second kind. airyaiprime: Derivative of the Airy function of the first kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3))) if arg.is_zero: return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3))) def fdiff(self, argindex=1): if argindex == 1: return airyaiprime(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return ((cbrt(3)*x)**(-n)*(cbrt(3)*x)**(n + 1)*sin(pi*(n*Rational(2, 3) + Rational(4, 3)))*factorial(n) * gamma(n/3 + Rational(2, 3))/(sin(pi*(n*Rational(2, 3) + Rational(2, 3)))*factorial(n + 1)*gamma(n/3 + Rational(1, 3))) * p) else: return (S.One/(3**Rational(2, 3)*pi) * gamma((n+S.One)/S(3)) * sin(Rational(2, 3)*pi*(n+S.One)) / factorial(n) * (cbrt(3)*x)**n) def _eval_rewrite_as_besselj(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return ot*sqrt(-z) * (besselj(-ot, tt*a) + besselj(ot, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(z, Rational(3, 2)) if re(z).is_positive: return ot*sqrt(z) * (besseli(-ot, tt*a) - besseli(ot, tt*a)) else: return ot*(Pow(a, ot)*besseli(-ot, tt*a) - z*Pow(a, -ot)*besseli(ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = S.One / (3**Rational(2, 3)*gamma(Rational(2, 3))) pf2 = z / (root(3, 3)*gamma(Rational(1, 3))) return pf1 * hyper([], [Rational(2, 3)], z**3/9) - pf2 * hyper([], [Rational(4, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is given by 03.05.16.0001.01 # http://functions.wolfram.com/Bessel-TypeFunctions/AiryAi/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d * z**n)**m / (d**m * z**(m*n)) newarg = c * d**m * z**(m*n) return S.Half * ((pf + S.One)*airyai(newarg) - (pf - S.One)/sqrt(3)*airybi(newarg)) class airybi(AiryBase): r""" The Airy function $\operatorname{Bi}$ of the second kind. Explanation =========== The Airy function $\operatorname{Bi}(z)$ is defined to be the function satisfying Airy's differential equation .. math:: \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0. Equivalently, for real $z$ .. math:: \operatorname{Bi}(z) := \frac{1}{\pi} \int_0^\infty \exp\left(-\frac{t^3}{3} + z t\right) + \sin\left(\frac{t^3}{3} + z t\right) \mathrm{d}t. Examples ======== Create an Airy function object: >>> from sympy import airybi >>> from sympy.abc import z >>> airybi(z) airybi(z) Several special values are known: >>> airybi(0) 3**(5/6)/(3*gamma(2/3)) >>> from sympy import oo >>> airybi(oo) oo >>> airybi(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airybi(z)) airybi(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airybi(z), z) airybiprime(z) >>> diff(airybi(z), z, 2) z*airybi(z) Series expansion is also supported: >>> from sympy import series >>> series(airybi(z), z, 0, 3) 3**(1/3)*gamma(1/3)/(2*pi) + 3**(2/3)*z*gamma(2/3)/(2*pi) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airybi(-2).evalf(50) -0.41230258795639848808323405461146104203453483447240 Rewrite $\operatorname{Bi}(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airybi(z).rewrite(hyper) 3**(1/6)*z*hyper((), (4/3,), z**3/9)/gamma(1/3) + 3**(5/6)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3)) See Also ======== airyai: Airy function of the first kind. airyaiprime: Derivative of the Airy function of the first kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3))) if arg.is_zero: return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3))) def fdiff(self, argindex=1): if argindex == 1: return airybiprime(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (cbrt(3)*x * Abs(sin(Rational(2, 3)*pi*(n + S.One))) * factorial((n - S.One)/S(3)) / ((n + S.One) * Abs(cos(Rational(2, 3)*pi*(n + S.Half))) * factorial((n - 2)/S(3))) * p) else: return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(Rational(2, 3)*pi*(n + S.One))) / factorial(n) * (cbrt(3)*x)**n) def _eval_rewrite_as_besselj(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(z, Rational(3, 2)) if re(z).is_positive: return sqrt(z)/sqrt(3) * (besseli(-ot, tt*a) + besseli(ot, tt*a)) else: b = Pow(a, ot) c = Pow(a, -ot) return sqrt(ot)*(b*besseli(-ot, tt*a) + z*c*besseli(ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = S.One / (root(3, 6)*gamma(Rational(2, 3))) pf2 = z*root(3, 6) / gamma(Rational(1, 3)) return pf1 * hyper([], [Rational(2, 3)], z**3/9) + pf2 * hyper([], [Rational(4, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is given by 03.06.16.0001.01 # http://functions.wolfram.com/Bessel-TypeFunctions/AiryBi/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d * z**n)**m / (d**m * z**(m*n)) newarg = c * d**m * z**(m*n) return S.Half * (sqrt(3)*(S.One - pf)*airyai(newarg) + (S.One + pf)*airybi(newarg)) class airyaiprime(AiryBase): r""" The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first kind. Explanation =========== The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the function .. math:: \operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operatorname{Ai}(z)}{\mathrm{d} z}. Examples ======== Create an Airy function object: >>> from sympy import airyaiprime >>> from sympy.abc import z >>> airyaiprime(z) airyaiprime(z) Several special values are known: >>> airyaiprime(0) -3**(2/3)/(3*gamma(1/3)) >>> from sympy import oo >>> airyaiprime(oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airyaiprime(z)) airyaiprime(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airyaiprime(z), z) z*airyai(z) >>> diff(airyaiprime(z), z, 2) z*airyaiprime(z) + airyai(z) Series expansion is also supported: >>> from sympy import series >>> series(airyaiprime(z), z, 0, 3) -3**(2/3)/(3*gamma(1/3)) + 3**(1/3)*z**2/(6*gamma(2/3)) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airyaiprime(-2).evalf(50) 0.61825902074169104140626429133247528291577794512415 Rewrite $\operatorname{Ai}^\prime(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airyaiprime(z).rewrite(hyper) 3**(1/3)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) - 3**(2/3)*hyper((), (1/3,), z**3/9)/(3*gamma(1/3)) See Also ======== airyai: Airy function of the first kind. airybi: Airy function of the second kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero if arg.is_zero: return S.NegativeOne / (3**Rational(1, 3) * gamma(Rational(1, 3))) def fdiff(self, argindex=1): if argindex == 1: return self.args[0]*airyai(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): z = self.args[0]._to_mpmath(prec) with workprec(prec): res = mp.airyai(z, derivative=1) return Expr._from_mpmath(res, prec) def _eval_rewrite_as_besselj(self, z, **kwargs): tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return z/3 * (besselj(-tt, tt*a) - besselj(tt, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = tt * Pow(z, Rational(3, 2)) if re(z).is_positive: return z/3 * (besseli(tt, a) - besseli(-tt, a)) else: a = Pow(z, Rational(3, 2)) b = Pow(a, tt) c = Pow(a, -tt) return ot * (z**2*c*besseli(tt, tt*a) - b*besseli(-ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = z**2 / (2*3**Rational(2, 3)*gamma(Rational(2, 3))) pf2 = 1 / (root(3, 3)*gamma(Rational(1, 3))) return pf1 * hyper([], [Rational(5, 3)], z**3/9) - pf2 * hyper([], [Rational(1, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is in principle # given by 03.07.16.0001.01 but note # that there is an error in this formula. # http://functions.wolfram.com/Bessel-TypeFunctions/AiryAiPrime/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d**m * z**(n*m)) / (d * z**n)**m newarg = c * d**m * z**(n*m) return S.Half * ((pf + S.One)*airyaiprime(newarg) + (pf - S.One)/sqrt(3)*airybiprime(newarg)) class airybiprime(AiryBase): r""" The derivative $\operatorname{Bi}^\prime$ of the Airy function of the first kind. Explanation =========== The Airy function $\operatorname{Bi}^\prime(z)$ is defined to be the function .. math:: \operatorname{Bi}^\prime(z) := \frac{\mathrm{d} \operatorname{Bi}(z)}{\mathrm{d} z}. Examples ======== Create an Airy function object: >>> from sympy import airybiprime >>> from sympy.abc import z >>> airybiprime(z) airybiprime(z) Several special values are known: >>> airybiprime(0) 3**(1/6)/gamma(1/3) >>> from sympy import oo >>> airybiprime(oo) oo >>> airybiprime(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airybiprime(z)) airybiprime(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airybiprime(z), z) z*airybi(z) >>> diff(airybiprime(z), z, 2) z*airybiprime(z) + airybi(z) Series expansion is also supported: >>> from sympy import series >>> series(airybiprime(z), z, 0, 3) 3**(1/6)/gamma(1/3) + 3**(5/6)*z**2/(6*gamma(2/3)) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airybiprime(-2).evalf(50) 0.27879516692116952268509756941098324140300059345163 Rewrite $\operatorname{Bi}^\prime(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airybiprime(z).rewrite(hyper) 3**(5/6)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) + 3**(1/6)*hyper((), (1/3,), z**3/9)/gamma(1/3) See Also ======== airyai: Airy function of the first kind. airybi: Airy function of the second kind. airyaiprime: Derivative of the Airy function of the first kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return 3**Rational(1, 6) / gamma(Rational(1, 3)) if arg.is_zero: return 3**Rational(1, 6) / gamma(Rational(1, 3)) def fdiff(self, argindex=1): if argindex == 1: return self.args[0]*airybi(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): z = self.args[0]._to_mpmath(prec) with workprec(prec): res = mp.airybi(z, derivative=1) return Expr._from_mpmath(res, prec) def _eval_rewrite_as_besselj(self, z, **kwargs): tt = Rational(2, 3) a = tt * Pow(-z, Rational(3, 2)) if re(z).is_negative: return -z/sqrt(3) * (besselj(-tt, a) + besselj(tt, a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = tt * Pow(z, Rational(3, 2)) if re(z).is_positive: return z/sqrt(3) * (besseli(-tt, a) + besseli(tt, a)) else: a = Pow(z, Rational(3, 2)) b = Pow(a, tt) c = Pow(a, -tt) return sqrt(ot) * (b*besseli(-tt, tt*a) + z**2*c*besseli(tt, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = z**2 / (2*root(3, 6)*gamma(Rational(2, 3))) pf2 = root(3, 6) / gamma(Rational(1, 3)) return pf1 * hyper([], [Rational(5, 3)], z**3/9) + pf2 * hyper([], [Rational(1, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is in principle # given by 03.08.16.0001.01 but note # that there is an error in this formula. # http://functions.wolfram.com/Bessel-TypeFunctions/AiryBiPrime/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d**m * z**(n*m)) / (d * z**n)**m newarg = c * d**m * z**(n*m) return S.Half * (sqrt(3)*(pf - S.One)*airyaiprime(newarg) + (pf + S.One)*airybiprime(newarg)) class marcumq(Function): r""" The Marcum Q-function. Explanation =========== The Marcum Q-function is defined by the meromorphic continuation of .. math:: Q_m(a, b) = a^{- m + 1} \int_{b}^{\infty} x^{m} e^{- \frac{a^{2}}{2} - \frac{x^{2}}{2}} I_{m - 1}\left(a x\right)\, dx Examples ======== >>> from sympy import marcumq >>> from sympy.abc import m, a, b >>> marcumq(m, a, b) marcumq(m, a, b) Special values: >>> marcumq(m, 0, b) uppergamma(m, b**2/2)/gamma(m) >>> marcumq(0, 0, 0) 0 >>> marcumq(0, a, 0) 1 - exp(-a**2/2) >>> marcumq(1, a, a) 1/2 + exp(-a**2)*besseli(0, a**2)/2 >>> marcumq(2, a, a) 1/2 + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) Differentiation with respect to $a$ and $b$ is supported: >>> from sympy import diff >>> diff(marcumq(m, a, b), a) a*(-marcumq(m, a, b) + marcumq(m + 1, a, b)) >>> diff(marcumq(m, a, b), b) -a**(1 - m)*b**m*exp(-a**2/2 - b**2/2)*besseli(m - 1, a*b) References ========== .. [1] https://en.wikipedia.org/wiki/Marcum_Q-function .. [2] http://mathworld.wolfram.com/MarcumQ-Function.html """ @classmethod def eval(cls, m, a, b): if a is S.Zero: if m is S.Zero and b is S.Zero: return S.Zero return uppergamma(m, b**2 * S.Half) / gamma(m) if m is S.Zero and b is S.Zero: return 1 - 1 / exp(a**2 * S.Half) if a == b: if m is S.One: return (1 + exp(-a**2) * besseli(0, a**2))*S.Half if m == 2: return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2) if a.is_zero: if m.is_zero and b.is_zero: return S.Zero return uppergamma(m, b**2*S.Half) / gamma(m) if m.is_zero and b.is_zero: return 1 - 1 / exp(a**2*S.Half) def fdiff(self, argindex=2): m, a, b = self.args if argindex == 2: return a * (-marcumq(m, a, b) + marcumq(1+m, a, b)) elif argindex == 3: return (-b**m / a**(m-1)) * exp(-(a**2 + b**2)/2) * besseli(m-1, a*b) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Integral(self, m, a, b, **kwargs): from sympy.integrals.integrals import Integral x = kwargs.get('x', Dummy('x')) return a ** (1 - m) * \ Integral(x**m * exp(-(x**2 + a**2)/2) * besseli(m-1, a*x), [x, b, S.Infinity]) def _eval_rewrite_as_Sum(self, m, a, b, **kwargs): from sympy.concrete.summations import Sum k = kwargs.get('k', Dummy('k')) return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, S.Infinity]) def _eval_rewrite_as_besseli(self, m, a, b, **kwargs): if a == b: if m == 1: return (1 + exp(-a**2) * besseli(0, a**2)) / 2 if m.is_Integer and m >= 2: s = sum([besseli(i, a**2) for i in range(1, m)]) return S.Half + exp(-a**2) * besseli(0, a**2) / 2 + exp(-a**2) * s def _eval_is_zero(self): if all(arg.is_zero for arg in self.args): return True
13861808f0078073413523702fc2e660bb97f1cbfdef125d4df9cb0c785351a6
from sympy.core import S, Integer from sympy.core.function import Function from sympy.core.logic import fuzzy_not from sympy.core.mul import prod from sympy.core.relational import Ne from sympy.core.sorting import default_sort_key from sympy.external.gmpy import SYMPY_INTS from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.piecewise import Piecewise from sympy.utilities.iterables import has_dups ############################################################################### ###################### Kronecker Delta, Levi-Civita etc. ###################### ############################################################################### def Eijk(*args, **kwargs): """ Represent the Levi-Civita symbol. This is a compatibility wrapper to ``LeviCivita()``. See Also ======== LeviCivita """ return LeviCivita(*args, **kwargs) def eval_levicivita(*args): """Evaluate Levi-Civita symbol.""" n = len(args) return prod( prod(args[j] - args[i] for j in range(i + 1, n)) / factorial(i) for i in range(n)) # converting factorial(i) to int is slightly faster class LeviCivita(Function): """ Represent the Levi-Civita symbol. Explanation =========== For even permutations of indices it returns 1, for odd permutations -1, and for everything else (a repeated index) it returns 0. Thus it represents an alternating pseudotensor. Examples ======== >>> from sympy import LeviCivita >>> from sympy.abc import i, j, k >>> LeviCivita(1, 2, 3) 1 >>> LeviCivita(1, 3, 2) -1 >>> LeviCivita(1, 2, 2) 0 >>> LeviCivita(i, j, k) LeviCivita(i, j, k) >>> LeviCivita(i, j, i) 0 See Also ======== Eijk """ is_integer = True @classmethod def eval(cls, *args): if all(isinstance(a, (SYMPY_INTS, Integer)) for a in args): return eval_levicivita(*args) if has_dups(args): return S.Zero def doit(self): return eval_levicivita(*self.args) class KroneckerDelta(Function): """ The discrete, or Kronecker, delta function. Explanation =========== A function that takes in two integers $i$ and $j$. It returns $0$ if $i$ and $j$ are not equal, or it returns $1$ if $i$ and $j$ are equal. Examples ======== An example with integer indices: >>> from sympy import KroneckerDelta >>> KroneckerDelta(1, 2) 0 >>> KroneckerDelta(3, 3) 1 Symbolic indices: >>> from sympy.abc import i, j, k >>> KroneckerDelta(i, j) KroneckerDelta(i, j) >>> KroneckerDelta(i, i) 1 >>> KroneckerDelta(i, i + 1) 0 >>> KroneckerDelta(i, i + 1 + k) KroneckerDelta(i, i + k + 1) Parameters ========== i : Number, Symbol The first index of the delta function. j : Number, Symbol The second index of the delta function. See Also ======== eval DiracDelta References ========== .. [1] https://en.wikipedia.org/wiki/Kronecker_delta """ is_integer = True @classmethod def eval(cls, i, j, delta_range=None): """ Evaluates the discrete delta function. Examples ======== >>> from sympy import KroneckerDelta >>> from sympy.abc import i, j, k >>> KroneckerDelta(i, j) KroneckerDelta(i, j) >>> KroneckerDelta(i, i) 1 >>> KroneckerDelta(i, i + 1) 0 >>> KroneckerDelta(i, i + 1 + k) KroneckerDelta(i, i + k + 1) # indirect doctest """ if delta_range is not None: dinf, dsup = delta_range if (dinf - i > 0) == True: return S.Zero if (dinf - j > 0) == True: return S.Zero if (dsup - i < 0) == True: return S.Zero if (dsup - j < 0) == True: return S.Zero diff = i - j if diff.is_zero: return S.One elif fuzzy_not(diff.is_zero): return S.Zero if i.assumptions0.get("below_fermi") and \ j.assumptions0.get("above_fermi"): return S.Zero if j.assumptions0.get("below_fermi") and \ i.assumptions0.get("above_fermi"): return S.Zero # to make KroneckerDelta canonical # following lines will check if inputs are in order # if not, will return KroneckerDelta with correct order if i != min(i, j, key=default_sort_key): if delta_range: return cls(j, i, delta_range) else: return cls(j, i) @property def delta_range(self): if len(self.args) > 2: return self.args[2] def _eval_power(self, expt): if expt.is_positive: return self if expt.is_negative and expt is not S.NegativeOne: return 1/self @property def is_above_fermi(self): """ True if Delta can be non-zero above fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_above_fermi True >>> KroneckerDelta(p, i).is_above_fermi False >>> KroneckerDelta(p, q).is_above_fermi True See Also ======== is_below_fermi, is_only_below_fermi, is_only_above_fermi """ if self.args[0].assumptions0.get("below_fermi"): return False if self.args[1].assumptions0.get("below_fermi"): return False return True @property def is_below_fermi(self): """ True if Delta can be non-zero below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_below_fermi False >>> KroneckerDelta(p, i).is_below_fermi True >>> KroneckerDelta(p, q).is_below_fermi True See Also ======== is_above_fermi, is_only_above_fermi, is_only_below_fermi """ if self.args[0].assumptions0.get("above_fermi"): return False if self.args[1].assumptions0.get("above_fermi"): return False return True @property def is_only_above_fermi(self): """ True if Delta is restricted to above fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_only_above_fermi True >>> KroneckerDelta(p, q).is_only_above_fermi False >>> KroneckerDelta(p, i).is_only_above_fermi False See Also ======== is_above_fermi, is_below_fermi, is_only_below_fermi """ return ( self.args[0].assumptions0.get("above_fermi") or self.args[1].assumptions0.get("above_fermi") ) or False @property def is_only_below_fermi(self): """ True if Delta is restricted to below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, i).is_only_below_fermi True >>> KroneckerDelta(p, q).is_only_below_fermi False >>> KroneckerDelta(p, a).is_only_below_fermi False See Also ======== is_above_fermi, is_below_fermi, is_only_above_fermi """ return ( self.args[0].assumptions0.get("below_fermi") or self.args[1].assumptions0.get("below_fermi") ) or False @property def indices_contain_equal_information(self): """ Returns True if indices are either both above or below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, q).indices_contain_equal_information True >>> KroneckerDelta(p, q+1).indices_contain_equal_information True >>> KroneckerDelta(i, p).indices_contain_equal_information False """ if (self.args[0].assumptions0.get("below_fermi") and self.args[1].assumptions0.get("below_fermi")): return True if (self.args[0].assumptions0.get("above_fermi") and self.args[1].assumptions0.get("above_fermi")): return True # if both indices are general we are True, else false return self.is_below_fermi and self.is_above_fermi @property def preferred_index(self): """ Returns the index which is preferred to keep in the final expression. Explanation =========== The preferred index is the index with more information regarding fermi level. If indices contain the same information, 'a' is preferred before 'b'. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> j = Symbol('j', below_fermi=True) >>> p = Symbol('p') >>> KroneckerDelta(p, i).preferred_index i >>> KroneckerDelta(p, a).preferred_index a >>> KroneckerDelta(i, j).preferred_index i See Also ======== killable_index """ if self._get_preferred_index(): return self.args[1] else: return self.args[0] @property def killable_index(self): """ Returns the index which is preferred to substitute in the final expression. Explanation =========== The index to substitute is the index with less information regarding fermi level. If indices contain the same information, 'a' is preferred before 'b'. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> j = Symbol('j', below_fermi=True) >>> p = Symbol('p') >>> KroneckerDelta(p, i).killable_index p >>> KroneckerDelta(p, a).killable_index p >>> KroneckerDelta(i, j).killable_index j See Also ======== preferred_index """ if self._get_preferred_index(): return self.args[0] else: return self.args[1] def _get_preferred_index(self): """ Returns the index which is preferred to keep in the final expression. The preferred index is the index with more information regarding fermi level. If indices contain the same information, index 0 is returned. """ if not self.is_above_fermi: if self.args[0].assumptions0.get("below_fermi"): return 0 else: return 1 elif not self.is_below_fermi: if self.args[0].assumptions0.get("above_fermi"): return 0 else: return 1 else: return 0 @property def indices(self): return self.args[0:2] def _eval_rewrite_as_Piecewise(self, *args, **kwargs): i, j = args return Piecewise((0, Ne(i, j)), (1, True))
9e5ed9b3b9a97ff3b73d5e024b584b259749e0f8cf7f0cbe098dc2ca78628973
""" This module contains various functions that are special cases of incomplete gamma functions. It should probably be renamed. """ from sympy.core import Add, S, sympify, cacheit, pi, I, Rational, EulerGamma from sympy.core.function import Function, ArgumentIndexError, expand_mul from sympy.core.relational import is_eq from sympy.core.power import Pow from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import factorial, factorial2, RisingFactorial from sympy.functions.elementary.complexes import polar_lift, re, unpolarify from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import sqrt, root from sympy.functions.elementary.exponential import exp, log, exp_polar from sympy.functions.elementary.hyperbolic import cosh, sinh from sympy.functions.elementary.trigonometric import cos, sin, sinc from sympy.functions.special.hyper import hyper, meijerg # TODO series expansions # TODO see the "Note:" in Ei # Helper function def real_to_real_as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: x, y = self.args[0].expand(deep, **hints).as_real_imag() else: x, y = self.args[0].as_real_imag() re = (self.func(x + I*y) + self.func(x - I*y))/2 im = (self.func(x + I*y) - self.func(x - I*y))/(2*I) return (re, im) ############################################################################### ################################ ERROR FUNCTION ############################### ############################################################################### class erf(Function): r""" The Gauss error function. Explanation =========== This function is defined as: .. math :: \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} \mathrm{d}t. Examples ======== >>> from sympy import I, oo, erf >>> from sympy.abc import z Several special values are known: >>> erf(0) 0 >>> erf(oo) 1 >>> erf(-oo) -1 >>> erf(I*oo) oo*I >>> erf(-I*oo) -oo*I In general one can pull out factors of -1 and $I$ from the argument: >>> erf(-z) -erf(z) The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erf(z)) erf(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erf(z), z) 2*exp(-z**2)/sqrt(pi) We can numerically evaluate the error function to arbitrary precision on the whole complex plane: >>> erf(4).evalf(30) 0.999999984582742099719981147840 >>> erf(-4*I).evalf(30) -1296959.73071763923152794095062*I See Also ======== erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/Erf.html .. [4] http://functions.wolfram.com/GammaBetaErf/Erf """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return 2*exp(-self.args[0]**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfinv @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.Zero if isinstance(arg, erfinv): return arg.args[0] if isinstance(arg, erfcinv): return S.One - arg.args[0] if arg.is_zero: return S.Zero # Only happens with unevaluated erf2inv if isinstance(arg, erf2inv) and arg.args[0].is_zero: return arg.args[1] # Try to pull out factors of I t = arg.extract_multiplicatively(S.ImaginaryUnit) if t in (S.Infinity, S.NegativeInfinity): return arg # Try to pull out factors of -1 if arg.could_extract_minus_sign(): return -cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return -previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return 2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(S.Pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): return self.args[0].is_extended_real def _eval_is_finite(self): if self.args[0].is_finite: return True else: return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(S.Pi)) def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi) return (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi) return (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2) def _eval_rewrite_as_expint(self, z, **kwargs): return sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): from sympy.series.limits import limit if limitvar: lim = limit(z, limitvar, S.Infinity) if lim is S.NegativeInfinity: return S.NegativeOne + _erfs(-z)*exp(-z**2) return S.One - _erfs(z)*exp(-z**2) def _eval_rewrite_as_erfc(self, z, **kwargs): return S.One - erfc(z) def _eval_rewrite_as_erfi(self, z, **kwargs): return -I*erfi(I*z) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+') if x in arg.free_symbols and arg0.is_zero: return 2*arg/sqrt(pi) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point in [S.Infinity, S.NegativeInfinity]: z = self.args[0] try: _, ex = z.leadterm(x) except (ValueError, NotImplementedError): return self ex = -ex # as x->1/x for aseries if ex.is_positive: newn = ceiling(n/ex) s = [S.NegativeOne**k * factorial2(2*k - 1) / (z**(2*k + 1) * 2**k) for k in range(0, newn)] + [Order(1/z**newn, x)] return S.One - (exp(-z**2)/sqrt(pi)) * Add(*s) return super(erf, self)._eval_aseries(n, args0, x, logx) as_real_imag = real_to_real_as_real_imag class erfc(Function): r""" Complementary Error Function. Explanation =========== The function is defined as: .. math :: \mathrm{erfc}(x) = \frac{2}{\sqrt{\pi}} \int_x^\infty e^{-t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfc >>> from sympy.abc import z Several special values are known: >>> erfc(0) 1 >>> erfc(oo) 0 >>> erfc(-oo) 2 >>> erfc(I*oo) -oo*I >>> erfc(-I*oo) oo*I The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erfc(z)) erfc(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erfc(z), z) -2*exp(-z**2)/sqrt(pi) It also follows >>> erfc(-z) 2 - erfc(z) We can numerically evaluate the complementary error function to arbitrary precision on the whole complex plane: >>> erfc(4).evalf(30) 0.0000000154172579002800188521596734869 >>> erfc(4*I).evalf(30) 1.0 - 1296959.73071763923152794095062*I See Also ======== erf: Gaussian error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/Erfc.html .. [4] http://functions.wolfram.com/GammaBetaErf/Erfc """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return -2*exp(-self.args[0]**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfcinv @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg.is_zero: return S.One if isinstance(arg, erfinv): return S.One - arg.args[0] if isinstance(arg, erfcinv): return arg.args[0] if arg.is_zero: return S.One # Try to pull out factors of I t = arg.extract_multiplicatively(S.ImaginaryUnit) if t in (S.Infinity, S.NegativeInfinity): return -arg # Try to pull out factors of -1 if arg.could_extract_minus_sign(): return 2 - cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.One elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return -previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return -2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(S.Pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): return self.args[0].is_extended_real def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar) def _eval_rewrite_as_erf(self, z, **kwargs): return S.One - erf(z) def _eval_rewrite_as_erfi(self, z, **kwargs): return S.One + I*erfi(I*z) def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi) return S.One - (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One-S.ImaginaryUnit)*z/sqrt(pi) return S.One - (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return S.One - z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return S.One - 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return S.One - sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(S.Pi)) def _eval_rewrite_as_expint(self, z, **kwargs): return S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi) def _eval_expand_func(self, **hints): return self.rewrite(erf) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+') if arg0.is_zero: return S.One else: return self.func(arg0) as_real_imag = real_to_real_as_real_imag def _eval_aseries(self, n, args0, x, logx): return S.One - erf(*self.args)._eval_aseries(n, args0, x, logx) class erfi(Function): r""" Imaginary error function. Explanation =========== The function erfi is defined as: .. math :: \mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfi >>> from sympy.abc import z Several special values are known: >>> erfi(0) 0 >>> erfi(oo) oo >>> erfi(-oo) -oo >>> erfi(I*oo) I >>> erfi(-I*oo) -I In general one can pull out factors of -1 and $I$ from the argument: >>> erfi(-z) -erfi(z) >>> from sympy import conjugate >>> conjugate(erfi(z)) erfi(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erfi(z), z) 2*exp(z**2)/sqrt(pi) We can numerically evaluate the imaginary error function to arbitrary precision on the whole complex plane: >>> erfi(2).evalf(30) 18.5648024145755525987042919132 >>> erfi(-2*I).evalf(30) -0.995322265018952734162069256367*I See Also ======== erf: Gaussian error function. erfc: Complementary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://mathworld.wolfram.com/Erfi.html .. [3] http://functions.wolfram.com/GammaBetaErf/Erfi """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return 2*exp(self.args[0]**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, z): if z.is_Number: if z is S.NaN: return S.NaN elif z.is_zero: return S.Zero elif z is S.Infinity: return S.Infinity if z.is_zero: return S.Zero # Try to pull out factors of -1 if z.could_extract_minus_sign(): return -cls(-z) # Try to pull out factors of I nz = z.extract_multiplicatively(I) if nz is not None: if nz is S.Infinity: return I if isinstance(nz, erfinv): return I*nz.args[0] if isinstance(nz, erfcinv): return I*(S.One - nz.args[0]) # Only happens with unevaluated erf2inv if isinstance(nz, erf2inv) and nz.args[0].is_zero: return I*nz.args[1] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return 2 * x**n/(n*factorial(k)*sqrt(S.Pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar) def _eval_rewrite_as_erf(self, z, **kwargs): return -I*erf(I*z) def _eval_rewrite_as_erfc(self, z, **kwargs): return I*erfc(I*z) - I def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One + S.ImaginaryUnit)*z/sqrt(pi) return (S.One - S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One + S.ImaginaryUnit)*z/sqrt(pi) return (S.One - S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], z**2) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(S.Pi) - S.One) def _eval_rewrite_as_expint(self, z, **kwargs): return sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi) def _eval_expand_func(self, **hints): return self.rewrite(erf) as_real_imag = real_to_real_as_real_imag def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if x in arg.free_symbols and arg0.is_zero: return 2*arg/sqrt(pi) elif arg0.is_finite: return self.func(arg0) return self.func(arg) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point is S.Infinity: z = self.args[0] s = [factorial2(2*k - 1) / (2**k * z**(2*k + 1)) for k in range(0, n)] + [Order(1/z**n, x)] return -S.ImaginaryUnit + (exp(z**2)/sqrt(pi)) * Add(*s) return super(erfi, self)._eval_aseries(n, args0, x, logx) class erf2(Function): r""" Two-argument error function. Explanation =========== This function is defined as: .. math :: \mathrm{erf2}(x, y) = \frac{2}{\sqrt{\pi}} \int_x^y e^{-t^2} \mathrm{d}t Examples ======== >>> from sympy import oo, erf2 >>> from sympy.abc import x, y Several special values are known: >>> erf2(0, 0) 0 >>> erf2(x, x) 0 >>> erf2(x, oo) 1 - erf(x) >>> erf2(x, -oo) -erf(x) - 1 >>> erf2(oo, y) erf(y) - 1 >>> erf2(-oo, y) erf(y) + 1 In general one can pull out factors of -1: >>> erf2(-x, -y) -erf2(x, y) The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erf2(x, y)) erf2(conjugate(x), conjugate(y)) Differentiation with respect to $x$, $y$ is supported: >>> from sympy import diff >>> diff(erf2(x, y), x) -2*exp(-x**2)/sqrt(pi) >>> diff(erf2(x, y), y) 2*exp(-y**2)/sqrt(pi) See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] http://functions.wolfram.com/GammaBetaErf/Erf2/ """ def fdiff(self, argindex): x, y = self.args if argindex == 1: return -2*exp(-x**2)/sqrt(S.Pi) elif argindex == 2: return 2*exp(-y**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y): chk = (S.Infinity, S.NegativeInfinity, S.Zero) if x is S.NaN or y is S.NaN: return S.NaN elif x == y: return S.Zero elif x in chk or y in chk: return erf(y) - erf(x) if isinstance(y, erf2inv) and y.args[0] == x: return y.args[1] if x.is_zero or y.is_zero or x.is_extended_real and x.is_infinite or \ y.is_extended_real and y.is_infinite: return erf(y) - erf(x) #Try to pull out -1 factor sign_x = x.could_extract_minus_sign() sign_y = y.could_extract_minus_sign() if (sign_x and sign_y): return -cls(-x, -y) elif (sign_x or sign_y): return erf(y)-erf(x) def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_rewrite_as_erf(self, x, y, **kwargs): return erf(y) - erf(x) def _eval_rewrite_as_erfc(self, x, y, **kwargs): return erfc(x) - erfc(y) def _eval_rewrite_as_erfi(self, x, y, **kwargs): return I*(erfi(I*x)-erfi(I*y)) def _eval_rewrite_as_fresnels(self, x, y, **kwargs): return erf(y).rewrite(fresnels) - erf(x).rewrite(fresnels) def _eval_rewrite_as_fresnelc(self, x, y, **kwargs): return erf(y).rewrite(fresnelc) - erf(x).rewrite(fresnelc) def _eval_rewrite_as_meijerg(self, x, y, **kwargs): return erf(y).rewrite(meijerg) - erf(x).rewrite(meijerg) def _eval_rewrite_as_hyper(self, x, y, **kwargs): return erf(y).rewrite(hyper) - erf(x).rewrite(hyper) def _eval_rewrite_as_uppergamma(self, x, y, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return (sqrt(y**2)/y*(S.One - uppergamma(S.Half, y**2)/sqrt(S.Pi)) - sqrt(x**2)/x*(S.One - uppergamma(S.Half, x**2)/sqrt(S.Pi))) def _eval_rewrite_as_expint(self, x, y, **kwargs): return erf(y).rewrite(expint) - erf(x).rewrite(expint) def _eval_expand_func(self, **hints): return self.rewrite(erf) def _eval_is_zero(self): return is_eq(*self.args) class erfinv(Function): r""" Inverse Error Function. The erfinv function is defined as: .. math :: \mathrm{erf}(x) = y \quad \Rightarrow \quad \mathrm{erfinv}(y) = x Examples ======== >>> from sympy import erfinv >>> from sympy.abc import x Several special values are known: >>> erfinv(0) 0 >>> erfinv(1) oo Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(erfinv(x), x) sqrt(pi)*exp(erfinv(x)**2)/2 We can numerically evaluate the inverse error function to arbitrary precision on [-1, 1]: >>> erfinv(0.2).evalf(30) 0.179143454621291692285822705344 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErf/ """ def fdiff(self, argindex =1): if argindex == 1: return sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half else : raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erf @classmethod def eval(cls, z): if z is S.NaN: return S.NaN elif z is S.NegativeOne: return S.NegativeInfinity elif z.is_zero: return S.Zero elif z is S.One: return S.Infinity if isinstance(z, erf) and z.args[0].is_extended_real: return z.args[0] if z.is_zero: return S.Zero # Try to pull out factors of -1 nz = z.extract_multiplicatively(-1) if nz is not None and (isinstance(nz, erf) and (nz.args[0]).is_extended_real): return -nz.args[0] def _eval_rewrite_as_erfcinv(self, z, **kwargs): return erfcinv(1-z) def _eval_is_zero(self): return self.args[0].is_zero class erfcinv (Function): r""" Inverse Complementary Error Function. The erfcinv function is defined as: .. math :: \mathrm{erfc}(x) = y \quad \Rightarrow \quad \mathrm{erfcinv}(y) = x Examples ======== >>> from sympy import erfcinv >>> from sympy.abc import x Several special values are known: >>> erfcinv(1) 0 >>> erfcinv(0) oo Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(erfcinv(x), x) -sqrt(pi)*exp(erfcinv(x)**2)/2 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErfc/ """ def fdiff(self, argindex =1): if argindex == 1: return -sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfc @classmethod def eval(cls, z): if z is S.NaN: return S.NaN elif z.is_zero: return S.Infinity elif z is S.One: return S.Zero elif z == 2: return S.NegativeInfinity if z.is_zero: return S.Infinity def _eval_rewrite_as_erfinv(self, z, **kwargs): return erfinv(1-z) def _eval_is_zero(self): return (self.args[0] - 1).is_zero def _eval_is_infinite(self): return self.args[0].is_zero class erf2inv(Function): r""" Two-argument Inverse error function. The erf2inv function is defined as: .. math :: \mathrm{erf2}(x, w) = y \quad \Rightarrow \quad \mathrm{erf2inv}(x, y) = w Examples ======== >>> from sympy import erf2inv, oo >>> from sympy.abc import x, y Several special values are known: >>> erf2inv(0, 0) 0 >>> erf2inv(1, 0) 1 >>> erf2inv(0, 1) oo >>> erf2inv(0, y) erfinv(y) >>> erf2inv(oo, y) erfcinv(-y) Differentiation with respect to $x$ and $y$ is supported: >>> from sympy import diff >>> diff(erf2inv(x, y), x) exp(-x**2 + erf2inv(x, y)**2) >>> diff(erf2inv(x, y), y) sqrt(pi)*exp(erf2inv(x, y)**2)/2 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse complementary error function. References ========== .. [1] http://functions.wolfram.com/GammaBetaErf/InverseErf2/ """ def fdiff(self, argindex): x, y = self.args if argindex == 1: return exp(self.func(x,y)**2-x**2) elif argindex == 2: return sqrt(S.Pi)*S.Half*exp(self.func(x,y)**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y): if x is S.NaN or y is S.NaN: return S.NaN elif x.is_zero and y.is_zero: return S.Zero elif x.is_zero and y is S.One: return S.Infinity elif x is S.One and y.is_zero: return S.One elif x.is_zero: return erfinv(y) elif x is S.Infinity: return erfcinv(-y) elif y.is_zero: return x elif y is S.Infinity: return erfinv(x) if x.is_zero: if y.is_zero: return S.Zero else: return erfinv(y) if y.is_zero: return x def _eval_is_zero(self): x, y = self.args if x.is_zero and y.is_zero: return True ############################################################################### #################### EXPONENTIAL INTEGRALS #################################### ############################################################################### class Ei(Function): r""" The classical exponential integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Ei}(x) = \sum_{n=1}^\infty \frac{x^n}{n\, n!} + \log(x) + \gamma, where $\gamma$ is the Euler-Mascheroni constant. If $x$ is a polar number, this defines an analytic function on the Riemann surface of the logarithm. Otherwise this defines an analytic function in the cut plane $\mathbb{C} \setminus (-\infty, 0]$. **Background** The name exponential integral comes from the following statement: .. math:: \operatorname{Ei}(x) = \int_{-\infty}^x \frac{e^t}{t} \mathrm{d}t If the integral is interpreted as a Cauchy principal value, this statement holds for $x > 0$ and $\operatorname{Ei}(x)$ as defined above. Examples ======== >>> from sympy import Ei, polar_lift, exp_polar, I, pi >>> from sympy.abc import x >>> Ei(-1) Ei(-1) This yields a real value: >>> Ei(-1).n(chop=True) -0.219383934395520 On the other hand the analytic continuation is not real: >>> Ei(polar_lift(-1)).n(chop=True) -0.21938393439552 + 3.14159265358979*I The exponential integral has a logarithmic branch point at the origin: >>> Ei(x*exp_polar(2*I*pi)) Ei(x) + 2*I*pi Differentiation is supported: >>> Ei(x).diff(x) exp(x)/x The exponential integral is related to many other special functions. For example: >>> from sympy import expint, Shi >>> Ei(x).rewrite(expint) -expint(1, x*exp_polar(I*pi)) - I*pi >>> Ei(x).rewrite(Shi) Chi(x) + Shi(x) See Also ======== expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. uppergamma: Upper incomplete gamma function. References ========== .. [1] http://dlmf.nist.gov/6.6 .. [2] https://en.wikipedia.org/wiki/Exponential_integral .. [3] Abramowitz & Stegun, section 5: http://people.math.sfu.ca/~cbm/aands/page_228.htm """ @classmethod def eval(cls, z): if z.is_zero: return S.NegativeInfinity elif z is S.Infinity: return S.Infinity elif z is S.NegativeInfinity: return S.Zero if z.is_zero: return S.NegativeInfinity nz, n = z.extract_branch_factor() if n: return Ei(nz) + 2*I*pi*n def fdiff(self, argindex=1): arg = unpolarify(self.args[0]) if argindex == 1: return exp(arg)/arg else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): if (self.args[0]/polar_lift(-1)).is_positive: return Function._eval_evalf(self, prec) + (I*pi)._eval_evalf(prec) return Function._eval_evalf(self, prec) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma # XXX this does not currently work usefully because uppergamma # immediately turns into expint return -uppergamma(0, polar_lift(-1)*z) - I*pi def _eval_rewrite_as_expint(self, z, **kwargs): return -expint(1, polar_lift(-1)*z) - I*pi def _eval_rewrite_as_li(self, z, **kwargs): if isinstance(z, log): return li(z.args[0]) # TODO: # Actually it only holds that: # Ei(z) = li(exp(z)) # for -pi < imag(z) <= pi return li(exp(z)) def _eval_rewrite_as_Si(self, z, **kwargs): if z.is_negative: return Shi(z) + Chi(z) - I*pi else: return Shi(z) + Chi(z) _eval_rewrite_as_Ci = _eval_rewrite_as_Si _eval_rewrite_as_Chi = _eval_rewrite_as_Si _eval_rewrite_as_Shi = _eval_rewrite_as_Si def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return exp(z) * _eis(z) def _eval_as_leading_term(self, x, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_Si(*self.args) return f._eval_as_leading_term(x, logx=logx, cdir=cdir) return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_Si(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point is S.Infinity: z = self.args[0] s = [factorial(k) / (z)**k for k in range(0, n)] + \ [Order(1/z**n, x)] return (exp(z)/z) * Add(*s) return super(Ei, self)._eval_aseries(n, args0, x, logx) class expint(Function): r""" Generalized exponential integral. Explanation =========== This function is defined as .. math:: \operatorname{E}_\nu(z) = z^{\nu - 1} \Gamma(1 - \nu, z), where $\Gamma(1 - \nu, z)$ is the upper incomplete gamma function (``uppergamma``). Hence for $z$ with positive real part we have .. math:: \operatorname{E}_\nu(z) = \int_1^\infty \frac{e^{-zt}}{t^\nu} \mathrm{d}t, which explains the name. The representation as an incomplete gamma function provides an analytic continuation for $\operatorname{E}_\nu(z)$. If $\nu$ is a non-positive integer, the exponential integral is thus an unbranched function of $z$, otherwise there is a branch point at the origin. Refer to the incomplete gamma function documentation for details of the branching behavior. Examples ======== >>> from sympy import expint, S >>> from sympy.abc import nu, z Differentiation is supported. Differentiation with respect to $z$ further explains the name: for integral orders, the exponential integral is an iterated integral of the exponential function. >>> expint(nu, z).diff(z) -expint(nu - 1, z) Differentiation with respect to $\nu$ has no classical expression: >>> expint(nu, z).diff(nu) -z**(nu - 1)*meijerg(((), (1, 1)), ((0, 0, 1 - nu), ()), z) At non-postive integer orders, the exponential integral reduces to the exponential function: >>> expint(0, z) exp(-z)/z >>> expint(-1, z) exp(-z)/z + exp(-z)/z**2 At half-integers it reduces to error functions: >>> expint(S(1)/2, z) sqrt(pi)*erfc(sqrt(z))/sqrt(z) At positive integer orders it can be rewritten in terms of exponentials and ``expint(1, z)``. Use ``expand_func()`` to do this: >>> from sympy import expand_func >>> expand_func(expint(5, z)) z**4*expint(1, z)/24 + (-z**3 + z**2 - 2*z + 6)*exp(-z)/24 The generalised exponential integral is essentially equivalent to the incomplete gamma function: >>> from sympy import uppergamma >>> expint(nu, z).rewrite(uppergamma) z**(nu - 1)*uppergamma(1 - nu, z) As such it is branched at the origin: >>> from sympy import exp_polar, pi, I >>> expint(4, z*exp_polar(2*pi*I)) I*pi*z**3/3 + expint(4, z) >>> expint(nu, z*exp_polar(2*pi*I)) z**(nu - 1)*(exp(2*I*pi*nu) - 1)*gamma(1 - nu) + expint(nu, z) See Also ======== Ei: Another related function called exponential integral. E1: The classical case, returns expint(1, z). li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. uppergamma References ========== .. [1] http://dlmf.nist.gov/8.19 .. [2] http://functions.wolfram.com/GammaBetaErf/ExpIntegralE/ .. [3] https://en.wikipedia.org/wiki/Exponential_integral """ @classmethod def eval(cls, nu, z): from sympy.functions.special.gamma_functions import (gamma, uppergamma) nu2 = unpolarify(nu) if nu != nu2: return expint(nu2, z) if nu.is_Integer and nu <= 0 or (not nu.is_Integer and (2*nu).is_Integer): return unpolarify(expand_mul(z**(nu - 1)*uppergamma(1 - nu, z))) # Extract branching information. This can be deduced from what is # explained in lowergamma.eval(). z, n = z.extract_branch_factor() if n is S.Zero: return if nu.is_integer: if not nu > 0: return return expint(nu, z) \ - 2*pi*I*n*S.NegativeOne**(nu - 1)/factorial(nu - 1)*unpolarify(z)**(nu - 1) else: return (exp(2*I*pi*nu*n) - 1)*z**(nu - 1)*gamma(1 - nu) + expint(nu, z) def fdiff(self, argindex): nu, z = self.args if argindex == 1: return -z**(nu - 1)*meijerg([], [1, 1], [0, 0, 1 - nu], [], z) elif argindex == 2: return -expint(nu - 1, z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_uppergamma(self, nu, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return z**(nu - 1)*uppergamma(1 - nu, z) def _eval_rewrite_as_Ei(self, nu, z, **kwargs): if nu == 1: return -Ei(z*exp_polar(-I*pi)) - I*pi elif nu.is_Integer and nu > 1: # DLMF, 8.19.7 x = -unpolarify(z) return x**(nu - 1)/factorial(nu - 1)*E1(z).rewrite(Ei) + \ exp(x)/factorial(nu - 1) * \ Add(*[factorial(nu - k - 2)*x**k for k in range(nu - 1)]) else: return self def _eval_expand_func(self, **hints): return self.rewrite(Ei).rewrite(expint, **hints) def _eval_rewrite_as_Si(self, nu, z, **kwargs): if nu != 1: return self return Shi(z) - Chi(z) _eval_rewrite_as_Ci = _eval_rewrite_as_Si _eval_rewrite_as_Chi = _eval_rewrite_as_Si _eval_rewrite_as_Shi = _eval_rewrite_as_Si def _eval_nseries(self, x, n, logx, cdir=0): if not self.args[0].has(x): nu = self.args[0] if nu == 1: f = self._eval_rewrite_as_Si(*self.args) return f._eval_nseries(x, n, logx) elif nu.is_Integer and nu > 1: f = self._eval_rewrite_as_Ei(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[1] nu = self.args[0] if point is S.Infinity: z = self.args[1] s = [S.NegativeOne**k * RisingFactorial(nu, k) / z**k for k in range(0, n)] + [Order(1/z**n, x)] return (exp(-z)/z) * Add(*s) return super(expint, self)._eval_aseries(n, args0, x, logx) def E1(z): """ Classical case of the generalized exponential integral. Explanation =========== This is equivalent to ``expint(1, z)``. Examples ======== >>> from sympy import E1 >>> E1(0) expint(1, 0) >>> E1(5) expint(1, 5) See Also ======== Ei: Exponential integral. expint: Generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. """ return expint(1, z) class li(Function): r""" The classical logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{li}(x) = \int_0^x \frac{1}{\log(t)} \mathrm{d}t \,. Examples ======== >>> from sympy import I, oo, li >>> from sympy.abc import z Several special values are known: >>> li(0) 0 >>> li(1) -oo >>> li(oo) oo Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(li(z), z) 1/log(z) Defining the ``li`` function via an integral: >>> from sympy import integrate >>> integrate(li(z)) z*li(z) - Ei(2*log(z)) >>> integrate(li(z),z) z*li(z) - Ei(2*log(z)) The logarithmic integral can also be defined in terms of ``Ei``: >>> from sympy import Ei >>> li(z).rewrite(Ei) Ei(log(z)) >>> diff(li(z).rewrite(Ei), z) 1/log(z) We can numerically evaluate the logarithmic integral to arbitrary precision on the whole complex plane (except the singular points): >>> li(2).evalf(30) 1.04516378011749278484458888919 >>> li(2*I).evalf(30) 1.0652795784357498247001125598 + 3.08346052231061726610939702133*I We can even compute Soldner's constant by the help of mpmath: >>> from mpmath import findroot >>> findroot(li, 2) 1.45136923488338 Further transformations include rewriting ``li`` in terms of the trigonometric integrals ``Si``, ``Ci``, ``Shi`` and ``Chi``: >>> from sympy import Si, Ci, Shi, Chi >>> li(z).rewrite(Si) -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)) >>> li(z).rewrite(Ci) -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)) >>> li(z).rewrite(Shi) -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z)) >>> li(z).rewrite(Chi) -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z)) See Also ======== Li: Offset logarithmic integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral .. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html .. [3] http://dlmf.nist.gov/6 .. [4] http://mathworld.wolfram.com/SoldnersConstant.html """ @classmethod def eval(cls, z): if z.is_zero: return S.Zero elif z is S.One: return S.NegativeInfinity elif z is S.Infinity: return S.Infinity if z.is_zero: return S.Zero def fdiff(self, argindex=1): arg = self.args[0] if argindex == 1: return S.One / log(arg) else: raise ArgumentIndexError(self, argindex) def _eval_conjugate(self): z = self.args[0] # Exclude values on the branch cut (-oo, 0) if not z.is_extended_negative: return self.func(z.conjugate()) def _eval_rewrite_as_Li(self, z, **kwargs): return Li(z) + li(2) def _eval_rewrite_as_Ei(self, z, **kwargs): return Ei(log(z)) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return (-uppergamma(0, -log(z)) + S.Half*(log(log(z)) - log(S.One/log(z))) - log(-log(z))) def _eval_rewrite_as_Si(self, z, **kwargs): return (Ci(I*log(z)) - I*Si(I*log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))) - log(I*log(z))) _eval_rewrite_as_Ci = _eval_rewrite_as_Si def _eval_rewrite_as_Shi(self, z, **kwargs): return (Chi(log(z)) - Shi(log(z)) - S.Half*(log(S.One/log(z)) - log(log(z)))) _eval_rewrite_as_Chi = _eval_rewrite_as_Shi def _eval_rewrite_as_hyper(self, z, **kwargs): return (log(z)*hyper((1, 1), (2, 2), log(z)) + S.Half*(log(log(z)) - log(S.One/log(z))) + S.EulerGamma) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (-log(-log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))) - meijerg(((), (1,)), ((0, 0), ()), -log(z))) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return z * _eis(log(z)) def _eval_nseries(self, x, n, logx, cdir=0): z = self.args[0] s = [(log(z))**k / (factorial(k) * k) for k in range(1, n)] return S.EulerGamma + log(log(z)) + Add(*s) def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True class Li(Function): r""" The offset logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2) Examples ======== >>> from sympy import Li >>> from sympy.abc import z The following special value is known: >>> Li(2) 0 Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(Li(z), z) 1/log(z) The shifted logarithmic integral can be written in terms of $li(z)$: >>> from sympy import li >>> Li(z).rewrite(li) li(z) - li(2) We can numerically evaluate the logarithmic integral to arbitrary precision on the whole complex plane (except the singular points): >>> Li(2).evalf(30) 0 >>> Li(4).evalf(30) 1.92242131492155809316615998938 See Also ======== li: Logarithmic integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral .. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html .. [3] http://dlmf.nist.gov/6 """ @classmethod def eval(cls, z): if z is S.Infinity: return S.Infinity elif z == S(2): return S.Zero def fdiff(self, argindex=1): arg = self.args[0] if argindex == 1: return S.One / log(arg) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): return self.rewrite(li).evalf(prec) def _eval_rewrite_as_li(self, z, **kwargs): return li(z) - li(2) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(li).rewrite("tractable", deep=True) def _eval_nseries(self, x, n, logx, cdir=0): f = self._eval_rewrite_as_li(*self.args) return f._eval_nseries(x, n, logx) ############################################################################### #################### TRIGONOMETRIC INTEGRALS ################################## ############################################################################### class TrigonometricIntegral(Function): """ Base class for trigonometric integrals. """ @classmethod def eval(cls, z): if z is S.Zero: return cls._atzero elif z is S.Infinity: return cls._atinf() elif z is S.NegativeInfinity: return cls._atneginf() if z.is_zero: return cls._atzero nz = z.extract_multiplicatively(polar_lift(I)) if nz is None and cls._trigfunc(0) == 0: nz = z.extract_multiplicatively(I) if nz is not None: return cls._Ifactor(nz, 1) nz = z.extract_multiplicatively(polar_lift(-I)) if nz is not None: return cls._Ifactor(nz, -1) nz = z.extract_multiplicatively(polar_lift(-1)) if nz is None and cls._trigfunc(0) == 0: nz = z.extract_multiplicatively(-1) if nz is not None: return cls._minusfactor(nz) nz, n = z.extract_branch_factor() if n == 0 and nz == z: return return 2*pi*I*n*cls._trigfunc(0) + cls(nz) def fdiff(self, argindex=1): arg = unpolarify(self.args[0]) if argindex == 1: return self._trigfunc(arg)/arg else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Ei(self, z, **kwargs): return self._eval_rewrite_as_expint(z).rewrite(Ei) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return self._eval_rewrite_as_expint(z).rewrite(uppergamma) def _eval_nseries(self, x, n, logx, cdir=0): # NOTE this is fairly inefficient n += 1 if self.args[0].subs(x, 0) != 0: return super()._eval_nseries(x, n, logx) baseseries = self._trigfunc(x)._eval_nseries(x, n, logx) if self._trigfunc(0) != 0: baseseries -= 1 baseseries = baseseries.replace(Pow, lambda t, n: t**n/n, simultaneous=False) if self._trigfunc(0) != 0: baseseries += EulerGamma + log(x) return baseseries.subs(x, self.args[0])._eval_nseries(x, n, logx) class Si(TrigonometricIntegral): r""" Sine integral. Explanation =========== This function is defined by .. math:: \operatorname{Si}(z) = \int_0^z \frac{\sin{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Si >>> from sympy.abc import z The sine integral is an antiderivative of $sin(z)/z$: >>> Si(z).diff(z) sin(z)/z It is unbranched: >>> from sympy import exp_polar, I, pi >>> Si(z*exp_polar(2*I*pi)) Si(z) Sine integral behaves much like ordinary sine under multiplication by ``I``: >>> Si(I*z) I*Shi(z) >>> Si(-z) -Si(z) It can also be expressed in terms of exponential integrals, but beware that the latter is branched: >>> from sympy import expint >>> Si(z).rewrite(expint) -I*(-expint(1, z*exp_polar(-I*pi/2))/2 + expint(1, z*exp_polar(I*pi/2))/2) + pi/2 It can be rewritten in the form of sinc function (by definition): >>> from sympy import sinc >>> Si(z).rewrite(sinc) Integral(sinc(t), (t, 0, z)) See Also ======== Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. sinc: unnormalized sinc function E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = sin _atzero = S.Zero @classmethod def _atinf(cls): return pi*S.Half @classmethod def _atneginf(cls): return -pi*S.Half @classmethod def _minusfactor(cls, z): return -Si(z) @classmethod def _Ifactor(cls, z, sign): return I*Shi(z)*sign def _eval_rewrite_as_expint(self, z, **kwargs): # XXX should we polarify z? return pi/2 + (E1(polar_lift(I)*z) - E1(polar_lift(-I)*z))/2/I def _eval_rewrite_as_sinc(self, z, **kwargs): from sympy.integrals.integrals import Integral t = Symbol('t', Dummy=True) return Integral(sinc(t), (t, 0, z)) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] p = [S.NegativeOne**k * factorial(2*k) / z**(2*k) for k in range(0, int((n - 1)/2))] + [Order(1/z**n, x)] q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1) for k in range(0, int(n/2) - 1)] + [Order(1/z**n, x)] return pi/2 - (cos(z)/z)*Add(*p) - (sin(z)/z)*Add(*q) # All other points are not handled return super(Si, self)._eval_aseries(n, args0, x, logx) def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True class Ci(TrigonometricIntegral): r""" Cosine integral. Explanation =========== This function is defined for positive $x$ by .. math:: \operatorname{Ci}(x) = \gamma + \log{x} + \int_0^x \frac{\cos{t} - 1}{t} \mathrm{d}t = -\int_x^\infty \frac{\cos{t}}{t} \mathrm{d}t, where $\gamma$ is the Euler-Mascheroni constant. We have .. math:: \operatorname{Ci}(z) = -\frac{\operatorname{E}_1\left(e^{i\pi/2} z\right) + \operatorname{E}_1\left(e^{-i \pi/2} z\right)}{2} which holds for all polar $z$ and thus provides an analytic continuation to the Riemann surface of the logarithm. The formula also holds as stated for $z \in \mathbb{C}$ with $\Re(z) > 0$. By lifting to the principal branch, we obtain an analytic function on the cut complex plane. Examples ======== >>> from sympy import Ci >>> from sympy.abc import z The cosine integral is a primitive of $\cos(z)/z$: >>> Ci(z).diff(z) cos(z)/z It has a logarithmic branch point at the origin: >>> from sympy import exp_polar, I, pi >>> Ci(z*exp_polar(2*I*pi)) Ci(z) + 2*I*pi The cosine integral behaves somewhat like ordinary $\cos$ under multiplication by $i$: >>> from sympy import polar_lift >>> Ci(polar_lift(I)*z) Chi(z) + I*pi/2 >>> Ci(polar_lift(-1)*z) Ci(z) + I*pi It can also be expressed in terms of exponential integrals: >>> from sympy import expint >>> Ci(z).rewrite(expint) -expint(1, z*exp_polar(-I*pi/2))/2 - expint(1, z*exp_polar(I*pi/2))/2 See Also ======== Si: Sine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = cos _atzero = S.ComplexInfinity @classmethod def _atinf(cls): return S.Zero @classmethod def _atneginf(cls): return I*pi @classmethod def _minusfactor(cls, z): return Ci(z) + I*pi @classmethod def _Ifactor(cls, z, sign): return Chi(z) + I*pi/2*sign def _eval_rewrite_as_expint(self, z, **kwargs): return -(E1(polar_lift(I)*z) + E1(polar_lift(-I)*z))/2 def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return S.EulerGamma elif arg0.is_finite: return self.func(arg0) else: return self def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] p = [S.NegativeOne**k * factorial(2*k) / z**(2*k) for k in range(0, int((n - 1)/2))] + [Order(1/z**n, x)] q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1) for k in range(0, int(n/2) - 1)] + [Order(1/z**n, x)] return (sin(z)/z)*Add(*p) - (cos(z)/z)*Add(*q) # All other points are not handled return super(Ci, self)._eval_aseries(n, args0, x, logx) class Shi(TrigonometricIntegral): r""" Sinh integral. Explanation =========== This function is defined by .. math:: \operatorname{Shi}(z) = \int_0^z \frac{\sinh{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Shi >>> from sympy.abc import z The Sinh integral is a primitive of $\sinh(z)/z$: >>> Shi(z).diff(z) sinh(z)/z It is unbranched: >>> from sympy import exp_polar, I, pi >>> Shi(z*exp_polar(2*I*pi)) Shi(z) The $\sinh$ integral behaves much like ordinary $\sinh$ under multiplication by $i$: >>> Shi(I*z) I*Si(z) >>> Shi(-z) -Shi(z) It can also be expressed in terms of exponential integrals, but beware that the latter is branched: >>> from sympy import expint >>> Shi(z).rewrite(expint) expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2 See Also ======== Si: Sine integral. Ci: Cosine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = sinh _atzero = S.Zero @classmethod def _atinf(cls): return S.Infinity @classmethod def _atneginf(cls): return S.NegativeInfinity @classmethod def _minusfactor(cls, z): return -Shi(z) @classmethod def _Ifactor(cls, z, sign): return I*Si(z)*sign def _eval_rewrite_as_expint(self, z, **kwargs): # XXX should we polarify z? return (E1(z) - E1(exp_polar(I*pi)*z))/2 - I*pi/2 def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return arg elif not arg0.is_infinite: return self.func(arg0) elif arg0.is_infinite: return -pi*S.ImaginaryUnit/2 else: return self class Chi(TrigonometricIntegral): r""" Cosh integral. Explanation =========== This function is defined for positive $x$ by .. math:: \operatorname{Chi}(x) = \gamma + \log{x} + \int_0^x \frac{\cosh{t} - 1}{t} \mathrm{d}t, where $\gamma$ is the Euler-Mascheroni constant. We have .. math:: \operatorname{Chi}(z) = \operatorname{Ci}\left(e^{i \pi/2}z\right) - i\frac{\pi}{2}, which holds for all polar $z$ and thus provides an analytic continuation to the Riemann surface of the logarithm. By lifting to the principal branch we obtain an analytic function on the cut complex plane. Examples ======== >>> from sympy import Chi >>> from sympy.abc import z The $\cosh$ integral is a primitive of $\cosh(z)/z$: >>> Chi(z).diff(z) cosh(z)/z It has a logarithmic branch point at the origin: >>> from sympy import exp_polar, I, pi >>> Chi(z*exp_polar(2*I*pi)) Chi(z) + 2*I*pi The $\cosh$ integral behaves somewhat like ordinary $\cosh$ under multiplication by $i$: >>> from sympy import polar_lift >>> Chi(polar_lift(I)*z) Ci(z) + I*pi/2 >>> Chi(polar_lift(-1)*z) Chi(z) + I*pi It can also be expressed in terms of exponential integrals: >>> from sympy import expint >>> Chi(z).rewrite(expint) -expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2 See Also ======== Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = cosh _atzero = S.ComplexInfinity @classmethod def _atinf(cls): return S.Infinity @classmethod def _atneginf(cls): return S.Infinity @classmethod def _minusfactor(cls, z): return Chi(z) + I*pi @classmethod def _Ifactor(cls, z, sign): return Ci(z) + I*pi/2*sign def _eval_rewrite_as_expint(self, z, **kwargs): return -I*pi/2 - (E1(z) + E1(exp_polar(I*pi)*z))/2 def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return S.EulerGamma elif arg0.is_finite: return self.func(arg0) else: return self ############################################################################### #################### FRESNEL INTEGRALS ######################################## ############################################################################### class FresnelIntegral(Function): """ Base class for the Fresnel integrals.""" unbranched = True @classmethod def eval(cls, z): # Values at positive infinities signs # if any were extracted automatically if z is S.Infinity: return S.Half # Value at zero if z.is_zero: return S.Zero # Try to pull out factors of -1 and I prefact = S.One newarg = z changed = False nz = newarg.extract_multiplicatively(-1) if nz is not None: prefact = -prefact newarg = nz changed = True nz = newarg.extract_multiplicatively(I) if nz is not None: prefact = cls._sign*I*prefact newarg = nz changed = True if changed: return prefact*cls(newarg) def fdiff(self, argindex=1): if argindex == 1: return self._trigfunc(S.Half*pi*self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_extended_real(self): return self.args[0].is_extended_real _eval_is_finite = _eval_is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_conjugate(self): return self.func(self.args[0].conjugate()) as_real_imag = real_to_real_as_real_imag class fresnels(FresnelIntegral): r""" Fresnel integral S. Explanation =========== This function is defined by .. math:: \operatorname{S}(z) = \int_0^z \sin{\frac{\pi}{2} t^2} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import I, oo, fresnels >>> from sympy.abc import z Several special values are known: >>> fresnels(0) 0 >>> fresnels(oo) 1/2 >>> fresnels(-oo) -1/2 >>> fresnels(I*oo) -I/2 >>> fresnels(-I*oo) I/2 In general one can pull out factors of -1 and $i$ from the argument: >>> fresnels(-z) -fresnels(z) >>> fresnels(I*z) -I*fresnels(z) The Fresnel S integral obeys the mirror symmetry $\overline{S(z)} = S(\bar{z})$: >>> from sympy import conjugate >>> conjugate(fresnels(z)) fresnels(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(fresnels(z), z) sin(pi*z**2/2) Defining the Fresnel functions via an integral: >>> from sympy import integrate, pi, sin, expand_func >>> integrate(sin(pi*z**2/2), z) 3*fresnels(z)*gamma(3/4)/(4*gamma(7/4)) >>> expand_func(integrate(sin(pi*z**2/2), z)) fresnels(z) We can numerically evaluate the Fresnel integral to arbitrary precision on the whole complex plane: >>> fresnels(2).evalf(30) 0.343415678363698242195300815958 >>> fresnels(-2*I).evalf(30) 0.343415678363698242195300815958*I See Also ======== fresnelc: Fresnel cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Fresnel_integral .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/FresnelIntegrals.html .. [4] http://functions.wolfram.com/GammaBetaErf/FresnelS .. [5] The converging factors for the fresnel integrals by John W. Wrench Jr. and Vicki Alley """ _trigfunc = sin _sign = -S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (-pi**2*x**4*(4*n - 1)/(8*n*(2*n + 1)*(4*n + 3))) * p else: return x**3 * (-x**4)**n * (S(2)**(-2*n - 1)*pi**(2*n + 1)) / ((4*n + 3)*factorial(2*n + 1)) def _eval_rewrite_as_erf(self, z, **kwargs): return (S.One + I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) def _eval_rewrite_as_hyper(self, z, **kwargs): return pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (pi*z**Rational(9, 4) / (sqrt(2)*(z**2)**Rational(3, 4)*(-z)**Rational(3, 4)) * meijerg([], [1], [Rational(3, 4)], [Rational(1, 4), 0], -pi**2*z**4/16)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return pi*arg**3/6 elif arg0 in [S.Infinity, S.NegativeInfinity]: s = 1 if arg0 is S.Infinity else -1 return s*S.Half + Order(x, x) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo and -oo if point in [S.Infinity, -S.Infinity]: z = self.args[0] # expansion of S(x) = S1(x*sqrt(pi/2)), see reference[5] page 1-8 # as only real infinities are dealt with, sin and cos are O(1) p = [S.NegativeOne**k * factorial(4*k + 1) / (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k)) for k in range(0, n) if 4*k + 3 < n] q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) / (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1)) for k in range(1, n) if 4*k + 1 < n] p = [-sqrt(2/pi)*t for t in p] q = [-sqrt(2/pi)*t for t in q] s = 1 if point is S.Infinity else -1 # The expansion at oo is 1/2 + some odd powers of z # To get the expansion at -oo, replace z by -z and flip the sign # The result -1/2 + the same odd powers of z as before. return s*S.Half + (sin(z**2)*Add(*p) + cos(z**2)*Add(*q) ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x) # All other points are not handled return super()._eval_aseries(n, args0, x, logx) class fresnelc(FresnelIntegral): r""" Fresnel integral C. Explanation =========== This function is defined by .. math:: \operatorname{C}(z) = \int_0^z \cos{\frac{\pi}{2} t^2} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import I, oo, fresnelc >>> from sympy.abc import z Several special values are known: >>> fresnelc(0) 0 >>> fresnelc(oo) 1/2 >>> fresnelc(-oo) -1/2 >>> fresnelc(I*oo) I/2 >>> fresnelc(-I*oo) -I/2 In general one can pull out factors of -1 and $i$ from the argument: >>> fresnelc(-z) -fresnelc(z) >>> fresnelc(I*z) I*fresnelc(z) The Fresnel C integral obeys the mirror symmetry $\overline{C(z)} = C(\bar{z})$: >>> from sympy import conjugate >>> conjugate(fresnelc(z)) fresnelc(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(fresnelc(z), z) cos(pi*z**2/2) Defining the Fresnel functions via an integral: >>> from sympy import integrate, pi, cos, expand_func >>> integrate(cos(pi*z**2/2), z) fresnelc(z)*gamma(1/4)/(4*gamma(5/4)) >>> expand_func(integrate(cos(pi*z**2/2), z)) fresnelc(z) We can numerically evaluate the Fresnel integral to arbitrary precision on the whole complex plane: >>> fresnelc(2).evalf(30) 0.488253406075340754500223503357 >>> fresnelc(-2*I).evalf(30) -0.488253406075340754500223503357*I See Also ======== fresnels: Fresnel sine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Fresnel_integral .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/FresnelIntegrals.html .. [4] http://functions.wolfram.com/GammaBetaErf/FresnelC .. [5] The converging factors for the fresnel integrals by John W. Wrench Jr. and Vicki Alley """ _trigfunc = cos _sign = S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (-pi**2*x**4*(4*n - 3)/(8*n*(2*n - 1)*(4*n + 1))) * p else: return x * (-x**4)**n * (S(2)**(-2*n)*pi**(2*n)) / ((4*n + 1)*factorial(2*n)) def _eval_rewrite_as_erf(self, z, **kwargs): return (S.One - I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) def _eval_rewrite_as_hyper(self, z, **kwargs): return z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (pi*z**Rational(3, 4) / (sqrt(2)*root(z**2, 4)*root(-z, 4)) * meijerg([], [1], [Rational(1, 4)], [Rational(3, 4), 0], -pi**2*z**4/16)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return arg elif arg0 in [S.Infinity, S.NegativeInfinity]: s = 1 if arg0 is S.Infinity else -1 return s*S.Half + Order(x, x) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point in [S.Infinity, -S.Infinity]: z = self.args[0] # expansion of C(x) = C1(x*sqrt(pi/2)), see reference[5] page 1-8 # as only real infinities are dealt with, sin and cos are O(1) p = [S.NegativeOne**k * factorial(4*k + 1) / (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k)) for k in range(0, n) if 4*k + 3 < n] q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) / (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1)) for k in range(1, n) if 4*k + 1 < n] p = [-sqrt(2/pi)*t for t in p] q = [ sqrt(2/pi)*t for t in q] s = 1 if point is S.Infinity else -1 # The expansion at oo is 1/2 + some odd powers of z # To get the expansion at -oo, replace z by -z and flip the sign # The result -1/2 + the same odd powers of z as before. return s*S.Half + (cos(z**2)*Add(*p) + sin(z**2)*Add(*q) ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x) # All other points are not handled return super()._eval_aseries(n, args0, x, logx) ############################################################################### #################### HELPER FUNCTIONS ######################################### ############################################################################### class _erfs(Function): """ Helper function to make the $\\mathrm{erf}(z)$ function tractable for the Gruntz algorithm. """ @classmethod def eval(cls, arg): if arg.is_zero: return S.One def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] l = [ 1/sqrt(S.Pi) * factorial(2*k)*(-S( 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(0, n) ] o = Order(1/z**(2*n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o # Expansion at I*oo t = point.extract_multiplicatively(S.ImaginaryUnit) if t is S.Infinity: z = self.args[0] # TODO: is the series really correct? l = [ 1/sqrt(S.Pi) * factorial(2*k)*(-S( 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(0, n) ] o = Order(1/z**(2*n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o # All other points are not handled return super()._eval_aseries(n, args0, x, logx) def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -2/sqrt(S.Pi) + 2*z*_erfs(z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_intractable(self, z, **kwargs): return (S.One - erf(z))*exp(z**2) class _eis(Function): """ Helper function to make the $\\mathrm{Ei}(z)$ and $\\mathrm{li}(z)$ functions tractable for the Gruntz algorithm. """ def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[0] != S.Infinity: return super(_erfs, self)._eval_aseries(n, args0, x, logx) z = self.args[0] l = [ factorial(k) * (1/z)**(k + 1) for k in range(0, n) ] o = Order(1/z**(n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return S.One / z - _eis(z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_intractable(self, z, **kwargs): return exp(-z)*Ei(z) def _eval_as_leading_term(self, x, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_as_leading_term(x, logx=logx, cdir=cdir) return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx)