hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
62e4753f7c63464c503fcf3e7667dcf3d4bc3b37f2b551a7f658fa35980f0998 | from sympy.core.relational import Eq, is_eq
from sympy.core.logic import fuzzy_and, fuzzy_bool
from sympy.logic.boolalg import And
from sympy.multipledispatch import dispatch
from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet
@dispatch(Interval, FiniteSet)
def _eval_is_eq(lhs, rhs): # noqa: F811
return False
@dispatch(FiniteSet, Interval)
def _eval_is_eq(lhs, rhs): # noqa: F811
return False
@dispatch(Interval, Interval)
def _eval_is_eq(lhs, rhs): # noqa: F811
return And(Eq(lhs.left, rhs.left),
Eq(lhs.right, rhs.right),
lhs.left_open == rhs.left_open,
lhs.right_open == rhs.right_open)
@dispatch(FiniteSet, Interval)
def _eval_is_eq(lhs, rhs): # noqa: F811
return False
@dispatch(FiniteSet, FiniteSet)
def _eval_is_eq(lhs, rhs): # noqa: F811
def all_in_both():
s_set = set(lhs.args)
o_set = set(rhs.args)
yield fuzzy_and(lhs._contains(e) for e in o_set - s_set)
yield fuzzy_and(rhs._contains(e) for e in s_set - o_set)
return tfn[fuzzy_and(all_in_both())]
@dispatch(ProductSet, ProductSet)
def _eval_is_eq(lhs, rhs): # noqa: F811
if len(lhs.sets) != len(rhs.sets):
return False
eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets))
return tfn[fuzzy_and(map(fuzzy_bool, eqs))]
|
a858020e4bebaa9f2c0b9fdb0c2077e413da1ac046b31db5f505498d183c9655 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import os
from itertools import chain
import json
import sys
import warnings
import pytest
from sympy.testing.runtests import setup_pprint, _get_doctest_blacklist
durations_path = os.path.join(os.path.dirname(__file__), '.ci', 'durations.json')
blacklist_path = os.path.join(os.path.dirname(__file__), '.ci', 'blacklisted.json')
# Collecting tests from rubi_tests under pytest leads to errors even if the
# tests will be skipped.
collect_ignore = ["sympy/integrals/rubi"] + _get_doctest_blacklist()
# Set up printing for doctests
setup_pprint()
sys.__displayhook__ = sys.displayhook
#from sympy import pprint_use_unicode
#pprint_use_unicode(False)
def _mk_group(group_dict):
return list(chain(*[[k+'::'+v for v in files] for k, files in group_dict.items()]))
if os.path.exists(durations_path):
veryslow_group, slow_group = [_mk_group(group_dict) for group_dict in json.loads(open(durations_path, 'rt').read())]
else:
# warnings in conftest has issues: https://github.com/pytest-dev/pytest/issues/2891
warnings.warn("conftest.py:22: Could not find %s, --quickcheck and --veryquickcheck will have no effect.\n" % durations_path)
veryslow_group, slow_group = [], []
if os.path.exists(blacklist_path):
blacklist_group = _mk_group(json.loads(open(blacklist_path, 'rt').read()))
else:
warnings.warn("conftest.py:28: Could not find %s, no tests will be skipped due to blacklisting\n" % blacklist_path)
blacklist_group = []
def pytest_addoption(parser):
parser.addoption("--quickcheck", dest="runquick", action="store_true",
help="Skip very slow tests (see ./ci/parse_durations_log.py)")
parser.addoption("--veryquickcheck", dest="runveryquick", action="store_true",
help="Skip slow & very slow (see ./ci/parse_durations_log.py)")
def pytest_configure(config):
# register an additional marker
config.addinivalue_line("markers", "slow: manually marked test as slow (use .ci/durations.json instead)")
config.addinivalue_line("markers", "quickcheck: skip very slow tests")
config.addinivalue_line("markers", "veryquickcheck: skip slow & very slow tests")
def pytest_runtest_setup(item):
if isinstance(item, pytest.Function):
if item.nodeid in veryslow_group and (item.config.getvalue("runquick") or
item.config.getvalue("runveryquick")):
pytest.skip("very slow test, skipping since --quickcheck or --veryquickcheck was passed.")
return
if item.nodeid in slow_group and item.config.getvalue("runveryquick"):
pytest.skip("slow test, skipping since --veryquickcheck was passed.")
return
if item.nodeid in blacklist_group:
pytest.skip("blacklisted test, see %s" % blacklist_path)
return
|
f6e3c0a0120b741b0d16511361ab5dab52e66b36c78a4379034f01a29ba4067b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A tool to generate AUTHORS. We started tracking authors before moving
to git, so we have to do some manual rearrangement of the git history
authors in order to get the order in AUTHORS. bin/mailmap_update.py
should be run before committing the results.
"""
from __future__ import unicode_literals
from __future__ import print_function
import codecs
import sys
import os
if sys.version_info < (3, 6):
sys.exit("This script requires Python 3.6 or newer")
from subprocess import run, PIPE
from distutils.version import LooseVersion
from collections import OrderedDict
def red(text):
return "\033[31m%s\033[0m" % text
def yellow(text):
return "\033[33m%s\033[0m" % text
def green(text):
return "\033[32m%s\033[0m" % text
# put sympy on the path
mailmap_update_path = os.path.abspath(__file__)
mailmap_update_dir = os.path.dirname(mailmap_update_path)
sympy_top = os.path.split(mailmap_update_dir)[0]
sympy_dir = os.path.join(sympy_top, 'sympy')
if os.path.isdir(sympy_dir):
sys.path.insert(0, sympy_top)
from sympy.utilities.misc import filldedent
# check git version
minimal = '1.8.4.2'
git_ver = run(['git', '--version'], stdout=PIPE, encoding='utf-8').stdout[12:]
if LooseVersion(git_ver) < LooseVersion(minimal):
print(yellow("Please use a git version >= %s" % minimal))
def author_name(line):
assert line.count("<") == line.count(">") == 1
assert line.endswith(">")
return line.split("<", 1)[0].strip()
def move(l, i1, i2, who):
x = l.pop(i1)
# this will fail if the .mailmap is not right
assert who == author_name(x), \
'%s was not found at line %i' % (who, i1)
l.insert(i2, x)
# find who git knows ahout
git_command = ["git", "log", "--topo-order", "--reverse", "--format=%aN <%aE>"]
git_people = run(git_command, stdout=PIPE, encoding='utf-8').stdout.strip().split("\n")
# remove duplicates, keeping the original order
git_people = list(OrderedDict.fromkeys(git_people))
# Do the few changes necessary in order to reproduce AUTHORS:
try:
move(git_people, 2, 0, 'Ondřej Čertík')
move(git_people, 42, 1, 'Fabian Pedregosa')
move(git_people, 22, 2, 'Jurjen N.E. Bos')
git_people.insert(4, "*Marc-Etienne M.Leveille <[email protected]>")
move(git_people, 10, 5, 'Brian Jorgensen')
git_people.insert(11, "*Ulrich Hecht <[email protected]>")
# this will fail if the .mailmap is not right
assert 'Kirill Smelkov' == author_name(git_people.pop(12)
), 'Kirill Smelkov was not found at line 12'
move(git_people, 12, 32, 'Sebastian Krämer')
move(git_people, 227, 35, 'Case Van Horsen')
git_people.insert(43, "*Dan <[email protected]>")
move(git_people, 57, 59, 'Aaron Meurer')
move(git_people, 58, 57, 'Andrew Docherty')
move(git_people, 67, 66, 'Chris Smith')
move(git_people, 79, 76, 'Kevin Goodsell')
git_people.insert(84, "*Chu-Ching Huang <[email protected]>")
move(git_people, 93, 92, 'James Pearson')
# this will fail if the .mailmap is not right
assert 'Sergey B Kirpichev' == author_name(git_people.pop(226)
), 'Sergey B Kirpichev was not found at line 226.'
index = git_people.index(
"azure-pipelines[bot] " +
"<azure-pipelines[bot]@users.noreply.github.com>")
git_people.pop(index)
index = git_people.index(
"whitesource-bolt-for-github[bot] " +
"<whitesource-bolt-for-github[bot]@users.noreply.github.com>")
git_people.pop(index)
except AssertionError as msg:
print(red(msg))
sys.exit(1)
# define new lines for the file
header = filldedent("""
All people who contributed to SymPy by sending at least a patch or
more (in the order of the date of their first contribution), except
those who explicitly didn't want to be mentioned. People with a * next
to their names are not found in the metadata of the git history. This
file is generated automatically by running `./bin/authors_update.py`.
""").lstrip()
fmt = """There are a total of {authors_count} authors."""
header_extra = fmt.format(authors_count=len(git_people))
lines = header.splitlines()
lines.append('')
lines.append(header_extra)
lines.append('')
lines.extend(git_people)
# compare to old lines and stop if no changes were made
old_lines = codecs.open(os.path.realpath(os.path.join(
__file__, os.path.pardir, os.path.pardir, "AUTHORS")),
"r", "utf-8").read().splitlines()
if old_lines == lines:
sys.exit(green('No changes made to AUTHORS.'))
# check for new additions
new_authors = []
for i in sorted(set(lines) - set(old_lines)):
try:
author_name(i)
new_authors.append(i)
except AssertionError:
continue
# write the new file
with codecs.open(os.path.realpath(os.path.join(
__file__, os.path.pardir, os.path.pardir, "AUTHORS")),
"w", "utf-8") as fd:
fd.write('\n'.join(lines))
fd.write('\n')
# warn about additions
if new_authors:
print(yellow(filldedent("""
The following authors were added to AUTHORS.
If mailmap_update.py has already been run and
each author appears as desired and is not a
duplicate of some other author, then the
changes can be committed. Otherwise, see
.mailmap for instructions on how to change
an author's entry.""")))
print()
for i in sorted(new_authors, key=lambda x: x.lower()):
print('\t%s' % i)
else:
print(yellow("The AUTHORS file was updated."))
|
6f570d05bae2bcd24dfb435352aa7686e333de8733998ad538326acaa26d61e5 | #!/usr/bin/env python
"""
Test that only executable files have an executable bit set
"""
from __future__ import print_function
import os
import sys
from get_sympy import path_hack
base_dir = path_hack()
def test_executable(path):
if not os.path.isdir(path):
if os.access(path, os.X_OK):
with open(path, 'r') as f:
if f.readline()[:2] != "#!":
exn_msg = "File at " + path + " either should not be executable or should have a shebang line"
raise OSError(exn_msg)
else:
for file in os.listdir(path):
test_executable(os.path.join(path, file))
test_executable(base_dir)
|
f27b6b78c19f8637e90dc32c70c275d67b062c75a1b4c82c192c12fccd200331 | #!/usr/bin/env python
"""
Test that
from sympy import *
doesn't import anything other than SymPy, it's hard dependencies (mpmath), and
hard optional dependencies (gmpy2). Importing unnecessary libraries
can accidentally add hard dependencies to SymPy in the worst case, or at best
slow down the SymPy import time when they are installed.
Note, for this test to be effective, every external library that could
potentially be imported by SymPy must be installed.
TODO: Monkeypatch the importer to detect non-standard library imports even
when they aren't installed.
Based on code from
https://stackoverflow.com/questions/22195382/how-to-check-if-a-module-library-package-is-part-of-the-python-standard-library.
"""
# These libraries will always be imported with SymPy
hard_dependencies = ['mpmath']
# These libraries are optional, but are always imported at SymPy import time
# when they are installed. External libraries should only be added to this
# list if they are required for core SymPy functionality.
hard_optional_dependencies = ['gmpy', 'gmpy2', 'pycosat']
import sys
import os
stdlib = {p for p in sys.path if p.startswith(sys.prefix) and
'site-packages' not in p}
existing_modules = list(sys.modules.keys())
# hook in-tree SymPy into Python path, if possible
this_path = os.path.abspath(__file__)
this_dir = os.path.dirname(this_path)
sympy_top = os.path.split(this_dir)[0]
sympy_dir = os.path.join(sympy_top, 'sympy')
if os.path.isdir(sympy_dir):
sys.path.insert(0, sympy_top)
def test_external_imports():
exec("from sympy import *", {})
bad = []
for mod in sys.modules:
if '.' in mod and mod.split('.')[0] in sys.modules:
# Only worry about the top-level modules
continue
if mod in existing_modules:
continue
if any(mod == i or mod.startswith(i + '.') for i in ['sympy'] +
hard_dependencies + hard_optional_dependencies):
continue
if mod in sys.builtin_module_names:
continue
fname = getattr(sys.modules[mod], "__file__", None)
if fname is None:
bad.append(mod)
continue
if fname.endswith(('__init__.py', '__init__.pyc', '__init__.pyo')):
fname = os.path.dirname(fname)
if os.path.dirname(fname) in stdlib:
continue
bad.append(mod)
if bad:
raise RuntimeError("""Unexpected external modules found when running 'from sympy import *':
""" + '\n '.join(bad))
print("No unexpected external modules were imported with 'from sympy import *'!")
if __name__ == '__main__':
test_external_imports()
|
77e2be58473622545b79a96ade239dd88ec3f60d9a44c20284fed0c4c4b56068 | #!/usr/bin/env python
"""
Test that
from sympy import *
only imports those sympy submodules that have names that are part of the
top-level namespace.
"""
import sys
import os
# hook in-tree SymPy into Python path, if possible
this_path = os.path.abspath(__file__)
this_dir = os.path.dirname(this_path)
sympy_top = os.path.split(this_dir)[0]
sympy_dir = os.path.join(sympy_top, 'sympy')
if os.path.isdir(sympy_dir):
sys.path.insert(0, sympy_top)
submodule_whitelist = [
'algebras',
'assumptions',
'calculus',
'concrete',
'core',
'deprecated',
'discrete',
'external',
'functions',
'geometry',
'integrals',
'interactive',
'logic',
'matrices',
'multipledispatch',
'ntheory',
'parsing',
'plotting',
'polys',
'printing',
'release',
'series',
'sets',
'simplify',
'solvers',
'strategies',
'tensor',
'testing',
'utilities',
]
def test_submodule_imports():
if 'sympy' in sys.modules:
raise RuntimeError("SymPy has already been imported, the test_submodule_imports test cannot run")
exec("from sympy import *", {})
for mod in sys.modules:
if not mod.startswith('sympy'):
continue
if not mod.count('.') == 1:
continue
_, submodule = mod.split('.')
if submodule not in submodule_whitelist:
sys.exit(f"""\
Error: The submodule {mod} was imported with 'from sympy import *', but it was
not expected to be.
If {mod} is a new module that has functions that are imported at the
top-level, then the whitelist in bin/test_submodule_imports should be updated.
If it is not, the place that imports it should be modified so that it does not
get imported at the top-level, e.g., by moving the 'import {mod}' import
inside the function that uses it.
If you are unsure which code is importing {mod}, it may help to add 'raise
Exception' to sympy/{submodule}/__init__.py and observe the traceback from
running 'from sympy import *'.""")
print("No unexpected submodules were imported with 'from sympy import *'")
if __name__ == '__main__':
test_submodule_imports()
|
b269c0ec426d3e816e80bd4ddb4d3223168257de1808f0e1aeeee4364cd9f1ab | #!/usr/bin/env python
"""
Script to generate test coverage reports.
Usage:
$ bin/coverage_report.py
This will create a directory covhtml with the coverage reports. To
restrict the analysis to a directory, you just need to pass its name as
argument. For example:
$ bin/coverage_report.py sympy/logic
runs only the tests in sympy/logic/ and reports only on the modules in
sympy/logic/. To also run slow tests use --slow option. You can also get a
report on the parts of the whole sympy code covered by the tests in
sympy/logic/ by following up the previous command with
$ bin/coverage_report.py -c
"""
from __future__ import print_function
import os
import re
import sys
from argparse import ArgumentParser
minver = '3.4'
try:
import coverage
if coverage.__version__ < minver:
raise ImportError
except ImportError:
print(
"You need to install module coverage (version %s or newer required).\n"
"See https://coverage.readthedocs.io/en/latest/ or \n"
"https://launchpad.net/ubuntu/+source/python-coverage/" % minver)
sys.exit(-1)
omit_dir_patterns = ['.*tests', 'benchmark', 'examples',
'pyglet', 'test_external']
omit_dir_re = re.compile(r'|'.join(omit_dir_patterns))
source_re = re.compile(r'.*\.py$')
def generate_covered_files(top_dir):
for dirpath, dirnames, filenames in os.walk(top_dir):
omit_dirs = [dirn for dirn in dirnames if omit_dir_re.match(dirn)]
for x in omit_dirs:
dirnames.remove(x)
for filename in filenames:
if source_re.match(filename):
yield os.path.join(dirpath, filename)
def make_report(
test_args, source_dir='sympy/', report_dir='covhtml', use_cache=False,
slow=False
):
# code adapted from /bin/test
from get_sympy import path_hack
sympy_top = path_hack()
os.chdir(sympy_top)
cov = coverage.coverage()
cov.exclude("raise NotImplementedError")
cov.exclude("def canonize") # this should be "@decorated"
if use_cache:
cov.load()
else:
cov.erase()
cov.start()
import sympy
sympy.test(*test_args, subprocess=False, slow=slow)
#sympy.doctest() # coverage doesn't play well with doctests
cov.stop()
try:
cov.save()
except PermissionError:
import warnings
warnings.warn(
"PermissionError has been raised while saving the " \
"coverage result.",
RuntimeWarning
)
covered_files = list(generate_covered_files(source_dir))
cov.html_report(morfs=covered_files, directory=report_dir)
parser = ArgumentParser()
parser.add_argument(
'-c', '--use-cache', action='store_true', default=False,
help='Use cached data.')
parser.add_argument(
'-d', '--report-dir', default='covhtml',
help='Directory to put the generated report in.')
parser.add_argument(
"--slow", action="store_true", dest="slow", default=False,
help="Run slow functions also.")
options, args = parser.parse_known_args()
if __name__ == '__main__':
report_dir = options.report_dir
use_cache = options.use_cache
slow = options.slow
make_report(
args, report_dir=report_dir, use_cache=use_cache, slow=slow)
print("The generated coverage report is in covhtml directory.")
print(
"Open %s in your web browser to view the report" %
os.sep.join([report_dir, 'index.html'])
)
|
e9e0c452359500b056918d133e572097e4b22377bde79c3dff43554945c6b3e4 | #!/usr/bin/env python3
import subprocess
import sys
from os.path import join, splitext, basename
from contextlib import contextmanager
from tempfile import TemporaryDirectory
from zipfile import ZipFile
from shutil import copytree
def main(sympy_doc_git, doc_html_zip, version, push=None):
"""Run this as ./update_docs.py SYMPY_DOC_GIT DOC_HTML_ZIP VERSION [--push]
!!!!!!!!!!!!!!!!!
NOTE: This is intended to be run as part of the release script.
NOTE: This script will automatically push to the sympy_doc repo.
!!!!!!!!!!!!!!!!!
Args
====
SYMPY_DOC_GIT: Path to the sympy_doc repo.
DOC_HTML_ZIP: Path to the zip of the built html docs.
VERSION: Version string (e.g. "1.6")
--push (optional): Push the results (Warning this pushes direct to github)
This script automates the "release docs" step described in the README of the
sympy/sympy_doc repo:
https://github.com/sympy/sympy_doc#release-docs
"""
if push is None:
push = False
elif push == "--push":
push = True
else:
raise ValueError("Invalid arguments")
update_docs(sympy_doc_git, doc_html_zip, version, push)
def update_docs(sympy_doc_git, doc_html_zip, version, push):
# We started with a clean tree so restore it on error
with git_rollback_on_error(sympy_doc_git, branch='gh-pages') as run:
# Delete docs for the last version
run('git', 'rm', '-rf', 'latest')
# Extract new docs in replacement
extract_docs(sympy_doc_git, doc_html_zip)
# Commit new docs
run('git', 'add', 'latest')
run('git', 'commit', '-m', 'Add sympy %s docs' % version)
# Update indexes
run('./generate_indexes.py')
run('git', 'diff')
run('git', 'commit', '-a', '-m', 'Update indexes')
if push:
run('git', 'push')
else:
print('Results are committed but not pushed')
@contextmanager
def git_rollback_on_error(gitroot_path, branch='master'):
def run(*cmdline, **kwargs):
"""Run subprocess with cwd in sympy_doc"""
print()
print('Running: $ ' + ' '.join(cmdline))
print()
return subprocess.run(cmdline, cwd=gitroot_path, check=True, **kwargs)
unclean_msg = "The git repo should be completely clean before running this"
try:
run('git', 'diff', '--exit-code') # Error if tree is unclean
except subprocess.CalledProcessError:
raise ValueError(unclean_msg)
if run('git', 'clean', '-n', stdout=subprocess.PIPE).stdout:
raise ValueError(unclean_msg)
run('git', 'checkout', branch)
run('git', 'pull')
bsha_start = run('git', 'rev-parse', 'HEAD', stdout=subprocess.PIPE).stdout
sha_start = bsha_start.strip().decode('ascii')
try:
yield run
except Exception as e:
run('git', 'reset', '--hard', sha_start)
raise e from None
def extract_docs(sympy_doc_git, doc_html_zip):
subdirname = splitext(basename(doc_html_zip))[0]
with TemporaryDirectory() as tempdir:
print()
print('Extracting docs to ' + tempdir)
print()
ZipFile(doc_html_zip).extractall(tempdir)
print()
print('Copying to sympy_doc/latest')
print()
srcpath = join(tempdir, subdirname)
dstpath = join(sympy_doc_git, 'latest')
copytree(srcpath, dstpath)
if __name__ == "__main__":
main(*sys.argv[1:])
|
626da77cf38bad8e05ec9065bb64975cd69be34ad8cde7c499d0e819bfa35a34 | """
SymPy is a Python library for symbolic mathematics. It aims to become a
full-featured computer algebra system (CAS) while keeping the code as simple
as possible in order to be comprehensible and easily extensible. SymPy is
written entirely in Python. It depends on mpmath, and other external libraries
may be optionally for things like plotting support.
See the webpage for more information and documentation:
https://sympy.org
"""
import sys
if sys.version_info < (3, 5):
raise ImportError("Python version 3.5 or above is required for SymPy.")
del sys
try:
import mpmath
except ImportError:
raise ImportError("SymPy now depends on mpmath as an external library. "
"See https://docs.sympy.org/latest/install.html#mpmath for more information.")
del mpmath
from sympy.release import __version__
if 'dev' in __version__:
def enable_warnings():
import warnings
warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*')
del warnings
enable_warnings()
del enable_warnings
def __sympy_debug():
# helper function so we don't import os globally
import os
debug_str = os.getenv('SYMPY_DEBUG', 'False')
if debug_str in ('True', 'False'):
return eval(debug_str)
else:
raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
debug_str)
SYMPY_DEBUG = __sympy_debug() # type: bool
from .core import (sympify, SympifyError, cacheit, Basic, Atom,
preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol,
Wild, Dummy, symbols, var, Number, Float, Rational, Integer,
NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo,
AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log,
Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality,
GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan,
vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass,
Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log,
expand_func, expand_trig, expand_complex, expand_multinomial, nfloat,
expand_power_base, expand_power_exp, arity, PrecisionExhausted, N,
evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate,
Catalan, EulerGamma, GoldenRatio, TribonacciConstant)
from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor,
Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map,
true, false, satisfiable)
from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext,
assuming, Q, ask, register_handler, remove_handler, refine)
from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr,
degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo,
pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert,
subresultants, resultant, discriminant, cofactors, gcd_list, gcd,
lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose,
decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf,
factor_list, factor, intervals, refine_root, count_roots, real_roots,
nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner,
is_zero_dimensional, GroebnerBasis, poly, symmetrize, horner,
interpolate, rational_interpolate, viete, together,
BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed,
OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed,
IsomorphismFailed, ExtraneousFactors, EvaluationFailed,
RefinementFailed, CoercionFailed, NotInvertible, NotReversible,
NotAlgebraic, DomainError, PolynomialError, UnificationFailed,
GeneratorsError, GeneratorsNeeded, ComputationFailed,
UnivariatePolynomialError, MultivariatePolynomialError,
PolificationFailed, OptionError, FlagError, minpoly,
minimal_polynomial, primitive_element, field_isomorphism,
to_number_field, isolate, itermonomials, Monomial, lex, grlex,
grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf,
ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing,
RationalField, RealField, ComplexField, PythonFiniteField,
GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational,
GMPYRationalField, AlgebraicField, PolynomialRing, FractionField,
ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python,
QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, construct_domain,
swinnerton_dyer_poly, cyclotomic_poly, symmetric_poly, random_poly,
interpolating_poly, jacobi_poly, chebyshevt_poly, chebyshevu_poly,
hermite_poly, legendre_poly, laguerre_poly, apart, apart_list,
assemble_partfrac_list, Options, ring, xring, vring, sring, field,
xfield, vfield, sfield)
from .series import (Order, O, limit, Limit, gruntz, series, approximants,
residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul,
fourier_series, fps, difference_delta, limit_seq)
from .functions import (factorial, factorial2, rf, ff, binomial,
RisingFactorial, FallingFactorial, subfactorial, carmichael,
fibonacci, lucas, tribonacci, harmonic, bernoulli, bell, euler,
catalan, genocchi, partition, sqrt, root, Min, Max, Id, real_root,
cbrt, re, im, sign, Abs, conjugate, arg, polar_lift,
periodic_argument, unbranched_argument, principal_branch, transpose,
adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc,
asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log,
LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh,
acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold,
erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, Ei, expint, E1, li,
Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, lowergamma,
uppergamma, polygamma, loggamma, digamma, trigamma, multigamma,
dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, LeviCivita,
KroneckerDelta, SingularityFunction, DiracDelta, Heaviside,
bspline_basis, bspline_basis_set, interpolating_spline, besselj,
bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1,
hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper,
meijerg, appellf1, legendre, assoc_legendre, hermite, chebyshevt,
chebyshevu, chebyshevu_root, chebyshevt_root, laguerre,
assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c,
Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus,
mathieuc, mathieusprime, mathieucprime)
from .ntheory import (nextprime, prevprime, prime, primepi, primerange,
randprime, Sieve, sieve, primorial, cycle_length, composite,
compositepi, isprime, divisors, proper_divisors, factorint,
multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors,
totient, trailing, divisor_count, proper_divisor_count, divisor_sigma,
factorrat, reduced_totient, primenu, primeomega,
mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
is_deficient, is_amicable, abundance, npartitions, is_primitive_root,
is_quad_residue, legendre_symbol, jacobi_symbol, n_order, sqrt_mod,
quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue,
sqrt_mod_iter, mobius, discrete_log, quadratic_congruence,
binomial_coefficients, binomial_coefficients_list,
multinomial_coefficients, continued_fraction_periodic,
continued_fraction_iterator, continued_fraction_reduce,
continued_fraction_convergents, continued_fraction, egyptian_fraction)
from .concrete import product, Product, summation, Sum
from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform,
inverse_mobius_transform, convolution, covering_product,
intersecting_product)
from .simplify import (simplify, hypersimp, hypersimilar, logcombine,
separatevars, posify, besselsimp, kroneckersimp, signsimp, bottom_up,
nsimplify, FU, fu, sqrtdenest, cse, use, epath, EPath, hyperexpand,
collect, rcollect, radsimp, collect_const, fraction, numer, denom,
trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp,
ratsimp, ratsimpmodprime)
from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet,
Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet,
Range, ComplexRegion, Reals, Contains, ConditionSet, Ordinal,
OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet,
Integers, Rationals)
from .solvers import (solve, solve_linear_system, solve_linear_system_LU,
solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick,
inv_quick, check_assumptions, failing_assumptions, diophantine,
rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol,
classify_ode, dsolve, homogeneous_order, solve_poly_system,
solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul,
pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities,
reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality,
solve_rational_inequalities, solve_univariate_inequality, decompogen,
solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution,
Complexes)
from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt,
casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix,
DeferredVector, MatrixBase, Matrix, MutableMatrix,
MutableSparseMatrix, banded, ImmutableDenseMatrix,
ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice,
BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse,
MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose,
ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols,
Adjoint, hadamard_product, HadamardProduct, HadamardPower,
Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix,
DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct,
PermutationMatrix, MatrixPermute)
from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D,
Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle,
Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid,
convex_hull, idiff, intersection, closest_points, farthest_points,
GeometryError, Curve, Parabola)
from .utilities import (flatten, group, take, subsets, variations,
numbered_symbols, cartes, capture, dict_merge, postorder_traversal,
interactive_traversal, prefixes, postfixes, sift, topological_sort,
unflatten, has_dups, has_variety, reshape, default_sort_key, ordered,
rotations, filldedent, lambdify, source, threaded, xthreaded, public,
memoize_property, timed)
from .integrals import (integrate, Integral, line_integrate, mellin_transform,
inverse_mellin_transform, MellinTransform, InverseMellinTransform,
laplace_transform, inverse_laplace_transform, LaplaceTransform,
InverseLaplaceTransform, fourier_transform, inverse_fourier_transform,
FourierTransform, InverseFourierTransform, sine_transform,
inverse_sine_transform, SineTransform, InverseSineTransform,
cosine_transform, inverse_cosine_transform, CosineTransform,
InverseCosineTransform, hankel_transform, inverse_hankel_transform,
HankelTransform, InverseHankelTransform, singularityintegrate)
from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure,
get_indices, MutableDenseNDimArray, ImmutableDenseNDimArray,
MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray,
tensorproduct, tensorcontraction, derive_by_array, permutedims, Array,
DenseNDimArray, SparseNDimArray)
from .parsing import parse_expr
from .calculus import (euler_equations, singularities, is_increasing,
is_strictly_increasing, is_decreasing, is_strictly_decreasing,
is_monotonic, finite_diff_weights, apply_finite_diff, as_finite_diff,
differentiate_finite, periodicity, not_empty_in, AccumBounds,
is_convex, stationary_points, minimum, maximum)
from .algebras import Quaternion
from .printing import (pager_print, pretty, pretty_print, pprint,
pprint_use_unicode, pprint_try_use_unicode, latex, print_latex,
multiline_latex, mathml, print_mathml, python, print_python, pycode,
ccode, print_ccode, glsl_code, print_glsl, cxxcode, fcode,
print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code,
mathematica_code, octave_code, rust_code, print_gtk, preview, srepr,
print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint,
maple_code, print_maple_code)
from .testing import test, doctest
# This module causes conflicts with other modules:
# from .stats import *
# Adds about .04-.05 seconds of import time
# from combinatorics import *
# This module is slow to import:
#from physics import units
from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric
from .interactive import init_session, init_printing
evalf._create_evalf_table()
# This is slow to import:
#import abc
from .deprecated import C, ClassRegistry, class_registry
__all__ = [
# sympy.core
'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom',
'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr',
'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float',
'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm',
'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp',
'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod',
'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality',
'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan',
'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative',
'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError',
'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig',
'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base',
'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple',
'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan',
'EulerGamma', 'GoldenRatio', 'TribonacciConstant',
# sympy.logic
'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
'bool_map', 'true', 'false', 'satisfiable',
# sympy.assumptions
'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q',
'ask', 'register_handler', 'remove_handler', 'refine',
# sympy.polys
'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content',
'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff',
'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor',
'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots',
'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner',
'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', 'horner',
'interpolate', 'rational_interpolate', 'viete', 'together',
'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
'UnivariatePolynomialError', 'MultivariatePolynomialError',
'PolificationFailed', 'OptionError', 'FlagError', 'minpoly',
'minimal_polynomial', 'primitive_element', 'field_isomorphism',
'to_number_field', 'isolate', 'itermonomials', 'Monomial', 'lex', 'grlex',
'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf',
'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField',
'IntegerRing', 'RationalField', 'RealField', 'ComplexField',
'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing',
'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField',
'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain',
'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy',
'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'construct_domain',
'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly',
'random_poly', 'interpolating_poly', 'jacobi_poly', 'chebyshevt_poly',
'chebyshevu_poly', 'hermite_poly', 'legendre_poly', 'laguerre_poly',
'apart', 'apart_list', 'assemble_partfrac_list', 'Options', 'ring',
'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', 'sfield',
# sympy.series
'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd',
'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq',
# sympy.functions
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas',
'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan',
'genocchi', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root',
'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
'periodic_argument', 'unbranched_argument', 'principal_branch',
'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan',
'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc',
'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh',
'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise',
'piecewise_fold', 'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv',
'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi',
'fresnels', 'fresnelc', 'gamma', 'lowergamma', 'uppergamma', 'polygamma',
'loggamma', 'digamma', 'trigamma', 'multigamma', 'dirichlet_eta', 'zeta',
'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita',
'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside',
'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj',
'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn',
'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre',
'assoc_legendre', 'hermite', 'chebyshevt', 'chebyshevu',
'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre',
'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm',
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta',
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
# sympy.ntheory
'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime',
'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity',
'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient',
'trailing', 'divisor_count', 'proper_divisor_count', 'divisor_sigma',
'factorrat', 'reduced_totient', 'primenu', 'primeomega',
'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime',
'is_abundant', 'is_deficient', 'is_amicable', 'abundance', 'npartitions',
'is_primitive_root', 'is_quad_residue', 'legendre_symbol',
'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues',
'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
'mobius', 'discrete_log', 'quadratic_congruence', 'binomial_coefficients',
'binomial_coefficients_list', 'multinomial_coefficients',
'continued_fraction_periodic', 'continued_fraction_iterator',
'continued_fraction_reduce', 'continued_fraction_convergents',
'continued_fraction', 'egyptian_fraction',
# sympy.concrete
'product', 'Product', 'summation', 'Sum',
# sympy.discrete
'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
'inverse_mobius_transform', 'convolution', 'covering_product',
'intersecting_product',
# sympy.simplify
'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
'posify', 'besselsimp', 'kroneckersimp', 'signsimp', 'bottom_up',
'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'use', 'epath', 'EPath',
'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const',
'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp',
'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime',
# sympy.sets
'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference',
'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet',
'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Reals', 'Naturals',
'Naturals0', 'UniversalSet', 'Integers', 'Rationals',
# sympy.solvers
'solve', 'solve_linear_system', 'solve_linear_system_LU',
'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
'solve_poly_system', 'solve_triangulated', 'pde_separate',
'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde',
'checkpdesol', 'ode_order', 'reduce_inequalities',
'reduce_abs_inequality', 'reduce_abs_inequalities',
'solve_poly_inequality', 'solve_rational_inequalities',
'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve',
'linear_eq_to_matrix', 'nonlinsolve', 'substitution', 'Complexes',
# sympy.matrices
'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag',
'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy',
'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1',
'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros',
'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix',
'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix',
'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice',
'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse',
'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace',
'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse',
'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct',
'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix',
'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct',
'kronecker_product', 'KroneckerProduct', 'PermutationMatrix',
'MatrixPermute',
# sympy.geometry
'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D',
'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse',
'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola',
# sympy.utilities
'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
'cartes', 'capture', 'dict_merge', 'postorder_traversal',
'interactive_traversal', 'prefixes', 'postfixes', 'sift',
'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
'default_sort_key', 'ordered', 'rotations', 'filldedent', 'lambdify',
'source', 'threaded', 'xthreaded', 'public', 'memoize_property', 'test',
'doctest', 'timed',
# sympy.integrals
'integrate', 'Integral', 'line_integrate', 'mellin_transform',
'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform',
'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform',
'InverseLaplaceTransform', 'fourier_transform',
'inverse_fourier_transform', 'FourierTransform',
'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
'SineTransform', 'InverseSineTransform', 'cosine_transform',
'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
'InverseHankelTransform', 'singularityintegrate',
# sympy.tensor
'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure',
'get_indices', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
'tensorproduct', 'tensorcontraction', 'derive_by_array', 'permutedims',
'Array', 'DenseNDimArray', 'SparseNDimArray',
# sympy.parsing
'parse_expr',
# sympy.calculus
'euler_equations', 'singularities', 'is_increasing',
'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing',
'is_monotonic', 'finite_diff_weights', 'apply_finite_diff',
'as_finite_diff', 'differentiate_finite', 'periodicity', 'not_empty_in',
'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum',
# sympy.algebras
'Quaternion',
# sympy.printing
'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex',
'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode',
'print_ccode', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode',
'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode',
'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk',
'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr',
'TableForm', 'dotprint', 'maple_code', 'print_maple_code',
# sympy.plotting
'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric',
# sympy.interactive
'init_session', 'init_printing',
# sympy.testing
'test', 'doctest',
# sympy.deprecated:
'C', 'ClassRegistry', 'class_registry',
]
#===========================================================================#
# #
# XXX: The names below were importable before sympy 1.6 using #
# #
# from sympy import * #
# #
# This happened implicitly because there was no __all__ defined in this #
# __init__.py file. Not every package is imported. The list matches what #
# would have been imported before. It is possible that these packages will #
# not be imported by a star-import from sympy in future. #
# #
#===========================================================================#
__all__.extend([
'algebras',
'assumptions',
'calculus',
'concrete',
'deprecated',
'discrete',
'external',
'functions',
'geometry',
'interactive',
'multipledispatch',
'ntheory',
'parsing',
'plotting',
'polys',
'printing',
'release',
'strategies',
'tensor',
'utilities',
])
#===========================================================================#
# #
# XXX: The names listed in _DEPRECATED_IMPORTS below were importable before #
# sympy 1.6 using #
# #
# from sympy import * #
# #
# This happened implicitly because there was no __all__ defined in this #
# __init__.py file. The plan is to remove them but for now they remain #
# importable but will give a deprecation warning when used. In future these #
# names will be removed and will not be importable from here. #
# #
#===========================================================================#
class DeprecatedImportModule:
# Add a docstring that someone can see if calling help on these objects
"""Deprecated imported module object.
See https://github.com/sympy/sympy/pull/19316
This is a wrapper around a module that has been imported incorrectly.
Previously this module was importable using
from sympy import *
or (for example)
from sympy import add
However it was unintentional that this module would be imported in that
way and it will be removed in a future sympy version. If you do need to
use this module then the correct way to import it is to give its full
module path e.g.
import sympy.core.add as add
"""
from sympy.utilities.exceptions import SymPyDeprecationWarning as Warn
import sys
sympy = sys.modules[__name__]
_DEPRECATED_IMPORTS = [
'sympy.concrete.expr_with_intlimits',
'sympy.concrete.expr_with_limits',
'sympy.concrete.gosper',
'sympy.concrete.products',
'sympy.concrete.summations',
'sympy.core.add',
'sympy.core.basic',
'sympy.core.cache',
'sympy.core.compatibility',
'sympy.core.containers',
'sympy.core.coreerrors',
'sympy.core.decorators',
'sympy.core.expr',
'sympy.core.exprtools',
'sympy.core.facts',
'sympy.core.function',
'sympy.core.logic',
'sympy.core.mod',
'sympy.core.mul',
'sympy.core.multidimensional',
'sympy.core.numbers',
'sympy.core.operations',
'sympy.core.power',
'sympy.core.relational',
'sympy.core.rules',
'sympy.core.singleton',
'sympy.core.symbol',
'sympy.discrete.convolutions',
'sympy.geometry.curve',
'sympy.geometry.ellipse',
'sympy.geometry.entity',
'sympy.geometry.exceptions',
'sympy.geometry.line',
'sympy.geometry.parabola',
'sympy.geometry.plane',
'sympy.geometry.point',
'sympy.geometry.polygon',
'sympy.geometry.util',
'sympy.integrals.integrals',
'sympy.integrals.manualintegrate',
'sympy.integrals.meijerint',
'sympy.integrals.singularityfunctions',
'sympy.integrals.transforms',
'sympy.integrals.trigonometry',
'sympy.logic.boolalg',
'sympy.logic.inference',
'sympy.matrices.common',
'sympy.matrices.dense',
'sympy.matrices.expressions',
'sympy.matrices.immutable',
'sympy.matrices.matrices',
'sympy.matrices.sparse',
'sympy.matrices.sparsetools',
'sympy.ntheory.factor_',
'sympy.ntheory.generate',
'sympy.ntheory.multinomial',
'sympy.ntheory.partitions_',
'sympy.ntheory.primetest',
'sympy.ntheory.residue_ntheory',
'sympy.sets.conditionset',
'sympy.sets.contains',
'sympy.sets.fancysets',
'sympy.sets.ordinals',
'sympy.sets.powerset',
'sympy.sets.sets',
'sympy.simplify.cse_main',
'sympy.simplify.cse_opts',
'sympy.simplify.epathtools',
'sympy.simplify.traversaltools',
'sympy.solvers.bivariate',
'sympy.solvers.deutils',
'sympy.solvers.inequalities',
'sympy.solvers.ode',
'sympy.solvers.pde',
'sympy.solvers.polysys',
'sympy.solvers.recurr',
'sympy.solvers.solvers',
'sympy.tensor.array',
'sympy.tensor.index_methods',
'sympy.tensor.indexed'
]
def __init__(self, modname):
from importlib import import_module
self.modname = modname
self.mod = import_module(modname)
def __getattr__(self, name):
self.Warn(
feature="importing %s with 'from sympy import *'" % self.modname,
useinstead="import %s" % self.modname,
issue=18245,
deprecated_since_version="1.6").warn()
return getattr(self.mod, name)
@classmethod
def inject_imports(cls):
for modname in cls._DEPRECATED_IMPORTS:
name = modname.split('.')[-1]
deprecated_mod = cls(modname)
setattr(cls.sympy, name, deprecated_mod)
__all__.append(name)
DeprecatedImportModule.inject_imports()
del DeprecatedImportModule
|
20f14288e489734a63a3fd43945b74666d87e23dcb203879269976242bce388e | #!/usr/bin/env python
"""Pretty print example
Demonstrates pretty printing.
"""
from sympy import Symbol, pprint, sin, cos, exp, sqrt, MatrixSymbol, KroneckerProduct
def main():
x = Symbol("x")
y = Symbol("y")
a = MatrixSymbol("a", 1, 1)
b = MatrixSymbol("b", 1, 1)
c = MatrixSymbol("c", 1, 1)
pprint( x**x )
print('\n') # separate with two blank lines
pprint(x**2 + y + x)
print('\n')
pprint(sin(x)**x)
print('\n')
pprint( sin(x)**cos(x) )
print('\n')
pprint( sin(x)/(cos(x)**2 * x**x + (2*y)) )
print('\n')
pprint( sin(x**2 + exp(x)) )
print('\n')
pprint( sqrt(exp(x)) )
print('\n')
pprint( sqrt(sqrt(exp(x))) )
print('\n')
pprint( (1/cos(x)).series(x, 0, 10) )
print('\n')
pprint(a*(KroneckerProduct(b, c)))
print('\n')
if __name__ == "__main__":
main()
|
fa79c8e992b8d9e9927793a513fe5cbae6afed27b460c32425a142714553d4b0 | """
========
numpydoc
========
Sphinx extension that handles docstrings in the Numpy standard format. [1]
It will:
- Convert Parameters etc. sections to field lists.
- Convert See Also section to a See also entry.
- Renumber references.
- Extract the signature from the docstring, if it can't be determined
otherwise.
.. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
"""
from __future__ import division, absolute_import, print_function
import sys
import re
import pydoc
import sphinx
import inspect
from collections.abc import Callable
if sphinx.__version__ < '1.0.1':
raise RuntimeError("Sphinx 1.0.1 or newer is required")
from docscrape_sphinx import get_doc_object, SphinxDocString
def mangle_docstrings(app, what, name, obj, options, lines,
reference_offset=[0]):
cfg = {'use_plots': app.config.numpydoc_use_plots,
'show_class_members': app.config.numpydoc_show_class_members,
'show_inherited_class_members':
app.config.numpydoc_show_inherited_class_members,
'class_members_toctree': app.config.numpydoc_class_members_toctree}
u_NL = '\n'
if what == 'module':
# Strip top title
pattern = '^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'
title_re = re.compile(pattern, re.I | re.S)
lines[:] = title_re.sub('', u_NL.join(lines)).split(u_NL)
else:
doc = get_doc_object(obj, what, u_NL.join(lines), config=cfg)
if sys.version_info[0] >= 3:
doc = str(doc)
else:
doc = unicode(doc)
lines[:] = doc.split(u_NL)
if (app.config.numpydoc_edit_link and hasattr(obj, '__name__') and
obj.__name__):
if hasattr(obj, '__module__'):
v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__))
else:
v = dict(full_name=obj.__name__)
lines += ['', '.. htmlonly::', '']
lines += [' %s' % x for x in
(app.config.numpydoc_edit_link % v).split("\n")]
# replace reference numbers so that there are no duplicates
references = []
for line in lines:
line = line.strip()
m = re.match('^.. \\[([a-z0-9_.-])\\]', line, re.I)
if m:
references.append(m.group(1))
# start renaming from the longest string, to avoid overwriting parts
references.sort(key=lambda x: -len(x))
if references:
for i, line in enumerate(lines):
for r in references:
if re.match('^\\d+$', r):
new_r = "R%d" % (reference_offset[0] + int(r))
else:
new_r = "%s%d" % (r, reference_offset[0])
lines[i] = lines[i].replace('[%s]_' % r,
'[%s]_' % new_r)
lines[i] = lines[i].replace('.. [%s]' % r,
'.. [%s]' % new_r)
reference_offset[0] += len(references)
def mangle_signature(app, what, name, obj, options, sig, retann):
# Do not try to inspect classes that don't define `__init__`
if (inspect.isclass(obj) and
(not hasattr(obj, '__init__') or
'initializes x; see ' in pydoc.getdoc(obj.__init__))):
return '', ''
if not (isinstance(obj, Callable) or
hasattr(obj, '__argspec_is_invalid_')):
return
if not hasattr(obj, '__doc__'):
return
doc = SphinxDocString(pydoc.getdoc(obj))
if doc['Signature']:
sig = re.sub("^[^(]*", "", doc['Signature'])
return sig, ''
def setup(app, get_doc_object_=get_doc_object):
if not hasattr(app, 'add_config_value'):
return # probably called by nose, better bail out
global get_doc_object
get_doc_object = get_doc_object_
app.connect('autodoc-process-docstring', mangle_docstrings)
app.connect('autodoc-process-signature', mangle_signature)
app.add_config_value('numpydoc_edit_link', None, False)
app.add_config_value('numpydoc_use_plots', None, False)
app.add_config_value('numpydoc_show_class_members', True, True)
app.add_config_value('numpydoc_show_inherited_class_members', True, True)
app.add_config_value('numpydoc_class_members_toctree', True, True)
# Extra mangling domains
app.add_domain(NumpyPythonDomain)
app.add_domain(NumpyCDomain)
# ------------------------------------------------------------------------------
# Docstring-mangling domains
# ------------------------------------------------------------------------------
from docutils.statemachine import ViewList
from sphinx.domains.c import CDomain
from sphinx.domains.python import PythonDomain
class ManglingDomainBase(object):
directive_mangling_map = {}
def __init__(self, *a, **kw):
super(ManglingDomainBase, self).__init__(*a, **kw)
self.wrap_mangling_directives()
def wrap_mangling_directives(self):
for name, objtype in list(self.directive_mangling_map.items()):
self.directives[name] = wrap_mangling_directive(
self.directives[name], objtype)
class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
name = 'np'
directive_mangling_map = {
'function': 'function',
'class': 'class',
'exception': 'class',
'method': 'function',
'classmethod': 'function',
'staticmethod': 'function',
'attribute': 'attribute',
}
indices = []
class NumpyCDomain(ManglingDomainBase, CDomain):
name = 'np-c'
directive_mangling_map = {
'function': 'function',
'member': 'attribute',
'macro': 'function',
'type': 'class',
'var': 'object',
}
def wrap_mangling_directive(base_directive, objtype):
class directive(base_directive):
def run(self):
env = self.state.document.settings.env
name = None
if self.arguments:
m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0])
name = m.group(2).strip()
if not name:
name = self.arguments[0]
lines = list(self.content)
mangle_docstrings(env.app, objtype, name, None, None, lines)
self.content = ViewList(lines, self.content.parent)
return base_directive.run(self)
return directive
|
2d9b891b19d8f9bdf2a577fb0fc458d6e737908345b2ffabcd7f016e1ca9f91d | from __future__ import division, absolute_import, print_function
import sys
import re
import inspect
import textwrap
import pydoc
import sphinx
import collections
from docscrape import NumpyDocString, FunctionDoc, ClassDoc
class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config={}):
NumpyDocString.__init__(self, docstring, config=config)
self.load_config(config)
def load_config(self, config):
self.use_plots = config.get('use_plots', False)
self.class_members_toctree = config.get('class_members_toctree', True)
# string conversion routines
def _str_header(self, name, symbol='`'):
return ['.. rubric:: ' + name, '']
def _str_field_list(self, name):
return [':' + name + ':']
def _str_indent(self, doc, indent=4):
out = []
for line in doc:
out += [' '*indent + line]
return out
def _str_signature(self):
return ['']
if self['Signature']:
return ['``%s``' % self['Signature']] + ['']
else:
return ['']
def _str_summary(self):
return self['Summary'] + ['']
def _str_extended_summary(self):
return self['Extended Summary'] + ['']
def _str_returns(self, name='Returns'):
out = []
if self[name]:
out += self._str_field_list(name)
out += ['']
for param, param_type, desc in self[name]:
if param_type:
out += self._str_indent(['**%s** : %s' % (param.strip(),
param_type)])
else:
out += self._str_indent([param.strip()])
if desc:
out += ['']
out += self._str_indent(desc, 8)
out += ['']
return out
def _str_param_list(self, name):
out = []
if self[name]:
out += self._str_field_list(name)
out += ['']
for param, param_type, desc in self[name]:
if param_type:
out += self._str_indent(['**%s** : %s' % (param.strip(),
param_type)])
else:
out += self._str_indent(['**%s**' % param.strip()])
if desc:
out += ['']
out += self._str_indent(desc, 8)
out += ['']
return out
@property
def _obj(self):
if hasattr(self, '_cls'):
return self._cls
elif hasattr(self, '_f'):
return self._f
return None
def _str_member_list(self, name):
"""
Generate a member listing, autosummary:: table where possible,
and a table where not.
"""
out = []
if self[name]:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
if prefix:
prefix = '~%s.' % prefix
# Lines that are commented out are used to make the
# autosummary:: table. Since SymPy does not use the
# autosummary:: functionality, it is easiest to just comment it
# out.
# autosum = []
others = []
for param, param_type, desc in self[name]:
param = param.strip()
# Check if the referenced member can have a docstring or not
param_obj = getattr(self._obj, param, None)
if not (callable(param_obj)
or isinstance(param_obj, property)
or inspect.isgetsetdescriptor(param_obj)):
param_obj = None
# if param_obj and (pydoc.getdoc(param_obj) or not desc):
# # Referenced object has a docstring
# autosum += [" %s%s" % (prefix, param)]
# else:
others.append((param, param_type, desc))
# if autosum:
# out += ['.. autosummary::']
# if self.class_members_toctree:
# out += [' :toctree:']
# out += [''] + autosum
if others:
maxlen_0 = max(3, max([len(x[0]) for x in others]))
hdr = "="*maxlen_0 + " " + "="*10
fmt = '%%%ds %%s ' % (maxlen_0,)
out += ['', '', hdr]
for param, param_type, desc in others:
desc = " ".join(x.strip() for x in desc).strip()
if param_type:
desc = "(%s) %s" % (param_type, desc)
out += [fmt % (param.strip(), desc)]
out += [hdr]
out += ['']
return out
def _str_section(self, name):
out = []
if self[name]:
out += self._str_header(name)
out += ['']
content = textwrap.dedent("\n".join(self[name])).split("\n")
out += content
out += ['']
return out
def _str_see_also(self, func_role):
out = []
if self['See Also']:
see_also = super(SphinxDocString, self)._str_see_also(func_role)
out = ['.. seealso::', '']
out += self._str_indent(see_also[2:])
return out
def _str_warnings(self):
out = []
if self['Warnings']:
out = ['.. warning::', '']
out += self._str_indent(self['Warnings'])
return out
def _str_index(self):
idx = self['index']
out = []
if len(idx) == 0:
return out
out += ['.. index:: %s' % idx.get('default', '')]
for section, references in idx.items():
if section == 'default':
continue
elif section == 'refguide':
out += [' single: %s' % (', '.join(references))]
else:
out += [' %s: %s' % (section, ','.join(references))]
return out
def _str_references(self):
out = []
if self['References']:
out += self._str_header('References')
if isinstance(self['References'], str):
self['References'] = [self['References']]
out.extend(self['References'])
out += ['']
# Latex collects all references to a separate bibliography,
# so we need to insert links to it
if sphinx.__version__ >= "0.6":
out += ['.. only:: latex', '']
else:
out += ['.. latexonly::', '']
items = []
for line in self['References']:
m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I)
if m:
items.append(m.group(1))
out += [' ' + ", ".join(["[%s]_" % item for item in items]), '']
return out
def _str_examples(self):
examples_str = "\n".join(self['Examples'])
if (self.use_plots and 'import matplotlib' in examples_str
and 'plot::' not in examples_str):
out = []
out += self._str_header('Examples')
out += ['.. plot::', '']
out += self._str_indent(self['Examples'])
out += ['']
return out
else:
return self._str_section('Examples')
def __str__(self, indent=0, func_role="obj"):
out = []
out += self._str_signature()
out += self._str_index() + ['']
out += self._str_summary()
out += self._str_extended_summary()
out += self._str_param_list('Parameters')
out += self._str_returns('Returns')
out += self._str_returns('Yields')
for param_list in ('Other Parameters', 'Raises', 'Warns'):
out += self._str_param_list(param_list)
out += self._str_warnings()
for s in self._other_keys:
out += self._str_section(s)
out += self._str_see_also(func_role)
out += self._str_references()
out += self._str_member_list('Attributes')
out = self._str_indent(out, indent)
return '\n'.join(out)
class SphinxFunctionDoc(SphinxDocString, FunctionDoc):
def __init__(self, obj, doc=None, config={}):
self.load_config(config)
FunctionDoc.__init__(self, obj, doc=doc, config=config)
class SphinxClassDoc(SphinxDocString, ClassDoc):
def __init__(self, obj, doc=None, func_doc=None, config={}):
self.load_config(config)
ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config)
class SphinxObjDoc(SphinxDocString):
def __init__(self, obj, doc=None, config={}):
self._f = obj
self.load_config(config)
SphinxDocString.__init__(self, doc, config=config)
def get_doc_object(obj, what=None, doc=None, config={}):
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc,
config=config)
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return SphinxObjDoc(obj, doc, config=config)
|
143099c96dc670625c55f30eeb8588e808c62f3719cc6f0d02db5799f474161c | from __future__ import print_function, division
import random
import itertools
from sympy import (Matrix, MatrixSymbol, S, Indexed, Basic,
Set, And, Eq, FiniteSet, ImmutableMatrix,
Lambda, Mul, Dummy, IndexedBase, Add, Interval, oo,
linsolve, eye, Or, Not, Intersection, factorial, Contains,
Union, Expr, Function, exp, cacheit, sqrt, pi, gamma,
Ge, Piecewise, Symbol, NonSquareMatrixError, EmptySet)
from sympy.core.relational import Relational
from sympy.logic.boolalg import Boolean
from sympy.stats.joint_rv import JointDistribution
from sympy.stats.joint_rv_types import JointDistributionHandmade
from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol,
_symbol_converter, _value_check, pspace, given,
dependent, is_random, sample_iter)
from sympy.stats.stochastic_process import StochasticPSpace
from sympy.stats.symbolic_probability import Probability, Expectation
from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV
from sympy.stats.drv_types import Poisson, PoissonDistribution
from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution
from sympy.core.sympify import _sympify
__all__ = [
'StochasticProcess',
'DiscreteTimeStochasticProcess',
'DiscreteMarkovChain',
'TransitionMatrixOf',
'StochasticStateSpaceOf',
'GeneratorMatrixOf',
'ContinuousMarkovChain',
'BernoulliProcess',
'PoissonProcess',
'WienerProcess',
'GammaProcess'
]
@is_random.register(Indexed)
def _(x):
return is_random(x.base)
@is_random.register(RandomIndexedSymbol)
def _(x):
return True
def _set_converter(itr):
"""
Helper function for converting list/tuple/set to Set.
If parameter is not an instance of list/tuple/set then
no operation is performed.
Returns
=======
Set
The argument converted to Set.
Raises
======
TypeError
If the argument is not an instance of list/tuple/set.
"""
if isinstance(itr, (list, tuple, set)):
itr = FiniteSet(*itr)
if not isinstance(itr, Set):
raise TypeError("%s is not an instance of list/tuple/set."%(itr))
return itr
def _sym_sympify(arg):
"""
Converts an arbitrary expression to a type that can be used inside SymPy.
As generally strings are unwise to use in the expressions,
it returns the Symbol of argument if the string type argument is passed.
Parameters
=========
arg: The parameter to be converted to be used in Sympy.
Returns
=======
The converted parameter.
"""
if isinstance(arg, str):
return Symbol(arg)
else:
return _sympify(arg)
def _matrix_checks(matrix):
if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)):
raise TypeError("Transition probabilities either should "
"be a Matrix or a MatrixSymbol.")
if matrix.shape[0] != matrix.shape[1]:
raise NonSquareMatrixError("%s is not a square matrix"%(matrix))
if isinstance(matrix, Matrix):
matrix = ImmutableMatrix(matrix.tolist())
return matrix
class StochasticProcess(Basic):
"""
Base class for all the stochastic processes whether
discrete or continuous.
Parameters
==========
sym: Symbol or str
state_space: Set
The state space of the stochastic process, by default S.Reals.
For discrete sets it is zero indexed.
See Also
========
DiscreteTimeStochasticProcess
"""
index_set = S.Reals
def __new__(cls, sym, state_space=S.Reals, **kwargs):
sym = _symbol_converter(sym)
state_space = _set_converter(state_space)
return Basic.__new__(cls, sym, state_space)
@property
def symbol(self):
return self.args[0]
@property
def state_space(self):
return self.args[1]
@property
def distribution(self):
return None
def __call__(self, time):
"""
Overridden in ContinuousTimeStochasticProcess.
"""
raise NotImplementedError("Use [] for indexing discrete time stochastic process.")
def __getitem__(self, time):
"""
Overridden in DiscreteTimeStochasticProcess.
"""
raise NotImplementedError("Use () for indexing continuous time stochastic process.")
def probability(self, condition):
raise NotImplementedError()
def joint_distribution(self, *args):
"""
Computes the joint distribution of the random indexed variables.
Parameters
==========
args: iterable
The finite list of random indexed variables/the key of a stochastic
process whose joint distribution has to be computed.
Returns
=======
JointDistribution
The joint distribution of the list of random indexed variables.
An unevaluated object is returned if it is not possible to
compute the joint distribution.
Raises
======
ValueError: When the arguments passed are not of type RandomIndexSymbol
or Number.
"""
args = list(args)
for i, arg in enumerate(args):
if S(arg).is_Number:
if self.index_set.is_subset(S.Integers):
args[i] = self.__getitem__(arg)
else:
args[i] = self.__call__(arg)
elif not isinstance(arg, RandomIndexedSymbol):
raise ValueError("Expected a RandomIndexedSymbol or "
"key not %s"%(type(arg)))
if args[0].pspace.distribution == None: # checks if there is any distribution available
return JointDistribution(*args)
pdf = Lambda(tuple(args),
expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args))
return JointDistributionHandmade(pdf)
def expectation(self, condition, given_condition):
raise NotImplementedError("Abstract method for expectation queries.")
def sample(self):
raise NotImplementedError("Abstract method for sampling queries.")
class DiscreteTimeStochasticProcess(StochasticProcess):
"""
Base class for all discrete stochastic processes.
"""
def __getitem__(self, time):
"""
For indexing discrete time stochastic processes.
Returns
=======
RandomIndexedSymbol
"""
if time not in self.index_set:
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
idx_obj = Indexed(self.symbol, time)
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution)
return RandomIndexedSymbol(idx_obj, pspace_obj)
class ContinuousTimeStochasticProcess(StochasticProcess):
"""
Base class for all continuous time stochastic process.
"""
def __call__(self, time):
"""
For indexing continuous time stochastic processes.
Returns
=======
RandomIndexedSymbol
"""
if time not in self.index_set:
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
func_obj = Function(self.symbol)(time)
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution)
return RandomIndexedSymbol(func_obj, pspace_obj)
class TransitionMatrixOf(Boolean):
"""
Assumes that the matrix is the transition matrix
of the process.
"""
def __new__(cls, process, matrix):
if not isinstance(process, DiscreteMarkovChain):
raise ValueError("Currently only DiscreteMarkovChain "
"support TransitionMatrixOf.")
matrix = _matrix_checks(matrix)
return Basic.__new__(cls, process, matrix)
process = property(lambda self: self.args[0])
matrix = property(lambda self: self.args[1])
class GeneratorMatrixOf(TransitionMatrixOf):
"""
Assumes that the matrix is the generator matrix
of the process.
"""
def __new__(cls, process, matrix):
if not isinstance(process, ContinuousMarkovChain):
raise ValueError("Currently only ContinuousMarkovChain "
"support GeneratorMatrixOf.")
matrix = _matrix_checks(matrix)
return Basic.__new__(cls, process, matrix)
class StochasticStateSpaceOf(Boolean):
def __new__(cls, process, state_space):
if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)):
raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain "
"support StochasticStateSpaceOf.")
state_space = _set_converter(state_space)
return Basic.__new__(cls, process, state_space)
process = property(lambda self: self.args[0])
state_space = property(lambda self: self.args[1])
class MarkovProcess(StochasticProcess):
"""
Contains methods that handle queries
common to Markov processes.
"""
def _extract_information(self, given_condition):
"""
Helper function to extract information, like,
transition matrix/generator matrix, state space, etc.
"""
if isinstance(self, DiscreteMarkovChain):
trans_probs = self.transition_probabilities
elif isinstance(self, ContinuousMarkovChain):
trans_probs = self.generator_matrix
state_space = self.state_space
if isinstance(given_condition, And):
gcs = given_condition.args
given_condition = S.true
for gc in gcs:
if isinstance(gc, TransitionMatrixOf):
trans_probs = gc.matrix
if isinstance(gc, StochasticStateSpaceOf):
state_space = gc.state_space
if isinstance(gc, Relational):
given_condition = given_condition & gc
if isinstance(given_condition, TransitionMatrixOf):
trans_probs = given_condition.matrix
given_condition = S.true
if isinstance(given_condition, StochasticStateSpaceOf):
state_space = given_condition.state_space
given_condition = S.true
return trans_probs, state_space, given_condition
def _check_trans_probs(self, trans_probs, row_sum=1):
"""
Helper function for checking the validity of transition
probabilities.
"""
if not isinstance(trans_probs, MatrixSymbol):
rows = trans_probs.tolist()
for row in rows:
if (sum(row) - row_sum) != 0:
raise ValueError("Values in a row must sum to %s. "
"If you are using Float or floats then please use Rational."%(row_sum))
def _work_out_state_space(self, state_space, given_condition, trans_probs):
"""
Helper function to extract state space if there
is a random symbol in the given condition.
"""
# if given condition is None, then there is no need to work out
# state_space from random variables
if given_condition != None:
rand_var = list(given_condition.atoms(RandomSymbol) -
given_condition.atoms(RandomIndexedSymbol))
if len(rand_var) == 1:
state_space = rand_var[0].pspace.set
if not FiniteSet(*[i for i in range(trans_probs.shape[0])]).is_subset(state_space):
raise ValueError("state space is not compatible with the transition probabilites.")
state_space = FiniteSet(*[i for i in range(trans_probs.shape[0])])
return state_space
@cacheit
def _preprocess(self, given_condition, evaluate):
"""
Helper function for pre-processing the information.
"""
is_insufficient = False
if not evaluate: # avoid pre-processing if the result is not to be evaluated
return (True, None, None, None)
# extracting transition matrix and state space
trans_probs, state_space, given_condition = self._extract_information(given_condition)
# given_condition does not have sufficient information
# for computations
if trans_probs == None or \
given_condition == None:
is_insufficient = True
else:
# checking transition probabilities
if isinstance(self, DiscreteMarkovChain):
self._check_trans_probs(trans_probs, row_sum=1)
elif isinstance(self, ContinuousMarkovChain):
self._check_trans_probs(trans_probs, row_sum=0)
# working out state space
state_space = self._work_out_state_space(state_space, given_condition, trans_probs)
return is_insufficient, trans_probs, state_space, given_condition
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Handles probability queries for Markov process.
Parameters
==========
condition: Relational
given_condition: Relational/And
Returns
=======
Probability
If the information is not sufficient.
Expr
In all other cases.
Note
====
Any information passed at the time of query overrides
any information passed at the time of object creation like
transition probabilities, state space.
Pass the transition matrix using TransitionMatrixOf,
generator matrix using GeneratorMatrixOf and state space
using StochasticStateSpaceOf in given_condition using & or And.
"""
check, mat, state_space, new_given_condition = \
self._preprocess(given_condition, evaluate)
if check:
return Probability(condition, new_given_condition)
if isinstance(self, ContinuousMarkovChain):
trans_probs = self.transition_probabilities(mat)
elif isinstance(self, DiscreteMarkovChain):
trans_probs = mat
if isinstance(condition, Relational):
rv, states = (list(condition.atoms(RandomIndexedSymbol))[0], condition.as_set())
if isinstance(new_given_condition, And):
gcs = new_given_condition.args
else:
gcs = (new_given_condition, )
grvs = new_given_condition.atoms(RandomIndexedSymbol)
min_key_rv = None
for grv in grvs:
if grv.key <= rv.key:
min_key_rv = grv
if min_key_rv == None:
return Probability(condition)
prob, gstate = dict(), None
for gc in gcs:
if gc.has(min_key_rv):
if gc.has(Probability):
p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \
else (gc.lhs, gc.rhs)
gr = gp.args[0]
gset = Intersection(gr.as_set(), state_space)
gstate = list(gset)[0]
prob[gset] = p
else:
_, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \
else (gc.rhs.key, gc.lhs)
if any((k not in self.index_set) for k in (rv.key, min_key_rv.key)):
raise IndexError("The timestamps of the process are not in it's index set.")
states = Intersection(states, state_space)
for state in Union(states, FiniteSet(gstate)):
if Ge(state, mat.shape[0]) == True:
raise IndexError("No information is available for (%s, %s) in "
"transition probabilities of shape, (%s, %s). "
"State space is zero indexed."
%(gstate, state, mat.shape[0], mat.shape[1]))
if prob:
gstates = Union(*prob.keys())
if len(gstates) == 1:
gstate = list(gstates)[0]
gprob = list(prob.values())[0]
prob[gstates] = gprob
elif len(gstates) == len(state_space) - 1:
gstate = list(state_space - gstates)[0]
gprob = S.One - sum(prob.values())
prob[state_space - gstates] = gprob
else:
raise ValueError("Conflicting information.")
else:
gprob = S.One
if min_key_rv == rv:
return sum([prob[FiniteSet(state)] for state in states])
if isinstance(self, ContinuousMarkovChain):
return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state))
for state in states])
if isinstance(self, DiscreteMarkovChain):
return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state))
for state in states])
if isinstance(condition, Not):
expr = condition.args[0]
return S.One - self.probability(expr, given_condition, evaluate, **kwargs)
if isinstance(condition, And):
compute_later, state2cond, conds = [], dict(), condition.args
for expr in conds:
if isinstance(expr, Relational):
ris = list(expr.atoms(RandomIndexedSymbol))[0]
if state2cond.get(ris, None) is None:
state2cond[ris] = S.true
state2cond[ris] &= expr
else:
compute_later.append(expr)
ris = []
for ri in state2cond:
ris.append(ri)
cset = Intersection(state2cond[ri].as_set(), state_space)
if len(cset) == 0:
return S.Zero
state2cond[ri] = cset.as_relational(ri)
sorted_ris = sorted(ris, key=lambda ri: ri.key)
prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs)
for i in range(1, len(sorted_ris)):
ri, prev_ri = sorted_ris[i], sorted_ris[i-1]
if not isinstance(state2cond[ri], Eq):
raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri))
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
prod *= self.probability(state2cond[ri], state2cond[prev_ri]
& mat_of
& StochasticStateSpaceOf(self, state_space),
evaluate, **kwargs)
for expr in compute_later:
prod *= self.probability(expr, given_condition, evaluate, **kwargs)
return prod
if isinstance(condition, Or):
return sum([self.probability(expr, given_condition, evaluate, **kwargs)
for expr in condition.args])
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
"implemented yet."%(expr, condition))
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Handles expectation queries for markov process.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
Returns
=======
Expectation
Unevaluated object if computations cannot be done due to
insufficient information.
Expr
In all other cases when the computations are successful.
Note
====
Any information passed at the time of query overrides
any information passed at the time of object creation like
transition probabilities, state space.
Pass the transition matrix using TransitionMatrixOf,
generator matrix using GeneratorMatrixOf and state space
using StochasticStateSpaceOf in given_condition using & or And.
"""
check, mat, state_space, condition = \
self._preprocess(condition, evaluate)
if check:
return Expectation(expr, condition)
rvs = random_symbols(expr)
if isinstance(expr, Expr) and isinstance(condition, Eq) \
and len(rvs) == 1:
# handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>))
rv = list(rvs)[0]
lhsg, rhsg = condition.lhs, condition.rhs
if not isinstance(lhsg, RandomIndexedSymbol):
lhsg, rhsg = (rhsg, lhsg)
if rhsg not in self.state_space:
raise ValueError("%s state is not in the state space."%(rhsg))
if rv.key < lhsg.key:
raise ValueError("Incorrect given condition is given, expectation "
"time %s < time %s"%(rv.key, rv.key))
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
cond = condition & mat_of & \
StochasticStateSpaceOf(self, state_space)
func = lambda s: self.probability(Eq(rv, s), cond)*expr.subs(rv, s)
return sum([func(s) for s in state_space])
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
"implemented yet."%(expr, condition))
class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess):
"""
Represents discrete time Markov chain.
Parameters
==========
sym: Symbol/str
state_space: Set
Optional, by default, S.Reals
trans_probs: Matrix/ImmutableMatrix/MatrixSymbol
Optional, by default, None
Examples
========
>>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf
>>> from sympy import Matrix, MatrixSymbol, Eq
>>> from sympy.stats import P
>>> 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)
>>> YS = DiscreteMarkovChain("Y")
>>> Y.state_space
FiniteSet(0, 1, 2)
>>> Y.transition_probabilities
Matrix([
[0.5, 0.2, 0.3],
[0.2, 0.5, 0.3],
[0.2, 0.3, 0.5]])
>>> TS = MatrixSymbol('T', 3, 3)
>>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS))
T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
0.36
References
==========
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain
.. [2] https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
"""
index_set = S.Naturals0
def __new__(cls, sym, state_space=S.Reals, trans_probs=None):
sym = _symbol_converter(sym)
state_space = _set_converter(state_space)
if trans_probs != None:
trans_probs = _matrix_checks(trans_probs)
return Basic.__new__(cls, sym, state_space, trans_probs)
@property
def transition_probabilities(self):
"""
Transition probabilities of discrete Markov chain,
either an instance of Matrix or MatrixSymbol.
"""
return self.args[2]
def _transient2transient(self):
"""
Computes the one step probabilities of transient
states to transient states. Used in finding
fundamental matrix, absorbing probabilties.
"""
trans_probs = self.transition_probabilities
if not isinstance(trans_probs, ImmutableMatrix):
return None
m = trans_probs.shape[0]
trans_states = [i for i in range(m) if trans_probs[i, i] != 1]
t2t = [[trans_probs[si, sj] for sj in trans_states] for si in trans_states]
return ImmutableMatrix(t2t)
def _transient2absorbing(self):
"""
Computes the one step probabilities of transient
states to absorbing states. Used in finding
fundamental matrix, absorbing probabilties.
"""
trans_probs = self.transition_probabilities
if not isinstance(trans_probs, ImmutableMatrix):
return None
m, trans_states, absorb_states = \
trans_probs.shape[0], [], []
for i in range(m):
if trans_probs[i, i] == 1:
absorb_states.append(i)
else:
trans_states.append(i)
if not absorb_states or not trans_states:
return None
t2a = [[trans_probs[si, sj] for sj in absorb_states]
for si in trans_states]
return ImmutableMatrix(t2a)
def fundamental_matrix(self):
Q = self._transient2transient()
if Q == None:
return None
I = eye(Q.shape[0])
if (I - Q).det() == 0:
raise ValueError("Fundamental matrix doesn't exists.")
return ImmutableMatrix((I - Q).inv().tolist())
def absorbing_probabilites(self):
"""
Computes the absorbing probabilities, i.e.,
the ij-th entry of the matrix denotes the
probability of Markov chain being absorbed
in state j starting from state i.
"""
R = self._transient2absorbing()
N = self.fundamental_matrix()
if R == None or N == None:
return None
return N*R
def is_regular(self):
w = self.fixed_row_vector()
if w is None or isinstance(w, (Lambda)):
return None
return all((wi > 0) == True for wi in w.row(0))
def is_absorbing_state(self, state):
trans_probs = self.transition_probabilities
if isinstance(trans_probs, ImmutableMatrix) and \
state < trans_probs.shape[0]:
return S(trans_probs[state, state]) is S.One
def is_absorbing_chain(self):
trans_probs = self.transition_probabilities
return any(self.is_absorbing_state(state) == True
for state in range(trans_probs.shape[0]))
def fixed_row_vector(self):
trans_probs = self.transition_probabilities
if trans_probs == None:
return None
if isinstance(trans_probs, MatrixSymbol):
wm = MatrixSymbol('wm', 1, trans_probs.shape[0])
return Lambda((wm, trans_probs), Eq(wm*trans_probs, wm))
w = IndexedBase('w')
wi = [w[i] for i in range(trans_probs.shape[0])]
wm = Matrix([wi])
eqs = (wm*trans_probs - wm).tolist()[0]
eqs.append(sum(wi) - 1)
soln = list(linsolve(eqs, wi))[0]
return ImmutableMatrix([[sol for sol in soln]])
@property
def limiting_distribution(self):
"""
The fixed row vector is the limiting
distribution of a discrete Markov chain.
"""
return self.fixed_row_vector()
def sample(self):
"""
Returns
=======
sample: iterator object
iterator object containing the sample
"""
if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)):
raise ValueError("Transition Matrix must be provided for sampling")
Tlist = self.transition_probabilities.tolist()
samps = [random.choice(list(self.state_space))]
yield samps[0]
time = 1
densities = {}
for state in self.state_space:
states = list(self.state_space)
densities[state] = {states[i]: Tlist[state][i]
for i in range(len(states))}
while time < S.Infinity:
samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]])))))
yield samps[time]
time += 1
class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess):
"""
Represents continuous time Markov chain.
Parameters
==========
sym: Symbol/str
state_space: Set
Optional, by default, S.Reals
gen_mat: Matrix/ImmutableMatrix/MatrixSymbol
Optional, by default, None
Examples
========
>>> from sympy.stats import ContinuousMarkovChain
>>> from sympy import Matrix, S
>>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]])
>>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G)
>>> C.limiting_distribution()
Matrix([[1/2, 1/2]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain
.. [2] http://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf
"""
index_set = S.Reals
def __new__(cls, sym, state_space=S.Reals, gen_mat=None):
sym = _symbol_converter(sym)
state_space = _set_converter(state_space)
if gen_mat != None:
gen_mat = _matrix_checks(gen_mat)
return Basic.__new__(cls, sym, state_space, gen_mat)
@property
def generator_matrix(self):
return self.args[2]
@cacheit
def transition_probabilities(self, gen_mat=None):
t = Dummy('t')
if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \
gen_mat.is_diagonalizable():
# for faster computation use diagonalized generator matrix
Q, D = gen_mat.diagonalize()
return Lambda(t, Q*exp(t*D)*Q.inv())
if gen_mat != None:
return Lambda(t, exp(t*gen_mat))
def limiting_distribution(self):
gen_mat = self.generator_matrix
if gen_mat == None:
return None
if isinstance(gen_mat, MatrixSymbol):
wm = MatrixSymbol('wm', 1, gen_mat.shape[0])
return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm))
w = IndexedBase('w')
wi = [w[i] for i in range(gen_mat.shape[0])]
wm = Matrix([wi])
eqs = (wm*gen_mat).tolist()[0]
eqs.append(sum(wi) - 1)
soln = list(linsolve(eqs, wi))[0]
return ImmutableMatrix([[sol for sol in soln]])
class BernoulliProcess(DiscreteTimeStochasticProcess):
"""
The Bernoulli process consists of repeated
independent Bernoulli process trials with the same parameter `p`.
It's assumed that the probability `p` applies to every
trial and that the outcomes of each trial
are independent of all the rest. Therefore Bernoulli Processs
is Discrete State and Discrete Time Stochastic Process.
Parameters
==========
sym: Symbol/str
success: Integer/str
The event which is considered to be success, by default is 1.
failure: Integer/str
The event which is considered to be failure, by default is 0.
p: Real Number between 0 and 1
Represents the probability of getting success.
Examples
========
>>> from sympy.stats import BernoulliProcess, P, E
>>> from sympy import Eq, Gt
>>> B = BernoulliProcess("B", p=0.7, success=1, failure=0)
>>> B.state_space
FiniteSet(0, 1)
>>> (B.p).round(2)
0.70
>>> B.success
1
>>> B.failure
0
>>> X = B[1] + B[2] + B[3]
>>> P(Eq(X, 0)).round(2)
0.03
>>> P(Eq(X, 2)).round(2)
0.44
>>> P(Eq(X, 4)).round(2)
0
>>> P(Gt(X, 1)).round(2)
0.78
>>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2)
0.04
>>> B.joint_distribution(B[1], B[2])
JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)),
(0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)),
(0, True))))
>>> E(2*B[1] + B[2]).round(2)
2.10
>>> P(B[1] < 1).round(2)
0.30
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_process
.. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf
"""
index_set = S.Naturals0
def __new__(cls, sym, p, success=1, failure=0):
_value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.')
sym = _symbol_converter(sym)
p = _sympify(p)
success = _sym_sympify(success)
failure = _sym_sympify(failure)
return Basic.__new__(cls, sym, p, success, failure)
@property
def symbol(self):
return self.args[0]
@property
def p(self):
return self.args[1]
@property
def success(self):
return self.args[2]
@property
def failure(self):
return self.args[3]
@property
def state_space(self):
return _set_converter([self.success, self.failure])
@property
def distribution(self):
return BernoulliDistribution(self.p)
def simple_rv(self, rv):
return Bernoulli(rv.name, p=self.p,
succ=self.success, fail=self.failure)
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Computes expectation.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
Returns
=======
Expectation of the RandomIndexedSymbol.
"""
return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs)
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Computes probability.
Parameters
==========
condition: Relational
Condition for which probability has to be computed. Must
contain a RandomIndexedSymbol of the process.
given_condition: Relational/And
The given conditions under which computations should be done.
Returns
=======
Probability of the condition.
"""
return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs)
def density(self, x):
return Piecewise((self.p, Eq(x, self.success)),
(1 - self.p, Eq(x, self.failure)),
(S.Zero, True))
class _SubstituteRV:
"""
Internal class to handle the queries of expectation and probability
by substitution.
"""
@staticmethod
def _rvindexed_subs(expr, condition=None):
"""
Substitutes the RandomIndexedSymbol with the RandomSymbol with
same name, distribution and probability as RandomIndexedSymbol.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
"""
rvs_expr = random_symbols(expr)
if len(rvs_expr) != 0:
swapdict_expr = {}
for rv in rvs_expr:
if isinstance(rv, RandomIndexedSymbol):
newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv
swapdict_expr[rv] = newrv
expr = expr.subs(swapdict_expr)
rvs_cond = random_symbols(condition)
if len(rvs_cond)!=0:
swapdict_cond = {}
for rv in rvs_cond:
if isinstance(rv, RandomIndexedSymbol):
newrv = rv.pspace.process.simple_rv(rv)
swapdict_cond[rv] = newrv
condition = condition.subs(swapdict_cond)
return expr, condition
@classmethod
def _expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Internal method for computing expectation of indexed RV.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
Returns
=======
Expectation of the RandomIndexedSymbol.
"""
new_expr, new_condition = self._rvindexed_subs(expr, condition)
if not is_random(new_expr):
return new_expr
new_pspace = pspace(new_expr)
if new_condition is not None:
new_expr = given(new_expr, new_condition)
if new_expr.is_Add: # As E is Linear
return Add(*[new_pspace.compute_expectation(
expr=arg, evaluate=evaluate, **kwargs)
for arg in new_expr.args])
return new_pspace.compute_expectation(
new_expr, evaluate=evaluate, **kwargs)
@classmethod
def _probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Internal method for computing probability of indexed RV
Parameters
==========
condition: Relational
Condition for which probability has to be computed. Must
contain a RandomIndexedSymbol of the process.
given_condition: Relational/And
The given conditions under which computations should be done.
Returns
=======
Probability of the condition.
"""
new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition)
if isinstance(new_givencondition, RandomSymbol):
condrv = random_symbols(new_condition)
if len(condrv) == 1 and condrv[0] == new_givencondition:
return BernoulliDistribution(self._probability(new_condition), 0, 1)
if any([dependent(rv, new_givencondition) for rv in condrv]):
return Probability(new_condition, new_givencondition)
else:
return self._probability(new_condition)
if new_givencondition is not None and \
not isinstance(new_givencondition, (Relational, Boolean)):
raise ValueError("%s is not a relational or combination of relationals"
% (new_givencondition))
if new_givencondition == False or new_condition == False:
return S.Zero
if new_condition == True:
return S.One
if not isinstance(new_condition, (Relational, Boolean)):
raise ValueError("%s is not a relational or combination of relationals"
% (new_condition))
if new_givencondition is not None: # If there is a condition
# Recompute on new conditional expr
return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs)
result = pspace(new_condition).probability(new_condition, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def get_timerv_swaps(expr, condition):
"""
Finds the appropriate interval for each time stamp in expr by parsing
the given condition and returns intervals for each timestamp and
dictionary that maps variable time-stamped Random Indexed Symbol to its
corresponding Random Indexed variable with fixed time stamp.
Parameters
==========
expr: Sympy Expression
Expression containing Random Indexed Symbols with variable time stamps
condition: Relational/Boolean Expression
Expression containing time bounds of variable time stamps in expr
Examples
========
>>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess
>>> from sympy import symbols, Contains, Interval
>>> x, t, d = symbols('x t d', positive=True)
>>> X = PoissonProcess("X", 3)
>>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1)))
([Interval.Lopen(0, 1)], {X(t): X(1)})
>>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1))
... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP
([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)})
Returns
=======
intervals: list
List of Intervals/FiniteSet on which each time stamp is defined
rv_swap: dict
Dictionary mapping variable time Random Indexed Symbol to constant time
Random Indexed Variable
"""
if not isinstance(condition, (Relational, Boolean)):
raise ValueError("%s is not a relational or combination of relationals"
% (condition))
expr_syms = list(expr.atoms(RandomIndexedSymbol))
if isinstance(condition, (And, Or)):
given_cond_args = condition.args
else: # single condition
given_cond_args = (condition, )
rv_swap = {}
intervals = []
for expr_sym in expr_syms:
for arg in given_cond_args:
if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol):
intv = _set_converter(arg.args[1])
diff_key = intv._sup - intv._inf
if diff_key == oo:
raise ValueError("%s should have finite bounds" % str(expr_sym.name))
elif diff_key == S.Zero: # has singleton set
diff_key = intv._sup
rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key})
intervals.append(intv)
return intervals, rv_swap
class CountingProcess(ContinuousTimeStochasticProcess):
"""
This class handles the common methods of the Counting Processes
such as Poisson, Wiener and Gamma Processes
"""
index_set = _set_converter(Interval(0, oo))
@property
def symbol(self):
return self.args[0]
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Computes expectation
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Boolean
The given conditions under which computations should be done, i.e,
the intervals on which each variable time stamp in expr is defined
Returns
=======
Expectation of the given expr
"""
if condition is not None:
intervals, rv_swap = get_timerv_swaps(expr, condition)
# they are independent when they have non-overlapping intervals
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
for intv_comb in itertools.combinations(intervals, 2)):
if expr.is_Add:
return Add.fromiter(self.expectation(arg, condition)
for arg in expr.args)
expr = expr.subs(rv_swap)
else:
return Expectation(expr, condition)
return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs)
def _solve_argwith_tworvs(self, arg):
if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq):
diff_key = abs(arg.args[0].key - arg.args[1].key)
rv = arg.args[0]
arg = arg.__class__(rv.pspace.process(diff_key), 0)
else:
diff_key = arg.args[1].key - arg.args[0].key
rv = arg.args[1]
arg = arg.__class__(rv.pspace.process(diff_key), 0)
return arg
def _solve_numerical(self, condition, given_condition=None):
if isinstance(condition, And):
args_list = list(condition.args)
else:
args_list = [condition]
if given_condition is not None:
if isinstance(given_condition, And):
args_list.extend(list(given_condition.args))
else:
args_list.extend([given_condition])
# sort the args based on timestamp to get the independent increments in
# each segment using all the condition args as well as given_condition args
args_list = sorted(args_list, key=lambda x: x.args[0].key)
result = []
cond_args = list(condition.args) if isinstance(condition, And) else [condition]
if args_list[0] in cond_args and not (is_random(args_list[0].args[0])
and is_random(args_list[0].args[1])):
result.append(_SubstituteRV._probability(args_list[0]))
if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]):
arg = self._solve_argwith_tworvs(args_list[0])
result.append(_SubstituteRV._probability(arg))
for i in range(len(args_list) - 1):
curr, nex = args_list[i], args_list[i + 1]
diff_key = nex.args[0].key - curr.args[0].key
working_set = curr.args[0].pspace.process.state_space
if curr.args[1] > nex.args[1]: #impossible condition so return 0
result.append(0)
break
if isinstance(curr, Eq):
working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo))
else:
working_set = Intersection(working_set, curr.as_set())
if isinstance(nex, Eq):
working_set = Intersection(working_set, Interval(-oo, nex.args[1]))
else:
working_set = Intersection(working_set, nex.as_set())
if working_set == EmptySet:
rv = Eq(curr.args[0].pspace.process(diff_key), 0)
result.append(_SubstituteRV._probability(rv))
else:
if working_set.is_finite_set:
if isinstance(curr, Eq) and isinstance(nex, Eq):
rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set))
result.append(_SubstituteRV._probability(rv))
elif isinstance(curr, Eq) ^ isinstance(nex, Eq):
result.append(Add.fromiter(_SubstituteRV._probability(Eq(
curr.args[0].pspace.process(diff_key), x))
for x in range(len(working_set))))
else:
n = len(working_set)
result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq(
curr.args[0].pspace.process(diff_key), x)) for x in range(n)))
else:
result.append(_SubstituteRV._probability(
curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf))
return Mul.fromiter(result)
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Computes probability
Parameters
==========
condition: Relational
Condition for which probability has to be computed. Must
contain a RandomIndexedSymbol of the process.
given_condition: Relational, Boolean
The given conditions under which computations should be done, i.e,
the intervals on which each variable time stamp in expr is defined
Returns
=======
Probability of the condition
"""
check_numeric = True
if isinstance(condition, (And, Or)):
cond_args = condition.args
else:
cond_args = (condition, )
# check that condition args are numeric or not
if not all(arg.args[0].key.is_number for arg in cond_args):
check_numeric = False
if given_condition is not None:
check_given_numeric = True
if isinstance(given_condition, (And, Or)):
given_cond_args = given_condition.args
else:
given_cond_args = (given_condition, )
# check that given condition args are numeric or not
if given_condition.has(Contains):
check_given_numeric = False
# Handle numerical queries
if check_numeric and check_given_numeric:
res = []
if isinstance(condition, Or):
res.append(Add.fromiter(self._solve_numerical(arg, given_condition)
for arg in condition.args))
if isinstance(given_condition, Or):
res.append(Add.fromiter(self._solve_numerical(condition, arg)
for arg in given_condition.args))
if res:
return Add.fromiter(res)
return self._solve_numerical(condition, given_condition)
# No numeric queries, go by Contains?... then check that all the
# given condition are in form of `Contains`
if not all(arg.has(Contains) for arg in given_cond_args):
raise ValueError("If given condition is passed with `Contains`, then "
"please pass the evaluated condition with its corresponding information "
"in terms of intervals of each time stamp to be passed in given condition.")
intervals, rv_swap = get_timerv_swaps(condition, given_condition)
# they are independent when they have non-overlapping intervals
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
for intv_comb in itertools.combinations(intervals, 2)):
if isinstance(condition, And):
return Mul.fromiter(self.probability(arg, given_condition)
for arg in condition.args)
elif isinstance(condition, Or):
return Add.fromiter(self.probability(arg, given_condition)
for arg in condition.args)
condition = condition.subs(rv_swap)
else:
return Probability(condition, given_condition)
if check_numeric:
return self._solve_numerical(condition)
return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs)
class PoissonProcess(CountingProcess):
"""
The Poisson process is a counting process. It is usually used in scenarios
where we are counting the occurrences of certain events that appear
to happen at a certain rate, but completely at random.
Parameters
==========
sym: Symbol/str
lamda: Positive number
Rate of the process, ``lamda > 0``
Examples
========
>>> from sympy.stats import PoissonProcess, P, E
>>> from sympy import symbols, Eq, Ne, Contains, Interval
>>> X = PoissonProcess("X", lamda=3)
>>> X.state_space
Naturals0
>>> X.lamda
3
>>> t1, t2 = symbols('t1 t2', positive=True)
>>> P(X(t1) < 4)
(9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1)
>>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4)))
1 - 36*exp(-6)
>>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2))
... & Contains(t2, Interval.Lopen(2, 4)))
648*exp(-12)
>>> E(X(t1))
3*t1
>>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
... & Contains(t2, Interval.Lopen(1, 2)))
18
>>> P(X(3) < 1, Eq(X(1), 0))
exp(-6)
>>> P(Eq(X(4), 3), Eq(X(2), 3))
exp(-6)
>>> P(X(2) <= 3, X(1) > 1)
5*exp(-3)
Merging two Poisson Processes
>>> Y = PoissonProcess("Y", lamda=4)
>>> Z = X + Y
>>> Z.lamda
7
Splitting a Poisson Process into two independent Poisson Processes
>>> N, M = Z.split(l1=2, l2=5)
>>> N.lamda, M.lamda
(2, 5)
References
==========
.. [1] https://www.probabilitycourse.com
.. [2] https://en.wikipedia.org/wiki/Poisson_point_process
"""
def __new__(cls, sym, lamda):
_value_check(lamda > 0, 'lamda should be a positive number.')
sym = _symbol_converter(sym)
lamda = _sympify(lamda)
return Basic.__new__(cls, sym, lamda)
@property
def lamda(self):
return self.args[1]
@property
def state_space(self):
return S.Naturals0
def distribution(self, rv):
return PoissonDistribution(self.lamda*rv.key)
def density(self, x):
return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key))
def simple_rv(self, rv):
return Poisson(rv.name, lamda=self.lamda*rv.key)
def __add__(self, other):
if not isinstance(other, PoissonProcess):
raise ValueError("Only instances of Poisson Process can be merged")
return PoissonProcess(Dummy(self.symbol.name + other.symbol.name),
self.lamda + other.lamda)
def split(self, l1, l2):
if _sympify(l1 + l2) != self.lamda:
raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda))
return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2)
class WienerProcess(CountingProcess):
"""
The Wiener process is a real valued continuous-time stochastic process.
In physics it is used to study Brownian motion and therefore also known as
Brownian Motion.
Parameters
==========
sym: Symbol/str
Examples
========
>>> from sympy.stats import WienerProcess, P, E
>>> from sympy import symbols, Contains, Interval
>>> X = WienerProcess("X")
>>> X.state_space
Reals
>>> t1, t2 = symbols('t1 t2', positive=True)
>>> P(X(t1) < 7).simplify()
erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2
>>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify()
-erf(1)/2 + erf(2)/2 + 1
>>> E(X(t1))
0
>>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
... & Contains(t2, Interval.Lopen(1, 2)))
0
References
==========
.. [1] https://www.probabilitycourse.com
.. [2] https://en.wikipedia.org/wiki/Wiener_process
"""
def __new__(cls, sym):
sym = _symbol_converter(sym)
return Basic.__new__(cls, sym)
@property
def state_space(self):
return S.Reals
def distribution(self, rv):
return NormalDistribution(0, sqrt(rv.key))
def density(self, x):
return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key))
def simple_rv(self, rv):
return Normal(rv.name, 0, sqrt(rv.key))
class GammaProcess(CountingProcess):
"""
A Gamma process is a random process with independent gamma distributed
increments. It is a pure-jump increasing Levy process.
Parameters
==========
sym: Symbol/str
lamda: Positive number
Jump size of the process, ``lamda > 0``
gamma: Positive number
Rate of jump arrivals, ``gamma > 0``
Examples
========
>>> from sympy.stats import GammaProcess, E, P, variance
>>> from sympy import symbols, Contains, Interval, Not
>>> t, d, x, l, g = symbols('t d x l g', positive=True)
>>> X = GammaProcess("X", l, g)
>>> E(X(t))
g*t/l
>>> variance(X(t)).simplify()
g*t/l**2
>>> X = GammaProcess('X', 1, 2)
>>> P(X(t) < 1).simplify()
lowergamma(2*t, 1)/gamma(2*t)
>>> 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
>>> E(X(2) + x*E(X(5)))
10*x + 4
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_process
"""
def __new__(cls, sym, lamda, gamma):
_value_check(lamda > 0, 'lamda should be a positive number')
_value_check(gamma > 0, 'gamma should be a positive number')
sym = _symbol_converter(sym)
gamma = _sympify(gamma)
lamda = _sympify(lamda)
return Basic.__new__(cls, sym, lamda, gamma)
@property
def lamda(self):
return self.args[1]
@property
def gamma(self):
return self.args[2]
@property
def state_space(self):
return _set_converter(Interval(0, oo))
def distribution(self, rv):
return GammaDistribution(self.gamma*rv.key, 1/self.lamda)
def density(self, x):
k = self.gamma*x.key
theta = 1/self.lamda
return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)
def simple_rv(self, rv):
return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
|
86a828c5502fb8e6c88bd2fdf80b8e0e80807e33537f7ab9c693aee5a2a1535e | from sympy import S, Basic, exp, multigamma, pi
from sympy.core.sympify import sympify, _sympify
from sympy.matrices import (ImmutableMatrix, Inverse, Trace, Determinant,
MatrixSymbol, MatrixBase, Transpose, MatrixSet,
matrix2numpy)
from sympy.stats.rv import (_value_check, RandomMatrixSymbol, NamedArgsMixin, PSpace,
_symbol_converter, MatrixDomain)
from sympy.external import import_module
scipy = import_module('scipy')
numpy = import_module('numpy')
pymc3 = import_module('pymc3')
################################################################################
#------------------------Matrix Probability Space------------------------------#
################################################################################
class MatrixPSpace(PSpace):
"""
Represents probability space for
Matrix Distributions
"""
def __new__(cls, sym, distribution, dim_n, dim_m):
sym = _symbol_converter(sym)
dim_n, dim_m = _sympify(dim_n), _sympify(dim_m)
if not (dim_n.is_integer and dim_m.is_integer):
raise ValueError("Dimensions should be integers")
return Basic.__new__(cls, sym, distribution, dim_n, dim_m)
distribution = property(lambda self: self.args[1])
symbol = property(lambda self: self.args[0])
@property
def domain(self):
return MatrixDomain(self.symbol, self.distribution.set)
@property
def value(self):
return RandomMatrixSymbol(self.symbol, self.args[2], self.args[3], self)
@property
def values(self):
return {self.value}
def compute_density(self, expr, *args):
rms = expr.atoms(RandomMatrixSymbol)
if len(rms) > 1 or (not isinstance(expr, RandomMatrixSymbol)):
raise NotImplementedError("Currently, no algorithm has been "
"implemented to handle general expressions containing "
"multiple matrix distributions.")
return self.distribution.pdf(expr)
def sample(self, size=(), library='scipy'):
"""
Internal sample method
Returns dictionary mapping RandomMatrixSymbol to realization value.
"""
return {self.value: self.distribution.sample(size, library=library)}
def rv(symbol, cls, args):
args = list(map(sympify, args))
dist = cls(*args)
dist.check(*args)
dim = dist.dimension
pspace = MatrixPSpace(symbol, dist, dim[0], dim[1])
return pspace.value
class SampleMatrixScipy:
"""Returns the sample from scipy of the given distribution"""
def __new__(cls, dist, size):
return cls._sample_scipy(dist, size)
scipy_rv_map = {
'WishartDistribution': lambda dist, size: scipy.stats.wishart.rvs(
df=int(dist.n), scale=matrix2numpy(dist.scale_matrix, float), size=size),
'MatrixNormalDistribution': lambda dist, size: scipy.stats.matrix_normal.rvs(
mean=matrix2numpy(dist.location_matrix, float),
rowcov=matrix2numpy(dist.scale_matrix_1, float),
colcov=matrix2numpy(dist.scale_matrix_2, float), size=size)
}
@classmethod
def _sample_scipy(cls, dist, size):
"""Sample from SciPy."""
dist_list = cls.scipy_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
return cls.scipy_rv_map[dist.__class__.__name__](dist, size)
class SampleMatrixNumpy:
"""Returns the sample from numpy of the given distribution"""
### TODO: Add tests after adding matrix distributions in numpy_rv_map
def __new__(cls, dist, size):
return cls._sample_numpy(dist, size)
numpy_rv_map = {
}
@classmethod
def _sample_numpy(cls, dist, size):
"""Sample from NumPy."""
dist_list = cls.numpy_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
return cls.numpy_rv_map[dist.__class__.__name__](dist, size)
class SampleMatrixPymc:
"""Returns the sample from pymc3 of the given distribution"""
def __new__(cls, dist, size):
return cls._sample_pymc3(dist, size)
pymc3_rv_map = {
'MatrixNormalDistribution': lambda dist: pymc3.MatrixNormal('X',
mu=matrix2numpy(dist.location_matrix, float),
rowcov=matrix2numpy(dist.scale_matrix_1, float),
colcov=matrix2numpy(dist.scale_matrix_2, float),
shape=dist.location_matrix.shape),
'WishartDistribution': lambda dist: pymc3.WishartBartlett('X',
nu=int(dist.n), S=matrix2numpy(dist.scale_matrix, float))
}
@classmethod
def _sample_pymc3(cls, dist, size):
"""Sample from PyMC3."""
dist_list = cls.pymc3_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
with pymc3.Model():
cls.pymc3_rv_map[dist.__class__.__name__](dist)
return pymc3.sample(size, chains=1, progressbar=False)[:]['X']
_get_sample_class_matrixrv = {
'scipy': SampleMatrixScipy,
'pymc3': SampleMatrixPymc,
'numpy': SampleMatrixNumpy
}
################################################################################
#-------------------------Matrix Distribution----------------------------------#
################################################################################
class MatrixDistribution(Basic, NamedArgsMixin):
"""
Abstract class for Matrix Distribution
"""
def __new__(cls, *args):
args = list(map(sympify, args))
return Basic.__new__(cls, *args)
@staticmethod
def check(*args):
pass
def __call__(self, expr):
if isinstance(expr, list):
expr = ImmutableMatrix(expr)
return self.pdf(expr)
def sample(self, size=(), library='scipy'):
"""
Internal sample method
Returns dictionary mapping RandomSymbol to realization value.
"""
libraries = ['scipy', 'numpy', 'pymc3']
if library not in libraries:
raise NotImplementedError("Sampling from %s is not supported yet."
% str(library))
if not import_module(library):
raise ValueError("Failed to import %s" % library)
samps = _get_sample_class_matrixrv[library](self, size)
if samps is not None:
return samps
raise NotImplementedError(
"Sampling for %s is not currently implemented from %s"
% (self.__class__.__name__, library)
)
################################################################################
#------------------------Matrix Distribution Types-----------------------------#
################################################################################
#-------------------------------------------------------------------------------
# Matrix Gamma distribution ----------------------------------------------------
class MatrixGammaDistribution(MatrixDistribution):
_argnames = ('alpha', 'beta', 'scale_matrix')
@staticmethod
def check(alpha, beta, scale_matrix):
if not isinstance(scale_matrix , MatrixSymbol):
_value_check(scale_matrix.is_positive_definite, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix.is_square, "Should "
"be square matrix")
_value_check(alpha.is_positive, "Shape parameter should be positive.")
_value_check(beta.is_positive, "Scale parameter should be positive.")
@property
def set(self):
k = self.scale_matrix.shape[0]
return MatrixSet(k, k, S.Reals)
@property
def dimension(self):
return self.scale_matrix.shape
def pdf(self, x):
alpha , beta , scale_matrix = self.alpha, self.beta, self.scale_matrix
p = scale_matrix.shape[0]
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
sigma_inv_x = - Inverse(scale_matrix)*x / beta
term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p))
term2 = (Determinant(scale_matrix))**(-alpha)
term3 = (Determinant(x))**(alpha - S(p + 1)/2)
return term1 * term2 * term3
def MatrixGamma(symbol, alpha, beta, scale_matrix):
"""
Creates a random variable with Matrix Gamma Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
alpha: Positive Real number
Shape Parameter
beta: Positive Real number
Scale Parameter
scale_matrix: Positive definite real square matrix
Scale Matrix
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, MatrixGamma
>>> from sympy import MatrixSymbol, symbols
>>> a, b = symbols('a b', positive=True)
>>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]])
>>> X = MatrixSymbol('X', 2, 2)
>>> density(M)(X).doit()
3**(-a)*b**(-2*a)*exp(Trace(Matrix([
[-2/3, 1/3],
[ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(sqrt(pi)*gamma(a)*gamma(a - 1/2))
>>> density(M)([[1, 0], [0, 1]]).doit()
3**(-a)*b**(-2*a)*exp(-4/(3*b))/(sqrt(pi)*gamma(a)*gamma(a - 1/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution
"""
if isinstance(scale_matrix, list):
scale_matrix = ImmutableMatrix(scale_matrix)
return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix))
#-------------------------------------------------------------------------------
# Wishart Distribution ---------------------------------------------------------
class WishartDistribution(MatrixDistribution):
_argnames = ('n', 'scale_matrix')
@staticmethod
def check(n, scale_matrix):
if not isinstance(scale_matrix , MatrixSymbol):
_value_check(scale_matrix.is_positive_definite, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix.is_square, "Should "
"be square matrix")
_value_check(n.is_positive, "Shape parameter should be positive.")
@property
def set(self):
k = self.scale_matrix.shape[0]
return MatrixSet(k, k, S.Reals)
@property
def dimension(self):
return self.scale_matrix.shape
def pdf(self, x):
n, scale_matrix = self.n, self.scale_matrix
p = scale_matrix.shape[0]
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
sigma_inv_x = - Inverse(scale_matrix)*x / S(2)
term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p))
term2 = (Determinant(scale_matrix))**(-n/S(2))
term3 = (Determinant(x))**(S(n - p - 1)/2)
return term1 * term2 * term3
def Wishart(symbol, n, scale_matrix):
"""
Creates a random variable with Wishart Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
n: Positive Real number
Represents degrees of freedom
scale_matrix: Positive definite real square matrix
Scale Matrix
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, Wishart
>>> from sympy import MatrixSymbol, symbols
>>> n = symbols('n', positive=True)
>>> W = Wishart('W', n, [[2, 1], [1, 2]])
>>> X = MatrixSymbol('X', 2, 2)
>>> density(W)(X).doit()
2**(-n)*3**(-n/2)*exp(Trace(Matrix([
[-1/3, 1/6],
[ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2))
>>> density(W)([[1, 0], [0, 1]]).doit()
2**(-n)*3**(-n/2)*exp(-2/3)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Wishart_distribution
"""
if isinstance(scale_matrix, list):
scale_matrix = ImmutableMatrix(scale_matrix)
return rv(symbol, WishartDistribution, (n, scale_matrix))
#-------------------------------------------------------------------------------
# Matrix Normal distribution ---------------------------------------------------
class MatrixNormalDistribution(MatrixDistribution):
_argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2')
@staticmethod
def check(location_matrix, scale_matrix_1, scale_matrix_2):
if not isinstance(scale_matrix_1 , MatrixSymbol):
_value_check(scale_matrix_1.is_positive_definite, "The shape "
"matrix must be positive definite.")
if not isinstance(scale_matrix_2 , MatrixSymbol):
_value_check(scale_matrix_2.is_positive_definite, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix_1.is_square, "Scale matrix 1 should be "
"be square matrix")
_value_check(scale_matrix_2.is_square, "Scale matrix 2 should be "
"be square matrix")
n = location_matrix.shape[0]
p = location_matrix.shape[1]
_value_check(scale_matrix_1.shape[0] == n, "Scale matrix 1 should be"
" of shape %s x %s"% (str(n), str(n)))
_value_check(scale_matrix_2.shape[0] == p, "Scale matrix 2 should be"
" of shape %s x %s"% (str(p), str(p)))
@property
def set(self):
n, p = self.location_matrix.shape
return MatrixSet(n, p, S.Reals)
@property
def dimension(self):
return self.location_matrix.shape
def pdf(self, x):
M , U , V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2
n, p = M.shape
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M)
num = exp(-Trace(term1)/S(2))
den = (2*pi)**(S(n*p)/2) * Determinant(U)**S(p)/2 * Determinant(V)**S(n)/2
return num/den
def MatrixNormal(symbol, location_matrix, scale_matrix_1, scale_matrix_2):
"""
Creates a random variable with Matrix Normal Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
location_matrix: Real ``n x p`` matrix
Represents degrees of freedom
scale_matrix_1: Positive definite matrix
Scale Matrix of shape ``n x n``
scale_matrix_2: Positive definite matrix
Scale Matrix of shape ``p x p``
Returns
=======
RandomSymbol
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.stats import density, MatrixNormal
>>> M = MatrixNormal('M', [[1, 2]], [1], [[1, 0], [0, 1]])
>>> X = MatrixSymbol('X', 1, 2)
>>> density(M)(X).doit()
2*exp(-Trace((Matrix([
[-1],
[-2]]) + X.T)*(Matrix([[-1, -2]]) + X))/2)/pi
>>> density(M)([[3, 4]]).doit()
2*exp(-4)/pi
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution
"""
if isinstance(location_matrix, list):
location_matrix = ImmutableMatrix(location_matrix)
if isinstance(scale_matrix_1, list):
scale_matrix_1 = ImmutableMatrix(scale_matrix_1)
if isinstance(scale_matrix_2, list):
scale_matrix_2 = ImmutableMatrix(scale_matrix_2)
args = (location_matrix, scale_matrix_1, scale_matrix_2)
return rv(symbol, MatrixNormalDistribution, args)
|
963b181026147d473ed1e42806d7322e11298bbc3821ecc6b0c5590b94247db0 | """
SymPy statistics module
Introduces a random variable type into the SymPy language.
Random variables may be declared using prebuilt functions such as
Normal, Exponential, Coin, Die, etc... or built with functions like FiniteRV.
Queries on random expressions can be made using the functions
========================= =============================
Expression Meaning
------------------------- -----------------------------
``P(condition)`` Probability
``E(expression)`` Expected value
``H(expression)`` Entropy
``variance(expression)`` Variance
``density(expression)`` Probability Density Function
``sample(expression)`` Produce a realization
``where(condition)`` Where the condition is true
========================= =============================
Examples
========
>>> from sympy.stats import P, E, variance, Die, Normal
>>> from sympy import Eq, simplify
>>> X, Y = Die('X', 6), Die('Y', 6) # Define two six sided dice
>>> Z = Normal('Z', 0, 1) # Declare a Normal random variable with mean 0, std 1
>>> P(X>3) # Probability X is greater than 3
1/2
>>> E(X+Y) # Expectation of the sum of two dice
7
>>> variance(X+Y) # Variance of the sum of two dice
35/6
>>> simplify(P(Z>1)) # Probability of Z being greater than 1
1/2 - erf(sqrt(2)/2)/2
One could also create custom distribution and define custom random variables
as follows:
1. If the you want to create a Continuous Random Variable:
>>> from sympy.stats import ContinuousRV, P, E
>>> from sympy import exp, Symbol, Interval, oo
>>> x = Symbol('x')
>>> pdf = exp(-x) # pdf of the Continuous Distribution
>>> Z = ContinuousRV(x, pdf, set=Interval(0, oo))
>>> E(Z)
1
>>> P(Z > 5)
exp(-5)
1.1 To create an instance of Continuous Distribution:
>>> from sympy.stats import ContinuousDistributionHandmade
>>> from sympy import Lambda
>>> dist = ContinuousDistributionHandmade(Lambda(x, pdf), set=Interval(0, oo))
>>> dist.pdf(x)
exp(-x)
2. If you want to create a Discrete Random Variable:
>>> from sympy.stats import DiscreteRV, P, E
>>> from sympy import Symbol, S
>>> p = S(1)/2
>>> x = Symbol('x', integer=True, positive=True)
>>> pdf = p*(1 - p)**(x - 1)
>>> D = DiscreteRV(x, pdf, set=S.Naturals)
>>> E(D)
2
>>> P(D > 3)
1/8
2.1 To create an instance of Discrete Distribution:
>>> from sympy.stats import DiscreteDistributionHandmade
>>> from sympy import Lambda
>>> dist = DiscreteDistributionHandmade(Lambda(x, pdf), set=S.Naturals)
>>> dist.pdf(x)
2**(1 - x)/2
3. If the you want to create a Finite Random Variable:
>>> from sympy.stats import FiniteRV, P, E
>>> from sympy import Rational
>>> pmf = {1: Rational(1, 3), 2: Rational(1, 6), 3: Rational(1, 4), 4: Rational(1, 4)}
>>> X = FiniteRV('X', pmf)
>>> E(X)
29/12
>>> P(X > 3)
1/4
3.1 To create an instance of Finite Distribution:
>>> from sympy.stats import FiniteDistributionHandmade
>>> dist = FiniteDistributionHandmade(pmf)
>>> dist.pmf(x)
Lambda(x, Piecewise((1/3, Eq(x, 1)), (1/6, Eq(x, 2)), (1/4, Eq(x, 3) | Eq(x, 4)), (0, True)))
"""
__all__ = [
'P', 'E', 'H', 'density', 'where', 'given', 'sample', 'cdf','median',
'characteristic_function', 'pspace', 'sample_iter', 'variance', 'std',
'skewness', 'kurtosis', 'covariance', 'dependent', 'entropy', 'independent',
'random_symbols', 'correlation', 'factorial_moment', 'moment', 'cmoment',
'sampling_density', 'moment_generating_function', 'smoment', 'quantile',
'coskewness', 'sample_stochastic_process',
'FiniteRV', 'DiscreteUniform', 'Die', 'Bernoulli', 'Coin', 'Binomial',
'BetaBinomial', 'Hypergeometric', 'Rademacher',
'FiniteDistributionHandmade',
'ContinuousRV', 'Arcsin', 'Benini', 'Beta', 'BetaNoncentral', 'BetaPrime',
'BoundedPareto', 'Cauchy', 'Chi', 'ChiNoncentral', 'ChiSquared', 'Dagum', 'Erlang',
'ExGaussian', 'Exponential', 'ExponentialPower', 'FDistribution',
'FisherZ', 'Frechet', 'Gamma', 'GammaInverse', 'Gompertz', 'Gumbel',
'Kumaraswamy', 'Laplace', 'Levy', 'Logistic', 'LogLogistic', 'LogNormal', 'Lomax',
'Moyal', 'Maxwell', 'Nakagami', 'Normal', 'GaussianInverse', 'Pareto', 'PowerFunction',
'QuadraticU', 'RaisedCosine', 'Rayleigh','Reciprocal', 'StudentT', 'ShiftedGompertz',
'Trapezoidal', 'Triangular', 'Uniform', 'UniformSum', 'VonMises', 'Wald',
'Weibull', 'WignerSemicircle', 'ContinuousDistributionHandmade',
'Geometric','Hermite', 'Logarithmic', 'NegativeBinomial', 'Poisson', 'Skellam',
'YuleSimon', 'Zeta', 'DiscreteRV', 'DiscreteDistributionHandmade',
'JointRV', 'Dirichlet', 'GeneralizedMultivariateLogGamma',
'GeneralizedMultivariateLogGammaOmega', 'Multinomial', 'MultivariateBeta',
'MultivariateEwens', 'MultivariateT', 'NegativeMultinomial',
'NormalGamma', 'MultivariateNormal', 'MultivariateLaplace', 'marginal_distribution',
'StochasticProcess', 'DiscreteTimeStochasticProcess',
'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf',
'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess',
'PoissonProcess', 'WienerProcess', 'GammaProcess',
'CircularEnsemble', 'CircularUnitaryEnsemble',
'CircularOrthogonalEnsemble', 'CircularSymplecticEnsemble',
'GaussianEnsemble', 'GaussianUnitaryEnsemble',
'GaussianOrthogonalEnsemble', 'GaussianSymplecticEnsemble',
'joint_eigen_distribution', 'JointEigenDistribution',
'level_spacing_distribution',
'MatrixGamma', 'Wishart', 'MatrixNormal',
'Probability', 'Expectation', 'Variance', 'Covariance', 'Moment',
'CentralMoment',
'ExpectationMatrix', 'VarianceMatrix', 'CrossCovarianceMatrix'
]
from .rv_interface import (P, E, H, density, where, given, sample, cdf, median,
characteristic_function, pspace, sample_iter, variance, std, skewness,
kurtosis, covariance, dependent, entropy, independent, random_symbols,
correlation, factorial_moment, moment, cmoment, sampling_density,
moment_generating_function, smoment, quantile, coskewness,
sample_stochastic_process)
from .frv_types import (FiniteRV, DiscreteUniform, Die, Bernoulli, Coin,
Binomial, BetaBinomial, Hypergeometric, Rademacher,
FiniteDistributionHandmade)
from .crv_types import (ContinuousRV, Arcsin, Benini, Beta, BetaNoncentral,
BetaPrime, BoundedPareto, Cauchy, Chi, ChiNoncentral, ChiSquared, Dagum, Erlang,
ExGaussian, Exponential, ExponentialPower, FDistribution, FisherZ,
Frechet, Gamma, GammaInverse, Gompertz, Gumbel, Kumaraswamy, Laplace,
Levy, Logistic, LogLogistic, LogNormal, Lomax, Maxwell, Moyal, Nakagami, Normal,
GaussianInverse, Pareto, QuadraticU, RaisedCosine, Rayleigh, Reciprocal, StudentT,
PowerFunction, ShiftedGompertz, Trapezoidal, Triangular, Uniform, UniformSum,
VonMises, Wald, Weibull, WignerSemicircle, ContinuousDistributionHandmade)
from .drv_types import (Geometric, Hermite, Logarithmic, NegativeBinomial, Poisson,
Skellam, YuleSimon, Zeta, DiscreteRV, DiscreteDistributionHandmade)
from .joint_rv_types import (JointRV, Dirichlet,
GeneralizedMultivariateLogGamma, GeneralizedMultivariateLogGammaOmega,
Multinomial, MultivariateBeta, MultivariateEwens, MultivariateT,
NegativeMultinomial, NormalGamma, MultivariateNormal, MultivariateLaplace,
marginal_distribution)
from .stochastic_process_types import (StochasticProcess,
DiscreteTimeStochasticProcess, DiscreteMarkovChain,
TransitionMatrixOf, StochasticStateSpaceOf, GeneratorMatrixOf,
ContinuousMarkovChain, BernoulliProcess, PoissonProcess, WienerProcess,
GammaProcess)
from .random_matrix_models import (CircularEnsemble, CircularUnitaryEnsemble,
CircularOrthogonalEnsemble, CircularSymplecticEnsemble,
GaussianEnsemble, GaussianUnitaryEnsemble, GaussianOrthogonalEnsemble,
GaussianSymplecticEnsemble, joint_eigen_distribution,
JointEigenDistribution, level_spacing_distribution)
from .matrix_distributions import MatrixGamma, Wishart, MatrixNormal
from .symbolic_probability import (Probability, Expectation, Variance,
Covariance, Moment, CentralMoment)
from .symbolic_multivariate_probability import (ExpectationMatrix, VarianceMatrix,
CrossCovarianceMatrix)
|
3de5d917cdecd68b97ac922eff77419c21ac4049206d45a2e951c26e5e41c97f | """
Main Random Variables Module
Defines abstract random variable type.
Contains interfaces for probability space object (PSpace) as well as standard
operators, P, E, sample, density, where, quantile
See Also
========
sympy.stats.crv
sympy.stats.frv
sympy.stats.rv_interface
"""
from __future__ import print_function, division
from functools import singledispatch
from typing import Tuple as tTuple
from sympy import (Basic, S, Expr, Symbol, Tuple, And, Add, Eq, lambdify, Or,
Equality, Lambda, sympify, Dummy, Ne, KroneckerDelta,
DiracDelta, Mul, Indexed, MatrixSymbol, Function)
from sympy.core.relational import Relational
from sympy.core.sympify import _sympify
from sympy.sets.sets import FiniteSet, ProductSet, Intersection
from sympy.solvers.solveset import solveset
from sympy.external import import_module
from sympy.utilities.misc import filldedent
import warnings
x = Symbol('x')
@singledispatch
def is_random(x):
return False
@is_random.register(Basic)
def _(x):
atoms = x.free_symbols
return any([is_random(i) for i in atoms])
class RandomDomain(Basic):
"""
Represents a set of variables and the values which they can take
See Also
========
sympy.stats.crv.ContinuousDomain
sympy.stats.frv.FiniteDomain
"""
is_ProductDomain = False
is_Finite = False
is_Continuous = False
is_Discrete = False
def __new__(cls, symbols, *args):
symbols = FiniteSet(*symbols)
return Basic.__new__(cls, symbols, *args)
@property
def symbols(self):
return self.args[0]
@property
def set(self):
return self.args[1]
def __contains__(self, other):
raise NotImplementedError()
def compute_expectation(self, expr):
raise NotImplementedError()
class SingleDomain(RandomDomain):
"""
A single variable and its domain
See Also
========
sympy.stats.crv.SingleContinuousDomain
sympy.stats.frv.SingleFiniteDomain
"""
def __new__(cls, symbol, set):
assert symbol.is_Symbol
return Basic.__new__(cls, symbol, set)
@property
def symbol(self):
return self.args[0]
@property
def symbols(self):
return FiniteSet(self.symbol)
def __contains__(self, other):
if len(other) != 1:
return False
sym, val = tuple(other)[0]
return self.symbol == sym and val in self.set
class MatrixDomain(RandomDomain):
"""
A Random Matrix variable and its domain
"""
def __new__(cls, symbol, set):
symbol, set = _symbol_converter(symbol), _sympify(set)
return Basic.__new__(cls, symbol, set)
@property
def symbol(self):
return self.args[0]
@property
def symbols(self):
return FiniteSet(self.symbol)
class ConditionalDomain(RandomDomain):
"""
A RandomDomain with an attached condition
See Also
========
sympy.stats.crv.ConditionalContinuousDomain
sympy.stats.frv.ConditionalFiniteDomain
"""
def __new__(cls, fulldomain, condition):
condition = condition.xreplace(dict((rs, rs.symbol)
for rs in random_symbols(condition)))
return Basic.__new__(cls, fulldomain, condition)
@property
def symbols(self):
return self.fulldomain.symbols
@property
def fulldomain(self):
return self.args[0]
@property
def condition(self):
return self.args[1]
@property
def set(self):
raise NotImplementedError("Set of Conditional Domain not Implemented")
def as_boolean(self):
return And(self.fulldomain.as_boolean(), self.condition)
class PSpace(Basic):
"""
A Probability Space
Probability Spaces encode processes that equal different values
probabilistically. These underly Random Symbols which occur in SymPy
expressions and contain the mechanics to evaluate statistical statements.
See Also
========
sympy.stats.crv.ContinuousPSpace
sympy.stats.frv.FinitePSpace
"""
is_Finite = None # type: bool
is_Continuous = None # type: bool
is_Discrete = None # type: bool
is_real = None # type: bool
@property
def domain(self):
return self.args[0]
@property
def density(self):
return self.args[1]
@property
def values(self):
return frozenset(RandomSymbol(sym, self) for sym in self.symbols)
@property
def symbols(self):
return self.domain.symbols
def where(self, condition):
raise NotImplementedError()
def compute_density(self, expr):
raise NotImplementedError()
def sample(self):
raise NotImplementedError()
def probability(self, condition):
raise NotImplementedError()
def compute_expectation(self, expr):
raise NotImplementedError()
class SinglePSpace(PSpace):
"""
Represents the probabilities of a set of random events that can be
attributed to a single variable/symbol.
"""
def __new__(cls, s, distribution):
if isinstance(s, str):
s = Symbol(s)
if not isinstance(s, Symbol):
raise TypeError("s should have been string or Symbol")
return Basic.__new__(cls, s, distribution)
@property
def value(self):
return RandomSymbol(self.symbol, self)
@property
def symbol(self):
return self.args[0]
@property
def distribution(self):
return self.args[1]
@property
def pdf(self):
return self.distribution.pdf(self.symbol)
class RandomSymbol(Expr):
"""
Random Symbols represent ProbabilitySpaces in SymPy Expressions
In principle they can take on any value that their symbol can take on
within the associated PSpace with probability determined by the PSpace
Density.
Random Symbols contain pspace and symbol properties.
The pspace property points to the represented Probability Space
The symbol is a standard SymPy Symbol that is used in that probability space
for example in defining a density.
You can form normal SymPy expressions using RandomSymbols and operate on
those expressions with the Functions
E - Expectation of a random expression
P - Probability of a condition
density - Probability Density of an expression
given - A new random expression (with new random symbols) given a condition
An object of the RandomSymbol type should almost never be created by the
user. They tend to be created instead by the PSpace class's value method.
Traditionally a user doesn't even do this but instead calls one of the
convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
"""
def __new__(cls, symbol, pspace=None):
from sympy.stats.joint_rv import JointRandomSymbol
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
if isinstance(symbol, str):
symbol = Symbol(symbol)
if not isinstance(symbol, Symbol):
raise TypeError("symbol should be of type Symbol or string")
if not isinstance(pspace, PSpace):
raise TypeError("pspace variable should be of type PSpace")
if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace):
cls = RandomSymbol
return Basic.__new__(cls, symbol, pspace)
is_finite = True
is_symbol = True
is_Atom = True
_diff_wrt = True
pspace = property(lambda self: self.args[1])
symbol = property(lambda self: self.args[0])
name = property(lambda self: self.symbol.name)
def _eval_is_positive(self):
return self.symbol.is_positive
def _eval_is_integer(self):
return self.symbol.is_integer
def _eval_is_real(self):
return self.symbol.is_real or self.pspace.is_real
@property
def is_commutative(self):
return self.symbol.is_commutative
@property
def free_symbols(self):
return {self}
class RandomIndexedSymbol(RandomSymbol):
def __new__(cls, idx_obj, pspace=None):
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
if not isinstance(idx_obj, (Indexed, Function)):
raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj))
return Basic.__new__(cls, idx_obj, pspace)
symbol = property(lambda self: self.args[0])
name = property(lambda self: str(self.args[0]))
@property
def key(self):
if isinstance(self.symbol, Indexed):
return self.symbol.args[1]
elif isinstance(self.symbol, Function):
return self.symbol.args[0]
@property
def free_symbols(self):
if self.key.free_symbols:
free_syms = self.key.free_symbols
free_syms.add(self)
return free_syms
return {self}
class RandomMatrixSymbol(RandomSymbol, MatrixSymbol):
def __new__(cls, symbol, n, m, pspace=None):
n, m = _sympify(n), _sympify(m)
symbol = _symbol_converter(symbol)
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
return Basic.__new__(cls, symbol, n, m, pspace)
symbol = property(lambda self: self.args[0])
pspace = property(lambda self: self.args[3])
class ProductPSpace(PSpace):
"""
Abstract class for representing probability spaces with multiple random
variables.
See Also
========
sympy.stats.rv.IndependentProductPSpace
sympy.stats.joint_rv.JointPSpace
"""
pass
class IndependentProductPSpace(ProductPSpace):
"""
A probability space resulting from the merger of two independent probability
spaces.
Often created using the function, pspace
"""
def __new__(cls, *spaces):
rs_space_dict = {}
for space in spaces:
for value in space.values:
rs_space_dict[value] = space
symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()])
# Overlapping symbols
from sympy.stats.joint_rv import MarginalDistribution
from sympy.stats.compound_rv import CompoundDistribution
if len(symbols) < sum(len(space.symbols) for space in spaces if not
isinstance(space.distribution, (
CompoundDistribution, MarginalDistribution))):
raise ValueError("Overlapping Random Variables")
if all(space.is_Finite for space in spaces):
from sympy.stats.frv import ProductFinitePSpace
cls = ProductFinitePSpace
obj = Basic.__new__(cls, *FiniteSet(*spaces))
return obj
@property
def pdf(self):
p = Mul(*[space.pdf for space in self.spaces])
return p.subs(dict((rv, rv.symbol) for rv in self.values))
@property
def rs_space_dict(self):
d = {}
for space in self.spaces:
for value in space.values:
d[value] = space
return d
@property
def symbols(self):
return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()])
@property
def spaces(self):
return FiniteSet(*self.args)
@property
def values(self):
return sumsets(space.values for space in self.spaces)
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
rvs = rvs or self.values
rvs = frozenset(rvs)
for space in self.spaces:
expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs)
if evaluate and hasattr(expr, 'doit'):
return expr.doit(**kwargs)
return expr
@property
def domain(self):
return ProductDomain(*[space.domain for space in self.spaces])
@property
def density(self):
raise NotImplementedError("Density not available for ProductSpaces")
def sample(self, size=(), library='scipy'):
return {k: v for space in self.spaces
for k, v in space.sample(size=size, library=library).items()}
def probability(self, condition, **kwargs):
cond_inv = False
if isinstance(condition, Ne):
condition = Eq(condition.args[0], condition.args[1])
cond_inv = True
elif isinstance(condition, And): # they are independent
return Mul(*[self.probability(arg) for arg in condition.args])
elif isinstance(condition, Or): # they are independent
return Add(*[self.probability(arg) for arg in condition.args])
expr = condition.lhs - condition.rhs
rvs = random_symbols(expr)
dens = self.compute_density(expr)
if any([pspace(rv).is_Continuous for rv in rvs]):
from sympy.stats.crv import SingleContinuousPSpace
from sympy.stats.crv_types import ContinuousDistributionHandmade
if expr in self.values:
# Marginalize all other random symbols out of the density
randomsymbols = tuple(set(self.values) - frozenset([expr]))
symbols = tuple(rs.symbol for rs in randomsymbols)
pdf = self.domain.integrate(self.pdf, symbols, **kwargs)
return Lambda(expr.symbol, pdf)
dens = ContinuousDistributionHandmade(dens)
z = Dummy('z', real=True)
space = SingleContinuousPSpace(z, dens)
result = space.probability(condition.__class__(space.value, 0))
else:
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import DiscreteDistributionHandmade
dens = DiscreteDistributionHandmade(dens)
z = Dummy('z', integer=True)
space = SingleDiscretePSpace(z, dens)
result = space.probability(condition.__class__(space.value, 0))
return result if not cond_inv else S.One - result
def compute_density(self, expr, **kwargs):
rvs = random_symbols(expr)
if any(pspace(rv).is_Continuous for rv in rvs):
z = Dummy('z', real=True)
expr = self.compute_expectation(DiracDelta(expr - z),
**kwargs)
else:
z = Dummy('z', integer=True)
expr = self.compute_expectation(KroneckerDelta(expr, z),
**kwargs)
return Lambda(z, expr)
def compute_cdf(self, expr, **kwargs):
raise ValueError("CDF not well defined on multivariate expressions")
def conditional_space(self, condition, normalize=True, **kwargs):
rvs = random_symbols(condition)
condition = condition.xreplace(dict((rv, rv.symbol) for rv in self.values))
if any([pspace(rv).is_Continuous for rv in rvs]):
from sympy.stats.crv import (ConditionalContinuousDomain,
ContinuousPSpace)
space = ContinuousPSpace
domain = ConditionalContinuousDomain(self.domain, condition)
elif any([pspace(rv).is_Discrete for rv in rvs]):
from sympy.stats.drv import (ConditionalDiscreteDomain,
DiscretePSpace)
space = DiscretePSpace
domain = ConditionalDiscreteDomain(self.domain, condition)
elif all([pspace(rv).is_Finite for rv in rvs]):
from sympy.stats.frv import FinitePSpace
return FinitePSpace.conditional_space(self, condition)
if normalize:
replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
norm = domain.compute_expectation(self.pdf, **kwargs)
pdf = self.pdf / norm.xreplace(replacement)
# XXX: Converting symbols from set to tuple. The order matters to
# Lambda though so we shouldn't be starting with a set here...
density = Lambda(tuple(domain.symbols), pdf)
return space(domain, density)
class ProductDomain(RandomDomain):
"""
A domain resulting from the merger of two independent domains
See Also
========
sympy.stats.crv.ProductContinuousDomain
sympy.stats.frv.ProductFiniteDomain
"""
is_ProductDomain = True
def __new__(cls, *domains):
# Flatten any product of products
domains2 = []
for domain in domains:
if not domain.is_ProductDomain:
domains2.append(domain)
else:
domains2.extend(domain.domains)
domains2 = FiniteSet(*domains2)
if all(domain.is_Finite for domain in domains2):
from sympy.stats.frv import ProductFiniteDomain
cls = ProductFiniteDomain
if all(domain.is_Continuous for domain in domains2):
from sympy.stats.crv import ProductContinuousDomain
cls = ProductContinuousDomain
if all(domain.is_Discrete for domain in domains2):
from sympy.stats.drv import ProductDiscreteDomain
cls = ProductDiscreteDomain
return Basic.__new__(cls, *domains2)
@property
def sym_domain_dict(self):
return dict((symbol, domain) for domain in self.domains
for symbol in domain.symbols)
@property
def symbols(self):
return FiniteSet(*[sym for domain in self.domains
for sym in domain.symbols])
@property
def domains(self):
return self.args
@property
def set(self):
return ProductSet(*(domain.set for domain in self.domains))
def __contains__(self, other):
# Split event into each subdomain
for domain in self.domains:
# Collect the parts of this event which associate to this domain
elem = frozenset([item for item in other
if sympify(domain.symbols.contains(item[0]))
is S.true])
# Test this sub-event
if elem not in domain:
return False
# All subevents passed
return True
def as_boolean(self):
return And(*[domain.as_boolean() for domain in self.domains])
def random_symbols(expr):
"""
Returns all RandomSymbols within a SymPy Expression.
"""
atoms = getattr(expr, 'atoms', None)
if atoms is not None:
comp = lambda rv: rv.symbol.name
l = list(atoms(RandomSymbol))
return sorted(l, key=comp)
else:
return []
def pspace(expr):
"""
Returns the underlying Probability Space of a random expression.
For internal use.
Examples
========
>>> from sympy.stats import pspace, Normal
>>> X = Normal('X', 0, 1)
>>> pspace(2*X + 1) == X.pspace
True
"""
expr = sympify(expr)
if isinstance(expr, RandomSymbol) and expr.pspace is not None:
return expr.pspace
if expr.has(RandomMatrixSymbol):
rm = list(expr.atoms(RandomMatrixSymbol))[0]
return rm.pspace
rvs = random_symbols(expr)
if not rvs:
raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
# If only one space present
if all(rv.pspace == rvs[0].pspace for rv in rvs):
return rvs[0].pspace
from sympy.stats.compound_rv import CompoundPSpace
for rv in rvs:
if isinstance(rv.pspace, CompoundPSpace):
return rv.pspace
# Otherwise make a product space
return IndependentProductPSpace(*[rv.pspace for rv in rvs])
def sumsets(sets):
"""
Union of sets
"""
return frozenset().union(*sets)
def rs_swap(a, b):
"""
Build a dictionary to swap RandomSymbols based on their underlying symbol.
i.e.
if ``X = ('x', pspace1)``
and ``Y = ('x', pspace2)``
then ``X`` and ``Y`` match and the key, value pair
``{X:Y}`` will appear in the result
Inputs: collections a and b of random variables which share common symbols
Output: dict mapping RVs in a to RVs in b
"""
d = {}
for rsa in a:
d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0]
return d
def given(expr, condition=None, **kwargs):
r""" Conditional Random Expression
From a random expression and a condition on that expression creates a new
probability space from the condition and returns the same expression on that
conditional probability space.
Examples
========
>>> from sympy.stats import given, density, Die
>>> X = Die('X', 6)
>>> Y = given(X, X > 3)
>>> density(Y).dict
{4: 1/3, 5: 1/3, 6: 1/3}
Following convention, if the condition is a random symbol then that symbol
is considered fixed.
>>> from sympy.stats import Normal
>>> from sympy import pprint
>>> from sympy.abc import z
>>> X = Normal('X', 0, 1)
>>> Y = Normal('Y', 0, 1)
>>> pprint(density(X + Y, Y)(z), use_unicode=False)
2
-(-Y + z)
-----------
___ 2
\/ 2 *e
------------------
____
2*\/ pi
"""
if not is_random(condition) or pspace_independent(expr, condition):
return expr
if isinstance(condition, RandomSymbol):
condition = Eq(condition, condition.symbol)
condsymbols = random_symbols(condition)
if (isinstance(condition, Equality) and len(condsymbols) == 1 and
not isinstance(pspace(expr).domain, ConditionalDomain)):
rv = tuple(condsymbols)[0]
results = solveset(condition, rv)
if isinstance(results, Intersection) and S.Reals in results.args:
results = list(results.args[1])
sums = 0
for res in results:
temp = expr.subs(rv, res)
if temp == True:
return True
if temp != False:
# XXX: This seems nonsensical but preserves existing behaviour
# after the change that Relational is no longer a subclass of
# Expr. Here expr is sometimes Relational and sometimes Expr
# but we are trying to add them with +=. This needs to be
# fixed somehow.
if sums == 0 and isinstance(expr, Relational):
sums = expr.subs(rv, res)
else:
sums += expr.subs(rv, res)
if sums == 0:
return False
return sums
# Get full probability space of both the expression and the condition
fullspace = pspace(Tuple(expr, condition))
# Build new space given the condition
space = fullspace.conditional_space(condition, **kwargs)
# Dictionary to swap out RandomSymbols in expr with new RandomSymbols
# That point to the new conditional space
swapdict = rs_swap(fullspace.values, space.values)
# Swap random variables in the expression
expr = expr.xreplace(swapdict)
return expr
def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs):
"""
Returns the expected value of a random expression
Parameters
==========
expr : Expr containing RandomSymbols
The expression of which you want to compute the expectation value
given : Expr containing RandomSymbols
A conditional expression. E(X, X>0) is expectation of X given X > 0
numsamples : int
Enables sampling and approximates the expectation with this many samples
evalf : Bool (defaults to True)
If sampling return a number rather than a complex expression
evaluate : Bool (defaults to True)
In case of continuous systems return unevaluated integral
Examples
========
>>> from sympy.stats import E, Die
>>> X = Die('X', 6)
>>> E(X)
7/2
>>> E(2*X + 1)
8
>>> E(X, X > 3) # Expectation of X given that it is above 3
5
"""
if not is_random(expr): # expr isn't random?
return expr
kwargs['numsamples'] = numsamples
from sympy.stats.symbolic_probability import Expectation
if evaluate:
return Expectation(expr, condition).doit(**kwargs)
### TODO: Remove the user warnings in the future releases
message = ("Since version 1.7, using `evaluate=False` returns `Expectation` "
"object. If you want unevaluated Integral/Sum use "
"`E(expr, condition, evaluate=False).rewrite(Integral)`")
warnings.warn(filldedent(message))
return Expectation(expr, condition)
def probability(condition, given_condition=None, numsamples=None,
evaluate=True, **kwargs):
"""
Probability that a condition is true, optionally given a second condition
Parameters
==========
condition : Combination of Relationals containing RandomSymbols
The condition of which you want to compute the probability
given_condition : Combination of Relationals containing RandomSymbols
A conditional expression. P(X > 1, X > 0) is expectation of X > 1
given X > 0
numsamples : int
Enables sampling and approximates the probability with this many samples
evaluate : Bool (defaults to True)
In case of continuous systems return unevaluated integral
Examples
========
>>> from sympy.stats import P, Die
>>> from sympy import Eq
>>> X, Y = Die('X', 6), Die('Y', 6)
>>> P(X > 3)
1/2
>>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2
1/4
>>> P(X > Y)
5/12
"""
kwargs['numsamples'] = numsamples
from sympy.stats.symbolic_probability import Probability
if evaluate:
return Probability(condition, given_condition).doit(**kwargs)
### TODO: Remove the user warnings in the future releases
message = ("Since version 1.7, using `evaluate=False` returns `Probability` "
"object. If you want unevaluated Integral/Sum use "
"`P(condition, given_condition, evaluate=False).rewrite(Integral)`")
warnings.warn(filldedent(message))
return Probability(condition, given_condition)
class Density(Basic):
expr = property(lambda self: self.args[0])
@property
def condition(self):
if len(self.args) > 1:
return self.args[1]
else:
return None
def doit(self, evaluate=True, **kwargs):
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.stats.joint_rv import JointPSpace
from sympy.stats.matrix_distributions import MatrixPSpace
from sympy.stats.compound_rv import CompoundPSpace
from sympy.stats.frv import SingleFiniteDistribution
expr, condition = self.expr, self.condition
if isinstance(expr, SingleFiniteDistribution):
return expr.dict
if condition is not None:
# Recompute on new conditional expr
expr = given(expr, condition, **kwargs)
if not random_symbols(expr):
return Lambda(x, DiracDelta(x - expr))
if isinstance(expr, RandomSymbol):
if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \
hasattr(expr.pspace, 'distribution'):
return expr.pspace.distribution
elif isinstance(expr.pspace, RandomMatrixPSpace):
return expr.pspace.model
if isinstance(pspace(expr), CompoundPSpace):
kwargs['compound_evaluate'] = evaluate
result = pspace(expr).compute_density(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs):
"""
Probability density of a random expression, optionally given a second
condition.
This density will take on different forms for different types of
probability spaces. Discrete variables produce Dicts. Continuous
variables produce Lambdas.
Parameters
==========
expr : Expr containing RandomSymbols
The expression of which you want to compute the density value
condition : Relational containing RandomSymbols
A conditional expression. density(X > 1, X > 0) is density of X > 1
given X > 0
numsamples : int
Enables sampling and approximates the density with this many samples
Examples
========
>>> from sympy.stats import density, Die, Normal
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> D = Die('D', 6)
>>> X = Normal(x, 0, 1)
>>> density(D).dict
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
>>> density(2*D).dict
{2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6}
>>> density(X)(x)
sqrt(2)*exp(-x**2/2)/(2*sqrt(pi))
"""
if numsamples:
return sampling_density(expr, condition, numsamples=numsamples,
**kwargs)
return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
def cdf(expr, condition=None, evaluate=True, **kwargs):
"""
Cumulative Distribution Function of a random expression.
optionally given a second condition
This density will take on different forms for different types of
probability spaces.
Discrete variables produce Dicts.
Continuous variables produce Lambdas.
Examples
========
>>> from sympy.stats import density, Die, Normal, cdf
>>> D = Die('D', 6)
>>> X = Normal('X', 0, 1)
>>> density(D).dict
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
>>> cdf(D)
{1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
>>> cdf(3*D, D > 2)
{9: 1/4, 12: 1/2, 15: 3/4, 18: 1}
>>> cdf(X)
Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2)
"""
if condition is not None: # If there is a condition
# Recompute on new conditional expr
return cdf(given(expr, condition, **kwargs), **kwargs)
# Otherwise pass work off to the ProbabilitySpace
result = pspace(expr).compute_cdf(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def characteristic_function(expr, condition=None, evaluate=True, **kwargs):
"""
Characteristic function of a random expression, optionally given a second condition
Returns a Lambda
Examples
========
>>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function
>>> X = Normal('X', 0, 1)
>>> characteristic_function(X)
Lambda(_t, exp(-_t**2/2))
>>> Y = DiscreteUniform('Y', [1, 2, 7])
>>> characteristic_function(Y)
Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3)
>>> Z = Poisson('Z', 2)
>>> characteristic_function(Z)
Lambda(_t, exp(2*exp(_t*I) - 2))
"""
if condition is not None:
return characteristic_function(given(expr, condition, **kwargs), **kwargs)
result = pspace(expr).compute_characteristic_function(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def moment_generating_function(expr, condition=None, evaluate=True, **kwargs):
if condition is not None:
return moment_generating_function(given(expr, condition, **kwargs), **kwargs)
result = pspace(expr).compute_moment_generating_function(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def where(condition, given_condition=None, **kwargs):
"""
Returns the domain where a condition is True.
Examples
========
>>> from sympy.stats import where, Die, Normal
>>> from sympy import And
>>> D1, D2 = Die('a', 6), Die('b', 6)
>>> a, b = D1.symbol, D2.symbol
>>> X = Normal('x', 0, 1)
>>> where(X**2<1)
Domain: (-1 < x) & (x < 1)
>>> where(X**2<1).set
Interval.open(-1, 1)
>>> where(And(D1<=D2 , D2<3))
Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2))
"""
if given_condition is not None: # If there is a condition
# Recompute on new conditional expr
return where(given(condition, given_condition, **kwargs), **kwargs)
# Otherwise pass work off to the ProbabilitySpace
return pspace(condition).where(condition, **kwargs)
def sample(expr, condition=None, size=(), library='scipy', numsamples=1,
**kwargs):
"""
A realization of the random expression
Parameters
==========
expr : Expression of random variables
Expression from which sample is extracted
condition : Expr containing RandomSymbols
A conditional expression
size : int, tuple
Represents size of each sample in numsamples
library : str
- 'scipy' : Sample using scipy
- 'numpy' : Sample using numpy
- 'pymc3' : Sample using PyMC3
Choose any of the available options to sample from as string,
by default is 'scipy'
numsamples : int
Number of samples, each with size as ``size``
Examples
========
>>> from sympy.stats import Die, sample, Normal, Geometric
>>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable
>>> die_roll = sample(X + Y + Z) # doctest: +SKIP
>>> next(die_roll) # doctest: +SKIP
6
>>> N = Normal('N', 3, 4) # Continuous Random Variable
>>> samp = next(sample(N)) # doctest: +SKIP
>>> samp in N.pspace.domain.set # doctest: +SKIP
True
>>> samp = next(sample(N, N>0)) # doctest: +SKIP
>>> samp > 0 # doctest: +SKIP
True
>>> samp_list = next(sample(N, size=4)) # doctest: +SKIP
>>> [sam in N.pspace.domain.set for sam in samp_list] # doctest: +SKIP
[True, True, True, True]
>>> G = Geometric('G', 0.5) # Discrete Random Variable
>>> samp_list = next(sample(G, size=3)) # doctest: +SKIP
>>> samp_list # doctest: +SKIP
array([10, 4, 1])
>>> [sam in G.pspace.domain.set for sam in samp_list] # doctest: +SKIP
[True, True, True]
>>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable
>>> samp_list = next(sample(MN, size=4)) # doctest: +SKIP
>>> samp_list # doctest: +SKIP
array([[4.22564264, 3.23364418],
[3.41002011, 4.60090908],
[3.76151866, 4.77617143],
[4.71440865, 2.65714157]])
>>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list] # doctest: +SKIP
[True, True, True, True]
Returns
=======
sample: iterator object
iterator object containing the sample/samples of given expr
"""
### TODO: Remove the user warnings in the future releases
message = ("The return type of sample has been changed to return an "
"iterator object since version 1.7. For more information see "
"https://github.com/sympy/sympy/issues/19061")
warnings.warn(filldedent(message))
return sample_iter(expr, condition, size=size, library=library,
numsamples=numsamples)
def quantile(expr, evaluate=True, **kwargs):
r"""
Return the :math:`p^{th}` order quantile of a probability distribution.
Quantile is defined as the value at which the probability of the random
variable is less than or equal to the given probability.
..math::
Q(p) = inf{x \in (-\infty, \infty) such that p <= F(x)}
Examples
========
>>> from sympy.stats import quantile, Die, Exponential
>>> from sympy import Symbol, pprint
>>> p = Symbol("p")
>>> l = Symbol("lambda", positive=True)
>>> X = Exponential("x", l)
>>> quantile(X)(p)
-log(1 - p)/lambda
>>> D = Die("d", 6)
>>> pprint(quantile(D)(p), use_unicode=False)
/nan for Or(p > 1, p < 0)
|
| 1 for p <= 1/6
|
| 2 for p <= 1/3
|
< 3 for p <= 1/2
|
| 4 for p <= 2/3
|
| 5 for p <= 5/6
|
\ 6 for p <= 1
"""
result = pspace(expr).compute_quantile(expr, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def sample_iter(expr, condition=None, size=(), library='scipy',
numsamples=S.Infinity, **kwargs):
"""
Returns an iterator of realizations from the expression given a condition
Parameters
==========
expr: Expr
Random expression to be realized
condition: Expr, optional
A conditional expression
size : int, tuple
Represents size of each sample in numsamples
numsamples: integer, optional
Length of the iterator (defaults to infinity)
Examples
========
>>> from sympy.stats import Normal, sample_iter
>>> X = Normal('X', 0, 1)
>>> expr = X*X + 3
>>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP
>>> list(iterator) # doctest: +SKIP
[12, 4, 7]
Returns
=======
sample_iter: iterator object
iterator object containing the sample/samples of given expr
See Also
========
sample
sampling_P
sampling_E
"""
from sympy.stats.joint_rv import JointRandomSymbol
if not import_module(library):
raise ValueError("Failed to import %s" % library)
if condition is not None:
ps = pspace(Tuple(expr, condition))
else:
ps = pspace(expr)
rvs = list(ps.values)
if isinstance(expr, JointRandomSymbol):
expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)})
else:
sub = {}
for arg in expr.args:
if isinstance(arg, JointRandomSymbol):
sub[arg] = RandomSymbol(arg.symbol, arg.pspace)
expr = expr.subs(sub)
if library == 'pymc3':
# Currently unable to lambdify in pymc3
# TODO : Remove 'pymc3' when lambdify accepts 'pymc3' as module
fn = lambdify(rvs, expr, **kwargs)
else:
fn = lambdify(rvs, expr, modules=library, **kwargs)
if condition is not None:
given_fn = lambdify(rvs, condition, **kwargs)
def return_generator():
count = 0
while count < numsamples:
d = ps.sample(size=size, library=library) # a dictionary that maps RVs to values
args = [d[rv] for rv in rvs]
if condition is not None: # Check that these values satisfy the condition
gd = given_fn(*args)
if gd != True and gd != False:
raise ValueError(
"Conditions must not contain free symbols")
if not gd: # If the values don't satisfy then try again
continue
yield fn(*args)
count += 1
return return_generator()
def sample_iter_lambdify(expr, condition=None, size=(), numsamples=S.Infinity,
**kwargs):
return sample_iter(expr, condition=condition, size=size, numsamples=numsamples,
**kwargs)
def sample_iter_subs(expr, condition=None, size=(), numsamples=S.Infinity,
**kwargs):
return sample_iter(expr, condition=condition, size=size, numsamples=numsamples,
**kwargs)
def sampling_P(condition, given_condition=None, library='scipy', numsamples=1,
evalf=True, **kwargs):
"""
Sampling version of P
See Also
========
P
sampling_E
sampling_density
"""
count_true = 0
count_false = 0
samples = sample_iter(condition, given_condition, library=library,
numsamples=numsamples, **kwargs)
for sample in samples:
if sample:
count_true += 1
else:
count_false += 1
result = S(count_true) / numsamples
if evalf:
return result.evalf()
else:
return result
def sampling_E(expr, given_condition=None, library='scipy', numsamples=1,
evalf=True, **kwargs):
"""
Sampling version of E
See Also
========
P
sampling_P
sampling_density
"""
samples = list(sample_iter(expr, given_condition, library=library,
numsamples=numsamples, **kwargs))
result = Add(*[samp for samp in samples]) / numsamples
if evalf:
return result.evalf()
else:
return result
def sampling_density(expr, given_condition=None, library='scipy',
numsamples=1, **kwargs):
"""
Sampling version of density
See Also
========
density
sampling_P
sampling_E
"""
results = {}
for result in sample_iter(expr, given_condition, library=library,
numsamples=numsamples, **kwargs):
results[result] = results.get(result, 0) + 1
return results
def dependent(a, b):
"""
Dependence of two random expressions
Two expressions are independent if knowledge of one does not change
computations on the other.
Examples
========
>>> from sympy.stats import Normal, dependent, given
>>> from sympy import Tuple, Eq
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
>>> dependent(X, Y)
False
>>> dependent(2*X + Y, -Y)
True
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
>>> dependent(X, Y)
True
See Also
========
independent
"""
if pspace_independent(a, b):
return False
z = Symbol('z', real=True)
# Dependent if density is unchanged when one is given information about
# the other
return (density(a, Eq(b, z)) != density(a) or
density(b, Eq(a, z)) != density(b))
def independent(a, b):
"""
Independence of two random expressions
Two expressions are independent if knowledge of one does not change
computations on the other.
Examples
========
>>> from sympy.stats import Normal, independent, given
>>> from sympy import Tuple, Eq
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
>>> independent(X, Y)
True
>>> independent(2*X + Y, -Y)
False
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
>>> independent(X, Y)
False
See Also
========
dependent
"""
return not dependent(a, b)
def pspace_independent(a, b):
"""
Tests for independence between a and b by checking if their PSpaces have
overlapping symbols. This is a sufficient but not necessary condition for
independence and is intended to be used internally.
Notes
=====
pspace_independent(a, b) implies independent(a, b)
independent(a, b) does not imply pspace_independent(a, b)
"""
a_symbols = set(pspace(b).symbols)
b_symbols = set(pspace(a).symbols)
if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0:
return False
if len(a_symbols.intersection(b_symbols)) == 0:
return True
return None
def rv_subs(expr, symbols=None):
"""
Given a random expression replace all random variables with their symbols.
If symbols keyword is given restrict the swap to only the symbols listed.
"""
if symbols is None:
symbols = random_symbols(expr)
if not symbols:
return expr
swapdict = {rv: rv.symbol for rv in symbols}
return expr.subs(swapdict)
class NamedArgsMixin(object):
_argnames = () # type: tTuple[str, ...]
def __getattr__(self, attr):
try:
return self.args[self._argnames.index(attr)]
except ValueError:
raise AttributeError("'%s' object has no attribute '%s'" % (
type(self).__name__, attr))
def _value_check(condition, message):
"""
Raise a ValueError with message if condition is False, else
return True if all conditions were True, else False.
Examples
========
>>> from sympy.stats.rv import _value_check
>>> from sympy.abc import a, b, c
>>> from sympy import And, Dummy
>>> _value_check(2 < 3, '')
True
Here, the condition is not False, but it doesn't evaluate to True
so False is returned (but no error is raised). So checking if the
return value is True or False will tell you if all conditions were
evaluated.
>>> _value_check(a < b, '')
False
In this case the condition is False so an error is raised:
>>> r = Dummy(real=True)
>>> _value_check(r < r - 1, 'condition is not true')
Traceback (most recent call last):
...
ValueError: condition is not true
If no condition of many conditions must be False, they can be
checked by passing them as an iterable:
>>> _value_check((a < 0, b < 0, c < 0), '')
False
The iterable can be a generator, too:
>>> _value_check((i < 0 for i in (a, b, c)), '')
False
The following are equivalent to the above but do not pass
an iterable:
>>> all(_value_check(i < 0, '') for i in (a, b, c))
False
>>> _value_check(And(a < 0, b < 0, c < 0), '')
False
"""
from sympy.core.compatibility import iterable
from sympy.core.logic import fuzzy_and
if not iterable(condition):
condition = [condition]
truth = fuzzy_and(condition)
if truth == False:
raise ValueError(message)
return truth == True
def _symbol_converter(sym):
"""
Casts the parameter to Symbol if it is 'str'
otherwise no operation is performed on it.
Parameters
==========
sym
The parameter to be converted.
Returns
=======
Symbol
the parameter converted to Symbol.
Raises
======
TypeError
If the parameter is not an instance of both str and
Symbol.
Examples
========
>>> from sympy import Symbol
>>> from sympy.stats.rv import _symbol_converter
>>> s = _symbol_converter('s')
>>> isinstance(s, Symbol)
True
>>> _symbol_converter(1)
Traceback (most recent call last):
...
TypeError: 1 is neither a Symbol nor a string
>>> r = Symbol('r')
>>> isinstance(r, Symbol)
True
"""
if isinstance(sym, str):
sym = Symbol(sym)
if not isinstance(sym, Symbol):
raise TypeError("%s is neither a Symbol nor a string"%(sym))
return sym
def sample_stochastic_process(process):
"""
This function is used to sample from stochastic process.
Parameters
==========
process: StochasticProcess
Process used to extract the samples. It must be an instance of
StochasticProcess
Examples
========
>>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain
>>> from sympy import Matrix
>>> 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)
>>> next(sample_stochastic_process(Y)) in Y.state_space # doctest: +SKIP
True
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
0
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
2
Returns
=======
sample: iterator object
iterator object containing the sample of given process
"""
from sympy.stats.stochastic_process_types import StochasticProcess
if not isinstance(process, StochasticProcess):
raise ValueError("Process must be an instance of Stochastic Process")
return process.sample()
|
348d9eb2190c55211bd577dde6578b0fc28fceccfa05fd76e318be4231fe73bb | """
Joint Random Variables Module
See Also
========
sympy.stats.rv
sympy.stats.frv
sympy.stats.crv
sympy.stats.drv
"""
from __future__ import print_function, division
from sympy import (Basic, Lambda, sympify, Indexed, Symbol, ProductSet, S,
Dummy)
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum, summation
from sympy.core.compatibility import iterable
from sympy.core.containers import Tuple
from sympy.integrals.integrals import Integral, integrate
from sympy.matrices import ImmutableMatrix, matrix2numpy, list2numpy
from sympy.stats.crv import SingleContinuousDistribution, SingleContinuousPSpace
from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace
from sympy.stats.rv import (ProductPSpace, NamedArgsMixin,
ProductDomain, RandomSymbol, random_symbols, SingleDomain)
from sympy.utilities.misc import filldedent
from sympy.external import import_module
# __all__ = ['marginal_distribution']
scipy = import_module('scipy')
numpy = import_module('numpy')
pymc3 = import_module('pymc3')
class JointPSpace(ProductPSpace):
"""
Represents a joint probability space. Represented using symbols for
each component and a distribution.
"""
def __new__(cls, sym, dist):
if isinstance(dist, SingleContinuousDistribution):
return SingleContinuousPSpace(sym, dist)
if isinstance(dist, SingleDiscreteDistribution):
return SingleDiscretePSpace(sym, dist)
if isinstance(sym, str):
sym = Symbol(sym)
if not isinstance(sym, Symbol):
raise TypeError("s should have been string or Symbol")
return Basic.__new__(cls, sym, dist)
@property
def set(self):
return self.domain.set
@property
def symbol(self):
return self.args[0]
@property
def distribution(self):
return self.args[1]
@property
def value(self):
return JointRandomSymbol(self.symbol, self)
@property
def component_count(self):
_set = self.distribution.set
if isinstance(_set, ProductSet):
return S(len(_set.args))
elif isinstance(_set, Product):
return _set.limits[0][-1]
return S.One
@property
def pdf(self):
sym = [Indexed(self.symbol, i) for i in range(self.component_count)]
return self.distribution(*sym)
@property
def domain(self):
rvs = random_symbols(self.distribution)
if not rvs:
return SingleDomain(self.symbol, self.distribution.set)
return ProductDomain(*[rv.pspace.domain for rv in rvs])
def component_domain(self, index):
return self.set.args[index]
def marginal_distribution(self, *indices):
count = self.component_count
if count.atoms(Symbol):
raise ValueError("Marginal distributions cannot be computed "
"for symbolic dimensions. It is a work under progress.")
orig = [Indexed(self.symbol, i) for i in range(count)]
all_syms = [Symbol(str(i)) for i in orig]
replace_dict = dict(zip(all_syms, orig))
sym = tuple(Symbol(str(Indexed(self.symbol, i))) for i in indices)
limits = list([i,] for i in all_syms if i not in sym)
index = 0
for i in range(count):
if i not in indices:
limits[index].append(self.distribution.set.args[i])
limits[index] = tuple(limits[index])
index += 1
if self.distribution.is_Continuous:
f = Lambda(sym, integrate(self.distribution(*all_syms), *limits))
elif self.distribution.is_Discrete:
f = Lambda(sym, summation(self.distribution(*all_syms), *limits))
return f.xreplace(replace_dict)
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
syms = tuple(self.value[i] for i in range(self.component_count))
rvs = rvs or syms
if not any([i in rvs for i in syms]):
return expr
expr = expr*self.pdf
for rv in rvs:
if isinstance(rv, Indexed):
expr = expr.xreplace({rv: Indexed(str(rv.base), rv.args[1])})
elif isinstance(rv, RandomSymbol):
expr = expr.xreplace({rv: rv.symbol})
if self.value in random_symbols(expr):
raise NotImplementedError(filldedent('''
Expectations of expression with unindexed joint random symbols
cannot be calculated yet.'''))
limits = tuple((Indexed(str(rv.base),rv.args[1]),
self.distribution.set.args[rv.args[1]]) for rv in syms)
return Integral(expr, *limits)
def where(self, condition):
raise NotImplementedError()
def compute_density(self, expr):
raise NotImplementedError()
def sample(self, size=(), library='scipy'):
"""
Internal sample method
Returns dictionary mapping RandomSymbol to realization value.
"""
return {RandomSymbol(self.symbol, self): self.distribution.sample(size,
library=library)}
def probability(self, condition):
raise NotImplementedError()
class SampleJointScipy:
"""Returns the sample from scipy of the given distribution"""
def __new__(cls, dist, size):
return cls._sample_scipy(dist, size)
scipy_rv_map = {
'MultivariateNormalDistribution': lambda dist, size: scipy.stats.multivariate_normal.rvs(
mean=matrix2numpy(dist.mu).flatten(),
cov=matrix2numpy(dist.sigma), size=size),
'MultivariateBetaDistribution': lambda dist, size: scipy.stats.dirichlet.rvs(
alpha=list2numpy(dist.alpha, float).flatten(), size=size),
'MultinomialDistribution': lambda dist, size: scipy.stats.multinomial.rvs(
n=int(dist.n), p=list2numpy(dist.p, float).flatten(), size=size)
}
@classmethod
def _sample_scipy(cls, dist, size):
"""Sample from SciPy."""
dist_list = cls.scipy_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
return cls.scipy_rv_map[dist.__class__.__name__](dist, size)
class SampleJointNumpy:
"""Returns the sample from numpy of the given distribution"""
def __new__(cls, dist, size):
return cls._sample_numpy(dist, size)
numpy_rv_map = {
'MultivariateNormalDistribution': lambda dist, size: numpy.random.multivariate_normal(
mean=matrix2numpy(dist.mu, float).flatten(),
cov=matrix2numpy(dist.sigma, float), size=size),
'MultivariateBetaDistribution': lambda dist, size: numpy.random.dirichlet(
alpha=list2numpy(dist.alpha, float).flatten(), size=size),
'MultinomialDistribution': lambda dist, size: numpy.random.multinomial(
n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size)
}
@classmethod
def _sample_numpy(cls, dist, size):
"""Sample from NumPy."""
dist_list = cls.numpy_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
return cls.numpy_rv_map[dist.__class__.__name__](dist, size)
class SampleJointPymc:
"""Returns the sample from pymc3 of the given distribution"""
def __new__(cls, dist, size):
return cls._sample_pymc3(dist, size)
pymc3_rv_map = {
'MultivariateNormalDistribution': lambda dist:
pymc3.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(),
cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])),
'MultivariateBetaDistribution': lambda dist:
pymc3.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()),
'MultinomialDistribution': lambda dist:
pymc3.Multinomial('X', n=int(dist.n),
p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p)))
}
@classmethod
def _sample_pymc3(cls, dist, size):
"""Sample from PyMC3."""
dist_list = cls.pymc3_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
with pymc3.Model():
cls.pymc3_rv_map[dist.__class__.__name__](dist)
return pymc3.sample(size, chains=1, progressbar=False)[:]['X']
_get_sample_class_jrv = {
'scipy': SampleJointScipy,
'pymc3': SampleJointPymc,
'numpy': SampleJointNumpy
}
class JointDistribution(Basic, NamedArgsMixin):
"""
Represented by the random variables part of the joint distribution.
Contains methods for PDF, CDF, sampling, marginal densities, etc.
"""
_argnames = ('pdf', )
def __new__(cls, *args):
args = list(map(sympify, args))
for i in range(len(args)):
if isinstance(args[i], list):
args[i] = ImmutableMatrix(args[i])
return Basic.__new__(cls, *args)
@property
def domain(self):
return ProductDomain(self.symbols)
@property
def pdf(self):
return self.density.args[1]
def cdf(self, other):
if not isinstance(other, dict):
raise ValueError("%s should be of type dict, got %s"%(other, type(other)))
rvs = other.keys()
_set = self.domain.set.sets
expr = self.pdf(tuple(i.args[0] for i in self.symbols))
for i in range(len(other)):
if rvs[i].is_Continuous:
density = Integral(expr, (rvs[i], _set[i].inf,
other[rvs[i]]))
elif rvs[i].is_Discrete:
density = Sum(expr, (rvs[i], _set[i].inf,
other[rvs[i]]))
return density
def sample(self, size=(), library='scipy'):
""" A random realization from the distribution """
libraries = ['scipy', 'numpy', 'pymc3']
if library not in libraries:
raise NotImplementedError("Sampling from %s is not supported yet."
% str(library))
if not import_module(library):
raise ValueError("Failed to import %s" % library)
samps = _get_sample_class_jrv[library](self, size)
if samps is not None:
return samps
raise NotImplementedError(
"Sampling for %s is not currently implemented from %s"
% (self.__class__.__name__, library)
)
def __call__(self, *args):
return self.pdf(*args)
class JointRandomSymbol(RandomSymbol):
"""
Representation of random symbols with joint probability distributions
to allow indexing."
"""
def __getitem__(self, key):
if isinstance(self.pspace, JointPSpace):
if (self.pspace.component_count <= key) == True:
raise ValueError("Index keys for %s can only up to %s." %
(self.name, self.pspace.component_count - 1))
return Indexed(self, key)
class MarginalDistribution(Basic):
"""
Represents the marginal distribution of a joint probability space.
Initialised using a probability distribution and random variables(or
their indexed components) which should be a part of the resultant
distribution.
"""
def __new__(cls, dist, *rvs):
if len(rvs) == 1 and iterable(rvs[0]):
rvs = tuple(rvs[0])
if not all([isinstance(rv, (Indexed, RandomSymbol))] for rv in rvs):
raise ValueError(filldedent('''Marginal distribution can be
intitialised only in terms of random variables or indexed random
variables'''))
rvs = Tuple.fromiter(rv for rv in rvs)
if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0:
return dist
return Basic.__new__(cls, dist, rvs)
def check(self):
pass
@property
def set(self):
rvs = [i for i in self.args[1] if isinstance(i, RandomSymbol)]
return ProductSet(*[rv.pspace.set for rv in rvs])
@property
def symbols(self):
rvs = self.args[1]
return set([rv.pspace.symbol for rv in rvs])
def pdf(self, *x):
expr, rvs = self.args[0], self.args[1]
marginalise_out = [i for i in random_symbols(expr) if i not in rvs]
if isinstance(expr, JointDistribution):
count = len(expr.domain.args)
x = Dummy('x', real=True, finite=True)
syms = tuple(Indexed(x, i) for i in count)
expr = expr.pdf(syms)
else:
syms = tuple(rv.pspace.symbol if isinstance(rv, RandomSymbol) else rv.args[0] for rv in rvs)
return Lambda(syms, self.compute_pdf(expr, marginalise_out))(*x)
def compute_pdf(self, expr, rvs):
for rv in rvs:
lpdf = 1
if isinstance(rv, RandomSymbol):
lpdf = rv.pspace.pdf
expr = self.marginalise_out(expr*lpdf, rv)
return expr
def marginalise_out(self, expr, rv):
from sympy.concrete.summations import Sum
if isinstance(rv, RandomSymbol):
dom = rv.pspace.set
elif isinstance(rv, Indexed):
dom = rv.base.component_domain(
rv.pspace.component_domain(rv.args[1]))
expr = expr.xreplace({rv: rv.pspace.symbol})
if rv.pspace.is_Continuous:
#TODO: Modify to support integration
#for all kinds of sets.
expr = Integral(expr, (rv.pspace.symbol, dom))
elif rv.pspace.is_Discrete:
#incorporate this into `Sum`/`summation`
if dom in (S.Integers, S.Naturals, S.Naturals0):
dom = (dom.inf, dom.sup)
expr = Sum(expr, (rv.pspace.symbol, dom))
return expr
def __call__(self, *args):
return self.pdf(*args)
|
755263de89f6d520833954ae6458cb2452f205c6bd413dae44409872811fd0d3 | from sympy import Basic, Sum, Dummy, Lambda, Integral
from sympy.stats.rv import (NamedArgsMixin, random_symbols, _symbol_converter,
PSpace, RandomSymbol, is_random)
from sympy.stats.crv import ContinuousDistribution, SingleContinuousPSpace
from sympy.stats.drv import DiscreteDistribution, SingleDiscretePSpace
from sympy.stats.frv import SingleFiniteDistribution, SingleFinitePSpace
from sympy.stats.crv_types import ContinuousDistributionHandmade
from sympy.stats.drv_types import DiscreteDistributionHandmade
from sympy.stats.frv_types import FiniteDistributionHandmade
class CompoundPSpace(PSpace):
"""
A temporary Probability Space for the Compound Distribution. After
Marginalization, this returns the corresponding Probability Space of the
parent distribution.
"""
def __new__(cls, s, distribution):
s = _symbol_converter(s)
if isinstance(distribution, ContinuousDistribution):
return SingleContinuousPSpace(s, distribution)
if isinstance(distribution, DiscreteDistribution):
return SingleDiscretePSpace(s, distribution)
if isinstance(distribution, SingleFiniteDistribution):
return SingleFinitePSpace(s, distribution)
if not isinstance(distribution, CompoundDistribution):
raise ValueError("%s should be an isinstance of "
"CompoundDistribution"%(distribution))
return Basic.__new__(cls, s, distribution)
@property
def value(self):
return RandomSymbol(self.symbol, self)
@property
def symbol(self):
return self.args[0]
@property
def is_Continuous(self):
return self.distribution.is_Continuous
@property
def is_Finite(self):
return self.distribution.is_Finite
@property
def is_Discrete(self):
return self.distribution.is_Discrete
@property
def distribution(self):
return self.args[1]
@property
def pdf(self):
return self.distribution.pdf(self.symbol)
@property
def set(self):
return self.distribution.set
@property
def domain(self):
return self._get_newpspace().domain
def _get_newpspace(self, evaluate=False):
x = Dummy('x')
parent_dist = self.distribution.args[0]
func = Lambda(x, self.distribution.pdf(x, evaluate))
new_pspace = self._transform_pspace(self.symbol, parent_dist, func)
if new_pspace is not None:
return new_pspace
message = ("Compound Distribution for %s is not implemeted yet" % str(parent_dist))
raise NotImplementedError(message)
def _transform_pspace(self, sym, dist, pdf):
"""
This function returns the new pspace of the distribution using handmade
Distributions and their corresponding pspace.
"""
pdf = Lambda(sym, pdf(sym))
_set = dist.set
if isinstance(dist, ContinuousDistribution):
return SingleContinuousPSpace(sym, ContinuousDistributionHandmade(pdf, _set))
elif isinstance(dist, DiscreteDistribution):
return SingleDiscretePSpace(sym, DiscreteDistributionHandmade(pdf, _set))
elif isinstance(dist, SingleFiniteDistribution):
dens = dict((k, pdf(k)) for k in _set)
return SingleFinitePSpace(sym, FiniteDistributionHandmade(dens))
def compute_density(self, expr, **kwargs):
new_pspace = self._get_newpspace(kwargs.pop('compound_evaluate', True))
expr = expr.subs({self.value: new_pspace.value})
return new_pspace.compute_density(expr, **kwargs)
def compute_cdf(self, expr, **kwargs):
new_pspace = self._get_newpspace(kwargs.pop('compound_evaluate', True))
expr = expr.subs({self.value: new_pspace.value})
return new_pspace.compute_cdf(expr, **kwargs)
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
new_pspace = self._get_newpspace(evaluate)
expr = expr.subs({self.value: new_pspace.value})
if rvs:
rvs = rvs.subs({self.value: new_pspace.value})
if isinstance(new_pspace, SingleFinitePSpace):
return new_pspace.compute_expectation(expr, rvs, **kwargs)
return new_pspace.compute_expectation(expr, rvs, evaluate, **kwargs)
def probability(self, condition, **kwargs):
new_pspace = self._get_newpspace(kwargs.pop('compound_evaluate', True))
condition = condition.subs({self.value: new_pspace.value})
return new_pspace.probability(condition)
def conditional_space(self, condition, **kwargs):
new_pspace = self._get_newpspace(kwargs.pop('compound_evaluate', True))
condition = condition.subs({self.value: new_pspace.value})
return new_pspace.conditional_space(condition)
class CompoundDistribution(Basic, NamedArgsMixin):
"""
Class for Compound Distributions.
Parameters
==========
dist : Distribution
Distribution must contain a random parameter
Examples
========
>>> from sympy.stats.compound_rv import CompoundDistribution
>>> from sympy.stats.crv_types import NormalDistribution
>>> from sympy.stats import Normal
>>> from sympy.abc import x
>>> X = Normal('X', 2, 4)
>>> N = NormalDistribution(X, 4)
>>> C = CompoundDistribution(N)
>>> C.set
Interval(-oo, oo)
>>> C.pdf(x, evaluate=True).simplify()
exp(-x**2/64 + x/16 - 1/16)/(8*sqrt(pi))
References
==========
.. [1] https://en.wikipedia.org/wiki/Compound_probability_distribution
"""
def __new__(cls, dist):
if not isinstance(dist, (ContinuousDistribution,
SingleFiniteDistribution, DiscreteDistribution)):
message = "Compound Distribution for %s is not implemeted yet" % str(dist)
raise NotImplementedError(message)
if not cls._compound_check(dist):
return dist
return Basic.__new__(cls, dist)
@property
def set(self):
return self.args[0].set
@property
def is_Continuous(self):
return isinstance(self.args[0], ContinuousDistribution)
@property
def is_Finite(self):
return isinstance(self.args[0], SingleFiniteDistribution)
@property
def is_Discrete(self):
return isinstance(self.args[0], DiscreteDistribution)
def pdf(self, x, evaluate=False):
dist = self.args[0]
randoms = [rv for rv in dist.args if is_random(rv)]
if isinstance(dist, SingleFiniteDistribution):
y = Dummy('y', integer=True, negative=False)
expr = dist.pmf(y)
else:
y = Dummy('y')
expr = dist.pdf(y)
for rv in randoms:
expr = self._marginalise(expr, rv, evaluate)
return Lambda(y, expr)(x)
def _marginalise(self, expr, rv, evaluate):
if isinstance(rv.pspace.distribution, SingleFiniteDistribution):
rv_dens = rv.pspace.distribution.pmf(rv)
else:
rv_dens = rv.pspace.distribution.pdf(rv)
rv_dom = rv.pspace.domain.set
if rv.pspace.is_Discrete or rv.pspace.is_Finite:
expr = Sum(expr*rv_dens, (rv, rv_dom._inf,
rv_dom._sup))
else:
expr = Integral(expr*rv_dens, (rv, rv_dom._inf,
rv_dom._sup))
if evaluate:
return expr.doit()
return expr
@classmethod
def _compound_check(self, dist):
"""
Checks if the given distribution contains random parameters.
"""
randoms = []
for arg in dist.args:
randoms.extend(random_symbols(arg))
if len(randoms) == 0:
return False
return True
|
5d55b05966aff116634da7fda462a42dba24e8d3a841b6d57c2d0cd183fad77a | from __future__ import print_function, division
from sympy import (Basic, exp, pi, Lambda, Trace, S, MatrixSymbol, Integral,
gamma, Product, Dummy, Sum, Abs, IndexedBase, I)
from sympy.core.sympify import _sympify
from sympy.stats.rv import _symbol_converter, Density, RandomMatrixSymbol, is_random
from sympy.stats.joint_rv_types import JointDistributionHandmade
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.tensor.array import ArrayComprehension
__all__ = [
'CircularEnsemble',
'CircularUnitaryEnsemble',
'CircularOrthogonalEnsemble',
'CircularSymplecticEnsemble',
'GaussianEnsemble',
'GaussianUnitaryEnsemble',
'GaussianOrthogonalEnsemble',
'GaussianSymplecticEnsemble',
'joint_eigen_distribution',
'JointEigenDistribution',
'level_spacing_distribution'
]
@is_random.register(RandomMatrixSymbol)
def _(x):
return True
class RandomMatrixEnsemble(Basic):
"""
Base class for random matrix ensembles.
It acts as an umbrella and contains
the methods common to all the ensembles
defined in sympy.stats.random_matrix_models.
"""
def __new__(cls, sym, dim=None):
sym, dim = _symbol_converter(sym), _sympify(dim)
if dim.is_integer == False:
raise ValueError("Dimension of the random matrices must be "
"integers, received %s instead."%(dim))
self = Basic.__new__(cls, sym, dim)
rmp = RandomMatrixPSpace(sym, model=self)
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
symbol = property(lambda self: self.args[0])
dimension = property(lambda self: self.args[1])
def density(self, expr):
return Density(expr)
def __call__(self, expr):
return self.density(expr)
class GaussianEnsemble(RandomMatrixEnsemble):
"""
Abstract class for Gaussian ensembles.
Contains the properties common to all the
gaussian ensembles.
References
==========
.. [1] https://en.wikipedia.org/wiki/Random_matrix#Gaussian_ensembles
.. [2] https://arxiv.org/pdf/1712.07903.pdf
"""
def _compute_normalization_constant(self, beta, n):
"""
Helper function for computing normalization
constant for joint probability density of eigen
values of Gaussian ensembles.
References
==========
.. [1] https://en.wikipedia.org/wiki/Selberg_integral#Mehta's_integral
"""
n = S(n)
prod_term = lambda j: gamma(1 + beta*S(j)/2)/gamma(S.One + beta/S(2))
j = Dummy('j', integer=True, positive=True)
term1 = Product(prod_term(j), (j, 1, n)).doit()
term2 = (2/(beta*n))**(beta*n*(n - 1)/4 + n/2)
term3 = (2*pi)**(n/2)
return term1 * term2 * term3
def _compute_joint_eigen_distribution(self, beta):
"""
Helper function for computing the joint
probability distribution of eigen values
of the random matrix.
"""
n = self.dimension
Zbn = self._compute_normalization_constant(beta, n)
l = IndexedBase('l')
i = Dummy('i', integer=True, positive=True)
j = Dummy('j', integer=True, positive=True)
k = Dummy('k', integer=True, positive=True)
term1 = exp((-S(n)/2) * Sum(l[k]**2, (k, 1, n)).doit())
sub_term = Lambda(i, Product(Abs(l[j] - l[i])**beta, (j, i + 1, n)))
term2 = Product(sub_term(i).doit(), (i, 1, n - 1)).doit()
syms = ArrayComprehension(l[k], (k, 1, n)).doit()
return Lambda(tuple(syms), (term1 * term2)/Zbn)
class GaussianUnitaryEnsemble(GaussianEnsemble):
"""
Represents Gaussian Unitary Ensembles.
Examples
========
>>> from sympy.stats import GaussianUnitaryEnsemble as GUE, density
>>> from sympy import MatrixSymbol
>>> G = GUE('U', 2)
>>> X = MatrixSymbol('X', 2, 2)
>>> density(G)(X)
exp(-Trace(X**2))/(2*pi**2)
"""
@property
def normalization_constant(self):
n = self.dimension
return 2**(S(n)/2) * pi**(S(n**2)/2)
def density(self, expr):
n, ZGUE = self.dimension, self.normalization_constant
h_pspace = RandomMatrixPSpace('P', model=self)
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
return Lambda(H, exp(-S(n)/2 * Trace(H**2))/ZGUE)(expr)
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S(2))
def level_spacing_distribution(self):
s = Dummy('s')
f = (32/pi**2)*(s**2)*exp((-4/pi)*s**2)
return Lambda(s, f)
class GaussianOrthogonalEnsemble(GaussianEnsemble):
"""
Represents Gaussian Orthogonal Ensembles.
Examples
========
>>> from sympy.stats import GaussianOrthogonalEnsemble as GOE, density
>>> from sympy import MatrixSymbol
>>> G = GOE('U', 2)
>>> X = MatrixSymbol('X', 2, 2)
>>> density(G)(X)
exp(-Trace(X**2)/2)/Integral(exp(-Trace(_H**2)/2), _H)
"""
@property
def normalization_constant(self):
n = self.dimension
_H = MatrixSymbol('_H', n, n)
return Integral(exp(-S(n)/4 * Trace(_H**2)))
def density(self, expr):
n, ZGOE = self.dimension, self.normalization_constant
h_pspace = RandomMatrixPSpace('P', model=self)
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
return Lambda(H, exp(-S(n)/4 * Trace(H**2))/ZGOE)(expr)
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S.One)
def level_spacing_distribution(self):
s = Dummy('s')
f = (pi/2)*s*exp((-pi/4)*s**2)
return Lambda(s, f)
class GaussianSymplecticEnsemble(GaussianEnsemble):
"""
Represents Gaussian Symplectic Ensembles.
Examples
========
>>> from sympy.stats import GaussianSymplecticEnsemble as GSE, density
>>> from sympy import MatrixSymbol
>>> G = GSE('U', 2)
>>> X = MatrixSymbol('X', 2, 2)
>>> density(G)(X)
exp(-2*Trace(X**2))/Integral(exp(-2*Trace(_H**2)), _H)
"""
@property
def normalization_constant(self):
n = self.dimension
_H = MatrixSymbol('_H', n, n)
return Integral(exp(-S(n) * Trace(_H**2)))
def density(self, expr):
n, ZGSE = self.dimension, self.normalization_constant
h_pspace = RandomMatrixPSpace('P', model=self)
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
return Lambda(H, exp(-S(n) * Trace(H**2))/ZGSE)(expr)
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S(4))
def level_spacing_distribution(self):
s = Dummy('s')
f = ((S(2)**18)/((S(3)**6)*(pi**3)))*(s**4)*exp((-64/(9*pi))*s**2)
return Lambda(s, f)
class CircularEnsemble(RandomMatrixEnsemble):
"""
Abstract class for Circular ensembles.
Contains the properties and methods
common to all the circular ensembles.
References
==========
.. [1] https://en.wikipedia.org/wiki/Circular_ensemble
"""
def density(self, expr):
# TODO : Add support for Lie groups(as extensions of sympy.diffgeom)
# and define measures on them
raise NotImplementedError("Support for Haar measure hasn't been "
"implemented yet, therefore the density of "
"%s cannot be computed."%(self))
def _compute_joint_eigen_distribution(self, beta):
"""
Helper function to compute the joint distribution of phases
of the complex eigen values of matrices belonging to any
circular ensembles.
"""
n = self.dimension
Zbn = ((2*pi)**n)*(gamma(beta*n/2 + 1)/S((gamma(beta/2 + 1)))**n)
t = IndexedBase('t')
i, j, k = (Dummy('i', integer=True), Dummy('j', integer=True),
Dummy('k', integer=True))
syms = ArrayComprehension(t[i], (i, 1, n)).doit()
f = Product(Product(Abs(exp(I*t[k]) - exp(I*t[j]))**beta, (j, k + 1, n)).doit(),
(k, 1, n - 1)).doit()
return Lambda(tuple(syms), f/Zbn)
class CircularUnitaryEnsemble(CircularEnsemble):
"""
Represents Cicular Unitary Ensembles.
Examples
========
>>> from sympy.stats import CircularUnitaryEnsemble as CUE
>>> from sympy.stats import joint_eigen_distribution
>>> C = CUE('U', 1)
>>> joint_eigen_distribution(C)
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**2, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi))
Note
====
As can be seen above in the example, density of CiruclarUnitaryEnsemble
is not evaluated becuase the exact definition is based on haar measure of
unitary group which is not unique.
"""
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S(2))
class CircularOrthogonalEnsemble(CircularEnsemble):
"""
Represents Cicular Orthogonal Ensembles.
Examples
========
>>> from sympy.stats import CircularOrthogonalEnsemble as COE
>>> from sympy.stats import joint_eigen_distribution
>>> C = COE('O', 1)
>>> joint_eigen_distribution(C)
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k])), (_j, _k + 1, 1), (_k, 1, 0))/(2*pi))
Note
====
As can be seen above in the example, density of CiruclarOrthogonalEnsemble
is not evaluated becuase the exact definition is based on haar measure of
unitary group which is not unique.
"""
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S.One)
class CircularSymplecticEnsemble(CircularEnsemble):
"""
Represents Cicular Symplectic Ensembles.
Examples
========
>>> from sympy.stats import CircularSymplecticEnsemble as CSE
>>> from sympy.stats import joint_eigen_distribution
>>> C = CSE('S', 1)
>>> joint_eigen_distribution(C)
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**4, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi))
Note
====
As can be seen above in the example, density of CiruclarSymplecticEnsemble
is not evaluated becuase the exact definition is based on haar measure of
unitary group which is not unique.
"""
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S(4))
def joint_eigen_distribution(mat):
"""
For obtaining joint probability distribution
of eigen values of random matrix.
Parameters
==========
mat: RandomMatrixSymbol
The matrix symbol whose eigen values are to be considered.
Returns
=======
Lambda
Examples
========
>>> from sympy.stats import GaussianUnitaryEnsemble as GUE
>>> from sympy.stats import joint_eigen_distribution
>>> U = GUE('U', 2)
>>> joint_eigen_distribution(U)
Lambda((l[1], l[2]), exp(-l[1]**2 - l[2]**2)*Product(Abs(l[_i] - l[_j])**2, (_j, _i + 1, 2), (_i, 1, 1))/pi)
"""
if not isinstance(mat, RandomMatrixSymbol):
raise ValueError("%s is not of type, RandomMatrixSymbol."%(mat))
return mat.pspace.model.joint_eigen_distribution()
def JointEigenDistribution(mat):
"""
Creates joint distribution of eigen values of matrices with random
expressions.
Parameters
==========
mat: Matrix
The matrix under consideration
Returns
=======
JointDistributionHandmade
Examples
========
>>> from sympy.stats import Normal, JointEigenDistribution
>>> from sympy import Matrix
>>> A = [[Normal('A00', 0, 1), Normal('A01', 0, 1)],
... [Normal('A10', 0, 1), Normal('A11', 0, 1)]]
>>> JointEigenDistribution(Matrix(A))
JointDistributionHandmade(-sqrt(A00**2 - 2*A00*A11 + 4*A01*A10 + A11**2)/2
+ A00/2 + A11/2, sqrt(A00**2 - 2*A00*A11 + 4*A01*A10 + A11**2)/2 + A00/2 + A11/2)
"""
eigenvals = mat.eigenvals(multiple=True)
if any(not is_random(eigenval) for eigenval in set(eigenvals)):
raise ValueError("Eigen values don't have any random expression, "
"joint distribution cannot be generated.")
return JointDistributionHandmade(*eigenvals)
def level_spacing_distribution(mat):
"""
For obtaining distribution of level spacings.
Parameters
==========
mat: RandomMatrixSymbol
The random matrix symbol whose eigen values are
to be considered for finding the level spacings.
Returns
=======
Lambda
Examples
========
>>> from sympy.stats import GaussianUnitaryEnsemble as GUE
>>> from sympy.stats import level_spacing_distribution
>>> U = GUE('U', 2)
>>> level_spacing_distribution(U)
Lambda(_s, 32*_s**2*exp(-4*_s**2/pi)/pi**2)
References
==========
.. [1] https://en.wikipedia.org/wiki/Random_matrix#Distribution_of_level_spacings
"""
return mat.pspace.model.level_spacing_distribution()
|
acbecd9795e590e73165f245e1f24feb8c2e6e1ff762c688161c494e501eeba4 | from sympy import Integer
import sympy.polys
from math import gcd
def egyptian_fraction(r, algorithm="Greedy"):
"""
Return the list of denominators of an Egyptian fraction
expansion [1]_ of the said rational `r`.
Parameters
==========
r : Rational
a positive rational number.
algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional
Denotes the algorithm to be used (the default is "Greedy").
Examples
========
>>> from sympy import Rational
>>> from sympy.ntheory.egyptian_fraction import egyptian_fraction
>>> egyptian_fraction(Rational(3, 7))
[3, 11, 231]
>>> egyptian_fraction(Rational(3, 7), "Graham Jewett")
[7, 8, 9, 56, 57, 72, 3192]
>>> egyptian_fraction(Rational(3, 7), "Takenouchi")
[4, 7, 28]
>>> egyptian_fraction(Rational(3, 7), "Golomb")
[3, 15, 35]
>>> egyptian_fraction(Rational(11, 5), "Golomb")
[1, 2, 3, 4, 9, 234, 1118, 2580]
See Also
========
sympy.core.numbers.Rational
Notes
=====
Currently the following algorithms are supported:
1) Greedy Algorithm
Also called the Fibonacci-Sylvester algorithm [2]_.
At each step, extract the largest unit fraction less
than the target and replace the target with the remainder.
It has some distinct properties:
a) Given `p/q` in lowest terms, generates an expansion of maximum
length `p`. Even as the numerators get large, the number of
terms is seldom more than a handful.
b) Uses minimal memory.
c) The terms can blow up (standard examples of this are 5/121 and
31/311). The denominator is at most squared at each step
(doubly-exponential growth) and typically exhibits
singly-exponential growth.
2) Graham Jewett Algorithm
The algorithm suggested by the result of Graham and Jewett.
Note that this has a tendency to blow up: the length of the
resulting expansion is always ``2**(x/gcd(x, y)) - 1``. See [3]_.
3) Takenouchi Algorithm
The algorithm suggested by Takenouchi (1921).
Differs from the Graham-Jewett algorithm only in the handling
of duplicates. See [3]_.
4) Golomb's Algorithm
A method given by Golumb (1962), using modular arithmetic and
inverses. It yields the same results as a method using continued
fractions proposed by Bleicher (1972). See [4]_.
If the given rational is greater than or equal to 1, a greedy algorithm
of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking
all the unit fractions of this sequence until adding one more would be
greater than the given number. This list of denominators is prefixed
to the result from the requested algorithm used on the remainder. For
example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4,
5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5,
6, 7] is part of the harmonic sequence summing to 363/140, leaving a
remainder of 31/420, which yields [14, 420] by the Greedy algorithm.
The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3,
4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on.
References
==========
.. [1] https://en.wikipedia.org/wiki/Egyptian_fraction
.. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions
.. [3] https://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html
.. [4] http://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf
"""
if r <= 0:
raise ValueError("Value must be positive")
prefix, rem = egypt_harmonic(r)
if rem == 0:
return prefix
x, y = rem.as_numer_denom()
if algorithm == "Greedy":
return prefix + egypt_greedy(x, y)
elif algorithm == "Graham Jewett":
return prefix + egypt_graham_jewett(x, y)
elif algorithm == "Takenouchi":
return prefix + egypt_takenouchi(x, y)
elif algorithm == "Golomb":
return prefix + egypt_golomb(x, y)
else:
raise ValueError("Entered invalid algorithm")
def egypt_greedy(x, y):
if x == 1:
return [y]
else:
a = (-y) % (x)
b = y*(y//x + 1)
c = gcd(a, b)
if c > 1:
num, denom = a//c, b//c
else:
num, denom = a, b
return [y//x + 1] + egypt_greedy(num, denom)
def egypt_graham_jewett(x, y):
l = [y] * x
# l is now a list of integers whose reciprocals sum to x/y.
# we shall now proceed to manipulate the elements of l without
# changing the reciprocated sum until all elements are unique.
while len(l) != len(set(l)):
l.sort() # so the list has duplicates. find a smallest pair
for i in range(len(l) - 1):
if l[i] == l[i + 1]:
break
# we have now identified a pair of identical
# elements: l[i] and l[i + 1].
# now comes the application of the result of graham and jewett:
l[i + 1] = l[i] + 1
# and we just iterate that until the list has no duplicates.
l.append(l[i]*(l[i] + 1))
return sorted(l)
def egypt_takenouchi(x, y):
l = [y] * x
while len(l) != len(set(l)):
l.sort()
for i in range(len(l) - 1):
if l[i] == l[i + 1]:
break
k = l[i]
if k % 2 == 0:
l[i] = l[i] // 2
del l[i + 1]
else:
l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2
return sorted(l)
def egypt_golomb(x, y):
if x == 1:
return [y]
xp = sympy.polys.ZZ.invert(int(x), int(y))
rv = [Integer(xp*y)]
rv.extend(egypt_golomb((x*xp - 1)//y, xp))
return sorted(rv)
def egypt_harmonic(r):
rv = []
d = Integer(1)
acc = Integer(0)
while acc + 1/d <= r:
acc += 1/d
rv.append(d)
d += 1
return (rv, r - acc)
|
fa830824c5508dcd5d3dae281f52ce8753fbb4b08cc084012b4e89e59230dd8e | from __future__ import print_function, division
from collections import defaultdict
from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify,
expand_func, Function, Dummy, Expr, factor_terms,
expand_power_exp, Eq)
from sympy.core.compatibility import iterable, ordered, as_int
from sympy.core.parameters import global_parameters
from sympy.core.function import (expand_log, count_ops, _mexpand, _coeff_isneg,
nfloat, expand_mul)
from sympy.core.numbers import Float, I, pi, Rational, Integer
from sympy.core.relational import Relational
from sympy.core.rules import Transform
from sympy.core.sympify import _sympify
from sympy.functions import gamma, exp, sqrt, log, exp_polar, re
from sympy.functions.combinatorial.factorials import CombinatorialFunction
from sympy.functions.elementary.complexes import unpolarify, Abs
from sympy.functions.elementary.exponential import ExpBase
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.functions.special.bessel import besselj, besseli, besselk, jn, bessely
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.polys import together, cancel, factor
from sympy.simplify.combsimp import combsimp
from sympy.simplify.cse_opts import sub_pre, sub_post
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import radsimp, fraction, collect_abs
from sympy.simplify.sqrtdenest import sqrtdenest
from sympy.simplify.trigsimp import trigsimp, exptrigsimp
from sympy.utilities.iterables import has_variety, sift
import mpmath
def separatevars(expr, symbols=[], dict=False, force=False):
"""
Separates variables in an expression, if possible. By
default, it separates with respect to all symbols in an
expression and collects constant coefficients that are
independent of symbols.
If dict=True then the separated terms will be returned
in a dictionary keyed to their corresponding symbols.
By default, all symbols in the expression will appear as
keys; if symbols are provided, then all those symbols will
be used as keys, and any terms in the expression containing
other symbols or non-symbols will be returned keyed to the
string 'coeff'. (Passing None for symbols will return the
expression in a dictionary keyed to 'coeff'.)
If force=True, then bases of powers will be separated regardless
of assumptions on the symbols involved.
Notes
=====
The order of the factors is determined by Mul, so that the
separated expressions may not necessarily be grouped together.
Although factoring is necessary to separate variables in some
expressions, it is not necessary in all cases, so one should not
count on the returned factors being factored.
Examples
========
>>> from sympy.abc import x, y, z, alpha
>>> from sympy import separatevars, sin
>>> separatevars((x*y)**y)
(x*y)**y
>>> separatevars((x*y)**y, force=True)
x**y*y**y
>>> e = 2*x**2*z*sin(y)+2*z*x**2
>>> separatevars(e)
2*x**2*z*(sin(y) + 1)
>>> separatevars(e, symbols=(x, y), dict=True)
{'coeff': 2*z, x: x**2, y: sin(y) + 1}
>>> separatevars(e, [x, y, alpha], dict=True)
{'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1}
If the expression is not really separable, or is only partially
separable, separatevars will do the best it can to separate it
by using factoring.
>>> separatevars(x + x*y - 3*x**2)
-x*(3*x - y - 1)
If the expression is not separable then expr is returned unchanged
or (if dict=True) then None is returned.
>>> eq = 2*x + y*sin(x)
>>> separatevars(eq) == eq
True
>>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None
True
"""
expr = sympify(expr)
if dict:
return _separatevars_dict(_separatevars(expr, force), symbols)
else:
return _separatevars(expr, force)
def _separatevars(expr, force):
if isinstance(expr, Abs):
arg = expr.args[0]
if arg.is_Mul and not arg.is_number:
s = separatevars(arg, dict=True, force=force)
if s is not None:
return Mul(*map(expr.func, s.values()))
else:
return expr
if len(expr.free_symbols) < 2:
return expr
# don't destroy a Mul since much of the work may already be done
if expr.is_Mul:
args = list(expr.args)
changed = False
for i, a in enumerate(args):
args[i] = separatevars(a, force)
changed = changed or args[i] != a
if changed:
expr = expr.func(*args)
return expr
# get a Pow ready for expansion
if expr.is_Pow:
expr = Pow(separatevars(expr.base, force=force), expr.exp)
# First try other expansion methods
expr = expr.expand(mul=False, multinomial=False, force=force)
_expr, reps = posify(expr) if force else (expr, {})
expr = factor(_expr).subs(reps)
if not expr.is_Add:
return expr
# Find any common coefficients to pull out
args = list(expr.args)
commonc = args[0].args_cnc(cset=True, warn=False)[0]
for i in args[1:]:
commonc &= i.args_cnc(cset=True, warn=False)[0]
commonc = Mul(*commonc)
commonc = commonc.as_coeff_Mul()[1] # ignore constants
commonc_set = commonc.args_cnc(cset=True, warn=False)[0]
# remove them
for i, a in enumerate(args):
c, nc = a.args_cnc(cset=True, warn=False)
c = c - commonc_set
args[i] = Mul(*c)*Mul(*nc)
nonsepar = Add(*args)
if len(nonsepar.free_symbols) > 1:
_expr = nonsepar
_expr, reps = posify(_expr) if force else (_expr, {})
_expr = (factor(_expr)).subs(reps)
if not _expr.is_Add:
nonsepar = _expr
return commonc*nonsepar
def _separatevars_dict(expr, symbols):
if symbols:
if not all((t.is_Atom for t in symbols)):
raise ValueError("symbols must be Atoms.")
symbols = list(symbols)
elif symbols is None:
return {'coeff': expr}
else:
symbols = list(expr.free_symbols)
if not symbols:
return None
ret = dict(((i, []) for i in symbols + ['coeff']))
for i in Mul.make_args(expr):
expsym = i.free_symbols
intersection = set(symbols).intersection(expsym)
if len(intersection) > 1:
return None
if len(intersection) == 0:
# There are no symbols, so it is part of the coefficient
ret['coeff'].append(i)
else:
ret[intersection.pop()].append(i)
# rebuild
for k, v in ret.items():
ret[k] = Mul(*v)
return ret
def _is_sum_surds(p):
args = p.args if p.is_Add else [p]
for y in args:
if not ((y**2).is_Rational and y.is_extended_real):
return False
return True
def posify(eq):
"""Return eq (with generic symbols made positive) and a
dictionary containing the mapping between the old and new
symbols.
Any symbol that has positive=None will be replaced with a positive dummy
symbol having the same name. This replacement will allow more symbolic
processing of expressions, especially those involving powers and
logarithms.
A dictionary that can be sent to subs to restore eq to its original
symbols is also returned.
>>> from sympy import posify, Symbol, log, solve
>>> from sympy.abc import x
>>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
(_x + n + p, {_x: x})
>>> eq = 1/x
>>> log(eq).expand()
log(1/x)
>>> log(posify(eq)[0]).expand()
-log(_x)
>>> p, rep = posify(eq)
>>> log(p).expand().subs(rep)
-log(x)
It is possible to apply the same transformations to an iterable
of expressions:
>>> eq = x**2 - 4
>>> solve(eq, x)
[-2, 2]
>>> eq_x, reps = posify([eq, x]); eq_x
[_x**2 - 4, _x]
>>> solve(*eq_x)
[2]
"""
eq = sympify(eq)
if iterable(eq):
f = type(eq)
eq = list(eq)
syms = set()
for e in eq:
syms = syms.union(e.atoms(Symbol))
reps = {}
for s in syms:
reps.update(dict((v, k) for k, v in posify(s)[1].items()))
for i, e in enumerate(eq):
eq[i] = e.subs(reps)
return f(eq), {r: s for s, r in reps.items()}
reps = {s: Dummy(s.name, positive=True, **s.assumptions0)
for s in eq.free_symbols if s.is_positive is None}
eq = eq.subs(reps)
return eq, {r: s for s, r in reps.items()}
def hypersimp(f, k):
"""Given combinatorial term f(k) simplify its consecutive term ratio
i.e. f(k+1)/f(k). The input term can be composed of functions and
integer sequences which have equivalent representation in terms
of gamma special function.
The algorithm performs three basic steps:
1. Rewrite all functions in terms of gamma, if possible.
2. Rewrite all occurrences of gamma in terms of products
of gamma and rising factorial with integer, absolute
constant exponent.
3. Perform simplification of nested fractions, powers
and if the resulting expression is a quotient of
polynomials, reduce their total degree.
If f(k) is hypergeometric then as result we arrive with a
quotient of polynomials of minimal degree. Otherwise None
is returned.
For more information on the implemented algorithm refer to:
1. W. Koepf, Algorithms for m-fold Hypergeometric Summation,
Journal of Symbolic Computation (1995) 20, 399-417
"""
f = sympify(f)
g = f.subs(k, k + 1) / f
g = g.rewrite(gamma)
if g.has(Piecewise):
g = piecewise_fold(g)
g = g.args[-1][0]
g = expand_func(g)
g = powsimp(g, deep=True, combine='exp')
if g.is_rational_function(k):
return simplify(g, ratio=S.Infinity)
else:
return None
def hypersimilar(f, g, k):
"""Returns True if 'f' and 'g' are hyper-similar.
Similarity in hypergeometric sense means that a quotient of
f(k) and g(k) is a rational function in k. This procedure
is useful in solving recurrence relations.
For more information see hypersimp().
"""
f, g = list(map(sympify, (f, g)))
h = (f/g).rewrite(gamma)
h = h.expand(func=True, basic=False)
return h.is_rational_function(k)
def signsimp(expr, evaluate=None):
"""Make all Add sub-expressions canonical wrt sign.
If an Add subexpression, ``a``, can have a sign extracted,
as determined by could_extract_minus_sign, it is replaced
with Mul(-1, a, evaluate=False). This allows signs to be
extracted from powers and products.
Examples
========
>>> from sympy import signsimp, exp, symbols
>>> from sympy.abc import x, y
>>> i = symbols('i', odd=True)
>>> n = -1 + 1/x
>>> n/x/(-n)**2 - 1/n/x
(-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x))
>>> signsimp(_)
0
>>> x*n + x*-n
x*(-1 + 1/x) + x*(1 - 1/x)
>>> signsimp(_)
0
Since powers automatically handle leading signs
>>> (-2)**i
-2**i
signsimp can be used to put the base of a power with an integer
exponent into canonical form:
>>> n**i
(-1 + 1/x)**i
By default, signsimp doesn't leave behind any hollow simplification:
if making an Add canonical wrt sign didn't change the expression, the
original Add is restored. If this is not desired then the keyword
``evaluate`` can be set to False:
>>> e = exp(y - x)
>>> signsimp(e) == e
True
>>> signsimp(e, evaluate=False)
exp(-(x - y))
"""
if evaluate is None:
evaluate = global_parameters.evaluate
expr = sympify(expr)
if not isinstance(expr, (Expr, Relational)) or expr.is_Atom:
return expr
e = sub_post(sub_pre(expr))
if not isinstance(e, (Expr, Relational)) or e.is_Atom:
return e
if e.is_Add:
return e.func(*[signsimp(a, evaluate) for a in e.args])
if evaluate:
e = e.xreplace({m: -(-m) for m in e.atoms(Mul) if -(-m) != m})
return e
def simplify(expr, ratio=1.7, measure=count_ops, rational=False, inverse=False, doit=True, **kwargs):
"""Simplifies the given expression.
Simplification is not a well defined term and the exact strategies
this function tries can change in the future versions of SymPy. If
your algorithm relies on "simplification" (whatever it is), try to
determine what you need exactly - is it powsimp()?, radsimp()?,
together()?, logcombine()?, or something else? And use this particular
function directly, because those are well defined and thus your algorithm
will be robust.
Nonetheless, especially for interactive use, or when you don't know
anything about the structure of the expression, simplify() tries to apply
intelligent heuristics to make the input expression "simpler". For
example:
>>> from sympy import simplify, cos, sin
>>> from sympy.abc import x, y
>>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
>>> a
(x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
>>> simplify(a)
x + 1
Note that we could have obtained the same result by using specific
simplification functions:
>>> from sympy import trigsimp, cancel
>>> trigsimp(a)
(x**2 + x)/x
>>> cancel(_)
x + 1
In some cases, applying :func:`simplify` may actually result in some more
complicated expression. The default ``ratio=1.7`` prevents more extreme
cases: if (result length)/(input length) > ratio, then input is returned
unmodified. The ``measure`` parameter lets you specify the function used
to determine how complex an expression is. The function should take a
single argument as an expression and return a number such that if
expression ``a`` is more complex than expression ``b``, then
``measure(a) > measure(b)``. The default measure function is
:func:`~.count_ops`, which returns the total number of operations in the
expression.
For example, if ``ratio=1``, ``simplify`` output can't be longer
than input.
::
>>> from sympy import sqrt, simplify, count_ops, oo
>>> root = 1/(sqrt(2)+3)
Since ``simplify(root)`` would result in a slightly longer expression,
root is returned unchanged instead::
>>> simplify(root, ratio=1) == root
True
If ``ratio=oo``, simplify will be applied anyway::
>>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
True
Note that the shortest expression is not necessary the simplest, so
setting ``ratio`` to 1 may not be a good idea.
Heuristically, the default value ``ratio=1.7`` seems like a reasonable
choice.
You can easily define your own measure function based on what you feel
should represent the "size" or "complexity" of the input expression. Note
that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
good metrics, but have other problems (in this case, the measure function
may slow down simplify too much for very large expressions). If you don't
know what a good metric would be, the default, ``count_ops``, is a good
one.
For example:
>>> from sympy import symbols, log
>>> a, b = symbols('a b', positive=True)
>>> g = log(a) + log(b) + log(a)*log(1/b)
>>> h = simplify(g)
>>> h
log(a*b**(1 - log(a)))
>>> count_ops(g)
8
>>> count_ops(h)
5
So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
However, we may not like how ``simplify`` (in this case, using
``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way
to reduce this would be to give more weight to powers as operations in
``count_ops``. We can do this by using the ``visual=True`` option:
>>> print(count_ops(g, visual=True))
2*ADD + DIV + 4*LOG + MUL
>>> print(count_ops(h, visual=True))
2*LOG + MUL + POW + SUB
>>> from sympy import Symbol, S
>>> def my_measure(expr):
... POW = Symbol('POW')
... # Discourage powers by giving POW a weight of 10
... count = count_ops(expr, visual=True).subs(POW, 10)
... # Every other operation gets a weight of 1 (the default)
... count = count.replace(Symbol, type(S.One))
... return count
>>> my_measure(g)
8
>>> my_measure(h)
14
>>> 15./8 > 1.7 # 1.7 is the default ratio
True
>>> simplify(g, measure=my_measure)
-log(a)*log(b) + log(a) + log(b)
Note that because ``simplify()`` internally tries many different
simplification strategies and then compares them using the measure
function, we get a completely different result that is still different
from the input expression by doing this.
If rational=True, Floats will be recast as Rationals before simplification.
If rational=None, Floats will be recast as Rationals but the result will
be recast as Floats. If rational=False(default) then nothing will be done
to the Floats.
If inverse=True, it will be assumed that a composition of inverse
functions, such as sin and asin, can be cancelled in any order.
For example, ``asin(sin(x))`` will yield ``x`` without checking whether
x belongs to the set where this relation is true. The default is
False.
Note that ``simplify()`` automatically calls ``doit()`` on the final
expression. You can avoid this behavior by passing ``doit=False`` as
an argument.
"""
def shorter(*choices):
"""
Return the choice that has the fewest ops. In case of a tie,
the expression listed first is selected.
"""
if not has_variety(choices):
return choices[0]
return min(choices, key=measure)
def done(e):
rv = e.doit() if doit else e
return shorter(rv, collect_abs(rv))
expr = sympify(expr)
kwargs = dict(
ratio=kwargs.get('ratio', ratio),
measure=kwargs.get('measure', measure),
rational=kwargs.get('rational', rational),
inverse=kwargs.get('inverse', inverse),
doit=kwargs.get('doit', doit))
# no routine for Expr needs to check for is_zero
if isinstance(expr, Expr) and expr.is_zero:
return S.Zero
_eval_simplify = getattr(expr, '_eval_simplify', None)
if _eval_simplify is not None:
return _eval_simplify(**kwargs)
original_expr = expr = collect_abs(signsimp(expr))
if not isinstance(expr, Basic) or not expr.args: # XXX: temporary hack
return expr
if inverse and expr.has(Function):
expr = inversecombine(expr)
if not expr.args: # simplified to atomic
return expr
# do deep simplification
handled = Add, Mul, Pow, ExpBase
expr = expr.replace(
# here, checking for x.args is not enough because Basic has
# args but Basic does not always play well with replace, e.g.
# when simultaneous is True found expressions will be masked
# off with a Dummy but not all Basic objects in an expression
# can be replaced with a Dummy
lambda x: isinstance(x, Expr) and x.args and not isinstance(
x, handled),
lambda x: x.func(*[simplify(i, **kwargs) for i in x.args]),
simultaneous=False)
if not isinstance(expr, handled):
return done(expr)
if not expr.is_commutative:
expr = nc_simplify(expr)
# TODO: Apply different strategies, considering expression pattern:
# is it a purely rational function? Is there any trigonometric function?...
# See also https://github.com/sympy/sympy/pull/185.
# rationalize Floats
floats = False
if rational is not False and expr.has(Float):
floats = True
expr = nsimplify(expr, rational=True)
expr = bottom_up(expr, lambda w: getattr(w, 'normal', lambda: w)())
expr = Mul(*powsimp(expr).as_content_primitive())
_e = cancel(expr)
expr1 = shorter(_e, _mexpand(_e).cancel()) # issue 6829
expr2 = shorter(together(expr, deep=True), together(expr1, deep=True))
if ratio is S.Infinity:
expr = expr2
else:
expr = shorter(expr2, expr1, expr)
if not isinstance(expr, Basic): # XXX: temporary hack
return expr
expr = factor_terms(expr, sign=False)
from sympy.simplify.hyperexpand import hyperexpand
from sympy.functions.special.bessel import BesselBase
from sympy import Sum, Product, Integral
from sympy.functions.elementary.complexes import sign
# must come before `Piecewise` since this introduces more `Piecewise` terms
if expr.has(sign):
expr = expr.rewrite(Abs)
# Deal with Piecewise separately to avoid recursive growth of expressions
if expr.has(Piecewise):
# Fold into a single Piecewise
expr = piecewise_fold(expr)
# Apply doit, if doit=True
expr = done(expr)
# Still a Piecewise?
if expr.has(Piecewise):
# Fold into a single Piecewise, in case doit lead to some
# expressions being Piecewise
expr = piecewise_fold(expr)
# kroneckersimp also affects Piecewise
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
# Still a Piecewise?
if expr.has(Piecewise):
from sympy.functions.elementary.piecewise import piecewise_simplify
# Do not apply doit on the segments as it has already
# been done above, but simplify
expr = piecewise_simplify(expr, deep=True, doit=False)
# Still a Piecewise?
if expr.has(Piecewise):
# Try factor common terms
expr = shorter(expr, factor_terms(expr))
# As all expressions have been simplified above with the
# complete simplify, nothing more needs to be done here
return expr
# hyperexpand automatically only works on hypergeometric terms
# Do this after the Piecewise part to avoid recursive expansion
expr = hyperexpand(expr)
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
if expr.has(BesselBase):
expr = besselsimp(expr)
if expr.has(TrigonometricFunction, HyperbolicFunction):
expr = trigsimp(expr, deep=True)
if expr.has(log):
expr = shorter(expand_log(expr, deep=True), logcombine(expr))
if expr.has(CombinatorialFunction, gamma):
# expression with gamma functions or non-integer arguments is
# automatically passed to gammasimp
expr = combsimp(expr)
if expr.has(Sum):
expr = sum_simplify(expr, **kwargs)
if expr.has(Integral):
expr = expr.xreplace(dict([
(i, factor_terms(i)) for i in expr.atoms(Integral)]))
if expr.has(Product):
expr = product_simplify(expr)
from sympy.physics.units import Quantity
from sympy.physics.units.util import quantity_simplify
if expr.has(Quantity):
expr = quantity_simplify(expr)
short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)
short = shorter(short, cancel(short))
short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))
if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):
short = exptrigsimp(short)
# get rid of hollow 2-arg Mul factorization
hollow_mul = Transform(
lambda x: Mul(*x.args),
lambda x:
x.is_Mul and
len(x.args) == 2 and
x.args[0].is_Number and
x.args[1].is_Add and
x.is_commutative)
expr = short.xreplace(hollow_mul)
numer, denom = expr.as_numer_denom()
if denom.is_Add:
n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1))
if n is not S.One:
expr = (numer*n).expand()/d
if expr.could_extract_minus_sign():
n, d = fraction(expr)
if d != 0:
expr = signsimp(-n/(-d))
if measure(expr) > ratio*measure(original_expr):
expr = original_expr
# restore floats
if floats and rational is None:
expr = nfloat(expr, exponent=False)
return done(expr)
def sum_simplify(s, **kwargs):
"""Main function for Sum simplification"""
from sympy.concrete.summations import Sum
from sympy.core.function import expand
if not isinstance(s, Add):
s = s.xreplace(dict([(a, sum_simplify(a, **kwargs))
for a in s.atoms(Add) if a.has(Sum)]))
s = expand(s)
if not isinstance(s, Add):
return s
terms = s.args
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
sum_terms, other = sift(Mul.make_args(term),
lambda i: isinstance(i, Sum), binary=True)
if not sum_terms:
o_t.append(term)
continue
other = [Mul(*other)]
s_t.append(Mul(*(other + [s._eval_simplify(**kwargs) for s in sum_terms])))
result = Add(sum_combine(s_t), *o_t)
return result
def sum_combine(s_t):
"""Helper function for Sum simplification
Attempts to simplify a list of sums, by combining limits / sum function's
returns the simplified sum
"""
from sympy.concrete.summations import Sum
used = [False] * len(s_t)
for method in range(2):
for i, s_term1 in enumerate(s_t):
if not used[i]:
for j, s_term2 in enumerate(s_t):
if not used[j] and i != j:
temp = sum_add(s_term1, s_term2, method)
if isinstance(temp, Sum) or isinstance(temp, Mul):
s_t[i] = temp
s_term1 = s_t[i]
used[j] = True
result = S.Zero
for i, s_term in enumerate(s_t):
if not used[i]:
result = Add(result, s_term)
return result
def factor_sum(self, limits=None, radical=False, clear=False, fraction=False, sign=True):
"""Return Sum with constant factors extracted.
If ``limits`` is specified then ``self`` is the summand; the other
keywords are passed to ``factor_terms``.
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y
>>> from sympy.simplify.simplify import factor_sum
>>> s = Sum(x*y, (x, 1, 3))
>>> factor_sum(s)
y*Sum(x, (x, 1, 3))
>>> factor_sum(s.function, s.limits)
y*Sum(x, (x, 1, 3))
"""
# XXX deprecate in favor of direct call to factor_terms
from sympy.concrete.summations import Sum
kwargs = dict(radical=radical, clear=clear,
fraction=fraction, sign=sign)
expr = Sum(self, *limits) if limits else self
return factor_terms(expr, **kwargs)
def sum_add(self, other, method=0):
"""Helper function for Sum simplification"""
from sympy.concrete.summations import Sum
from sympy import Mul
#we know this is something in terms of a constant * a sum
#so we temporarily put the constants inside for simplification
#then simplify the result
def __refactor(val):
args = Mul.make_args(val)
sumv = next(x for x in args if isinstance(x, Sum))
constant = Mul(*[x for x in args if x != sumv])
return Sum(constant * sumv.function, *sumv.limits)
if isinstance(self, Mul):
rself = __refactor(self)
else:
rself = self
if isinstance(other, Mul):
rother = __refactor(other)
else:
rother = other
if type(rself) == type(rother):
if method == 0:
if rself.limits == rother.limits:
return factor_sum(Sum(rself.function + rother.function, *rself.limits))
elif method == 1:
if simplify(rself.function - rother.function) == 0:
if len(rself.limits) == len(rother.limits) == 1:
i = rself.limits[0][0]
x1 = rself.limits[0][1]
y1 = rself.limits[0][2]
j = rother.limits[0][0]
x2 = rother.limits[0][1]
y2 = rother.limits[0][2]
if i == j:
if x2 == y1 + 1:
return factor_sum(Sum(rself.function, (i, x1, y2)))
elif x1 == y2 + 1:
return factor_sum(Sum(rself.function, (i, x2, y1)))
return Add(self, other)
def product_simplify(s):
"""Main function for Product simplification"""
from sympy.concrete.products import Product
terms = Mul.make_args(s)
p_t = [] # Product Terms
o_t = [] # Other Terms
for term in terms:
if isinstance(term, Product):
p_t.append(term)
else:
o_t.append(term)
used = [False] * len(p_t)
for method in range(2):
for i, p_term1 in enumerate(p_t):
if not used[i]:
for j, p_term2 in enumerate(p_t):
if not used[j] and i != j:
if isinstance(product_mul(p_term1, p_term2, method), Product):
p_t[i] = product_mul(p_term1, p_term2, method)
used[j] = True
result = Mul(*o_t)
for i, p_term in enumerate(p_t):
if not used[i]:
result = Mul(result, p_term)
return result
def product_mul(self, other, method=0):
"""Helper function for Product simplification"""
from sympy.concrete.products import Product
if type(self) == type(other):
if method == 0:
if self.limits == other.limits:
return Product(self.function * other.function, *self.limits)
elif method == 1:
if simplify(self.function - other.function) == 0:
if len(self.limits) == len(other.limits) == 1:
i = self.limits[0][0]
x1 = self.limits[0][1]
y1 = self.limits[0][2]
j = other.limits[0][0]
x2 = other.limits[0][1]
y2 = other.limits[0][2]
if i == j:
if x2 == y1 + 1:
return Product(self.function, (i, x1, y2))
elif x1 == y2 + 1:
return Product(self.function, (i, x2, y1))
return Mul(self, other)
def _nthroot_solve(p, n, prec):
"""
helper function for ``nthroot``
It denests ``p**Rational(1, n)`` using its minimal polynomial
"""
from sympy.polys.numberfields import _minimal_polynomial_sq
from sympy.solvers import solve
while n % 2 == 0:
p = sqrtdenest(sqrt(p))
n = n // 2
if n == 1:
return p
pn = p**Rational(1, n)
x = Symbol('x')
f = _minimal_polynomial_sq(p, n, x)
if f is None:
return None
sols = solve(f, x)
for sol in sols:
if abs(sol - pn).n() < 1./10**prec:
sol = sqrtdenest(sol)
if _mexpand(sol**n) == p:
return sol
def logcombine(expr, force=False):
"""
Takes logarithms and combines them using the following rules:
- log(x) + log(y) == log(x*y) if both are positive
- a*log(x) == log(x**a) if x is positive and a is real
If ``force`` is True then the assumptions above will be assumed to hold if
there is no assumption already in place on a quantity. For example, if
``a`` is imaginary or the argument negative, force will not perform a
combination but if ``a`` is a symbol with no assumptions the change will
take place.
Examples
========
>>> from sympy import Symbol, symbols, log, logcombine, I
>>> from sympy.abc import a, x, y, z
>>> logcombine(a*log(x) + log(y) - log(z))
a*log(x) + log(y) - log(z)
>>> logcombine(a*log(x) + log(y) - log(z), force=True)
log(x**a*y/z)
>>> x,y,z = symbols('x,y,z', positive=True)
>>> a = Symbol('a', real=True)
>>> logcombine(a*log(x) + log(y) - log(z))
log(x**a*y/z)
The transformation is limited to factors and/or terms that
contain logs, so the result depends on the initial state of
expansion:
>>> eq = (2 + 3*I)*log(x)
>>> logcombine(eq, force=True) == eq
True
>>> logcombine(eq.expand(), force=True)
log(x**2) + I*log(x**3)
See Also
========
posify: replace all symbols with symbols having positive assumptions
sympy.core.function.expand_log: expand the logarithms of products
and powers; the opposite of logcombine
"""
def f(rv):
if not (rv.is_Add or rv.is_Mul):
return rv
def gooda(a):
# bool to tell whether the leading ``a`` in ``a*log(x)``
# could appear as log(x**a)
return (a is not S.NegativeOne and # -1 *could* go, but we disallow
(a.is_extended_real or force and a.is_extended_real is not False))
def goodlog(l):
# bool to tell whether log ``l``'s argument can combine with others
a = l.args[0]
return a.is_positive or force and a.is_nonpositive is not False
other = []
logs = []
log1 = defaultdict(list)
for a in Add.make_args(rv):
if isinstance(a, log) and goodlog(a):
log1[()].append(([], a))
elif not a.is_Mul:
other.append(a)
else:
ot = []
co = []
lo = []
for ai in a.args:
if ai.is_Rational and ai < 0:
ot.append(S.NegativeOne)
co.append(-ai)
elif isinstance(ai, log) and goodlog(ai):
lo.append(ai)
elif gooda(ai):
co.append(ai)
else:
ot.append(ai)
if len(lo) > 1:
logs.append((ot, co, lo))
elif lo:
log1[tuple(ot)].append((co, lo[0]))
else:
other.append(a)
# if there is only one log in other, put it with the
# good logs
if len(other) == 1 and isinstance(other[0], log):
log1[()].append(([], other.pop()))
# if there is only one log at each coefficient and none have
# an exponent to place inside the log then there is nothing to do
if not logs and all(len(log1[k]) == 1 and log1[k][0] == [] for k in log1):
return rv
# collapse multi-logs as far as possible in a canonical way
# TODO: see if x*log(a)+x*log(a)*log(b) -> x*log(a)*(1+log(b))?
# -- in this case, it's unambiguous, but if it were were a log(c) in
# each term then it's arbitrary whether they are grouped by log(a) or
# by log(c). So for now, just leave this alone; it's probably better to
# let the user decide
for o, e, l in logs:
l = list(ordered(l))
e = log(l.pop(0).args[0]**Mul(*e))
while l:
li = l.pop(0)
e = log(li.args[0]**e)
c, l = Mul(*o), e
if isinstance(l, log): # it should be, but check to be sure
log1[(c,)].append(([], l))
else:
other.append(c*l)
# logs that have the same coefficient can multiply
for k in list(log1.keys()):
log1[Mul(*k)] = log(logcombine(Mul(*[
l.args[0]**Mul(*c) for c, l in log1.pop(k)]),
force=force), evaluate=False)
# logs that have oppositely signed coefficients can divide
for k in ordered(list(log1.keys())):
if not k in log1: # already popped as -k
continue
if -k in log1:
# figure out which has the minus sign; the one with
# more op counts should be the one
num, den = k, -k
if num.count_ops() > den.count_ops():
num, den = den, num
other.append(
num*log(log1.pop(num).args[0]/log1.pop(den).args[0],
evaluate=False))
else:
other.append(k*log1.pop(k))
return Add(*other)
return bottom_up(expr, f)
def inversecombine(expr):
"""Simplify the composition of a function and its inverse.
No attention is paid to whether the inverse is a left inverse or a
right inverse; thus, the result will in general not be equivalent
to the original expression.
Examples
========
>>> from sympy.simplify.simplify import inversecombine
>>> from sympy import asin, sin, log, exp
>>> from sympy.abc import x
>>> inversecombine(asin(sin(x)))
x
>>> inversecombine(2*log(exp(3*x)))
6*x
"""
def f(rv):
if rv.is_Function and hasattr(rv, "inverse"):
if (len(rv.args) == 1 and len(rv.args[0].args) == 1 and
isinstance(rv.args[0], rv.inverse(argindex=1))):
rv = rv.args[0].args[0]
return rv
return bottom_up(expr, f)
def walk(e, *target):
"""iterate through the args that are the given types (target) and
return a list of the args that were traversed; arguments
that are not of the specified types are not traversed.
Examples
========
>>> from sympy.simplify.simplify import walk
>>> from sympy import Min, Max
>>> from sympy.abc import x, y, z
>>> list(walk(Min(x, Max(y, Min(1, z))), Min))
[Min(x, Max(y, Min(1, z)))]
>>> list(walk(Min(x, Max(y, Min(1, z))), Min, Max))
[Min(x, Max(y, Min(1, z))), Max(y, Min(1, z)), Min(1, z)]
See Also
========
bottom_up
"""
if isinstance(e, target):
yield e
for i in e.args:
for w in walk(i, *target):
yield w
def bottom_up(rv, F, atoms=False, nonbasic=False):
"""Apply ``F`` to all expressions in an expression tree from the
bottom up. If ``atoms`` is True, apply ``F`` even if there are no args;
if ``nonbasic`` is True, try to apply ``F`` to non-Basic objects.
"""
args = getattr(rv, 'args', None)
if args is not None:
if args:
args = tuple([bottom_up(a, F, atoms, nonbasic) for a in args])
if args != rv.args:
rv = rv.func(*args)
rv = F(rv)
elif atoms:
rv = F(rv)
else:
if nonbasic:
try:
rv = F(rv)
except TypeError:
pass
return rv
def kroneckersimp(expr):
"""
Simplify expressions with KroneckerDelta.
The only simplification currently attempted is to identify multiplicative cancellation:
>>> from sympy import KroneckerDelta, kroneckersimp
>>> from sympy.abc import i
>>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i))
1
"""
def args_cancel(args1, args2):
for i1 in range(2):
for i2 in range(2):
a1 = args1[i1]
a2 = args2[i2]
a3 = args1[(i1 + 1) % 2]
a4 = args2[(i2 + 1) % 2]
if Eq(a1, a2) is S.true and Eq(a3, a4) is S.false:
return True
return False
def cancel_kronecker_mul(m):
from sympy.utilities.iterables import subsets
args = m.args
deltas = [a for a in args if isinstance(a, KroneckerDelta)]
for delta1, delta2 in subsets(deltas, 2):
args1 = delta1.args
args2 = delta2.args
if args_cancel(args1, args2):
return 0*m
return m
if not expr.has(KroneckerDelta):
return expr
if expr.has(Piecewise):
expr = expr.rewrite(KroneckerDelta)
newexpr = expr
expr = None
while newexpr != expr:
expr = newexpr
newexpr = expr.replace(lambda e: isinstance(e, Mul), cancel_kronecker_mul)
return expr
def besselsimp(expr):
"""
Simplify bessel-type functions.
This routine tries to simplify bessel-type functions. Currently it only
works on the Bessel J and I functions, however. It works by looking at all
such functions in turn, and eliminating factors of "I" and "-1" (actually
their polar equivalents) in front of the argument. Then, functions of
half-integer order are rewritten using strigonometric functions and
functions of integer order (> 1) are rewritten using functions
of low order. Finally, if the expression was changed, compute
factorization of the result with factor().
>>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S
>>> from sympy.abc import z, nu
>>> besselsimp(besselj(nu, z*polar_lift(-1)))
exp(I*pi*nu)*besselj(nu, z)
>>> besselsimp(besseli(nu, z*polar_lift(-I)))
exp(-I*pi*nu/2)*besselj(nu, z)
>>> besselsimp(besseli(S(-1)/2, z))
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
>>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z))
3*z*besseli(0, z)/2
"""
# TODO
# - better algorithm?
# - simplify (cos(pi*b)*besselj(b,z) - besselj(-b,z))/sin(pi*b) ...
# - use contiguity relations?
def replacer(fro, to, factors):
factors = set(factors)
def repl(nu, z):
if factors.intersection(Mul.make_args(z)):
return to(nu, z)
return fro(nu, z)
return repl
def torewrite(fro, to):
def tofunc(nu, z):
return fro(nu, z).rewrite(to)
return tofunc
def tominus(fro):
def tofunc(nu, z):
return exp(I*pi*nu)*fro(nu, exp_polar(-I*pi)*z)
return tofunc
orig_expr = expr
ifactors = [I, exp_polar(I*pi/2), exp_polar(-I*pi/2)]
expr = expr.replace(
besselj, replacer(besselj,
torewrite(besselj, besseli), ifactors))
expr = expr.replace(
besseli, replacer(besseli,
torewrite(besseli, besselj), ifactors))
minusfactors = [-1, exp_polar(I*pi)]
expr = expr.replace(
besselj, replacer(besselj, tominus(besselj), minusfactors))
expr = expr.replace(
besseli, replacer(besseli, tominus(besseli), minusfactors))
z0 = Dummy('z')
def expander(fro):
def repl(nu, z):
if (nu % 1) == S.Half:
return simplify(trigsimp(unpolarify(
fro(nu, z0).rewrite(besselj).rewrite(jn).expand(
func=True)).subs(z0, z)))
elif nu.is_Integer and nu > 1:
return fro(nu, z).expand(func=True)
return fro(nu, z)
return repl
expr = expr.replace(besselj, expander(besselj))
expr = expr.replace(bessely, expander(bessely))
expr = expr.replace(besseli, expander(besseli))
expr = expr.replace(besselk, expander(besselk))
def _bessel_simp_recursion(expr):
def _use_recursion(bessel, expr):
while True:
bessels = expr.find(lambda x: isinstance(x, bessel))
try:
for ba in sorted(bessels, key=lambda x: re(x.args[0])):
a, x = ba.args
bap1 = bessel(a+1, x)
bap2 = bessel(a+2, x)
if expr.has(bap1) and expr.has(bap2):
expr = expr.subs(ba, 2*(a+1)/x*bap1 - bap2)
break
else:
return expr
except (ValueError, TypeError):
return expr
if expr.has(besselj):
expr = _use_recursion(besselj, expr)
if expr.has(bessely):
expr = _use_recursion(bessely, expr)
return expr
expr = _bessel_simp_recursion(expr)
if expr != orig_expr:
expr = expr.factor()
return expr
def nthroot(expr, n, max_len=4, prec=15):
"""
compute a real nth-root of a sum of surds
Parameters
==========
expr : sum of surds
n : integer
max_len : maximum number of surds passed as constants to ``nsimplify``
Algorithm
=========
First ``nsimplify`` is used to get a candidate root; if it is not a
root the minimal polynomial is computed; the answer is one of its
roots.
Examples
========
>>> from sympy.simplify.simplify import nthroot
>>> from sympy import sqrt
>>> nthroot(90 + 34*sqrt(7), 3)
sqrt(7) + 3
"""
expr = sympify(expr)
n = sympify(n)
p = expr**Rational(1, n)
if not n.is_integer:
return p
if not _is_sum_surds(expr):
return p
surds = []
coeff_muls = [x.as_coeff_Mul() for x in expr.args]
for x, y in coeff_muls:
if not x.is_rational:
return p
if y is S.One:
continue
if not (y.is_Pow and y.exp == S.Half and y.base.is_integer):
return p
surds.append(y)
surds.sort()
surds = surds[:max_len]
if expr < 0 and n % 2 == 1:
p = (-expr)**Rational(1, n)
a = nsimplify(p, constants=surds)
res = a if _mexpand(a**n) == _mexpand(-expr) else p
return -res
a = nsimplify(p, constants=surds)
if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr):
return _mexpand(a)
expr = _nthroot_solve(expr, n, prec)
if expr is None:
return p
return expr
def nsimplify(expr, constants=(), tolerance=None, full=False, rational=None,
rational_conversion='base10'):
"""
Find a simple representation for a number or, if there are free symbols or
if rational=True, then replace Floats with their Rational equivalents. If
no change is made and rational is not False then Floats will at least be
converted to Rationals.
For numerical expressions, a simple formula that numerically matches the
given numerical expression is sought (and the input should be possible
to evalf to a precision of at least 30 digits).
Optionally, a list of (rationally independent) constants to
include in the formula may be given.
A lower tolerance may be set to find less exact matches. If no tolerance
is given then the least precise value will set the tolerance (e.g. Floats
default to 15 digits of precision, so would be tolerance=10**-15).
With full=True, a more extensive search is performed
(this is useful to find simpler numbers when the tolerance
is set low).
When converting to rational, if rational_conversion='base10' (the default), then
convert floats to rationals using their base-10 (string) representation.
When rational_conversion='exact' it uses the exact, base-2 representation.
Examples
========
>>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi
>>> nsimplify(4/(1+sqrt(5)), [GoldenRatio])
-2 + 2*GoldenRatio
>>> nsimplify((1/(exp(3*pi*I/5)+1)))
1/2 - I*sqrt(sqrt(5)/10 + 1/4)
>>> nsimplify(I**I, [pi])
exp(-pi/2)
>>> nsimplify(pi, tolerance=0.01)
22/7
>>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact')
6004799503160655/18014398509481984
>>> nsimplify(0.333333333333333, rational=True)
1/3
See Also
========
sympy.core.function.nfloat
"""
try:
return sympify(as_int(expr))
except (TypeError, ValueError):
pass
expr = sympify(expr).xreplace({
Float('inf'): S.Infinity,
Float('-inf'): S.NegativeInfinity,
})
if expr is S.Infinity or expr is S.NegativeInfinity:
return expr
if rational or expr.free_symbols:
return _real_to_rational(expr, tolerance, rational_conversion)
# SymPy's default tolerance for Rationals is 15; other numbers may have
# lower tolerances set, so use them to pick the largest tolerance if None
# was given
if tolerance is None:
tolerance = 10**-min([15] +
[mpmath.libmp.libmpf.prec_to_dps(n._prec)
for n in expr.atoms(Float)])
# XXX should prec be set independent of tolerance or should it be computed
# from tolerance?
prec = 30
bprec = int(prec*3.33)
constants_dict = {}
for constant in constants:
constant = sympify(constant)
v = constant.evalf(prec)
if not v.is_Float:
raise ValueError("constants must be real-valued")
constants_dict[str(constant)] = v._to_mpmath(bprec)
exprval = expr.evalf(prec, chop=True)
re, im = exprval.as_real_imag()
# safety check to make sure that this evaluated to a number
if not (re.is_Number and im.is_Number):
return expr
def nsimplify_real(x):
orig = mpmath.mp.dps
xv = x._to_mpmath(bprec)
try:
# We'll be happy with low precision if a simple fraction
if not (tolerance or full):
mpmath.mp.dps = 15
rat = mpmath.pslq([xv, 1])
if rat is not None:
return Rational(-int(rat[1]), int(rat[0]))
mpmath.mp.dps = prec
newexpr = mpmath.identify(xv, constants=constants_dict,
tol=tolerance, full=full)
if not newexpr:
raise ValueError
if full:
newexpr = newexpr[0]
expr = sympify(newexpr)
if x and not expr: # don't let x become 0
raise ValueError
if expr.is_finite is False and not xv in [mpmath.inf, mpmath.ninf]:
raise ValueError
return expr
finally:
# even though there are returns above, this is executed
# before leaving
mpmath.mp.dps = orig
try:
if re:
re = nsimplify_real(re)
if im:
im = nsimplify_real(im)
except ValueError:
if rational is None:
return _real_to_rational(expr, rational_conversion=rational_conversion)
return expr
rv = re + im*S.ImaginaryUnit
# if there was a change or rational is explicitly not wanted
# return the value, else return the Rational representation
if rv != expr or rational is False:
return rv
return _real_to_rational(expr, rational_conversion=rational_conversion)
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
>>> _real_to_rational(.76 + .1*x**.5)
sqrt(x)/10 + 19/25
If rational_conversion='base10', this uses the base-10 string. If
rational_conversion='exact', the exact, base-2 representation is used.
>>> _real_to_rational(0.333333333333333, rational_conversion='exact')
6004799503160655/18014398509481984
>>> _real_to_rational(0.333333333333333)
1/3
"""
expr = _sympify(expr)
inf = Float('inf')
p = expr
reps = {}
reduce_num = None
if tolerance is not None and tolerance < 1:
reduce_num = ceiling(1/tolerance)
for fl in p.atoms(Float):
key = fl
if reduce_num is not None:
r = Rational(fl).limit_denominator(reduce_num)
elif (tolerance is not None and tolerance >= 1 and
fl.is_Integer is False):
r = Rational(tolerance*round(fl/tolerance)
).limit_denominator(int(tolerance))
else:
if rational_conversion == 'exact':
r = Rational(fl)
reps[key] = r
continue
elif rational_conversion != 'base10':
raise ValueError("rational_conversion must be 'base10' or 'exact'")
r = nsimplify(fl, rational=False)
# e.g. log(3).n() -> log(3) instead of a Rational
if fl and not r:
r = Rational(fl)
elif not r.is_Rational:
if fl == inf or fl == -inf:
r = S.ComplexInfinity
elif fl < 0:
fl = -fl
d = Pow(10, int((mpmath.log(fl)/mpmath.log(10))))
r = -Rational(str(fl/d))*d
elif fl > 0:
d = Pow(10, int((mpmath.log(fl)/mpmath.log(10))))
r = Rational(str(fl/d))*d
else:
r = Integer(0)
reps[key] = r
return p.subs(reps, simultaneous=True)
def clear_coefficients(expr, rhs=S.Zero):
"""Return `p, r` where `p` is the expression obtained when Rational
additive and multiplicative coefficients of `expr` have been stripped
away in a naive fashion (i.e. without simplification). The operations
needed to remove the coefficients will be applied to `rhs` and returned
as `r`.
Examples
========
>>> from sympy.simplify.simplify import clear_coefficients
>>> from sympy.abc import x, y
>>> from sympy import Dummy
>>> expr = 4*y*(6*x + 3)
>>> clear_coefficients(expr - 2)
(y*(2*x + 1), 1/6)
When solving 2 or more expressions like `expr = a`,
`expr = b`, etc..., it is advantageous to provide a Dummy symbol
for `rhs` and simply replace it with `a`, `b`, etc... in `r`.
>>> rhs = Dummy('rhs')
>>> clear_coefficients(expr, rhs)
(y*(2*x + 1), _rhs/12)
>>> _[1].subs(rhs, 2)
1/6
"""
was = None
free = expr.free_symbols
if expr.is_Rational:
return (S.Zero, rhs - expr)
while expr and was != expr:
was = expr
m, expr = (
expr.as_content_primitive()
if free else
factor_terms(expr).as_coeff_Mul(rational=True))
rhs /= m
c, expr = expr.as_coeff_Add(rational=True)
rhs -= c
expr = signsimp(expr, evaluate = False)
if _coeff_isneg(expr):
expr = -expr
rhs = -rhs
return expr, rhs
def nc_simplify(expr, deep=True):
'''
Simplify a non-commutative expression composed of multiplication
and raising to a power by grouping repeated subterms into one power.
Priority is given to simplifications that give the fewest number
of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying
to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3).
If `expr` is a sum of such terms, the sum of the simplified terms
is returned.
Keyword argument `deep` controls whether or not subexpressions
nested deeper inside the main expression are simplified. See examples
below. Setting `deep` to `False` can save time on nested expressions
that don't need simplifying on all levels.
Examples
========
>>> from sympy import symbols
>>> from sympy.simplify.simplify import nc_simplify
>>> a, b, c = symbols("a b c", commutative=False)
>>> nc_simplify(a*b*a*b*c*a*b*c)
a*b*(a*b*c)**2
>>> expr = a**2*b*a**4*b*a**4
>>> nc_simplify(expr)
a**2*(b*a**4)**2
>>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2)
((a*b)**2*c**2)**2
>>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a)
(a*b)**2 + 2*(a*c*a)**3
>>> nc_simplify(b**-1*a**-1*(a*b)**2)
a*b
>>> nc_simplify(a**-1*b**-1*c*a)
(b*a)**(-1)*c*a
>>> expr = (a*b*a*b)**2*a*c*a*c
>>> nc_simplify(expr)
(a*b)**4*(a*c)**2
>>> nc_simplify(expr, deep=False)
(a*b*a*b)**2*(a*c)**2
'''
from sympy.matrices.expressions import (MatrixExpr, MatAdd, MatMul,
MatPow, MatrixSymbol)
from sympy.core.exprtools import factor_nc
if isinstance(expr, MatrixExpr):
expr = expr.doit(inv_expand=False)
_Add, _Mul, _Pow, _Symbol = MatAdd, MatMul, MatPow, MatrixSymbol
else:
_Add, _Mul, _Pow, _Symbol = Add, Mul, Pow, Symbol
# =========== Auxiliary functions ========================
def _overlaps(args):
# Calculate a list of lists m such that m[i][j] contains the lengths
# of all possible overlaps between args[:i+1] and args[i+1+j:].
# An overlap is a suffix of the prefix that matches a prefix
# of the suffix.
# For example, let expr=c*a*b*a*b*a*b*a*b. Then m[3][0] contains
# the lengths of overlaps of c*a*b*a*b with a*b*a*b. The overlaps
# are a*b*a*b, a*b and the empty word so that m[3][0]=[4,2,0].
# All overlaps rather than only the longest one are recorded
# because this information helps calculate other overlap lengths.
m = [[([1, 0] if a == args[0] else [0]) for a in args[1:]]]
for i in range(1, len(args)):
overlaps = []
j = 0
for j in range(len(args) - i - 1):
overlap = []
for v in m[i-1][j+1]:
if j + i + 1 + v < len(args) and args[i] == args[j+i+1+v]:
overlap.append(v + 1)
overlap += [0]
overlaps.append(overlap)
m.append(overlaps)
return m
def _reduce_inverses(_args):
# replace consecutive negative powers by an inverse
# of a product of positive powers, e.g. a**-1*b**-1*c
# will simplify to (a*b)**-1*c;
# return that new args list and the number of negative
# powers in it (inv_tot)
inv_tot = 0 # total number of inverses
inverses = []
args = []
for arg in _args:
if isinstance(arg, _Pow) and arg.args[1] < 0:
inverses = [arg**-1] + inverses
inv_tot += 1
else:
if len(inverses) == 1:
args.append(inverses[0]**-1)
elif len(inverses) > 1:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
inverses = []
args.append(arg)
if inverses:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
return inv_tot, tuple(args)
def get_score(s):
# compute the number of arguments of s
# (including in nested expressions) overall
# but ignore exponents
if isinstance(s, _Pow):
return get_score(s.args[0])
elif isinstance(s, (_Add, _Mul)):
return sum([get_score(a) for a in s.args])
return 1
def compare(s, alt_s):
# compare two possible simplifications and return a
# "better" one
if s != alt_s and get_score(alt_s) < get_score(s):
return alt_s
return s
# ========================================================
if not isinstance(expr, (_Add, _Mul, _Pow)) or expr.is_commutative:
return expr
args = expr.args[:]
if isinstance(expr, _Pow):
if deep:
return _Pow(nc_simplify(args[0]), args[1]).doit()
else:
return expr
elif isinstance(expr, _Add):
return _Add(*[nc_simplify(a, deep=deep) for a in args]).doit()
else:
# get the non-commutative part
c_args, args = expr.args_cnc()
com_coeff = Mul(*c_args)
if com_coeff != 1:
return com_coeff*nc_simplify(expr/com_coeff, deep=deep)
inv_tot, args = _reduce_inverses(args)
# if most arguments are negative, work with the inverse
# of the expression, e.g. a**-1*b*a**-1*c**-1 will become
# (c*a*b**-1*a)**-1 at the end so can work with c*a*b**-1*a
invert = False
if inv_tot > len(args)/2:
invert = True
args = [a**-1 for a in args[::-1]]
if deep:
args = tuple(nc_simplify(a) for a in args)
m = _overlaps(args)
# simps will be {subterm: end} where `end` is the ending
# index of a sequence of repetitions of subterm;
# this is for not wasting time with subterms that are part
# of longer, already considered sequences
simps = {}
post = 1
pre = 1
# the simplification coefficient is the number of
# arguments by which contracting a given sequence
# would reduce the word; e.g. in a*b*a*b*c*a*b*c,
# contracting a*b*a*b to (a*b)**2 removes 3 arguments
# while a*b*c*a*b*c to (a*b*c)**2 removes 6. It's
# better to contract the latter so simplification
# with a maximum simplification coefficient will be chosen
max_simp_coeff = 0
simp = None # information about future simplification
for i in range(1, len(args)):
simp_coeff = 0
l = 0 # length of a subterm
p = 0 # the power of a subterm
if i < len(args) - 1:
rep = m[i][0]
start = i # starting index of the repeated sequence
end = i+1 # ending index of the repeated sequence
if i == len(args)-1 or rep == [0]:
# no subterm is repeated at this stage, at least as
# far as the arguments are concerned - there may be
# a repetition if powers are taken into account
if (isinstance(args[i], _Pow) and
not isinstance(args[i].args[0], _Symbol)):
subterm = args[i].args[0].args
l = len(subterm)
if args[i-l:i] == subterm:
# e.g. a*b in a*b*(a*b)**2 is not repeated
# in args (= [a, b, (a*b)**2]) but it
# can be matched here
p += 1
start -= l
if args[i+1:i+1+l] == subterm:
# e.g. a*b in (a*b)**2*a*b
p += 1
end += l
if p:
p += args[i].args[1]
else:
continue
else:
l = rep[0] # length of the longest repeated subterm at this point
start -= l - 1
subterm = args[start:end]
p = 2
end += l
if subterm in simps and simps[subterm] >= start:
# the subterm is part of a sequence that
# has already been considered
continue
# count how many times it's repeated
while end < len(args):
if l in m[end-1][0]:
p += 1
end += l
elif isinstance(args[end], _Pow) and args[end].args[0].args == subterm:
# for cases like a*b*a*b*(a*b)**2*a*b
p += args[end].args[1]
end += 1
else:
break
# see if another match can be made, e.g.
# for b*a**2 in b*a**2*b*a**3 or a*b in
# a**2*b*a*b
pre_exp = 0
pre_arg = 1
if start - l >= 0 and args[start-l+1:start] == subterm[1:]:
if isinstance(subterm[0], _Pow):
pre_arg = subterm[0].args[0]
exp = subterm[0].args[1]
else:
pre_arg = subterm[0]
exp = 1
if isinstance(args[start-l], _Pow) and args[start-l].args[0] == pre_arg:
pre_exp = args[start-l].args[1] - exp
start -= l
p += 1
elif args[start-l] == pre_arg:
pre_exp = 1 - exp
start -= l
p += 1
post_exp = 0
post_arg = 1
if end + l - 1 < len(args) and args[end:end+l-1] == subterm[:-1]:
if isinstance(subterm[-1], _Pow):
post_arg = subterm[-1].args[0]
exp = subterm[-1].args[1]
else:
post_arg = subterm[-1]
exp = 1
if isinstance(args[end+l-1], _Pow) and args[end+l-1].args[0] == post_arg:
post_exp = args[end+l-1].args[1] - exp
end += l
p += 1
elif args[end+l-1] == post_arg:
post_exp = 1 - exp
end += l
p += 1
# Consider a*b*a**2*b*a**2*b*a:
# b*a**2 is explicitly repeated, but note
# that in this case a*b*a is also repeated
# so there are two possible simplifications:
# a*(b*a**2)**3*a**-1 or (a*b*a)**3
# The latter is obviously simpler.
# But in a*b*a**2*b**2*a**2 the simplifications are
# a*(b*a**2)**2 and (a*b*a)**3*a in which case
# it's better to stick with the shorter subterm
if post_exp and exp % 2 == 0 and start > 0:
exp = exp/2
_pre_exp = 1
_post_exp = 1
if isinstance(args[start-1], _Pow) and args[start-1].args[0] == post_arg:
_post_exp = post_exp + exp
_pre_exp = args[start-1].args[1] - exp
elif args[start-1] == post_arg:
_post_exp = post_exp + exp
_pre_exp = 1 - exp
if _pre_exp == 0 or _post_exp == 0:
if not pre_exp:
start -= 1
post_exp = _post_exp
pre_exp = _pre_exp
pre_arg = post_arg
subterm = (post_arg**exp,) + subterm[:-1] + (post_arg**exp,)
simp_coeff += end-start
if post_exp:
simp_coeff -= 1
if pre_exp:
simp_coeff -= 1
simps[subterm] = end
if simp_coeff > max_simp_coeff:
max_simp_coeff = simp_coeff
simp = (start, _Mul(*subterm), p, end, l)
pre = pre_arg**pre_exp
post = post_arg**post_exp
if simp:
subterm = _Pow(nc_simplify(simp[1], deep=deep), simp[2])
pre = nc_simplify(_Mul(*args[:simp[0]])*pre, deep=deep)
post = post*nc_simplify(_Mul(*args[simp[3]:]), deep=deep)
simp = pre*subterm*post
if pre != 1 or post != 1:
# new simplifications may be possible but no need
# to recurse over arguments
simp = nc_simplify(simp, deep=False)
else:
simp = _Mul(*args)
if invert:
simp = _Pow(simp, -1)
# see if factor_nc(expr) is simplified better
if not isinstance(expr, MatrixExpr):
f_expr = factor_nc(expr)
if f_expr != expr:
alt_simp = nc_simplify(f_expr, deep=deep)
simp = compare(simp, alt_simp)
else:
simp = simp.doit(inv_expand=False)
return simp
def dotprodsimp(expr, withsimp=False):
"""Simplification for a sum of products targeted at the kind of blowup that
occurs during summation of products. Intended to reduce expression blowup
during matrix multiplication or other similar operations. Only works with
algebraic expressions and does not recurse into non.
Parameters
==========
withsimp : bool, optional
Specifies whether a flag should be returned along with the expression
to indicate roughly whether simplification was successful. It is used
in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to
simplify an expression repetitively which does not simplify.
"""
def count_ops_alg(expr):
"""Optimized count algebraic operations with no recursion into
non-algebraic args that ``core.function.count_ops`` does. Also returns
whether rational functions may be present according to negative
exponents of powers or non-number fractions.
Returns
=======
ops, ratfunc : int, bool
``ops`` is the number of algebraic operations starting at the top
level expression (not recursing into non-alg children). ``ratfunc``
specifies whether the expression MAY contain rational functions
which ``cancel`` MIGHT optimize.
"""
ops = 0
args = [expr]
ratfunc = False
while args:
a = args.pop()
if not isinstance(a, Basic):
continue
if a.is_Rational:
if a is not S.One: # -1/3 = NEG + DIV
ops += bool (a.p < 0) + bool (a.q != 1)
elif a.is_Mul:
if _coeff_isneg(a):
ops += 1
if a.args[0] is S.NegativeOne:
a = a.as_two_terms()[1]
else:
a = -a
n, d = fraction(a)
if n.is_Integer:
ops += 1 + bool (n < 0)
args.append(d) # won't be -Mul but could be Add
elif d is not S.One:
if not d.is_Integer:
args.append(d)
ratfunc=True
ops += 1
args.append(n) # could be -Mul
else:
ops += len(a.args) - 1
args.extend(a.args)
elif a.is_Add:
laargs = len(a.args)
negs = 0
for ai in a.args:
if _coeff_isneg(ai):
negs += 1
ai = -ai
args.append(ai)
ops += laargs - (negs != laargs) # -x - y = NEG + SUB
elif a.is_Pow:
ops += 1
args.append(a.base)
if not ratfunc:
ratfunc = a.exp.is_negative is not False
return ops, ratfunc
def nonalg_subs_dummies(expr, dummies):
"""Substitute dummy variables for non-algebraic expressions to avoid
evaluation of non-algebraic terms that ``polys.polytools.cancel`` does.
"""
if not expr.args:
return expr
if expr.is_Add or expr.is_Mul or expr.is_Pow:
args = None
for i, a in enumerate(expr.args):
c = nonalg_subs_dummies(a, dummies)
if c is a:
continue
if args is None:
args = list(expr.args)
args[i] = c
if args is None:
return expr
return expr.func(*args)
return dummies.setdefault(expr, Dummy())
simplified = False # doesn't really mean simplified, rather "can simplify again"
if isinstance(expr, Basic) and (expr.is_Add or expr.is_Mul or expr.is_Pow):
expr2 = expr.expand(deep=True, modulus=None, power_base=False,
power_exp=False, mul=True, log=False, multinomial=True, basic=False)
if expr2 != expr:
expr = expr2
simplified = True
exprops, ratfunc = count_ops_alg(expr)
if exprops >= 6: # empirically tested cutoff for expensive simplification
if ratfunc:
dummies = {}
expr2 = nonalg_subs_dummies(expr, dummies)
if expr2 is expr or count_ops_alg(expr2)[0] >= 6: # check again after substitution
expr3 = cancel(expr2)
if expr3 != expr2:
expr = expr3.subs([(d, e) for e, d in dummies.items()])
simplified = True
# very special case: x/(x-1) - 1/(x-1) -> 1
elif (exprops == 5 and expr.is_Add and expr.args [0].is_Mul and
expr.args [1].is_Mul and expr.args [0].args [-1].is_Pow and
expr.args [1].args [-1].is_Pow and
expr.args [0].args [-1].exp is S.NegativeOne and
expr.args [1].args [-1].exp is S.NegativeOne):
expr2 = together (expr)
expr2ops = count_ops_alg(expr2)[0]
if expr2ops < exprops:
expr = expr2
simplified = True
else:
simplified = True
return (expr, simplified) if withsimp else expr
|
032de2bec20a5ead97aa7c3d9ffa457bb9e80752dc02cdba8c48ca4d5de48e5b | from sympy.core import Add, Expr, Mul, S, sympify
from sympy.core.function import _mexpand, count_ops, expand_mul
from sympy.core.symbol import Dummy
from sympy.functions import root, sign, sqrt
from sympy.polys import Poly, PolynomialError
from sympy.utilities import default_sort_key
def is_sqrt(expr):
"""Return True if expr is a sqrt, otherwise False."""
return expr.is_Pow and expr.exp.is_Rational and abs(expr.exp) is S.Half
def sqrt_depth(p):
"""Return the maximum depth of any square root argument of p.
>>> from sympy.functions.elementary.miscellaneous import sqrt
>>> from sympy.simplify.sqrtdenest import sqrt_depth
Neither of these square roots contains any other square roots
so the depth is 1:
>>> sqrt_depth(1 + sqrt(2)*(1 + sqrt(3)))
1
The sqrt(3) is contained within a square root so the depth is
2:
>>> sqrt_depth(1 + sqrt(2)*sqrt(1 + sqrt(3)))
2
"""
if p is S.ImaginaryUnit:
return 1
if p.is_Atom:
return 0
elif p.is_Add or p.is_Mul:
return max([sqrt_depth(x) for x in p.args], key=default_sort_key)
elif is_sqrt(p):
return sqrt_depth(p.base) + 1
else:
return 0
def is_algebraic(p):
"""Return True if p is comprised of only Rationals or square roots
of Rationals and algebraic operations.
Examples
========
>>> from sympy.functions.elementary.miscellaneous import sqrt
>>> from sympy.simplify.sqrtdenest import is_algebraic
>>> from sympy import cos
>>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*sqrt(2))))
True
>>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*cos(2))))
False
"""
if p.is_Rational:
return True
elif p.is_Atom:
return False
elif is_sqrt(p) or p.is_Pow and p.exp.is_Integer:
return is_algebraic(p.base)
elif p.is_Add or p.is_Mul:
return all(is_algebraic(x) for x in p.args)
else:
return False
def _subsets(n):
"""
Returns all possible subsets of the set (0, 1, ..., n-1) except the
empty set, listed in reversed lexicographical order according to binary
representation, so that the case of the fourth root is treated last.
Examples
========
>>> from sympy.simplify.sqrtdenest import _subsets
>>> _subsets(2)
[[1, 0], [0, 1], [1, 1]]
"""
if n == 1:
a = [[1]]
elif n == 2:
a = [[1, 0], [0, 1], [1, 1]]
elif n == 3:
a = [[1, 0, 0], [0, 1, 0], [1, 1, 0],
[0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
else:
b = _subsets(n - 1)
a0 = [x + [0] for x in b]
a1 = [x + [1] for x in b]
a = a0 + [[0]*(n - 1) + [1]] + a1
return a
def sqrtdenest(expr, max_iter=3):
"""Denests sqrts in an expression that contain other square roots
if possible, otherwise returns the expr unchanged. This is based on the
algorithms of [1].
Examples
========
>>> from sympy.simplify.sqrtdenest import sqrtdenest
>>> from sympy import sqrt
>>> sqrtdenest(sqrt(5 + 2 * sqrt(6)))
sqrt(2) + sqrt(3)
See Also
========
sympy.solvers.solvers.unrad
References
==========
.. [1] http://researcher.watson.ibm.com/researcher/files/us-fagin/symb85.pdf
.. [2] D. J. Jeffrey and A. D. Rich, 'Symplifying Square Roots of Square Roots
by Denesting' (available at http://www.cybertester.com/data/denest.pdf)
"""
expr = expand_mul(sympify(expr))
for i in range(max_iter):
z = _sqrtdenest0(expr)
if expr == z:
return expr
expr = z
return expr
def _sqrt_match(p):
"""Return [a, b, r] for p.match(a + b*sqrt(r)) where, in addition to
matching, sqrt(r) also has then maximal sqrt_depth among addends of p.
Examples
========
>>> from sympy.functions.elementary.miscellaneous import sqrt
>>> from sympy.simplify.sqrtdenest import _sqrt_match
>>> _sqrt_match(1 + sqrt(2) + sqrt(2)*sqrt(3) + 2*sqrt(1+sqrt(5)))
[1 + sqrt(2) + sqrt(6), 2, 1 + sqrt(5)]
"""
from sympy.simplify.radsimp import split_surds
p = _mexpand(p)
if p.is_Number:
res = (p, S.Zero, S.Zero)
elif p.is_Add:
pargs = sorted(p.args, key=default_sort_key)
sqargs = [x**2 for x in pargs]
if all(sq.is_Rational and sq.is_positive for sq in sqargs):
r, b, a = split_surds(p)
res = a, b, r
return list(res)
# to make the process canonical, the argument is included in the tuple
# so when the max is selected, it will be the largest arg having a
# given depth
v = [(sqrt_depth(x), x, i) for i, x in enumerate(pargs)]
nmax = max(v, key=default_sort_key)
if nmax[0] == 0:
res = []
else:
# select r
depth, _, i = nmax
r = pargs.pop(i)
v.pop(i)
b = S.One
if r.is_Mul:
bv = []
rv = []
for x in r.args:
if sqrt_depth(x) < depth:
bv.append(x)
else:
rv.append(x)
b = Mul._from_args(bv)
r = Mul._from_args(rv)
# collect terms comtaining r
a1 = []
b1 = [b]
for x in v:
if x[0] < depth:
a1.append(x[1])
else:
x1 = x[1]
if x1 == r:
b1.append(1)
else:
if x1.is_Mul:
x1args = list(x1.args)
if r in x1args:
x1args.remove(r)
b1.append(Mul(*x1args))
else:
a1.append(x[1])
else:
a1.append(x[1])
a = Add(*a1)
b = Add(*b1)
res = (a, b, r**2)
else:
b, r = p.as_coeff_Mul()
if is_sqrt(r):
res = (S.Zero, b, r**2)
else:
res = []
return list(res)
class SqrtdenestStopIteration(StopIteration):
pass
def _sqrtdenest0(expr):
"""Returns expr after denesting its arguments."""
if is_sqrt(expr):
n, d = expr.as_numer_denom()
if d is S.One: # n is a square root
if n.base.is_Add:
args = sorted(n.base.args, key=default_sort_key)
if len(args) > 2 and all((x**2).is_Integer for x in args):
try:
return _sqrtdenest_rec(n)
except SqrtdenestStopIteration:
pass
expr = sqrt(_mexpand(Add(*[_sqrtdenest0(x) for x in args])))
return _sqrtdenest1(expr)
else:
n, d = [_sqrtdenest0(i) for i in (n, d)]
return n/d
if isinstance(expr, Add):
cs = []
args = []
for arg in expr.args:
c, a = arg.as_coeff_Mul()
cs.append(c)
args.append(a)
if all(c.is_Rational for c in cs) and all(is_sqrt(arg) for arg in args):
return _sqrt_ratcomb(cs, args)
if isinstance(expr, Expr):
args = expr.args
if args:
return expr.func(*[_sqrtdenest0(a) for a in args])
return expr
def _sqrtdenest_rec(expr):
"""Helper that denests the square root of three or more surds.
It returns the denested expression; if it cannot be denested it
throws SqrtdenestStopIteration
Algorithm: expr.base is in the extension Q_m = Q(sqrt(r_1),..,sqrt(r_k));
split expr.base = a + b*sqrt(r_k), where `a` and `b` are on
Q_(m-1) = Q(sqrt(r_1),..,sqrt(r_(k-1))); then a**2 - b**2*r_k is
on Q_(m-1); denest sqrt(a**2 - b**2*r_k) and so on.
See [1], section 6.
Examples
========
>>> from sympy import sqrt
>>> from sympy.simplify.sqrtdenest import _sqrtdenest_rec
>>> _sqrtdenest_rec(sqrt(-72*sqrt(2) + 158*sqrt(5) + 498))
-sqrt(10) + sqrt(2) + 9 + 9*sqrt(5)
>>> w=-6*sqrt(55)-6*sqrt(35)-2*sqrt(22)-2*sqrt(14)+2*sqrt(77)+6*sqrt(10)+65
>>> _sqrtdenest_rec(sqrt(w))
-sqrt(11) - sqrt(7) + sqrt(2) + 3*sqrt(5)
"""
from sympy.simplify.radsimp import radsimp, rad_rationalize, split_surds
if not expr.is_Pow:
return sqrtdenest(expr)
if expr.base < 0:
return sqrt(-1)*_sqrtdenest_rec(sqrt(-expr.base))
g, a, b = split_surds(expr.base)
a = a*sqrt(g)
if a < b:
a, b = b, a
c2 = _mexpand(a**2 - b**2)
if len(c2.args) > 2:
g, a1, b1 = split_surds(c2)
a1 = a1*sqrt(g)
if a1 < b1:
a1, b1 = b1, a1
c2_1 = _mexpand(a1**2 - b1**2)
c_1 = _sqrtdenest_rec(sqrt(c2_1))
d_1 = _sqrtdenest_rec(sqrt(a1 + c_1))
num, den = rad_rationalize(b1, d_1)
c = _mexpand(d_1/sqrt(2) + num/(den*sqrt(2)))
else:
c = _sqrtdenest1(sqrt(c2))
if sqrt_depth(c) > 1:
raise SqrtdenestStopIteration
ac = a + c
if len(ac.args) >= len(expr.args):
if count_ops(ac) >= count_ops(expr.base):
raise SqrtdenestStopIteration
d = sqrtdenest(sqrt(ac))
if sqrt_depth(d) > 1:
raise SqrtdenestStopIteration
num, den = rad_rationalize(b, d)
r = d/sqrt(2) + num/(den*sqrt(2))
r = radsimp(r)
return _mexpand(r)
def _sqrtdenest1(expr, denester=True):
"""Return denested expr after denesting with simpler methods or, that
failing, using the denester."""
from sympy.simplify.simplify import radsimp
if not is_sqrt(expr):
return expr
a = expr.base
if a.is_Atom:
return expr
val = _sqrt_match(a)
if not val:
return expr
a, b, r = val
# try a quick numeric denesting
d2 = _mexpand(a**2 - b**2*r)
if d2.is_Rational:
if d2.is_positive:
z = _sqrt_numeric_denest(a, b, r, d2)
if z is not None:
return z
else:
# fourth root case
# sqrtdenest(sqrt(3 + 2*sqrt(3))) =
# sqrt(2)*3**(1/4)/2 + sqrt(2)*3**(3/4)/2
dr2 = _mexpand(-d2*r)
dr = sqrt(dr2)
if dr.is_Rational:
z = _sqrt_numeric_denest(_mexpand(b*r), a, r, dr2)
if z is not None:
return z/root(r, 4)
else:
z = _sqrt_symbolic_denest(a, b, r)
if z is not None:
return z
if not denester or not is_algebraic(expr):
return expr
res = sqrt_biquadratic_denest(expr, a, b, r, d2)
if res:
return res
# now call to the denester
av0 = [a, b, r, d2]
z = _denester([radsimp(expr**2)], av0, 0, sqrt_depth(expr))[0]
if av0[1] is None:
return expr
if z is not None:
if sqrt_depth(z) == sqrt_depth(expr) and count_ops(z) > count_ops(expr):
return expr
return z
return expr
def _sqrt_symbolic_denest(a, b, r):
"""Given an expression, sqrt(a + b*sqrt(b)), return the denested
expression or None.
Algorithm:
If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
(y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
(cb + b)**2 - 4*ca*cc is 0, then sqrt(a + b*sqrt(r)) can be rewritten as
sqrt(ca*(sqrt(r) + (cb + b)/(2*ca))**2).
Examples
========
>>> from sympy.simplify.sqrtdenest import _sqrt_symbolic_denest, sqrtdenest
>>> from sympy import sqrt, Symbol
>>> from sympy.abc import x
>>> a, b, r = 16 - 2*sqrt(29), 2, -10*sqrt(29) + 55
>>> _sqrt_symbolic_denest(a, b, r)
sqrt(11 - 2*sqrt(29)) + sqrt(5)
If the expression is numeric, it will be simplified:
>>> w = sqrt(sqrt(sqrt(3) + 1) + 1) + 1 + sqrt(2)
>>> sqrtdenest(sqrt((w**2).expand()))
1 + sqrt(2) + sqrt(1 + sqrt(1 + sqrt(3)))
Otherwise, it will only be simplified if assumptions allow:
>>> w = w.subs(sqrt(3), sqrt(x + 3))
>>> sqrtdenest(sqrt((w**2).expand()))
sqrt((sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2))**2)
Notice that the argument of the sqrt is a square. If x is made positive
then the sqrt of the square is resolved:
>>> _.subs(x, Symbol('x', positive=True))
sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2)
"""
a, b, r = map(sympify, (a, b, r))
rval = _sqrt_match(r)
if not rval:
return None
ra, rb, rr = rval
if rb:
y = Dummy('y', positive=True)
try:
newa = Poly(a.subs(sqrt(rr), (y**2 - ra)/rb), y)
except PolynomialError:
return None
if newa.degree() == 2:
ca, cb, cc = newa.all_coeffs()
cb += b
if _mexpand(cb**2 - 4*ca*cc).equals(0):
z = sqrt(ca*(sqrt(r) + cb/(2*ca))**2)
if z.is_number:
z = _mexpand(Mul._from_args(z.as_content_primitive()))
return z
def _sqrt_numeric_denest(a, b, r, d2):
r"""Helper that denest
$\sqrt{a + b \sqrt{r}}, d^2 = a^2 - b^2 r > 0$
If it cannot be denested, it returns ``None``.
"""
d = sqrt(d2)
s = a + d
# sqrt_depth(res) <= sqrt_depth(s) + 1
# sqrt_depth(expr) = sqrt_depth(r) + 2
# there is denesting if sqrt_depth(s) + 1 < sqrt_depth(r) + 2
# if s**2 is Number there is a fourth root
if sqrt_depth(s) < sqrt_depth(r) + 1 or (s**2).is_Rational:
s1, s2 = sign(s), sign(b)
if s1 == s2 == -1:
s1 = s2 = 1
res = (s1 * sqrt(a + d) + s2 * sqrt(a - d)) * sqrt(2) / 2
return res.expand()
def sqrt_biquadratic_denest(expr, a, b, r, d2):
"""denest expr = sqrt(a + b*sqrt(r))
where a, b, r are linear combinations of square roots of
positive rationals on the rationals (SQRR) and r > 0, b != 0,
d2 = a**2 - b**2*r > 0
If it cannot denest it returns None.
ALGORITHM
Search for a solution A of type SQRR of the biquadratic equation
4*A**4 - 4*a*A**2 + b**2*r = 0 (1)
sqd = sqrt(a**2 - b**2*r)
Choosing the sqrt to be positive, the possible solutions are
A = sqrt(a/2 +/- sqd/2)
Since a, b, r are SQRR, then a**2 - b**2*r is a SQRR,
so if sqd can be denested, it is done by
_sqrtdenest_rec, and the result is a SQRR.
Similarly for A.
Examples of solutions (in both cases a and sqd are positive):
Example of expr with solution sqrt(a/2 + sqd/2) but not
solution sqrt(a/2 - sqd/2):
expr = sqrt(-sqrt(15) - sqrt(2)*sqrt(-sqrt(5) + 5) - sqrt(3) + 8)
a = -sqrt(15) - sqrt(3) + 8; sqd = -2*sqrt(5) - 2 + 4*sqrt(3)
Example of expr with solution sqrt(a/2 - sqd/2) but not
solution sqrt(a/2 + sqd/2):
w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3)
expr = sqrt((w**2).expand())
a = 4*sqrt(6) + 8*sqrt(2) + 47 + 28*sqrt(3)
sqd = 29 + 20*sqrt(3)
Define B = b/2*A; eq.(1) implies a = A**2 + B**2*r; then
expr**2 = a + b*sqrt(r) = (A + B*sqrt(r))**2
Examples
========
>>> from sympy import sqrt
>>> from sympy.simplify.sqrtdenest import _sqrt_match, sqrt_biquadratic_denest
>>> z = sqrt((2*sqrt(2) + 4)*sqrt(2 + sqrt(2)) + 5*sqrt(2) + 8)
>>> a, b, r = _sqrt_match(z**2)
>>> d2 = a**2 - b**2*r
>>> sqrt_biquadratic_denest(z, a, b, r, d2)
sqrt(2) + sqrt(sqrt(2) + 2) + 2
"""
from sympy.simplify.radsimp import radsimp, rad_rationalize
if r <= 0 or d2 < 0 or not b or sqrt_depth(expr.base) < 2:
return None
for x in (a, b, r):
for y in x.args:
y2 = y**2
if not y2.is_Integer or not y2.is_positive:
return None
sqd = _mexpand(sqrtdenest(sqrt(radsimp(d2))))
if sqrt_depth(sqd) > 1:
return None
x1, x2 = [a/2 + sqd/2, a/2 - sqd/2]
# look for a solution A with depth 1
for x in (x1, x2):
A = sqrtdenest(sqrt(x))
if sqrt_depth(A) > 1:
continue
Bn, Bd = rad_rationalize(b, _mexpand(2*A))
B = Bn/Bd
z = A + B*sqrt(r)
if z < 0:
z = -z
return _mexpand(z)
return None
def _denester(nested, av0, h, max_depth_level):
"""Denests a list of expressions that contain nested square roots.
Algorithm based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>.
It is assumed that all of the elements of 'nested' share the same
bottom-level radicand. (This is stated in the paper, on page 177, in
the paragraph immediately preceding the algorithm.)
When evaluating all of the arguments in parallel, the bottom-level
radicand only needs to be denested once. This means that calling
_denester with x arguments results in a recursive invocation with x+1
arguments; hence _denester has polynomial complexity.
However, if the arguments were evaluated separately, each call would
result in two recursive invocations, and the algorithm would have
exponential complexity.
This is discussed in the paper in the middle paragraph of page 179.
"""
from sympy.simplify.simplify import radsimp
if h > max_depth_level:
return None, None
if av0[1] is None:
return None, None
if (av0[0] is None and
all(n.is_Number for n in nested)): # no arguments are nested
for f in _subsets(len(nested)): # test subset 'f' of nested
p = _mexpand(Mul(*[nested[i] for i in range(len(f)) if f[i]]))
if f.count(1) > 1 and f[-1]:
p = -p
sqp = sqrt(p)
if sqp.is_Rational:
return sqp, f # got a perfect square so return its square root.
# Otherwise, return the radicand from the previous invocation.
return sqrt(nested[-1]), [0]*len(nested)
else:
R = None
if av0[0] is not None:
values = [av0[:2]]
R = av0[2]
nested2 = [av0[3], R]
av0[0] = None
else:
values = list(filter(None, [_sqrt_match(expr) for expr in nested]))
for v in values:
if v[2]: # Since if b=0, r is not defined
if R is not None:
if R != v[2]:
av0[1] = None
return None, None
else:
R = v[2]
if R is None:
# return the radicand from the previous invocation
return sqrt(nested[-1]), [0]*len(nested)
nested2 = [_mexpand(v[0]**2) -
_mexpand(R*v[1]**2) for v in values] + [R]
d, f = _denester(nested2, av0, h + 1, max_depth_level)
if not f:
return None, None
if not any(f[i] for i in range(len(nested))):
v = values[-1]
return sqrt(v[0] + _mexpand(v[1]*d)), f
else:
p = Mul(*[nested[i] for i in range(len(nested)) if f[i]])
v = _sqrt_match(p)
if 1 in f and f.index(1) < len(nested) - 1 and f[len(nested) - 1]:
v[0] = -v[0]
v[1] = -v[1]
if not f[len(nested)]: # Solution denests with square roots
vad = _mexpand(v[0] + d)
if vad <= 0:
# return the radicand from the previous invocation.
return sqrt(nested[-1]), [0]*len(nested)
if not(sqrt_depth(vad) <= sqrt_depth(R) + 1 or
(vad**2).is_Number):
av0[1] = None
return None, None
sqvad = _sqrtdenest1(sqrt(vad), denester=False)
if not (sqrt_depth(sqvad) <= sqrt_depth(R) + 1):
av0[1] = None
return None, None
sqvad1 = radsimp(1/sqvad)
res = _mexpand(sqvad/sqrt(2) + (v[1]*sqrt(R)*sqvad1/sqrt(2)))
return res, f
# sign(v[1])*sqrt(_mexpand(v[1]**2*R*vad1/2))), f
else: # Solution requires a fourth root
s2 = _mexpand(v[1]*R) + d
if s2 <= 0:
return sqrt(nested[-1]), [0]*len(nested)
FR, s = root(_mexpand(R), 4), sqrt(s2)
return _mexpand(s/(sqrt(2)*FR) + v[0]*FR/(sqrt(2)*s)), f
def _sqrt_ratcomb(cs, args):
"""Denest rational combinations of radicals.
Based on section 5 of [1].
Examples
========
>>> from sympy import sqrt
>>> from sympy.simplify.sqrtdenest import sqrtdenest
>>> z = sqrt(1+sqrt(3)) + sqrt(3+3*sqrt(3)) - sqrt(10+6*sqrt(3))
>>> sqrtdenest(z)
0
"""
from sympy.simplify.radsimp import radsimp
# check if there exists a pair of sqrt that can be denested
def find(a):
n = len(a)
for i in range(n - 1):
for j in range(i + 1, n):
s1 = a[i].base
s2 = a[j].base
p = _mexpand(s1 * s2)
s = sqrtdenest(sqrt(p))
if s != sqrt(p):
return s, i, j
indices = find(args)
if indices is None:
return Add(*[c * arg for c, arg in zip(cs, args)])
s, i1, i2 = indices
c2 = cs.pop(i2)
args.pop(i2)
a1 = args[i1]
# replace a2 by s/a1
cs[i1] += radsimp(c2 * s / a1.base)
return _sqrt_ratcomb(cs, args)
|
ef34f4749e04b60f3562902026d72790384375b43e4cafa58b508f99ebe596bc | from typing import Any, Set
from itertools import permutations
from sympy.combinatorics import Permutation
from sympy.core import (
Basic, Expr, Function, diff,
Pow, Mul, Add, Atom, Lambda, S, Tuple, Dict
)
from sympy.core.cache import cacheit
from sympy.core.compatibility import reduce
from sympy.core.symbol import Symbol, Dummy
from sympy.core.symbol import Str
from sympy.core.sympify import _sympify
from sympy.functions import factorial
from sympy.matrices import ImmutableDenseMatrix as Matrix
from sympy.simplify import simplify
from sympy.solvers import solve
from sympy.utilities.exceptions import SymPyDeprecationWarning
# TODO you are a bit excessive in the use of Dummies
# TODO dummy point, literal field
# TODO too often one needs to call doit or simplify on the output, check the
# tests and find out why
from sympy.tensor.array import ImmutableDenseNDimArray
class Manifold(Atom):
"""A mathematical manifold.
Explanation
===========
A manifold is a topological space that locally resembles
Euclidean space near each point [1].
This class does not provide any means to study the topological
characteristics of the manifold that it represents, though.
Parameters
==========
name : str
The name of the manifold.
dim : int
The dimension of the manifold.
Examples
========
>>> from sympy.diffgeom import Manifold
>>> m = Manifold('M', 2)
>>> m
M
>>> m.dim
2
References
==========
.. [1] https://en.wikipedia.org/wiki/Manifold
"""
def __new__(cls, name, dim, **kwargs):
if not isinstance(name, Str):
name = Str(name)
dim = _sympify(dim)
obj = super().__new__(cls, name, dim)
obj.patches = _deprecated_list(
"Manifold.patches",
"external container for registry",
19321,
"1.7",
[]
)
return obj
@property
def name(self):
return self.args[0]
@property
def dim(self):
return self.args[1]
class Patch(Atom):
"""A patch on a manifold.
Explanation
===========
Coordinate patch, or patch in short, is a simply-connected open set around a point
in the manifold [1]. On a manifold one can have many patches that do not always
include the whole manifold. On these patches coordinate charts can be defined that
permit the parameterization of any point on the patch in terms of a tuple of
real numbers (the coordinates).
This class does not provide any means to study the topological
characteristics of the patch that it represents.
Parameters
==========
name : str
The name of the patch.
manifold : Manifold
The manifold on which the patch is defined.
Examples
========
>>> from sympy.diffgeom import Manifold, Patch
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> p
P
>>> p.dim
2
References
==========
.. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry (2013)
"""
def __new__(cls, name, manifold, **kwargs):
if not isinstance(name, Str):
name = Str(name)
obj = super().__new__(cls, name, manifold)
obj.manifold.patches.append(obj) # deprecated
obj.coord_systems = _deprecated_list(
"Patch.coord_systems",
"external container for registry",
19321,
"1.7",
[]
)
return obj
@property
def name(self):
return self.args[0]
@property
def manifold(self):
return self.args[1]
@property
def dim(self):
return self.manifold.dim
class CoordSystem(Atom):
"""A coordinate system defined on the patch.
Explanation
===========
Coordinate system is a system that uses one or more coordinates to uniquely determine
the position of the points or other geometric elements on a manifold [1].
By passing Symbols to *symbols* parameter, user can define the name and assumptions
of coordinate symbols of the coordinate system. If not passed, these symbols are
generated automatically and are assumed to be real valued.
By passing *relations* parameter, user can define the tranform relations of coordinate
systems. Inverse transformation and indirect transformation can be found automatically.
If this parameter is not passed, coordinate transformation cannot be done.
Parameters
==========
name : str
The name of the coordinate system.
patch : Patch
The patch where the coordinate system is defined.
symbols : list of Symbols, optional
Defines the names and assumptions of coordinate symbols.
relations : dict, optional
- key : tuple of two strings, who are the names of systems where
the coordinates transform from and transform to.
- value : Lambda returning the transformed coordinates.
Examples
========
>>> from sympy import symbols, pi, Lambda, Matrix, sqrt, atan2, cos, sin
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> x, y = symbols('x y', real=True)
>>> r, theta = symbols('r theta', nonnegative=True)
>>> relation_dict = {
... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])),
... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)]))
... }
>>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict)
>>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict)
>>> Car2D
Car2D
>>> Car2D.dim
2
>>> Car2D.symbols
[x, y]
>>> Car2D.transformation(Pol)
Lambda((x, y), Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]]))
>>> Car2D.transform(Pol)
Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]])
>>> Car2D.transform(Pol, [1, 2])
Matrix([
[sqrt(5)],
[atan(2)]])
>>> Pol.jacobian(Car2D)
Matrix([
[cos(theta), -r*sin(theta)],
[sin(theta), r*cos(theta)]])
>>> Pol.jacobian(Car2D, [1, pi/2])
Matrix([
[0, -1],
[1, 0]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Coordinate_system
"""
def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
if not isinstance(name, Str):
name = Str(name)
# canonicallize the symbols
if symbols is None:
names = kwargs.get('names', None)
if names is None:
symbols = Tuple(
*[Symbol('%s_%s' % (name.name, i), real=True) for i in range(patch.dim)]
)
else:
SymPyDeprecationWarning(
feature="Class signature 'names' of CoordSystem",
useinstead="class signature 'symbols'",
issue=19321,
deprecated_since_version="1.7"
).warn()
symbols = Tuple(
*[Symbol(n, real=True) for n in names]
)
else:
syms = []
for s in symbols:
if isinstance(s, Symbol):
syms.append(Symbol(s.name, **s._assumptions.generator))
elif isinstance(s, str):
SymPyDeprecationWarning(
feature="Passing str as coordinate symbol's name",
useinstead="Symbol which contains the name and assumption for coordinate symbol",
issue=19321,
deprecated_since_version="1.7"
).warn()
syms.append(Symbol(s, real=True))
symbols = Tuple(*syms)
# canonicallize the relations
rel_temp = {}
for k,v in relations.items():
s1, s2 = k
if not isinstance(s1, Str):
s1 = Str(s1)
if not isinstance(s2, Str):
s2 = Str(s2)
key = Tuple(s1, s2)
rel_temp[key] = v
relations = Dict(rel_temp)
# construct the object
obj = super().__new__(cls, name, patch, symbols, relations)
# Add deprecated attributes
obj.transforms = _deprecated_dict(
"Mutable CoordSystem.transforms",
"'relations' parameter in class signature",
19321,
"1.7",
{}
)
obj._names = [str(n) for n in symbols]
obj.patch.coord_systems.append(obj) # deprecated
obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated
obj._dummy = Dummy()
return obj
@property
def name(self):
return self.args[0]
@property
def patch(self):
return self.args[1]
@property
def manifold(self):
return self.patch.manifold
@property
def symbols(self):
return [
CoordinateSymbol(
self, i, **s._assumptions.generator
) for i,s in enumerate(self.args[2])
]
@property
def relations(self):
return self.args[3]
@property
def dim(self):
return self.patch.dim
##########################################################################
# Finding transformation relation
##########################################################################
def transformation(self, sys):
"""
Return coordinate transform relation from *self* to *sys* as Lambda.
"""
if self.relations != sys.relations:
raise TypeError(
"Two coordinate systems have different relations")
key = Tuple(self.name, sys.name)
if key in self.relations:
return self.relations[key]
elif key[::-1] in self.relations:
return self._inverse_transformation(sys, self)
else:
return self._indirect_transformation(self, sys)
@staticmethod
def _inverse_transformation(sys1, sys2):
# Find the transformation relation from sys2 to sys1
forward_transform = sys1.transform(sys2)
forward_syms, forward_results = forward_transform.args
inv_syms = [i.as_dummy() for i in forward_syms]
inv_results = solve(
[t[0] - t[1] for t in zip(inv_syms, forward_results)],
list(forward_syms), dict=True)[0]
inv_results = [inv_results[s] for s in forward_syms]
signature = tuple(inv_syms)
expr = Matrix(inv_results)
return Lambda(signature, expr)
@classmethod
@cacheit
def _indirect_transformation(cls, sys1, sys2):
# Find the transformation relation between two indirectly connected coordinate systems
path = cls._dijkstra(sys1, sys2)
Lambdas = []
for i in range(len(path) - 1):
s1, s2 = path[i], path[i + 1]
Lambdas.append(s1.transformation(s2))
syms = Lambdas[-1].signature
expr = syms
for l in reversed(Lambdas):
expr = l(*expr)
return Lambda(syms, expr)
@staticmethod
def _dijkstra(sys1, sys2):
# Use Dijkstra algorithm to find the shortest path between two indirectly-connected
# coordinate systems
relations = sys1.relations
graph = {}
for s1, s2 in relations.keys():
if s1 not in graph:
graph[s1] = {s2}
else:
graph[s1].add(s2)
if s2 not in graph:
graph[s2] = {s1}
else:
graph[s2].add(s1)
path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited
def visit(sys):
path_dict[sys][2] = 1
for newsys in graph[sys]:
distance = path_dict[sys][0] + 1
if path_dict[newsys][0] >= distance or not path_dict[newsys][1]:
path_dict[newsys][0] = distance
path_dict[newsys][1] = [i for i in path_dict[sys][1]]
path_dict[newsys][1].append(sys)
visit(sys1)
while True:
min_distance = max(path_dict.values(), key=lambda x:x[0])[0]
newsys = None
for sys, lst in path_dict.items():
if 0 < lst[0] <= min_distance and not lst[2]:
min_distance = lst[0]
newsys = sys
if newsys is None:
break
visit(newsys)
result = path_dict[sys2][1]
result.append(sys2)
if result == [sys2]:
raise KeyError("Two coordinate systems are not connected.")
return result
def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False):
SymPyDeprecationWarning(
feature="CoordSystem.connect_to",
useinstead="new instance generated with new 'transforms' parameter",
issue=19321,
deprecated_since_version="1.7"
).warn()
from_coords, to_exprs = dummyfy(from_coords, to_exprs)
self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
if inverse:
to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
if fill_in_gaps:
self._fill_gaps_in_transformations()
@staticmethod
def _inv_transf(from_coords, to_exprs):
# Will be removed when connect_to is removed
inv_from = [i.as_dummy() for i in from_coords]
inv_to = solve(
[t[0] - t[1] for t in zip(inv_from, to_exprs)],
list(from_coords), dict=True)[0]
inv_to = [inv_to[fc] for fc in from_coords]
return Matrix(inv_from), Matrix(inv_to)
@staticmethod
def _fill_gaps_in_transformations():
# Will be removed when connect_to is removed
raise NotImplementedError
##########################################################################
# Coordinate transformations
##########################################################################
def transform(self, sys, coordinates=None):
"""
Return the result of coordinate transformation from *self* to *sys*.
If coordinates are not given, coordinate symbols of *self* are used.
"""
if coordinates is None:
coordinates = Matrix(self.symbols)
else:
coordinates = Matrix(coordinates)
if self != sys:
transf = self.transformation(sys)
coordinates = transf(*coordinates)
return coordinates
def coord_tuple_transform_to(self, to_sys, coords):
"""Transform ``coords`` to coord system ``to_sys``."""
SymPyDeprecationWarning(
feature="CoordSystem.coord_tuple_transform_to",
useinstead="CoordSystem.transform",
issue=19321,
deprecated_since_version="1.7"
).warn()
coords = Matrix(coords)
if self != to_sys:
transf = self.transforms[to_sys]
coords = transf[1].subs(list(zip(transf[0], coords)))
return coords
def jacobian(self, sys, coordinates=None):
"""
Return the jacobian matrix of a transformation.
"""
result = self.transform(sys).jacobian(self.symbols)
if coordinates is not None:
result = result.subs(list(zip(self.symbols, coordinates)))
return result
jacobian_matrix = jacobian
def jacobian_determinant(self, sys, coordinates=None):
"""Return the jacobian determinant of a transformation."""
return self.jacobian(sys, coordinates).det()
##########################################################################
# Points
##########################################################################
def point(self, coords):
"""Create a ``Point`` with coordinates given in this coord system."""
return Point(self, coords)
def point_to_coords(self, point):
"""Calculate the coordinates of a point in this coord system."""
return point.coords(self)
##########################################################################
# Base fields.
##########################################################################
def base_scalar(self, coord_index):
"""Return ``BaseScalarField`` that takes a point and returns one of the coordinates."""
return BaseScalarField(self, coord_index)
coord_function = base_scalar
def base_scalars(self):
"""Returns a list of all coordinate functions.
For more details see the ``base_scalar`` method of this class."""
return [self.base_scalar(i) for i in range(self.dim)]
coord_functions = base_scalars
def base_vector(self, coord_index):
"""Return a basis vector field.
The basis vector field for this coordinate system. It is also an
operator on scalar fields."""
return BaseVectorField(self, coord_index)
def base_vectors(self):
"""Returns a list of all base vectors.
For more details see the ``base_vector`` method of this class."""
return [self.base_vector(i) for i in range(self.dim)]
def base_oneform(self, coord_index):
"""Return a basis 1-form field.
The basis one-form field for this coordinate system. It is also an
operator on vector fields."""
return Differential(self.coord_function(coord_index))
def base_oneforms(self):
"""Returns a list of all base oneforms.
For more details see the ``base_oneform`` method of this class."""
return [self.base_oneform(i) for i in range(self.dim)]
class CoordinateSymbol(Symbol):
"""A symbol which denotes an abstract value of i-th coordinate of
the coordinate system with given context.
Explanation
===========
Each coordinates in coordinate system are represented by unique symbol,
such as x, y, z in Cartesian coordinate system.
You may not construct this class directly. Instead, use `symbols` method
of CoordSystem.
Parameters
==========
coord_sys : CoordSystem
index : integer
Examples
========
>>> from sympy import symbols
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> _x, _y = symbols('x y', nonnegative=True)
>>> C = CoordSystem('C', p, [_x, _y])
>>> x, y = C.symbols
>>> x.name
'x'
>>> x.coord_sys == C
True
>>> x.index
0
>>> x.is_nonnegative
True
"""
def __new__(cls, coord_sys, index, **assumptions):
name = coord_sys.args[2][index].name
obj = super().__new__(cls, name, **assumptions)
obj.coord_sys = coord_sys
obj.index = index
return obj
def __getnewargs__(self):
return (self.coord_sys, self.index)
def _hashable_content(self):
return (
self.coord_sys, self.index
) + tuple(sorted(self.assumptions0.items()))
class Point(Basic):
"""Point defined in a coordinate system.
Explanation
===========
Mathematically, point is defined in the manifold and does not have any coordinates
by itself. Coordinate system is what imbues the coordinates to the point by coordinate
chart. However, due to the difficulty of realizing such logic, you must supply
a coordinate system and coordinates to define a Point here.
The usage of this object after its definition is independent of the
coordinate system that was used in order to define it, however due to
limitations in the simplification routines you can arrive at complicated
expressions if you use inappropriate coordinate systems.
Parameters
==========
coord_sys : CoordSystem
coords : list
The coordinates of the point.
Examples
========
>>> from sympy import pi
>>> from sympy.diffgeom import Point
>>> from sympy.diffgeom.rn import R2, R2_r, R2_p
>>> rho, theta = R2_p.symbols
>>> p = Point(R2_p, [rho, 3*pi/4])
>>> p.manifold == R2
True
>>> p.coords()
Matrix([
[ rho],
[3*pi/4]])
>>> p.coords(R2_r)
Matrix([
[-sqrt(2)*rho/2],
[ sqrt(2)*rho/2]])
"""
def __new__(cls, coord_sys, coords, **kwargs):
coords = Matrix(coords)
obj = super().__new__(cls, coord_sys, coords)
obj._coord_sys = coord_sys
obj._coords = coords
return obj
@property
def patch(self):
return self._coord_sys.patch
@property
def manifold(self):
return self._coord_sys.manifold
@property
def dim(self):
return self.manifold.dim
def coords(self, sys=None):
"""
Coordinates of the point in given coordinate system. If coordinate system
is not passed, it returns the coordinates in the coordinate system in which
the poin was defined.
"""
if sys is None:
return self._coords
else:
return self._coord_sys.transform(sys, self._coords)
@property
def free_symbols(self):
return self._coords.free_symbols
class BaseScalarField(Expr):
"""Base scalar field over a manifold for a given coordinate system.
Explanation
===========
A scalar field takes a point as an argument and returns a scalar.
A base scalar field of a coordinate system takes a point and returns one of
the coordinates of that point in the coordinate system in question.
To define a scalar field you need to choose the coordinate system and the
index of the coordinate.
The use of the scalar field after its definition is independent of the
coordinate system in which it was defined, however due to limitations in
the simplification routines you may arrive at more complicated
expression if you use unappropriate coordinate systems.
You can build complicated scalar fields by just building up SymPy
expressions containing ``BaseScalarField`` instances.
Parameters
==========
coord_sys : CoordSystem
index : integer
Examples
========
>>> from sympy import Function, pi
>>> from sympy.diffgeom import BaseScalarField
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> rho, _ = R2_p.symbols
>>> point = R2_p.point([rho, 0])
>>> fx, fy = R2_r.base_scalars()
>>> ftheta = BaseScalarField(R2_r, 1)
>>> fx(point)
rho
>>> fy(point)
0
>>> (fx**2+fy**2).rcall(point)
rho**2
>>> g = Function('g')
>>> fg = g(ftheta-pi)
>>> fg.rcall(point)
g(-pi)
"""
is_commutative = True
def __new__(cls, coord_sys, index, **kwargs):
index = _sympify(index)
obj = super().__new__(cls, coord_sys, index)
obj._coord_sys = coord_sys
obj._index = index
return obj
@property
def coord_sys(self):
return self.args[0]
@property
def index(self):
return self.args[1]
@property
def patch(self):
return self.coord_sys.patch
@property
def manifold(self):
return self.coord_sys.manifold
@property
def dim(self):
return self.manifold.dim
def __call__(self, *args):
"""Evaluating the field at a point or doing nothing.
If the argument is a ``Point`` instance, the field is evaluated at that
point. The field is returned itself if the argument is any other
object. It is so in order to have working recursive calling mechanics
for all fields (check the ``__call__`` method of ``Expr``).
"""
point = args[0]
if len(args) != 1 or not isinstance(point, Point):
return self
coords = point.coords(self._coord_sys)
# XXX Calling doit is necessary with all the Subs expressions
# XXX Calling simplify is necessary with all the trig expressions
return simplify(coords[self._index]).doit()
# XXX Workaround for limitations on the content of args
free_symbols = set() # type: Set[Any]
def doit(self):
return self
class BaseVectorField(Expr):
r"""Base vector field over a manifold for a given coordinate system.
Explanation
===========
A vector field is an operator taking a scalar field and returning a
directional derivative (which is also a scalar field).
A base vector field is the same type of operator, however the derivation is
specifically done with respect to a chosen coordinate.
To define a base vector field you need to choose the coordinate system and
the index of the coordinate.
The use of the vector field after its definition is independent of the
coordinate system in which it was defined, however due to limitations in the
simplification routines you may arrive at more complicated expression if you
use unappropriate coordinate systems.
Parameters
==========
coord_sys : CoordSystem
index : integer
Examples
========
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2_p, R2_r
>>> from sympy.diffgeom import BaseVectorField
>>> from sympy import pprint
>>> x, y = R2_r.symbols
>>> rho, theta = R2_p.symbols
>>> fx, fy = R2_r.base_scalars()
>>> point_p = R2_p.point([rho, theta])
>>> point_r = R2_r.point([x, y])
>>> g = Function('g')
>>> s_field = g(fx, fy)
>>> v = BaseVectorField(R2_r, 1)
>>> pprint(v(s_field))
/ d \|
|---(g(x, xi))||
\dxi /|xi=y
>>> pprint(v(s_field).rcall(point_r).doit())
d
--(g(x, y))
dy
>>> pprint(v(s_field).rcall(point_p))
/ d \|
|---(g(rho*cos(theta), xi))||
\dxi /|xi=rho*sin(theta)
"""
is_commutative = False
def __new__(cls, coord_sys, index, **kwargs):
index = _sympify(index)
obj = super().__new__(cls, coord_sys, index)
obj._coord_sys = coord_sys
obj._index = index
return obj
@property
def coord_sys(self):
return self.args[0]
@property
def index(self):
return self.args[1]
@property
def patch(self):
return self.coord_sys.patch
@property
def manifold(self):
return self.coord_sys.manifold
@property
def dim(self):
return self.manifold.dim
def __call__(self, scalar_field):
"""Apply on a scalar field.
The action of a vector field on a scalar field is a directional
differentiation.
If the argument is not a scalar field an error is raised.
"""
if covariant_order(scalar_field) or contravariant_order(scalar_field):
raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
if scalar_field is None:
return self
base_scalars = list(scalar_field.atoms(BaseScalarField))
# First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)
d_var = self._coord_sys._dummy
# TODO: you need a real dummy function for the next line
d_funcs = [Function('_#_%s' % i)(d_var) for i,
b in enumerate(base_scalars)]
d_result = scalar_field.subs(list(zip(base_scalars, d_funcs)))
d_result = d_result.diff(d_var)
# Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y))
coords = self._coord_sys.symbols
d_funcs_deriv = [f.diff(d_var) for f in d_funcs]
d_funcs_deriv_sub = []
for b in base_scalars:
jac = self._coord_sys.jacobian(b._coord_sys, coords)
d_funcs_deriv_sub.append(jac[b._index, self._index])
d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
# Remove the dummies
result = d_result.subs(list(zip(d_funcs, base_scalars)))
result = result.subs(list(zip(coords, self._coord_sys.coord_functions())))
return result.doit()
def _find_coords(expr):
# Finds CoordinateSystems existing in expr
fields = expr.atoms(BaseScalarField, BaseVectorField)
result = set()
for f in fields:
result.add(f._coord_sys)
return result
class Commutator(Expr):
r"""Commutator of two vector fields.
Explanation
===========
The commutator of two vector fields `v_1` and `v_2` is defined as the
vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal
to `v_1(v_2(f)) - v_2(v_1(f))`.
Examples
========
>>> from sympy.diffgeom.rn import R2_p, R2_r
>>> from sympy.diffgeom import Commutator
>>> from sympy.simplify import simplify
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> e_r = R2_p.base_vector(0)
>>> c_xy = Commutator(e_x, e_y)
>>> c_xr = Commutator(e_x, e_r)
>>> c_xy
0
Unfortunately, the current code is not able to compute everything:
>>> c_xr
Commutator(e_x, e_rho)
>>> simplify(c_xr(fy**2))
-2*cos(theta)*y**2/(x**2 + y**2)
"""
def __new__(cls, v1, v2):
if (covariant_order(v1) or contravariant_order(v1) != 1
or covariant_order(v2) or contravariant_order(v2) != 1):
raise ValueError(
'Only commutators of vector fields are supported.')
if v1 == v2:
return S.Zero
coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)])
if len(coord_sys) == 1:
# Only one coordinate systems is used, hence it is easy enough to
# actually evaluate the commutator.
if all(isinstance(v, BaseVectorField) for v in (v1, v2)):
return S.Zero
bases_1, bases_2 = [list(v.atoms(BaseVectorField))
for v in (v1, v2)]
coeffs_1 = [v1.expand().coeff(b) for b in bases_1]
coeffs_2 = [v2.expand().coeff(b) for b in bases_2]
res = 0
for c1, b1 in zip(coeffs_1, bases_1):
for c2, b2 in zip(coeffs_2, bases_2):
res += c1*b1(c2)*b2 - c2*b2(c1)*b1
return res
else:
obj = super().__new__(cls, v1, v2)
obj._v1 = v1 # deprecated assignment
obj._v2 = v2 # deprecated assignment
return obj
@property
def v1(self):
return self.args[0]
@property
def v2(self):
return self.args[1]
def __call__(self, scalar_field):
"""Apply on a scalar field.
If the argument is not a scalar field an error is raised.
"""
return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field))
class Differential(Expr):
r"""Return the differential (exterior derivative) of a form field.
Explanation
===========
The differential of a form (i.e. the exterior derivative) has a complicated
definition in the general case.
The differential `df` of the 0-form `f` is defined for any vector field `v`
as `df(v) = v(f)`.
Examples
========
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import Differential
>>> from sympy import pprint
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> g = Function('g')
>>> s_field = g(fx, fy)
>>> dg = Differential(s_field)
>>> dg
d(g(x, y))
>>> pprint(dg(e_x))
/ d \|
|---(g(xi, y))||
\dxi /|xi=x
>>> pprint(dg(e_y))
/ d \|
|---(g(x, xi))||
\dxi /|xi=y
Applying the exterior derivative operator twice always results in:
>>> Differential(dg)
0
"""
is_commutative = False
def __new__(cls, form_field):
if contravariant_order(form_field):
raise ValueError(
'A vector field was supplied as an argument to Differential.')
if isinstance(form_field, Differential):
return S.Zero
else:
obj = super().__new__(cls, form_field)
obj._form_field = form_field # deprecated assignment
return obj
@property
def form_field(self):
return self.args[0]
def __call__(self, *vector_fields):
"""Apply on a list of vector_fields.
Explanation
===========
If the number of vector fields supplied is not equal to 1 + the order of
the form field inside the differential the result is undefined.
For 1-forms (i.e. differentials of scalar fields) the evaluation is
done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector
field, the differential is returned unchanged. This is done in order to
permit partial contractions for higher forms.
In the general case the evaluation is done by applying the form field
inside the differential on a list with one less elements than the number
of elements in the original list. Lowering the number of vector fields
is achieved through replacing each pair of fields by their
commutator.
If the arguments are not vectors or ``None``s an error is raised.
"""
if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None
for a in vector_fields):
raise ValueError('The arguments supplied to Differential should be vector fields or Nones.')
k = len(vector_fields)
if k == 1:
if vector_fields[0]:
return vector_fields[0].rcall(self._form_field)
return self
else:
# For higher form it is more complicated:
# Invariant formula:
# https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula
# df(v1, ... vn) = +/- vi(f(v1..no i..vn))
# +/- f([vi,vj],v1..no i, no j..vn)
f = self._form_field
v = vector_fields
ret = 0
for i in range(k):
t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:]))
ret += (-1)**i*t
for j in range(i + 1, k):
c = Commutator(v[i], v[j])
if c: # TODO this is ugly - the Commutator can be Zero and
# this causes the next line to fail
t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:])
ret += (-1)**(i + j)*t
return ret
class TensorProduct(Expr):
"""Tensor product of forms.
Explanation
===========
The tensor product permits the creation of multilinear functionals (i.e.
higher order tensors) out of lower order fields (e.g. 1-forms and vector
fields). However, the higher tensors thus created lack the interesting
features provided by the other type of product, the wedge product, namely
they are not antisymmetric and hence are not form fields.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import TensorProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> TensorProduct(dx, dy)(e_x, e_y)
1
>>> TensorProduct(dx, dy)(e_y, e_x)
0
>>> TensorProduct(dx, fx*dy)(fx*e_x, e_y)
x**2
>>> TensorProduct(e_x, e_y)(fx**2, fy**2)
4*x*y
>>> TensorProduct(e_y, dx)(fy)
dx
You can nest tensor products.
>>> tp1 = TensorProduct(dx, dy)
>>> TensorProduct(tp1, dx)(e_x, e_y, e_x)
1
You can make partial contraction for instance when 'raising an index'.
Putting ``None`` in the second argument of ``rcall`` means that the
respective position in the tensor product is left as it is.
>>> TP = TensorProduct
>>> metric = TP(dx, dx) + 3*TP(dy, dy)
>>> metric.rcall(e_y, None)
3*dy
Or automatically pad the args with ``None`` without specifying them.
>>> metric.rcall(e_y)
3*dy
"""
def __new__(cls, *args):
scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])
multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]
if multifields:
if len(multifields) == 1:
return scalar*multifields[0]
return scalar*super().__new__(cls, *multifields)
else:
return scalar
def __call__(self, *fields):
"""Apply on a list of fields.
If the number of input fields supplied is not equal to the order of
the tensor product field, the list of arguments is padded with ``None``'s.
The list of arguments is divided in sublists depending on the order of
the forms inside the tensor product. The sublists are provided as
arguments to these forms and the resulting expressions are given to the
constructor of ``TensorProduct``.
"""
tot_order = covariant_order(self) + contravariant_order(self)
tot_args = len(fields)
if tot_args != tot_order:
fields = list(fields) + [None]*(tot_order - tot_args)
orders = [covariant_order(f) + contravariant_order(f) for f in self._args]
indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]
fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]
multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]
return TensorProduct(*multipliers)
class WedgeProduct(TensorProduct):
"""Wedge product of forms.
Explanation
===========
In the context of integration only completely antisymmetric forms make
sense. The wedge product permits the creation of such forms.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import WedgeProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> WedgeProduct(dx, dy)(e_x, e_y)
1
>>> WedgeProduct(dx, dy)(e_y, e_x)
-1
>>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y)
x**2
>>> WedgeProduct(e_x, e_y)(fy, None)
-e_x
You can nest wedge products.
>>> wp1 = WedgeProduct(dx, dy)
>>> WedgeProduct(wp1, dx)(e_x, e_y, e_x)
0
"""
# TODO the calculation of signatures is slow
# TODO you do not need all these permutations (neither the prefactor)
def __call__(self, *fields):
"""Apply on a list of vector_fields.
The expression is rewritten internally in terms of tensor products and evaluated."""
orders = (covariant_order(e) + contravariant_order(e) for e in self.args)
mul = 1/Mul(*(factorial(o) for o in orders))
perms = permutations(fields)
perms_par = (Permutation(
p).signature() for p in permutations(list(range(len(fields)))))
tensor_prod = TensorProduct(*self.args)
return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
class LieDerivative(Expr):
"""Lie derivative with respect to a vector field.
Explanation
===========
The transport operator that defines the Lie derivative is the pushforward of
the field to be derived along the integral curve of the field with respect
to which one derives.
Examples
========
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> from sympy.diffgeom import (LieDerivative, TensorProduct)
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> e_rho, e_theta = R2_p.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> LieDerivative(e_x, fy)
0
>>> LieDerivative(e_x, fx)
1
>>> LieDerivative(e_x, e_x)
0
The Lie derivative of a tensor field by another tensor field is equal to
their commutator:
>>> LieDerivative(e_x, e_rho)
Commutator(e_x, e_rho)
>>> LieDerivative(e_x + e_y, fx)
1
>>> tp = TensorProduct(dx, dy)
>>> LieDerivative(e_x, tp)
LieDerivative(e_x, TensorProduct(dx, dy))
>>> LieDerivative(e_x, tp)
LieDerivative(e_x, TensorProduct(dx, dy))
"""
def __new__(cls, v_field, expr):
expr_form_ord = covariant_order(expr)
if contravariant_order(v_field) != 1 or covariant_order(v_field):
raise ValueError('Lie derivatives are defined only with respect to'
' vector fields. The supplied argument was not a '
'vector field.')
if expr_form_ord > 0:
obj = super().__new__(cls, v_field, expr)
# deprecated assignments
obj._v_field = v_field
obj._expr = expr
return obj
if expr.atoms(BaseVectorField):
return Commutator(v_field, expr)
else:
return v_field.rcall(expr)
@property
def v_field(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
def __call__(self, *args):
v = self.v_field
expr = self.expr
lead_term = v(expr(*args))
rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:])
for i in range(len(args))])
return lead_term - rest
class BaseCovarDerivativeOp(Expr):
"""Covariant derivative operator with respect to a base vector.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import BaseCovarDerivativeOp
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
>>> ch
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
>>> cvd(fx)
1
>>> cvd(fx*e_x)
e_x
"""
def __new__(cls, coord_sys, index, christoffel):
index = _sympify(index)
christoffel = ImmutableDenseNDimArray(christoffel)
obj = super().__new__(cls, coord_sys, index, christoffel)
# deprecated assignments
obj._coord_sys = coord_sys
obj._index = index
obj._christoffel = christoffel
return obj
@property
def coord_sys(self):
return self.args[0]
@property
def index(self):
return self.args[1]
@property
def christoffel(self):
return self.args[2]
def __call__(self, field):
"""Apply on a scalar field.
The action of a vector field on a scalar field is a directional
differentiation.
If the argument is not a scalar field the behaviour is undefined.
"""
if covariant_order(field) != 0:
raise NotImplementedError()
field = vectors_in_basis(field, self._coord_sys)
wrt_vector = self._coord_sys.base_vector(self._index)
wrt_scalar = self._coord_sys.coord_function(self._index)
vectors = list(field.atoms(BaseVectorField))
# First step: replace all vectors with something susceptible to
# derivation and do the derivation
# TODO: you need a real dummy function for the next line
d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i,
b in enumerate(vectors)]
d_result = field.subs(list(zip(vectors, d_funcs)))
d_result = wrt_vector(d_result)
# Second step: backsubstitute the vectors in
d_result = d_result.subs(list(zip(d_funcs, vectors)))
# Third step: evaluate the derivatives of the vectors
derivs = []
for v in vectors:
d = Add(*[(self._christoffel[k, wrt_vector._index, v._index]
*v._coord_sys.base_vector(k))
for k in range(v._coord_sys.dim)])
derivs.append(d)
to_subs = [wrt_vector(d) for d in d_funcs]
# XXX: This substitution can fail when there are Dummy symbols and the
# cache is disabled: https://github.com/sympy/sympy/issues/17794
result = d_result.subs(list(zip(to_subs, derivs)))
# Remove the dummies
result = result.subs(list(zip(d_funcs, vectors)))
return result.doit()
class CovarDerivativeOp(Expr):
"""Covariant derivative operator.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import CovarDerivativeOp
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
>>> ch
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> cvd = CovarDerivativeOp(fx*e_x, ch)
>>> cvd(fx)
x
>>> cvd(fx*e_x)
x*e_x
"""
def __new__(cls, wrt, christoffel):
if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1:
raise NotImplementedError()
if contravariant_order(wrt) != 1 or covariant_order(wrt):
raise ValueError('Covariant derivatives are defined only with '
'respect to vector fields. The supplied argument '
'was not a vector field.')
obj = super().__new__(cls, wrt, christoffel)
# deprecated assigments
obj._wrt = wrt
obj._christoffel = christoffel
return obj
@property
def wrt(self):
return self.args[0]
@property
def christoffel(self):
return self.args[1]
def __call__(self, field):
vectors = list(self._wrt.atoms(BaseVectorField))
base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel)
for v in vectors]
return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
###############################################################################
# Integral curves on vector fields
###############################################################################
def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False):
r"""Return the series expansion for an integral curve of the field.
Explanation
===========
Integral curve is a function `\gamma` taking a parameter in `R` to a point
in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any
value `t` for the parameter and any scalar field `f`.
This equation can also be decomposed of a basis of coordinate functions
`V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
This function returns a series expansion of `\gamma(t)` in terms of the
coordinate system ``coord_sys``. The equations and expansions are necessarily
done in coordinate-system-dependent way as there is no other way to
represent movement between points on the manifold (i.e. there is no such
thing as a difference of points for a general manifold).
Parameters
==========
vector_field
the vector field for which an integral curve will be given
param
the argument of the function `\gamma` from R to the curve
start_point
the point which corresponds to `\gamma(0)`
n
the order to which to expand
coord_sys
the coordinate system in which to expand
coeffs (default False) - if True return a list of elements of the expansion
Examples
========
Use the predefined R2 manifold:
>>> from sympy.abc import t, x, y
>>> from sympy.diffgeom.rn import R2_p, R2_r
>>> from sympy.diffgeom import intcurve_series
Specify a starting point and a vector field:
>>> start_point = R2_r.point([x, y])
>>> vector_field = R2_r.e_x
Calculate the series:
>>> intcurve_series(vector_field, t, start_point, n=3)
Matrix([
[t + x],
[ y]])
Or get the elements of the expansion in a list:
>>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True)
>>> series[0]
Matrix([
[x],
[y]])
>>> series[1]
Matrix([
[t],
[0]])
>>> series[2]
Matrix([
[0],
[0]])
The series in the polar coordinate system:
>>> series = intcurve_series(vector_field, t, start_point,
... n=3, coord_sys=R2_p, coeffs=True)
>>> series[0]
Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]])
>>> series[1]
Matrix([
[t*x/sqrt(x**2 + y**2)],
[ -t*y/(x**2 + y**2)]])
>>> series[2]
Matrix([
[t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2],
[ t**2*x*y/(x**2 + y**2)**2]])
See Also
========
intcurve_diffequ
"""
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
raise ValueError('The supplied field was not a vector field.')
def iter_vfield(scalar_field, i):
"""Return ``vector_field`` called `i` times on ``scalar_field``."""
return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
def taylor_terms_per_coord(coord_function):
"""Return the series for one of the coordinates."""
return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i)
for i in range(n)]
coord_sys = coord_sys if coord_sys else start_point._coord_sys
coord_functions = coord_sys.coord_functions()
taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions]
if coeffs:
return [Matrix(t) for t in zip(*taylor_terms)]
else:
return Matrix([sum(c) for c in taylor_terms])
def intcurve_diffequ(vector_field, param, start_point, coord_sys=None):
r"""Return the differential equation for an integral curve of the field.
Explanation
===========
Integral curve is a function `\gamma` taking a parameter in `R` to a point
in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any
value `t` for the parameter and any scalar field `f`.
This function returns the differential equation of `\gamma(t)` in terms of the
coordinate system ``coord_sys``. The equations and expansions are necessarily
done in coordinate-system-dependent way as there is no other way to
represent movement between points on the manifold (i.e. there is no such
thing as a difference of points for a general manifold).
Parameters
==========
vector_field
the vector field for which an integral curve will be given
param
the argument of the function `\gamma` from R to the curve
start_point
the point which corresponds to `\gamma(0)`
coord_sys
the coordinate system in which to give the equations
Returns
=======
a tuple of (equations, initial conditions)
Examples
========
Use the predefined R2 manifold:
>>> from sympy.abc import t
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
>>> from sympy.diffgeom import intcurve_diffequ
Specify a starting point and a vector field:
>>> start_point = R2_r.point([0, 1])
>>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
Get the equation:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
>>> equations
[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]
>>> init_cond
[f_0(0), f_1(0) - 1]
The series in the polar coordinate system:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
>>> equations
[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]
>>> init_cond
[f_0(0) - 1, f_1(0) - pi/2]
See Also
========
intcurve_series
"""
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
raise ValueError('The supplied field was not a vector field.')
coord_sys = coord_sys if coord_sys else start_point._coord_sys
gammas = [Function('f_%d' % i)(param) for i in range(
start_point._coord_sys.dim)]
arbitrary_p = Point(coord_sys, gammas)
coord_functions = coord_sys.coord_functions()
equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p))
for cf in coord_functions]
init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point))
for cf in coord_functions]
return equations, init_cond
###############################################################################
# Helpers
###############################################################################
def dummyfy(args, exprs):
# TODO Is this a good idea?
d_args = Matrix([s.as_dummy() for s in args])
reps = dict(zip(args, d_args))
d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs])
return d_args, d_exprs
###############################################################################
# Helpers
###############################################################################
def contravariant_order(expr, _strict=False):
"""Return the contravariant order of an expression.
Examples
========
>>> from sympy.diffgeom import contravariant_order
>>> from sympy.diffgeom.rn import R2
>>> from sympy.abc import a
>>> contravariant_order(a)
0
>>> contravariant_order(a*R2.x + 2)
0
>>> contravariant_order(a*R2.x*R2.e_y + R2.e_x)
1
"""
# TODO move some of this to class methods.
# TODO rewrite using the .as_blah_blah methods
if isinstance(expr, Add):
orders = [contravariant_order(e) for e in expr.args]
if len(set(orders)) != 1:
raise ValueError('Misformed expression containing contravariant fields of varying order.')
return orders[0]
elif isinstance(expr, Mul):
orders = [contravariant_order(e) for e in expr.args]
not_zero = [o for o in orders if o != 0]
if len(not_zero) > 1:
raise ValueError('Misformed expression containing multiplication between vectors.')
return 0 if not not_zero else not_zero[0]
elif isinstance(expr, Pow):
if covariant_order(expr.base) or covariant_order(expr.exp):
raise ValueError(
'Misformed expression containing a power of a vector.')
return 0
elif isinstance(expr, BaseVectorField):
return 1
elif isinstance(expr, TensorProduct):
return sum(contravariant_order(a) for a in expr.args)
elif not _strict or expr.atoms(BaseScalarField):
return 0
else: # If it does not contain anything related to the diffgeom module and it is _strict
return -1
def covariant_order(expr, _strict=False):
"""Return the covariant order of an expression.
Examples
========
>>> from sympy.diffgeom import covariant_order
>>> from sympy.diffgeom.rn import R2
>>> from sympy.abc import a
>>> covariant_order(a)
0
>>> covariant_order(a*R2.x + 2)
0
>>> covariant_order(a*R2.x*R2.dy + R2.dx)
1
"""
# TODO move some of this to class methods.
# TODO rewrite using the .as_blah_blah methods
if isinstance(expr, Add):
orders = [covariant_order(e) for e in expr.args]
if len(set(orders)) != 1:
raise ValueError('Misformed expression containing form fields of varying order.')
return orders[0]
elif isinstance(expr, Mul):
orders = [covariant_order(e) for e in expr.args]
not_zero = [o for o in orders if o != 0]
if len(not_zero) > 1:
raise ValueError('Misformed expression containing multiplication between forms.')
return 0 if not not_zero else not_zero[0]
elif isinstance(expr, Pow):
if covariant_order(expr.base) or covariant_order(expr.exp):
raise ValueError(
'Misformed expression containing a power of a form.')
return 0
elif isinstance(expr, Differential):
return covariant_order(*expr.args) + 1
elif isinstance(expr, TensorProduct):
return sum(covariant_order(a) for a in expr.args)
elif not _strict or expr.atoms(BaseScalarField):
return 0
else: # If it does not contain anything related to the diffgeom module and it is _strict
return -1
###############################################################################
# Coordinate transformation functions
###############################################################################
def vectors_in_basis(expr, to_sys):
"""Transform all base vectors in base vectors of a specified coord basis.
While the new base vectors are in the new coordinate system basis, any
coefficients are kept in the old system.
Examples
========
>>> from sympy.diffgeom import vectors_in_basis
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> vectors_in_basis(R2_r.e_x, R2_p)
-y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2)
>>> vectors_in_basis(R2_p.e_r, R2_r)
sin(theta)*e_y + cos(theta)*e_x
"""
vectors = list(expr.atoms(BaseVectorField))
new_vectors = []
for v in vectors:
cs = v._coord_sys
jac = cs.jacobian(to_sys, cs.coord_functions())
new = (jac.T*Matrix(to_sys.base_vectors()))[v._index]
new_vectors.append(new)
return expr.subs(list(zip(vectors, new_vectors)))
###############################################################################
# Coordinate-dependent functions
###############################################################################
def twoform_to_matrix(expr):
"""Return the matrix representing the twoform.
For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`,
where `e_i` is the i-th base vector field for the coordinate system in
which the expression of `w` is given.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import twoform_to_matrix, TensorProduct
>>> TP = TensorProduct
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
Matrix([
[1, 0],
[0, 1]])
>>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
Matrix([
[x, 0],
[0, 1]])
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2)
Matrix([
[ 1, 0],
[-1/2, 1]])
"""
if covariant_order(expr) != 2 or contravariant_order(expr):
raise ValueError('The input expression is not a two-form.')
coord_sys = _find_coords(expr)
if len(coord_sys) != 1:
raise ValueError('The input expression concerns more than one '
'coordinate systems, hence there is no unambiguous '
'way to choose a coordinate system for the matrix.')
coord_sys = coord_sys.pop()
vectors = coord_sys.base_vectors()
expr = expr.expand()
matrix_content = [[expr.rcall(v1, v2) for v1 in vectors]
for v2 in vectors]
return Matrix(matrix_content)
def metric_to_Christoffel_1st(expr):
"""Return the nested list of Christoffel symbols for the given metric.
This returns the Christoffel symbol of first kind that represents the
Levi-Civita connection for the given metric.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]]
"""
matrix = twoform_to_matrix(expr)
if not matrix.is_symmetric():
raise ValueError(
'The two-form representing the metric is not symmetric.')
coord_sys = _find_coords(expr).pop()
deriv_matrices = [matrix.applyfunc(lambda a: d(a))
for d in coord_sys.base_vectors()]
indices = list(range(coord_sys.dim))
christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2
for k in indices]
for j in indices]
for i in indices]
return ImmutableDenseNDimArray(christoffel)
def metric_to_Christoffel_2nd(expr):
"""Return the nested list of Christoffel symbols for the given metric.
This returns the Christoffel symbol of second kind that represents the
Levi-Civita connection for the given metric.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]]
"""
ch_1st = metric_to_Christoffel_1st(expr)
coord_sys = _find_coords(expr).pop()
indices = list(range(coord_sys.dim))
# XXX workaround, inverting a matrix does not work if it contains non
# symbols
#matrix = twoform_to_matrix(expr).inv()
matrix = twoform_to_matrix(expr)
s_fields = set()
for e in matrix:
s_fields.update(e.atoms(BaseScalarField))
s_fields = list(s_fields)
dums = coord_sys.symbols
matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields)))
# XXX end of workaround
christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices])
for k in indices]
for j in indices]
for i in indices]
return ImmutableDenseNDimArray(christoffel)
def metric_to_Riemann_components(expr):
"""Return the components of the Riemann tensor expressed in a given basis.
Given a metric it calculates the components of the Riemann tensor in the
canonical basis of the coordinate system in which the metric expression is
given.
Examples
========
>>> from sympy import exp
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
R2.r**2*TP(R2.dtheta, R2.dtheta)
>>> non_trivial_metric
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
>>> riemann = metric_to_Riemann_components(non_trivial_metric)
>>> riemann[0, :, :, :]
[[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]]
>>> riemann[1, :, :, :]
[[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]]
"""
ch_2nd = metric_to_Christoffel_2nd(expr)
coord_sys = _find_coords(expr).pop()
indices = list(range(coord_sys.dim))
deriv_ch = [[[[d(ch_2nd[i, j, k])
for d in coord_sys.base_vectors()]
for k in indices]
for j in indices]
for i in indices]
riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices])
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
return ImmutableDenseNDimArray(riemann)
def metric_to_Ricci_components(expr):
"""Return the components of the Ricci tensor expressed in a given basis.
Given a metric it calculates the components of the Ricci tensor in the
canonical basis of the coordinate system in which the metric expression is
given.
Examples
========
>>> from sympy import exp
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[0, 0], [0, 0]]
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
R2.r**2*TP(R2.dtheta, R2.dtheta)
>>> non_trivial_metric
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
>>> metric_to_Ricci_components(non_trivial_metric)
[[1/rho, 0], [0, exp(-2*rho)*rho]]
"""
riemann = metric_to_Riemann_components(expr)
coord_sys = _find_coords(expr).pop()
indices = list(range(coord_sys.dim))
ricci = [[Add(*[riemann[k, i, k, j] for k in indices])
for j in indices]
for i in indices]
return ImmutableDenseNDimArray(ricci)
###############################################################################
# Classes for deprecation
###############################################################################
class _deprecated_container(object):
# This class gives deprecation warning.
# When deprecated features are completely deleted, this should be removed as well.
# See https://github.com/sympy/sympy/pull/19368
def __init__(self, feature, useinstead, issue, version, data):
super().__init__(data)
self.feature = feature
self.useinstead = useinstead
self.issue = issue
self.version = version
def warn(self):
SymPyDeprecationWarning(
feature=self.feature,
useinstead=self.useinstead,
issue=self.issue,
deprecated_since_version=self.version).warn()
def __iter__(self):
self.warn()
return super().__iter__()
def __getitem__(self, key):
self.warn()
return super().__getitem__(key)
def __contains__(self, key):
self.warn()
return super().__contains__(key)
class _deprecated_list(_deprecated_container, list):
pass
class _deprecated_dict(_deprecated_container, dict):
pass
|
a4e118caef58a38834b98d6562da42eea909725bbfac46b0e251b250b060047f | """
AST nodes specific to the C family of languages
"""
from sympy.codegen.ast import Attribute, Declaration, Node, String, Token, Type, none, FunctionCall
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.sympify import sympify
void = Type('void')
restrict = Attribute('restrict') # guarantees no pointer aliasing
volatile = Attribute('volatile')
static = Attribute('static')
def alignof(arg):
""" Generate of FunctionCall instance for calling 'alignof' """
return FunctionCall('alignof', [String(arg) if isinstance(arg, str) else arg])
def sizeof(arg):
""" Generate of FunctionCall instance for calling 'sizeof'
Examples
========
>>> from sympy.codegen.ast import real
>>> from sympy.codegen.cnodes import sizeof
>>> from sympy.printing import ccode
>>> ccode(sizeof(real))
'sizeof(double)'
"""
return FunctionCall('sizeof', [String(arg) if isinstance(arg, str) else arg])
class CommaOperator(Basic):
""" Represents the comma operator in C """
def __new__(cls, *args):
return Basic.__new__(cls, *[sympify(arg) for arg in args])
class Label(String):
""" Label for use with e.g. goto statement.
Examples
========
>>> from sympy.codegen.cnodes import Label
>>> from sympy.printing import ccode
>>> print(ccode(Label('foo')))
foo:
"""
class goto(Token):
""" Represents goto in C """
__slots__ = ('label',)
_construct_label = Label
class PreDecrement(Basic):
""" Represents the pre-decrement operator
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cnodes import PreDecrement
>>> from sympy.printing import ccode
>>> ccode(PreDecrement(x))
'--(x)'
"""
nargs = 1
class PostDecrement(Basic):
""" Represents the post-decrement operator """
nargs = 1
class PreIncrement(Basic):
""" Represents the pre-increment operator """
nargs = 1
class PostIncrement(Basic):
""" Represents the post-increment operator """
nargs = 1
class struct(Node):
""" Represents a struct in C """
__slots__ = ('name', 'declarations')
defaults = {'name': none}
_construct_name = String
@classmethod
def _construct_declarations(cls, args):
return Tuple(*[Declaration(arg) for arg in args])
class union(struct):
""" Represents a union in C """
|
8f6a275dc6626891b2eb08cfb795a1e8a177ab44396c7bbd58c991f4841da4e7 | from sympy.core.function import Add, ArgumentIndexError, Function
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp, log
from sympy.utilities import default_sort_key
def _logaddexp(x1, x2, *, evaluate=True):
return log(Add(exp(x1, evaluate=evaluate), exp(x2, evaluate=evaluate), evaluate=evaluate))
_two = S.One*2
_ln2 = log(_two)
def _lb(x, *, evaluate=True):
return log(x, evaluate=evaluate)/_ln2
def _exp2(x, *, evaluate=True):
return Pow(_two, x, evaluate=evaluate)
def _logaddexp2(x1, x2, *, evaluate=True):
return _lb(Add(_exp2(x1, evaluate=evaluate),
_exp2(x2, evaluate=evaluate), evaluate=evaluate))
class logaddexp(Function):
""" Logarithm of the sum of exponentiations of the inputs.
Helper class for use with e.g. numpy.logaddexp
See: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html
"""
nargs = 2
def __new__(cls, *args):
return Function.__new__(cls, *sorted(args, key=default_sort_key))
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
wrt, other = self.args
elif argindex == 2:
other, wrt = self.args
else:
raise ArgumentIndexError(self, argindex)
return S.One/(S.One + exp(other-wrt))
def _eval_rewrite_as_log(self, x1, x2, **kwargs):
return _logaddexp(x1, x2)
def _eval_evalf(self, *args, **kwargs):
return self.rewrite(log).evalf(*args, **kwargs)
def _eval_simplify(self, *args, **kwargs):
a, b = map(lambda x: x.simplify(**kwargs), self.args)
candidate = _logaddexp(a, b)
if candidate != _logaddexp(a, b, evaluate=False):
return candidate
else:
return logaddexp(a, b)
class logaddexp2(Function):
""" Logarithm of the sum of exponentiations of the inputs in base-2.
Helper class for use with e.g. numpy.logaddexp2
See: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp2.html
"""
nargs = 2
def __new__(cls, *args):
return Function.__new__(cls, *sorted(args, key=default_sort_key))
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
wrt, other = self.args
elif argindex == 2:
other, wrt = self.args
else:
raise ArgumentIndexError(self, argindex)
return S.One/(S.One + _exp2(other-wrt))
def _eval_rewrite_as_log(self, x1, x2, **kwargs):
return _logaddexp2(x1, x2)
def _eval_evalf(self, *args, **kwargs):
return self.rewrite(log).evalf(*args, **kwargs)
def _eval_simplify(self, *args, **kwargs):
a, b = map(lambda x: x.simplify(**kwargs).factor(), self.args)
candidate = _logaddexp2(a, b)
if candidate != _logaddexp2(a, b, evaluate=False):
return candidate
else:
return logaddexp2(a, b)
|
d5f7fec78bfcb8975afef511081337de38e895cbb03497993eb7cf4c2bff1634 | """
Classes and functions useful for rewriting expressions for optimized code
generation. Some languages (or standards thereof), e.g. C99, offer specialized
math functions for better performance and/or precision.
Using the ``optimize`` function in this module, together with a collection of
rules (represented as instances of ``Optimization``), one can rewrite the
expressions for this purpose::
>>> from sympy import Symbol, exp, log
>>> from sympy.codegen.rewriting import optimize, optims_c99
>>> x = Symbol('x')
>>> optimize(3*exp(2*x) - 3, optims_c99)
3*expm1(2*x)
>>> optimize(exp(2*x) - 3, optims_c99)
exp(2*x) - 3
>>> optimize(log(3*x + 3), optims_c99)
log1p(x) + log(3)
>>> optimize(log(2*x + 3), optims_c99)
log(2*x + 3)
The ``optims_c99`` imported above is tuple containing the following instances
(which may be imported from ``sympy.codegen.rewriting``):
- ``expm1_opt``
- ``log1p_opt``
- ``exp2_opt``
- ``log2_opt``
- ``log2const_opt``
"""
from itertools import chain
from sympy import log, exp, Max, Min, Wild, expand_log, Dummy
from sympy.assumptions import Q, ask
from sympy.codegen.cfunctions import log1p, log2, exp2, expm1
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.core.expr import UnevaluatedExpr
from sympy.core.power import Pow
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.core.mul import Mul
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.utilities.iterables import sift
class Optimization:
""" Abstract base class for rewriting optimization.
Subclasses should implement ``__call__`` taking an expression
as argument.
Parameters
==========
cost_function : callable returning number
priority : number
"""
def __init__(self, cost_function=None, priority=1):
self.cost_function = cost_function
self.priority=priority
class ReplaceOptim(Optimization):
""" Rewriting optimization calling replace on expressions.
The instance can be used as a function on expressions for which
it will apply the ``replace`` method (see
:meth:`sympy.core.basic.Basic.replace`).
Parameters
==========
query : first argument passed to replace
value : second argument passed to replace
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.rewriting import ReplaceOptim
>>> from sympy.codegen.cfunctions import exp2
>>> x = Symbol('x')
>>> exp2_opt = ReplaceOptim(lambda p: p.is_Pow and p.base == 2,
... lambda p: exp2(p.exp))
>>> exp2_opt(2**x)
exp2(x)
"""
def __init__(self, query, value, **kwargs):
super().__init__(**kwargs)
self.query = query
self.value = value
def __call__(self, expr):
return expr.replace(self.query, self.value)
def optimize(expr, optimizations):
""" Apply optimizations to an expression.
Parameters
==========
expr : expression
optimizations : iterable of ``Optimization`` instances
The optimizations will be sorted with respect to ``priority`` (highest first).
Examples
========
>>> from sympy import log, Symbol
>>> from sympy.codegen.rewriting import optims_c99, optimize
>>> x = Symbol('x')
>>> optimize(log(x+3)/log(2) + log(x**2 + 1), optims_c99)
log1p(x**2) + log2(x + 3)
"""
for optim in sorted(optimizations, key=lambda opt: opt.priority, reverse=True):
new_expr = optim(expr)
if optim.cost_function is None:
expr = new_expr
else:
before, after = map(lambda x: optim.cost_function(x), (expr, new_expr))
if before > after:
expr = new_expr
return expr
exp2_opt = ReplaceOptim(
lambda p: p.is_Pow and p.base == 2,
lambda p: exp2(p.exp)
)
_d = Wild('d', properties=[lambda x: x.is_Dummy])
_u = Wild('u', properties=[lambda x: not x.is_number and not x.is_Add])
_v = Wild('v')
_w = Wild('w')
log2_opt = ReplaceOptim(_v*log(_w)/log(2), _v*log2(_w), cost_function=lambda expr: expr.count(
lambda e: ( # division & eval of transcendentals are expensive floating point operations...
e.is_Pow and e.exp.is_negative # division
or (isinstance(e, (log, log2)) and not e.args[0].is_number)) # transcendental
)
)
log2const_opt = ReplaceOptim(log(2)*log2(_w), log(_w))
logsumexp_2terms_opt = ReplaceOptim(
lambda l: (isinstance(l, log)
and l.args[0].is_Add
and len(l.args[0].args) == 2
and all(isinstance(t, exp) for t in l.args[0].args)),
lambda l: (
Max(*[e.args[0] for e in l.args[0].args]) +
log1p(exp(Min(*[e.args[0] for e in l.args[0].args])))
)
)
def _try_expm1(expr):
protected, old_new = expr.replace(exp, lambda arg: Dummy(), map=True)
factored = protected.factor()
new_old = {v: k for k, v in old_new.items()}
return factored.replace(_d - 1, lambda d: expm1(new_old[d].args[0])).xreplace(new_old)
def _expm1_value(e):
numbers, non_num = sift(e.args, lambda arg: arg.is_number, binary=True)
non_num_exp, non_num_other = sift(non_num, lambda arg: arg.has(exp),
binary=True)
numsum = sum(numbers)
new_exp_terms, done = [], False
for exp_term in non_num_exp:
if done:
new_exp_terms.append(exp_term)
else:
looking_at = exp_term + numsum
attempt = _try_expm1(looking_at)
if looking_at == attempt:
new_exp_terms.append(exp_term)
else:
done = True
new_exp_terms.append(attempt)
if not done:
new_exp_terms.append(numsum)
return e.func(*chain(new_exp_terms, non_num_other))
expm1_opt = ReplaceOptim(lambda e: e.is_Add, _expm1_value)
log1p_opt = ReplaceOptim(
lambda e: isinstance(e, log),
lambda l: expand_log(l.replace(
log, lambda arg: log(arg.factor())
)).replace(log(_u+1), log1p(_u))
)
def create_expand_pow_optimization(limit):
""" Creates an instance of :class:`ReplaceOptim` for expanding ``Pow``.
The requirements for expansions are that the base needs to be a symbol
and the exponent needs to be an Integer (and be less than or equal to
``limit``).
Parameters
==========
limit : int
The highest power which is expanded into multiplication.
Examples
========
>>> from sympy import Symbol, sin
>>> from sympy.codegen.rewriting import create_expand_pow_optimization
>>> x = Symbol('x')
>>> expand_opt = create_expand_pow_optimization(3)
>>> expand_opt(x**5 + x**3)
x**5 + x*x*x
>>> expand_opt(x**5 + x**3 + sin(x)**3)
x**5 + sin(x)**3 + x*x*x
"""
return ReplaceOptim(
lambda e: e.is_Pow and e.base.is_symbol and e.exp.is_Integer and abs(e.exp) <= limit,
lambda p: (
UnevaluatedExpr(Mul(*([p.base]*+p.exp), evaluate=False)) if p.exp > 0 else
1/UnevaluatedExpr(Mul(*([p.base]*-p.exp), evaluate=False))
))
# Optimization procedures for turning A**(-1) * x into MatrixSolve(A, x)
def _matinv_predicate(expr):
# TODO: We should be able to support more than 2 elements
if expr.is_MatMul and len(expr.args) == 2:
left, right = expr.args
if left.is_Inverse and right.shape[1] == 1:
inv_arg = left.arg
if isinstance(inv_arg, MatrixSymbol):
return bool(ask(Q.fullrank(left.arg)))
return False
def _matinv_transform(expr):
left, right = expr.args
inv_arg = left.arg
return MatrixSolve(inv_arg, right)
matinv_opt = ReplaceOptim(_matinv_predicate, _matinv_transform)
logaddexp_opt = ReplaceOptim(log(exp(_v)+exp(_w)), logaddexp(_v, _w))
logaddexp2_opt = ReplaceOptim(log(Pow(2, _v)+Pow(2, _w)), logaddexp2(_v, _w)*log(2))
# Collections of optimizations:
optims_c99 = (expm1_opt, log1p_opt, exp2_opt, log2_opt, log2const_opt)
optims_numpy = (logaddexp_opt, logaddexp2_opt)
|
28adbba1735a1e33952f0d9576334f2d1e7b523778e2967c1be126fce9495b3b | """
Types used to represent a full function/module as an Abstract Syntax Tree.
Most types are small, and are merely used as tokens in the AST. A tree diagram
has been included below to illustrate the relationships between the AST types.
AST Type Tree
-------------
::
*Basic*
|--->AssignmentBase
| |--->Assignment
| |--->AugmentedAssignment
| |--->AddAugmentedAssignment
| |--->SubAugmentedAssignment
| |--->MulAugmentedAssignment
| |--->DivAugmentedAssignment
| |--->ModAugmentedAssignment
|
|--->CodeBlock
|
|
|--->Token
| |--->Attribute
| |--->For
| |--->String
| | |--->QuotedString
| | |--->Comment
| |--->Type
| | |--->IntBaseType
| | | |--->_SizedIntType
| | | |--->SignedIntType
| | | |--->UnsignedIntType
| | |--->FloatBaseType
| | |--->FloatType
| | |--->ComplexBaseType
| | |--->ComplexType
| |--->Node
| | |--->Variable
| | | |---> Pointer
| | |--->FunctionPrototype
| | |--->FunctionDefinition
| |--->Element
| |--->Declaration
| |--->While
| |--->Scope
| |--->Stream
| |--->Print
| |--->FunctionCall
| |--->BreakToken
| |--->ContinueToken
| |--->NoneToken
|
|--->Statement
|--->Return
Predefined types
----------------
A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module
for convenience. Perhaps the two most common ones for code-generation (of numeric
codes) are ``float32`` and ``float64`` (known as single and double precision respectively).
There are also precision generic versions of Types (for which the codeprinters selects the
underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``.
The other ``Type`` instances defined are:
- ``intc``: Integer type used by C's "int".
- ``intp``: Integer type used by C's "unsigned".
- ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers.
- ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers.
- ``float80``: known as "extended precision" on modern x86/amd64 hardware.
- ``complex64``: Complex number represented by two ``float32`` numbers
- ``complex128``: Complex number represented by two ``float64`` numbers
Using the nodes
---------------
It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying
Newton's method::
>>> from sympy import symbols, cos
>>> from sympy.codegen.ast import While, Assignment, aug_assign, Print
>>> t, dx, x = symbols('tol delta val')
>>> expr = cos(x) - x**3
>>> whl = While(abs(dx) > t, [
... Assignment(dx, -expr/expr.diff(x)),
... aug_assign(x, '+', dx),
... Print([x])
... ])
>>> from sympy.printing import pycode
>>> py_str = pycode(whl)
>>> print(py_str)
while (abs(delta) > tol):
delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val))
val += delta
print(val)
>>> import math
>>> tol, val, delta = 1e-5, 0.5, float('inf')
>>> exec(py_str)
1.1121416371
0.909672693737
0.867263818209
0.865477135298
0.865474033111
>>> print('%3.1g' % (math.cos(val) - val**3))
-3e-11
If we want to generate Fortran code for the same while loop we simple call ``fcode``::
>>> from sympy.printing import fcode
>>> print(fcode(whl, standard=2003, source_format='free'))
do while (abs(delta) > tol)
delta = (val**3 - cos(val))/(-3*val**2 - sin(val))
val = val + delta
print *, val
end do
There is a function constructing a loop (or a complete function) like this in
:mod:`sympy.codegen.algorithms`.
"""
from typing import Any, Dict, List
from collections import defaultdict
from sympy import Lt, Le, Ge, Gt
from sympy.core import Symbol, Tuple, Dummy
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.numbers import Float, Integer, oo
from sympy.core.sympify import _sympify, sympify, SympifyError
from sympy.utilities.iterables import iterable
def _mk_Tuple(args):
"""
Create a Sympy Tuple object from an iterable, converting Python strings to
AST strings.
Parameters
==========
args: iterable
Arguments to :class:`sympy.Tuple`.
Returns
=======
sympy.Tuple
"""
args = [String(arg) if isinstance(arg, str) else arg for arg in args]
return Tuple(*args)
class Token(Basic):
""" Base class for the AST types.
Defining fields are set in ``__slots__``. Attributes (defined in __slots__)
are only allowed to contain instances of Basic (unless atomic, see
``String``). The arguments to ``__new__()`` correspond to the attributes in
the order defined in ``__slots__`. The ``defaults`` class attribute is a
dictionary mapping attribute names to their default values.
Subclasses should not need to override the ``__new__()`` method. They may
define a class or static method named ``_construct_<attr>`` for each
attribute to process the value passed to ``__new__()``. Attributes listed
in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`.
"""
__slots__ = ()
defaults = {} # type: Dict[str, Any]
not_in_args = [] # type: List[str]
indented_args = ['body']
@property
def is_Atom(self):
return len(self.__slots__) == 0
@classmethod
def _get_constructor(cls, attr):
""" Get the constructor function for an attribute by name. """
return getattr(cls, '_construct_%s' % attr, lambda x: x)
@classmethod
def _construct(cls, attr, arg):
""" Construct an attribute value from argument passed to ``__new__()``. """
# arg may be ``NoneToken()``, so comparation is done using == instead of ``is`` operator
if arg == None:
return cls.defaults.get(attr, none)
else:
if isinstance(arg, Dummy): # sympy's replace uses Dummy instances
return arg
else:
return cls._get_constructor(attr)(arg)
def __new__(cls, *args, **kwargs):
# Pass through existing instances when given as sole argument
if len(args) == 1 and not kwargs and isinstance(args[0], cls):
return args[0]
if len(args) > len(cls.__slots__):
raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls.__slots__)))
attrvals = []
# Process positional arguments
for attrname, argval in zip(cls.__slots__, args):
if attrname in kwargs:
raise TypeError('Got multiple values for attribute %r' % attrname)
attrvals.append(cls._construct(attrname, argval))
# Process keyword arguments
for attrname in cls.__slots__[len(args):]:
if attrname in kwargs:
argval = kwargs.pop(attrname)
elif attrname in cls.defaults:
argval = cls.defaults[attrname]
else:
raise TypeError('No value for %r given and attribute has no default' % attrname)
attrvals.append(cls._construct(attrname, argval))
if kwargs:
raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs))
# Parent constructor
basic_args = [
val for attr, val in zip(cls.__slots__, attrvals)
if attr not in cls.not_in_args
]
obj = Basic.__new__(cls, *basic_args)
# Set attributes
for attr, arg in zip(cls.__slots__, attrvals):
setattr(obj, attr, arg)
return obj
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
for attr in self.__slots__:
if getattr(self, attr) != getattr(other, attr):
return False
return True
def _hashable_content(self):
return tuple([getattr(self, attr) for attr in self.__slots__])
def __hash__(self):
return super().__hash__()
def _joiner(self, k, indent_level):
return (',\n' + ' '*indent_level) if k in self.indented_args else ', '
def _indented(self, printer, k, v, *args, **kwargs):
il = printer._context['indent_level']
def _print(arg):
if isinstance(arg, Token):
return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs)
else:
return printer._print(arg, *args, **kwargs)
if isinstance(v, Tuple):
joined = self._joiner(k, il).join([_print(arg) for arg in v.args])
if k in self.indented_args:
return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')'
else:
return ('({0},)' if len(v.args) == 1 else '({0})').format(joined)
else:
return _print(v)
def _sympyrepr(self, printer, *args, **kwargs):
from sympy.printing.printer import printer_context
exclude = kwargs.get('exclude', ())
values = [getattr(self, k) for k in self.__slots__]
indent_level = printer._context.get('indent_level', 0)
joiner = kwargs.pop('joiner', ', ')
arg_reprs = []
for i, (attr, value) in enumerate(zip(self.__slots__, values)):
if attr in exclude:
continue
# Skip attributes which have the default value
if attr in self.defaults and value == self.defaults[attr]:
continue
ilvl = indent_level + 4 if attr in self.indented_args else 0
with printer_context(printer, indent_level=ilvl):
indented = self._indented(printer, attr, value, *args, **kwargs)
arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip()))
return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs))
_sympystr = _sympyrepr
def __repr__(self): # sympy.core.Basic.__repr__ uses sstr
from sympy.printing import srepr
return srepr(self)
def kwargs(self, exclude=(), apply=None):
""" Get instance's attributes as dict of keyword arguments.
Parameters
==========
exclude : collection of str
Collection of keywords to exclude.
apply : callable, optional
Function to apply to all values.
"""
kwargs = {k: getattr(self, k) for k in self.__slots__ if k not in exclude}
if apply is not None:
return {k: apply(v) for k, v in kwargs.items()}
else:
return kwargs
class BreakToken(Token):
""" Represents 'break' in C/Python ('exit' in Fortran).
Use the premade instance ``break_`` or instantiate manually.
Examples
========
>>> from sympy.printing import ccode, fcode
>>> from sympy.codegen.ast import break_
>>> ccode(break_)
'break'
>>> fcode(break_, source_format='free')
'exit'
"""
break_ = BreakToken()
class ContinueToken(Token):
""" Represents 'continue' in C/Python ('cycle' in Fortran)
Use the premade instance ``continue_`` or instantiate manually.
Examples
========
>>> from sympy.printing import ccode, fcode
>>> from sympy.codegen.ast import continue_
>>> ccode(continue_)
'continue'
>>> fcode(continue_, source_format='free')
'cycle'
"""
continue_ = ContinueToken()
class NoneToken(Token):
""" The AST equivalence of Python's NoneType
The corresponding instance of Python's ``None`` is ``none``.
Examples
========
>>> from sympy.codegen.ast import none, Variable
>>> from sympy.printing.pycode import pycode
>>> print(pycode(Variable('x').as_Declaration(value=none)))
x = None
"""
def __eq__(self, other):
return other is None or isinstance(other, NoneToken)
def _hashable_content(self):
return ()
def __hash__(self):
return super().__hash__()
none = NoneToken()
class AssignmentBase(Basic):
""" Abstract base class for Assignment and AugmentedAssignment.
Attributes:
===========
op : str
Symbol for assignment operator, e.g. "=", "+=", etc.
"""
def __new__(cls, lhs, rhs):
lhs = _sympify(lhs)
rhs = _sympify(rhs)
cls._check_args(lhs, rhs)
return super().__new__(cls, lhs, rhs)
@property
def lhs(self):
return self.args[0]
@property
def rhs(self):
return self.args[1]
@classmethod
def _check_args(cls, lhs, rhs):
""" Check arguments to __new__ and raise exception if any problems found.
Derived classes may wish to override this.
"""
from sympy.matrices.expressions.matexpr import (
MatrixElement, MatrixSymbol)
from sympy.tensor.indexed import Indexed
# Tuple of things that can be on the lhs of an assignment
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable)
if not isinstance(lhs, assignable):
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
# Indexed types implement shape, but don't define it until later. This
# causes issues in assignment validation. For now, matrices are defined
# as anything with a shape that is not an Indexed
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
# If lhs and rhs have same structure, then this assignment is ok
if lhs_is_mat:
if not rhs_is_mat:
raise ValueError("Cannot assign a scalar to a matrix.")
elif lhs.shape != rhs.shape:
raise ValueError("Dimensions of lhs and rhs don't align.")
elif rhs_is_mat and not lhs_is_mat:
raise ValueError("Cannot assign a matrix to a scalar.")
class Assignment(AssignmentBase):
"""
Represents variable assignment for code generation.
Parameters
==========
lhs : Expr
Sympy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
subclass these types are also supported.
rhs : Expr
Sympy object representing the rhs of the expression. This can be any
type, provided its shape corresponds to that of the lhs. For example,
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
the dimensions will not align.
Examples
========
>>> from sympy import symbols, MatrixSymbol, Matrix
>>> from sympy.codegen.ast import Assignment
>>> x, y, z = symbols('x, y, z')
>>> Assignment(x, y)
Assignment(x, y)
>>> Assignment(x, 0)
Assignment(x, 0)
>>> A = MatrixSymbol('A', 1, 3)
>>> mat = Matrix([x, y, z]).T
>>> Assignment(A, mat)
Assignment(A, Matrix([[x, y, z]]))
>>> Assignment(A[0, 1], x)
Assignment(A[0, 1], x)
"""
op = ':='
class AugmentedAssignment(AssignmentBase):
"""
Base class for augmented assignments.
Attributes:
===========
binop : str
Symbol for binary operation being applied in the assignment, such as "+",
"*", etc.
"""
binop = None # type: str
@property
def op(self):
return self.binop + '='
class AddAugmentedAssignment(AugmentedAssignment):
binop = '+'
class SubAugmentedAssignment(AugmentedAssignment):
binop = '-'
class MulAugmentedAssignment(AugmentedAssignment):
binop = '*'
class DivAugmentedAssignment(AugmentedAssignment):
binop = '/'
class ModAugmentedAssignment(AugmentedAssignment):
binop = '%'
# Mapping from binary op strings to AugmentedAssignment subclasses
augassign_classes = {
cls.binop: cls for cls in [
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
DivAugmentedAssignment, ModAugmentedAssignment
]
}
def aug_assign(lhs, op, rhs):
"""
Create 'lhs op= rhs'.
Represents augmented variable assignment for code generation. This is a
convenience function. You can also use the AugmentedAssignment classes
directly, like AddAugmentedAssignment(x, y).
Parameters
==========
lhs : Expr
Sympy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
subclass these types are also supported.
op : str
Operator (+, -, /, \\*, %).
rhs : Expr
Sympy object representing the rhs of the expression. This can be any
type, provided its shape corresponds to that of the lhs. For example,
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
the dimensions will not align.
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import aug_assign
>>> x, y = symbols('x, y')
>>> aug_assign(x, '+', y)
AddAugmentedAssignment(x, y)
"""
if op not in augassign_classes:
raise ValueError("Unrecognized operator %s" % op)
return augassign_classes[op](lhs, rhs)
class CodeBlock(Basic):
"""
Represents a block of code
For now only assignments are supported. This restriction will be lifted in
the future.
Useful attributes on this object are:
``left_hand_sides``:
Tuple of left-hand sides of assignments, in order.
``left_hand_sides``:
Tuple of right-hand sides of assignments, in order.
``free_symbols``: Free symbols of the expressions in the right-hand sides
which do not appear in the left-hand side of an assignment.
Useful methods on this object are:
``topological_sort``:
Class method. Return a CodeBlock with assignments
sorted so that variables are assigned before they
are used.
``cse``:
Return a new CodeBlock with common subexpressions eliminated and
pulled out as assignments.
Examples
========
>>> from sympy import symbols, ccode
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y = symbols('x y')
>>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
>>> print(ccode(c))
x = 1;
y = x + 1;
"""
def __new__(cls, *args):
left_hand_sides = []
right_hand_sides = []
for i in args:
if isinstance(i, Assignment):
lhs, rhs = i.args
left_hand_sides.append(lhs)
right_hand_sides.append(rhs)
obj = Basic.__new__(cls, *args)
obj.left_hand_sides = Tuple(*left_hand_sides)
obj.right_hand_sides = Tuple(*right_hand_sides)
return obj
def __iter__(self):
return iter(self.args)
def _sympyrepr(self, printer, *args, **kwargs):
il = printer._context.get('indent_level', 0)
joiner = ',\n' + ' '*il
joined = joiner.join(map(printer._print, self.args))
return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) +
' '*il + joined + '\n' + ' '*(il - 4) + ')')
_sympystr = _sympyrepr
@property
def free_symbols(self):
return super().free_symbols - set(self.left_hand_sides)
@classmethod
def topological_sort(cls, assignments):
"""
Return a CodeBlock with topologically sorted assignments so that
variables are assigned before they are used.
The existing order of assignments is preserved as much as possible.
This function assumes that variables are assigned to only once.
This is a class constructor so that the default constructor for
CodeBlock can error when variables are used before they are assigned.
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y, z = symbols('x y z')
>>> assignments = [
... Assignment(x, y + z),
... Assignment(y, z + 1),
... Assignment(z, 2),
... ]
>>> CodeBlock.topological_sort(assignments)
CodeBlock(
Assignment(z, 2),
Assignment(y, z + 1),
Assignment(x, y + z)
)
"""
from sympy.utilities.iterables import topological_sort
if not all(isinstance(i, Assignment) for i in assignments):
# Will support more things later
raise NotImplementedError("CodeBlock.topological_sort only supports Assignments")
if any(isinstance(i, AugmentedAssignment) for i in assignments):
raise NotImplementedError("CodeBlock.topological_sort doesn't yet work with AugmentedAssignments")
# Create a graph where the nodes are assignments and there is a directed edge
# between nodes that use a variable and nodes that assign that
# variable, like
# [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)]
# If we then topologically sort these nodes, they will be in
# assignment order, like
# x := 1
# y := x + 1
# z := y + z
# A = The nodes
#
# enumerate keeps nodes in the same order they are already in if
# possible. It will also allow us to handle duplicate assignments to
# the same variable when those are implemented.
A = list(enumerate(assignments))
# var_map = {variable: [nodes for which this variable is assigned to]}
# like {x: [(1, x := y + z), (4, x := 2 * w)], ...}
var_map = defaultdict(list)
for node in A:
i, a = node
var_map[a.lhs].append(node)
# E = Edges in the graph
E = []
for dst_node in A:
i, a = dst_node
for s in a.rhs.free_symbols:
for src_node in var_map[s]:
E.append((src_node, dst_node))
ordered_assignments = topological_sort([A, E])
# De-enumerate the result
return cls(*[a for i, a in ordered_assignments])
def cse(self, symbols=None, optimizations=None, postprocess=None,
order='canonical'):
"""
Return a new code block with common subexpressions eliminated
See the docstring of :func:`sympy.simplify.cse_main.cse` for more
information.
Examples
========
>>> from sympy import symbols, sin
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y, z = symbols('x y z')
>>> c = CodeBlock(
... Assignment(x, 1),
... Assignment(y, sin(x) + 1),
... Assignment(z, sin(x) - 1),
... )
...
>>> c.cse()
CodeBlock(
Assignment(x, 1),
Assignment(x0, sin(x)),
Assignment(y, x0 + 1),
Assignment(z, x0 - 1)
)
"""
from sympy.simplify.cse_main import cse
from sympy.utilities.iterables import numbered_symbols, filter_symbols
# Check that the CodeBlock only contains assignments to unique variables
if not all(isinstance(i, Assignment) for i in self.args):
# Will support more things later
raise NotImplementedError("CodeBlock.cse only supports Assignments")
if any(isinstance(i, AugmentedAssignment) for i in self.args):
raise NotImplementedError("CodeBlock.cse doesn't yet work with AugmentedAssignments")
for i, lhs in enumerate(self.left_hand_sides):
if lhs in self.left_hand_sides[:i]:
raise NotImplementedError("Duplicate assignments to the same "
"variable are not yet supported (%s)" % lhs)
# Ensure new symbols for subexpressions do not conflict with existing
existing_symbols = self.atoms(Symbol)
if symbols is None:
symbols = numbered_symbols()
symbols = filter_symbols(symbols, existing_symbols)
replacements, reduced_exprs = cse(list(self.right_hand_sides),
symbols=symbols, optimizations=optimizations, postprocess=postprocess,
order=order)
new_block = [Assignment(var, expr) for var, expr in
zip(self.left_hand_sides, reduced_exprs)]
new_assignments = [Assignment(var, expr) for var, expr in replacements]
return self.topological_sort(new_assignments + new_block)
class For(Token):
"""Represents a 'for-loop' in the code.
Expressions are of the form:
"for target in iter:
body..."
Parameters
==========
target : symbol
iter : iterable
body : CodeBlock or iterable
! When passed an iterable it is used to instantiate a CodeBlock.
Examples
========
>>> from sympy import symbols, Range
>>> from sympy.codegen.ast import aug_assign, For
>>> x, i, j, k = symbols('x i j k')
>>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)])
>>> for_i # doctest: -NORMALIZE_WHITESPACE
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
>>> for_ji = For(j, Range(7), [for_i])
>>> for_ji # doctest: -NORMALIZE_WHITESPACE
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
))
>>> for_kji =For(k, Range(5), [for_ji])
>>> for_kji # doctest: -NORMALIZE_WHITESPACE
For(k, iterable=Range(0, 5, 1), body=CodeBlock(
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
))
))
"""
__slots__ = ('target', 'iterable', 'body')
_construct_target = staticmethod(_sympify)
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
@classmethod
def _construct_iterable(cls, itr):
if not iterable(itr):
raise TypeError("iterable must be an iterable")
if isinstance(itr, list): # _sympify errors on lists because they are mutable
itr = tuple(itr)
return _sympify(itr)
class String(Token):
""" SymPy object representing a string.
Atomic object which is not an expression (as opposed to Symbol).
Parameters
==========
text : str
Examples
========
>>> from sympy.codegen.ast import String
>>> f = String('foo')
>>> f
foo
>>> str(f)
'foo'
>>> f.text
'foo'
>>> print(repr(f))
String('foo')
"""
__slots__ = ('text',)
not_in_args = ['text']
is_Atom = True
@classmethod
def _construct_text(cls, text):
if not isinstance(text, str):
raise TypeError("Argument text is not a string type.")
return text
def _sympystr(self, printer, *args, **kwargs):
return self.text
class QuotedString(String):
""" Represents a string which should be printed with quotes. """
class Comment(String):
""" Represents a comment. """
class Node(Token):
""" Subclass of Token, carrying the attribute 'attrs' (Tuple)
Examples
========
>>> from sympy.codegen.ast import Node, value_const, pointer_const
>>> n1 = Node([value_const])
>>> n1.attr_params('value_const') # get the parameters of attribute (by name)
()
>>> from sympy.codegen.fnodes import dimension
>>> n2 = Node([value_const, dimension(5, 3)])
>>> n2.attr_params(value_const) # get the parameters of attribute (by Attribute instance)
()
>>> n2.attr_params('dimension') # get the parameters of attribute (by name)
(5, 3)
>>> n2.attr_params(pointer_const) is None
True
"""
__slots__ = ('attrs',)
defaults = {'attrs': Tuple()} # type: Dict[str, Any]
_construct_attrs = staticmethod(_mk_Tuple)
def attr_params(self, looking_for):
""" Returns the parameters of the Attribute with name ``looking_for`` in self.attrs """
for attr in self.attrs:
if str(attr.name) == str(looking_for):
return attr.parameters
class Type(Token):
""" Represents a type.
The naming is a super-set of NumPy naming. Type has a classmethod
``from_expr`` which offer type deduction. It also has a method
``cast_check`` which casts the argument to its type, possibly raising an
exception if rounding error is not within tolerances, or if the value is not
representable by the underlying data type (e.g. unsigned integers).
Parameters
==========
name : str
Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two
would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively).
If a ``Type`` instance is given, the said instance is returned.
Examples
========
>>> from sympy.codegen.ast import Type
>>> t = Type.from_expr(42)
>>> t
integer
>>> print(repr(t))
IntBaseType(String('integer'))
>>> from sympy.codegen.ast import uint8
>>> uint8.cast_check(-1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Minimum value for data type bigger than new value.
>>> from sympy.codegen.ast import float32
>>> v6 = 0.123456
>>> float32.cast_check(v6)
0.123456
>>> v10 = 12345.67894
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50')
>>> from sympy.printing import cxxcode
>>> from sympy.codegen.ast import Declaration, Variable
>>> cxxcode(Declaration(Variable('x', type=boost_mp50)))
'boost::multiprecision::cpp_dec_float_50 x'
References
==========
.. [1] https://docs.scipy.org/doc/numpy/user/basics.types.html
"""
__slots__ = ('name',)
_construct_name = String
def _sympystr(self, printer, *args, **kwargs):
return str(self.name)
@classmethod
def from_expr(cls, expr):
""" Deduces type from an expression or a ``Symbol``.
Parameters
==========
expr : number or SymPy object
The type will be deduced from type or properties.
Examples
========
>>> from sympy.codegen.ast import Type, integer, complex_
>>> Type.from_expr(2) == integer
True
>>> from sympy import Symbol
>>> Type.from_expr(Symbol('z', complex=True)) == complex_
True
>>> Type.from_expr(sum) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Could not deduce type from expr.
Raises
======
ValueError when type deduction fails.
"""
if isinstance(expr, (float, Float)):
return real
if isinstance(expr, (int, Integer)) or getattr(expr, 'is_integer', False):
return integer
if getattr(expr, 'is_real', False):
return real
if isinstance(expr, complex) or getattr(expr, 'is_complex', False):
return complex_
if isinstance(expr, bool) or getattr(expr, 'is_Relational', False):
return bool_
else:
raise ValueError("Could not deduce type from expr.")
def _check(self, value):
pass
def cast_check(self, value, rtol=None, atol=0, limits=None, precision_targets=None):
""" Casts a value to the data type of the instance.
Parameters
==========
value : number
rtol : floating point number
Relative tolerance. (will be deduced if not given).
atol : floating point number
Absolute tolerance (in addition to ``rtol``).
limits : dict
Values given by ``limits.h``, x86/IEEE754 defaults if not given.
type_aliases : dict
Maps substitutions for Type, e.g. {integer: int64, real: float32}
Examples
========
>>> from sympy.codegen.ast import integer, float32, int8
>>> integer.cast_check(3.0) == 3
True
>>> float32.cast_check(1e-40) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Minimum value for data type bigger than new value.
>>> int8.cast_check(256) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value.
>>> v10 = 12345.67894
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> from sympy.codegen.ast import float64
>>> float64.cast_check(v10)
12345.67894
>>> from sympy import Float
>>> v18 = Float('0.123456789012345646')
>>> float64.cast_check(v18)
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> from sympy.codegen.ast import float80
>>> float80.cast_check(v18)
0.123456789012345649
"""
val = sympify(value)
ten = Integer(10)
exp10 = getattr(self, 'decimal_dig', None)
if rtol is None:
rtol = 1e-15 if exp10 is None else 2.0*ten**(-exp10)
def tol(num):
return atol + rtol*abs(num)
new_val = self.cast_nocheck(value)
self._check(new_val)
delta = new_val - val
if abs(delta) > tol(val): # rounding, e.g. int(3.5) != 3.5
raise ValueError("Casting gives a significantly different value.")
return new_val
class IntBaseType(Type):
""" Integer base type, contains no size information. """
__slots__ = ('name',)
cast_nocheck = lambda self, i: Integer(int(i))
class _SizedIntType(IntBaseType):
__slots__ = ('name', 'nbits',)
_construct_nbits = Integer
def _check(self, value):
if value < self.min:
raise ValueError("Value is too small: %d < %d" % (value, self.min))
if value > self.max:
raise ValueError("Value is too big: %d > %d" % (value, self.max))
class SignedIntType(_SizedIntType):
""" Represents a signed integer type. """
@property
def min(self):
return -2**(self.nbits-1)
@property
def max(self):
return 2**(self.nbits-1) - 1
class UnsignedIntType(_SizedIntType):
""" Represents an unsigned integer type. """
@property
def min(self):
return 0
@property
def max(self):
return 2**self.nbits - 1
two = Integer(2)
class FloatBaseType(Type):
""" Represents a floating point number type. """
cast_nocheck = Float
class FloatType(FloatBaseType):
""" Represents a floating point type with fixed bit width.
Base 2 & one sign bit is assumed.
Parameters
==========
name : str
Name of the type.
nbits : integer
Number of bits used (storage).
nmant : integer
Number of bits used to represent the mantissa.
nexp : integer
Number of bits used to represent the mantissa.
Examples
========
>>> from sympy import S
>>> from sympy.codegen.ast import FloatType
>>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
>>> half_precision.max
65504
>>> half_precision.tiny == S(2)**-14
True
>>> half_precision.eps == S(2)**-10
True
>>> half_precision.dig == 3
True
>>> half_precision.decimal_dig == 5
True
>>> half_precision.cast_check(1.0)
1.0
>>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value.
"""
__slots__ = ('name', 'nbits', 'nmant', 'nexp',)
_construct_nbits = _construct_nmant = _construct_nexp = Integer
@property
def max_exponent(self):
""" The largest positive number n, such that 2**(n - 1) is a representable finite value. """
# cf. C++'s ``std::numeric_limits::max_exponent``
return two**(self.nexp - 1)
@property
def min_exponent(self):
""" The lowest negative number n, such that 2**(n - 1) is a valid normalized number. """
# cf. C++'s ``std::numeric_limits::min_exponent``
return 3 - self.max_exponent
@property
def max(self):
""" Maximum value representable. """
return (1 - two**-(self.nmant+1))*two**self.max_exponent
@property
def tiny(self):
""" The minimum positive normalized value. """
# See C macros: FLT_MIN, DBL_MIN, LDBL_MIN
# or C++'s ``std::numeric_limits::min``
# or numpy.finfo(dtype).tiny
return two**(self.min_exponent - 1)
@property
def eps(self):
""" Difference between 1.0 and the next representable value. """
return two**(-self.nmant)
@property
def dig(self):
""" Number of decimal digits that are guaranteed to be preserved in text.
When converting text -> float -> text, you are guaranteed that at least ``dig``
number of digits are preserved with respect to rounding or overflow.
"""
from sympy.functions import floor, log
return floor(self.nmant * log(2)/log(10))
@property
def decimal_dig(self):
""" Number of digits needed to store & load without loss.
Number of decimal digits needed to guarantee that two consecutive conversions
(float -> text -> float) to be idempotent. This is useful when one do not want
to loose precision due to rounding errors when storing a floating point value
as text.
"""
from sympy.functions import ceiling, log
return ceiling((self.nmant + 1) * log(2)/log(10) + 1)
def cast_nocheck(self, value):
""" Casts without checking if out of bounds or subnormal. """
if value == oo: # float(oo) or oo
return float(oo)
elif value == -oo: # float(-oo) or -oo
return float(-oo)
return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig)
def _check(self, value):
if value < -self.max:
raise ValueError("Value is too small: %d < %d" % (value, -self.max))
if value > self.max:
raise ValueError("Value is too big: %d > %d" % (value, self.max))
if abs(value) < self.tiny:
raise ValueError("Smallest (absolute) value for data type bigger than new value.")
class ComplexBaseType(FloatBaseType):
def cast_nocheck(self, value):
""" Casts without checking if out of bounds or subnormal. """
from sympy.functions import re, im
return (
super().cast_nocheck(re(value)) +
super().cast_nocheck(im(value))*1j
)
def _check(self, value):
from sympy.functions import re, im
super()._check(re(value))
super()._check(im(value))
class ComplexType(ComplexBaseType, FloatType):
""" Represents a complex floating point number. """
# NumPy types:
intc = IntBaseType('intc')
intp = IntBaseType('intp')
int8 = SignedIntType('int8', 8)
int16 = SignedIntType('int16', 16)
int32 = SignedIntType('int32', 32)
int64 = SignedIntType('int64', 64)
uint8 = UnsignedIntType('uint8', 8)
uint16 = UnsignedIntType('uint16', 16)
uint32 = UnsignedIntType('uint32', 32)
uint64 = UnsignedIntType('uint64', 64)
float16 = FloatType('float16', 16, nexp=5, nmant=10) # IEEE 754 binary16, Half precision
float32 = FloatType('float32', 32, nexp=8, nmant=23) # IEEE 754 binary32, Single precision
float64 = FloatType('float64', 64, nexp=11, nmant=52) # IEEE 754 binary64, Double precision
float80 = FloatType('float80', 80, nexp=15, nmant=63) # x86 extended precision (1 integer part bit), "long double"
float128 = FloatType('float128', 128, nexp=15, nmant=112) # IEEE 754 binary128, Quadruple precision
float256 = FloatType('float256', 256, nexp=19, nmant=236) # IEEE 754 binary256, Octuple precision
complex64 = ComplexType('complex64', nbits=64, **float32.kwargs(exclude=('name', 'nbits')))
complex128 = ComplexType('complex128', nbits=128, **float64.kwargs(exclude=('name', 'nbits')))
# Generic types (precision may be chosen by code printers):
untyped = Type('untyped')
real = FloatBaseType('real')
integer = IntBaseType('integer')
complex_ = ComplexBaseType('complex')
bool_ = Type('bool')
class Attribute(Token):
""" Attribute (possibly parametrized)
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
``Attribute`` as ``attrs``).
Parameters
==========
name : str
parameters : Tuple
Examples
========
>>> from sympy.codegen.ast import Attribute
>>> volatile = Attribute('volatile')
>>> volatile
volatile
>>> print(repr(volatile))
Attribute(String('volatile'))
>>> a = Attribute('foo', [1, 2, 3])
>>> a
foo(1, 2, 3)
>>> a.parameters == (1, 2, 3)
True
"""
__slots__ = ('name', 'parameters')
defaults = {'parameters': Tuple()}
_construct_name = String
_construct_parameters = staticmethod(_mk_Tuple)
def _sympystr(self, printer, *args, **kwargs):
result = str(self.name)
if self.parameters:
result += '(%s)' % ', '.join(map(lambda arg: printer._print(
arg, *args, **kwargs), self.parameters))
return result
value_const = Attribute('value_const')
pointer_const = Attribute('pointer_const')
class Variable(Node):
""" Represents a variable
Parameters
==========
symbol : Symbol
type : Type (optional)
Type of the variable.
attrs : iterable of Attribute instances
Will be stored as a Tuple.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Variable, float32, integer
>>> x = Symbol('x')
>>> v = Variable(x, type=float32)
>>> v.attrs
()
>>> v == Variable('x')
False
>>> v == Variable('x', type=float32)
True
>>> v
Variable(x, type=float32)
One may also construct a ``Variable`` instance with the type deduced from
assumptions about the symbol using the ``deduced`` classmethod:
>>> i = Symbol('i', integer=True)
>>> v = Variable.deduced(i)
>>> v.type == integer
True
>>> v == Variable('i')
False
>>> from sympy.codegen.ast import value_const
>>> value_const in v.attrs
False
>>> w = Variable('w', attrs=[value_const])
>>> w
Variable(w, attrs=(value_const,))
>>> value_const in w.attrs
True
>>> w.as_Declaration(value=42)
Declaration(Variable(w, value=42, attrs=(value_const,)))
"""
__slots__ = ('symbol', 'type', 'value') + Node.__slots__
defaults = Node.defaults.copy()
defaults.update({'type': untyped, 'value': none})
_construct_symbol = staticmethod(sympify)
_construct_value = staticmethod(sympify)
@classmethod
def deduced(cls, symbol, value=None, attrs=Tuple(), cast_check=True):
""" Alt. constructor with type deduction from ``Type.from_expr``.
Deduces type primarily from ``symbol``, secondarily from ``value``.
Parameters
==========
symbol : Symbol
value : expr
(optional) value of the variable.
attrs : iterable of Attribute instances
cast_check : bool
Whether to apply ``Type.cast_check`` on ``value``.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Variable, complex_
>>> n = Symbol('n', integer=True)
>>> str(Variable.deduced(n).type)
'integer'
>>> x = Symbol('x', real=True)
>>> v = Variable.deduced(x)
>>> v.type
real
>>> z = Symbol('z', complex=True)
>>> Variable.deduced(z).type == complex_
True
"""
if isinstance(symbol, Variable):
return symbol
try:
type_ = Type.from_expr(symbol)
except ValueError:
type_ = Type.from_expr(value)
if value is not None and cast_check:
value = type_.cast_check(value)
return cls(symbol, type=type_, value=value, attrs=attrs)
def as_Declaration(self, **kwargs):
""" Convenience method for creating a Declaration instance.
If the variable of the Declaration need to wrap a modified
variable keyword arguments may be passed (overriding e.g.
the ``value`` of the Variable instance).
Examples
========
>>> from sympy.codegen.ast import Variable, NoneToken
>>> x = Variable('x')
>>> decl1 = x.as_Declaration()
>>> # value is special NoneToken() which must be tested with == operator
>>> decl1.variable.value is None # won't work
False
>>> decl1.variable.value == None # not PEP-8 compliant
True
>>> decl1.variable.value == NoneToken() # OK
True
>>> decl2 = x.as_Declaration(value=42.0)
>>> decl2.variable.value == 42
True
"""
kw = self.kwargs()
kw.update(kwargs)
return Declaration(self.func(**kw))
def _relation(self, rhs, op):
try:
rhs = _sympify(rhs)
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, rhs))
return op(self, rhs, evaluate=False)
__lt__ = lambda self, other: self._relation(other, Lt)
__le__ = lambda self, other: self._relation(other, Le)
__ge__ = lambda self, other: self._relation(other, Ge)
__gt__ = lambda self, other: self._relation(other, Gt)
class Pointer(Variable):
""" Represents a pointer. See ``Variable``.
Examples
========
Can create instances of ``Element``:
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Pointer
>>> i = Symbol('i', integer=True)
>>> p = Pointer('x')
>>> p[i+1]
Element(x, indices=(i + 1,))
"""
def __getitem__(self, key):
try:
return Element(self.symbol, key)
except TypeError:
return Element(self.symbol, (key,))
class Element(Token):
""" Element in (a possibly N-dimensional) array.
Examples
========
>>> from sympy.codegen.ast import Element
>>> elem = Element('x', 'ijk')
>>> elem.symbol.name == 'x'
True
>>> elem.indices
(i, j, k)
>>> from sympy import ccode
>>> ccode(elem)
'x[i][j][k]'
>>> ccode(Element('x', 'ijk', strides='lmn', offset='o'))
'x[i*l + j*m + k*n + o]'
"""
__slots__ = ('symbol', 'indices', 'strides', 'offset')
defaults = {'strides': none, 'offset': none}
_construct_symbol = staticmethod(sympify)
_construct_indices = staticmethod(lambda arg: Tuple(*arg))
_construct_strides = staticmethod(lambda arg: Tuple(*arg))
_construct_offset = staticmethod(sympify)
class Declaration(Token):
""" Represents a variable declaration
Parameters
==========
variable : Variable
Examples
========
>>> from sympy.codegen.ast import Declaration, NoneToken, untyped
>>> z = Declaration('z')
>>> z.variable.type == untyped
True
>>> # value is special NoneToken() which must be tested with == operator
>>> z.variable.value is None # won't work
False
>>> z.variable.value == None # not PEP-8 compliant
True
>>> z.variable.value == NoneToken() # OK
True
"""
__slots__ = ('variable',)
_construct_variable = Variable
class While(Token):
""" Represents a 'for-loop' in the code.
Expressions are of the form:
"while condition:
body..."
Parameters
==========
condition : expression convertible to Boolean
body : CodeBlock or iterable
When passed an iterable it is used to instantiate a CodeBlock.
Examples
========
>>> from sympy import symbols, Gt, Abs
>>> from sympy.codegen import aug_assign, Assignment, While
>>> x, dx = symbols('x dx')
>>> expr = 1 - x**2
>>> whl = While(Gt(Abs(dx), 1e-9), [
... Assignment(dx, -expr/expr.diff(x)),
... aug_assign(x, '+', dx)
... ])
"""
__slots__ = ('condition', 'body')
_construct_condition = staticmethod(lambda cond: _sympify(cond))
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class Scope(Token):
""" Represents a scope in the code.
Parameters
==========
body : CodeBlock or iterable
When passed an iterable it is used to instantiate a CodeBlock.
"""
__slots__ = ('body',)
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class Stream(Token):
""" Represents a stream.
There are two predefined Stream instances ``stdout`` & ``stderr``.
Parameters
==========
name : str
Examples
========
>>> from sympy import Symbol
>>> from sympy.printing.pycode import pycode
>>> from sympy.codegen.ast import Print, stderr, QuotedString
>>> print(pycode(Print(['x'], file=stderr)))
print(x, file=sys.stderr)
>>> x = Symbol('x')
>>> print(pycode(Print([QuotedString('x')], file=stderr))) # print literally "x"
print("x", file=sys.stderr)
"""
__slots__ = ('name',)
_construct_name = String
stdout = Stream('stdout')
stderr = Stream('stderr')
class Print(Token):
""" Represents print command in the code.
Parameters
==========
formatstring : str
*args : Basic instances (or convertible to such through sympify)
Examples
========
>>> from sympy.codegen.ast import Print
>>> from sympy.printing.pycode import pycode
>>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g")))
print("coordinate: %12.5g %12.5g" % (x, y))
"""
__slots__ = ('print_args', 'format_string', 'file')
defaults = {'format_string': none, 'file': none}
_construct_print_args = staticmethod(_mk_Tuple)
_construct_format_string = QuotedString
_construct_file = Stream
class FunctionPrototype(Node):
""" Represents a function prototype
Allows the user to generate forward declaration in e.g. C/C++.
Parameters
==========
return_type : Type
name : str
parameters: iterable of Variable instances
attrs : iterable of Attribute instances
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import real, FunctionPrototype
>>> from sympy.printing import ccode
>>> x, y = symbols('x y', real=True)
>>> fp = FunctionPrototype(real, 'foo', [x, y])
>>> ccode(fp)
'double foo(double x, double y)'
"""
__slots__ = ('return_type', 'name', 'parameters', 'attrs')
_construct_return_type = Type
_construct_name = String
@staticmethod
def _construct_parameters(args):
def _var(arg):
if isinstance(arg, Declaration):
return arg.variable
elif isinstance(arg, Variable):
return arg
else:
return Variable.deduced(arg)
return Tuple(*map(_var, args))
@classmethod
def from_FunctionDefinition(cls, func_def):
if not isinstance(func_def, FunctionDefinition):
raise TypeError("func_def is not an instance of FunctionDefiniton")
return cls(**func_def.kwargs(exclude=('body',)))
class FunctionDefinition(FunctionPrototype):
""" Represents a function definition in the code.
Parameters
==========
return_type : Type
name : str
parameters: iterable of Variable instances
body : CodeBlock or iterable
attrs : iterable of Attribute instances
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import real, FunctionPrototype
>>> from sympy.printing import ccode
>>> x, y = symbols('x y', real=True)
>>> fp = FunctionPrototype(real, 'foo', [x, y])
>>> ccode(fp)
'double foo(double x, double y)'
>>> from sympy.codegen.ast import FunctionDefinition, Return
>>> body = [Return(x*y)]
>>> fd = FunctionDefinition.from_FunctionPrototype(fp, body)
>>> print(ccode(fd))
double foo(double x, double y){
return x*y;
}
"""
__slots__ = FunctionPrototype.__slots__[:-1] + ('body', 'attrs')
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
@classmethod
def from_FunctionPrototype(cls, func_proto, body):
if not isinstance(func_proto, FunctionPrototype):
raise TypeError("func_proto is not an instance of FunctionPrototype")
return cls(body=body, **func_proto.kwargs())
class Return(Basic):
""" Represents a return command in the code. """
class FunctionCall(Token, Expr):
""" Represents a call to a function in the code.
Parameters
==========
name : str
function_args : Tuple
Examples
========
>>> from sympy.codegen.ast import FunctionCall
>>> from sympy.printing.pycode import pycode
>>> fcall = FunctionCall('foo', 'bar baz'.split())
>>> print(pycode(fcall))
foo(bar, baz)
"""
__slots__ = ('name', 'function_args')
_construct_name = String
_construct_function_args = staticmethod(lambda args: Tuple(*args))
|
0fb522feaf94491631fa068070f0d31ab30558ec2bffa82449da30ab07927557 | """
This module contains SymPy functions mathcin corresponding to special math functions in the
C standard library (since C99, also available in C++11).
The functions defined in this module allows the user to express functions such as ``expm1``
as a SymPy function for symbolic manipulation.
"""
from sympy.core.function import ArgumentIndexError, Function
from sympy.core.numbers import Rational
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.miscellaneous import sqrt
def _expm1(x):
return exp(x) - S.One
class expm1(Function):
"""
Represents the exponential function minus one.
The benefit of using ``expm1(x)`` over ``exp(x) - 1``
is that the latter is prone to cancellation under finite precision
arithmetic when x is close to zero.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import expm1
>>> '%.0e' % expm1(1e-99).evalf()
'1e-99'
>>> from math import exp
>>> exp(1e-99) - 1
0.0
>>> expm1(x).diff(x)
exp(x)
See Also
========
log1p
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return exp(*self.args)
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _expm1(*self.args)
def _eval_rewrite_as_exp(self, arg, **kwargs):
return exp(arg) - S.One
_eval_rewrite_as_tractable = _eval_rewrite_as_exp
@classmethod
def eval(cls, arg):
exp_arg = exp.eval(arg)
if exp_arg is not None:
return exp_arg - S.One
def _eval_is_real(self):
return self.args[0].is_real
def _eval_is_finite(self):
return self.args[0].is_finite
def _log1p(x):
return log(x + S.One)
class log1p(Function):
"""
Represents the natural logarithm of a number plus one.
The benefit of using ``log1p(x)`` over ``log(x + 1)``
is that the latter is prone to cancellation under finite precision
arithmetic when x is close to zero.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import log1p
>>> from sympy.core.function import expand_log
>>> '%.0e' % expand_log(log1p(1e-99)).evalf()
'1e-99'
>>> from math import log
>>> log(1 + 1e-99)
0.0
>>> log1p(x).diff(x)
1/(x + 1)
See Also
========
expm1
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return S.One/(self.args[0] + S.One)
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _log1p(*self.args)
def _eval_rewrite_as_log(self, arg, **kwargs):
return _log1p(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_log
@classmethod
def eval(cls, arg):
if arg.is_Rational:
return log(arg + S.One)
elif not arg.is_Float: # not safe to add 1 to Float
return log.eval(arg + S.One)
elif arg.is_number:
return log(Rational(arg) + S.One)
def _eval_is_real(self):
return (self.args[0] + S.One).is_nonnegative
def _eval_is_finite(self):
if (self.args[0] + S.One).is_zero:
return False
return self.args[0].is_finite
def _eval_is_positive(self):
return self.args[0].is_positive
def _eval_is_zero(self):
return self.args[0].is_zero
def _eval_is_nonnegative(self):
return self.args[0].is_nonnegative
_Two = S(2)
def _exp2(x):
return Pow(_Two, x)
class exp2(Function):
"""
Represents the exponential function with base two.
The benefit of using ``exp2(x)`` over ``2**x``
is that the latter is not as efficient under finite precision
arithmetic.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import exp2
>>> exp2(2).evalf() == 4
True
>>> exp2(x).diff(x)
log(2)*exp2(x)
See Also
========
log2
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return self*log(_Two)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
return _exp2(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
def _eval_expand_func(self, **hints):
return _exp2(*self.args)
@classmethod
def eval(cls, arg):
if arg.is_number:
return _exp2(arg)
def _log2(x):
return log(x)/log(_Two)
class log2(Function):
"""
Represents the logarithm function with base two.
The benefit of using ``log2(x)`` over ``log(x)/log(2)``
is that the latter is not as efficient under finite precision
arithmetic.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import log2
>>> log2(4).evalf() == 2
True
>>> log2(x).diff(x)
1/(x*log(2))
See Also
========
exp2
log10
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return S.One/(log(_Two)*self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
if arg.is_number:
result = log.eval(arg, base=_Two)
if result.is_Atom:
return result
elif arg.is_Pow and arg.base == _Two:
return arg.exp
def _eval_evalf(self, *args, **kwargs):
return self.rewrite(log).evalf(*args, **kwargs)
def _eval_expand_func(self, **hints):
return _log2(*self.args)
def _eval_rewrite_as_log(self, arg, **kwargs):
return _log2(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _fma(x, y, z):
return x*y + z
class fma(Function):
"""
Represents "fused multiply add".
The benefit of using ``fma(x, y, z)`` over ``x*y + z``
is that, under finite precision arithmetic, the former is
supported by special instructions on some CPUs.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.codegen.cfunctions import fma
>>> fma(x, y, z).diff(x)
y
"""
nargs = 3
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex in (1, 2):
return self.args[2 - argindex]
elif argindex == 3:
return S.One
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _fma(*self.args)
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
return _fma(arg)
_Ten = S(10)
def _log10(x):
return log(x)/log(_Ten)
class log10(Function):
"""
Represents the logarithm function with base ten.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import log10
>>> log10(100).evalf() == 2
True
>>> log10(x).diff(x)
1/(x*log(10))
See Also
========
log2
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return S.One/(log(_Ten)*self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
if arg.is_number:
result = log.eval(arg, base=_Ten)
if result.is_Atom:
return result
elif arg.is_Pow and arg.base == _Ten:
return arg.exp
def _eval_expand_func(self, **hints):
return _log10(*self.args)
def _eval_rewrite_as_log(self, arg, **kwargs):
return _log10(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _Sqrt(x):
return Pow(x, S.Half)
class Sqrt(Function): # 'sqrt' already defined in sympy.functions.elementary.miscellaneous
"""
Represents the square root function.
The reason why one would use ``Sqrt(x)`` over ``sqrt(x)``
is that the latter is internally represented as ``Pow(x, S.Half)`` which
may not be what one wants when doing code-generation.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import Sqrt
>>> Sqrt(x)
Sqrt(x)
>>> Sqrt(x).diff(x)
1/(2*sqrt(x))
See Also
========
Cbrt
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return Pow(self.args[0], Rational(-1, 2))/_Two
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _Sqrt(*self.args)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
return _Sqrt(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
def _Cbrt(x):
return Pow(x, Rational(1, 3))
class Cbrt(Function): # 'cbrt' already defined in sympy.functions.elementary.miscellaneous
"""
Represents the cube root function.
The reason why one would use ``Cbrt(x)`` over ``cbrt(x)``
is that the latter is internally represented as ``Pow(x, Rational(1, 3))`` which
may not be what one wants when doing code-generation.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import Cbrt
>>> Cbrt(x)
Cbrt(x)
>>> Cbrt(x).diff(x)
1/(3*x**(2/3))
See Also
========
Sqrt
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return Pow(self.args[0], Rational(-_Two/3))/3
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _Cbrt(*self.args)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
return _Cbrt(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
def _hypot(x, y):
return sqrt(Pow(x, 2) + Pow(y, 2))
class hypot(Function):
"""
Represents the hypotenuse function.
The hypotenuse function is provided by e.g. the math library
in the C99 standard, hence one may want to represent the function
symbolically when doing code-generation.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.codegen.cfunctions import hypot
>>> hypot(3, 4).evalf() == 5
True
>>> hypot(x, y)
hypot(x, y)
>>> hypot(x, y).diff(x)
x/hypot(x, y)
"""
nargs = 2
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex in (1, 2):
return 2*self.args[argindex-1]/(_Two*self.func(*self.args))
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _hypot(*self.args)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
return _hypot(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
be5cccb3c3a40b906ee2c20ff801769987ffb48a3b528e2bd83008fcb3616733 | from sympy.printing.c import C99CodePrinter
def render_as_source_file(content, Printer=C99CodePrinter, settings=None):
""" Renders a C source file (with required #include statements) """
printer = Printer(settings or {})
code_str = printer.doprint(content)
includes = '\n'.join(['#include <%s>' % h for h in printer.headers])
return includes + '\n\n' + code_str
|
93e9b13092abfd0fda7d3cba36b28d97f3765d02c199275902cb0ee610689cd6 | from itertools import chain
from sympy.codegen.fnodes import Module
from sympy.core.symbol import Dummy
from sympy.printing.fortran import FCodePrinter
""" This module collects utilities for rendering Fortran code. """
def render_as_module(definitions, name, declarations=(), printer_settings=None):
""" Creates a ``Module`` instance and renders it as a string.
This generates Fortran source code for a module with the correct ``use`` statements.
Parameters
==========
definitions : iterable
Passed to :class:`sympy.codegen.fnodes.Module`.
name : str
Passed to :class:`sympy.codegen.fnodes.Module`.
declarations : iterable
Passed to :class:`sympy.codegen.fnodes.Module`. It will be extended with
use statements, 'implicit none' and public list generated from ``definitions``.
printer_settings : dict
Passed to ``FCodePrinter`` (default: ``{'standard': 2003, 'source_format': 'free'}``).
"""
printer_settings = printer_settings or {'standard': 2003, 'source_format': 'free'}
printer = FCodePrinter(printer_settings)
dummy = Dummy()
if isinstance(definitions, Module):
raise ValueError("This function expects to construct a module on its own.")
mod = Module(name, chain(declarations, [dummy]), definitions)
fstr = printer.doprint(mod)
module_use_str = ' %s\n' % ' \n'.join(['use %s, only: %s' % (k, ', '.join(v)) for
k, v in printer.module_uses.items()])
module_use_str += ' implicit none\n'
module_use_str += ' private\n'
module_use_str += ' public %s\n' % ', '.join([str(node.name) for node in definitions if getattr(node, 'name', None)])
return fstr.replace(printer.doprint(dummy), module_use_str)
|
076385f0c02c6909def3fe4032a00099f48f4aabc63f21ae6d609a10136c5d15 | """
module for generating C, C++, Fortran77, Fortran90, Julia, Rust
and Octave/Matlab routines that evaluate sympy expressions.
This module is work in progress.
Only the milestones with a '+' character in the list below have been completed.
--- How is sympy.utilities.codegen different from sympy.printing.ccode? ---
We considered the idea to extend the printing routines for sympy functions in
such a way that it prints complete compilable code, but this leads to a few
unsurmountable issues that can only be tackled with dedicated code generator:
- For C, one needs both a code and a header file, while the printing routines
generate just one string. This code generator can be extended to support
.pyf files for f2py.
- SymPy functions are not concerned with programming-technical issues, such
as input, output and input-output arguments. Other examples are contiguous
or non-contiguous arrays, including headers of other libraries such as gsl
or others.
- It is highly interesting to evaluate several sympy functions in one C
routine, eventually sharing common intermediate results with the help
of the cse routine. This is more than just printing.
- From the programming perspective, expressions with constants should be
evaluated in the code generator as much as possible. This is different
for printing.
--- Basic assumptions ---
* A generic Routine data structure describes the routine that must be
translated into C/Fortran/... code. This data structure covers all
features present in one or more of the supported languages.
* Descendants from the CodeGen class transform multiple Routine instances
into compilable code. Each derived class translates into a specific
language.
* In many cases, one wants a simple workflow. The friendly functions in the
last part are a simple api on top of the Routine/CodeGen stuff. They are
easier to use, but are less powerful.
--- Milestones ---
+ First working version with scalar input arguments, generating C code,
tests
+ Friendly functions that are easier to use than the rigorous
Routine/CodeGen workflow.
+ Integer and Real numbers as input and output
+ Output arguments
+ InputOutput arguments
+ Sort input/output arguments properly
+ Contiguous array arguments (numpy matrices)
+ Also generate .pyf code for f2py (in autowrap module)
+ Isolate constants and evaluate them beforehand in double precision
+ Fortran 90
+ Octave/Matlab
- Common Subexpression Elimination
- User defined comments in the generated code
- Optional extra include lines for libraries/objects that can eval special
functions
- Test other C compilers and libraries: gcc, tcc, libtcc, gcc+gsl, ...
- Contiguous array arguments (sympy matrices)
- Non-contiguous array arguments (sympy matrices)
- ccode must raise an error when it encounters something that can not be
translated into c. ccode(integrate(sin(x)/x, x)) does not make sense.
- Complex numbers as input and output
- A default complex datatype
- Include extra information in the header: date, user, hostname, sha1
hash, ...
- Fortran 77
- C++
- Python
- Julia
- Rust
- ...
"""
import os
import textwrap
from sympy import __version__ as sympy_version
from sympy.core import Symbol, S, Tuple, Equality, Function, Basic
from sympy.core.compatibility import is_sequence, StringIO
from sympy.printing.c import c_code_printers
from sympy.printing.codeprinter import AssignmentError
from sympy.printing.fortran import FCodePrinter
from sympy.printing.julia import JuliaCodePrinter
from sympy.printing.octave import OctaveCodePrinter
from sympy.printing.rust import RustCodePrinter
from sympy.tensor import Idx, Indexed, IndexedBase
from sympy.matrices import (MatrixSymbol, ImmutableMatrix, MatrixBase,
MatrixExpr, MatrixSlice)
__all__ = [
# description of routines
"Routine", "DataType", "default_datatypes", "get_default_datatype",
"Argument", "InputArgument", "OutputArgument", "Result",
# routines -> code
"CodeGen", "CCodeGen", "FCodeGen", "JuliaCodeGen", "OctaveCodeGen",
"RustCodeGen",
# friendly functions
"codegen", "make_routine",
]
#
# Description of routines
#
class Routine:
"""Generic description of evaluation routine for set of expressions.
A CodeGen class can translate instances of this class into code in a
particular language. The routine specification covers all the features
present in these languages. The CodeGen part must raise an exception
when certain features are not present in the target language. For
example, multiple return values are possible in Python, but not in C or
Fortran. Another example: Fortran and Python support complex numbers,
while C does not.
"""
def __init__(self, name, arguments, results, local_vars, global_vars):
"""Initialize a Routine instance.
Parameters
==========
name : string
Name of the routine.
arguments : list of Arguments
These are things that appear in arguments of a routine, often
appearing on the right-hand side of a function call. These are
commonly InputArguments but in some languages, they can also be
OutputArguments or InOutArguments (e.g., pass-by-reference in C
code).
results : list of Results
These are the return values of the routine, often appearing on
the left-hand side of a function call. The difference between
Results and OutputArguments and when you should use each is
language-specific.
local_vars : list of Results
These are variables that will be defined at the beginning of the
function.
global_vars : list of Symbols
Variables which will not be passed into the function.
"""
# extract all input symbols and all symbols appearing in an expression
input_symbols = set()
symbols = set()
for arg in arguments:
if isinstance(arg, OutputArgument):
symbols.update(arg.expr.free_symbols - arg.expr.atoms(Indexed))
elif isinstance(arg, InputArgument):
input_symbols.add(arg.name)
elif isinstance(arg, InOutArgument):
input_symbols.add(arg.name)
symbols.update(arg.expr.free_symbols - arg.expr.atoms(Indexed))
else:
raise ValueError("Unknown Routine argument: %s" % arg)
for r in results:
if not isinstance(r, Result):
raise ValueError("Unknown Routine result: %s" % r)
symbols.update(r.expr.free_symbols - r.expr.atoms(Indexed))
local_symbols = set()
for r in local_vars:
if isinstance(r, Result):
symbols.update(r.expr.free_symbols - r.expr.atoms(Indexed))
local_symbols.add(r.name)
else:
local_symbols.add(r)
symbols = {s.label if isinstance(s, Idx) else s for s in symbols}
# Check that all symbols in the expressions are covered by
# InputArguments/InOutArguments---subset because user could
# specify additional (unused) InputArguments or local_vars.
notcovered = symbols.difference(
input_symbols.union(local_symbols).union(global_vars))
if notcovered != set():
raise ValueError("Symbols needed for output are not in input " +
", ".join([str(x) for x in notcovered]))
self.name = name
self.arguments = arguments
self.results = results
self.local_vars = local_vars
self.global_vars = global_vars
def __str__(self):
return self.__class__.__name__ + "({name!r}, {arguments}, {results}, {local_vars}, {global_vars})".format(**self.__dict__)
__repr__ = __str__
@property
def variables(self):
"""Returns a set of all variables possibly used in the routine.
For routines with unnamed return values, the dummies that may or
may not be used will be included in the set.
"""
v = set(self.local_vars)
for arg in self.arguments:
v.add(arg.name)
for res in self.results:
v.add(res.result_var)
return v
@property
def result_variables(self):
"""Returns a list of OutputArgument, InOutArgument and Result.
If return values are present, they are at the end ot the list.
"""
args = [arg for arg in self.arguments if isinstance(
arg, (OutputArgument, InOutArgument))]
args.extend(self.results)
return args
class DataType:
"""Holds strings for a certain datatype in different languages."""
def __init__(self, cname, fname, pyname, jlname, octname, rsname):
self.cname = cname
self.fname = fname
self.pyname = pyname
self.jlname = jlname
self.octname = octname
self.rsname = rsname
default_datatypes = {
"int": DataType("int", "INTEGER*4", "int", "", "", "i32"),
"float": DataType("double", "REAL*8", "float", "", "", "f64"),
"complex": DataType("double", "COMPLEX*16", "complex", "", "", "float") #FIXME:
# complex is only supported in fortran, python, julia, and octave.
# So to not break c or rust code generation, we stick with double or
# float, respecitvely (but actually should raise an exception for
# explicitly complex variables (x.is_complex==True))
}
COMPLEX_ALLOWED = False
def get_default_datatype(expr, complex_allowed=None):
"""Derives an appropriate datatype based on the expression."""
if complex_allowed is None:
complex_allowed = COMPLEX_ALLOWED
if complex_allowed:
final_dtype = "complex"
else:
final_dtype = "float"
if expr.is_integer:
return default_datatypes["int"]
elif expr.is_real:
return default_datatypes["float"]
elif isinstance(expr, MatrixBase):
#check all entries
dt = "int"
for element in expr:
if dt == "int" and not element.is_integer:
dt = "float"
if dt == "float" and not element.is_real:
return default_datatypes[final_dtype]
return default_datatypes[dt]
else:
return default_datatypes[final_dtype]
class Variable:
"""Represents a typed variable."""
def __init__(self, name, datatype=None, dimensions=None, precision=None):
"""Return a new variable.
Parameters
==========
name : Symbol or MatrixSymbol
datatype : optional
When not given, the data type will be guessed based on the
assumptions on the symbol argument.
dimension : sequence containing tupes, optional
If present, the argument is interpreted as an array, where this
sequence of tuples specifies (lower, upper) bounds for each
index of the array.
precision : int, optional
Controls the precision of floating point constants.
"""
if not isinstance(name, (Symbol, MatrixSymbol)):
raise TypeError("The first argument must be a sympy symbol.")
if datatype is None:
datatype = get_default_datatype(name)
elif not isinstance(datatype, DataType):
raise TypeError("The (optional) `datatype' argument must be an "
"instance of the DataType class.")
if dimensions and not isinstance(dimensions, (tuple, list)):
raise TypeError(
"The dimension argument must be a sequence of tuples")
self._name = name
self._datatype = {
'C': datatype.cname,
'FORTRAN': datatype.fname,
'JULIA': datatype.jlname,
'OCTAVE': datatype.octname,
'PYTHON': datatype.pyname,
'RUST': datatype.rsname,
}
self.dimensions = dimensions
self.precision = precision
def __str__(self):
return "%s(%r)" % (self.__class__.__name__, self.name)
__repr__ = __str__
@property
def name(self):
return self._name
def get_datatype(self, language):
"""Returns the datatype string for the requested language.
Examples
========
>>> from sympy import Symbol
>>> from sympy.utilities.codegen import Variable
>>> x = Variable(Symbol('x'))
>>> x.get_datatype('c')
'double'
>>> x.get_datatype('fortran')
'REAL*8'
"""
try:
return self._datatype[language.upper()]
except KeyError:
raise CodeGenError("Has datatypes for languages: %s" %
", ".join(self._datatype))
class Argument(Variable):
"""An abstract Argument data structure: a name and a data type.
This structure is refined in the descendants below.
"""
pass
class InputArgument(Argument):
pass
class ResultBase:
"""Base class for all "outgoing" information from a routine.
Objects of this class stores a sympy expression, and a sympy object
representing a result variable that will be used in the generated code
only if necessary.
"""
def __init__(self, expr, result_var):
self.expr = expr
self.result_var = result_var
def __str__(self):
return "%s(%r, %r)" % (self.__class__.__name__, self.expr,
self.result_var)
__repr__ = __str__
class OutputArgument(Argument, ResultBase):
"""OutputArgument are always initialized in the routine."""
def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None):
"""Return a new variable.
Parameters
==========
name : Symbol, MatrixSymbol
The name of this variable. When used for code generation, this
might appear, for example, in the prototype of function in the
argument list.
result_var : Symbol, Indexed
Something that can be used to assign a value to this variable.
Typically the same as `name` but for Indexed this should be e.g.,
"y[i]" whereas `name` should be the Symbol "y".
expr : object
The expression that should be output, typically a SymPy
expression.
datatype : optional
When not given, the data type will be guessed based on the
assumptions on the symbol argument.
dimension : sequence containing tupes, optional
If present, the argument is interpreted as an array, where this
sequence of tuples specifies (lower, upper) bounds for each
index of the array.
precision : int, optional
Controls the precision of floating point constants.
"""
Argument.__init__(self, name, datatype, dimensions, precision)
ResultBase.__init__(self, expr, result_var)
def __str__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.result_var, self.expr)
__repr__ = __str__
class InOutArgument(Argument, ResultBase):
"""InOutArgument are never initialized in the routine."""
def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None):
if not datatype:
datatype = get_default_datatype(expr)
Argument.__init__(self, name, datatype, dimensions, precision)
ResultBase.__init__(self, expr, result_var)
__init__.__doc__ = OutputArgument.__init__.__doc__
def __str__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.expr,
self.result_var)
__repr__ = __str__
class Result(Variable, ResultBase):
"""An expression for a return value.
The name result is used to avoid conflicts with the reserved word
"return" in the python language. It is also shorter than ReturnValue.
These may or may not need a name in the destination (e.g., "return(x*y)"
might return a value without ever naming it).
"""
def __init__(self, expr, name=None, result_var=None, datatype=None,
dimensions=None, precision=None):
"""Initialize a return value.
Parameters
==========
expr : SymPy expression
name : Symbol, MatrixSymbol, optional
The name of this return variable. When used for code generation,
this might appear, for example, in the prototype of function in a
list of return values. A dummy name is generated if omitted.
result_var : Symbol, Indexed, optional
Something that can be used to assign a value to this variable.
Typically the same as `name` but for Indexed this should be e.g.,
"y[i]" whereas `name` should be the Symbol "y". Defaults to
`name` if omitted.
datatype : optional
When not given, the data type will be guessed based on the
assumptions on the expr argument.
dimension : sequence containing tupes, optional
If present, this variable is interpreted as an array,
where this sequence of tuples specifies (lower, upper)
bounds for each index of the array.
precision : int, optional
Controls the precision of floating point constants.
"""
# Basic because it is the base class for all types of expressions
if not isinstance(expr, (Basic, MatrixBase)):
raise TypeError("The first argument must be a sympy expression.")
if name is None:
name = 'result_%d' % abs(hash(expr))
if datatype is None:
#try to infer data type from the expression
datatype = get_default_datatype(expr)
if isinstance(name, str):
if isinstance(expr, (MatrixBase, MatrixExpr)):
name = MatrixSymbol(name, *expr.shape)
else:
name = Symbol(name)
if result_var is None:
result_var = name
Variable.__init__(self, name, datatype=datatype,
dimensions=dimensions, precision=precision)
ResultBase.__init__(self, expr, result_var)
def __str__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__, self.expr, self.name,
self.result_var)
__repr__ = __str__
#
# Transformation of routine objects into code
#
class CodeGen:
"""Abstract class for the code generators."""
printer = None # will be set to an instance of a CodePrinter subclass
def _indent_code(self, codelines):
return self.printer.indent_code(codelines)
def _printer_method_with_settings(self, method, settings=None, *args, **kwargs):
settings = settings or {}
ori = {k: self.printer._settings[k] for k in settings}
for k, v in settings.items():
self.printer._settings[k] = v
result = getattr(self.printer, method)(*args, **kwargs)
for k, v in ori.items():
self.printer._settings[k] = v
return result
def _get_symbol(self, s):
"""Returns the symbol as fcode prints it."""
if self.printer._settings['human']:
expr_str = self.printer.doprint(s)
else:
constants, not_supported, expr_str = self.printer.doprint(s)
if constants or not_supported:
raise ValueError("Failed to print %s" % str(s))
return expr_str.strip()
def __init__(self, project="project", cse=False):
"""Initialize a code generator.
Derived classes will offer more options that affect the generated
code.
"""
self.project = project
self.cse = cse
def routine(self, name, expr, argument_sequence=None, global_vars=None):
"""Creates an Routine object that is appropriate for this language.
This implementation is appropriate for at least C/Fortran. Subclasses
can override this if necessary.
Here, we assume at most one return value (the l-value) which must be
scalar. Additional outputs are OutputArguments (e.g., pointers on
right-hand-side or pass-by-reference). Matrices are always returned
via OutputArguments. If ``argument_sequence`` is None, arguments will
be ordered alphabetically, but with all InputArguments first, and then
OutputArgument and InOutArguments.
"""
if self.cse:
from sympy.simplify.cse_main import cse
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
for e in expr:
if not e.is_Equality:
raise CodeGenError("Lists of expressions must all be Equalities. {} is not.".format(e))
# create a list of right hand sides and simplify them
rhs = [e.rhs for e in expr]
common, simplified = cse(rhs)
# pack the simplified expressions back up with their left hand sides
expr = [Equality(e.lhs, rhs) for e, rhs in zip(expr, simplified)]
else:
rhs = [expr]
if isinstance(expr, Equality):
common, simplified = cse(expr.rhs) #, ignore=in_out_args)
expr = Equality(expr.lhs, simplified[0])
else:
common, simplified = cse(expr)
expr = simplified
local_vars = [Result(b,a) for a,b in common]
local_symbols = {a for a,_ in common}
local_expressions = Tuple(*[b for _,b in common])
else:
local_expressions = Tuple()
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
expressions = Tuple(*expr)
else:
expressions = Tuple(expr)
if self.cse:
if {i.label for i in expressions.atoms(Idx)} != set():
raise CodeGenError("CSE and Indexed expressions do not play well together yet")
else:
# local variables for indexed expressions
local_vars = {i.label for i in expressions.atoms(Idx)}
local_symbols = local_vars
# global variables
global_vars = set() if global_vars is None else set(global_vars)
# symbols that should be arguments
symbols = (expressions.free_symbols | local_expressions.free_symbols) - local_symbols - global_vars
new_symbols = set()
new_symbols.update(symbols)
for symbol in symbols:
if isinstance(symbol, Idx):
new_symbols.remove(symbol)
new_symbols.update(symbol.args[1].free_symbols)
if isinstance(symbol, Indexed):
new_symbols.remove(symbol)
symbols = new_symbols
# Decide whether to use output argument or return value
return_val = []
output_args = []
for expr in expressions:
if isinstance(expr, Equality):
out_arg = expr.lhs
expr = expr.rhs
if isinstance(out_arg, Indexed):
dims = tuple([ (S.Zero, dim - 1) for dim in out_arg.shape])
symbol = out_arg.base.label
elif isinstance(out_arg, Symbol):
dims = []
symbol = out_arg
elif isinstance(out_arg, MatrixSymbol):
dims = tuple([ (S.Zero, dim - 1) for dim in out_arg.shape])
symbol = out_arg
else:
raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
"can define output arguments.")
if expr.has(symbol):
output_args.append(
InOutArgument(symbol, out_arg, expr, dimensions=dims))
else:
output_args.append(
OutputArgument(symbol, out_arg, expr, dimensions=dims))
# remove duplicate arguments when they are not local variables
if symbol not in local_vars:
# avoid duplicate arguments
symbols.remove(symbol)
elif isinstance(expr, (ImmutableMatrix, MatrixSlice)):
# Create a "dummy" MatrixSymbol to use as the Output arg
out_arg = MatrixSymbol('out_%s' % abs(hash(expr)), *expr.shape)
dims = tuple([(S.Zero, dim - 1) for dim in out_arg.shape])
output_args.append(
OutputArgument(out_arg, out_arg, expr, dimensions=dims))
else:
return_val.append(Result(expr))
arg_list = []
# setup input argument list
# helper to get dimensions for data for array-like args
def dimensions(s):
return [(S.Zero, dim - 1) for dim in s.shape]
array_symbols = {}
for array in expressions.atoms(Indexed) | local_expressions.atoms(Indexed):
array_symbols[array.base.label] = array
for array in expressions.atoms(MatrixSymbol) | local_expressions.atoms(MatrixSymbol):
array_symbols[array] = array
for symbol in sorted(symbols, key=str):
if symbol in array_symbols:
array = array_symbols[symbol]
metadata = {'dimensions': dimensions(array)}
else:
metadata = {}
arg_list.append(InputArgument(symbol, **metadata))
output_args.sort(key=lambda x: str(x.name))
arg_list.extend(output_args)
if argument_sequence is not None:
# if the user has supplied IndexedBase instances, we'll accept that
new_sequence = []
for arg in argument_sequence:
if isinstance(arg, IndexedBase):
new_sequence.append(arg.label)
else:
new_sequence.append(arg)
argument_sequence = new_sequence
missing = [x for x in arg_list if x.name not in argument_sequence]
if missing:
msg = "Argument list didn't specify: {0} "
msg = msg.format(", ".join([str(m.name) for m in missing]))
raise CodeGenArgumentListError(msg, missing)
# create redundant arguments to produce the requested sequence
name_arg_dict = {x.name: x for x in arg_list}
new_args = []
for symbol in argument_sequence:
try:
new_args.append(name_arg_dict[symbol])
except KeyError:
if isinstance(symbol, (IndexedBase, MatrixSymbol)):
metadata = {'dimensions': dimensions(symbol)}
else:
metadata = {}
new_args.append(InputArgument(symbol, **metadata))
arg_list = new_args
return Routine(name, arg_list, return_val, local_vars, global_vars)
def write(self, routines, prefix, to_files=False, header=True, empty=True):
"""Writes all the source code files for the given routines.
The generated source is returned as a list of (filename, contents)
tuples, or is written to files (see below). Each filename consists
of the given prefix, appended with an appropriate extension.
Parameters
==========
routines : list
A list of Routine instances to be written
prefix : string
The prefix for the output files
to_files : bool, optional
When True, the output is written to files. Otherwise, a list
of (filename, contents) tuples is returned. [default: False]
header : bool, optional
When True, a header comment is included on top of each source
file. [default: True]
empty : bool, optional
When True, empty lines are included to structure the source
files. [default: True]
"""
if to_files:
for dump_fn in self.dump_fns:
filename = "%s.%s" % (prefix, dump_fn.extension)
with open(filename, "w") as f:
dump_fn(self, routines, f, prefix, header, empty)
else:
result = []
for dump_fn in self.dump_fns:
filename = "%s.%s" % (prefix, dump_fn.extension)
contents = StringIO()
dump_fn(self, routines, contents, prefix, header, empty)
result.append((filename, contents.getvalue()))
return result
def dump_code(self, routines, f, prefix, header=True, empty=True):
"""Write the code by calling language specific methods.
The generated file contains all the definitions of the routines in
low-level code and refers to the header file if appropriate.
Parameters
==========
routines : list
A list of Routine instances.
f : file-like
Where to write the file.
prefix : string
The filename prefix, used to refer to the proper header file.
Only the basename of the prefix is used.
header : bool, optional
When True, a header comment is included on top of each source
file. [default : True]
empty : bool, optional
When True, empty lines are included to structure the source
files. [default : True]
"""
code_lines = self._preprocessor_statements(prefix)
for routine in routines:
if empty:
code_lines.append("\n")
code_lines.extend(self._get_routine_opening(routine))
code_lines.extend(self._declare_arguments(routine))
code_lines.extend(self._declare_globals(routine))
code_lines.extend(self._declare_locals(routine))
if empty:
code_lines.append("\n")
code_lines.extend(self._call_printer(routine))
if empty:
code_lines.append("\n")
code_lines.extend(self._get_routine_ending(routine))
code_lines = self._indent_code(''.join(code_lines))
if header:
code_lines = ''.join(self._get_header() + [code_lines])
if code_lines:
f.write(code_lines)
class CodeGenError(Exception):
pass
class CodeGenArgumentListError(Exception):
@property
def missing_args(self):
return self.args[1]
header_comment = """Code generated with sympy %(version)s
See http://www.sympy.org/ for more information.
This file is part of '%(project)s'
"""
class CCodeGen(CodeGen):
"""Generator for C code.
The .write() method inherited from CodeGen will output a code file and
an interface file, <prefix>.c and <prefix>.h respectively.
"""
code_extension = "c"
interface_extension = "h"
standard = 'c99'
def __init__(self, project="project", printer=None,
preprocessor_statements=None, cse=False):
super().__init__(project=project, cse=cse)
self.printer = printer or c_code_printers[self.standard.lower()]()
self.preprocessor_statements = preprocessor_statements
if preprocessor_statements is None:
self.preprocessor_statements = ['#include <math.h>']
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
code_lines.append("/" + "*"*78 + '\n')
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
code_lines.append(" *%s*\n" % line.center(76))
code_lines.append(" " + "*"*78 + "/\n")
return code_lines
def get_prototype(self, routine):
"""Returns a string for the function prototype of the routine.
If the routine has multiple result objects, an CodeGenError is
raised.
See: https://en.wikipedia.org/wiki/Function_prototype
"""
if len(routine.results) > 1:
raise CodeGenError("C only supports a single or no return value.")
elif len(routine.results) == 1:
ctype = routine.results[0].get_datatype('C')
else:
ctype = "void"
type_args = []
for arg in routine.arguments:
name = self.printer.doprint(arg.name)
if arg.dimensions or isinstance(arg, ResultBase):
type_args.append((arg.get_datatype('C'), "*%s" % name))
else:
type_args.append((arg.get_datatype('C'), name))
arguments = ", ".join([ "%s %s" % t for t in type_args])
return "%s %s(%s)" % (ctype, routine.name, arguments)
def _preprocessor_statements(self, prefix):
code_lines = []
code_lines.append('#include "{}.h"'.format(os.path.basename(prefix)))
code_lines.extend(self.preprocessor_statements)
code_lines = ['{}\n'.format(l) for l in code_lines]
return code_lines
def _get_routine_opening(self, routine):
prototype = self.get_prototype(routine)
return ["%s {\n" % prototype]
def _declare_arguments(self, routine):
# arguments are declared in prototype
return []
def _declare_globals(self, routine):
# global variables are not explicitly declared within C functions
return []
def _declare_locals(self, routine):
# Compose a list of symbols to be dereferenced in the function
# body. These are the arguments that were passed by a reference
# pointer, excluding arrays.
dereference = []
for arg in routine.arguments:
if isinstance(arg, ResultBase) and not arg.dimensions:
dereference.append(arg.name)
code_lines = []
for result in routine.local_vars:
# local variables that are simple symbols such as those used as indices into
# for loops are defined declared elsewhere.
if not isinstance(result, Result):
continue
if result.name != result.result_var:
raise CodeGen("Result variable and name should match: {}".format(result))
assign_to = result.name
t = result.get_datatype('c')
if isinstance(result.expr, (MatrixBase, MatrixExpr)):
dims = result.expr.shape
if dims[1] != 1:
raise CodeGenError("Only column vectors are supported in local variabels. Local result {} has dimensions {}".format(result, dims))
code_lines.append("{} {}[{}];\n".format(t, str(assign_to), dims[0]))
prefix = ""
else:
prefix = "const {} ".format(t)
constants, not_c, c_expr = self._printer_method_with_settings(
'doprint', dict(human=False, dereference=dereference),
result.expr, assign_to=assign_to)
for name, value in sorted(constants, key=str):
code_lines.append("double const %s = %s;\n" % (name, value))
code_lines.append("{}{}\n".format(prefix, c_expr))
return code_lines
def _call_printer(self, routine):
code_lines = []
# Compose a list of symbols to be dereferenced in the function
# body. These are the arguments that were passed by a reference
# pointer, excluding arrays.
dereference = []
for arg in routine.arguments:
if isinstance(arg, ResultBase) and not arg.dimensions:
dereference.append(arg.name)
return_val = None
for result in routine.result_variables:
if isinstance(result, Result):
assign_to = routine.name + "_result"
t = result.get_datatype('c')
code_lines.append("{} {};\n".format(t, str(assign_to)))
return_val = assign_to
else:
assign_to = result.result_var
try:
constants, not_c, c_expr = self._printer_method_with_settings(
'doprint', dict(human=False, dereference=dereference),
result.expr, assign_to=assign_to)
except AssignmentError:
assign_to = result.result_var
code_lines.append(
"%s %s;\n" % (result.get_datatype('c'), str(assign_to)))
constants, not_c, c_expr = self._printer_method_with_settings(
'doprint', dict(human=False, dereference=dereference),
result.expr, assign_to=assign_to)
for name, value in sorted(constants, key=str):
code_lines.append("double const %s = %s;\n" % (name, value))
code_lines.append("%s\n" % c_expr)
if return_val:
code_lines.append(" return %s;\n" % return_val)
return code_lines
def _get_routine_ending(self, routine):
return ["}\n"]
def dump_c(self, routines, f, prefix, header=True, empty=True):
self.dump_code(routines, f, prefix, header, empty)
dump_c.extension = code_extension # type: ignore
dump_c.__doc__ = CodeGen.dump_code.__doc__
def dump_h(self, routines, f, prefix, header=True, empty=True):
"""Writes the C header file.
This file contains all the function declarations.
Parameters
==========
routines : list
A list of Routine instances.
f : file-like
Where to write the file.
prefix : string
The filename prefix, used to construct the include guards.
Only the basename of the prefix is used.
header : bool, optional
When True, a header comment is included on top of each source
file. [default : True]
empty : bool, optional
When True, empty lines are included to structure the source
files. [default : True]
"""
if header:
print(''.join(self._get_header()), file=f)
guard_name = "%s__%s__H" % (self.project.replace(
" ", "_").upper(), prefix.replace("/", "_").upper())
# include guards
if empty:
print(file=f)
print("#ifndef %s" % guard_name, file=f)
print("#define %s" % guard_name, file=f)
if empty:
print(file=f)
# declaration of the function prototypes
for routine in routines:
prototype = self.get_prototype(routine)
print("%s;" % prototype, file=f)
# end if include guards
if empty:
print(file=f)
print("#endif", file=f)
if empty:
print(file=f)
dump_h.extension = interface_extension # type: ignore
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_c, dump_h]
class C89CodeGen(CCodeGen):
standard = 'C89'
class C99CodeGen(CCodeGen):
standard = 'C99'
class FCodeGen(CodeGen):
"""Generator for Fortran 95 code
The .write() method inherited from CodeGen will output a code file and
an interface file, <prefix>.f90 and <prefix>.h respectively.
"""
code_extension = "f90"
interface_extension = "h"
def __init__(self, project='project', printer=None):
super().__init__(project)
self.printer = printer or FCodePrinter()
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
code_lines.append("!" + "*"*78 + '\n')
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
code_lines.append("!*%s*\n" % line.center(76))
code_lines.append("!" + "*"*78 + '\n')
return code_lines
def _preprocessor_statements(self, prefix):
return []
def _get_routine_opening(self, routine):
"""Returns the opening statements of the fortran routine."""
code_list = []
if len(routine.results) > 1:
raise CodeGenError(
"Fortran only supports a single or no return value.")
elif len(routine.results) == 1:
result = routine.results[0]
code_list.append(result.get_datatype('fortran'))
code_list.append("function")
else:
code_list.append("subroutine")
args = ", ".join("%s" % self._get_symbol(arg.name)
for arg in routine.arguments)
call_sig = "{}({})\n".format(routine.name, args)
# Fortran 95 requires all lines be less than 132 characters, so wrap
# this line before appending.
call_sig = ' &\n'.join(textwrap.wrap(call_sig,
width=60,
break_long_words=False)) + '\n'
code_list.append(call_sig)
code_list = [' '.join(code_list)]
code_list.append('implicit none\n')
return code_list
def _declare_arguments(self, routine):
# argument type declarations
code_list = []
array_list = []
scalar_list = []
for arg in routine.arguments:
if isinstance(arg, InputArgument):
typeinfo = "%s, intent(in)" % arg.get_datatype('fortran')
elif isinstance(arg, InOutArgument):
typeinfo = "%s, intent(inout)" % arg.get_datatype('fortran')
elif isinstance(arg, OutputArgument):
typeinfo = "%s, intent(out)" % arg.get_datatype('fortran')
else:
raise CodeGenError("Unknown Argument type: %s" % type(arg))
fprint = self._get_symbol
if arg.dimensions:
# fortran arrays start at 1
dimstr = ", ".join(["%s:%s" % (
fprint(dim[0] + 1), fprint(dim[1] + 1))
for dim in arg.dimensions])
typeinfo += ", dimension(%s)" % dimstr
array_list.append("%s :: %s\n" % (typeinfo, fprint(arg.name)))
else:
scalar_list.append("%s :: %s\n" % (typeinfo, fprint(arg.name)))
# scalars first, because they can be used in array declarations
code_list.extend(scalar_list)
code_list.extend(array_list)
return code_list
def _declare_globals(self, routine):
# Global variables not explicitly declared within Fortran 90 functions.
# Note: a future F77 mode may need to generate "common" blocks.
return []
def _declare_locals(self, routine):
code_list = []
for var in sorted(routine.local_vars, key=str):
typeinfo = get_default_datatype(var)
code_list.append("%s :: %s\n" % (
typeinfo.fname, self._get_symbol(var)))
return code_list
def _get_routine_ending(self, routine):
"""Returns the closing statements of the fortran routine."""
if len(routine.results) == 1:
return ["end function\n"]
else:
return ["end subroutine\n"]
def get_interface(self, routine):
"""Returns a string for the function interface.
The routine should have a single result object, which can be None.
If the routine has multiple result objects, a CodeGenError is
raised.
See: https://en.wikipedia.org/wiki/Function_prototype
"""
prototype = [ "interface\n" ]
prototype.extend(self._get_routine_opening(routine))
prototype.extend(self._declare_arguments(routine))
prototype.extend(self._get_routine_ending(routine))
prototype.append("end interface\n")
return "".join(prototype)
def _call_printer(self, routine):
declarations = []
code_lines = []
for result in routine.result_variables:
if isinstance(result, Result):
assign_to = routine.name
elif isinstance(result, (OutputArgument, InOutArgument)):
assign_to = result.result_var
constants, not_fortran, f_expr = self._printer_method_with_settings(
'doprint', dict(human=False, source_format='free', standard=95),
result.expr, assign_to=assign_to)
for obj, v in sorted(constants, key=str):
t = get_default_datatype(obj)
declarations.append(
"%s, parameter :: %s = %s\n" % (t.fname, obj, v))
for obj in sorted(not_fortran, key=str):
t = get_default_datatype(obj)
if isinstance(obj, Function):
name = obj.func
else:
name = obj
declarations.append("%s :: %s\n" % (t.fname, name))
code_lines.append("%s\n" % f_expr)
return declarations + code_lines
def _indent_code(self, codelines):
return self._printer_method_with_settings(
'indent_code', dict(human=False, source_format='free'), codelines)
def dump_f95(self, routines, f, prefix, header=True, empty=True):
# check that symbols are unique with ignorecase
for r in routines:
lowercase = {str(x).lower() for x in r.variables}
orig_case = {str(x) for x in r.variables}
if len(lowercase) < len(orig_case):
raise CodeGenError("Fortran ignores case. Got symbols: %s" %
(", ".join([str(var) for var in r.variables])))
self.dump_code(routines, f, prefix, header, empty)
dump_f95.extension = code_extension # type: ignore
dump_f95.__doc__ = CodeGen.dump_code.__doc__
def dump_h(self, routines, f, prefix, header=True, empty=True):
"""Writes the interface to a header file.
This file contains all the function declarations.
Parameters
==========
routines : list
A list of Routine instances.
f : file-like
Where to write the file.
prefix : string
The filename prefix.
header : bool, optional
When True, a header comment is included on top of each source
file. [default : True]
empty : bool, optional
When True, empty lines are included to structure the source
files. [default : True]
"""
if header:
print(''.join(self._get_header()), file=f)
if empty:
print(file=f)
# declaration of the function prototypes
for routine in routines:
prototype = self.get_interface(routine)
f.write(prototype)
if empty:
print(file=f)
dump_h.extension = interface_extension # type: ignore
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_f95, dump_h]
class JuliaCodeGen(CodeGen):
"""Generator for Julia code.
The .write() method inherited from CodeGen will output a code file
<prefix>.jl.
"""
code_extension = "jl"
def __init__(self, project='project', printer=None):
super().__init__(project)
self.printer = printer or JuliaCodePrinter()
def routine(self, name, expr, argument_sequence, global_vars):
"""Specialized Routine creation for Julia."""
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
expressions = Tuple(*expr)
else:
expressions = Tuple(expr)
# local variables
local_vars = {i.label for i in expressions.atoms(Idx)}
# global variables
global_vars = set() if global_vars is None else set(global_vars)
# symbols that should be arguments
old_symbols = expressions.free_symbols - local_vars - global_vars
symbols = set()
for s in old_symbols:
if isinstance(s, Idx):
symbols.update(s.args[1].free_symbols)
elif not isinstance(s, Indexed):
symbols.add(s)
# Julia supports multiple return values
return_vals = []
output_args = []
for (i, expr) in enumerate(expressions):
if isinstance(expr, Equality):
out_arg = expr.lhs
expr = expr.rhs
symbol = out_arg
if isinstance(out_arg, Indexed):
dims = tuple([ (S.One, dim) for dim in out_arg.shape])
symbol = out_arg.base.label
output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))
if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
"can define output arguments.")
return_vals.append(Result(expr, name=symbol, result_var=out_arg))
if not expr.has(symbol):
# this is a pure output: remove from the symbols list, so
# it doesn't become an input.
symbols.remove(symbol)
else:
# we have no name for this output
return_vals.append(Result(expr, name='out%d' % (i+1)))
# setup input argument list
output_args.sort(key=lambda x: str(x.name))
arg_list = list(output_args)
array_symbols = {}
for array in expressions.atoms(Indexed):
array_symbols[array.base.label] = array
for array in expressions.atoms(MatrixSymbol):
array_symbols[array] = array
for symbol in sorted(symbols, key=str):
arg_list.append(InputArgument(symbol))
if argument_sequence is not None:
# if the user has supplied IndexedBase instances, we'll accept that
new_sequence = []
for arg in argument_sequence:
if isinstance(arg, IndexedBase):
new_sequence.append(arg.label)
else:
new_sequence.append(arg)
argument_sequence = new_sequence
missing = [x for x in arg_list if x.name not in argument_sequence]
if missing:
msg = "Argument list didn't specify: {0} "
msg = msg.format(", ".join([str(m.name) for m in missing]))
raise CodeGenArgumentListError(msg, missing)
# create redundant arguments to produce the requested sequence
name_arg_dict = {x.name: x for x in arg_list}
new_args = []
for symbol in argument_sequence:
try:
new_args.append(name_arg_dict[symbol])
except KeyError:
new_args.append(InputArgument(symbol))
arg_list = new_args
return Routine(name, arg_list, return_vals, local_vars, global_vars)
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
if line == '':
code_lines.append("#\n")
else:
code_lines.append("# %s\n" % line)
return code_lines
def _preprocessor_statements(self, prefix):
return []
def _get_routine_opening(self, routine):
"""Returns the opening statements of the routine."""
code_list = []
code_list.append("function ")
# Inputs
args = []
for i, arg in enumerate(routine.arguments):
if isinstance(arg, OutputArgument):
raise CodeGenError("Julia: invalid argument of type %s" %
str(type(arg)))
if isinstance(arg, (InputArgument, InOutArgument)):
args.append("%s" % self._get_symbol(arg.name))
args = ", ".join(args)
code_list.append("%s(%s)\n" % (routine.name, args))
code_list = [ "".join(code_list) ]
return code_list
def _declare_arguments(self, routine):
return []
def _declare_globals(self, routine):
return []
def _declare_locals(self, routine):
return []
def _get_routine_ending(self, routine):
outs = []
for result in routine.results:
if isinstance(result, Result):
# Note: name not result_var; want `y` not `y[i]` for Indexed
s = self._get_symbol(result.name)
else:
raise CodeGenError("unexpected object in Routine results")
outs.append(s)
return ["return " + ", ".join(outs) + "\nend\n"]
def _call_printer(self, routine):
declarations = []
code_lines = []
for i, result in enumerate(routine.results):
if isinstance(result, Result):
assign_to = result.result_var
else:
raise CodeGenError("unexpected object in Routine results")
constants, not_supported, jl_expr = self._printer_method_with_settings(
'doprint', dict(human=False), result.expr, assign_to=assign_to)
for obj, v in sorted(constants, key=str):
declarations.append(
"%s = %s\n" % (obj, v))
for obj in sorted(not_supported, key=str):
if isinstance(obj, Function):
name = obj.func
else:
name = obj
declarations.append(
"# unsupported: %s\n" % (name))
code_lines.append("%s\n" % (jl_expr))
return declarations + code_lines
def _indent_code(self, codelines):
# Note that indenting seems to happen twice, first
# statement-by-statement by JuliaPrinter then again here.
p = JuliaCodePrinter({'human': False})
return p.indent_code(codelines)
def dump_jl(self, routines, f, prefix, header=True, empty=True):
self.dump_code(routines, f, prefix, header, empty)
dump_jl.extension = code_extension # type: ignore
dump_jl.__doc__ = CodeGen.dump_code.__doc__
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_jl]
class OctaveCodeGen(CodeGen):
"""Generator for Octave code.
The .write() method inherited from CodeGen will output a code file
<prefix>.m.
Octave .m files usually contain one function. That function name should
match the filename (``prefix``). If you pass multiple ``name_expr`` pairs,
the latter ones are presumed to be private functions accessed by the
primary function.
You should only pass inputs to ``argument_sequence``: outputs are ordered
according to their order in ``name_expr``.
"""
code_extension = "m"
def __init__(self, project='project', printer=None):
super().__init__(project)
self.printer = printer or OctaveCodePrinter()
def routine(self, name, expr, argument_sequence, global_vars):
"""Specialized Routine creation for Octave."""
# FIXME: this is probably general enough for other high-level
# languages, perhaps its the C/Fortran one that is specialized!
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
expressions = Tuple(*expr)
else:
expressions = Tuple(expr)
# local variables
local_vars = {i.label for i in expressions.atoms(Idx)}
# global variables
global_vars = set() if global_vars is None else set(global_vars)
# symbols that should be arguments
old_symbols = expressions.free_symbols - local_vars - global_vars
symbols = set()
for s in old_symbols:
if isinstance(s, Idx):
symbols.update(s.args[1].free_symbols)
elif not isinstance(s, Indexed):
symbols.add(s)
# Octave supports multiple return values
return_vals = []
for (i, expr) in enumerate(expressions):
if isinstance(expr, Equality):
out_arg = expr.lhs
expr = expr.rhs
symbol = out_arg
if isinstance(out_arg, Indexed):
symbol = out_arg.base.label
if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
"can define output arguments.")
return_vals.append(Result(expr, name=symbol, result_var=out_arg))
if not expr.has(symbol):
# this is a pure output: remove from the symbols list, so
# it doesn't become an input.
symbols.remove(symbol)
else:
# we have no name for this output
return_vals.append(Result(expr, name='out%d' % (i+1)))
# setup input argument list
arg_list = []
array_symbols = {}
for array in expressions.atoms(Indexed):
array_symbols[array.base.label] = array
for array in expressions.atoms(MatrixSymbol):
array_symbols[array] = array
for symbol in sorted(symbols, key=str):
arg_list.append(InputArgument(symbol))
if argument_sequence is not None:
# if the user has supplied IndexedBase instances, we'll accept that
new_sequence = []
for arg in argument_sequence:
if isinstance(arg, IndexedBase):
new_sequence.append(arg.label)
else:
new_sequence.append(arg)
argument_sequence = new_sequence
missing = [x for x in arg_list if x.name not in argument_sequence]
if missing:
msg = "Argument list didn't specify: {0} "
msg = msg.format(", ".join([str(m.name) for m in missing]))
raise CodeGenArgumentListError(msg, missing)
# create redundant arguments to produce the requested sequence
name_arg_dict = {x.name: x for x in arg_list}
new_args = []
for symbol in argument_sequence:
try:
new_args.append(name_arg_dict[symbol])
except KeyError:
new_args.append(InputArgument(symbol))
arg_list = new_args
return Routine(name, arg_list, return_vals, local_vars, global_vars)
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
if line == '':
code_lines.append("%\n")
else:
code_lines.append("%% %s\n" % line)
return code_lines
def _preprocessor_statements(self, prefix):
return []
def _get_routine_opening(self, routine):
"""Returns the opening statements of the routine."""
code_list = []
code_list.append("function ")
# Outputs
outs = []
for i, result in enumerate(routine.results):
if isinstance(result, Result):
# Note: name not result_var; want `y` not `y(i)` for Indexed
s = self._get_symbol(result.name)
else:
raise CodeGenError("unexpected object in Routine results")
outs.append(s)
if len(outs) > 1:
code_list.append("[" + (", ".join(outs)) + "]")
else:
code_list.append("".join(outs))
code_list.append(" = ")
# Inputs
args = []
for i, arg in enumerate(routine.arguments):
if isinstance(arg, (OutputArgument, InOutArgument)):
raise CodeGenError("Octave: invalid argument of type %s" %
str(type(arg)))
if isinstance(arg, InputArgument):
args.append("%s" % self._get_symbol(arg.name))
args = ", ".join(args)
code_list.append("%s(%s)\n" % (routine.name, args))
code_list = [ "".join(code_list) ]
return code_list
def _declare_arguments(self, routine):
return []
def _declare_globals(self, routine):
if not routine.global_vars:
return []
s = " ".join(sorted([self._get_symbol(g) for g in routine.global_vars]))
return ["global " + s + "\n"]
def _declare_locals(self, routine):
return []
def _get_routine_ending(self, routine):
return ["end\n"]
def _call_printer(self, routine):
declarations = []
code_lines = []
for i, result in enumerate(routine.results):
if isinstance(result, Result):
assign_to = result.result_var
else:
raise CodeGenError("unexpected object in Routine results")
constants, not_supported, oct_expr = self._printer_method_with_settings(
'doprint', dict(human=False), result.expr, assign_to=assign_to)
for obj, v in sorted(constants, key=str):
declarations.append(
" %s = %s; %% constant\n" % (obj, v))
for obj in sorted(not_supported, key=str):
if isinstance(obj, Function):
name = obj.func
else:
name = obj
declarations.append(
" %% unsupported: %s\n" % (name))
code_lines.append("%s\n" % (oct_expr))
return declarations + code_lines
def _indent_code(self, codelines):
return self._printer_method_with_settings(
'indent_code', dict(human=False), codelines)
def dump_m(self, routines, f, prefix, header=True, empty=True, inline=True):
# Note used to call self.dump_code() but we need more control for header
code_lines = self._preprocessor_statements(prefix)
for i, routine in enumerate(routines):
if i > 0:
if empty:
code_lines.append("\n")
code_lines.extend(self._get_routine_opening(routine))
if i == 0:
if routine.name != prefix:
raise ValueError('Octave function name should match prefix')
if header:
code_lines.append("%" + prefix.upper() +
" Autogenerated by sympy\n")
code_lines.append(''.join(self._get_header()))
code_lines.extend(self._declare_arguments(routine))
code_lines.extend(self._declare_globals(routine))
code_lines.extend(self._declare_locals(routine))
if empty:
code_lines.append("\n")
code_lines.extend(self._call_printer(routine))
if empty:
code_lines.append("\n")
code_lines.extend(self._get_routine_ending(routine))
code_lines = self._indent_code(''.join(code_lines))
if code_lines:
f.write(code_lines)
dump_m.extension = code_extension # type: ignore
dump_m.__doc__ = CodeGen.dump_code.__doc__
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_m]
class RustCodeGen(CodeGen):
"""Generator for Rust code.
The .write() method inherited from CodeGen will output a code file
<prefix>.rs
"""
code_extension = "rs"
def __init__(self, project="project", printer=None):
super().__init__(project=project)
self.printer = printer or RustCodePrinter()
def routine(self, name, expr, argument_sequence, global_vars):
"""Specialized Routine creation for Rust."""
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
expressions = Tuple(*expr)
else:
expressions = Tuple(expr)
# local variables
local_vars = {i.label for i in expressions.atoms(Idx)}
# global variables
global_vars = set() if global_vars is None else set(global_vars)
# symbols that should be arguments
symbols = expressions.free_symbols - local_vars - global_vars - expressions.atoms(Indexed)
# Rust supports multiple return values
return_vals = []
output_args = []
for (i, expr) in enumerate(expressions):
if isinstance(expr, Equality):
out_arg = expr.lhs
expr = expr.rhs
symbol = out_arg
if isinstance(out_arg, Indexed):
dims = tuple([ (S.One, dim) for dim in out_arg.shape])
symbol = out_arg.base.label
output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))
if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
"can define output arguments.")
return_vals.append(Result(expr, name=symbol, result_var=out_arg))
if not expr.has(symbol):
# this is a pure output: remove from the symbols list, so
# it doesn't become an input.
symbols.remove(symbol)
else:
# we have no name for this output
return_vals.append(Result(expr, name='out%d' % (i+1)))
# setup input argument list
output_args.sort(key=lambda x: str(x.name))
arg_list = list(output_args)
array_symbols = {}
for array in expressions.atoms(Indexed):
array_symbols[array.base.label] = array
for array in expressions.atoms(MatrixSymbol):
array_symbols[array] = array
for symbol in sorted(symbols, key=str):
arg_list.append(InputArgument(symbol))
if argument_sequence is not None:
# if the user has supplied IndexedBase instances, we'll accept that
new_sequence = []
for arg in argument_sequence:
if isinstance(arg, IndexedBase):
new_sequence.append(arg.label)
else:
new_sequence.append(arg)
argument_sequence = new_sequence
missing = [x for x in arg_list if x.name not in argument_sequence]
if missing:
msg = "Argument list didn't specify: {0} "
msg = msg.format(", ".join([str(m.name) for m in missing]))
raise CodeGenArgumentListError(msg, missing)
# create redundant arguments to produce the requested sequence
name_arg_dict = {x.name: x for x in arg_list}
new_args = []
for symbol in argument_sequence:
try:
new_args.append(name_arg_dict[symbol])
except KeyError:
new_args.append(InputArgument(symbol))
arg_list = new_args
return Routine(name, arg_list, return_vals, local_vars, global_vars)
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
code_lines.append("/*\n")
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
code_lines.append((" *%s" % line.center(76)).rstrip() + "\n")
code_lines.append(" */\n")
return code_lines
def get_prototype(self, routine):
"""Returns a string for the function prototype of the routine.
If the routine has multiple result objects, an CodeGenError is
raised.
See: https://en.wikipedia.org/wiki/Function_prototype
"""
results = [i.get_datatype('Rust') for i in routine.results]
if len(results) == 1:
rstype = " -> " + results[0]
elif len(routine.results) > 1:
rstype = " -> (" + ", ".join(results) + ")"
else:
rstype = ""
type_args = []
for arg in routine.arguments:
name = self.printer.doprint(arg.name)
if arg.dimensions or isinstance(arg, ResultBase):
type_args.append(("*%s" % name, arg.get_datatype('Rust')))
else:
type_args.append((name, arg.get_datatype('Rust')))
arguments = ", ".join([ "%s: %s" % t for t in type_args])
return "fn %s(%s)%s" % (routine.name, arguments, rstype)
def _preprocessor_statements(self, prefix):
code_lines = []
# code_lines.append("use std::f64::consts::*;\n")
return code_lines
def _get_routine_opening(self, routine):
prototype = self.get_prototype(routine)
return ["%s {\n" % prototype]
def _declare_arguments(self, routine):
# arguments are declared in prototype
return []
def _declare_globals(self, routine):
# global variables are not explicitly declared within C functions
return []
def _declare_locals(self, routine):
# loop variables are declared in loop statement
return []
def _call_printer(self, routine):
code_lines = []
declarations = []
returns = []
# Compose a list of symbols to be dereferenced in the function
# body. These are the arguments that were passed by a reference
# pointer, excluding arrays.
dereference = []
for arg in routine.arguments:
if isinstance(arg, ResultBase) and not arg.dimensions:
dereference.append(arg.name)
for i, result in enumerate(routine.results):
if isinstance(result, Result):
assign_to = result.result_var
returns.append(str(result.result_var))
else:
raise CodeGenError("unexpected object in Routine results")
constants, not_supported, rs_expr = self._printer_method_with_settings(
'doprint', dict(human=False), result.expr, assign_to=assign_to)
for name, value in sorted(constants, key=str):
declarations.append("const %s: f64 = %s;\n" % (name, value))
for obj in sorted(not_supported, key=str):
if isinstance(obj, Function):
name = obj.func
else:
name = obj
declarations.append("// unsupported: %s\n" % (name))
code_lines.append("let %s\n" % rs_expr);
if len(returns) > 1:
returns = ['(' + ', '.join(returns) + ')']
returns.append('\n')
return declarations + code_lines + returns
def _get_routine_ending(self, routine):
return ["}\n"]
def dump_rs(self, routines, f, prefix, header=True, empty=True):
self.dump_code(routines, f, prefix, header, empty)
dump_rs.extension = code_extension # type: ignore
dump_rs.__doc__ = CodeGen.dump_code.__doc__
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_rs]
def get_code_generator(language, project=None, standard=None, printer = None):
if language == 'C':
if standard is None:
pass
elif standard.lower() == 'c89':
language = 'C89'
elif standard.lower() == 'c99':
language = 'C99'
CodeGenClass = {"C": CCodeGen, "C89": C89CodeGen, "C99": C99CodeGen,
"F95": FCodeGen, "JULIA": JuliaCodeGen,
"OCTAVE": OctaveCodeGen,
"RUST": RustCodeGen}.get(language.upper())
if CodeGenClass is None:
raise ValueError("Language '%s' is not supported." % language)
return CodeGenClass(project, printer)
#
# Friendly functions
#
def codegen(name_expr, language=None, prefix=None, project="project",
to_files=False, header=True, empty=True, argument_sequence=None,
global_vars=None, standard=None, code_gen=None, printer = None):
"""Generate source code for expressions in a given language.
Parameters
==========
name_expr : tuple, or list of tuples
A single (name, expression) tuple or a list of (name, expression)
tuples. Each tuple corresponds to a routine. If the expression is
an equality (an instance of class Equality) the left hand side is
considered an output argument. If expression is an iterable, then
the routine will have multiple outputs.
language : string,
A string that indicates the source code language. This is case
insensitive. Currently, 'C', 'F95' and 'Octave' are supported.
'Octave' generates code compatible with both Octave and Matlab.
prefix : string, optional
A prefix for the names of the files that contain the source code.
Language-dependent suffixes will be appended. If omitted, the name
of the first name_expr tuple is used.
project : string, optional
A project name, used for making unique preprocessor instructions.
[default: "project"]
to_files : bool, optional
When True, the code will be written to one or more files with the
given prefix, otherwise strings with the names and contents of
these files are returned. [default: False]
header : bool, optional
When True, a header is written on top of each source file.
[default: True]
empty : bool, optional
When True, empty lines are used to structure the code.
[default: True]
argument_sequence : iterable, optional
Sequence of arguments for the routine in a preferred order. A
CodeGenError is raised if required arguments are missing.
Redundant arguments are used without warning. If omitted,
arguments will be ordered alphabetically, but with all input
arguments first, and then output or in-out arguments.
global_vars : iterable, optional
Sequence of global variables used by the routine. Variables
listed here will not show up as function arguments.
standard : string
code_gen : CodeGen instance
An instance of a CodeGen subclass. Overrides ``language``.
Examples
========
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(c_name, c_code), (h_name, c_header)] = codegen(
... ("f", x+y*z), "C89", "test", header=False, empty=False)
>>> print(c_name)
test.c
>>> print(c_code)
#include "test.h"
#include <math.h>
double f(double x, double y, double z) {
double f_result;
f_result = x + y*z;
return f_result;
}
<BLANKLINE>
>>> print(h_name)
test.h
>>> print(c_header)
#ifndef PROJECT__TEST__H
#define PROJECT__TEST__H
double f(double x, double y, double z);
#endif
<BLANKLINE>
Another example using Equality objects to give named outputs. Here the
filename (prefix) is taken from the first (name, expr) pair.
>>> from sympy.abc import f, g
>>> from sympy import Eq
>>> [(c_name, c_code), (h_name, c_header)] = codegen(
... [("myfcn", x + y), ("fcn2", [Eq(f, 2*x), Eq(g, y)])],
... "C99", header=False, empty=False)
>>> print(c_name)
myfcn.c
>>> print(c_code)
#include "myfcn.h"
#include <math.h>
double myfcn(double x, double y) {
double myfcn_result;
myfcn_result = x + y;
return myfcn_result;
}
void fcn2(double x, double y, double *f, double *g) {
(*f) = 2*x;
(*g) = y;
}
<BLANKLINE>
If the generated function(s) will be part of a larger project where various
global variables have been defined, the 'global_vars' option can be used
to remove the specified variables from the function signature
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(f_name, f_code), header] = codegen(
... ("f", x+y*z), "F95", header=False, empty=False,
... argument_sequence=(x, y), global_vars=(z,))
>>> print(f_code)
REAL*8 function f(x, y)
implicit none
REAL*8, intent(in) :: x
REAL*8, intent(in) :: y
f = x + y*z
end function
<BLANKLINE>
"""
# Initialize the code generator.
if language is None:
if code_gen is None:
raise ValueError("Need either language or code_gen")
else:
if code_gen is not None:
raise ValueError("You cannot specify both language and code_gen.")
code_gen = get_code_generator(language, project, standard, printer)
if isinstance(name_expr[0], str):
# single tuple is given, turn it into a singleton list with a tuple.
name_expr = [name_expr]
if prefix is None:
prefix = name_expr[0][0]
# Construct Routines appropriate for this code_gen from (name, expr) pairs.
routines = []
for name, expr in name_expr:
routines.append(code_gen.routine(name, expr, argument_sequence,
global_vars))
# Write the code.
return code_gen.write(routines, prefix, to_files, header, empty)
def make_routine(name, expr, argument_sequence=None,
global_vars=None, language="F95"):
"""A factory that makes an appropriate Routine from an expression.
Parameters
==========
name : string
The name of this routine in the generated code.
expr : expression or list/tuple of expressions
A SymPy expression that the Routine instance will represent. If
given a list or tuple of expressions, the routine will be
considered to have multiple return values and/or output arguments.
argument_sequence : list or tuple, optional
List arguments for the routine in a preferred order. If omitted,
the results are language dependent, for example, alphabetical order
or in the same order as the given expressions.
global_vars : iterable, optional
Sequence of global variables used by the routine. Variables
listed here will not show up as function arguments.
language : string, optional
Specify a target language. The Routine itself should be
language-agnostic but the precise way one is created, error
checking, etc depend on the language. [default: "F95"].
A decision about whether to use output arguments or return values is made
depending on both the language and the particular mathematical expressions.
For an expression of type Equality, the left hand side is typically made
into an OutputArgument (or perhaps an InOutArgument if appropriate).
Otherwise, typically, the calculated expression is made a return values of
the routine.
Examples
========
>>> from sympy.utilities.codegen import make_routine
>>> from sympy.abc import x, y, f, g
>>> from sympy import Eq
>>> r = make_routine('test', [Eq(f, 2*x), Eq(g, x + y)])
>>> [arg.result_var for arg in r.results]
[]
>>> [arg.name for arg in r.arguments]
[x, y, f, g]
>>> [arg.name for arg in r.result_variables]
[f, g]
>>> r.local_vars
set()
Another more complicated example with a mixture of specified and
automatically-assigned names. Also has Matrix output.
>>> from sympy import Matrix
>>> r = make_routine('fcn', [x*y, Eq(f, 1), Eq(g, x + g), Matrix([[x, 2]])])
>>> [arg.result_var for arg in r.results] # doctest: +SKIP
[result_5397460570204848505]
>>> [arg.expr for arg in r.results]
[x*y]
>>> [arg.name for arg in r.arguments] # doctest: +SKIP
[x, y, f, g, out_8598435338387848786]
We can examine the various arguments more closely:
>>> from sympy.utilities.codegen import (InputArgument, OutputArgument,
... InOutArgument)
>>> [a.name for a in r.arguments if isinstance(a, InputArgument)]
[x, y]
>>> [a.name for a in r.arguments if isinstance(a, OutputArgument)] # doctest: +SKIP
[f, out_8598435338387848786]
>>> [a.expr for a in r.arguments if isinstance(a, OutputArgument)]
[1, Matrix([[x, 2]])]
>>> [a.name for a in r.arguments if isinstance(a, InOutArgument)]
[g]
>>> [a.expr for a in r.arguments if isinstance(a, InOutArgument)]
[g + x]
"""
# initialize a new code generator
code_gen = get_code_generator(language)
return code_gen.routine(name, expr, argument_sequence, global_vars)
|
06c9c61ffdbc253e4878da6d1ecc279f5b153a0830fa4db0900145dd2074ee36 | """
Python code printers
This module contains python code printers for plain python as well as NumPy & SciPy enabled code.
"""
from collections import defaultdict
from itertools import chain
from sympy.core import S
from .precedence import precedence
from .codeprinter import CodePrinter
_kw_py2and3 = {
'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield', 'None' # 'None' is actually not in Python 2's keyword.kwlist
}
_kw_only_py2 = {'exec', 'print'}
_kw_only_py3 = {'False', 'nonlocal', 'True'}
_known_functions = {
'Abs': 'abs',
}
_known_functions_math = {
'acos': 'acos',
'acosh': 'acosh',
'asin': 'asin',
'asinh': 'asinh',
'atan': 'atan',
'atan2': 'atan2',
'atanh': 'atanh',
'ceiling': 'ceil',
'cos': 'cos',
'cosh': 'cosh',
'erf': 'erf',
'erfc': 'erfc',
'exp': 'exp',
'expm1': 'expm1',
'factorial': 'factorial',
'floor': 'floor',
'gamma': 'gamma',
'hypot': 'hypot',
'loggamma': 'lgamma',
'log': 'log',
'ln': 'log',
'log10': 'log10',
'log1p': 'log1p',
'log2': 'log2',
'sin': 'sin',
'sinh': 'sinh',
'Sqrt': 'sqrt',
'tan': 'tan',
'tanh': 'tanh'
} # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf
# radians trunc fmod fsum gcd degrees fabs]
_known_constants_math = {
'Exp1': 'e',
'Pi': 'pi',
'E': 'e'
# Only in python >= 3.5:
# 'Infinity': 'inf',
# 'NaN': 'nan'
}
def _print_known_func(self, expr):
known = self.known_functions[expr.__class__.__name__]
return '{name}({args})'.format(name=self._module_format(known),
args=', '.join(map(lambda arg: self._print(arg), expr.args)))
def _print_known_const(self, expr):
known = self.known_constants[expr.__class__.__name__]
return self._module_format(known)
class AbstractPythonCodePrinter(CodePrinter):
printmethod = "_pythoncode"
language = "Python"
reserved_words = _kw_py2and3.union(_kw_only_py3)
modules = None # initialized to a set in __init__
tab = ' '
_kf = dict(chain(
_known_functions.items(),
[(k, 'math.' + v) for k, v in _known_functions_math.items()]
))
_kc = {k: 'math.'+v for k, v in _known_constants_math.items()}
_operators = {'and': 'and', 'or': 'or', 'not': 'not'}
_default_settings = dict(
CodePrinter._default_settings,
user_functions={},
precision=17,
inline=True,
fully_qualified_modules=True,
contract=False,
standard='python3',
)
def __init__(self, settings=None):
super(AbstractPythonCodePrinter, self).__init__(settings)
# Python standard handler
std = self._settings['standard']
if std is None:
import sys
std = 'python{}'.format(sys.version_info.major)
if std not in ('python2', 'python3'):
raise ValueError('Unrecognized python standard : {}'.format(std))
self.standard = std
self.module_imports = defaultdict(set)
# Known functions and constants handler
self.known_functions = dict(self._kf, **(settings or {}).get(
'user_functions', {}))
self.known_constants = dict(self._kc, **(settings or {}).get(
'user_constants', {}))
def _declare_number_const(self, name, value):
return "%s = %s" % (name, value)
def _module_format(self, fqn, register=True):
parts = fqn.split('.')
if register and len(parts) > 1:
self.module_imports['.'.join(parts[:-1])].add(parts[-1])
if self._settings['fully_qualified_modules']:
return fqn
else:
return fqn.split('(')[0].split('[')[0].split('.')[-1]
def _format_code(self, lines):
return lines
def _get_statement(self, codestring):
return "{}".format(codestring)
def _get_comment(self, text):
return " # {0}".format(text)
def _expand_fold_binary_op(self, op, args):
"""
This method expands a fold on binary operations.
``functools.reduce`` is an example of a folded operation.
For example, the expression
`A + B + C + D`
is folded into
`((A + B) + C) + D`
"""
if len(args) == 1:
return self._print(args[0])
else:
return "%s(%s, %s)" % (
self._module_format(op),
self._expand_fold_binary_op(op, args[:-1]),
self._print(args[-1]),
)
def _expand_reduce_binary_op(self, op, args):
"""
This method expands a reductin on binary operations.
Notice: this is NOT the same as ``functools.reduce``.
For example, the expression
`A + B + C + D`
is reduced into:
`(A + B) + (C + D)`
"""
if len(args) == 1:
return self._print(args[0])
else:
N = len(args)
Nhalf = N // 2
return "%s(%s, %s)" % (
self._module_format(op),
self._expand_reduce_binary_op(args[:Nhalf]),
self._expand_reduce_binary_op(args[Nhalf:]),
)
def _get_einsum_string(self, subranks, contraction_indices):
letters = self._get_letter_generator_for_einsum()
contraction_string = ""
counter = 0
d = {j: min(i) for i in contraction_indices for j in i}
indices = []
for rank_arg in subranks:
lindices = []
for i in range(rank_arg):
if counter in d:
lindices.append(d[counter])
else:
lindices.append(counter)
counter += 1
indices.append(lindices)
mapping = {}
letters_free = []
letters_dum = []
for i in indices:
for j in i:
if j not in mapping:
l = next(letters)
mapping[j] = l
else:
l = mapping[j]
contraction_string += l
if j in d:
if l not in letters_dum:
letters_dum.append(l)
else:
letters_free.append(l)
contraction_string += ","
contraction_string = contraction_string[:-1]
return contraction_string, letters_free, letters_dum
def _print_NaN(self, expr):
return "float('nan')"
def _print_Infinity(self, expr):
return "float('inf')"
def _print_NegativeInfinity(self, expr):
return "float('-inf')"
def _print_ComplexInfinity(self, expr):
return self._print_NaN(expr)
def _print_Mod(self, expr):
PREC = precedence(expr)
return ('{0} % {1}'.format(*map(lambda x: self.parenthesize(x, PREC), expr.args)))
def _print_Piecewise(self, expr):
result = []
i = 0
for arg in expr.args:
e = arg.expr
c = arg.cond
if i == 0:
result.append('(')
result.append('(')
result.append(self._print(e))
result.append(')')
result.append(' if ')
result.append(self._print(c))
result.append(' else ')
i += 1
result = result[:-1]
if result[-1] == 'True':
result = result[:-2]
result.append(')')
else:
result.append(' else None)')
return ''.join(result)
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs)
return super(AbstractPythonCodePrinter, self)._print_Relational(expr)
def _print_ITE(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(expr.rewrite(Piecewise))
def _print_Sum(self, expr):
loops = (
'for {i} in range({a}, {b}+1)'.format(
i=self._print(i),
a=self._print(a),
b=self._print(b))
for i, a, b in expr.limits)
return '(builtins.sum({function} {loops}))'.format(
function=self._print(expr.function),
loops=' '.join(loops))
def _print_ImaginaryUnit(self, expr):
return '1j'
def _print_KroneckerDelta(self, expr):
a, b = expr.args
return '(1 if {a} == {b} else 0)'.format(
a = self._print(a),
b = self._print(b)
)
def _print_MatrixBase(self, expr):
name = expr.__class__.__name__
func = self.known_functions.get(name, name)
return "%s(%s)" % (func, self._print(expr.tolist()))
_print_SparseMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
lambda self, expr: self._print_MatrixBase(expr)
def _indent_codestring(self, codestring):
return '\n'.join([self.tab + line for line in codestring.split('\n')])
def _print_FunctionDefinition(self, fd):
body = '\n'.join(map(lambda arg: self._print(arg), fd.body))
return "def {name}({parameters}):\n{body}".format(
name=self._print(fd.name),
parameters=', '.join([self._print(var.symbol) for var in fd.parameters]),
body=self._indent_codestring(body)
)
def _print_While(self, whl):
body = '\n'.join(map(lambda arg: self._print(arg), whl.body))
return "while {cond}:\n{body}".format(
cond=self._print(whl.condition),
body=self._indent_codestring(body)
)
def _print_Declaration(self, decl):
return '%s = %s' % (
self._print(decl.variable.symbol),
self._print(decl.variable.value)
)
def _print_Return(self, ret):
arg, = ret.args
return 'return %s' % self._print(arg)
def _print_Print(self, prnt):
print_args = ', '.join(map(lambda arg: self._print(arg), prnt.print_args))
if prnt.format_string != None: # Must be '!= None', cannot be 'is not None'
print_args = '{0} % ({1})'.format(
self._print(prnt.format_string), print_args)
if prnt.file != None: # Must be '!= None', cannot be 'is not None'
print_args += ', file=%s' % self._print(prnt.file)
if self.standard == 'python2':
return 'print %s' % print_args
return 'print(%s)' % print_args
def _print_Stream(self, strm):
if str(strm.name) == 'stdout':
return self._module_format('sys.stdout')
elif str(strm.name) == 'stderr':
return self._module_format('sys.stderr')
else:
return self._print(strm.name)
def _print_NoneToken(self, arg):
return 'None'
class PythonCodePrinter(AbstractPythonCodePrinter):
def _print_sign(self, e):
return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(
f=self._module_format('math.copysign'), e=self._print(e.args[0]))
def _print_Not(self, expr):
PREC = precedence(expr)
return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
def _print_Indexed(self, expr):
base = expr.args[0]
index = expr.args[1:]
return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))
def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):
"""Printing helper function for ``Pow``
Notes
=====
This only preprocesses the ``sqrt`` as math formatter
Examples
========
>>> from sympy.functions import sqrt
>>> from sympy.printing.pycode import PythonCodePrinter
>>> from sympy.abc import x
Python code printer automatically looks up ``math.sqrt``.
>>> printer = PythonCodePrinter({'standard':'python3'})
>>> printer._hprint_Pow(sqrt(x), rational=True)
'x**(1/2)'
>>> printer._hprint_Pow(sqrt(x), rational=False)
'math.sqrt(x)'
>>> printer._hprint_Pow(1/sqrt(x), rational=True)
'x**(-1/2)'
>>> printer._hprint_Pow(1/sqrt(x), rational=False)
'1/math.sqrt(x)'
Using sqrt from numpy or mpmath
>>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt')
'numpy.sqrt(x)'
>>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt')
'mpmath.sqrt(x)'
See Also
========
sympy.printing.str.StrPrinter._print_Pow
"""
PREC = precedence(expr)
if expr.exp == S.Half and not rational:
func = self._module_format(sqrt)
arg = self._print(expr.base)
return '{func}({arg})'.format(func=func, arg=arg)
if expr.is_commutative:
if -expr.exp is S.Half and not rational:
func = self._module_format(sqrt)
num = self._print(S.One)
arg = self._print(expr.base)
return "{num}/{func}({arg})".format(
num=num, func=func, arg=arg)
base_str = self.parenthesize(expr.base, PREC, strict=False)
exp_str = self.parenthesize(expr.exp, PREC, strict=False)
return "{}**{}".format(base_str, exp_str)
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational)
def _print_Rational(self, expr):
if self.standard == 'python2':
return '{}./{}.'.format(expr.p, expr.q)
return '{}/{}'.format(expr.p, expr.q)
def _print_Half(self, expr):
return self._print_Rational(expr)
_print_lowergamma = CodePrinter._print_not_supported
_print_uppergamma = CodePrinter._print_not_supported
_print_fresnelc = CodePrinter._print_not_supported
_print_fresnels = CodePrinter._print_not_supported
for k in PythonCodePrinter._kf:
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)
for k in _known_constants_math:
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const)
def pycode(expr, **settings):
""" Converts an expr to a string of Python code
Parameters
==========
expr : Expr
A SymPy expression.
fully_qualified_modules : bool
Whether or not to write out full module names of functions
(``math.sin`` vs. ``sin``). default: ``True``.
standard : str or None, optional
If 'python2', Python 2 sematics will be used.
If 'python3', Python 3 sematics will be used.
If None, the standard will be automatically detected.
Default is 'python3'. And this parameter may be removed in the
future.
Examples
========
>>> from sympy import tan, Symbol
>>> from sympy.printing.pycode import pycode
>>> pycode(tan(Symbol('x')) + 1)
'math.tan(x) + 1'
"""
return PythonCodePrinter(settings).doprint(expr)
_not_in_mpmath = 'log1p log2'.split()
_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath]
_known_functions_mpmath = dict(_in_mpmath, **{
'beta': 'beta',
'fresnelc': 'fresnelc',
'fresnels': 'fresnels',
'sign': 'sign',
})
_known_constants_mpmath = {
'Exp1': 'e',
'Pi': 'pi',
'GoldenRatio': 'phi',
'EulerGamma': 'euler',
'Catalan': 'catalan',
'NaN': 'nan',
'Infinity': 'inf',
'NegativeInfinity': 'ninf'
}
class MpmathPrinter(PythonCodePrinter):
"""
Lambda printer for mpmath which maintains precision for floats
"""
printmethod = "_mpmathcode"
language = "Python with mpmath"
_kf = dict(chain(
_known_functions.items(),
[(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]
))
_kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()}
def _print_Float(self, e):
# XXX: This does not handle setting mpmath.mp.dps. It is assumed that
# the caller of the lambdified function will have set it to sufficient
# precision to match the Floats in the expression.
# Remove 'mpz' if gmpy is installed.
args = str(tuple(map(int, e._mpf_)))
return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)
def _print_Rational(self, e):
return "{func}({p})/{func}({q})".format(
func=self._module_format('mpmath.mpf'),
q=self._print(e.q),
p=self._print(e.p)
)
def _print_Half(self, e):
return self._print_Rational(e)
def _print_uppergamma(self, e):
return "{0}({1}, {2}, {3})".format(
self._module_format('mpmath.gammainc'),
self._print(e.args[0]),
self._print(e.args[1]),
self._module_format('mpmath.inf'))
def _print_lowergamma(self, e):
return "{0}({1}, 0, {2})".format(
self._module_format('mpmath.gammainc'),
self._print(e.args[0]),
self._print(e.args[1]))
def _print_log2(self, e):
return '{0}({1})/{0}(2)'.format(
self._module_format('mpmath.log'), self._print(e.args[0]))
def _print_log1p(self, e):
return '{0}({1}+1)'.format(
self._module_format('mpmath.log'), self._print(e.args[0]))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt')
for k in MpmathPrinter._kf:
setattr(MpmathPrinter, '_print_%s' % k, _print_known_func)
for k in _known_constants_mpmath:
setattr(MpmathPrinter, '_print_%s' % k, _print_known_const)
_not_in_numpy = 'erf erfc factorial gamma loggamma'.split()
_in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy]
_known_functions_numpy = dict(_in_numpy, **{
'acos': 'arccos',
'acosh': 'arccosh',
'asin': 'arcsin',
'asinh': 'arcsinh',
'atan': 'arctan',
'atan2': 'arctan2',
'atanh': 'arctanh',
'exp2': 'exp2',
'sign': 'sign',
'logaddexp': 'logaddexp',
'logaddexp2': 'logaddexp2',
})
_known_constants_numpy = {
'Exp1': 'e',
'Pi': 'pi',
'EulerGamma': 'euler_gamma',
'NaN': 'nan',
'Infinity': 'PINF',
'NegativeInfinity': 'NINF'
}
class NumPyPrinter(PythonCodePrinter):
"""
Numpy printer which handles vectorized piecewise functions,
logical operators, etc.
"""
printmethod = "_numpycode"
language = "Python with NumPy"
_kf = dict(chain(
PythonCodePrinter._kf.items(),
[(k, 'numpy.' + v) for k, v in _known_functions_numpy.items()]
))
_kc = {k: 'numpy.'+v for k, v in _known_constants_numpy.items()}
def _print_seq(self, seq):
"General sequence printer: converts to tuple"
# Print tuples here instead of lists because numba supports
# tuples in nopython mode.
delimiter=', '
return '({},)'.format(delimiter.join(self._print(item) for item in seq))
def _print_MatMul(self, expr):
"Matrix multiplication printer"
if expr.as_coeff_matrices()[0] is not S.One:
expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])]
return '({0})'.format(').dot('.join(self._print(i) for i in expr_list))
return '({0})'.format(').dot('.join(self._print(i) for i in expr.args))
def _print_MatPow(self, expr):
"Matrix power printer"
return '{0}({1}, {2})'.format(self._module_format('numpy.linalg.matrix_power'),
self._print(expr.args[0]), self._print(expr.args[1]))
def _print_Inverse(self, expr):
"Matrix inverse printer"
return '{0}({1})'.format(self._module_format('numpy.linalg.inv'),
self._print(expr.args[0]))
def _print_DotProduct(self, expr):
# DotProduct allows any shape order, but numpy.dot does matrix
# multiplication, so we have to make sure it gets 1 x n by n x 1.
arg1, arg2 = expr.args
if arg1.shape[0] != 1:
arg1 = arg1.T
if arg2.shape[1] != 1:
arg2 = arg2.T
return "%s(%s, %s)" % (self._module_format('numpy.dot'),
self._print(arg1),
self._print(arg2))
def _print_MatrixSolve(self, expr):
return "%s(%s, %s)" % (self._module_format('numpy.linalg.solve'),
self._print(expr.matrix),
self._print(expr.vector))
def _print_ZeroMatrix(self, expr):
return '{}({})'.format(self._module_format('numpy.zeros'),
self._print(expr.shape))
def _print_OneMatrix(self, expr):
return '{}({})'.format(self._module_format('numpy.ones'),
self._print(expr.shape))
def _print_FunctionMatrix(self, expr):
from sympy.core.function import Lambda
from sympy.abc import i, j
lamda = expr.lamda
if not isinstance(lamda, Lambda):
lamda = Lambda((i, j), lamda(i, j))
return '{}(lambda {}: {}, {})'.format(self._module_format('numpy.fromfunction'),
', '.join(self._print(arg) for arg in lamda.args[0]),
self._print(lamda.args[1]), self._print(expr.shape))
def _print_HadamardProduct(self, expr):
func = self._module_format('numpy.multiply')
return ''.join('{}({}, '.format(func, self._print(arg)) \
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
')' * (len(expr.args) - 1))
def _print_KroneckerProduct(self, expr):
func = self._module_format('numpy.kron')
return ''.join('{}({}, '.format(func, self._print(arg)) \
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
')' * (len(expr.args) - 1))
def _print_Adjoint(self, expr):
return '{}({}({}))'.format(
self._module_format('numpy.conjugate'),
self._module_format('numpy.transpose'),
self._print(expr.args[0]))
def _print_DiagonalOf(self, expr):
vect = '{}({})'.format(
self._module_format('numpy.diag'),
self._print(expr.arg))
return '{}({}, (-1, 1))'.format(
self._module_format('numpy.reshape'), vect)
def _print_DiagMatrix(self, expr):
return '{}({})'.format(self._module_format('numpy.diagflat'),
self._print(expr.args[0]))
def _print_DiagonalMatrix(self, expr):
return '{}({}, {}({}, {}))'.format(self._module_format('numpy.multiply'),
self._print(expr.arg), self._module_format('numpy.eye'),
self._print(expr.shape[0]), self._print(expr.shape[1]))
def _print_Piecewise(self, expr):
"Piecewise function printer"
exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args))
conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args))
# If [default_value, True] is a (expr, cond) sequence in a Piecewise object
# it will behave the same as passing the 'default' kwarg to select()
# *as long as* it is the last element in expr.args.
# If this is not the case, it may be triggered prematurely.
return '{0}({1}, {2}, default={3})'.format(
self._module_format('numpy.select'), conds, exprs,
self._print(S.NaN))
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '{op}({lhs}, {rhs})'.format(op=self._module_format('numpy.'+op[expr.rel_op]),
lhs=lhs, rhs=rhs)
return super(NumPyPrinter, self)._print_Relational(expr)
def _print_And(self, expr):
"Logical And printer"
# We have to override LambdaPrinter because it uses Python 'and' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.
return '{0}.reduce(({1}))'.format(self._module_format('numpy.logical_and'), ','.join(self._print(i) for i in expr.args))
def _print_Or(self, expr):
"Logical Or printer"
# We have to override LambdaPrinter because it uses Python 'or' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.
return '{0}.reduce(({1}))'.format(self._module_format('numpy.logical_or'), ','.join(self._print(i) for i in expr.args))
def _print_Not(self, expr):
"Logical Not printer"
# We have to override LambdaPrinter because it uses Python 'not' keyword.
# If LambdaPrinter didn't define it, we would still have to define our
# own because StrPrinter doesn't define it.
return '{0}({1})'.format(self._module_format('numpy.logical_not'), ','.join(self._print(i) for i in expr.args))
def _print_Pow(self, expr, rational=False):
# XXX Workaround for negative integer power error
from sympy.core.power import Pow
if expr.exp.is_integer and expr.exp.is_negative:
expr = Pow(expr.base, expr.exp.evalf(), evaluate=False)
return self._hprint_Pow(expr, rational=rational, sqrt='numpy.sqrt')
def _print_Min(self, expr):
return '{0}(({1}), axis=0)'.format(self._module_format('numpy.amin'), ','.join(self._print(i) for i in expr.args))
def _print_Max(self, expr):
return '{0}(({1}), axis=0)'.format(self._module_format('numpy.amax'), ','.join(self._print(i) for i in expr.args))
def _print_arg(self, expr):
return "%s(%s)" % (self._module_format('numpy.angle'), self._print(expr.args[0]))
def _print_im(self, expr):
return "%s(%s)" % (self._module_format('numpy.imag'), self._print(expr.args[0]))
def _print_Mod(self, expr):
return "%s(%s)" % (self._module_format('numpy.mod'), ', '.join(
map(lambda arg: self._print(arg), expr.args)))
def _print_re(self, expr):
return "%s(%s)" % (self._module_format('numpy.real'), self._print(expr.args[0]))
def _print_sinc(self, expr):
return "%s(%s)" % (self._module_format('numpy.sinc'), self._print(expr.args[0]/S.Pi))
def _print_MatrixBase(self, expr):
func = self.known_functions.get(expr.__class__.__name__, None)
if func is None:
func = self._module_format('numpy.array')
return "%s(%s)" % (func, self._print(expr.tolist()))
def _print_Identity(self, expr):
shape = expr.shape
if all([dim.is_Integer for dim in shape]):
return "%s(%s)" % (self._module_format('numpy.eye'), self._print(expr.shape[0]))
else:
raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")
def _print_BlockMatrix(self, expr):
return '{0}({1})'.format(self._module_format('numpy.block'),
self._print(expr.args[0].tolist()))
def _print_CodegenArrayTensorProduct(self, expr):
array_list = [j for i, arg in enumerate(expr.args) for j in
(self._print(arg), "[%i, %i]" % (2*i, 2*i+1))]
return "%s(%s)" % (self._module_format('numpy.einsum'), ", ".join(array_list))
def _print_CodegenArrayContraction(self, expr):
from sympy.codegen.array_utils import CodegenArrayTensorProduct
base = expr.expr
contraction_indices = expr.contraction_indices
if not contraction_indices:
return self._print(base)
if isinstance(base, CodegenArrayTensorProduct):
counter = 0
d = {j: min(i) for i in contraction_indices for j in i}
indices = []
for rank_arg in base.subranks:
lindices = []
for i in range(rank_arg):
if counter in d:
lindices.append(d[counter])
else:
lindices.append(counter)
counter += 1
indices.append(lindices)
elems = ["%s, %s" % (self._print(arg), ind) for arg, ind in zip(base.args, indices)]
return "%s(%s)" % (
self._module_format('numpy.einsum'),
", ".join(elems)
)
raise NotImplementedError()
def _print_CodegenArrayDiagonal(self, expr):
diagonal_indices = list(expr.diagonal_indices)
if len(diagonal_indices) > 1:
# TODO: this should be handled in sympy.codegen.array_utils,
# possibly by creating the possibility of unfolding the
# CodegenArrayDiagonal object into nested ones. Same reasoning for
# the array contraction.
raise NotImplementedError
if len(diagonal_indices[0]) != 2:
raise NotImplementedError
return "%s(%s, 0, axis1=%s, axis2=%s)" % (
self._module_format("numpy.diagonal"),
self._print(expr.expr),
diagonal_indices[0][0],
diagonal_indices[0][1],
)
def _print_CodegenArrayPermuteDims(self, expr):
return "%s(%s, %s)" % (
self._module_format("numpy.transpose"),
self._print(expr.expr),
self._print(expr.permutation.array_form),
)
def _print_CodegenArrayElementwiseAdd(self, expr):
return self._expand_fold_binary_op('numpy.add', expr.args)
_print_lowergamma = CodePrinter._print_not_supported
_print_uppergamma = CodePrinter._print_not_supported
_print_fresnelc = CodePrinter._print_not_supported
_print_fresnels = CodePrinter._print_not_supported
for k in NumPyPrinter._kf:
setattr(NumPyPrinter, '_print_%s' % k, _print_known_func)
for k in NumPyPrinter._kc:
setattr(NumPyPrinter, '_print_%s' % k, _print_known_const)
_known_functions_scipy_special = {
'erf': 'erf',
'erfc': 'erfc',
'besselj': 'jv',
'bessely': 'yv',
'besseli': 'iv',
'besselk': 'kv',
'factorial': 'factorial',
'gamma': 'gamma',
'loggamma': 'gammaln',
'digamma': 'psi',
'RisingFactorial': 'poch',
'jacobi': 'eval_jacobi',
'gegenbauer': 'eval_gegenbauer',
'chebyshevt': 'eval_chebyt',
'chebyshevu': 'eval_chebyu',
'legendre': 'eval_legendre',
'hermite': 'eval_hermite',
'laguerre': 'eval_laguerre',
'assoc_laguerre': 'eval_genlaguerre',
'beta': 'beta',
'LambertW' : 'lambertw',
}
_known_constants_scipy_constants = {
'GoldenRatio': 'golden_ratio',
'Pi': 'pi',
}
class SciPyPrinter(NumPyPrinter):
language = "Python with SciPy"
_kf = dict(chain(
NumPyPrinter._kf.items(),
[(k, 'scipy.special.' + v) for k, v in _known_functions_scipy_special.items()]
))
_kc =dict(chain(
NumPyPrinter._kc.items(),
[(k, 'scipy.constants.' + v) for k, v in _known_constants_scipy_constants.items()]
))
def _print_SparseMatrix(self, expr):
i, j, data = [], [], []
for (r, c), v in expr._smat.items():
i.append(r)
j.append(c)
data.append(v)
return "{name}(({data}, ({i}, {j})), shape={shape})".format(
name=self._module_format('scipy.sparse.coo_matrix'),
data=data, i=i, j=j, shape=expr.shape
)
_print_ImmutableSparseMatrix = _print_SparseMatrix
# SciPy's lpmv has a different order of arguments from assoc_legendre
def _print_assoc_legendre(self, expr):
return "{0}({2}, {1}, {3})".format(
self._module_format('scipy.special.lpmv'),
self._print(expr.args[0]),
self._print(expr.args[1]),
self._print(expr.args[2]))
def _print_lowergamma(self, expr):
return "{0}({2})*{1}({2}, {3})".format(
self._module_format('scipy.special.gamma'),
self._module_format('scipy.special.gammainc'),
self._print(expr.args[0]),
self._print(expr.args[1]))
def _print_uppergamma(self, expr):
return "{0}({2})*{1}({2}, {3})".format(
self._module_format('scipy.special.gamma'),
self._module_format('scipy.special.gammaincc'),
self._print(expr.args[0]),
self._print(expr.args[1]))
def _print_fresnels(self, expr):
return "{0}({1})[0]".format(
self._module_format("scipy.special.fresnel"),
self._print(expr.args[0]))
def _print_fresnelc(self, expr):
return "{0}({1})[1]".format(
self._module_format("scipy.special.fresnel"),
self._print(expr.args[0]))
def _print_airyai(self, expr):
return "{0}({1})[0]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airyaiprime(self, expr):
return "{0}({1})[1]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airybi(self, expr):
return "{0}({1})[2]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airybiprime(self, expr):
return "{0}({1})[3]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
for k in SciPyPrinter._kf:
setattr(SciPyPrinter, '_print_%s' % k, _print_known_func)
for k in SciPyPrinter._kc:
setattr(SciPyPrinter, '_print_%s' % k, _print_known_const)
class SymPyPrinter(PythonCodePrinter):
language = "Python with SymPy"
_kf = {k: 'sympy.' + v for k, v in chain(
_known_functions.items(),
_known_functions_math.items()
)}
def _print_Function(self, expr):
mod = expr.func.__module__ or ''
return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),
', '.join(map(lambda arg: self._print(arg), expr.args)))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
|
fdaa994e864d9b004814d3c9703051e420381aa8b940949f5606fe1e219bdbb8 | """
A Printer for generating readable representation of most sympy classes.
"""
from __future__ import print_function, division
from typing import Any, Dict
from sympy.core import S, Rational, Pow, Basic, Mul, Number
from sympy.core.mul import _keep_coeff
from .printer import Printer
from sympy.printing.precedence import precedence, PRECEDENCE
from mpmath.libmp import prec_to_dps, to_str as mlib_to_str
from sympy.utilities import default_sort_key
class StrPrinter(Printer):
printmethod = "_sympystr"
_default_settings = {
"order": None,
"full_prec": "auto",
"sympy_integers": False,
"abbrev": False,
"perm_cyclic": True,
"min": None,
"max": None,
} # type: Dict[str, Any]
_relationals = dict() # type: Dict[str, str]
def parenthesize(self, item, level, strict=False):
if (precedence(item) < level) or ((not strict) and precedence(item) <= level):
return "(%s)" % self._print(item)
else:
return self._print(item)
def stringify(self, args, sep, level=0):
return sep.join([self.parenthesize(item, level) for item in args])
def emptyPrinter(self, expr):
if isinstance(expr, str):
return expr
elif isinstance(expr, Basic):
return repr(expr)
else:
return str(expr)
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
PREC = precedence(expr)
l = []
for term in terms:
t = self._print(term)
if t.startswith('-'):
sign = "-"
t = t[1:]
else:
sign = "+"
if precedence(term) < PREC:
l.extend([sign, "(%s)" % t])
else:
l.extend([sign, t])
sign = l.pop(0)
if sign == '+':
sign = ""
return sign + ' '.join(l)
def _print_BooleanTrue(self, expr):
return "True"
def _print_BooleanFalse(self, expr):
return "False"
def _print_Not(self, expr):
return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"]))
def _print_And(self, expr):
return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"])
def _print_Or(self, expr):
return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"])
def _print_Xor(self, expr):
return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"])
def _print_AppliedPredicate(self, expr):
return '%s(%s)' % (self._print(expr.func), self._print(expr.arg))
def _print_Basic(self, expr):
l = [self._print(o) for o in expr.args]
return expr.__class__.__name__ + "(%s)" % ", ".join(l)
def _print_BlockMatrix(self, B):
if B.blocks.shape == (1, 1):
self._print(B.blocks[0, 0])
return self._print(B.blocks)
def _print_Catalan(self, expr):
return 'Catalan'
def _print_ComplexInfinity(self, expr):
return 'zoo'
def _print_ConditionSet(self, s):
args = tuple([self._print(i) for i in (s.sym, s.condition)])
if s.base_set is S.UniversalSet:
return 'ConditionSet(%s, %s)' % args
args += (self._print(s.base_set),)
return 'ConditionSet(%s, %s, %s)' % args
def _print_Derivative(self, expr):
dexpr = expr.expr
dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars))
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
item = "%s: %s" % (self._print(key), self._print(d[key]))
items.append(item)
return "{%s}" % ", ".join(items)
def _print_Dict(self, expr):
return self._print_dict(expr)
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
return 'Domain: ' + self._print(d.as_boolean())
elif hasattr(d, 'set'):
return ('Domain: ' + self._print(d.symbols) + ' in ' +
self._print(d.set))
else:
return 'Domain on ' + self._print(d.symbols)
def _print_Dummy(self, expr):
return '_' + expr.name
def _print_EulerGamma(self, expr):
return 'EulerGamma'
def _print_Exp1(self, expr):
return 'E'
def _print_ExprCondPair(self, expr):
return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond))
def _print_Function(self, expr):
return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ")
def _print_GoldenRatio(self, expr):
return 'GoldenRatio'
def _print_TribonacciConstant(self, expr):
return 'TribonacciConstant'
def _print_ImaginaryUnit(self, expr):
return 'I'
def _print_Infinity(self, expr):
return 'oo'
def _print_Integral(self, expr):
def _xab_tostr(xab):
if len(xab) == 1:
return self._print(xab[0])
else:
return self._print((xab[0],) + tuple(xab[1:]))
L = ', '.join([_xab_tostr(l) for l in expr.limits])
return 'Integral(%s, %s)' % (self._print(expr.function), L)
def _print_Interval(self, i):
fin = 'Interval{m}({a}, {b})'
a, b, l, r = i.args
if a.is_infinite and b.is_infinite:
m = ''
elif a.is_infinite and not r:
m = ''
elif b.is_infinite and not l:
m = ''
elif not l and not r:
m = ''
elif l and r:
m = '.open'
elif l:
m = '.Lopen'
else:
m = '.Ropen'
return fin.format(**{'a': a, 'b': b, 'm': m})
def _print_AccumulationBounds(self, i):
return "AccumBounds(%s, %s)" % (self._print(i.min),
self._print(i.max))
def _print_Inverse(self, I):
return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"])
def _print_Lambda(self, obj):
expr = obj.expr
sig = obj.signature
if len(sig) == 1 and sig[0].is_symbol:
sig = sig[0]
return "Lambda(%s, %s)" % (self._print(sig), self._print(expr))
def _print_LatticeOp(self, expr):
args = sorted(expr.args, key=default_sort_key)
return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args)
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
if str(dir) == "+":
return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0)))
else:
return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print,
(e, z, z0, dir)))
def _print_list(self, expr):
return "[%s]" % self.stringify(expr, ", ")
def _print_MatrixBase(self, expr):
return expr._format_str(self)
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
+ '[%s, %s]' % (self._print(expr.i), self._print(expr.j))
def _print_MatrixSlice(self, expr):
def strslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = ''
if x[1] == dim:
x[1] = ''
return ':'.join(map(lambda arg: self._print(arg), x))
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' +
strslice(expr.rowslice, expr.parent.rows) + ', ' +
strslice(expr.colslice, expr.parent.cols) + ']')
def _print_DeferredVector(self, expr):
return expr.name
def _print_Mul(self, expr):
prec = precedence(expr)
# Check for unevaluated Mul. In this case we need to make sure the
# identities are visible, multiple Rational factors are not combined
# etc so we display in a straight-forward form that fully preserves all
# args and their order.
args = expr.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
factors = [self.parenthesize(a, prec, strict=False) for a in args]
return '*'.join(factors)
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
# Gather args for numerator/denominator
for item in args:
if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
pow_paren.append(item)
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append(Rational(item.p))
if item.q != 1:
b.append(Rational(item.q))
else:
a.append(item)
a = a or [S.One]
a_str = [self.parenthesize(x, prec, strict=False) for x in a]
b_str = [self.parenthesize(x, prec, strict=False) for x in b]
# To parenthesize Pow with exp = -1 and having more than one Symbol
for item in pow_paren:
if item.base in b:
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
if not b:
return sign + '*'.join(a_str)
elif len(b) == 1:
return sign + '*'.join(a_str) + "/" + b_str[0]
else:
return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
def _print_MatMul(self, expr):
c, m = expr.as_coeff_mmul()
sign = ""
if c.is_number:
re, im = c.as_real_imag()
if im.is_zero and re.is_negative:
expr = _keep_coeff(-c, m)
sign = "-"
elif re.is_zero and im.is_negative:
expr = _keep_coeff(-c, m)
sign = "-"
return sign + '*'.join(
[self.parenthesize(arg, precedence(expr)) for arg in expr.args]
)
def _print_ElementwiseApplyFunction(self, expr):
return "{0}.({1})".format(
expr.function,
self._print(expr.expr),
)
def _print_NaN(self, expr):
return 'nan'
def _print_NegativeInfinity(self, expr):
return '-oo'
def _print_Order(self, expr):
if not expr.variables or all(p is S.Zero for p in expr.point):
if len(expr.variables) <= 1:
return 'O(%s)' % self._print(expr.expr)
else:
return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0)
else:
return 'O(%s)' % self.stringify(expr.args, ', ', 0)
def _print_Ordinal(self, expr):
return expr.__str__()
def _print_Cycle(self, expr):
return expr.__str__()
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
from sympy.utilities.exceptions import SymPyDeprecationWarning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
if not expr.size:
return '()'
# before taking Cycle notation, see if the last element is
# a singleton and move it to the head of the string
s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
last = s.rfind('(')
if not last == 0 and ',' not in s[last:]:
s = s[last:] + s[:last]
s = s.replace(',', '')
return s
else:
s = expr.support()
if not s:
if expr.size < 5:
return 'Permutation(%s)' % self._print(expr.array_form)
return 'Permutation([], size=%s)' % self._print(expr.size)
trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size)
use = full = self._print(expr.array_form)
if len(trim) < len(full):
use = trim
return 'Permutation(%s)' % use
def _print_Subs(self, obj):
expr, old, new = obj.args
if len(obj.point) == 1:
old = old[0]
new = new[0]
return "Subs(%s, %s, %s)" % (
self._print(expr), self._print(old), self._print(new))
def _print_TensorIndex(self, expr):
return expr._print()
def _print_TensorHead(self, expr):
return expr._print()
def _print_Tensor(self, expr):
return expr._print()
def _print_TensMul(self, expr):
# prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
sign, args = expr._get_args_for_traditional_printer()
return sign + "*".join(
[self.parenthesize(arg, precedence(expr)) for arg in args]
)
def _print_TensAdd(self, expr):
return expr._print()
def _print_PermutationGroup(self, expr):
p = [' %s' % self._print(a) for a in expr.args]
return 'PermutationGroup([\n%s])' % ',\n'.join(p)
def _print_Pi(self, expr):
return 'pi'
def _print_PolyRing(self, ring):
return "Polynomial ring in %s over %s with %s order" % \
(", ".join(map(lambda rs: self._print(rs), ring.symbols)),
self._print(ring.domain), self._print(ring.order))
def _print_FracField(self, field):
return "Rational function field in %s over %s with %s order" % \
(", ".join(map(lambda fs: self._print(fs), field.symbols)),
self._print(field.domain), self._print(field.order))
def _print_FreeGroupElement(self, elm):
return elm.__str__()
def _print_GaussianElement(self, poly):
return "(%s + %s*I)" % (poly.x, poly.y)
def _print_PolyElement(self, poly):
return poly.str(self, PRECEDENCE, "%s**%s", "*")
def _print_FracElement(self, frac):
if frac.denom == 1:
return self._print(frac.numer)
else:
numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True)
denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True)
return numer + "/" + denom
def _print_Poly(self, expr):
ATOM_PREC = PRECEDENCE["Atom"] - 1
terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ]
for monom, coeff in expr.terms():
s_monom = []
for i, exp in enumerate(monom):
if exp > 0:
if exp == 1:
s_monom.append(gens[i])
else:
s_monom.append(gens[i] + "**%d" % exp)
s_monom = "*".join(s_monom)
if coeff.is_Add:
if s_monom:
s_coeff = "(" + self._print(coeff) + ")"
else:
s_coeff = self._print(coeff)
else:
if s_monom:
if coeff is S.One:
terms.extend(['+', s_monom])
continue
if coeff is S.NegativeOne:
terms.extend(['-', s_monom])
continue
s_coeff = self._print(coeff)
if not s_monom:
s_term = s_coeff
else:
s_term = s_coeff + "*" + s_monom
if s_term.startswith('-'):
terms.extend(['-', s_term[1:]])
else:
terms.extend(['+', s_term])
if terms[0] in ['-', '+']:
modifier = terms.pop(0)
if modifier == '-':
terms[0] = '-' + terms[0]
format = expr.__class__.__name__ + "(%s, %s"
from sympy.polys.polyerrors import PolynomialError
try:
format += ", modulus=%s" % expr.get_modulus()
except PolynomialError:
format += ", domain='%s'" % expr.get_domain()
format += ")"
for index, item in enumerate(gens):
if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"):
gens[index] = item[1:len(item) - 1]
return format % (' '.join(terms), ', '.join(gens))
def _print_UniversalSet(self, p):
return 'UniversalSet'
def _print_AlgebraicNumber(self, expr):
if expr.is_aliased:
return self._print(expr.as_poly().as_expr())
else:
return self._print(expr.as_expr())
def _print_Pow(self, expr, rational=False):
"""Printing helper function for ``Pow``
Parameters
==========
rational : bool, optional
If ``True``, it will not attempt printing ``sqrt(x)`` or
``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)``
instead.
See examples for additional details
Examples
========
>>> from sympy.functions import sqrt
>>> from sympy.printing.str import StrPrinter
>>> from sympy.abc import x
How ``rational`` keyword works with ``sqrt``:
>>> printer = StrPrinter()
>>> printer._print_Pow(sqrt(x), rational=True)
'x**(1/2)'
>>> printer._print_Pow(sqrt(x), rational=False)
'sqrt(x)'
>>> printer._print_Pow(1/sqrt(x), rational=True)
'x**(-1/2)'
>>> printer._print_Pow(1/sqrt(x), rational=False)
'1/sqrt(x)'
Notes
=====
``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy,
so there is no need of defining a separate printer for ``sqrt``.
Instead, it should be handled here as well.
"""
PREC = precedence(expr)
if expr.exp is S.Half and not rational:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if -expr.exp is S.Half and not rational:
# Note: Don't test "expr.exp == -S.Half" here, because that will
# match -0.5, which we don't want.
return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base)))
if expr.exp is -S.One:
# Similarly to the S.Half case, don't test with "==" here.
return '%s/%s' % (self._print(S.One),
self.parenthesize(expr.base, PREC, strict=False))
e = self.parenthesize(expr.exp, PREC, strict=False)
if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1:
# the parenthesized exp should be '(Rational(a, b))' so strip parens,
# but just check to be sure.
if e.startswith('(Rational'):
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1])
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def _print_MatPow(self, expr):
PREC = precedence(expr)
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False),
self.parenthesize(expr.exp, PREC, strict=False))
def _print_Integer(self, expr):
if self._settings.get("sympy_integers", False):
return "S(%s)" % (expr)
return str(expr.p)
def _print_Integers(self, expr):
return 'Integers'
def _print_Naturals(self, expr):
return 'Naturals'
def _print_Naturals0(self, expr):
return 'Naturals0'
def _print_Rationals(self, expr):
return 'Rationals'
def _print_Reals(self, expr):
return 'Reals'
def _print_Complexes(self, expr):
return 'Complexes'
def _print_EmptySet(self, expr):
return 'EmptySet'
def _print_EmptySequence(self, expr):
return 'EmptySequence'
def _print_int(self, expr):
return str(expr)
def _print_mpz(self, expr):
return str(expr)
def _print_Rational(self, expr):
if expr.q == 1:
return str(expr.p)
else:
if self._settings.get("sympy_integers", False):
return "S(%s)/%s" % (expr.p, expr.q)
return "%s/%s" % (expr.p, expr.q)
def _print_PythonRational(self, expr):
if expr.q == 1:
return str(expr.p)
else:
return "%d/%d" % (expr.p, expr.q)
def _print_Fraction(self, expr):
if expr.denominator == 1:
return str(expr.numerator)
else:
return "%s/%s" % (expr.numerator, expr.denominator)
def _print_mpq(self, expr):
if expr.denominator == 1:
return str(expr.numerator)
else:
return "%s/%s" % (expr.numerator, expr.denominator)
def _print_Float(self, expr):
prec = expr._prec
if prec < 5:
dps = 0
else:
dps = prec_to_dps(expr._prec)
if self._settings["full_prec"] is True:
strip = False
elif self._settings["full_prec"] is False:
strip = True
elif self._settings["full_prec"] == "auto":
strip = self._print_level > 1
low = self._settings["min"] if "min" in self._settings else None
high = self._settings["max"] if "max" in self._settings else None
rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
if rv.startswith('-.0'):
rv = '-0.' + rv[3:]
elif rv.startswith('.0'):
rv = '0.' + rv[2:]
if rv.startswith('+'):
# e.g., +inf -> inf
rv = rv[1:]
return rv
def _print_Relational(self, expr):
charmap = {
"==": "Eq",
"!=": "Ne",
":=": "Assignment",
'+=': "AddAugmentedAssignment",
"-=": "SubAugmentedAssignment",
"*=": "MulAugmentedAssignment",
"/=": "DivAugmentedAssignment",
"%=": "ModAugmentedAssignment",
}
if expr.rel_op in charmap:
return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs),
self._print(expr.rhs))
return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)),
self._relationals.get(expr.rel_op) or expr.rel_op,
self.parenthesize(expr.rhs, precedence(expr)))
def _print_ComplexRootOf(self, expr):
return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'),
expr.index)
def _print_RootSum(self, expr):
args = [self._print_Add(expr.expr, order='lex')]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
return "RootSum(%s)" % ", ".join(args)
def _print_GroebnerBasis(self, basis):
cls = basis.__class__.__name__
exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs]
exprs = "[%s]" % ", ".join(exprs)
gens = [ self._print(gen) for gen in basis.gens ]
domain = "domain='%s'" % self._print(basis.domain)
order = "order='%s'" % self._print(basis.order)
args = [exprs] + gens + [domain, order]
return "%s(%s)" % (cls, ", ".join(args))
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
args = ', '.join(self._print(item) for item in items)
if not args:
return "set()"
return '{%s}' % args
def _print_frozenset(self, s):
if not s:
return "frozenset()"
return "frozenset(%s)" % self._print_set(s)
def _print_Sum(self, expr):
def _xab_tostr(xab):
if len(xab) == 1:
return self._print(xab[0])
else:
return self._print((xab[0],) + tuple(xab[1:]))
L = ', '.join([_xab_tostr(l) for l in expr.limits])
return 'Sum(%s, %s)' % (self._print(expr.function), L)
def _print_Symbol(self, expr):
return expr.name
_print_MatrixSymbol = _print_Symbol
_print_RandomSymbol = _print_Symbol
def _print_Identity(self, expr):
return "I"
def _print_ZeroMatrix(self, expr):
return "0"
def _print_OneMatrix(self, expr):
return "1"
def _print_Predicate(self, expr):
return "Q.%s" % expr.name
def _print_str(self, expr):
return str(expr)
def _print_tuple(self, expr):
if len(expr) == 1:
return "(%s,)" % self._print(expr[0])
else:
return "(%s)" % self.stringify(expr, ", ")
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_Transpose(self, T):
return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"])
def _print_Uniform(self, expr):
return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b))
def _print_Quantity(self, expr):
if self._settings.get("abbrev", False):
return "%s" % expr.abbrev
return "%s" % expr.name
def _print_Quaternion(self, expr):
s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args]
a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")]
return " + ".join(a)
def _print_Dimension(self, expr):
return str(expr)
def _print_Wild(self, expr):
return expr.name + '_'
def _print_WildFunction(self, expr):
return expr.name + '_'
def _print_Zero(self, expr):
if self._settings.get("sympy_integers", False):
return "S(0)"
return "0"
def _print_DMP(self, p):
from sympy.core.sympify import SympifyError
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
cls = p.__class__.__name__
rep = self._print(p.rep)
dom = self._print(p.dom)
ring = self._print(p.ring)
return "%s(%s, %s, %s)" % (cls, rep, dom, ring)
def _print_DMF(self, expr):
return self._print_DMP(expr)
def _print_Object(self, obj):
return 'Object("%s")' % obj.name
def _print_IdentityMorphism(self, morphism):
return 'IdentityMorphism(%s)' % morphism.domain
def _print_NamedMorphism(self, morphism):
return 'NamedMorphism(%s, %s, "%s")' % \
(morphism.domain, morphism.codomain, morphism.name)
def _print_Category(self, category):
return 'Category("%s")' % category.name
def _print_Manifold(self, manifold):
return manifold.name.name
def _print_Patch(self, patch):
return patch.name.name
def _print_CoordSystem(self, coords):
return coords.name.name
def _print_BaseScalarField(self, field):
return field._coord_sys.symbols[field._index].name
def _print_BaseVectorField(self, field):
return 'e_%s' % field._coord_sys.symbols[field._index].name
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
return 'd%s' % field._coord_sys.symbols[field._index].name
else:
return 'd(%s)' % self._print(field)
def _print_Tr(self, expr):
#TODO : Handle indices
return "%s(%s)" % ("Tr", self._print(expr.args[0]))
def _print_Str(self, s):
return self._print(s.name)
def sstr(expr, **settings):
"""Returns the expression as a string.
For large expressions where speed is a concern, use the setting
order='none'. If abbrev=True setting is used then units are printed in
abbreviated form.
Examples
========
>>> from sympy import symbols, Eq, sstr
>>> a, b = symbols('a b')
>>> sstr(Eq(a + b, 0))
'Eq(a + b, 0)'
"""
p = StrPrinter(settings)
s = p.doprint(expr)
return s
class StrReprPrinter(StrPrinter):
"""(internal) -- see sstrrepr"""
def _print_str(self, s):
return repr(s)
def _print_Str(self, s):
# Str does not to be printed same as str here
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
def sstrrepr(expr, **settings):
"""return expr in mixed str/repr form
i.e. strings are returned in repr form with quotes, and everything else
is returned in str form.
This function could be useful for hooking into sys.displayhook
"""
p = StrReprPrinter(settings)
s = p.doprint(expr)
return s
|
5b059a164f16ba0a2fd642a11ee0e0c78584dc764b03aca9a9b838c0941bd842 | """Printing subsystem"""
from .pretty import pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode
from .latex import latex, print_latex, multiline_latex
from .mathml import mathml, print_mathml
from .python import python, print_python
from .pycode import pycode
from .codeprinter import print_ccode, print_fcode
from .codeprinter import ccode, fcode, cxxcode # noqa:F811
from .glsl import glsl_code, print_glsl
from .rcode import rcode, print_rcode
from .jscode import jscode, print_jscode
from .julia import julia_code
from .mathematica import mathematica_code
from .octave import octave_code
from .rust import rust_code
from .gtk import print_gtk
from .preview import preview
from .repr import srepr
from .tree import print_tree
from .str import StrPrinter, sstr, sstrrepr
from .tableform import TableForm
from .dot import dotprint
from .maple import maple_code, print_maple_code
__all__ = [
# sympy.printing.pretty
'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
'pprint_try_use_unicode',
# sympy.printing.latex
'latex', 'print_latex', 'multiline_latex',
# sympy.printing.mathml
'mathml', 'print_mathml',
# sympy.printing.python
'python', 'print_python',
# sympy.printing.pycode
'pycode',
# sympy.printing.codeprinter
'ccode', 'print_ccode', 'cxxcode', 'fcode', 'print_fcode',
# sympy.printing.glsl
'glsl_code', 'print_glsl',
# sympy.printing.rcode
'rcode', 'print_rcode',
# sympy.printing.jscode
'jscode', 'print_jscode',
# sympy.printing.julia
'julia_code',
# sympy.printing.mathematica
'mathematica_code',
# sympy.printing.octave
'octave_code',
# sympy.printing.rust
'rust_code',
# sympy.printing.gtk
'print_gtk',
# sympy.printing.preview
'preview',
# sympy.printing.repr
'srepr',
# sympy.printing.tree
'print_tree',
# sympy.printing.str
'StrPrinter', 'sstr', 'sstrrepr',
# sympy.printing.tableform
'TableForm',
# sympy.printing.dot
'dotprint',
# sympy.printing.maple
'maple_code', 'print_maple_code',
]
|
0c1d1e721d28637d9c6625a6c3fea8eca95468f18f926598fd1cd61cf4e6b670 | """
Rust code printer
The `RustCodePrinter` converts SymPy expressions into Rust expressions.
A complete code generator, which uses `rust_code` extensively, can be found
in `sympy.utilities.codegen`. The `codegen` module can be used to generate
complete source code files.
"""
# Possible Improvement
#
# * make sure we follow Rust Style Guidelines_
# * make use of pattern matching
# * better support for reference
# * generate generic code and use trait to make sure they have specific methods
# * use crates_ to get more math support
# - num_
# + BigInt_, BigUint_
# + Complex_
# + Rational64_, Rational32_, BigRational_
#
# .. _crates: https://crates.io/
# .. _Guidelines: https://github.com/rust-lang/rust/tree/master/src/doc/style
# .. _num: http://rust-num.github.io/num/num/
# .. _BigInt: http://rust-num.github.io/num/num/bigint/struct.BigInt.html
# .. _BigUint: http://rust-num.github.io/num/num/bigint/struct.BigUint.html
# .. _Complex: http://rust-num.github.io/num/num/complex/struct.Complex.html
# .. _Rational32: http://rust-num.github.io/num/num/rational/type.Rational32.html
# .. _Rational64: http://rust-num.github.io/num/num/rational/type.Rational64.html
# .. _BigRational: http://rust-num.github.io/num/num/rational/type.BigRational.html
from __future__ import print_function, division
from typing import Any, Dict
from sympy.core import S, Rational, Float, Lambda
from sympy.printing.codeprinter import CodePrinter
# Rust's methods for integer and float can be found at here :
#
# * `Rust - Primitive Type f64 <https://doc.rust-lang.org/std/primitive.f64.html>`_
# * `Rust - Primitive Type i64 <https://doc.rust-lang.org/std/primitive.i64.html>`_
#
# Function Style :
#
# 1. args[0].func(args[1:]), method with arguments
# 2. args[0].func(), method without arguments
# 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
# 4. func(args), function with arguments
# dictionary mapping sympy function to (argument_conditions, Rust_function).
# Used in RustCodePrinter._print_Function(self)
# f64 method in Rust
known_functions = {
# "": "is_nan",
# "": "is_infinite",
# "": "is_finite",
# "": "is_normal",
# "": "classify",
"floor": "floor",
"ceiling": "ceil",
# "": "round",
# "": "trunc",
# "": "fract",
"Abs": "abs",
"sign": "signum",
# "": "is_sign_positive",
# "": "is_sign_negative",
# "": "mul_add",
"Pow": [(lambda base, exp: exp == -S.One, "recip", 2), # 1.0/x
(lambda base, exp: exp == S.Half, "sqrt", 2), # x ** 0.5
(lambda base, exp: exp == -S.Half, "sqrt().recip", 2), # 1/(x ** 0.5)
(lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3)
(lambda base, exp: base == S.One*2, "exp2", 3), # 2 ** x
(lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32
(lambda base, exp: not exp.is_integer, "powf", 1)], # x ** y, for f64
"exp": [(lambda exp: True, "exp", 2)], # e ** x
"log": "ln",
# "": "log", # number.log(base)
# "": "log2",
# "": "log10",
# "": "to_degrees",
# "": "to_radians",
"Max": "max",
"Min": "min",
# "": "hypot", # (x**2 + y**2) ** 0.5
"sin": "sin",
"cos": "cos",
"tan": "tan",
"asin": "asin",
"acos": "acos",
"atan": "atan",
"atan2": "atan2",
# "": "sin_cos",
# "": "exp_m1", # e ** x - 1
# "": "ln_1p", # ln(1 + x)
"sinh": "sinh",
"cosh": "cosh",
"tanh": "tanh",
"asinh": "asinh",
"acosh": "acosh",
"atanh": "atanh",
}
# i64 method in Rust
# known_functions_i64 = {
# "": "min_value",
# "": "max_value",
# "": "from_str_radix",
# "": "count_ones",
# "": "count_zeros",
# "": "leading_zeros",
# "": "trainling_zeros",
# "": "rotate_left",
# "": "rotate_right",
# "": "swap_bytes",
# "": "from_be",
# "": "from_le",
# "": "to_be", # to big endian
# "": "to_le", # to little endian
# "": "checked_add",
# "": "checked_sub",
# "": "checked_mul",
# "": "checked_div",
# "": "checked_rem",
# "": "checked_neg",
# "": "checked_shl",
# "": "checked_shr",
# "": "checked_abs",
# "": "saturating_add",
# "": "saturating_sub",
# "": "saturating_mul",
# "": "wrapping_add",
# "": "wrapping_sub",
# "": "wrapping_mul",
# "": "wrapping_div",
# "": "wrapping_rem",
# "": "wrapping_neg",
# "": "wrapping_shl",
# "": "wrapping_shr",
# "": "wrapping_abs",
# "": "overflowing_add",
# "": "overflowing_sub",
# "": "overflowing_mul",
# "": "overflowing_div",
# "": "overflowing_rem",
# "": "overflowing_neg",
# "": "overflowing_shl",
# "": "overflowing_shr",
# "": "overflowing_abs",
# "Pow": "pow",
# "Abs": "abs",
# "sign": "signum",
# "": "is_positive",
# "": "is_negnative",
# }
# These are the core reserved words in the Rust language. Taken from:
# http://doc.rust-lang.org/grammar.html#keywords
reserved_words = ['abstract',
'alignof',
'as',
'become',
'box',
'break',
'const',
'continue',
'crate',
'do',
'else',
'enum',
'extern',
'false',
'final',
'fn',
'for',
'if',
'impl',
'in',
'let',
'loop',
'macro',
'match',
'mod',
'move',
'mut',
'offsetof',
'override',
'priv',
'proc',
'pub',
'pure',
'ref',
'return',
'Self',
'self',
'sizeof',
'static',
'struct',
'super',
'trait',
'true',
'type',
'typeof',
'unsafe',
'unsized',
'use',
'virtual',
'where',
'while',
'yield']
class RustCodePrinter(CodePrinter):
"""A printer to convert python expressions to strings of Rust code"""
printmethod = "_rust_code"
language = "Rust"
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'contract': True,
'dereference': set(),
'error_on_reserved': False,
'reserved_word_suffix': '_',
'inline': False,
} # type: Dict[str, Any]
def __init__(self, settings={}):
CodePrinter.__init__(self, settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
self._dereference = set(settings.get('dereference', []))
self.reserved_words = set(reserved_words)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "// %s" % text
def _declare_number_const(self, name, value):
return "const %s: f64 = %s;" % (name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for i in range(rows) for j in range(cols))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
loopstart = "for %(var)s in %(start)s..%(end)s {"
for i in indices:
# Rust arrays start at 0 and end at dimension-1
open_lines.append(loopstart % {
'var': self._print(i),
'start': self._print(i.lower),
'end': self._print(i.upper + 1)})
close_lines.append("}")
return open_lines, close_lines
def _print_caller_var(self, expr):
if len(expr.args) > 1:
# for something like `sin(x + y + z)`,
# make sure we can get '(x + y + z).sin()'
# instead of 'x + y + z.sin()'
return '(' + self._print(expr) + ')'
elif expr.is_number:
return self._print(expr, _type=True)
else:
return self._print(expr)
def _print_Function(self, expr):
"""
basic function for printing `Function`
Function Style :
1. args[0].func(args[1:]), method with arguments
2. args[0].func(), method without arguments
3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
4. func(args), function with arguments
"""
if expr.func.__name__ in self.known_functions:
cond_func = self.known_functions[expr.func.__name__]
func = None
style = 1
if isinstance(cond_func, str):
func = cond_func
else:
for cond, func, style in cond_func:
if cond(*expr.args):
break
if func is not None:
if style == 1:
ret = "%(var)s.%(method)s(%(args)s)" % {
'var': self._print_caller_var(expr.args[0]),
'method': func,
'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else ''
}
elif style == 2:
ret = "%(var)s.%(method)s()" % {
'var': self._print_caller_var(expr.args[0]),
'method': func,
}
elif style == 3:
ret = "%(var)s.%(method)s()" % {
'var': self._print_caller_var(expr.args[1]),
'method': func,
}
else:
ret = "%(func)s(%(args)s)" % {
'func': func,
'args': self.stringify(expr.args, ", "),
}
return ret
elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
# inlined function
return self._print(expr._imp_(*expr.args))
else:
return self._print_not_supported(expr)
def _print_Pow(self, expr):
if expr.base.is_integer and not expr.exp.is_integer:
expr = type(expr)(Float(expr.base), expr.exp)
return self._print(expr)
return self._print_Function(expr)
def _print_Float(self, expr, _type=False):
ret = super(RustCodePrinter, self)._print_Float(expr)
if _type:
return ret + '_f64'
else:
return ret
def _print_Integer(self, expr, _type=False):
ret = super(RustCodePrinter, self)._print_Integer(expr)
if _type:
return ret + '_i32'
else:
return ret
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return '%d_f64/%d.0' % (p, q)
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_Indexed(self, expr):
# calculate index for 1d array
dims = expr.shape
elem = S.Zero
offset = S.One
for i in reversed(range(expr.rank)):
elem += expr.indices[i]*offset
offset *= dims[i]
return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
def _print_Idx(self, expr):
return expr.label.name
def _print_Dummy(self, expr):
return expr.name
def _print_Exp1(self, expr, _type=False):
return "E"
def _print_Pi(self, expr, _type=False):
return 'PI'
def _print_Infinity(self, expr, _type=False):
return 'INFINITY'
def _print_NegativeInfinity(self, expr, _type=False):
return 'NEG_INFINITY'
def _print_BooleanTrue(self, expr, _type=False):
return "true"
def _print_BooleanFalse(self, expr, _type=False):
return "false"
def _print_bool(self, expr, _type=False):
return str(expr).lower()
def _print_NaN(self, expr, _type=False):
return "NAN"
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) {" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines[-1] += " else {"
else:
lines[-1] += " else if (%s) {" % self._print(c)
code0 = self._print(e)
lines.append(code0)
lines.append("}")
if self._settings['inline']:
return " ".join(lines)
else:
return "\n".join(lines)
def _print_ITE(self, expr):
from sympy.functions import Piecewise
_piecewise = Piecewise((expr.args[1], expr.args[0]), (expr.args[2], True))
return self._print(_piecewise)
def _print_MatrixBase(self, A):
if A.cols == 1:
return "[%s]" % ", ".join(self._print(a) for a in A)
else:
raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).")
def _print_SparseMatrix(self, mat):
# do not allow sparse matrices to be made dense
return self._print_not_supported(mat)
def _print_MatrixElement(self, expr):
return "%s[%s]" % (expr.parent,
expr.j + expr.i*expr.parent.shape[1])
def _print_Symbol(self, expr):
name = super(RustCodePrinter, self)._print_Symbol(expr)
if expr in self._dereference:
return '(*%s)' % name
else:
return name
def _print_Assignment(self, expr):
from sympy.tensor.indexed import IndexedBase
lhs = expr.lhs
rhs = expr.rhs
if self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
decrease = [ int(any(map(line.startswith, dec_token)))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def rust_code(expr, assign_to=None, **settings):
"""Converts an expr to a string of Rust code
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=15].
user_functions : dict, optional
A dictionary where the keys are string representations of either
``FunctionClass`` or ``UndefinedFunction`` instances and the values
are their desired C string representations. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
cfunction_string)]. See below for examples.
dereference : iterable, optional
An iterable of symbols that should be dereferenced in the printed code
expression. These would be values passed by address to the function.
For example, if ``dereference=[a]``, the resulting code would print
``(*a)`` instead of ``a``.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
Examples
========
>>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> rust_code((2*tau)**Rational(7, 2))
'8*1.4142135623731*tau.powf(7_f64/2.0)'
>>> rust_code(sin(x), assign_to="s")
's = x.sin();'
Simple custom printing can be defined for certain types by passing a
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
Alternatively, the dictionary value can be a list of tuples i.e.
[(argument_test, cfunction_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "Abs": [(lambda x: not x.is_integer, "fabs", 4),
... (lambda x: x.is_integer, "ABS", 4)],
... "func": "f"
... }
>>> func = Function('func')
>>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
'(fabs(x) + x.CEIL()).f()'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(rust_code(expr, tau))
tau = if (x > 0) {
x + 1
} else {
x
};
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> rust_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(rust_code(mat, A))
A = [x.powi(2), if (x > 0) {
x + 1
} else {
x
}, x.sin()];
"""
return RustCodePrinter(settings).doprint(expr, assign_to)
def print_rust_code(expr, **settings):
"""Prints Rust representation of the given expression."""
print(rust_code(expr, **settings))
|
b7774aa8930090d11f1b1f7db2c18e1e25103b3e69f5924da09e759460349bfa | """
C++ code printer
"""
from __future__ import (absolute_import, division, print_function)
from itertools import chain
from sympy.codegen.ast import Type, none
from .c import C89CodePrinter, C99CodePrinter
# These are defined in the other file so we can avoid importing sympy.codegen
# from the top-level 'import sympy'. Export them here as well.
from sympy.printing.codeprinter import cxxcode # noqa:F401
# from http://en.cppreference.com/w/cpp/keyword
reserved = {
'C++98': [
'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break',
'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast',
'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast',
'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float',
'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable',
'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq',
'private', 'protected', 'public', 'register', 'reinterpret_cast',
'return', 'short', 'signed', 'sizeof', 'static', 'static_cast',
'struct', 'switch', 'template', 'this', 'throw', 'true', 'try',
'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using',
'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'
]
}
reserved['C++11'] = reserved['C++98'][:] + [
'alignas', 'alignof', 'char16_t', 'char32_t', 'constexpr', 'decltype',
'noexcept', 'nullptr', 'static_assert', 'thread_local'
]
reserved['C++17'] = reserved['C++11'][:]
reserved['C++17'].remove('register')
# TM TS: atomic_cancel, atomic_commit, atomic_noexcept, synchronized
# concepts TS: concept, requires
# module TS: import, module
_math_functions = {
'C++98': {
'Mod': 'fmod',
'ceiling': 'ceil',
},
'C++11': {
'gamma': 'tgamma',
},
'C++17': {
'beta': 'beta',
'Ei': 'expint',
'zeta': 'riemann_zeta',
}
}
# from http://en.cppreference.com/w/cpp/header/cmath
for k in ('Abs', 'exp', 'log', 'log10', 'sqrt', 'sin', 'cos', 'tan', # 'Pow'
'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'floor'):
_math_functions['C++98'][k] = k.lower()
for k in ('asinh', 'acosh', 'atanh', 'erf', 'erfc'):
_math_functions['C++11'][k] = k.lower()
def _attach_print_method(cls, sympy_name, func_name):
meth_name = '_print_%s' % sympy_name
if hasattr(cls, meth_name):
raise ValueError("Edit method (or subclass) instead of overwriting.")
def _print_method(self, expr):
return '{0}{1}({2})'.format(self._ns, func_name, ', '.join(map(self._print, expr.args)))
_print_method.__doc__ = "Prints code for %s" % k
setattr(cls, meth_name, _print_method)
def _attach_print_methods(cls, cont):
for sympy_name, cxx_name in cont[cls.standard].items():
_attach_print_method(cls, sympy_name, cxx_name)
class _CXXCodePrinterBase(object):
printmethod = "_cxxcode"
language = 'C++'
_ns = 'std::' # namespace
def __init__(self, settings=None):
super(_CXXCodePrinterBase, self).__init__(settings or {})
def _print_Max(self, expr):
from sympy import Max
if len(expr.args) == 1:
return self._print(expr.args[0])
return "%smax(%s, %s)" % (self._ns, expr.args[0], self._print(Max(*expr.args[1:])))
def _print_Min(self, expr):
from sympy import Min
if len(expr.args) == 1:
return self._print(expr.args[0])
return "%smin(%s, %s)" % (self._ns, expr.args[0], self._print(Min(*expr.args[1:])))
def _print_using(self, expr):
if expr.alias == none:
return 'using %s' % expr.type
else:
raise ValueError("C++98 does not support type aliases")
class CXX98CodePrinter(_CXXCodePrinterBase, C89CodePrinter):
standard = 'C++98'
reserved_words = set(reserved['C++98'])
# _attach_print_methods(CXX98CodePrinter, _math_functions)
class CXX11CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
standard = 'C++11'
reserved_words = set(reserved['C++11'])
type_mappings = dict(chain(
CXX98CodePrinter.type_mappings.items(),
{
Type('int8'): ('int8_t', {'cstdint'}),
Type('int16'): ('int16_t', {'cstdint'}),
Type('int32'): ('int32_t', {'cstdint'}),
Type('int64'): ('int64_t', {'cstdint'}),
Type('uint8'): ('uint8_t', {'cstdint'}),
Type('uint16'): ('uint16_t', {'cstdint'}),
Type('uint32'): ('uint32_t', {'cstdint'}),
Type('uint64'): ('uint64_t', {'cstdint'}),
Type('complex64'): ('std::complex<float>', {'complex'}),
Type('complex128'): ('std::complex<double>', {'complex'}),
Type('bool'): ('bool', None),
}.items()
))
def _print_using(self, expr):
if expr.alias == none:
return super(CXX11CodePrinter, self)._print_using(expr)
else:
return 'using %(alias)s = %(type)s' % expr.kwargs(apply=self._print)
# _attach_print_methods(CXX11CodePrinter, _math_functions)
class CXX17CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
standard = 'C++17'
reserved_words = set(reserved['C++17'])
_kf = dict(C99CodePrinter._kf, **_math_functions['C++17'])
def _print_beta(self, expr):
return self._print_math_func(expr)
def _print_Ei(self, expr):
return self._print_math_func(expr)
def _print_zeta(self, expr):
return self._print_math_func(expr)
# _attach_print_methods(CXX17CodePrinter, _math_functions)
cxx_code_printers = {
'c++98': CXX98CodePrinter,
'c++11': CXX11CodePrinter,
'c++17': CXX17CodePrinter
}
|
6db3f65d8d8c2b83c395c1f2c79aadc7d3bd279aa135e64cc6bdc889b69c2e30 | """
A Printer which converts an expression into its LaTeX equivalent.
"""
from __future__ import print_function, division
from typing import Any, Dict
import itertools
from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol
from sympy.core.alphabets import greeks
from sympy.core.containers import Tuple
from sympy.core.function import _coeff_isneg, AppliedUndef, Derivative
from sympy.core.operations import AssocOp
from sympy.core.sympify import SympifyError
from sympy.logic.boolalg import true
# sympy.printing imports
from sympy.printing.precedence import precedence_traditional
from sympy.printing.printer import Printer
from sympy.printing.conventions import split_super_sub, requires_partial
from sympy.printing.precedence import precedence, PRECEDENCE
import mpmath.libmp as mlib
from mpmath.libmp import prec_to_dps
from sympy.core.compatibility import default_sort_key
from sympy.utilities.iterables import has_variety
import re
# Hand-picked functions which can be used directly in both LaTeX and MathJax
# Complete list at
# https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands
# This variable only contains those functions which sympy uses.
accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan',
'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec',
'csc', 'cot', 'coth', 're', 'im', 'frac', 'root',
'arg',
]
tex_greek_dictionary = {
'Alpha': 'A',
'Beta': 'B',
'Gamma': r'\Gamma',
'Delta': r'\Delta',
'Epsilon': 'E',
'Zeta': 'Z',
'Eta': 'H',
'Theta': r'\Theta',
'Iota': 'I',
'Kappa': 'K',
'Lambda': r'\Lambda',
'Mu': 'M',
'Nu': 'N',
'Xi': r'\Xi',
'omicron': 'o',
'Omicron': 'O',
'Pi': r'\Pi',
'Rho': 'P',
'Sigma': r'\Sigma',
'Tau': 'T',
'Upsilon': r'\Upsilon',
'Phi': r'\Phi',
'Chi': 'X',
'Psi': r'\Psi',
'Omega': r'\Omega',
'lamda': r'\lambda',
'Lamda': r'\Lambda',
'khi': r'\chi',
'Khi': r'X',
'varepsilon': r'\varepsilon',
'varkappa': r'\varkappa',
'varphi': r'\varphi',
'varpi': r'\varpi',
'varrho': r'\varrho',
'varsigma': r'\varsigma',
'vartheta': r'\vartheta',
}
other_symbols = set(['aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
'hslash', 'mho', 'wp', ])
# Variable name modifiers
modifier_dict = {
# Accents
'mathring': lambda s: r'\mathring{'+s+r'}',
'ddddot': lambda s: r'\ddddot{'+s+r'}',
'dddot': lambda s: r'\dddot{'+s+r'}',
'ddot': lambda s: r'\ddot{'+s+r'}',
'dot': lambda s: r'\dot{'+s+r'}',
'check': lambda s: r'\check{'+s+r'}',
'breve': lambda s: r'\breve{'+s+r'}',
'acute': lambda s: r'\acute{'+s+r'}',
'grave': lambda s: r'\grave{'+s+r'}',
'tilde': lambda s: r'\tilde{'+s+r'}',
'hat': lambda s: r'\hat{'+s+r'}',
'bar': lambda s: r'\bar{'+s+r'}',
'vec': lambda s: r'\vec{'+s+r'}',
'prime': lambda s: "{"+s+"}'",
'prm': lambda s: "{"+s+"}'",
# Faces
'bold': lambda s: r'\boldsymbol{'+s+r'}',
'bm': lambda s: r'\boldsymbol{'+s+r'}',
'cal': lambda s: r'\mathcal{'+s+r'}',
'scr': lambda s: r'\mathscr{'+s+r'}',
'frak': lambda s: r'\mathfrak{'+s+r'}',
# Brackets
'norm': lambda s: r'\left\|{'+s+r'}\right\|',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
'abs': lambda s: r'\left|{'+s+r'}\right|',
'mag': lambda s: r'\left|{'+s+r'}\right|',
}
greek_letters_set = frozenset(greeks)
_between_two_numbers_p = (
re.compile(r'[0-9][} ]*$'), # search
re.compile(r'[{ ]*[-+0-9]'), # match
)
def latex_escape(s):
"""
Escape a string such that latex interprets it as plaintext.
We can't use verbatim easily with mathjax, so escaping is easier.
Rules from https://tex.stackexchange.com/a/34586/41112.
"""
s = s.replace('\\', r'\textbackslash')
for c in '&%$#_{}':
s = s.replace(c, '\\' + c)
s = s.replace('~', r'\textasciitilde')
s = s.replace('^', r'\textasciicircum')
return s
class LatexPrinter(Printer):
printmethod = "_latex"
_default_settings = {
"full_prec": False,
"fold_frac_powers": False,
"fold_func_brackets": False,
"fold_short_frac": None,
"inv_trig_style": "abbreviated",
"itex": False,
"ln_notation": False,
"long_frac_ratio": None,
"mat_delim": "[",
"mat_str": None,
"mode": "plain",
"mul_symbol": None,
"order": None,
"symbol_names": {},
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"gothic_re_im": False,
"decimal_separator": "period",
"perm_cyclic": True,
"parenthesize_super": True,
"min": None,
"max": None,
} # type: Dict[str, Any]
def __init__(self, settings=None):
Printer.__init__(self, settings)
if 'mode' in self._settings:
valid_modes = ['inline', 'plain', 'equation',
'equation*']
if self._settings['mode'] not in valid_modes:
raise ValueError("'mode' must be one of 'inline', 'plain', "
"'equation' or 'equation*'")
if self._settings['fold_short_frac'] is None and \
self._settings['mode'] == 'inline':
self._settings['fold_short_frac'] = True
mul_symbol_table = {
None: r" ",
"ldot": r" \,.\, ",
"dot": r" \cdot ",
"times": r" \times "
}
try:
self._settings['mul_symbol_latex'] = \
mul_symbol_table[self._settings['mul_symbol']]
except KeyError:
self._settings['mul_symbol_latex'] = \
self._settings['mul_symbol']
try:
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table[self._settings['mul_symbol'] or 'dot']
except KeyError:
if (self._settings['mul_symbol'].strip() in
['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table['dot']
else:
self._settings['mul_symbol_latex_numbers'] = \
self._settings['mul_symbol']
self._delim_dict = {'(': ')', '[': ']'}
imaginary_unit_table = {
None: r"i",
"i": r"i",
"ri": r"\mathrm{i}",
"ti": r"\text{i}",
"j": r"j",
"rj": r"\mathrm{j}",
"tj": r"\text{j}",
}
try:
self._settings['imaginary_unit_latex'] = \
imaginary_unit_table[self._settings['imaginary_unit']]
except KeyError:
self._settings['imaginary_unit_latex'] = \
self._settings['imaginary_unit']
def _add_parens(self, s):
return r"\left({}\right)".format(s)
# TODO: merge this with the above, which requires a lot of test changes
def _add_parens_lspace(self, s):
return r"\left( {}\right)".format(s)
def parenthesize(self, item, level, is_neg=False, strict=False):
prec_val = precedence_traditional(item)
if is_neg and strict:
return self._add_parens(self._print(item))
if (prec_val < level) or ((not strict) and prec_val <= level):
return self._add_parens(self._print(item))
else:
return self._print(item)
def parenthesize_super(self, s):
"""
Protect superscripts in s
If the parenthesize_super option is set, protect with parentheses, else
wrap in braces.
"""
if "^" in s:
if self._settings['parenthesize_super']:
return self._add_parens(s)
else:
return "{{{}}}".format(s)
return s
def doprint(self, expr):
tex = Printer.doprint(self, expr)
if self._settings['mode'] == 'plain':
return tex
elif self._settings['mode'] == 'inline':
return r"$%s$" % tex
elif self._settings['itex']:
return r"$$%s$$" % tex
else:
env_str = self._settings['mode']
return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str)
def _needs_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed, False otherwise. For example: a + b => True; a => False;
10 => False; -10 => True.
"""
return not ((expr.is_Integer and expr.is_nonnegative)
or (expr.is_Atom and (expr is not S.NegativeOne
and expr.is_Rational is False)))
def _needs_function_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
passed as an argument to a function, False otherwise. This is a more
liberal version of _needs_brackets, in that many expressions which need
to be wrapped in brackets when added/subtracted/raised to a power do
not need them when passed to a function. Such an example is a*b.
"""
if not self._needs_brackets(expr):
return False
else:
# Muls of the form a*b*c... can be folded
if expr.is_Mul and not self._mul_is_clean(expr):
return True
# Pows which don't need brackets can be folded
elif expr.is_Pow and not self._pow_is_clean(expr):
return True
# Add and Function always need brackets
elif expr.is_Add or expr.is_Function:
return True
else:
return False
def _needs_mul_brackets(self, expr, first=False, last=False):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of a Mul, False otherwise. This is True for Add,
but also for some container objects that would not need brackets
when appearing last in a Mul, e.g. an Integral. ``last=True``
specifies that this expr is the last to appear in a Mul.
``first=True`` specifies that this expr is the first to appear in
a Mul.
"""
from sympy import Integral, Product, Sum
if expr.is_Mul:
if not first and _coeff_isneg(expr):
return True
elif precedence_traditional(expr) < PRECEDENCE["Mul"]:
return True
elif expr.is_Relational:
return True
if expr.is_Piecewise:
return True
if any([expr.has(x) for x in (Mod,)]):
return True
if (not last and
any([expr.has(x) for x in (Integral, Product, Sum)])):
return True
return False
def _needs_add_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of an Add, False otherwise. This is False for most
things.
"""
if expr.is_Relational:
return True
if any([expr.has(x) for x in (Mod,)]):
return True
if expr.is_Add:
return True
return False
def _mul_is_clean(self, expr):
for arg in expr.args:
if arg.is_Function:
return False
return True
def _pow_is_clean(self, expr):
return not self._needs_brackets(expr.base)
def _do_exponent(self, expr, exp):
if exp is not None:
return r"\left(%s\right)^{%s}" % (expr, exp)
else:
return expr
def _print_Basic(self, expr):
ls = [self._print(o) for o in expr.args]
return self._deal_with_super_sub(expr.__class__.__name__) + \
r"\left(%s\right)" % ", ".join(ls)
def _print_bool(self, e):
return r"\text{%s}" % e
_print_BooleanTrue = _print_bool
_print_BooleanFalse = _print_bool
def _print_NoneType(self, e):
return r"\text{%s}" % e
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
tex = ""
for i, term in enumerate(terms):
if i == 0:
pass
elif _coeff_isneg(term):
tex += " - "
term = -term
else:
tex += " + "
term_tex = self._print(term)
if self._needs_add_brackets(term):
term_tex = r"\left(%s\right)" % term_tex
tex += term_tex
return tex
def _print_Cycle(self, expr):
from sympy.combinatorics.permutations import Permutation
if expr.size == 0:
return r"\left( \right)"
expr = Permutation(expr)
expr_perm = expr.cyclic_form
siz = expr.size
if expr.array_form[-1] == siz - 1:
expr_perm = expr_perm + [[siz - 1]]
term_tex = ''
for i in expr_perm:
term_tex += str(i).replace(',', r"\;")
term_tex = term_tex.replace('[', r"\left( ")
term_tex = term_tex.replace(']', r"\right)")
return term_tex
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation
from sympy.utilities.exceptions import SymPyDeprecationWarning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(expr)
if expr.size == 0:
return r"\left( \right)"
lower = [self._print(arg) for arg in expr.array_form]
upper = [self._print(arg) for arg in range(len(lower))]
row1 = " & ".join(upper)
row2 = " & ".join(lower)
mat = r" \\ ".join((row1, row2))
return r"\begin{pmatrix} %s \end{pmatrix}" % mat
def _print_AppliedPermutation(self, expr):
perm, var = expr.args
return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var))
def _print_Float(self, expr):
# Based off of that in StrPrinter
dps = prec_to_dps(expr._prec)
strip = False if self._settings['full_prec'] else True
low = self._settings["min"] if "min" in self._settings else None
high = self._settings["max"] if "max" in self._settings else None
str_real = mlib.to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
# thus we use the number separator
separator = self._settings['mul_symbol_latex_numbers']
if 'e' in str_real:
(mant, exp) = str_real.split('e')
if exp[0] == '+':
exp = exp[1:]
if self._settings['decimal_separator'] == 'comma':
mant = mant.replace('.','{,}')
return r"%s%s10^{%s}" % (mant, separator, exp)
elif str_real == "+inf":
return r"\infty"
elif str_real == "-inf":
return r"- \infty"
else:
if self._settings['decimal_separator'] == 'comma':
str_real = str_real.replace('.','{,}')
return str_real
def _print_Cross(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Curl(self, expr):
vec = expr._expr
return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Divergence(self, expr):
vec = expr._expr
return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Dot(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Gradient(self, expr):
func = expr._expr
return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Laplacian(self, expr):
func = expr._expr
return r"\triangle %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Mul(self, expr):
from sympy.core.power import Pow
from sympy.physics.units import Quantity
from sympy.simplify import fraction
separator = self._settings['mul_symbol_latex']
numbersep = self._settings['mul_symbol_latex_numbers']
def convert(expr):
if not expr.is_Mul:
return str(self._print(expr))
else:
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
args = list(expr.args)
# If quantities are present append them at the back
args = sorted(args, key=lambda x: isinstance(x, Quantity) or
(isinstance(x, Pow) and
isinstance(x.base, Quantity)))
return convert_args(args)
def convert_args(args):
_tex = last_term_tex = ""
for i, term in enumerate(args):
term_tex = self._print(term)
if self._needs_mul_brackets(term, first=(i == 0),
last=(i == len(args) - 1)):
term_tex = r"\left(%s\right)" % term_tex
if _between_two_numbers_p[0].search(last_term_tex) and \
_between_two_numbers_p[1].match(term_tex):
# between two numbers
_tex += numbersep
elif _tex:
_tex += separator
_tex += term_tex
last_term_tex = term_tex
return _tex
# Check for unevaluated Mul. In this case we need to make sure the
# identities are visible, multiple Rational factors are not combined
# etc so we display in a straight-forward form that fully preserves all
# args and their order.
# XXX: _print_Pow calls this routine with instances of Pow...
if isinstance(expr, Mul):
args = expr.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
return convert_args(args)
include_parens = False
if _coeff_isneg(expr):
expr = -expr
tex = "- "
if expr.is_Add:
tex += "("
include_parens = True
else:
tex = ""
numer, denom = fraction(expr, exact=True)
if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args:
# use the original expression here, since fraction() may have
# altered it when producing numer and denom
tex += convert(expr)
else:
snumer = convert(numer)
sdenom = convert(denom)
ldenom = len(sdenom.split())
ratio = self._settings['long_frac_ratio']
if self._settings['fold_short_frac'] and ldenom <= 2 and \
"^" not in sdenom:
# handle short fractions
if self._needs_mul_brackets(numer, last=False):
tex += r"\left(%s\right) / %s" % (snumer, sdenom)
else:
tex += r"%s / %s" % (snumer, sdenom)
elif ratio is not None and \
len(snumer.split()) > ratio*ldenom:
# handle long fractions
if self._needs_mul_brackets(numer, last=True):
tex += r"\frac{1}{%s}%s\left(%s\right)" \
% (sdenom, separator, snumer)
elif numer.is_Mul:
# split a long numerator
a = S.One
b = S.One
for x in numer.args:
if self._needs_mul_brackets(x, last=False) or \
len(convert(a*x).split()) > ratio*ldenom or \
(b.is_commutative is x.is_commutative is False):
b *= x
else:
a *= x
if self._needs_mul_brackets(b, last=True):
tex += r"\frac{%s}{%s}%s\left(%s\right)" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{%s}{%s}%s%s" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer)
else:
tex += r"\frac{%s}{%s}" % (snumer, sdenom)
if include_parens:
tex += ")"
return tex
def _print_Pow(self, expr):
# Treat x**Rational(1,n) as special case
if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1 \
and self._settings['root_notation']:
base = self._print(expr.base)
expq = expr.exp.q
if expq == 2:
tex = r"\sqrt{%s}" % base
elif self._settings['itex']:
tex = r"\root{%d}{%s}" % (expq, base)
else:
tex = r"\sqrt[%d]{%s}" % (expq, base)
if expr.exp.is_negative:
return r"\frac{1}{%s}" % tex
else:
return tex
elif self._settings['fold_frac_powers'] \
and expr.exp.is_Rational \
and expr.exp.q != 1:
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
p, q = expr.exp.p, expr.exp.q
# issue #12886: add parentheses for superscripts raised to powers
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
if expr.base.is_Function:
return self._print(expr.base, exp="%s/%s" % (p, q))
return r"%s^{%s/%s}" % (base, p, q)
elif expr.exp.is_Rational and expr.exp.is_negative and \
expr.base.is_commutative:
# special case for 1^(-x), issue 9216
if expr.base == 1:
return r"%s^{%s}" % (expr.base, expr.exp)
# things like 1/x
return self._print_Mul(expr)
else:
if expr.base.is_Function:
return self._print(expr.base, exp=self._print(expr.exp))
else:
tex = r"%s^{%s}"
return self._helper_print_standard_power(expr, tex)
def _helper_print_standard_power(self, expr, template):
exp = self._print(expr.exp)
# issue #12886: add parentheses around superscripts raised
# to powers
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
elif (isinstance(expr.base, Derivative)
and base.startswith(r'\left(')
and re.match(r'\\left\(\\d?d?dot', base)
and base.endswith(r'\right)')):
# don't use parentheses around dotted derivative
base = base[6: -7] # remove outermost added parens
return template % (base, exp)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def _print_Sum(self, expr):
if len(expr.limits) == 1:
tex = r"\sum_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\sum_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_Product(self, expr):
if len(expr.limits) == 1:
tex = r"\prod_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\prod_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
o1 = []
if expr == expr.zero:
return expr.zero._latex_form
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key=lambda x: x[0].__str__())
for k, v in inneritems:
if v == 1:
o1.append(' + ' + k._latex_form)
elif v == -1:
o1.append(' - ' + k._latex_form)
else:
arg_str = '(' + self._print(v) + ')'
o1.append(' + ' + arg_str + k._latex_form)
outstr = (''.join(o1))
if outstr[1] != '-':
outstr = outstr[3:]
else:
outstr = outstr[1:]
return outstr
def _print_Indexed(self, expr):
tex_base = self._print(expr.base)
tex = '{'+tex_base+'}'+'_{%s}' % ','.join(
map(self._print, expr.indices))
return tex
def _print_IndexedBase(self, expr):
return self._print(expr.label)
def _print_Derivative(self, expr):
if requires_partial(expr.expr):
diff_symbol = r'\partial'
else:
diff_symbol = r'd'
tex = ""
dim = 0
for x, num in reversed(expr.variable_count):
dim += num
if num == 1:
tex += r"%s %s" % (diff_symbol, self._print(x))
else:
tex += r"%s %s^{%s}" % (diff_symbol,
self.parenthesize_super(self._print(x)),
self._print(num))
if dim == 1:
tex = r"\frac{%s}{%s}" % (diff_symbol, tex)
else:
tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex)
if any(_coeff_isneg(i) for i in expr.args):
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=True,
strict=True))
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=False,
strict=True))
def _print_Subs(self, subs):
expr, old, new = subs.args
latex_expr = self._print(expr)
latex_old = (self._print(e) for e in old)
latex_new = (self._print(e) for e in new)
latex_subs = r'\\ '.join(
e[0] + '=' + e[1] for e in zip(latex_old, latex_new))
return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,
latex_subs)
def _print_Integral(self, expr):
tex, symbols = "", []
# Only up to \iiiint exists
if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):
# Use len(expr.limits)-1 so that syntax highlighters don't think
# \" is an escaped quote
tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt"
symbols = [r"\, d%s" % self._print(symbol[0])
for symbol in expr.limits]
else:
for lim in reversed(expr.limits):
symbol = lim[0]
tex += r"\int"
if len(lim) > 1:
if self._settings['mode'] != 'inline' \
and not self._settings['itex']:
tex += r"\limits"
if len(lim) == 3:
tex += "_{%s}^{%s}" % (self._print(lim[1]),
self._print(lim[2]))
if len(lim) == 2:
tex += "^{%s}" % (self._print(lim[1]))
symbols.insert(0, r"\, d%s" % self._print(symbol))
return r"%s %s%s" % (tex, self.parenthesize(expr.function,
PRECEDENCE["Mul"],
is_neg=any(_coeff_isneg(i) for i in expr.args),
strict=True),
"".join(symbols))
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
tex = r"\lim_{%s \to " % self._print(z)
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
tex += r"%s}" % self._print(z0)
else:
tex += r"%s^%s}" % (self._print(z0), self._print(dir))
if isinstance(e, AssocOp):
return r"%s\left(%s\right)" % (tex, self._print(e))
else:
return r"%s %s" % (tex, self._print(e))
def _hprint_Function(self, func):
r'''
Logic to decide how to render a function to latex
- if it is a recognized latex name, use the appropriate latex command
- if it is a single letter, just use that letter
- if it is a longer name, then put \operatorname{} around it and be
mindful of undercores in the name
'''
func = self._deal_with_super_sub(func)
if func in accepted_latex_functions:
name = r"\%s" % func
elif len(func) == 1 or func.startswith('\\'):
name = func
else:
name = r"\operatorname{%s}" % func
return name
def _print_Function(self, expr, exp=None):
r'''
Render functions to LaTeX, handling functions that LaTeX knows about
e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).
For single-letter function names, render them as regular LaTeX math
symbols. For multi-letter function names that LaTeX does not know
about, (e.g., Li, sech) use \operatorname{} so that the function name
is rendered in Roman font and LaTeX handles spacing properly.
expr is the expression involving the function
exp is an exponent
'''
func = expr.func.__name__
if hasattr(self, '_print_' + func) and \
not isinstance(expr, AppliedUndef):
return getattr(self, '_print_' + func)(expr, exp)
else:
args = [str(self._print(arg)) for arg in expr.args]
# How inverse trig functions should be displayed, formats are:
# abbreviated: asin, full: arcsin, power: sin^-1
inv_trig_style = self._settings['inv_trig_style']
# If we are dealing with a power-style inverse trig function
inv_trig_power_case = False
# If it is applicable to fold the argument brackets
can_fold_brackets = self._settings['fold_func_brackets'] and \
len(args) == 1 and \
not self._needs_function_brackets(expr.args[0])
inv_trig_table = [
"asin", "acos", "atan",
"acsc", "asec", "acot",
"asinh", "acosh", "atanh",
"acsch", "asech", "acoth",
]
# If the function is an inverse trig function, handle the style
if func in inv_trig_table:
if inv_trig_style == "abbreviated":
pass
elif inv_trig_style == "full":
func = "arc" + func[1:]
elif inv_trig_style == "power":
func = func[1:]
inv_trig_power_case = True
# Can never fold brackets if we're raised to a power
if exp is not None:
can_fold_brackets = False
if inv_trig_power_case:
if func in accepted_latex_functions:
name = r"\%s^{-1}" % func
else:
name = r"\operatorname{%s}^{-1}" % func
elif exp is not None:
func_tex = self._hprint_Function(func)
func_tex = self.parenthesize_super(func_tex)
name = r'%s^{%s}' % (func_tex, exp)
else:
name = self._hprint_Function(func)
if can_fold_brackets:
if func in accepted_latex_functions:
# Wrap argument safely to avoid parse-time conflicts
# with the function name itself
name += r" {%s}"
else:
name += r"%s"
else:
name += r"{\left(%s \right)}"
if inv_trig_power_case and exp is not None:
name += r"^{%s}" % exp
return name % ",".join(args)
def _print_UndefinedFunction(self, expr):
return self._hprint_Function(str(expr))
def _print_ElementwiseApplyFunction(self, expr):
return r"{%s}_{\circ}\left({%s}\right)" % (
self._print(expr.function),
self._print(expr.expr),
)
@property
def _special_function_classes(self):
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.gamma_functions import gamma, lowergamma
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: r'\delta',
gamma: r'\Gamma',
lowergamma: r'\gamma',
beta: r'\operatorname{B}',
DiracDelta: r'\delta',
Chi: r'\operatorname{Chi}'}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
return self._special_function_classes[cls]
return self._hprint_Function(str(expr))
def _print_Lambda(self, expr):
symbols, expr = expr.args
if len(symbols) == 1:
symbols = self._print(symbols[0])
else:
symbols = self._print(tuple(symbols))
tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr))
return tex
def _print_IdentityFunction(self, expr):
return r"\left( x \mapsto x \right)"
def _hprint_variadic_function(self, expr, exp=None):
args = sorted(expr.args, key=default_sort_key)
texargs = [r"%s" % self._print(symbol) for symbol in args]
tex = r"\%s\left(%s\right)" % (str(expr.func).lower(),
", ".join(texargs))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Min = _print_Max = _hprint_variadic_function
def _print_floor(self, expr, exp=None):
tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_ceiling(self, expr, exp=None):
tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_log(self, expr, exp=None):
if not self._settings["ln_notation"]:
tex = r"\log{\left(%s \right)}" % self._print(expr.args[0])
else:
tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_Abs(self, expr, exp=None):
tex = r"\left|{%s}\right|" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Determinant = _print_Abs
def _print_re(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_im(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_Not(self, e):
from sympy import Equivalent, Implies
if isinstance(e.args[0], Equivalent):
return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow")
if isinstance(e.args[0], Implies):
return self._print_Implies(e.args[0], r"\not\Rightarrow")
if (e.args[0].is_Boolean):
return r"\neg \left(%s\right)" % self._print(e.args[0])
else:
return r"\neg %s" % self._print(e.args[0])
def _print_LogOp(self, args, char):
arg = args[0]
if arg.is_Boolean and not arg.is_Not:
tex = r"\left(%s\right)" % self._print(arg)
else:
tex = r"%s" % self._print(arg)
for arg in args[1:]:
if arg.is_Boolean and not arg.is_Not:
tex += r" %s \left(%s\right)" % (char, self._print(arg))
else:
tex += r" %s %s" % (char, self._print(arg))
return tex
def _print_And(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\wedge")
def _print_Or(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\vee")
def _print_Xor(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\veebar")
def _print_Implies(self, e, altchar=None):
return self._print_LogOp(e.args, altchar or r"\Rightarrow")
def _print_Equivalent(self, e, altchar=None):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, altchar or r"\Leftrightarrow")
def _print_conjugate(self, expr, exp=None):
tex = r"\overline{%s}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_polar_lift(self, expr, exp=None):
func = r"\operatorname{polar\_lift}"
arg = r"{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (func, exp, arg)
else:
return r"%s%s" % (func, arg)
def _print_ExpBase(self, expr, exp=None):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
tex = r"e^{%s}" % self._print(expr.args[0])
return self._do_exponent(tex, exp)
def _print_elliptic_k(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"K^{%s}%s" % (exp, tex)
else:
return r"K%s" % tex
def _print_elliptic_f(self, expr, exp=None):
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"F^{%s}%s" % (exp, tex)
else:
return r"F%s" % tex
def _print_elliptic_e(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"E^{%s}%s" % (exp, tex)
else:
return r"E%s" % tex
def _print_elliptic_pi(self, expr, exp=None):
if len(expr.args) == 3:
tex = r"\left(%s; %s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]),
self._print(expr.args[2]))
else:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"\Pi^{%s}%s" % (exp, tex)
else:
return r"\Pi%s" % tex
def _print_beta(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\operatorname{B}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{B}%s" % tex
def _print_uppergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\Gamma^{%s}%s" % (exp, tex)
else:
return r"\Gamma%s" % tex
def _print_lowergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\gamma^{%s}%s" % (exp, tex)
else:
return r"\gamma%s" % tex
def _hprint_one_arg_func(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (self._print(expr.func), exp, tex)
else:
return r"%s%s" % (self._print(expr.func), tex)
_print_gamma = _hprint_one_arg_func
def _print_Chi(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\operatorname{Chi}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{Chi}%s" % tex
def _print_expint(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[1])
nu = self._print(expr.args[0])
if exp is not None:
return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex)
else:
return r"\operatorname{E}_{%s}%s" % (nu, tex)
def _print_fresnels(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"S^{%s}%s" % (exp, tex)
else:
return r"S%s" % tex
def _print_fresnelc(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"C^{%s}%s" % (exp, tex)
else:
return r"C%s" % tex
def _print_subfactorial(self, expr, exp=None):
tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"\left(%s\right)^{%s}" % (tex, exp)
else:
return tex
def _print_factorial(self, expr, exp=None):
tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_factorial2(self, expr, exp=None):
tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_binomial(self, expr, exp=None):
tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_RisingFactorial(self, expr, exp=None):
n, k = expr.args
base = r"%s" % self.parenthesize(n, PRECEDENCE['Func'])
tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k))
return self._do_exponent(tex, exp)
def _print_FallingFactorial(self, expr, exp=None):
n, k = expr.args
sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func'])
tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub)
return self._do_exponent(tex, exp)
def _hprint_BesselBase(self, expr, exp, sym):
tex = r"%s" % (sym)
need_exp = False
if exp is not None:
if tex.find('^') == -1:
tex = r"%s^{%s}" % (tex, exp)
else:
need_exp = True
tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order),
self._print(expr.argument))
if need_exp:
tex = self._do_exponent(tex, exp)
return tex
def _hprint_vec(self, vec):
if not vec:
return ""
s = ""
for i in vec[:-1]:
s += "%s, " % self._print(i)
s += self._print(vec[-1])
return s
def _print_besselj(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'J')
def _print_besseli(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'I')
def _print_besselk(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'K')
def _print_bessely(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'Y')
def _print_yn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'y')
def _print_jn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'j')
def _print_hankel1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(1)}')
def _print_hankel2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
def _print_hn1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(1)}')
def _print_hn2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(2)}')
def _hprint_airy(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (notation, exp, tex)
else:
return r"%s%s" % (notation, tex)
def _hprint_airy_prime(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"{%s^\prime}^{%s}%s" % (notation, exp, tex)
else:
return r"%s^\prime%s" % (notation, tex)
def _print_airyai(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Ai')
def _print_airybi(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Bi')
def _print_airyaiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Ai')
def _print_airybiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Bi')
def _print_hyper(self, expr, exp=None):
tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \
r"\middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_meijerg(self, expr, exp=None):
tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \
r"%s & %s \end{matrix} \middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._print(len(expr.bm)), self._print(len(expr.an)),
self._hprint_vec(expr.an), self._hprint_vec(expr.aother),
self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_dirichlet_eta(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\eta^{%s}%s" % (exp, tex)
return r"\eta%s" % tex
def _print_zeta(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\zeta^{%s}%s" % (exp, tex)
return r"\zeta%s" % tex
def _print_stieltjes(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"_{%s}" % self._print(expr.args[0])
if exp is not None:
return r"\gamma%s^{%s}" % (tex, exp)
return r"\gamma%s" % tex
def _print_lerchphi(self, expr, exp=None):
tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args))
if exp is None:
return r"\Phi%s" % tex
return r"\Phi^{%s}%s" % (exp, tex)
def _print_polylog(self, expr, exp=None):
s, z = map(self._print, expr.args)
tex = r"\left(%s\right)" % z
if exp is None:
return r"\operatorname{Li}_{%s}%s" % (s, tex)
return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex)
def _print_jacobi(self, expr, exp=None):
n, a, b, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_gegenbauer(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevt(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"T_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevu(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"U_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_legendre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"P_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_legendre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_hermite(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"H_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_laguerre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"L_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_laguerre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Ynm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Znm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def __print_mathieu_functions(self, character, args, prime=False, exp=None):
a, q, z = map(self._print, args)
sup = r"^{\prime}" if prime else ""
exp = "" if not exp else "^{%s}" % exp
return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp)
def _print_mathieuc(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, exp=exp)
def _print_mathieus(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, exp=exp)
def _print_mathieucprime(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp)
def _print_mathieusprime(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp)
def _print_Rational(self, expr):
if expr.q != 1:
sign = ""
p = expr.p
if expr.p < 0:
sign = "- "
p = -p
if self._settings['fold_short_frac']:
return r"%s%d / %d" % (sign, p, expr.q)
return r"%s\frac{%d}{%d}" % (sign, p, expr.q)
else:
return self._print(expr.p)
def _print_Order(self, expr):
s = self._print(expr.expr)
if expr.point and any(p != S.Zero for p in expr.point) or \
len(expr.variables) > 1:
s += '; '
if len(expr.variables) > 1:
s += self._print(expr.variables)
elif expr.variables:
s += self._print(expr.variables[0])
s += r'\rightarrow '
if len(expr.point) > 1:
s += self._print(expr.point)
else:
s += self._print(expr.point[0])
return r"O\left(%s\right)" % s
def _print_Symbol(self, expr, style='plain'):
if expr in self._settings['symbol_names']:
return self._settings['symbol_names'][expr]
return self._deal_with_super_sub(expr.name, style=style)
_print_RandomSymbol = _print_Symbol
def _deal_with_super_sub(self, string, style='plain'):
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
# apply the style only to the name
if style == 'bold':
name = "\\mathbf{{{}}}".format(name)
# glue all items together:
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Relational(self, expr):
if self._settings['itex']:
gt = r"\gt"
lt = r"\lt"
else:
gt = ">"
lt = "<"
charmap = {
"==": "=",
">": gt,
"<": lt,
">=": r"\geq",
"<=": r"\leq",
"!=": r"\neq",
}
return "%s %s %s" % (self._print(expr.lhs),
charmap[expr.rel_op], self._print(expr.rhs))
def _print_Piecewise(self, expr):
ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c))
for e, c in expr.args[:-1]]
if expr.args[-1].cond == true:
ecpairs.append(r"%s & \text{otherwise}" %
self._print(expr.args[-1].expr))
else:
ecpairs.append(r"%s & \text{for}\: %s" %
(self._print(expr.args[-1].expr),
self._print(expr.args[-1].cond)))
tex = r"\begin{cases} %s \end{cases}"
return tex % r" \\".join(ecpairs)
def _print_MatrixBase(self, expr):
lines = []
for line in range(expr.rows): # horrible, should be 'rows'
lines.append(" & ".join([self._print(i) for i in expr[line, :]]))
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.cols <= 10) is True:
mat_str = 'matrix'
else:
mat_str = 'array'
out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
out_str = out_str.replace('%MATSTR%', mat_str)
if mat_str == 'array':
out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s')
if self._settings['mat_delim']:
left_delim = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
out_str = r'\left' + left_delim + out_str + \
r'\right' + right_delim
return out_str % r"\\".join(lines)
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\
+ '_{%s, %s}' % (self._print(expr.i), self._print(expr.j))
def _print_MatrixSlice(self, expr):
def latexslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = None
if x[1] == dim:
x[1] = None
return ':'.join(self._print(xi) if xi is not None else '' for xi in x)
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +
latexslice(expr.rowslice, expr.parent.rows) + ', ' +
latexslice(expr.colslice, expr.parent.cols) + r'\right]')
def _print_BlockMatrix(self, expr):
return self._print(expr.blocks)
def _print_Transpose(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol
if not isinstance(mat, MatrixSymbol):
return r"\left(%s\right)^{T}" % self._print(mat)
else:
return "%s^{T}" % self.parenthesize(mat, precedence_traditional(expr), True)
def _print_Trace(self, expr):
mat = expr.arg
return r"\operatorname{tr}\left(%s \right)" % self._print(mat)
def _print_Adjoint(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol
if not isinstance(mat, MatrixSymbol):
return r"\left(%s\right)^{\dagger}" % self._print(mat)
else:
return r"%s^{\dagger}" % self._print(mat)
def _print_MatMul(self, expr):
from sympy import MatMul, Mul
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
args = expr.args
if isinstance(args[0], Mul):
args = args[0].as_ordered_factors() + list(args[1:])
else:
args = list(args)
if isinstance(expr, MatMul) and _coeff_isneg(expr):
if args[0] == -1:
args = args[1:]
else:
args[0] = -args[0]
return '- ' + ' '.join(map(parens, args))
else:
return ' '.join(map(parens, args))
def _print_Mod(self, expr, exp=None):
if exp is not None:
return r'\left(%s\bmod{%s}\right)^{%s}' % \
(self.parenthesize(expr.args[0], PRECEDENCE['Mul'],
strict=True), self._print(expr.args[1]),
exp)
return r'%s\bmod{%s}' % (self.parenthesize(expr.args[0],
PRECEDENCE['Mul'], strict=True),
self._print(expr.args[1]))
def _print_HadamardProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \circ '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_HadamardPower(self, expr):
if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]:
template = r"%s^{\circ \left({%s}\right)}"
else:
template = r"%s^{\circ {%s}}"
return self._helper_print_standard_power(expr, template)
def _print_KroneckerProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \otimes '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_MatPow(self, expr):
base, exp = expr.base, expr.exp
from sympy.matrices import MatrixSymbol
if not isinstance(base, MatrixSymbol):
return "\\left(%s\\right)^{%s}" % (self._print(base),
self._print(exp))
else:
return "%s^{%s}" % (self._print(base), self._print(exp))
def _print_MatrixSymbol(self, expr):
return self._print_Symbol(expr, style=self._settings[
'mat_symbol_style'])
def _print_ZeroMatrix(self, Z):
return r"\mathbb{0}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{0}"
def _print_OneMatrix(self, O):
return r"\mathbb{1}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{1}"
def _print_Identity(self, I):
return r"\mathbb{I}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{I}"
def _print_PermutationMatrix(self, P):
perm_str = self._print(P.args[0])
return "P_{%s}" % perm_str
def _print_NDimArray(self, expr):
if expr.rank() == 0:
return self._print(expr[()])
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.rank() == 0) or (expr.shape[-1] <= 10):
mat_str = 'matrix'
else:
mat_str = 'array'
block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
block_str = block_str.replace('%MATSTR%', mat_str)
if self._settings['mat_delim']:
left_delim = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
block_str = r'\left' + left_delim + block_str + \
r'\right' + right_delim
if expr.rank() == 0:
return block_str % ""
level_str = [[]] + [[] for i in range(expr.rank())]
shape_ranges = [list(range(i)) for i in expr.shape]
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(self._print(expr[outer_i]))
even = True
for back_outer_i in range(expr.rank()-1, -1, -1):
if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
break
if even:
level_str[back_outer_i].append(
r" & ".join(level_str[back_outer_i+1]))
else:
level_str[back_outer_i].append(
block_str % (r"\\".join(level_str[back_outer_i+1])))
if len(level_str[back_outer_i+1]) == 1:
level_str[back_outer_i][-1] = r"\left[" + \
level_str[back_outer_i][-1] + r"\right]"
even = not even
level_str[back_outer_i+1] = []
out_str = level_str[0][0]
if expr.rank() % 2 == 1:
out_str = block_str % out_str
return out_str
def _printer_tensor_indices(self, name, indices, index_map={}):
out_str = self._print(name)
last_valence = None
prev_map = None
for index in indices:
new_valence = index.is_up
if ((index in index_map) or prev_map) and \
last_valence == new_valence:
out_str += ","
if last_valence != new_valence:
if last_valence is not None:
out_str += "}"
if index.is_up:
out_str += "{}^{"
else:
out_str += "{}_{"
out_str += self._print(index.args[0])
if index in index_map:
out_str += "="
out_str += self._print(index_map[index])
prev_map = True
else:
prev_map = False
last_valence = new_valence
if last_valence is not None:
out_str += "}"
return out_str
def _print_Tensor(self, expr):
name = expr.args[0].args[0]
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices)
def _print_TensorElement(self, expr):
name = expr.expr.args[0].args[0]
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
def _print_TensMul(self, expr):
# prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
sign, args = expr._get_args_for_traditional_printer()
return sign + "".join(
[self.parenthesize(arg, precedence(expr)) for arg in args]
)
def _print_TensAdd(self, expr):
a = []
args = expr.args
for x in args:
a.append(self.parenthesize(x, precedence(expr)))
a.sort()
s = ' + '.join(a)
s = s.replace('+ -', '- ')
return s
def _print_TensorIndex(self, expr):
return "{}%s{%s}" % (
"^" if expr.is_up else "_",
self._print(expr.args[0])
)
def _print_PartialDerivative(self, expr):
if len(expr.variables) == 1:
return r"\frac{\partial}{\partial {%s}}{%s}" % (
self._print(expr.variables[0]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
else:
return r"\frac{\partial^{%s}}{%s}{%s}" % (
len(expr.variables),
" ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
def _print_UniversalSet(self, expr):
return r"\mathbb{U}"
def _print_frac(self, expr, exp=None):
if exp is None:
return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])
else:
return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (
self._print(expr.args[0]), exp)
def _print_tuple(self, expr):
if self._settings['decimal_separator'] == 'comma':
sep = ";"
elif self._settings['decimal_separator'] == 'period':
sep = ","
else:
raise ValueError('Unknown Decimal Separator')
if len(expr) == 1:
# 1-tuple needs a trailing separator
return self._add_parens_lspace(self._print(expr[0]) + sep)
else:
return self._add_parens_lspace(
(sep + r" \ ").join([self._print(i) for i in expr]))
def _print_TensorProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \otimes '.join(elements)
def _print_WedgeProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \wedge '.join(elements)
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_list(self, expr):
if self._settings['decimal_separator'] == 'comma':
return r"\left[ %s\right]" % \
r"; \ ".join([self._print(i) for i in expr])
elif self._settings['decimal_separator'] == 'period':
return r"\left[ %s\right]" % \
r", \ ".join([self._print(i) for i in expr])
else:
raise ValueError('Unknown Decimal Separator')
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
val = d[key]
items.append("%s : %s" % (self._print(key), self._print(val)))
return r"\left\{ %s\right\}" % r", \ ".join(items)
def _print_Dict(self, expr):
return self._print_dict(expr)
def _print_DiracDelta(self, expr, exp=None):
if len(expr.args) == 1 or expr.args[1] == 0:
tex = r"\delta\left(%s\right)" % self._print(expr.args[0])
else:
tex = r"\delta^{\left( %s \right)}\left( %s \right)" % (
self._print(expr.args[1]), self._print(expr.args[0]))
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_SingularityFunction(self, expr):
shift = self._print(expr.args[0] - expr.args[1])
power = self._print(expr.args[2])
tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)
return tex
def _print_Heaviside(self, expr, exp=None):
tex = r"\theta\left(%s\right)" % self._print(expr.args[0])
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_KroneckerDelta(self, expr, exp=None):
i = self._print(expr.args[0])
j = self._print(expr.args[1])
if expr.args[0].is_Atom and expr.args[1].is_Atom:
tex = r'\delta_{%s %s}' % (i, j)
else:
tex = r'\delta_{%s, %s}' % (i, j)
if exp is not None:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_LeviCivita(self, expr, exp=None):
indices = map(self._print, expr.args)
if all(x.is_Atom for x in expr.args):
tex = r'\varepsilon_{%s}' % " ".join(indices)
else:
tex = r'\varepsilon_{%s}' % ", ".join(indices)
if exp:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
return '\\text{Domain: }' + self._print(d.as_boolean())
elif hasattr(d, 'set'):
return ('\\text{Domain: }' + self._print(d.symbols) + '\\text{ in }' +
self._print(d.set))
elif hasattr(d, 'symbols'):
return '\\text{Domain on }' + self._print(d.symbols)
else:
return self._print(None)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_set(items)
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
if self._settings['decimal_separator'] == 'comma':
items = "; ".join(map(self._print, items))
elif self._settings['decimal_separator'] == 'period':
items = ", ".join(map(self._print, items))
else:
raise ValueError('Unknown Decimal Separator')
return r"\left\{%s\right\}" % items
_print_frozenset = _print_set
def _print_Range(self, s):
dots = object()
if s.has(Symbol):
return self._print_Basic(s)
if s.start.is_infinite and s.stop.is_infinite:
if s.step.is_positive:
printset = dots, -1, 0, 1, dots
else:
printset = dots, 1, 0, -1, dots
elif s.start.is_infinite:
printset = dots, s[-1] - s.step, s[-1]
elif s.stop.is_infinite:
it = iter(s)
printset = next(it), next(it), dots
elif len(s) > 4:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
printset = tuple(s)
return (r"\left\{" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right\}")
def __print_number_polynomial(self, expr, letter, exp=None):
if len(expr.args) == 2:
if exp is not None:
return r"%s_{%s}^{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), exp,
self._print(expr.args[1]))
return r"%s_{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), self._print(expr.args[1]))
tex = r"%s_{%s}" % (letter, self._print(expr.args[0]))
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_bernoulli(self, expr, exp=None):
return self.__print_number_polynomial(expr, "B", exp)
def _print_bell(self, expr, exp=None):
if len(expr.args) == 3:
tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for
el in expr.args[2])
if exp is not None:
tex = r"%s^{%s}%s" % (tex1, exp, tex2)
else:
tex = tex1 + tex2
return tex
return self.__print_number_polynomial(expr, "B", exp)
def _print_fibonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "F", exp)
def _print_lucas(self, expr, exp=None):
tex = r"L_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_tribonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "T", exp)
def _print_SeqFormula(self, s):
dots = object()
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
return r"\left\{%s\right\}_{%s=%s}^{%s}" % (
self._print(s.formula),
self._print(s.variables[0]),
self._print(s.start),
self._print(s.stop)
)
if s.start is S.NegativeInfinity:
stop = s.stop
printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
s.coeff(stop - 1), s.coeff(stop))
elif s.stop is S.Infinity or s.length > 4:
printset = s[:4]
printset.append(dots)
else:
printset = tuple(s)
return (r"\left[" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right]")
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_Interval(self, i):
if i.start == i.end:
return r"\left\{%s\right\}" % self._print(i.start)
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return r"\left%s%s, %s\right%s" % \
(left, self._print(i.start), self._print(i.end), right)
def _print_AccumulationBounds(self, i):
return r"\left\langle %s, %s\right\rangle" % \
(self._print(i.min), self._print(i.max))
def _print_Union(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cup ".join(args_str)
def _print_Complement(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \setminus ".join(args_str)
def _print_Intersection(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cap ".join(args_str)
def _print_SymmetricDifference(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \triangle ".join(args_str)
def _print_ProductSet(self, p):
prec = precedence_traditional(p)
if len(p.sets) >= 1 and not has_variety(p.sets):
return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets)
return r" \times ".join(
self.parenthesize(set, prec) for set in p.sets)
def _print_EmptySet(self, e):
return r"\emptyset"
def _print_Naturals(self, n):
return r"\mathbb{N}"
def _print_Naturals0(self, n):
return r"\mathbb{N}_0"
def _print_Integers(self, i):
return r"\mathbb{Z}"
def _print_Rationals(self, i):
return r"\mathbb{Q}"
def _print_Reals(self, i):
return r"\mathbb{R}"
def _print_Complexes(self, i):
return r"\mathbb{C}"
def _print_ImageSet(self, s):
expr = s.lamda.expr
sig = s.lamda.signature
xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets))
xinys = r" , ".join(r"%s \in %s" % xy for xy in xys)
return r"\left\{%s\; |\; %s\right\}" % (self._print(expr), xinys)
def _print_ConditionSet(self, s):
vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])
if s.base_set is S.UniversalSet:
return r"\left\{%s \mid %s \right\}" % \
(vars_print, self._print(s.condition))
return r"\left\{%s \mid %s \in %s \wedge %s \right\}" % (
vars_print,
vars_print,
self._print(s.base_set),
self._print(s.condition))
def _print_ComplexRegion(self, s):
vars_print = ', '.join([self._print(var) for var in s.variables])
return r"\left\{%s\; |\; %s \in %s \right\}" % (
self._print(s.expr),
vars_print,
self._print(s.sets))
def _print_Contains(self, e):
return r"%s \in %s" % tuple(self._print(a) for a in e.args)
def _print_FourierSeries(self, s):
return self._print_Add(s.truncate()) + r' + \ldots'
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_FiniteField(self, expr):
return r"\mathbb{F}_{%s}" % expr.mod
def _print_IntegerRing(self, expr):
return r"\mathbb{Z}"
def _print_RationalField(self, expr):
return r"\mathbb{Q}"
def _print_RealField(self, expr):
return r"\mathbb{R}"
def _print_ComplexField(self, expr):
return r"\mathbb{C}"
def _print_PolynomialRing(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left[%s\right]" % (domain, symbols)
def _print_FractionField(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left(%s\right)" % (domain, symbols)
def _print_PolynomialRingBase(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
inv = ""
if not expr.is_Poly:
inv = r"S_<^{-1}"
return r"%s%s\left[%s\right]" % (inv, domain, symbols)
def _print_Poly(self, poly):
cls = poly.__class__.__name__
terms = []
for monom, coeff in poly.terms():
s_monom = ''
for i, exp in enumerate(monom):
if exp > 0:
if exp == 1:
s_monom += self._print(poly.gens[i])
else:
s_monom += self._print(pow(poly.gens[i], exp))
if coeff.is_Add:
if s_monom:
s_coeff = r"\left(%s\right)" % self._print(coeff)
else:
s_coeff = self._print(coeff)
else:
if s_monom:
if coeff is S.One:
terms.extend(['+', s_monom])
continue
if coeff is S.NegativeOne:
terms.extend(['-', s_monom])
continue
s_coeff = self._print(coeff)
if not s_monom:
s_term = s_coeff
else:
s_term = s_coeff + " " + s_monom
if s_term.startswith('-'):
terms.extend(['-', s_term[1:]])
else:
terms.extend(['+', s_term])
if terms[0] in ['-', '+']:
modifier = terms.pop(0)
if modifier == '-':
terms[0] = '-' + terms[0]
expr = ' '.join(terms)
gens = list(map(self._print, poly.gens))
domain = "domain=%s" % self._print(poly.get_domain())
args = ", ".join([expr] + gens + [domain])
if cls in accepted_latex_functions:
tex = r"\%s {\left(%s \right)}" % (cls, args)
else:
tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args)
return tex
def _print_ComplexRootOf(self, root):
cls = root.__class__.__name__
if cls == "ComplexRootOf":
cls = "CRootOf"
expr = self._print(root.expr)
index = root.index
if cls in accepted_latex_functions:
return r"\%s {\left(%s, %d\right)}" % (cls, expr, index)
else:
return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr,
index)
def _print_RootSum(self, expr):
cls = expr.__class__.__name__
args = [self._print(expr.expr)]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
if cls in accepted_latex_functions:
return r"\%s {\left(%s\right)}" % (cls, ", ".join(args))
else:
return r"\operatorname{%s} {\left(%s\right)}" % (cls,
", ".join(args))
def _print_PolyElement(self, poly):
mul_symbol = self._settings['mul_symbol_latex']
return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)
def _print_FracElement(self, frac):
if frac.denom == 1:
return self._print(frac.numer)
else:
numer = self._print(frac.numer)
denom = self._print(frac.denom)
return r"\frac{%s}{%s}" % (numer, denom)
def _print_euler(self, expr, exp=None):
m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args
tex = r"E_{%s}" % self._print(m)
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
if x is not None:
tex = r"%s\left(%s\right)" % (tex, self._print(x))
return tex
def _print_catalan(self, expr, exp=None):
tex = r"C_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_UnifiedTransform(self, expr, s, inverse=False):
return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))
def _print_MellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M')
def _print_InverseMellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M', True)
def _print_LaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L')
def _print_InverseLaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L', True)
def _print_FourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F')
def _print_InverseFourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F', True)
def _print_SineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN')
def _print_InverseSineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN', True)
def _print_CosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS')
def _print_InverseCosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS', True)
def _print_DMP(self, p):
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
return self._print(repr(p))
def _print_DMF(self, p):
return self._print_DMP(p)
def _print_Object(self, object):
return self._print(Symbol(object.name))
def _print_LambertW(self, expr):
if len(expr.args) == 1:
return r"W\left(%s\right)" % self._print(expr.args[0])
return r"W_{%s}\left(%s\right)" % \
(self._print(expr.args[1]), self._print(expr.args[0]))
def _print_Morphism(self, morphism):
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
return "%s\\rightarrow %s" % (domain, codomain)
def _print_TransferFunction(self, expr):
from sympy.core import Mul, Pow
num, den = expr.num, expr.den
res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False)
return self._print_Mul(res)
def _print_Series(self, expr):
args = list(expr.args)
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
return ' '.join(map(parens, args))
def _print_Parallel(self, expr):
args = list(expr.args)
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
return ' '.join(map(parens, args))
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Parallel, Series
num, tf = expr.num, TransferFunction(1, 1, expr.num.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.den.args) if isinstance(expr.den, Series) else [expr.den]
if isinstance(num, Series) and isinstance(expr.den, Series):
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
elif isinstance(num, Series) and isinstance(expr.den, TransferFunction):
if expr.den == tf:
den = Parallel(tf, Series(*num_arg_list))
else:
den = Parallel(tf, Series(*num_arg_list, expr.den))
elif isinstance(num, TransferFunction) and isinstance(expr.den, Series):
if num == tf:
den = Parallel(tf, Series(*den_arg_list))
else:
den = Parallel(tf, Series(num, *den_arg_list))
else:
if num == tf:
den = Parallel(tf, *den_arg_list)
elif expr.den == tf:
den = Parallel(tf, *num_arg_list)
else:
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
numer = self._print(num)
denom = self._print(den)
return r"\frac{%s}{%s}" % (numer, denom)
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(Symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return "%s:%s" % (pretty_name, pretty_morphism)
def _print_IdentityMorphism(self, morphism):
from sympy.categories import NamedMorphism
return self._print_NamedMorphism(NamedMorphism(
morphism.domain, morphism.codomain, "id"))
def _print_CompositeMorphism(self, morphism):
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [self._print(Symbol(component.name)) for
component in morphism.components]
component_names_list.reverse()
component_names = "\\circ ".join(component_names_list) + ":"
pretty_morphism = self._print_Morphism(morphism)
return component_names + pretty_morphism
def _print_Category(self, morphism):
return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name)))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
latex_result = self._print(diagram.premises)
if diagram.conclusions:
latex_result += "\\Longrightarrow %s" % \
self._print(diagram.conclusions)
return latex_result
def _print_DiagramGrid(self, grid):
latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width)
for i in range(grid.height):
for j in range(grid.width):
if grid[i, j]:
latex_result += latex(grid[i, j])
latex_result += " "
if j != grid.width - 1:
latex_result += "& "
if i != grid.height - 1:
latex_result += "\\\\"
latex_result += "\n"
latex_result += "\\end{array}\n"
return latex_result
def _print_FreeModule(self, M):
return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank))
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return r"\left[ {} \right]".format(",".join(
'{' + self._print(x) + '}' for x in m))
def _print_SubModule(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for x in m.gens))
def _print_ModuleImplementedIdeal(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for [x] in m._module.gens))
def _print_Quaternion(self, expr):
# TODO: This expression is potentially confusing,
# shall we print it as `Quaternion( ... )`?
s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True)
for i in expr.args]
a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")]
return " + ".join(a)
def _print_QuotientRing(self, R):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(R.ring),
self._print(R.base_ideal))
def _print_QuotientRingElement(self, x):
return r"{{{}}} + {{{}}}".format(self._print(x.data),
self._print(x.ring.base_ideal))
def _print_QuotientModuleElement(self, m):
return r"{{{}}} + {{{}}}".format(self._print(m.data),
self._print(m.module.killed_module))
def _print_QuotientModule(self, M):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(M.base),
self._print(M.killed_module))
def _print_MatrixHomomorphism(self, h):
return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()),
self._print(h.domain), self._print(h.codomain))
def _print_Manifold(self, manifold):
string = manifold.name.name
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
name = r'\text{%s}' % name
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Patch(self, patch):
return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold))
def _print_CoordSystem(self, coordsys):
return r'\text{%s}^{\text{%s}}_{%s}' % (
self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold)
)
def _print_CovarDerivativeOp(self, cvd):
return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\mathbf{{{}}}'.format(self._print(Symbol(string)))
def _print_BaseVectorField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\partial_{{{}}}'.format(self._print(Symbol(string)))
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return r'\operatorname{{d}}{}'.format(self._print(Symbol(string)))
else:
string = self._print(field)
return r'\operatorname{{d}}\left({}\right)'.format(string)
def _print_Tr(self, p):
# TODO: Handle indices
contents = self._print(p.args[0])
return r'\operatorname{{tr}}\left({}\right)'.format(contents)
def _print_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\phi\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\phi\left(%s\right)' % self._print(expr.args[0])
def _print_reduced_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\lambda\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\lambda\left(%s\right)' % self._print(expr.args[0])
def _print_divisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^{%s}%s" % (exp, tex)
return r"\sigma%s" % tex
def _print_udivisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^*^{%s}%s" % (exp, tex)
return r"\sigma^*%s" % tex
def _print_primenu(self, expr, exp=None):
if exp is not None:
return r'\left(\nu\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\nu\left(%s\right)' % self._print(expr.args[0])
def _print_primeomega(self, expr, exp=None):
if exp is not None:
return r'\left(\Omega\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\Omega\left(%s\right)' % self._print(expr.args[0])
def _print_Str(self, s):
return str(s.name)
def _print_float(self, expr):
return self._print(Float(expr))
def _print_int(self, expr):
return str(expr)
def _print_mpz(self, expr):
return str(expr)
def _print_mpq(self, expr):
return str(expr)
def emptyPrinter(self, expr):
# default to just printing as monospace, like would normally be shown
s = super().emptyPrinter(expr)
return r"\mathtt{\text{%s}}" % latex_escape(s)
def translate(s):
r'''
Check for a modifier ending the string. If present, convert the
modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character,
return the appropriate latex.
Let everything else pass as given.
>>> from sympy.printing.latex import translate
>>> translate('alphahatdotprime')
"{\\dot{\\hat{\\alpha}}}'"
'''
# Process the rest
tex = tex_greek_dictionary.get(s)
if tex:
return tex
elif s.lower() in greek_letters_set:
return "\\" + s.lower()
elif s in other_symbols:
return "\\" + s
else:
# Process modifiers, if any, and recurse
for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True):
if s.lower().endswith(key) and len(s) > len(key):
return modifier_dict[key](translate(s[:-len(key)]))
return s
def latex(expr, full_prec=False, min=None, max=None, fold_frac_powers=False,
fold_func_brackets=False, fold_short_frac=None, inv_trig_style="abbreviated",
itex=False, ln_notation=False, long_frac_ratio=None,
mat_delim="[", mat_str=None, mode="plain", mul_symbol=None,
order=None, symbol_names=None, root_notation=True,
mat_symbol_style="plain", imaginary_unit="i", gothic_re_im=False,
decimal_separator="period", perm_cyclic=True, parenthesize_super=True):
r"""Convert the given expression to LaTeX string representation.
Parameters
==========
full_prec: boolean, optional
If set to True, a floating point number is printed with full precision.
fold_frac_powers : boolean, optional
Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers.
fold_func_brackets : boolean, optional
Fold function brackets where applicable.
fold_short_frac : boolean, optional
Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is
simple enough (at most two terms and no powers). The default value is
``True`` for inline mode, ``False`` otherwise.
inv_trig_style : string, optional
How inverse trig functions should be displayed. Can be one of
``abbreviated``, ``full``, or ``power``. Defaults to ``abbreviated``.
itex : boolean, optional
Specifies if itex-specific syntax is used, including emitting
``$$...$$``.
ln_notation : boolean, optional
If set to ``True``, ``\ln`` is used instead of default ``\log``.
long_frac_ratio : float or None, optional
The allowed ratio of the width of the numerator to the width of the
denominator before the printer breaks off long fractions. If ``None``
(the default value), long fractions are not broken up.
mat_delim : string, optional
The delimiter to wrap around matrices. Can be one of ``[``, ``(``, or
the empty string. Defaults to ``[``.
mat_str : string, optional
Which matrix environment string to emit. ``smallmatrix``, ``matrix``,
``array``, etc. Defaults to ``smallmatrix`` for inline mode, ``matrix``
for matrices of no more than 10 columns, and ``array`` otherwise.
mode: string, optional
Specifies how the generated code will be delimited. ``mode`` can be one
of ``plain``, ``inline``, ``equation`` or ``equation*``. If ``mode``
is set to ``plain``, then the resulting code will not be delimited at
all (this is the default). If ``mode`` is set to ``inline`` then inline
LaTeX ``$...$`` will be used. If ``mode`` is set to ``equation`` or
``equation*``, the resulting code will be enclosed in the ``equation``
or ``equation*`` environment (remember to import ``amsmath`` for
``equation*``), unless the ``itex`` option is set. In the latter case,
the ``$$...$$`` syntax is used.
mul_symbol : string or None, optional
The symbol to use for multiplication. Can be one of ``None``, ``ldot``,
``dot``, or ``times``.
order: string, optional
Any of the supported monomial orderings (currently ``lex``, ``grlex``,
or ``grevlex``), ``old``, and ``none``. This parameter does nothing for
Mul objects. Setting order to ``old`` uses the compatibility ordering
for Add defined in Printer. For very large expressions, set the
``order`` keyword to ``none`` if speed is a concern.
symbol_names : dictionary of strings mapped to symbols, optional
Dictionary of symbols and the custom strings they should be emitted as.
root_notation : boolean, optional
If set to ``False``, exponents of the form 1/n are printed in fractonal
form. Default is ``True``, to print exponent in root form.
mat_symbol_style : string, optional
Can be either ``plain`` (default) or ``bold``. If set to ``bold``,
a MatrixSymbol A will be printed as ``\mathbf{A}``, otherwise as ``A``.
imaginary_unit : string, optional
String to use for the imaginary unit. Defined options are "i" (default)
and "j". Adding "r" or "t" in front gives ``\mathrm`` or ``\text``, so
"ri" leads to ``\mathrm{i}`` which gives `\mathrm{i}`.
gothic_re_im : boolean, optional
If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively.
The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`.
decimal_separator : string, optional
Specifies what separator to use to separate the whole and fractional parts of a
floating point number as in `2.5` for the default, ``period`` or `2{,}5`
when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon
separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when
``comma`` is chosen and [1,2,3] for when ``period`` is chosen.
parenthesize_super : boolean, optional
If set to ``False``, superscripted expressions will not be parenthesized when
powered. Default is ``True``, which parenthesizes the expression when powered.
min: Integer or None, optional
Sets the lower bound for the exponent to print floating point numbers in
fixed-point format.
max: Integer or None, optional
Sets the upper bound for the exponent to print floating point numbers in
fixed-point format.
Notes
=====
Not using a print statement for printing, results in double backslashes for
latex commands since that's the way Python escapes backslashes in strings.
>>> from sympy import latex, Rational
>>> from sympy.abc import tau
>>> latex((2*tau)**Rational(7,2))
'8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
Examples
========
>>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log
>>> from sympy.abc import x, y, mu, r, tau
Basic usage:
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
``mode`` and ``itex`` options:
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
Fraction options:
>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True))
8 \sqrt{2} \tau^{7/2}
>>> print(latex((2*tau)**sin(Rational(7,2))))
\left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
>>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True))
\left(2 \tau\right)^{\sin {\frac{7}{2}}}
>>> print(latex(3*x**2/y))
\frac{3 x^{2}}{y}
>>> print(latex(3*x**2/y, fold_short_frac=True))
3 x^{2} / y
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2))
\frac{\int r\, dr}{2 \pi}
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0))
\frac{1}{2 \pi} \int r\, dr
Multiplication options:
>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times"))
\left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
Trig options:
>>> print(latex(asin(Rational(7,2))))
\operatorname{asin}{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="full"))
\arcsin{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="power"))
\sin^{-1}{\left(\frac{7}{2} \right)}
Matrix options:
>>> print(latex(Matrix(2, 1, [x, y])))
\left[\begin{matrix}x\\y\end{matrix}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array"))
\left[\begin{array}{c}x\\y\end{array}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_delim="("))
\left(\begin{matrix}x\\y\end{matrix}\right)
Custom printing of symbols:
>>> print(latex(x**2, symbol_names={x: 'x_i'}))
x_i^{2}
Logarithms:
>>> print(latex(log(10)))
\log{\left(10 \right)}
>>> print(latex(log(10), ln_notation=True))
\ln{\left(10 \right)}
``latex()`` also supports the builtin container types :class:`list`,
:class:`tuple`, and :class:`dict`:
>>> print(latex([2/x, y], mode='inline'))
$\left[ 2 / x, \ y\right]$
Unsupported types are rendered as monospaced plaintext:
>>> print(latex(int))
\mathtt{\text{<class 'int'>}}
>>> print(latex("plain % text"))
\mathtt{\text{plain \% text}}
See :ref:`printer_method_example` for an example of how to override
this behavior for your own types by implementing ``_latex``.
.. versionchanged:: 1.7.0
Unsupported types no longer have their ``str`` representation treated as valid latex.
"""
if symbol_names is None:
symbol_names = {}
settings = {
'full_prec': full_prec,
'fold_frac_powers': fold_frac_powers,
'fold_func_brackets': fold_func_brackets,
'fold_short_frac': fold_short_frac,
'inv_trig_style': inv_trig_style,
'itex': itex,
'ln_notation': ln_notation,
'long_frac_ratio': long_frac_ratio,
'mat_delim': mat_delim,
'mat_str': mat_str,
'mode': mode,
'mul_symbol': mul_symbol,
'order': order,
'symbol_names': symbol_names,
'root_notation': root_notation,
'mat_symbol_style': mat_symbol_style,
'imaginary_unit': imaginary_unit,
'gothic_re_im': gothic_re_im,
'decimal_separator': decimal_separator,
'perm_cyclic' : perm_cyclic,
'parenthesize_super' : parenthesize_super,
'min': min,
'max': max,
}
return LatexPrinter(settings).doprint(expr)
def print_latex(expr, **settings):
"""Prints LaTeX representation of the given expression. Takes the same
settings as ``latex()``."""
print(latex(expr, **settings))
def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings):
r"""
This function generates a LaTeX equation with a multiline right-hand side
in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment.
Parameters
==========
lhs : Expr
Left-hand side of equation
rhs : Expr
Right-hand side of equation
terms_per_line : integer, optional
Number of terms per line to print. Default is 1.
environment : "string", optional
Which LaTeX wnvironment to use for the output. Options are "align*"
(default), "eqnarray", and "IEEEeqnarray".
use_dots : boolean, optional
If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``.
Examples
========
>>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I
>>> x, y, alpha = symbols('x y alpha')
>>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y))
>>> print(multiline_latex(x, expr))
\begin{align*}
x = & e^{i \alpha} \\
& + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using at most two terms per line:
>>> print(multiline_latex(x, expr, 2))
\begin{align*}
x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using ``eqnarray`` and dots:
>>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True))
\begin{eqnarray}
x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{eqnarray}
Using ``IEEEeqnarray``:
>>> print(multiline_latex(x, expr, environment="IEEEeqnarray"))
\begin{IEEEeqnarray}{rCl}
x & = & e^{i \alpha} \nonumber\\
& & + \sin{\left(\alpha y \right)} \nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{IEEEeqnarray}
Notes
=====
All optional parameters from ``latex`` can also be used.
"""
# Based on code from https://github.com/sympy/sympy/issues/3001
l = LatexPrinter(**settings)
if environment == "eqnarray":
result = r'\begin{eqnarray}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{eqnarray}'
doubleet = True
elif environment == "IEEEeqnarray":
result = r'\begin{IEEEeqnarray}{rCl}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{IEEEeqnarray}'
doubleet = True
elif environment == "align*":
result = r'\begin{align*}' + '\n'
first_term = '= &'
nonumber = ''
end_term = '\n\\end{align*}'
doubleet = False
else:
raise ValueError("Unknown environment: {}".format(environment))
dots = ''
if use_dots:
dots=r'\dots'
terms = rhs.as_ordered_terms()
n_terms = len(terms)
term_count = 1
for i in range(n_terms):
term = terms[i]
term_start = ''
term_end = ''
sign = '+'
if term_count > terms_per_line:
if doubleet:
term_start = '& & '
else:
term_start = '& '
term_count = 1
if term_count == terms_per_line:
# End of line
if i < n_terms-1:
# There are terms remaining
term_end = dots + nonumber + r'\\' + '\n'
else:
term_end = ''
if term.as_ordered_factors()[0] == -1:
term = -1*term
sign = r'-'
if i == 0: # beginning
if sign == '+':
sign = ''
result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs),
first_term, sign, l.doprint(term), term_end)
else:
result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign,
l.doprint(term), term_end)
term_count += 1
result += end_term
return result
|
d4f4f6ea6126628a52c757e711ef7e7a36fae9f8545eca238990b2020bca537f | """Printing subsystem driver
SymPy's printing system works the following way: Any expression can be
passed to a designated Printer who then is responsible to return an
adequate representation of that expression.
**The basic concept is the following:**
1. Let the object print itself if it knows how.
2. Take the best fitting method defined in the printer.
3. As fall-back use the emptyPrinter method for the printer.
Which Method is Responsible for Printing?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The whole printing process is started by calling ``.doprint(expr)`` on the printer
which you want to use. This method looks for an appropriate method which can
print the given expression in the given style that the printer defines.
While looking for the method, it follows these steps:
1. **Let the object print itself if it knows how.**
The printer looks for a specific method in every object. The name of that method
depends on the specific printer and is defined under ``Printer.printmethod``.
For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``.
Look at the documentation of the printer that you want to use.
The name of the method is specified there.
This was the original way of doing printing in sympy. Every class had
its own latex, mathml, str and repr methods, but it turned out that it
is hard to produce a high quality printer, if all the methods are spread
out that far. Therefore all printing code was combined into the different
printers, which works great for built-in sympy objects, but not that
good for user defined classes where it is inconvenient to patch the
printers.
2. **Take the best fitting method defined in the printer.**
The printer loops through expr classes (class + its bases), and tries
to dispatch the work to ``_print_<EXPR_CLASS>``
e.g., suppose we have the following class hierarchy::
Basic
|
Atom
|
Number
|
Rational
then, for ``expr=Rational(...)``, the Printer will try
to call printer methods in the order as shown in the figure below::
p._print(expr)
|
|-- p._print_Rational(expr)
|
|-- p._print_Number(expr)
|
|-- p._print_Atom(expr)
|
`-- p._print_Basic(expr)
if ``._print_Rational`` method exists in the printer, then it is called,
and the result is returned back. Otherwise, the printer tries to call
``._print_Number`` and so on.
3. **As a fall-back use the emptyPrinter method for the printer.**
As fall-back ``self.emptyPrinter`` will be called with the expression. If
not defined in the Printer subclass this will be the same as ``str(expr)``.
.. _printer_example:
Example of Custom Printer
^^^^^^^^^^^^^^^^^^^^^^^^^
In the example below, we have a printer which prints the derivative of a function
in a shorter form.
.. code-block:: python
from sympy import Symbol
from sympy.printing.latex import LatexPrinter, print_latex
from sympy.core.function import UndefinedFunction, Function
class MyLatexPrinter(LatexPrinter):
\"\"\"Print derivative of a function of symbols in a shorter form.
\"\"\"
def _print_Derivative(self, expr):
function, *vars = expr.args
if not isinstance(type(function), UndefinedFunction) or \\
not all(isinstance(i, Symbol) for i in vars):
return super()._print_Derivative(expr)
# If you want the printer to work correctly for nested
# expressions then use self._print() instead of str() or latex().
# See the example of nested modulo below in the custom printing
# method section.
return "{}_{{{}}}".format(
self._print(Symbol(function.func.__name__)),
''.join(self._print(i) for i in vars))
def print_my_latex(expr):
\"\"\" Most of the printers define their own wrappers for print().
These wrappers usually take printer settings. Our printer does not have
any settings.
\"\"\"
print(MyLatexPrinter().doprint(expr))
y = Symbol("y")
x = Symbol("x")
f = Function("f")
expr = f(x, y).diff(x, y)
# Print the expression using the normal latex printer and our custom
# printer.
print_latex(expr)
print_my_latex(expr)
The output of the code above is::
\\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)}
f_{xy}
.. _printer_method_example:
Example of Custom Printing Method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In the example below, the latex printing of the modulo operator is modified.
This is done by overriding the method ``_latex`` of ``Mod``.
>>> from sympy import Symbol, Mod, Integer
>>> from sympy.printing.latex import print_latex
>>> # Always use printer._print()
>>> class ModOp(Mod):
... def _latex(self, printer):
... a, b = [printer._print(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b)
Comparing the output of our custom operator to the builtin one:
>>> x = Symbol('x')
>>> m = Symbol('m')
>>> print_latex(Mod(x, m))
x\\bmod{m}
>>> print_latex(ModOp(x, m))
\\operatorname{Mod}{\\left( x,m \\right)}
Common mistakes
~~~~~~~~~~~~~~~
It's important to always use ``self._print(obj)`` to print subcomponents of
an expression when customizing a printer. Mistakes include:
1. Using ``self.doprint(obj)`` instead:
>>> # This example does not work properly, as only the outermost call may use
>>> # doprint.
>>> class ModOpModeWrong(Mod):
... def _latex(self, printer):
... a, b = [printer.doprint(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b)
This fails when the `mode` argument is passed to the printer:
>>> print_latex(ModOp(x, m), mode='inline') # ok
$\\operatorname{Mod}{\\left( x,m \\right)}$
>>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad
$\\operatorname{Mod}{\\left( $x$,$m$ \\right)}$
2. Using ``str(obj)`` instead:
>>> class ModOpNestedWrong(Mod):
... def _latex(self, printer):
... a, b = [str(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b)
This fails on nested objects:
>>> # Nested modulo.
>>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok
\\operatorname{Mod}{\\left( \\operatorname{Mod}{\\left( x,m \\right)},7 \\right)}
>>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad
\\operatorname{Mod}{\\left( ModOpNestedWrong(x, m),7 \\right)}
3. Using ``LatexPrinter()._print(obj)`` instead.
>>> from sympy.printing.latex import LatexPrinter
>>> class ModOpSettingsWrong(Mod):
... def _latex(self, printer):
... a, b = [LatexPrinter()._print(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b)
This causes all the settings to be discarded in the subobjects. As an
example, the ``full_prec`` setting which shows floats to full precision is
ignored:
>>> from sympy import Float
>>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok
\\operatorname{Mod}{\\left( 1.00000000000000 x,m \\right)}
>>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad
\\operatorname{Mod}{\\left( 1.0 x,m \\right)}
"""
from __future__ import print_function, division
from typing import Any, Dict
from contextlib import contextmanager
from sympy import Basic, Add
from sympy.core.core import BasicMeta
from sympy.core.function import AppliedUndef, UndefinedFunction, Function
from functools import cmp_to_key
@contextmanager
def printer_context(printer, **kwargs):
original = printer._context.copy()
try:
printer._context.update(kwargs)
yield
finally:
printer._context = original
class Printer(object):
""" Generic printer
Its job is to provide infrastructure for implementing new printers easily.
If you want to define your custom Printer or your custom printing method
for your custom class then see the example above: printer_example_ .
"""
_global_settings = {} # type: Dict[str, Any]
_default_settings = {} # type: Dict[str, Any]
printmethod = None # type: str
def __init__(self, settings=None):
self._str = str
self._settings = self._default_settings.copy()
self._context = dict() # mutable during printing
for key, val in self._global_settings.items():
if key in self._default_settings:
self._settings[key] = val
if settings is not None:
self._settings.update(settings)
if len(self._settings) > len(self._default_settings):
for key in self._settings:
if key not in self._default_settings:
raise TypeError("Unknown setting '%s'." % key)
# _print_level is the number of times self._print() was recursively
# called. See StrPrinter._print_Float() for an example of usage
self._print_level = 0
@classmethod
def set_global_settings(cls, **settings):
"""Set system-wide printing settings. """
for key, val in settings.items():
if val is not None:
cls._global_settings[key] = val
@property
def order(self):
if 'order' in self._settings:
return self._settings['order']
else:
raise AttributeError("No order defined.")
def doprint(self, expr):
"""Returns printer's representation for expr (as a string)"""
return self._str(self._print(expr))
def _print(self, expr, **kwargs):
"""Internal dispatcher
Tries the following concepts to print an expression:
1. Let the object print itself if it knows how.
2. Take the best fitting method defined in the printer.
3. As fall-back use the emptyPrinter method for the printer.
"""
self._print_level += 1
try:
# If the printer defines a name for a printing method
# (Printer.printmethod) and the object knows for itself how it
# should be printed, use that method.
if (self.printmethod and hasattr(expr, self.printmethod)
and not isinstance(expr, BasicMeta)):
return getattr(expr, self.printmethod)(self, **kwargs)
# See if the class of expr is known, or if one of its super
# classes is known, and use that print function
# Exception: ignore the subclasses of Undefined, so that, e.g.,
# Function('gamma') does not get dispatched to _print_gamma
classes = type(expr).__mro__
if AppliedUndef in classes:
classes = classes[classes.index(AppliedUndef):]
if UndefinedFunction in classes:
classes = classes[classes.index(UndefinedFunction):]
# Another exception: if someone subclasses a known function, e.g.,
# gamma, and changes the name, then ignore _print_gamma
if Function in classes:
i = classes.index(Function)
classes = tuple(c for c in classes[:i] if \
c.__name__ == classes[0].__name__ or \
c.__name__.endswith("Base")) + classes[i:]
for cls in classes:
printmethod = '_print_' + cls.__name__
if hasattr(self, printmethod):
return getattr(self, printmethod)(expr, **kwargs)
# Unknown object, fall back to the emptyPrinter.
return self.emptyPrinter(expr)
finally:
self._print_level -= 1
def emptyPrinter(self, expr):
return str(expr)
def _as_ordered_terms(self, expr, order=None):
"""A compatibility function for ordering terms in Add. """
order = order or self.order
if order == 'old':
return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty))
elif order == 'none':
return list(expr.args)
else:
return expr.as_ordered_terms(order=order)
|
570af13e0dd88ad6497996d5328fd081a5f4d3d9ea9530297dfad5ced6ca3393 | """
C code printer
The C89CodePrinter & C99CodePrinter converts single sympy expressions into
single C expressions, using the functions defined in math.h where possible.
A complete code generator, which uses ccode extensively, can be found in
sympy.utilities.codegen. The codegen module can be used to generate complete
source code files that are compilable without further modifications.
"""
from __future__ import print_function, division
from typing import Any, Dict, Tuple
from functools import wraps
from itertools import chain
from sympy.core import S
from sympy.codegen.ast import (
Assignment, Pointer, Variable, Declaration, Type,
real, complex_, integer, bool_, float32, float64, float80,
complex64, complex128, intc, value_const, pointer_const,
int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped
)
from sympy.printing.codeprinter import CodePrinter, requires
from sympy.printing.precedence import precedence, PRECEDENCE
from sympy.sets.fancysets import Range
# These are defined in the other file so we can avoid importing sympy.codegen
# from the top-level 'import sympy'. Export them here as well.
from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401
# dictionary mapping sympy function to (argument_conditions, C_function).
# Used in C89CodePrinter._print_Function(self)
known_functions_C89 = {
"Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
"sin": "sin",
"cos": "cos",
"tan": "tan",
"asin": "asin",
"acos": "acos",
"atan": "atan",
"atan2": "atan2",
"exp": "exp",
"log": "log",
"sinh": "sinh",
"cosh": "cosh",
"tanh": "tanh",
"floor": "floor",
"ceiling": "ceil",
}
known_functions_C99 = dict(known_functions_C89, **{
'exp2': 'exp2',
'expm1': 'expm1',
'log10': 'log10',
'log2': 'log2',
'log1p': 'log1p',
'Cbrt': 'cbrt',
'hypot': 'hypot',
'fma': 'fma',
'loggamma': 'lgamma',
'erfc': 'erfc',
'Max': 'fmax',
'Min': 'fmin',
"asinh": "asinh",
"acosh": "acosh",
"atanh": "atanh",
"erf": "erf",
"gamma": "tgamma",
})
# These are the core reserved words in the C language. Taken from:
# http://en.cppreference.com/w/c/keyword
reserved_words = [
'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
'struct', 'entry', # never standardized, we'll leave it here anyway
'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'
]
reserved_words_c99 = ['inline', 'restrict']
def get_math_macros():
""" Returns a dictionary with math-related macros from math.h/cmath
Note that these macros are not strictly required by the C/C++-standard.
For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably
via a compilation flag).
Returns
=======
Dictionary mapping sympy expressions to strings (macro names)
"""
from sympy.codegen.cfunctions import log2, Sqrt
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.miscellaneous import sqrt
return {
S.Exp1: 'M_E',
log2(S.Exp1): 'M_LOG2E',
1/log(2): 'M_LOG2E',
log(2): 'M_LN2',
log(10): 'M_LN10',
S.Pi: 'M_PI',
S.Pi/2: 'M_PI_2',
S.Pi/4: 'M_PI_4',
1/S.Pi: 'M_1_PI',
2/S.Pi: 'M_2_PI',
2/sqrt(S.Pi): 'M_2_SQRTPI',
2/Sqrt(S.Pi): 'M_2_SQRTPI',
sqrt(2): 'M_SQRT2',
Sqrt(2): 'M_SQRT2',
1/sqrt(2): 'M_SQRT1_2',
1/Sqrt(2): 'M_SQRT1_2'
}
def _as_macro_if_defined(meth):
""" Decorator for printer methods
When a Printer's method is decorated using this decorator the expressions printed
will first be looked for in the attribute ``math_macros``, and if present it will
print the macro name in ``math_macros`` followed by a type suffix for the type
``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.
"""
@wraps(meth)
def _meth_wrapper(self, expr, **kwargs):
if expr in self.math_macros:
return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real))
else:
return meth(self, expr, **kwargs)
return _meth_wrapper
class C89CodePrinter(CodePrinter):
"""A printer to convert python expressions to strings of c code"""
printmethod = "_ccode"
language = "C"
standard = "C89"
reserved_words = set(reserved_words)
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'contract': True,
'dereference': set(),
'error_on_reserved': False,
'reserved_word_suffix': '_',
} # type: Dict[str, Any]
type_aliases = {
real: float64,
complex_: complex128,
integer: intc
}
type_mappings = {
real: 'double',
intc: 'int',
float32: 'float',
float64: 'double',
integer: 'int',
bool_: 'bool',
int8: 'int8_t',
int16: 'int16_t',
int32: 'int32_t',
int64: 'int64_t',
uint8: 'int8_t',
uint16: 'int16_t',
uint32: 'int32_t',
uint64: 'int64_t',
} # type: Dict[Type, Any]
type_headers = {
bool_: {'stdbool.h'},
int8: {'stdint.h'},
int16: {'stdint.h'},
int32: {'stdint.h'},
int64: {'stdint.h'},
uint8: {'stdint.h'},
uint16: {'stdint.h'},
uint32: {'stdint.h'},
uint64: {'stdint.h'},
}
# Macros needed to be defined when using a Type
type_macros = {} # type: Dict[Type, Tuple[str, ...]]
type_func_suffixes = {
float32: 'f',
float64: '',
float80: 'l'
}
type_literal_suffixes = {
float32: 'F',
float64: '',
float80: 'L'
}
type_math_macro_suffixes = {
float80: 'l'
}
math_macros = None
_ns = '' # namespace, C++ uses 'std::'
# known_functions-dict to copy
_kf = known_functions_C89 # type: Dict[str, Any]
def __init__(self, settings=None):
settings = settings or {}
if self.math_macros is None:
self.math_macros = settings.pop('math_macros', get_math_macros())
self.type_aliases = dict(chain(self.type_aliases.items(),
settings.pop('type_aliases', {}).items()))
self.type_mappings = dict(chain(self.type_mappings.items(),
settings.pop('type_mappings', {}).items()))
self.type_headers = dict(chain(self.type_headers.items(),
settings.pop('type_headers', {}).items()))
self.type_macros = dict(chain(self.type_macros.items(),
settings.pop('type_macros', {}).items()))
self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(),
settings.pop('type_func_suffixes', {}).items()))
self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(),
settings.pop('type_literal_suffixes', {}).items()))
self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(),
settings.pop('type_math_macro_suffixes', {}).items()))
super(C89CodePrinter, self).__init__(settings)
self.known_functions = dict(self._kf, **settings.get('user_functions', {}))
self._dereference = set(settings.get('dereference', []))
self.headers = set()
self.libraries = set()
self.macros = set()
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
""" Get code string as a statement - i.e. ending with a semicolon. """
return codestring if codestring.endswith(';') else codestring + ';'
def _get_comment(self, text):
return "// {0}".format(text)
def _declare_number_const(self, name, value):
type_ = self.type_aliases[real]
var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const})
decl = Declaration(var)
return self._get_statement(self._print(decl))
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for i in range(rows) for j in range(cols))
@_as_macro_if_defined
def _print_Mul(self, expr, **kwargs):
return super(C89CodePrinter, self)._print_Mul(expr, **kwargs)
@_as_macro_if_defined
def _print_Pow(self, expr):
if "Pow" in self.known_functions:
return self._print_Function(expr)
PREC = precedence(expr)
suffix = self._get_func_suffix(real)
if expr.exp == -1:
return '1.0%s/%s' % (suffix.upper(), self.parenthesize(expr.base, PREC))
elif expr.exp == 0.5:
return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
elif expr.exp == S.One/3 and self.standard != 'C89':
return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
else:
return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base),
self._print(expr.exp))
def _print_Mod(self, expr):
num, den = expr.args
if num.is_integer and den.is_integer:
return "(({}) % ({}))".format(self._print(num), self._print(den))
else:
return self._print_math_func(expr, known='fmod')
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
suffix = self._get_literal_suffix(real)
return '%d.0%s/%d.0%s' % (p, suffix, q, suffix)
def _print_Indexed(self, expr):
# calculate index for 1d array
offset = getattr(expr.base, 'offset', S.Zero)
strides = getattr(expr.base, 'strides', None)
indices = expr.indices
if strides is None or isinstance(strides, str):
dims = expr.shape
shift = S.One
temp = tuple()
if strides == 'C' or strides is None:
traversal = reversed(range(expr.rank))
indices = indices[::-1]
elif strides == 'F':
traversal = range(expr.rank)
for i in traversal:
temp += (shift,)
shift *= dims[i]
strides = temp
flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset
return "%s[%s]" % (self._print(expr.base.label),
self._print(flat_index))
def _print_Idx(self, expr):
return self._print(expr.label)
@_as_macro_if_defined
def _print_NumberSymbol(self, expr):
return super(C89CodePrinter, self)._print_NumberSymbol(expr)
def _print_Infinity(self, expr):
return 'HUGE_VAL'
def _print_NegativeInfinity(self, expr):
return '-HUGE_VAL'
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if expr.has(Assignment):
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) {" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else {")
else:
lines.append("else if (%s) {" % self._print(c))
code0 = self._print(e)
lines.append(code0)
lines.append("}")
return "\n".join(lines)
else:
# The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will
# not work for statements that span multiple lines (Matrix or
# Indexed expressions).
ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
self._print(e))
for e, c in expr.args[:-1]]
last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
def _print_ITE(self, expr):
from sympy.functions import Piecewise
_piecewise = Piecewise((expr.args[1], expr.args[0]), (expr.args[2], True))
return self._print(_piecewise)
def _print_MatrixElement(self, expr):
return "{0}[{1}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
strict=True), expr.j + expr.i*expr.parent.shape[1])
def _print_Symbol(self, expr):
name = super(C89CodePrinter, self)._print_Symbol(expr)
if expr in self._settings['dereference']:
return '(*{0})'.format(name)
else:
return name
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_sinc(self, expr):
from sympy.functions.elementary.trigonometric import sin
from sympy.core.relational import Ne
from sympy.functions import Piecewise
_piecewise = Piecewise(
(sin(expr.args[0]) / expr.args[0], Ne(expr.args[0], 0)), (1, True))
return self._print(_piecewise)
def _print_For(self, expr):
target = self._print(expr.target)
if isinstance(expr.iterable, Range):
start, stop, step = expr.iterable.args
else:
raise NotImplementedError("Only iterable currently supported is Range")
body = self._print(expr.body)
return ('for ({target} = {start}; {target} < {stop}; {target} += '
'{step}) {{\n{body}\n}}').format(target=target, start=start,
stop=stop, step=step, body=body)
def _print_sign(self, func):
return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0]))
def _print_Max(self, expr):
if "Max" in self.known_functions:
return self._print_Function(expr)
def inner_print_max(args): # The more natural abstraction of creating
if len(args) == 1: # and printing smaller Max objects is slow
return self._print(args[0]) # when there are many arguments.
half = len(args) // 2
return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % {
'a': inner_print_max(args[:half]),
'b': inner_print_max(args[half:])
}
return inner_print_max(expr.args)
def _print_Min(self, expr):
if "Min" in self.known_functions:
return self._print_Function(expr)
def inner_print_min(args): # The more natural abstraction of creating
if len(args) == 1: # and printing smaller Min objects is slow
return self._print(args[0]) # when there are many arguments.
half = len(args) // 2
return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % {
'a': inner_print_min(args[:half]),
'b': inner_print_min(args[half:])
}
return inner_print_min(expr.args)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [line.lstrip(' \t') for line in code]
increase = [int(any(map(line.endswith, inc_token))) for line in code]
decrease = [int(any(map(line.startswith, dec_token))) for line in code]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def _get_func_suffix(self, type_):
return self.type_func_suffixes[self.type_aliases.get(type_, type_)]
def _get_literal_suffix(self, type_):
return self.type_literal_suffixes[self.type_aliases.get(type_, type_)]
def _get_math_macro_suffix(self, type_):
alias = self.type_aliases.get(type_, type_)
dflt = self.type_math_macro_suffixes.get(alias, '')
return self.type_math_macro_suffixes.get(type_, dflt)
def _print_Type(self, type_):
self.headers.update(self.type_headers.get(type_, set()))
self.macros.update(self.type_macros.get(type_, set()))
return self._print(self.type_mappings.get(type_, type_.name))
def _print_Declaration(self, decl):
from sympy.codegen.cnodes import restrict
var = decl.variable
val = var.value
if var.type == untyped:
raise ValueError("C does not support untyped variables")
if isinstance(var, Pointer):
result = '{vc}{t} *{pc} {r}{s}'.format(
vc='const ' if value_const in var.attrs else '',
t=self._print(var.type),
pc=' const' if pointer_const in var.attrs else '',
r='restrict ' if restrict in var.attrs else '',
s=self._print(var.symbol)
)
elif isinstance(var, Variable):
result = '{vc}{t} {s}'.format(
vc='const ' if value_const in var.attrs else '',
t=self._print(var.type),
s=self._print(var.symbol)
)
else:
raise NotImplementedError("Unknown type of var: %s" % type(var))
if val != None: # Must be "!= None", cannot be "is not None"
result += ' = %s' % self._print(val)
return result
def _print_Float(self, flt):
type_ = self.type_aliases.get(real, real)
self.macros.update(self.type_macros.get(type_, set()))
suffix = self._get_literal_suffix(type_)
num = str(flt.evalf(type_.decimal_dig))
if 'e' not in num and '.' not in num:
num += '.0'
num_parts = num.split('e')
num_parts[0] = num_parts[0].rstrip('0')
if num_parts[0].endswith('.'):
num_parts[0] += '0'
return 'e'.join(num_parts) + suffix
@requires(headers={'stdbool.h'})
def _print_BooleanTrue(self, expr):
return 'true'
@requires(headers={'stdbool.h'})
def _print_BooleanFalse(self, expr):
return 'false'
def _print_Element(self, elem):
if elem.strides == None: # Must be "== None", cannot be "is None"
if elem.offset != None: # Must be "!= None", cannot be "is not None"
raise ValueError("Expected strides when offset is given")
idxs = ']['.join(map(lambda arg: self._print(arg),
elem.indices))
else:
global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)])
if elem.offset != None: # Must be "!= None", cannot be "is not None"
global_idx += elem.offset
idxs = self._print(global_idx)
return "{symb}[{idxs}]".format(
symb=self._print(elem.symbol),
idxs=idxs
)
def _print_CodeBlock(self, expr):
""" Elements of code blocks printed as statements. """
return '\n'.join([self._get_statement(self._print(i)) for i in expr.args])
def _print_While(self, expr):
return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs(
apply=lambda arg: self._print(arg)))
def _print_Scope(self, expr):
return '{\n%s\n}' % self._print_CodeBlock(expr.body)
@requires(headers={'stdio.h'})
def _print_Print(self, expr):
return 'printf({fmt}, {pargs})'.format(
fmt=self._print(expr.format_string),
pargs=', '.join(map(lambda arg: self._print(arg), expr.print_args))
)
def _print_FunctionPrototype(self, expr):
pars = ', '.join(map(lambda arg: self._print(Declaration(arg)),
expr.parameters))
return "%s %s(%s)" % (
tuple(map(lambda arg: self._print(arg),
(expr.return_type, expr.name))) + (pars,)
)
def _print_FunctionDefinition(self, expr):
return "%s%s" % (self._print_FunctionPrototype(expr),
self._print_Scope(expr))
def _print_Return(self, expr):
arg, = expr.args
return 'return %s' % self._print(arg)
def _print_CommaOperator(self, expr):
return '(%s)' % ', '.join(map(lambda arg: self._print(arg), expr.args))
def _print_Label(self, expr):
return '%s:' % str(expr)
def _print_goto(self, expr):
return 'goto %s' % expr.label
def _print_PreIncrement(self, expr):
arg, = expr.args
return '++(%s)' % self._print(arg)
def _print_PostIncrement(self, expr):
arg, = expr.args
return '(%s)++' % self._print(arg)
def _print_PreDecrement(self, expr):
arg, = expr.args
return '--(%s)' % self._print(arg)
def _print_PostDecrement(self, expr):
arg, = expr.args
return '(%s)--' % self._print(arg)
def _print_struct(self, expr):
return "%(keyword)s %(name)s {\n%(lines)s}" % dict(
keyword=expr.__class__.__name__, name=expr.name, lines=';\n'.join(
[self._print(decl) for decl in expr.declarations] + [''])
)
def _print_BreakToken(self, _):
return 'break'
def _print_ContinueToken(self, _):
return 'continue'
_print_union = _print_struct
class C99CodePrinter(C89CodePrinter):
standard = 'C99'
reserved_words = set(reserved_words + reserved_words_c99)
type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), {
complex64: 'float complex',
complex128: 'double complex',
}.items()))
type_headers = dict(chain(C89CodePrinter.type_headers.items(), {
complex64: {'complex.h'},
complex128: {'complex.h'}
}.items()))
# known_functions-dict to copy
_kf = known_functions_C99 # type: Dict[str, Any]
# functions with versions with 'f' and 'l' suffixes:
_prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2'
' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan'
' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf'
' erfc tgamma lgamma ceil floor trunc round nearbyint rint'
' frexp ldexp modf scalbn ilogb logb nextafter copysign').split()
def _print_Infinity(self, expr):
return 'INFINITY'
def _print_NegativeInfinity(self, expr):
return '-INFINITY'
def _print_NaN(self, expr):
return 'NAN'
# tgamma was already covered by 'known_functions' dict
@requires(headers={'math.h'}, libraries={'m'})
@_as_macro_if_defined
def _print_math_func(self, expr, nest=False, known=None):
if known is None:
known = self.known_functions[expr.__class__.__name__]
if not isinstance(known, str):
for cb, name in known:
if cb(*expr.args):
known = name
break
else:
raise ValueError("No matching printer")
try:
return known(self, *expr.args)
except TypeError:
suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else ''
if nest:
args = self._print(expr.args[0])
if len(expr.args) > 1:
paren_pile = ''
for curr_arg in expr.args[1:-1]:
paren_pile += ')'
args += ', {ns}{name}{suffix}({next}'.format(
ns=self._ns,
name=known,
suffix=suffix,
next = self._print(curr_arg)
)
args += ', %s%s' % (
self._print(expr.func(expr.args[-1])),
paren_pile
)
else:
args = ', '.join(map(lambda arg: self._print(arg), expr.args))
return '{ns}{name}{suffix}({args})'.format(
ns=self._ns,
name=known,
suffix=suffix,
args=args
)
def _print_Max(self, expr):
return self._print_math_func(expr, nest=True)
def _print_Min(self, expr):
return self._print_math_func(expr, nest=True)
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99
for i in indices:
# C arrays start at 0 and end at dimension-1
open_lines.append(loopstart % {
'var': self._print(i.label),
'start': self._print(i.lower),
'end': self._print(i.upper + 1)})
close_lines.append("}")
return open_lines, close_lines
for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma'
' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh '
'atanh erf erfc loggamma gamma ceiling floor').split():
setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func)
class C11CodePrinter(C99CodePrinter):
@requires(headers={'stdalign.h'})
def _print_alignof(self, expr):
arg, = expr.args
return 'alignof(%s)' % self._print(arg)
c_code_printers = {
'c89': C89CodePrinter,
'c99': C99CodePrinter,
'c11': C11CodePrinter
}
|
e2bd7712684273cf9b5e0bdf665dad984931edc110cccf31847432e4b93eb8a7 | """
Fortran code printer
The FCodePrinter converts single sympy expressions into single Fortran
expressions, using the functions defined in the Fortran 77 standard where
possible. Some useful pointers to Fortran can be found on wikipedia:
https://en.wikipedia.org/wiki/Fortran
Most of the code below is based on the "Professional Programmer\'s Guide to
Fortran77" by Clive G. Page:
http://www.star.le.ac.uk/~cgp/prof77.html
Fortran is a case-insensitive language. This might cause trouble because
SymPy is case sensitive. So, fcode adds underscores to variable names when
it is necessary to make them different for Fortran.
"""
from __future__ import print_function, division
from typing import Dict, Any
from collections import defaultdict
from itertools import chain
import string
from sympy.codegen.ast import (
Assignment, Declaration, Pointer, value_const,
float32, float64, float80, complex64, complex128, int8, int16, int32,
int64, intc, real, integer, bool_, complex_
)
from sympy.codegen.fnodes import (
allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure,
intent_in, intent_out, intent_inout
)
from sympy.core import S, Add, N, Float, Symbol
from sympy.core.function import Function
from sympy.core.relational import Eq
from sympy.sets import Range
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
from sympy.printing.printer import printer_context
# These are defined in the other file so we can avoid importing sympy.codegen
# from the top-level 'import sympy'. Export them here as well.
from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401
known_functions = {
"sin": "sin",
"cos": "cos",
"tan": "tan",
"asin": "asin",
"acos": "acos",
"atan": "atan",
"atan2": "atan2",
"sinh": "sinh",
"cosh": "cosh",
"tanh": "tanh",
"log": "log",
"exp": "exp",
"erf": "erf",
"Abs": "abs",
"conjugate": "conjg",
"Max": "max",
"Min": "min",
}
class FCodePrinter(CodePrinter):
"""A printer to convert sympy expressions to strings of Fortran code"""
printmethod = "_fcode"
language = "Fortran"
type_aliases = {
integer: int32,
real: float64,
complex_: complex128,
}
type_mappings = {
intc: 'integer(c_int)',
float32: 'real*4', # real(kind(0.e0))
float64: 'real*8', # real(kind(0.d0))
float80: 'real*10', # real(kind(????))
complex64: 'complex*8',
complex128: 'complex*16',
int8: 'integer*1',
int16: 'integer*2',
int32: 'integer*4',
int64: 'integer*8',
bool_: 'logical'
}
type_modules = {
intc: {'iso_c_binding': 'c_int'}
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'source_format': 'fixed',
'contract': True,
'standard': 77,
'name_mangling' : True,
} # type: Dict[str, Any]
_operators = {
'and': '.and.',
'or': '.or.',
'xor': '.neqv.',
'equivalent': '.eqv.',
'not': '.not. ',
}
_relationals = {
'!=': '/=',
}
def __init__(self, settings=None):
if not settings:
settings = {}
self.mangled_symbols = {} # Dict showing mapping of all words
self.used_name = []
self.type_aliases = dict(chain(self.type_aliases.items(),
settings.pop('type_aliases', {}).items()))
self.type_mappings = dict(chain(self.type_mappings.items(),
settings.pop('type_mappings', {}).items()))
super(FCodePrinter, self).__init__(settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
# leading columns depend on fixed or free format
standards = {66, 77, 90, 95, 2003, 2008}
if self._settings['standard'] not in standards:
raise ValueError("Unknown Fortran standard: %s" % self._settings[
'standard'])
self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int
@property
def _lead(self):
if self._settings['source_format'] == 'fixed':
return {'code': " ", 'cont': " @ ", 'comment': "C "}
elif self._settings['source_format'] == 'free':
return {'code': "", 'cont': " ", 'comment': "! "}
else:
raise ValueError("Unknown source format: %s" % self._settings['source_format'])
def _print_Symbol(self, expr):
if self._settings['name_mangling'] == True:
if expr not in self.mangled_symbols:
name = expr.name
while name.lower() in self.used_name:
name += '_'
self.used_name.append(name.lower())
if name == expr.name:
self.mangled_symbols[expr] = expr
else:
self.mangled_symbols[expr] = Symbol(name)
expr = expr.xreplace(self.mangled_symbols)
name = super(FCodePrinter, self)._print_Symbol(expr)
return name
def _rate_index_position(self, p):
return -p*5
def _get_statement(self, codestring):
return codestring
def _get_comment(self, text):
return "! {0}".format(text)
def _declare_number_const(self, name, value):
return "parameter ({0} = {1})".format(name, self._print(value))
def _print_NumberSymbol(self, expr):
# A Number symbol that is not implemented here or with _printmethod
# is registered and evaluated
self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision']))))
return str(expr)
def _format_code(self, lines):
return self._wrap_fortran(self.indent_code(lines))
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for j in range(cols) for i in range(rows))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
for i in indices:
# fortran arrays start at 1 and end at dimension
var, start, stop = map(self._print,
[i.label, i.lower + 1, i.upper + 1])
open_lines.append("do %s = %s, %s" % (var, start, stop))
close_lines.append("end do")
return open_lines, close_lines
def _print_sign(self, expr):
from sympy import Abs
arg, = expr.args
if arg.is_integer:
new_expr = merge(0, isign(1, arg), Eq(arg, 0))
elif (arg.is_complex or arg.is_infinite):
new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0)))
else:
new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0)))
return self._print(new_expr)
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if expr.has(Assignment):
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) then" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else")
else:
lines.append("else if (%s) then" % self._print(c))
lines.append(self._print(e))
lines.append("end if")
return "\n".join(lines)
elif self._settings["standard"] >= 95:
# Only supported in F95 and newer:
# The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will
# not work for statements that span multiple lines (Matrix or
# Indexed expressions).
pattern = "merge({T}, {F}, {COND})"
code = self._print(expr.args[-1].expr)
terms = list(expr.args[:-1])
while terms:
e, c = terms.pop()
expr = self._print(e)
cond = self._print(c)
code = pattern.format(T=expr, F=code, COND=cond)
return code
else:
# `merge` is not supported prior to F95
raise NotImplementedError("Using Piecewise as an expression using "
"inline operators is not supported in "
"standards earlier than Fortran95.")
def _print_MatrixElement(self, expr):
return "{0}({1}, {2})".format(self.parenthesize(expr.parent,
PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1)
def _print_Add(self, expr):
# purpose: print complex numbers nicely in Fortran.
# collect the purely real and purely imaginary parts:
pure_real = []
pure_imaginary = []
mixed = []
for arg in expr.args:
if arg.is_number and arg.is_real:
pure_real.append(arg)
elif arg.is_number and arg.is_imaginary:
pure_imaginary.append(arg)
else:
mixed.append(arg)
if pure_imaginary:
if mixed:
PREC = precedence(expr)
term = Add(*mixed)
t = self._print(term)
if t.startswith('-'):
sign = "-"
t = t[1:]
else:
sign = "+"
if precedence(term) < PREC:
t = "(%s)" % t
return "cmplx(%s,%s) %s %s" % (
self._print(Add(*pure_real)),
self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
sign, t,
)
else:
return "cmplx(%s,%s)" % (
self._print(Add(*pure_real)),
self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
)
else:
return CodePrinter._print_Add(self, expr)
def _print_Function(self, expr):
# All constant function args are evaluated as floats
prec = self._settings['precision']
args = [N(a, prec) for a in expr.args]
eval_expr = expr.func(*args)
if not isinstance(eval_expr, Function):
return self._print(eval_expr)
else:
return CodePrinter._print_Function(self, expr.func(*args))
def _print_Mod(self, expr):
# NOTE : Fortran has the functions mod() and modulo(). modulo() behaves
# the same wrt to the sign of the arguments as Python and SymPy's
# modulus computations (% and Mod()) but is not available in Fortran 66
# or Fortran 77, thus we raise an error.
if self._settings['standard'] in [66, 77]:
msg = ("Python % operator and SymPy's Mod() function are not "
"supported by Fortran 66 or 77 standards.")
raise NotImplementedError(msg)
else:
x, y = expr.args
return " modulo({}, {})".format(self._print(x), self._print(y))
def _print_ImaginaryUnit(self, expr):
# purpose: print complex numbers nicely in Fortran.
return "cmplx(0,1)"
def _print_int(self, expr):
return str(expr)
def _print_Mul(self, expr):
# purpose: print complex numbers nicely in Fortran.
if expr.is_number and expr.is_imaginary:
return "cmplx(0,%s)" % (
self._print(-S.ImaginaryUnit*expr)
)
else:
return CodePrinter._print_Mul(self, expr)
def _print_Pow(self, expr):
PREC = precedence(expr)
if expr.exp == -1:
return '%s/%s' % (
self._print(literal_dp(1)),
self.parenthesize(expr.base, PREC)
)
elif expr.exp == 0.5:
if expr.base.is_integer:
# Fortran intrinsic sqrt() does not accept integer argument
if expr.base.is_Number:
return 'sqrt(%s.0d0)' % self._print(expr.base)
else:
return 'sqrt(dble(%s))' % self._print(expr.base)
else:
return 'sqrt(%s)' % self._print(expr.base)
else:
return CodePrinter._print_Pow(self, expr)
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return "%d.0d0/%d.0d0" % (p, q)
def _print_Float(self, expr):
printed = CodePrinter._print_Float(self, expr)
e = printed.find('e')
if e > -1:
return "%sd%s" % (printed[:e], printed[e + 1:])
return "%sd0" % printed
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
op = op if op not in self._relationals else self._relationals[op]
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_AugmentedAssignment(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
return self._get_statement("{0} = {0} {1} {2}".format(
*map(lambda arg: self._print(arg),
[lhs_code, expr.binop, rhs_code])))
def _print_sum_(self, sm):
params = self._print(sm.array)
if sm.dim != None: # Must use '!= None', cannot use 'is not None'
params += ', ' + self._print(sm.dim)
if sm.mask != None: # Must use '!= None', cannot use 'is not None'
params += ', mask=' + self._print(sm.mask)
return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params)
def _print_product_(self, prod):
return self._print_sum_(prod)
def _print_Do(self, do):
excl = ['concurrent']
if do.step == 1:
excl.append('step')
step = ''
else:
step = ', {step}'
return (
'do {concurrent}{counter} = {first}, {last}'+step+'\n'
'{body}\n'
'end do\n'
).format(
concurrent='concurrent ' if do.concurrent else '',
**do.kwargs(apply=lambda arg: self._print(arg), exclude=excl)
)
def _print_ImpliedDoLoop(self, idl):
step = '' if idl.step == 1 else ', {step}'
return ('({expr}, {counter} = {first}, {last}'+step+')').format(
**idl.kwargs(apply=lambda arg: self._print(arg))
)
def _print_For(self, expr):
target = self._print(expr.target)
if isinstance(expr.iterable, Range):
start, stop, step = expr.iterable.args
else:
raise NotImplementedError("Only iterable currently supported is Range")
body = self._print(expr.body)
return ('do {target} = {start}, {stop}, {step}\n'
'{body}\n'
'end do').format(target=target, start=start, stop=stop,
step=step, body=body)
def _print_Type(self, type_):
type_ = self.type_aliases.get(type_, type_)
type_str = self.type_mappings.get(type_, type_.name)
module_uses = self.type_modules.get(type_)
if module_uses:
for k, v in module_uses:
self.module_uses[k].add(v)
return type_str
def _print_Element(self, elem):
return '{symbol}({idxs})'.format(
symbol=self._print(elem.symbol),
idxs=', '.join(map(lambda arg: self._print(arg), elem.indices))
)
def _print_Extent(self, ext):
return str(ext)
def _print_Declaration(self, expr):
var = expr.variable
val = var.value
dim = var.attr_params('dimension')
intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)]
if intents.count(True) == 0:
intent = ''
elif intents.count(True) == 1:
intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)]
else:
raise ValueError("Multiple intents specified for %s" % self)
if isinstance(var, Pointer):
raise NotImplementedError("Pointers are not available by default in Fortran.")
if self._settings["standard"] >= 90:
result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format(
t=self._print(var.type),
vc=', parameter' if value_const in var.attrs else '',
dim=', dimension(%s)' % ', '.join(map(lambda arg: self._print(arg), dim)) if dim else '',
intent=intent,
alloc=', allocatable' if allocatable in var.attrs else '',
s=self._print(var.symbol)
)
if val != None: # Must be "!= None", cannot be "is not None"
result += ' = %s' % self._print(val)
else:
if value_const in var.attrs or val:
raise NotImplementedError("F77 init./parameter statem. req. multiple lines.")
result = ' '.join(map(lambda arg: self._print(arg), [var.type, var.symbol]))
return result
def _print_Infinity(self, expr):
return '(huge(%s) + 1)' % self._print(literal_dp(0))
def _print_While(self, expr):
return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs(
apply=lambda arg: self._print(arg)))
def _print_BooleanTrue(self, expr):
return '.true.'
def _print_BooleanFalse(self, expr):
return '.false.'
def _pad_leading_columns(self, lines):
result = []
for line in lines:
if line.startswith('!'):
result.append(self._lead['comment'] + line[1:].lstrip())
else:
result.append(self._lead['code'] + line)
return result
def _wrap_fortran(self, lines):
"""Wrap long Fortran lines
Argument:
lines -- a list of lines (without \\n character)
A comment line is split at white space. Code lines are split with a more
complex rule to give nice results.
"""
# routine to find split point in a code line
my_alnum = set("_+-." + string.digits + string.ascii_letters)
my_white = set(" \t()")
def split_pos_code(line, endpos):
if len(line) <= endpos:
return len(line)
pos = endpos
split = lambda pos: \
(line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \
(line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \
(line[pos] in my_white and line[pos - 1] not in my_white) or \
(line[pos] not in my_white and line[pos - 1] in my_white)
while not split(pos):
pos -= 1
if pos == 0:
return endpos
return pos
# split line by line and add the split lines to result
result = []
if self._settings['source_format'] == 'free':
trailing = ' &'
else:
trailing = ''
for line in lines:
if line.startswith(self._lead['comment']):
# comment line
if len(line) > 72:
pos = line.rfind(" ", 6, 72)
if pos == -1:
pos = 72
hunk = line[:pos]
line = line[pos:].lstrip()
result.append(hunk)
while line:
pos = line.rfind(" ", 0, 66)
if pos == -1 or len(line) < 66:
pos = 66
hunk = line[:pos]
line = line[pos:].lstrip()
result.append("%s%s" % (self._lead['comment'], hunk))
else:
result.append(line)
elif line.startswith(self._lead['code']):
# code line
pos = split_pos_code(line, 72)
hunk = line[:pos].rstrip()
line = line[pos:].lstrip()
if line:
hunk += trailing
result.append(hunk)
while line:
pos = split_pos_code(line, 65)
hunk = line[:pos].rstrip()
line = line[pos:].lstrip()
if line:
hunk += trailing
result.append("%s%s" % (self._lead['cont'], hunk))
else:
result.append(line)
return result
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
free = self._settings['source_format'] == 'free'
code = [ line.lstrip(' \t') for line in code ]
inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface')
dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface')
increase = [ int(any(map(line.startswith, inc_keyword)))
for line in code ]
decrease = [ int(any(map(line.startswith, dec_keyword)))
for line in code ]
continuation = [ int(any(map(line.endswith, ['&', '&\n'])))
for line in code ]
level = 0
cont_padding = 0
tabwidth = 3
new_code = []
for i, line in enumerate(code):
if line == '' or line == '\n':
new_code.append(line)
continue
level -= decrease[i]
if free:
padding = " "*(level*tabwidth + cont_padding)
else:
padding = " "*level*tabwidth
line = "%s%s" % (padding, line)
if not free:
line = self._pad_leading_columns([line])[0]
new_code.append(line)
if continuation[i]:
cont_padding = 2*tabwidth
else:
cont_padding = 0
level += increase[i]
if not free:
return self._wrap_fortran(new_code)
return new_code
def _print_GoTo(self, goto):
if goto.expr: # computed goto
return "go to ({labels}), {expr}".format(
labels=', '.join(map(lambda arg: self._print(arg), goto.labels)),
expr=self._print(goto.expr)
)
else:
lbl, = goto.labels
return "go to %s" % self._print(lbl)
def _print_Program(self, prog):
return (
"program {name}\n"
"{body}\n"
"end program\n"
).format(**prog.kwargs(apply=lambda arg: self._print(arg)))
def _print_Module(self, mod):
return (
"module {name}\n"
"{declarations}\n"
"\ncontains\n\n"
"{definitions}\n"
"end module\n"
).format(**mod.kwargs(apply=lambda arg: self._print(arg)))
def _print_Stream(self, strm):
if strm.name == 'stdout' and self._settings["standard"] >= 2003:
self.module_uses['iso_c_binding'].add('stdint=>input_unit')
return 'input_unit'
elif strm.name == 'stderr' and self._settings["standard"] >= 2003:
self.module_uses['iso_c_binding'].add('stdint=>error_unit')
return 'error_unit'
else:
if strm.name == 'stdout':
return '*'
else:
return strm.name
def _print_Print(self, ps):
if ps.format_string != None: # Must be '!= None', cannot be 'is not None'
fmt = self._print(ps.format_string)
else:
fmt = "*"
return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join(
map(lambda arg: self._print(arg), ps.print_args)))
def _print_Return(self, rs):
arg, = rs.args
return "{result_name} = {arg}".format(
result_name=self._context.get('result_name', 'sympy_result'),
arg=self._print(arg)
)
def _print_FortranReturn(self, frs):
arg, = frs.args
if arg:
return 'return %s' % self._print(arg)
else:
return 'return'
def _head(self, entity, fp, **kwargs):
bind_C_params = fp.attr_params('bind_C')
if bind_C_params is None:
bind = ''
else:
bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)'
result_name = self._settings.get('result_name', None)
return (
"{entity}{name}({arg_names}){result}{bind}\n"
"{arg_declarations}"
).format(
entity=entity,
name=self._print(fp.name),
arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]),
result=(' result(%s)' % result_name) if result_name else '',
bind=bind,
arg_declarations='\n'.join(map(lambda arg: self._print(Declaration(arg)), fp.parameters))
)
def _print_FunctionPrototype(self, fp):
entity = "{0} function ".format(self._print(fp.return_type))
return (
"interface\n"
"{function_head}\n"
"end function\n"
"end interface"
).format(function_head=self._head(entity, fp))
def _print_FunctionDefinition(self, fd):
if elemental in fd.attrs:
prefix = 'elemental '
elif pure in fd.attrs:
prefix = 'pure '
else:
prefix = ''
entity = "{0} function ".format(self._print(fd.return_type))
with printer_context(self, result_name=fd.name):
return (
"{prefix}{function_head}\n"
"{body}\n"
"end function\n"
).format(
prefix=prefix,
function_head=self._head(entity, fd),
body=self._print(fd.body)
)
def _print_Subroutine(self, sub):
return (
'{subroutine_head}\n'
'{body}\n'
'end subroutine\n'
).format(
subroutine_head=self._head('subroutine ', sub),
body=self._print(sub.body)
)
def _print_SubroutineCall(self, scall):
return 'call {name}({args})'.format(
name=self._print(scall.name),
args=', '.join(map(lambda arg: self._print(arg), scall.subroutine_args))
)
def _print_use_rename(self, rnm):
return "%s => %s" % tuple(map(lambda arg: self._print(arg), rnm.args))
def _print_use(self, use):
result = 'use %s' % self._print(use.namespace)
if use.rename != None: # Must be '!= None', cannot be 'is not None'
result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename])
if use.only != None: # Must be '!= None', cannot be 'is not None'
result += ', only: ' + ', '.join([self._print(nly) for nly in use.only])
return result
def _print_BreakToken(self, _):
return 'exit'
def _print_ContinueToken(self, _):
return 'cycle'
def _print_ArrayConstructor(self, ac):
fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)'
return fmtstr % ', '.join(map(lambda arg: self._print(arg), ac.elements))
|
2027de104d67865a78a0c365637f5dd36e11b43789b3b83b34b2cacc8390b552 | """
R code printer
The RCodePrinter converts single sympy expressions into single R expressions,
using the functions defined in math.h where possible.
"""
from __future__ import print_function, division
from typing import Any, Dict
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
from sympy.sets.fancysets import Range
# dictionary mapping sympy function to (argument_conditions, C_function).
# Used in RCodePrinter._print_Function(self)
known_functions = {
#"Abs": [(lambda x: not x.is_integer, "fabs")],
"Abs": "abs",
"sin": "sin",
"cos": "cos",
"tan": "tan",
"asin": "asin",
"acos": "acos",
"atan": "atan",
"atan2": "atan2",
"exp": "exp",
"log": "log",
"erf": "erf",
"sinh": "sinh",
"cosh": "cosh",
"tanh": "tanh",
"asinh": "asinh",
"acosh": "acosh",
"atanh": "atanh",
"floor": "floor",
"ceiling": "ceiling",
"sign": "sign",
"Max": "max",
"Min": "min",
"factorial": "factorial",
"gamma": "gamma",
"digamma": "digamma",
"trigamma": "trigamma",
"beta": "beta",
}
# These are the core reserved words in the R language. Taken from:
# https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words
reserved_words = ['if',
'else',
'repeat',
'while',
'function',
'for',
'in',
'next',
'break',
'TRUE',
'FALSE',
'NULL',
'Inf',
'NaN',
'NA',
'NA_integer_',
'NA_real_',
'NA_complex_',
'NA_character_',
'volatile']
class RCodePrinter(CodePrinter):
"""A printer to convert python expressions to strings of R code"""
printmethod = "_rcode"
language = "R"
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 15,
'user_functions': {},
'human': True,
'contract': True,
'dereference': set(),
'error_on_reserved': False,
'reserved_word_suffix': '_',
} # type: Dict[str, Any]
_operators = {
'and': '&',
'or': '|',
'not': '!',
}
_relationals = {
} # type: Dict[str, str]
def __init__(self, settings={}):
CodePrinter.__init__(self, settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
self._dereference = set(settings.get('dereference', []))
self.reserved_words = set(reserved_words)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "// {0}".format(text)
def _declare_number_const(self, name, value):
return "{0} = {1};".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for i in range(rows) for j in range(cols))
def _get_loop_opening_ending(self, indices):
"""Returns a tuple (open_lines, close_lines) containing lists of codelines
"""
open_lines = []
close_lines = []
loopstart = "for (%(var)s in %(start)s:%(end)s){"
for i in indices:
# R arrays start at 1 and end at dimension
open_lines.append(loopstart % {
'var': self._print(i.label),
'start': self._print(i.lower+1),
'end': self._print(i.upper + 1)})
close_lines.append("}")
return open_lines, close_lines
def _print_Pow(self, expr):
if "Pow" in self.known_functions:
return self._print_Function(expr)
PREC = precedence(expr)
if expr.exp == -1:
return '1.0/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp == 0.5:
return 'sqrt(%s)' % self._print(expr.base)
else:
return '%s^%s' % (self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC))
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return '%d.0/%d.0' % (p, q)
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Exp1(self, expr):
return "exp(1)"
def _print_Pi(self, expr):
return 'pi'
def _print_Infinity(self, expr):
return 'Inf'
def _print_NegativeInfinity(self, expr):
return '-Inf'
def _print_Assignment(self, expr):
from sympy.codegen.ast import Assignment
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.indexed import IndexedBase
lhs = expr.lhs
rhs = expr.rhs
# We special case assignments that take multiple lines
#if isinstance(expr.rhs, Piecewise):
# from sympy.functions.elementary.piecewise import Piecewise
# # Here we modify Piecewise so each expression is now
# # an Assignment, and then continue on the print.
# expressions = []
# conditions = []
# for (e, c) in rhs.args:
# expressions.append(Assignment(lhs, e))
# conditions.append(c)
# temp = Piecewise(*zip(expressions, conditions))
# return self._print(temp)
#elif isinstance(lhs, MatrixSymbol):
if isinstance(lhs, MatrixSymbol):
# Here we form an Assignment for each element in the array,
# printing each one.
lines = []
for (i, j) in self._traverse_matrix_indices(lhs):
temp = Assignment(lhs[i, j], rhs[i, j])
code0 = self._print(temp)
lines.append(code0)
return "\n".join(lines)
elif self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_Piecewise(self, expr):
# This method is called only for inline if constructs
# Top level piecewise is handled in doprint()
if expr.args[-1].cond == True:
last_line = "%s" % self._print(expr.args[-1].expr)
else:
last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr))
code=last_line
for e, c in reversed(expr.args[:-1]):
code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")"
return(code)
def _print_ITE(self, expr):
from sympy.functions import Piecewise
_piecewise = Piecewise((expr.args[1], expr.args[0]), (expr.args[2], True))
return self._print(_piecewise)
def _print_MatrixElement(self, expr):
return "{0}[{1}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
strict=True), expr.j + expr.i*expr.parent.shape[1])
def _print_Symbol(self, expr):
name = super(RCodePrinter, self)._print_Symbol(expr)
if expr in self._dereference:
return '(*{0})'.format(name)
else:
return name
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_sinc(self, expr):
from sympy.functions.elementary.trigonometric import sin
from sympy.core.relational import Ne
from sympy.functions import Piecewise
_piecewise = Piecewise(
(sin(expr.args[0]) / expr.args[0], Ne(expr.args[0], 0)), (1, True))
return self._print(_piecewise)
def _print_AugmentedAssignment(self, expr):
lhs_code = self._print(expr.lhs)
op = expr.op
rhs_code = self._print(expr.rhs)
return "{0} {1} {2};".format(lhs_code, op, rhs_code)
def _print_For(self, expr):
target = self._print(expr.target)
if isinstance(expr.iterable, Range):
start, stop, step = expr.iterable.args
else:
raise NotImplementedError("Only iterable currently supported is Range")
body = self._print(expr.body)
return ('for ({target} = {start}; {target} < {stop}; {target} += '
'{step}) {{\n{body}\n}}').format(target=target, start=start,
stop=stop, step=step, body=body)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
decrease = [ int(any(map(line.startswith, dec_token)))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def rcode(expr, assign_to=None, **settings):
"""Converts an expr to a string of r code
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=15].
user_functions : dict, optional
A dictionary where the keys are string representations of either
``FunctionClass`` or ``UndefinedFunction`` instances and the values
are their desired R string representations. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
rfunction_string)] or [(argument_test, rfunction_formater)]. See below
for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
Examples
========
>>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> rcode((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau^(7.0/2.0)'
>>> rcode(sin(x), assign_to="s")
's = sin(x);'
Simple custom printing can be defined for certain types by passing a
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
Alternatively, the dictionary value can be a list of tuples i.e.
[(argument_test, cfunction_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "Abs": [(lambda x: not x.is_integer, "fabs"),
... (lambda x: x.is_integer, "ABS")],
... "func": "f"
... }
>>> func = Function('func')
>>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
'f(fabs(x) + CEIL(x))'
or if the R-function takes a subset of the original arguments:
>>> rcode(2**x + 3**x, user_functions={'Pow': [
... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
... (lambda b, e: b != 2, 'pow')]})
'exp2(x) + pow(3, x)'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(rcode(expr, assign_to=tau))
tau = ifelse(x > 0,x + 1,x);
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> rcode(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(rcode(mat, A))
A[0] = x^2;
A[1] = ifelse(x > 0,x + 1,x);
A[2] = sin(x);
"""
return RCodePrinter(settings).doprint(expr, assign_to)
def print_rcode(expr, **settings):
"""Prints R representation of the given expression."""
print(rcode(expr, **settings))
|
39527a752ee2242ea4b2e47bf125cdd3f17a8b54705d4dad63d924f78baa927b | """
Octave (and Matlab) code printer
The `OctaveCodePrinter` converts SymPy expressions into Octave expressions.
It uses a subset of the Octave language for Matlab compatibility.
A complete code generator, which uses `octave_code` extensively, can be found
in `sympy.utilities.codegen`. The `codegen` module can be used to generate
complete source code files.
"""
from __future__ import print_function, division
from typing import Any, Dict
from sympy.core import Mul, Pow, S, Rational
from sympy.core.mul import _keep_coeff
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
from re import search
# List of known functions. First, those that have the same name in
# SymPy and Octave. This is almost certainly incomplete!
known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
"asin", "acos", "acot", "atan", "atan2", "asec", "acsc",
"sinh", "cosh", "tanh", "coth", "csch", "sech",
"asinh", "acosh", "atanh", "acoth", "asech", "acsch",
"erfc", "erfi", "erf", "erfinv", "erfcinv",
"besseli", "besselj", "besselk", "bessely",
"bernoulli", "beta", "euler", "exp", "factorial", "floor",
"fresnelc", "fresnels", "gamma", "harmonic", "log",
"polylog", "sign", "zeta", "legendre"]
# These functions have different names ("Sympy": "Octave"), more
# generally a mapping to (argument_conditions, octave_function).
known_fcns_src2 = {
"Abs": "abs",
"arg": "angle", # arg/angle ok in Octave but only angle in Matlab
"binomial": "bincoeff",
"ceiling": "ceil",
"chebyshevu": "chebyshevU",
"chebyshevt": "chebyshevT",
"Chi": "coshint",
"Ci": "cosint",
"conjugate": "conj",
"DiracDelta": "dirac",
"Heaviside": "heaviside",
"im": "imag",
"laguerre": "laguerreL",
"LambertW": "lambertw",
"li": "logint",
"loggamma": "gammaln",
"Max": "max",
"Min": "min",
"Mod": "mod",
"polygamma": "psi",
"re": "real",
"RisingFactorial": "pochhammer",
"Shi": "sinhint",
"Si": "sinint",
}
class OctaveCodePrinter(CodePrinter):
"""
A printer to convert expressions to strings of Octave/Matlab code.
"""
printmethod = "_octave"
language = "Octave"
_operators = {
'and': '&',
'or': '|',
'not': '~',
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'contract': True,
'inline': True,
} # type: Dict[str, Any]
# Note: contract is for expressing tensors as loops (if True), or just
# assignment (if False). FIXME: this should be looked a more carefully
# for Octave.
def __init__(self, settings={}):
super(OctaveCodePrinter, self).__init__(settings)
self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
self.known_functions.update(dict(known_fcns_src2))
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "% {0}".format(text)
def _declare_number_const(self, name, value):
return "{0} = {1};".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
# Octave uses Fortran order (column-major)
rows, cols = mat.shape
return ((i, j) for j in range(cols) for i in range(rows))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
for i in indices:
# Octave arrays start at 1 and end at dimension
var, start, stop = map(self._print,
[i.label, i.lower + 1, i.upper + 1])
open_lines.append("for %s = %s:%s" % (var, start, stop))
close_lines.append("end")
return open_lines, close_lines
def _print_Mul(self, expr):
# print complex numbers nicely in Octave
if (expr.is_number and expr.is_imaginary and
(S.ImaginaryUnit*expr).is_Integer):
return "%si" % self._print(-S.ImaginaryUnit*expr)
# cribbed from str.py
prec = precedence(expr)
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
# Gather args for numerator/denominator
for item in args:
if (item.is_commutative and item.is_Pow and item.exp.is_Rational
and item.exp.is_negative):
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
pow_paren.append(item)
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append(Rational(item.p))
if item.q != 1:
b.append(Rational(item.q))
else:
a.append(item)
a = a or [S.One]
a_str = [self.parenthesize(x, prec) for x in a]
b_str = [self.parenthesize(x, prec) for x in b]
# To parenthesize Pow with exp = -1 and having more than one Symbol
for item in pow_paren:
if item.base in b:
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
# from here it differs from str.py to deal with "*" and ".*"
def multjoin(a, a_str):
# here we probably are assuming the constants will come first
r = a_str[0]
for i in range(1, len(a)):
mulsym = '*' if a[i-1].is_number else '.*'
r = r + mulsym + a_str[i]
return r
if not b:
return sign + multjoin(a, a_str)
elif len(b) == 1:
divsym = '/' if b[0].is_number else './'
return sign + multjoin(a, a_str) + divsym + b_str[0]
else:
divsym = '/' if all([bi.is_number for bi in b]) else './'
return (sign + multjoin(a, a_str) +
divsym + "(%s)" % multjoin(b, b_str))
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_Pow(self, expr):
powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^'
PREC = precedence(expr)
if expr.exp == S.Half:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if expr.exp == -S.Half:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "sqrt(%s)" % self._print(expr.base)
if expr.exp == -S.One:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
self.parenthesize(expr.exp, PREC))
def _print_MatPow(self, expr):
PREC = precedence(expr)
return '%s^%s' % (self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC))
def _print_MatrixSolve(self, expr):
PREC = precedence(expr)
return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC),
self.parenthesize(expr.vector, PREC))
def _print_Pi(self, expr):
return 'pi'
def _print_ImaginaryUnit(self, expr):
return "1i"
def _print_Exp1(self, expr):
return "exp(1)"
def _print_GoldenRatio(self, expr):
# FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
#return self._print((1+sqrt(S(5)))/2)
return "(1+sqrt(5))/2"
def _print_Assignment(self, expr):
from sympy.codegen.ast import Assignment
from sympy.functions.elementary.piecewise import Piecewise
from sympy.tensor.indexed import IndexedBase
# Copied from codeprinter, but remove special MatrixSymbol treatment
lhs = expr.lhs
rhs = expr.rhs
# We special case assignments that take multiple lines
if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
# Here we modify Piecewise so each expression is now
# an Assignment, and then continue on the print.
expressions = []
conditions = []
for (e, c) in rhs.args:
expressions.append(Assignment(lhs, e))
conditions.append(c)
temp = Piecewise(*zip(expressions, conditions))
return self._print(temp)
if self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_Infinity(self, expr):
return 'inf'
def _print_NegativeInfinity(self, expr):
return '-inf'
def _print_NaN(self, expr):
return 'NaN'
def _print_list(self, expr):
return '{' + ', '.join(self._print(a) for a in expr) + '}'
_print_tuple = _print_list
_print_Tuple = _print_list
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_bool(self, expr):
return str(expr).lower()
# Could generate quadrature code for definite Integrals?
#_print_Integral = _print_not_supported
def _print_MatrixBase(self, A):
# Handle zero dimensions:
if (A.rows, A.cols) == (0, 0):
return '[]'
elif A.rows == 0 or A.cols == 0:
return 'zeros(%s, %s)' % (A.rows, A.cols)
elif (A.rows, A.cols) == (1, 1):
# Octave does not distinguish between scalars and 1x1 matrices
return self._print(A[0, 0])
return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]])
for r in range(A.rows))
def _print_SparseMatrix(self, A):
from sympy.matrices import Matrix
L = A.col_list();
# make row vectors of the indices and entries
I = Matrix([[k[0] + 1 for k in L]])
J = Matrix([[k[1] + 1 for k in L]])
AIJ = Matrix([[k[2] for k in L]])
return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
self._print(AIJ), A.rows, A.cols)
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
+ '(%s, %s)' % (expr.i + 1, expr.j + 1)
def _print_MatrixSlice(self, expr):
def strslice(x, lim):
l = x[0] + 1
h = x[1]
step = x[2]
lstr = self._print(l)
hstr = 'end' if h == lim else self._print(h)
if step == 1:
if l == 1 and h == lim:
return ':'
if l == h:
return lstr
else:
return lstr + ':' + hstr
else:
return ':'.join((lstr, self._print(step), hstr))
return (self._print(expr.parent) + '(' +
strslice(expr.rowslice, expr.parent.shape[0]) + ', ' +
strslice(expr.colslice, expr.parent.shape[1]) + ')')
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_KroneckerDelta(self, expr):
prec = PRECEDENCE["Pow"]
return "double(%s == %s)" % tuple(self.parenthesize(x, prec)
for x in expr.args)
def _print_HadamardProduct(self, expr):
return '.*'.join([self.parenthesize(arg, precedence(expr))
for arg in expr.args])
def _print_HadamardPower(self, expr):
PREC = precedence(expr)
return '.**'.join([
self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC)
])
def _print_Identity(self, expr):
shape = expr.shape
if len(shape) == 2 and shape[0] == shape[1]:
shape = [shape[0]]
s = ", ".join(self._print(n) for n in shape)
return "eye(" + s + ")"
def _print_lowergamma(self, expr):
# Octave implements regularized incomplete gamma function
return "(gammainc({1}, {0}).*gamma({0}))".format(
self._print(expr.args[0]), self._print(expr.args[1]))
def _print_uppergamma(self, expr):
return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format(
self._print(expr.args[0]), self._print(expr.args[1]))
def _print_sinc(self, expr):
#Note: Divide by pi because Octave implements normalized sinc function.
return "sinc(%s)" % self._print(expr.args[0]/S.Pi)
def _print_hankel1(self, expr):
return "besselh(%s, 1, %s)" % (self._print(expr.order),
self._print(expr.argument))
def _print_hankel2(self, expr):
return "besselh(%s, 2, %s)" % (self._print(expr.order),
self._print(expr.argument))
# Note: as of 2015, Octave doesn't have spherical Bessel functions
def _print_jn(self, expr):
from sympy.functions import sqrt, besselj
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
return self._print(expr2)
def _print_yn(self, expr):
from sympy.functions import sqrt, bessely
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
return self._print(expr2)
def _print_airyai(self, expr):
return "airy(0, %s)" % self._print(expr.args[0])
def _print_airyaiprime(self, expr):
return "airy(1, %s)" % self._print(expr.args[0])
def _print_airybi(self, expr):
return "airy(2, %s)" % self._print(expr.args[0])
def _print_airybiprime(self, expr):
return "airy(3, %s)" % self._print(expr.args[0])
def _print_expint(self, expr):
mu, x = expr.args
if mu != 1:
return self._print_not_supported(expr)
return "expint(%s)" % self._print(x)
def _one_or_two_reversed_args(self, expr):
assert len(expr.args) <= 2
return '{name}({args})'.format(
name=self.known_functions[expr.__class__.__name__],
args=", ".join([self._print(x) for x in reversed(expr.args)])
)
_print_DiracDelta = _print_LambertW = _one_or_two_reversed_args
def _nested_binary_math_func(self, expr):
return '{name}({arg1}, {arg2})'.format(
name=self.known_functions[expr.__class__.__name__],
arg1=self._print(expr.args[0]),
arg2=self._print(expr.func(*expr.args[1:]))
)
_print_Max = _print_Min = _nested_binary_math_func
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if self._settings["inline"]:
# Express each (cond, expr) pair in a nested Horner form:
# (condition) .* (expr) + (not cond) .* (<others>)
# Expressions that result in multiple statements won't work here.
ecpairs = ["({0}).*({1}) + (~({0})).*(".format
(self._print(c), self._print(e))
for e, c in expr.args[:-1]]
elast = "%s" % self._print(expr.args[-1].expr)
pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs)
# Note: current need these outer brackets for 2*pw. Would be
# nicer to teach parenthesize() to do this for us when needed!
return "(" + pw + ")"
else:
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s)" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else")
else:
lines.append("elseif (%s)" % self._print(c))
code0 = self._print(e)
lines.append(code0)
if i == len(expr.args) - 1:
lines.append("end")
return "\n".join(lines)
def _print_zeta(self, expr):
if len(expr.args) == 1:
return "zeta(%s)" % self._print(expr.args[0])
else:
# Matlab two argument zeta is not equivalent to SymPy's
return self._print_not_supported(expr)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
# code mostly copied from ccode
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
dec_regex = ('^end$', '^elseif ', '^else$')
# pre-strip left-space from the code
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any([search(re, line) for re in inc_regex]))
for line in code ]
decrease = [ int(any([search(re, line) for re in dec_regex]))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def octave_code(expr, assign_to=None, **settings):
r"""Converts `expr` to a string of Octave (or Matlab) code.
The string uses a subset of the Octave language for Matlab compatibility.
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=16].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
inline: bool, optional
If True, we try to create single-statement code instead of multiple
statements. [default=True].
Examples
========
>>> from sympy import octave_code, symbols, sin, pi
>>> x = symbols('x')
>>> octave_code(sin(x).series(x).removeO())
'x.^5/120 - x.^3/6 + x'
>>> from sympy import Rational, ceiling
>>> x, y, tau = symbols("x, y, tau")
>>> octave_code((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau.^(7/2)'
Note that element-wise (Hadamard) operations are used by default between
symbols. This is because its very common in Octave to write "vectorized"
code. It is harmless if the values are scalars.
>>> octave_code(sin(pi*x*y), assign_to="s")
's = sin(pi*x.*y);'
If you need a matrix product "*" or matrix power "^", you can specify the
symbol as a ``MatrixSymbol``.
>>> from sympy import Symbol, MatrixSymbol
>>> n = Symbol('n', integer=True, positive=True)
>>> A = MatrixSymbol('A', n, n)
>>> octave_code(3*pi*A**3)
'(3*pi)*A^3'
This class uses several rules to decide which symbol to use a product.
Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
A HadamardProduct can be used to specify componentwise multiplication ".*"
of two MatrixSymbols. There is currently there is no easy way to specify
scalar symbols, so sometimes the code might have some minor cosmetic
issues. For example, suppose x and y are scalars and A is a Matrix, then
while a human programmer might write "(x^2*y)*A^3", we generate:
>>> octave_code(x**2*y*A**3)
'(x.^2.*y)*A^3'
Matrices are supported using Octave inline notation. When using
``assign_to`` with matrices, the name can be specified either as a string
or as a ``MatrixSymbol``. The dimensions must align in the latter case.
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.^2 sin(x) ceil(x)];'
``Piecewise`` expressions are implemented with logical masking by default.
Alternatively, you can pass "inline=False" to use if-else conditionals.
Note that if the ``Piecewise`` lacks a default term, represented by
``(expr, True)`` then an error will be thrown. This is to prevent
generating an expression that may not evaluate to anything.
>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> octave_code(pw, assign_to=tau)
'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'
Note that any expression that can be generated normally can also exist
inside a Matrix:
>>> mat = Matrix([[x**2, pw, sin(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'
Custom printing can be defined for certain types by passing a dictionary of
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
dictionary value can be a list of tuples i.e., [(argument_test,
cfunction_string)]. This can be used to call a custom Octave function.
>>> from sympy import Function
>>> f = Function('f')
>>> g = Function('g')
>>> custom_functions = {
... "f": "existing_octave_fcn",
... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
... (lambda x: not x.is_Matrix, "my_fcn")]
... }
>>> mat = Matrix([[1, x]])
>>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> octave_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
"""
return OctaveCodePrinter(settings).doprint(expr, assign_to)
def print_octave_code(expr, **settings):
"""Prints the Octave (or Matlab) representation of the given expression.
See `octave_code` for the meaning of the optional arguments.
"""
print(octave_code(expr, **settings))
|
ceb2f98089b8b2e759004f7604cffac6f11db3e6f475da77a20068a04ec3f20b | from __future__ import print_function, division
from typing import Any, Dict, Set, Tuple
from functools import wraps
from sympy.core import Add, Expr, Mul, Pow, S, sympify, Float
from sympy.core.basic import Basic
from sympy.core.compatibility import default_sort_key
from sympy.core.function import Lambda
from sympy.core.mul import _keep_coeff
from sympy.core.symbol import Symbol
from sympy.printing.str import StrPrinter
from sympy.printing.precedence import precedence
class requires(object):
""" Decorator for registering requirements on print methods. """
def __init__(self, **kwargs):
self._req = kwargs
def __call__(self, method):
def _method_wrapper(self_, *args, **kwargs):
for k, v in self._req.items():
getattr(self_, k).update(v)
return method(self_, *args, **kwargs)
return wraps(method)(_method_wrapper)
class AssignmentError(Exception):
"""
Raised if an assignment variable for a loop is missing.
"""
pass
class CodePrinter(StrPrinter):
"""
The base class for code-printing subclasses.
"""
_operators = {
'and': '&&',
'or': '||',
'not': '!',
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'error_on_reserved': False,
'reserved_word_suffix': '_',
'human': True,
'inline': False,
'allow_unknown_functions': False,
} # type: Dict[str, Any]
# Functions which are "simple" to rewrite to other functions that
# may be supported
_rewriteable_functions = {
'erf2': 'erf',
'Li': 'li',
'beta': 'gamma'
}
def __init__(self, settings=None):
super(CodePrinter, self).__init__(settings=settings)
if not hasattr(self, 'reserved_words'):
self.reserved_words = set()
def doprint(self, expr, assign_to=None):
"""
Print the expression as code.
Parameters
----------
expr : Expression
The expression to be printed.
assign_to : Symbol, MatrixSymbol, or string (optional)
If provided, the printed code will set the expression to a
variable with name ``assign_to``.
"""
from sympy.codegen.ast import Assignment
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(assign_to, str):
if expr.is_Matrix:
assign_to = MatrixSymbol(assign_to, *expr.shape)
else:
assign_to = Symbol(assign_to)
elif not isinstance(assign_to, (Basic, type(None))):
raise TypeError("{0} cannot assign to object of type {1}".format(
type(self).__name__, type(assign_to)))
if assign_to:
expr = Assignment(assign_to, expr)
else:
# _sympify is not enough b/c it errors on iterables
expr = sympify(expr)
# keep a set of expressions that are not strictly translatable to Code
# and number constants that must be declared and initialized
self._not_supported = set()
self._number_symbols = set() # type: Set[Tuple[Expr, Float]]
lines = self._print(expr).splitlines()
# format the output
if self._settings["human"]:
frontlines = []
if self._not_supported:
frontlines.append(self._get_comment(
"Not supported in {0}:".format(self.language)))
for expr in sorted(self._not_supported, key=str):
frontlines.append(self._get_comment(type(expr).__name__))
for name, value in sorted(self._number_symbols, key=str):
frontlines.append(self._declare_number_const(name, value))
lines = frontlines + lines
lines = self._format_code(lines)
result = "\n".join(lines)
else:
lines = self._format_code(lines)
num_syms = set([(k, self._print(v)) for k, v in self._number_symbols])
result = (num_syms, self._not_supported, "\n".join(lines))
self._not_supported = set()
self._number_symbols = set()
return result
def _doprint_loops(self, expr, assign_to=None):
# Here we print an expression that contains Indexed objects, they
# correspond to arrays in the generated code. The low-level implementation
# involves looping over array elements and possibly storing results in temporary
# variables or accumulate it in the assign_to object.
if self._settings.get('contract', True):
from sympy.tensor import get_contraction_structure
# Setup loops over non-dummy indices -- all terms need these
indices = self._get_expression_indices(expr, assign_to)
# Setup loops over dummy indices -- each term needs separate treatment
dummies = get_contraction_structure(expr)
else:
indices = []
dummies = {None: (expr,)}
openloop, closeloop = self._get_loop_opening_ending(indices)
# terms with no summations first
if None in dummies:
text = StrPrinter.doprint(self, Add(*dummies[None]))
else:
# If all terms have summations we must initialize array to Zero
text = StrPrinter.doprint(self, 0)
# skip redundant assignments (where lhs == rhs)
lhs_printed = self._print(assign_to)
lines = []
if text != lhs_printed:
lines.extend(openloop)
if assign_to is not None:
text = self._get_statement("%s = %s" % (lhs_printed, text))
lines.append(text)
lines.extend(closeloop)
# then terms with summations
for d in dummies:
if isinstance(d, tuple):
indices = self._sort_optimized(d, expr)
openloop_d, closeloop_d = self._get_loop_opening_ending(
indices)
for term in dummies[d]:
if term in dummies and not ([list(f.keys()) for f in dummies[term]]
== [[None] for f in dummies[term]]):
# If one factor in the term has it's own internal
# contractions, those must be computed first.
# (temporary variables?)
raise NotImplementedError(
"FIXME: no support for contractions in factor yet")
else:
# We need the lhs expression as an accumulator for
# the loops, i.e
#
# for (int d=0; d < dim; d++){
# lhs[] = lhs[] + term[][d]
# } ^.................. the accumulator
#
# We check if the expression already contains the
# lhs, and raise an exception if it does, as that
# syntax is currently undefined. FIXME: What would be
# a good interpretation?
if assign_to is None:
raise AssignmentError(
"need assignment variable for loops")
if term.has(assign_to):
raise ValueError("FIXME: lhs present in rhs,\
this is undefined in CodePrinter")
lines.extend(openloop)
lines.extend(openloop_d)
text = "%s = %s" % (lhs_printed, StrPrinter.doprint(
self, assign_to + term))
lines.append(self._get_statement(text))
lines.extend(closeloop_d)
lines.extend(closeloop)
return "\n".join(lines)
def _get_expression_indices(self, expr, assign_to):
from sympy.tensor import get_indices
rinds, junk = get_indices(expr)
linds, junk = get_indices(assign_to)
# support broadcast of scalar
if linds and not rinds:
rinds = linds
if rinds != linds:
raise ValueError("lhs indices must match non-dummy"
" rhs indices in %s" % expr)
return self._sort_optimized(rinds, assign_to)
def _sort_optimized(self, indices, expr):
from sympy.tensor.indexed import Indexed
if not indices:
return []
# determine optimized loop order by giving a score to each index
# the index with the highest score are put in the innermost loop.
score_table = {}
for i in indices:
score_table[i] = 0
arrays = expr.atoms(Indexed)
for arr in arrays:
for p, ind in enumerate(arr.indices):
try:
score_table[ind] += self._rate_index_position(p)
except KeyError:
pass
return sorted(indices, key=lambda x: score_table[x])
def _rate_index_position(self, p):
"""function to calculate score based on position among indices
This method is used to sort loops in an optimized order, see
CodePrinter._sort_optimized()
"""
raise NotImplementedError("This function must be implemented by "
"subclass of CodePrinter.")
def _get_statement(self, codestring):
"""Formats a codestring with the proper line ending."""
raise NotImplementedError("This function must be implemented by "
"subclass of CodePrinter.")
def _get_comment(self, text):
"""Formats a text string as a comment."""
raise NotImplementedError("This function must be implemented by "
"subclass of CodePrinter.")
def _declare_number_const(self, name, value):
"""Declare a numeric constant at the top of a function"""
raise NotImplementedError("This function must be implemented by "
"subclass of CodePrinter.")
def _format_code(self, lines):
"""Take in a list of lines of code, and format them accordingly.
This may include indenting, wrapping long lines, etc..."""
raise NotImplementedError("This function must be implemented by "
"subclass of CodePrinter.")
def _get_loop_opening_ending(self, indices):
"""Returns a tuple (open_lines, close_lines) containing lists
of codelines"""
raise NotImplementedError("This function must be implemented by "
"subclass of CodePrinter.")
def _print_Dummy(self, expr):
if expr.name.startswith('Dummy_'):
return '_' + expr.name
else:
return '%s_%d' % (expr.name, expr.dummy_index)
def _print_CodeBlock(self, expr):
return '\n'.join([self._print(i) for i in expr.args])
def _print_String(self, string):
return str(string)
def _print_QuotedString(self, arg):
return '"%s"' % arg.text
def _print_Comment(self, string):
return self._get_comment(str(string))
def _print_Assignment(self, expr):
from sympy.codegen.ast import Assignment
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.indexed import IndexedBase
lhs = expr.lhs
rhs = expr.rhs
# We special case assignments that take multiple lines
if isinstance(expr.rhs, Piecewise):
# Here we modify Piecewise so each expression is now
# an Assignment, and then continue on the print.
expressions = []
conditions = []
for (e, c) in rhs.args:
expressions.append(Assignment(lhs, e))
conditions.append(c)
temp = Piecewise(*zip(expressions, conditions))
return self._print(temp)
elif isinstance(lhs, MatrixSymbol):
# Here we form an Assignment for each element in the array,
# printing each one.
lines = []
for (i, j) in self._traverse_matrix_indices(lhs):
temp = Assignment(lhs[i, j], rhs[i, j])
code0 = self._print(temp)
lines.append(code0)
return "\n".join(lines)
elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_AugmentedAssignment(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
return self._get_statement("{0} {1} {2}".format(
*map(lambda arg: self._print(arg),
[lhs_code, expr.op, rhs_code])))
def _print_FunctionCall(self, expr):
return '%s(%s)' % (
expr.name,
', '.join(map(lambda arg: self._print(arg),
expr.function_args)))
def _print_Variable(self, expr):
return self._print(expr.symbol)
def _print_Statement(self, expr):
arg, = expr.args
return self._get_statement(self._print(arg))
def _print_Symbol(self, expr):
name = super(CodePrinter, self)._print_Symbol(expr)
if name in self.reserved_words:
if self._settings['error_on_reserved']:
msg = ('This expression includes the symbol "{}" which is a '
'reserved keyword in this language.')
raise ValueError(msg.format(name))
return name + self._settings['reserved_word_suffix']
else:
return name
def _print_Function(self, expr):
if expr.func.__name__ in self.known_functions:
cond_func = self.known_functions[expr.func.__name__]
func = None
if isinstance(cond_func, str):
func = cond_func
else:
for cond, func in cond_func:
if cond(*expr.args):
break
if func is not None:
try:
return func(*[self.parenthesize(item, 0) for item in expr.args])
except TypeError:
return "%s(%s)" % (func, self.stringify(expr.args, ", "))
elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
# inlined function
return self._print(expr._imp_(*expr.args))
elif (expr.func.__name__ in self._rewriteable_functions and
self._rewriteable_functions[expr.func.__name__] in self.known_functions):
# Simple rewrite to supported function possible
return self._print(expr.rewrite(self._rewriteable_functions[expr.func.__name__]))
elif expr.is_Function and self._settings.get('allow_unknown_functions', False):
return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args)))
else:
return self._print_not_supported(expr)
_print_Expr = _print_Function
def _print_NumberSymbol(self, expr):
if self._settings.get("inline", False):
return self._print(Float(expr.evalf(self._settings["precision"])))
else:
# A Number symbol that is not implemented here or with _printmethod
# is registered and evaluated
self._number_symbols.add((expr,
Float(expr.evalf(self._settings["precision"]))))
return str(expr)
def _print_Catalan(self, expr):
return self._print_NumberSymbol(expr)
def _print_EulerGamma(self, expr):
return self._print_NumberSymbol(expr)
def _print_GoldenRatio(self, expr):
return self._print_NumberSymbol(expr)
def _print_TribonacciConstant(self, expr):
return self._print_NumberSymbol(expr)
def _print_Exp1(self, expr):
return self._print_NumberSymbol(expr)
def _print_Pi(self, expr):
return self._print_NumberSymbol(expr)
def _print_And(self, expr):
PREC = precedence(expr)
return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC)
for a in sorted(expr.args, key=default_sort_key))
def _print_Or(self, expr):
PREC = precedence(expr)
return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC)
for a in sorted(expr.args, key=default_sort_key))
def _print_Xor(self, expr):
if self._operators.get('xor') is None:
return self._print_not_supported(expr)
PREC = precedence(expr)
return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC)
for a in expr.args)
def _print_Equivalent(self, expr):
if self._operators.get('equivalent') is None:
return self._print_not_supported(expr)
PREC = precedence(expr)
return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC)
for a in expr.args)
def _print_Not(self, expr):
PREC = precedence(expr)
return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
def _print_Mul(self, expr):
prec = precedence(expr)
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
# Gather args for numerator/denominator
for item in args:
if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
pow_paren.append(item)
b.append(Pow(item.base, -item.exp))
else:
a.append(item)
a = a or [S.One]
a_str = [self.parenthesize(x, prec) for x in a]
b_str = [self.parenthesize(x, prec) for x in b]
# To parenthesize Pow with exp = -1 and having more than one Symbol
for item in pow_paren:
if item.base in b:
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
if not b:
return sign + '*'.join(a_str)
elif len(b) == 1:
return sign + '*'.join(a_str) + "/" + b_str[0]
else:
return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
def _print_not_supported(self, expr):
try:
self._not_supported.add(expr)
except TypeError:
# not hashable
pass
return self.emptyPrinter(expr)
# The following can not be simply translated into C or Fortran
_print_Basic = _print_not_supported
_print_ComplexInfinity = _print_not_supported
_print_Derivative = _print_not_supported
_print_ExprCondPair = _print_not_supported
_print_GeometryEntity = _print_not_supported
_print_Infinity = _print_not_supported
_print_Integral = _print_not_supported
_print_Interval = _print_not_supported
_print_AccumulationBounds = _print_not_supported
_print_Limit = _print_not_supported
_print_MatrixBase = _print_not_supported
_print_DeferredVector = _print_not_supported
_print_NaN = _print_not_supported
_print_NegativeInfinity = _print_not_supported
_print_Order = _print_not_supported
_print_RootOf = _print_not_supported
_print_RootsOf = _print_not_supported
_print_RootSum = _print_not_supported
_print_Uniform = _print_not_supported
_print_Unit = _print_not_supported
_print_Wild = _print_not_supported
_print_WildFunction = _print_not_supported
_print_Relational = _print_not_supported
# Code printer functions. These are included in this file so that they can be
# imported in the top-level __init__.py without importing the sympy.codegen
# module.
def ccode(expr, assign_to=None, standard='c99', **settings):
"""Converts an expr to a string of c code
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
standard : str, optional
String specifying the standard. If your compiler supports a more modern
standard you may set this to 'c99' to allow the printer to use more math
functions. [default='c89'].
precision : integer, optional
The precision for numbers such as pi [default=17].
user_functions : dict, optional
A dictionary where the keys are string representations of either
``FunctionClass`` or ``UndefinedFunction`` instances and the values
are their desired C string representations. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
cfunction_string)] or [(argument_test, cfunction_formater)]. See below
for examples.
dereference : iterable, optional
An iterable of symbols that should be dereferenced in the printed code
expression. These would be values passed by address to the function.
For example, if ``dereference=[a]``, the resulting code would print
``(*a)`` instead of ``a``.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
Examples
========
>>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> expr = (2*tau)**Rational(7, 2)
>>> ccode(expr)
'8*M_SQRT2*pow(tau, 7.0/2.0)'
>>> ccode(expr, math_macros={})
'8*sqrt(2)*pow(tau, 7.0/2.0)'
>>> ccode(sin(x), assign_to="s")
's = sin(x);'
>>> from sympy.codegen.ast import real, float80
>>> ccode(expr, type_aliases={real: float80})
'8*M_SQRT2l*powl(tau, 7.0L/2.0L)'
Simple custom printing can be defined for certain types by passing a
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
Alternatively, the dictionary value can be a list of tuples i.e.
[(argument_test, cfunction_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "Abs": [(lambda x: not x.is_integer, "fabs"),
... (lambda x: x.is_integer, "ABS")],
... "func": "f"
... }
>>> func = Function('func')
>>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions)
'f(fabs(x) + CEIL(x))'
or if the C-function takes a subset of the original arguments:
>>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [
... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
... (lambda b, e: b != 2, 'pow')]})
'exp2(x) + pow(3, x)'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(ccode(expr, tau, standard='C89'))
if (x > 0) {
tau = x + 1;
}
else {
tau = x;
}
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89')
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(ccode(mat, A, standard='C89'))
A[0] = pow(x, 2);
if (x > 0) {
A[1] = x + 1;
}
else {
A[1] = x;
}
A[2] = sin(x);
"""
from sympy.printing.c import c_code_printers
return c_code_printers[standard.lower()](settings).doprint(expr, assign_to)
def print_ccode(expr, **settings):
"""Prints C representation of the given expression."""
print(ccode(expr, **settings))
def fcode(expr, assign_to=None, **settings):
"""Converts an expr to a string of fortran code
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
precision : integer, optional
DEPRECATED. Use type_mappings instead. The precision for numbers such
as pi [default=17].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, cfunction_string)]. See below
for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
source_format : optional
The source format can be either 'fixed' or 'free'. [default='fixed']
standard : integer, optional
The Fortran standard to be followed. This is specified as an integer.
Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77.
Note that currently the only distinction internally is between
standards before 95, and those 95 and after. This may change later as
more features are added.
name_mangling : bool, optional
If True, then the variables that would become identical in
case-insensitive Fortran are mangled by appending different number
of ``_`` at the end. If False, SymPy won't interfere with naming of
variables. [default=True]
Examples
========
>>> from sympy import fcode, symbols, Rational, sin, ceiling, floor
>>> x, tau = symbols("x, tau")
>>> fcode((2*tau)**Rational(7, 2))
' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
>>> fcode(sin(x), assign_to="s")
' s = sin(x)'
Custom printing can be defined for certain types by passing a dictionary of
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
cfunction_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "floor": [(lambda x: not x.is_integer, "FLOOR1"),
... (lambda x: x.is_integer, "FLOOR2")]
... }
>>> fcode(floor(x) + ceiling(x), user_functions=custom_functions)
' CEIL(x) + FLOOR1(x)'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(fcode(expr, tau))
if (x > 0) then
tau = x + 1
else
tau = x
end if
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> fcode(e.rhs, assign_to=e.lhs, contract=False)
' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(fcode(mat, A))
A(1, 1) = x**2
if (x > 0) then
A(2, 1) = x + 1
else
A(2, 1) = x
end if
A(3, 1) = sin(x)
"""
from sympy.printing.fortran import FCodePrinter
return FCodePrinter(settings).doprint(expr, assign_to)
def print_fcode(expr, **settings):
"""Prints the Fortran representation of the given expression.
See fcode for the meaning of the optional arguments.
"""
print(fcode(expr, **settings))
def cxxcode(expr, assign_to=None, standard='c++11', **settings):
""" C++ equivalent of :func:`~.ccode`. """
from sympy.printing.cxx import cxx_code_printers
return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to)
|
84af4fcb21029aad9b496fe8558e6b49486afb0f388772fbedfeb5d396b88d2c | """
Maple code printer
The MapleCodePrinter converts single sympy expressions into single
Maple expressions, using the functions defined in the Maple objects where possible.
FIXME: This module is still under actively developed. Some functions may be not completed.
"""
from __future__ import print_function, division
from sympy.core import S
from sympy.core.numbers import Integer, IntegerConstant
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
import sympy
_known_func_same_name = [
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech',
'csch', 'coth', 'exp', 'floor', 'factorial'
]
known_functions = {
# Sympy -> Maple
'Abs': 'abs',
'log': 'ln',
'asin': 'arcsin',
'acos': 'arccos',
'atan': 'arctan',
'asec': 'arcsec',
'acsc': 'arccsc',
'acot': 'arccot',
'asinh': 'arcsinh',
'acosh': 'arccosh',
'atanh': 'arctanh',
'asech': 'arcsech',
'acsch': 'arccsch',
'acoth': 'arccoth',
'ceiling': 'ceil',
'besseli': 'BesselI',
'besselj': 'BesselJ',
'besselk': 'BesselK',
'bessely': 'BesselY',
'hankelh1': 'HankelH1',
'hankelh2': 'HankelH2',
'airyai': 'AiryAi',
'airybi': 'AiryBi'
}
for _func in _known_func_same_name:
known_functions[_func] = _func
number_symbols = {
# Sympy -> Maple
S.Pi: 'Pi',
S.Exp1: 'exp(1)',
S.Catalan: 'Catalan',
S.EulerGamma: 'gamma',
S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))'
}
spec_relational_ops = {
# Sympy -> Maple
'==': '=',
'!=': '<>'
}
not_supported_symbol = [
S.ComplexInfinity
]
class MapleCodePrinter(CodePrinter):
"""
Printer which converts a sympy expression into a maple code.
"""
printmethod = "_maple"
language = "maple"
_default_settings = {
'order': None,
'full_prec': 'auto',
'human': True,
'inline': True,
'allow_unknown_functions': True,
}
def __init__(self, settings=None):
if settings is None:
settings = dict()
super(MapleCodePrinter, self).__init__(settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "# {0}".format(text)
def _declare_number_const(self, name, value):
return "{0} := {1};".format(name,
value.evalf(self._settings['precision']))
def _format_code(self, lines):
return lines
def _print_tuple(self, expr):
return self._print(list(expr))
def _print_Tuple(self, expr):
return self._print(list(expr))
def _print_Assignment(self, expr):
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs)
def _print_Pow(self, expr, **kwargs):
PREC = precedence(expr)
if expr.exp == -1:
return '1/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp == 0.5 or expr.exp == S(1) / 2:
return 'sqrt(%s)' % self._print(expr.base)
elif expr.exp == -0.5 or expr.exp == -S(1) / 2:
return '1/sqrt(%s)' % self._print(expr.base)
else:
return '{base}^{exp}'.format(
base=self.parenthesize(expr.base, PREC),
exp=self.parenthesize(expr.exp, PREC))
def _print_Piecewise(self, expr):
if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue):
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
_coup_list = [
("{c}, {e}".format(c=self._print(c),
e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format(
e=self._print(e)))
for e, c in expr.args]
_inbrace = ', '.join(_coup_list)
return 'piecewise({_inbrace})'.format(_inbrace=_inbrace)
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return "{p}/{q}".format(p=str(p), q=str(q))
def _print_Relational(self, expr):
PREC=precedence(expr)
lhs_code = self.parenthesize(expr.lhs, PREC)
rhs_code = self.parenthesize(expr.rhs, PREC)
op = expr.rel_op
if op in spec_relational_ops:
op = spec_relational_ops[op]
return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code)
def _print_NumberSymbol(self, expr):
return number_symbols[expr]
def _print_NegativeInfinity(self, expr):
return '-infinity'
def _print_Infinity(self, expr):
return 'infinity'
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_bool(self, expr):
return 'true' if expr else 'false'
def _print_NaN(self, expr):
return 'undefined'
def _get_matrix(self, expr, sparse=False):
if expr.cols == 0 or expr.rows == 0:
_strM = 'Matrix([], storage = {storage})'.format(
storage='sparse' if sparse else 'rectangular')
else:
_strM = 'Matrix({list}, storage = {storage})'.format(
list=self._print(expr.tolist()),
storage='sparse' if sparse else 'rectangular')
return _strM
def _print_MatrixElement(self, expr):
return "{parent}[{i_maple}, {j_maple}]".format(
parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True),
i_maple=self._print(expr.i + 1),
j_maple=self._print(expr.j + 1))
def _print_MatrixBase(self, expr):
return self._get_matrix(expr, sparse=False)
def _print_SparseMatrix(self, expr):
return self._get_matrix(expr, sparse=True)
def _print_Identity(self, expr):
if isinstance(expr.rows, Integer) or isinstance(expr.rows, IntegerConstant):
return self._print(sympy.SparseMatrix(expr))
else:
return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows))
def _print_MatMul(self, expr):
PREC=precedence(expr)
_fact_list = list(expr.args)
_const = None
if not (
isinstance(_fact_list[0], sympy.MatrixBase) or isinstance(
_fact_list[0], sympy.MatrixExpr) or isinstance(
_fact_list[0], sympy.MatrixSlice) or isinstance(
_fact_list[0], sympy.MatrixSymbol)):
_const, _fact_list = _fact_list[0], _fact_list[1:]
if _const is None or _const == 1:
return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
else:
return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list))
def _print_MatPow(self, expr):
# This function requires LinearAlgebra Function in Maple
return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp))
def _print_HadamardProduct(self, expr):
PREC = precedence(expr)
_fact_list = list(expr.args)
return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
def _print_Derivative(self, expr):
_f, (_var, _order) = expr.args
if _order != 1:
_second_arg = '{var}${order}'.format(var=self._print(_var),
order=self._print(_order))
else:
_second_arg = '{var}'.format(var=self._print(_var))
return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg)
def maple_code(expr, assign_to=None, **settings):
r"""Converts ``expr`` to a string of Maple code.
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=16].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
inline: bool, optional
If True, we try to create single-statement code instead of multiple
statements. [default=True].
"""
return MapleCodePrinter(settings).doprint(expr, assign_to)
def print_maple_code(expr, **settings):
"""Prints the Maple representation of the given expression.
See :func:`maple_code` for the meaning of the optional arguments.
Examples
========
>>> from sympy.printing.maple import print_maple_code
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> print_maple_code(x, assign_to=y)
y := x
"""
print(maple_code(expr, **settings))
|
f735a5fdf563cc0b045eb3005b609c0f268b0d2f7d778aa47ff7c0e091da54e5 | from __future__ import print_function, division
import io
import os
from os.path import join
import shutil
import tempfile
try:
from subprocess import STDOUT, CalledProcessError, check_output
except ImportError:
pass
from sympy.utilities.decorator import doctest_depends_on
from .latex import latex
__doctest_requires__ = {('preview',): ['pyglet']}
def _check_output_no_window(*args, **kwargs):
# Avoid showing a cmd.exe window when running this
# on Windows
if os.name == 'nt':
creation_flag = 0x08000000 # CREATE_NO_WINDOW
else:
creation_flag = 0 # Default value
return check_output(*args, creationflags=creation_flag, **kwargs)
def _run_pyglet(fname, fmt):
from pyglet import window, image, gl
from pyglet.window import key
if fmt == "png":
from pyglet.image.codecs.png import PNGImageDecoder
img = image.load(fname, decoder=PNGImageDecoder())
else:
raise ValueError("pyglet preview works only for 'png' files.")
offset = 25
config = gl.Config(double_buffer=False)
win = window.Window(
width=img.width + 2*offset,
height=img.height + 2*offset,
caption="sympy",
resizable=False,
config=config
)
win.set_vsync(False)
try:
def on_close():
win.has_exit = True
win.on_close = on_close
def on_key_press(symbol, modifiers):
if symbol in [key.Q, key.ESCAPE]:
on_close()
win.on_key_press = on_key_press
def on_expose():
gl.glClearColor(1.0, 1.0, 1.0, 1.0)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
img.blit(
(win.width - img.width) / 2,
(win.height - img.height) / 2
)
win.on_expose = on_expose
while not win.has_exit:
win.dispatch_events()
win.flip()
except KeyboardInterrupt:
pass
win.close()
@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',),
disable_viewers=('evince', 'gimp', 'superior-dvi-viewer'))
def preview(expr, output='png', viewer=None, euler=True, packages=(),
filename=None, outputbuffer=None, preamble=None, dvioptions=None,
outputTexFile=None, **latex_settings):
r"""
View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.
If the expr argument is an expression, it will be exported to LaTeX and
then compiled using the available TeX distribution. The first argument,
'expr', may also be a LaTeX string. The function will then run the
appropriate viewer for the given output format or use the user defined
one. By default png output is generated.
By default pretty Euler fonts are used for typesetting (they were used to
typeset the well known "Concrete Mathematics" book). For that to work, you
need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
texlive-fonts-extra package). If you prefer default AMS fonts or your
system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
argument.
To use viewer auto-detection, lets say for 'png' output, issue
>>> from sympy import symbols, preview, Symbol
>>> x, y = symbols("x,y")
>>> preview(x + y, output='png')
This will choose 'pyglet' by default. To select a different one, do
>>> preview(x + y, output='png', viewer='gimp')
The 'png' format is considered special. For all other formats the rules
are slightly different. As an example we will take 'dvi' output format. If
you would run
>>> preview(x + y, output='dvi')
then 'view' will look for available 'dvi' viewers on your system
(predefined in the function, so it will try evince, first, then kdvi and
xdvi). If nothing is found you will need to set the viewer explicitly.
>>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
This will skip auto-detection and will run user specified
'superior-dvi-viewer'. If 'view' fails to find it on your system it will
gracefully raise an exception.
You may also enter 'file' for the viewer argument. Doing so will cause
this function to return a file object in read-only mode, if 'filename'
is unset. However, if it was set, then 'preview' writes the genereted
file to this filename instead.
There is also support for writing to a BytesIO like object, which needs
to be passed to the 'outputbuffer' argument.
>>> from io import BytesIO
>>> obj = BytesIO()
>>> preview(x + y, output='png', viewer='BytesIO',
... outputbuffer=obj)
The LaTeX preamble can be customized by setting the 'preamble' keyword
argument. This can be used, e.g., to set a different font size, use a
custom documentclass or import certain set of LaTeX packages.
>>> preamble = "\\documentclass[10pt]{article}\n" \
... "\\usepackage{amsmath,amsfonts}\\begin{document}"
>>> preview(x + y, output='png', preamble=preamble)
If the value of 'output' is different from 'dvi' then command line
options can be set ('dvioptions' argument) for the execution of the
'dvi'+output conversion tool. These options have to be in the form of a
list of strings (see subprocess.Popen).
Additional keyword args will be passed to the latex call, e.g., the
symbol_names flag.
>>> phidd = Symbol('phidd')
>>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'})
For post-processing the generated TeX File can be written to a file by
passing the desired filename to the 'outputTexFile' keyword
argument. To write the TeX code to a file named
"sample.tex" and run the default png viewer to display the resulting
bitmap, do
>>> preview(x + y, outputTexFile="sample.tex")
"""
special = [ 'pyglet' ]
if viewer is None:
if output == "png":
viewer = "pyglet"
else:
# sorted in order from most pretty to most ugly
# very discussable, but indeed 'gv' looks awful :)
# TODO add candidates for windows to list
candidates = {
"dvi": [ "evince", "okular", "kdvi", "xdvi" ],
"ps": [ "evince", "okular", "gsview", "gv" ],
"pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ],
}
try:
candidate_viewers = candidates[output]
except KeyError:
raise ValueError("Invalid output format: %s" % output) from None
for candidate in candidate_viewers:
path = shutil.which(candidate)
if path is not None:
viewer = path
break
else:
raise OSError(
"No viewers found for '%s' output format." % output)
else:
if viewer == "file":
if filename is None:
raise ValueError("filename has to be specified if viewer=\"file\"")
elif viewer == "BytesIO":
if outputbuffer is None:
raise ValueError("outputbuffer has to be a BytesIO "
"compatible object if viewer=\"BytesIO\"")
elif viewer not in special and not shutil.which(viewer):
raise OSError("Unrecognized viewer: %s" % viewer)
if preamble is None:
actual_packages = packages + ("amsmath", "amsfonts")
if euler:
actual_packages += ("euler",)
package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p
for p in actual_packages])
preamble = r"""\documentclass[varwidth,12pt]{standalone}
%s
\begin{document}
""" % (package_includes)
else:
if packages:
raise ValueError("The \"packages\" keyword must not be set if a "
"custom LaTeX preamble was specified")
if isinstance(expr, str):
latex_string = expr
else:
latex_string = ('$\\displaystyle ' +
latex(expr, mode='plain', **latex_settings) +
'$')
latex_main = preamble + '\n' + latex_string + '\n\n' + r"\end{document}"
with tempfile.TemporaryDirectory() as workdir:
with io.open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
fh.write(latex_main)
if outputTexFile is not None:
shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)
if not shutil.which('latex'):
raise RuntimeError("latex program is not installed")
try:
_check_output_no_window(
['latex', '-halt-on-error', '-interaction=nonstopmode',
'texput.tex'],
cwd=workdir,
stderr=STDOUT)
except CalledProcessError as e:
raise RuntimeError(
"'latex' exited abnormally with the following output:\n%s" %
e.output)
src = "texput.%s" % (output)
if output != "dvi":
# in order of preference
commandnames = {
"ps": ["dvips"],
"pdf": ["dvipdfmx", "dvipdfm", "dvipdf"],
"png": ["dvipng"],
"svg": ["dvisvgm"],
}
try:
cmd_variants = commandnames[output]
except KeyError:
raise ValueError("Invalid output format: %s" % output) from None
# find an appropriate command
for cmd_variant in cmd_variants:
cmd_path = shutil.which(cmd_variant)
if cmd_path:
cmd = [cmd_path]
break
else:
if len(cmd_variants) > 1:
raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants))
else:
raise RuntimeError("%s is not installed" % cmd_variants[0])
defaultoptions = {
"dvipng": ["-T", "tight", "-z", "9", "--truecolor"],
"dvisvgm": ["--no-fonts"],
}
commandend = {
"dvips": ["-o", src, "texput.dvi"],
"dvipdf": ["texput.dvi", src],
"dvipdfm": ["-o", src, "texput.dvi"],
"dvipdfmx": ["-o", src, "texput.dvi"],
"dvipng": ["-o", src, "texput.dvi"],
"dvisvgm": ["-o", src, "texput.dvi"],
}
if dvioptions is not None:
cmd.extend(dvioptions)
else:
cmd.extend(defaultoptions.get(cmd_variant, []))
cmd.extend(commandend[cmd_variant])
try:
_check_output_no_window(cmd, cwd=workdir, stderr=STDOUT)
except CalledProcessError as e:
raise RuntimeError(
"'%s' exited abnormally with the following output:\n%s" %
(' '.join(cmd), e.output))
if viewer == "file":
shutil.move(join(workdir, src), filename)
elif viewer == "BytesIO":
with open(join(workdir, src), 'rb') as fh:
outputbuffer.write(fh.read())
elif viewer == "pyglet":
try:
import pyglet # noqa: F401
except ImportError:
raise ImportError("pyglet is required for preview.\n visit http://www.pyglet.org/")
return _run_pyglet(join(workdir, src), fmt=output)
else:
try:
_check_output_no_window(
[viewer, src], cwd=workdir, stderr=STDOUT)
except CalledProcessError as e:
raise RuntimeError(
"'%s %s' exited abnormally with the following output:\n%s" %
(viewer, src, e.output))
|
e6a43ccf52a61bbb2d3bca06e442720cb3d8c17b8d29d254e21f4aff7b8183a2 | """
Javascript code printer
The JavascriptCodePrinter converts single sympy expressions into single
Javascript expressions, using the functions defined in the Javascript
Math object where possible.
"""
from __future__ import print_function, division
from typing import Any, Dict
from sympy.core import S
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
# dictionary mapping sympy function to (argument_conditions, Javascript_function).
# Used in JavascriptCodePrinter._print_Function(self)
known_functions = {
'Abs': 'Math.abs',
'acos': 'Math.acos',
'acosh': 'Math.acosh',
'asin': 'Math.asin',
'asinh': 'Math.asinh',
'atan': 'Math.atan',
'atan2': 'Math.atan2',
'atanh': 'Math.atanh',
'ceiling': 'Math.ceil',
'cos': 'Math.cos',
'cosh': 'Math.cosh',
'exp': 'Math.exp',
'floor': 'Math.floor',
'log': 'Math.log',
'Max': 'Math.max',
'Min': 'Math.min',
'sign': 'Math.sign',
'sin': 'Math.sin',
'sinh': 'Math.sinh',
'tan': 'Math.tan',
'tanh': 'Math.tanh',
}
class JavascriptCodePrinter(CodePrinter):
""""A Printer to convert python expressions to strings of javascript code
"""
printmethod = '_javascript'
language = 'Javascript'
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'contract': True,
} # type: Dict[str, Any]
def __init__(self, settings={}):
CodePrinter.__init__(self, settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "// {0}".format(text)
def _declare_number_const(self, name, value):
return "var {0} = {1};".format(name, value.evalf(self._settings['precision']))
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for i in range(rows) for j in range(cols))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
for i in indices:
# Javascript arrays start at 0 and end at dimension-1
open_lines.append(loopstart % {
'varble': self._print(i.label),
'start': self._print(i.lower),
'end': self._print(i.upper + 1)})
close_lines.append("}")
return open_lines, close_lines
def _print_Pow(self, expr):
PREC = precedence(expr)
if expr.exp == -1:
return '1/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp == 0.5:
return 'Math.sqrt(%s)' % self._print(expr.base)
elif expr.exp == S.One/3:
return 'Math.cbrt(%s)' % self._print(expr.base)
else:
return 'Math.pow(%s, %s)' % (self._print(expr.base),
self._print(expr.exp))
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return '%d/%d' % (p, q)
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_Indexed(self, expr):
# calculate index for 1d array
dims = expr.shape
elem = S.Zero
offset = S.One
for i in reversed(range(expr.rank)):
elem += expr.indices[i]*offset
offset *= dims[i]
return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Exp1(self, expr):
return "Math.E"
def _print_Pi(self, expr):
return 'Math.PI'
def _print_Infinity(self, expr):
return 'Number.POSITIVE_INFINITY'
def _print_NegativeInfinity(self, expr):
return 'Number.NEGATIVE_INFINITY'
def _print_Piecewise(self, expr):
from sympy.codegen.ast import Assignment
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if expr.has(Assignment):
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) {" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else {")
else:
lines.append("else if (%s) {" % self._print(c))
code0 = self._print(e)
lines.append(code0)
lines.append("}")
return "\n".join(lines)
else:
# The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will
# not work for statements that span multiple lines (Matrix or
# Indexed expressions).
ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e))
for e, c in expr.args[:-1]]
last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
def _print_MatrixElement(self, expr):
return "{0}[{1}]".format(self.parenthesize(expr.parent,
PRECEDENCE["Atom"], strict=True),
expr.j + expr.i*expr.parent.shape[1])
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
decrease = [ int(any(map(line.startswith, dec_token)))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def jscode(expr, assign_to=None, **settings):
"""Converts an expr to a string of javascript code
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=15].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, js_function_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
Examples
========
>>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
>>> x, tau = symbols("x, tau")
>>> jscode((2*tau)**Rational(7, 2))
'8*Math.sqrt(2)*Math.pow(tau, 7/2)'
>>> jscode(sin(x), assign_to="s")
's = Math.sin(x);'
Custom printing can be defined for certain types by passing a dictionary of
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
js_function_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "Abs": [(lambda x: not x.is_integer, "fabs"),
... (lambda x: x.is_integer, "ABS")]
... }
>>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
'fabs(x) + CEIL(x)'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(jscode(expr, tau))
if (x > 0) {
tau = x + 1;
}
else {
tau = x;
}
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> jscode(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(jscode(mat, A))
A[0] = Math.pow(x, 2);
if (x > 0) {
A[1] = x + 1;
}
else {
A[1] = x;
}
A[2] = Math.sin(x);
"""
return JavascriptCodePrinter(settings).doprint(expr, assign_to)
def print_jscode(expr, **settings):
"""Prints the Javascript representation of the given expression.
See jscode for the meaning of the optional arguments.
"""
print(jscode(expr, **settings))
|
968ede0b36d5c9ea8b40c448796332e2dbb8c1e9d940babf9557a6a494c2cbe0 | """
A Printer for generating executable code.
The most important function here is srepr that returns a string so that the
relation eval(srepr(expr))=expr holds in an appropriate environment.
"""
from __future__ import print_function, division
from typing import Any, Dict
from sympy.core.function import AppliedUndef
from sympy.core.mul import Mul
from mpmath.libmp import repr_dps, to_str as mlib_to_str
from .printer import Printer
class ReprPrinter(Printer):
printmethod = "_sympyrepr"
_default_settings = {
"order": None,
"perm_cyclic" : True,
} # type: Dict[str, Any]
def reprify(self, args, sep):
"""
Prints each item in `args` and joins them with `sep`.
"""
return sep.join([self.doprint(item) for item in args])
def emptyPrinter(self, expr):
"""
The fallback printer.
"""
if isinstance(expr, str):
return expr
elif hasattr(expr, "__srepr__"):
return expr.__srepr__()
elif hasattr(expr, "args") and hasattr(expr.args, "__iter__"):
l = []
for o in expr.args:
l.append(self._print(o))
return expr.__class__.__name__ + '(%s)' % ', '.join(l)
elif hasattr(expr, "__module__") and hasattr(expr, "__name__"):
return "<'%s.%s'>" % (expr.__module__, expr.__name__)
else:
return str(expr)
def _print_Add(self, expr, order=None):
args = self._as_ordered_terms(expr, order=order)
nargs = len(args)
args = map(self._print, args)
clsname = type(expr).__name__
if nargs > 255: # Issue #10259, Python < 3.7
return clsname + "(*[%s])" % ", ".join(args)
return clsname + "(%s)" % ", ".join(args)
def _print_Cycle(self, expr):
return expr.__repr__()
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
from sympy.utilities.exceptions import SymPyDeprecationWarning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
if not expr.size:
return 'Permutation()'
# before taking Cycle notation, see if the last element is
# a singleton and move it to the head of the string
s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
last = s.rfind('(')
if not last == 0 and ',' not in s[last:]:
s = s[last:] + s[:last]
return 'Permutation%s' %s
else:
s = expr.support()
if not s:
if expr.size < 5:
return 'Permutation(%s)' % str(expr.array_form)
return 'Permutation([], size=%s)' % expr.size
trim = str(expr.array_form[:s[-1] + 1]) + ', size=%s' % expr.size
use = full = str(expr.array_form)
if len(trim) < len(full):
use = trim
return 'Permutation(%s)' % use
def _print_Function(self, expr):
r = self._print(expr.func)
r += '(%s)' % ', '.join([self._print(a) for a in expr.args])
return r
def _print_FunctionClass(self, expr):
if issubclass(expr, AppliedUndef):
return 'Function(%r)' % (expr.__name__)
else:
return expr.__name__
def _print_Half(self, expr):
return 'Rational(1, 2)'
def _print_RationalConstant(self, expr):
return str(expr)
def _print_AtomicExpr(self, expr):
return str(expr)
def _print_NumberSymbol(self, expr):
return str(expr)
def _print_Integer(self, expr):
return 'Integer(%i)' % expr.p
def _print_Integers(self, expr):
return 'Integers'
def _print_Naturals(self, expr):
return 'Naturals'
def _print_Naturals0(self, expr):
return 'Naturals0'
def _print_Reals(self, expr):
return 'Reals'
def _print_EmptySet(self, expr):
return 'EmptySet'
def _print_EmptySequence(self, expr):
return 'EmptySequence'
def _print_list(self, expr):
return "[%s]" % self.reprify(expr, ", ")
def _print_dict(self, expr):
sep = ", "
dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()]
return "{%s}" % sep.join(dict_kvs)
def _print_set(self, expr):
if not expr:
return "set()"
return "{%s}" % self.reprify(expr, ", ")
def _print_MatrixBase(self, expr):
# special case for some empty matrices
if (expr.rows == 0) ^ (expr.cols == 0):
return '%s(%s, %s, %s)' % (expr.__class__.__name__,
self._print(expr.rows),
self._print(expr.cols),
self._print([]))
l = []
for i in range(expr.rows):
l.append([])
for j in range(expr.cols):
l[-1].append(expr[i, j])
return '%s(%s)' % (expr.__class__.__name__, self._print(l))
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_NaN(self, expr):
return "nan"
def _print_Mul(self, expr, order=None):
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
nargs = len(args)
args = map(self._print, args)
clsname = type(expr).__name__
if nargs > 255: # Issue #10259, Python < 3.7
return clsname + "(*[%s])" % ", ".join(args)
return clsname + "(%s)" % ", ".join(args)
def _print_Rational(self, expr):
return 'Rational(%s, %s)' % (self._print(expr.p), self._print(expr.q))
def _print_PythonRational(self, expr):
return "%s(%d, %d)" % (expr.__class__.__name__, expr.p, expr.q)
def _print_Fraction(self, expr):
return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))
def _print_Float(self, expr):
r = mlib_to_str(expr._mpf_, repr_dps(expr._prec))
return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)
def _print_Sum2(self, expr):
return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),
self._print(expr.a), self._print(expr.b))
def _print_Str(self, s):
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
def _print_Symbol(self, expr):
d = expr._assumptions.generator
# print the dummy_index like it was an assumption
if expr.is_Dummy:
d['dummy_index'] = expr.dummy_index
if d == {}:
return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))
else:
attr = ['%s=%s' % (k, v) for k, v in d.items()]
return "%s(%s, %s)" % (expr.__class__.__name__,
self._print(expr.name), ', '.join(attr))
def _print_CoordinateSymbol(self, expr):
d = expr._assumptions.generator
if d == {}:
return "%s(%s, %s)" % (
expr.__class__.__name__,
self._print(expr.coordinate_system),
self._print(expr.index)
)
else:
attr = ['%s=%s' % (k, v) for k, v in d.items()]
return "%s(%s, %s, %s)" % (
expr.__class__.__name__,
self._print(expr.coordinate_system),
self._print(expr.index),
', '.join(attr)
)
def _print_Predicate(self, expr):
return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))
def _print_AppliedPredicate(self, expr):
return "%s(%s, %s)" % (expr.__class__.__name__, expr.func, expr.arg)
def _print_str(self, expr):
return repr(expr)
def _print_tuple(self, expr):
if len(expr) == 1:
return "(%s,)" % self._print(expr[0])
else:
return "(%s)" % self.reprify(expr, ", ")
def _print_WildFunction(self, expr):
return "%s('%s')" % (expr.__class__.__name__, expr.name)
def _print_AlgebraicNumber(self, expr):
return "%s(%s, %s)" % (expr.__class__.__name__,
self._print(expr.root), self._print(expr.coeffs()))
def _print_PolyRing(self, ring):
return "%s(%s, %s, %s)" % (ring.__class__.__name__,
self._print(ring.symbols), self._print(ring.domain), self._print(ring.order))
def _print_FracField(self, field):
return "%s(%s, %s, %s)" % (field.__class__.__name__,
self._print(field.symbols), self._print(field.domain), self._print(field.order))
def _print_PolyElement(self, poly):
terms = list(poly.terms())
terms.sort(key=poly.ring.order, reverse=True)
return "%s(%s, %s)" % (poly.__class__.__name__, self._print(poly.ring), self._print(terms))
def _print_FracElement(self, frac):
numer_terms = list(frac.numer.terms())
numer_terms.sort(key=frac.field.order, reverse=True)
denom_terms = list(frac.denom.terms())
denom_terms.sort(key=frac.field.order, reverse=True)
numer = self._print(numer_terms)
denom = self._print(denom_terms)
return "%s(%s, %s, %s)" % (frac.__class__.__name__, self._print(frac.field), numer, denom)
def _print_FractionField(self, domain):
cls = domain.__class__.__name__
field = self._print(domain.field)
return "%s(%s)" % (cls, field)
def _print_PolynomialRingBase(self, ring):
cls = ring.__class__.__name__
dom = self._print(ring.domain)
gens = ', '.join(map(self._print, ring.gens))
order = str(ring.order)
if order != ring.default_order:
orderstr = ", order=" + order
else:
orderstr = ""
return "%s(%s, %s%s)" % (cls, dom, gens, orderstr)
def _print_DMP(self, p):
cls = p.__class__.__name__
rep = self._print(p.rep)
dom = self._print(p.dom)
if p.ring is not None:
ringstr = ", ring=" + self._print(p.ring)
else:
ringstr = ""
return "%s(%s, %s%s)" % (cls, rep, dom, ringstr)
def _print_MonogenicFiniteExtension(self, ext):
# The expanded tree shown by srepr(ext.modulus)
# is not practical.
return "FiniteExtension(%s)" % str(ext.modulus)
def _print_ExtensionElement(self, f):
rep = self._print(f.rep)
ext = self._print(f.ext)
return "ExtElem(%s, %s)" % (rep, ext)
def srepr(expr, **settings):
"""return expr in repr form"""
return ReprPrinter(settings).doprint(expr)
|
0d85e1ba5eb8e871122cb79ea542ece74b1f0bc54993d6af521b1d7f49764882 | """
Julia code printer
The `JuliaCodePrinter` converts SymPy expressions into Julia expressions.
A complete code generator, which uses `julia_code` extensively, can be found
in `sympy.utilities.codegen`. The `codegen` module can be used to generate
complete source code files.
"""
from __future__ import print_function, division
from typing import Any, Dict
from sympy.core import Mul, Pow, S, Rational
from sympy.core.mul import _keep_coeff
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
from re import search
# List of known functions. First, those that have the same name in
# SymPy and Julia. This is almost certainly incomplete!
known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
"asin", "acos", "atan", "acot", "asec", "acsc",
"sinh", "cosh", "tanh", "coth", "sech", "csch",
"asinh", "acosh", "atanh", "acoth", "asech", "acsch",
"sinc", "atan2", "sign", "floor", "log", "exp",
"cbrt", "sqrt", "erf", "erfc", "erfi",
"factorial", "gamma", "digamma", "trigamma",
"polygamma", "beta",
"airyai", "airyaiprime", "airybi", "airybiprime",
"besselj", "bessely", "besseli", "besselk",
"erfinv", "erfcinv"]
# These functions have different names ("Sympy": "Julia"), more
# generally a mapping to (argument_conditions, julia_function).
known_fcns_src2 = {
"Abs": "abs",
"ceiling": "ceil",
"conjugate": "conj",
"hankel1": "hankelh1",
"hankel2": "hankelh2",
"im": "imag",
"re": "real"
}
class JuliaCodePrinter(CodePrinter):
"""
A printer to convert expressions to strings of Julia code.
"""
printmethod = "_julia"
language = "Julia"
_operators = {
'and': '&&',
'or': '||',
'not': '!',
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'contract': True,
'inline': True,
} # type: Dict[str, Any]
# Note: contract is for expressing tensors as loops (if True), or just
# assignment (if False). FIXME: this should be looked a more carefully
# for Julia.
def __init__(self, settings={}):
super(JuliaCodePrinter, self).__init__(settings)
self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
self.known_functions.update(dict(known_fcns_src2))
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s" % codestring
def _get_comment(self, text):
return "# {0}".format(text)
def _declare_number_const(self, name, value):
return "const {0} = {1}".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
# Julia uses Fortran order (column-major)
rows, cols = mat.shape
return ((i, j) for j in range(cols) for i in range(rows))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
for i in indices:
# Julia arrays start at 1 and end at dimension
var, start, stop = map(self._print,
[i.label, i.lower + 1, i.upper + 1])
open_lines.append("for %s = %s:%s" % (var, start, stop))
close_lines.append("end")
return open_lines, close_lines
def _print_Mul(self, expr):
# print complex numbers nicely in Julia
if (expr.is_number and expr.is_imaginary and
expr.as_coeff_Mul()[0].is_integer):
return "%sim" % self._print(-S.ImaginaryUnit*expr)
# cribbed from str.py
prec = precedence(expr)
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
# Gather args for numerator/denominator
for item in args:
if (item.is_commutative and item.is_Pow and item.exp.is_Rational
and item.exp.is_negative):
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
pow_paren.append(item)
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append(Rational(item.p))
if item.q != 1:
b.append(Rational(item.q))
else:
a.append(item)
a = a or [S.One]
a_str = [self.parenthesize(x, prec) for x in a]
b_str = [self.parenthesize(x, prec) for x in b]
# To parenthesize Pow with exp = -1 and having more than one Symbol
for item in pow_paren:
if item.base in b:
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
# from here it differs from str.py to deal with "*" and ".*"
def multjoin(a, a_str):
# here we probably are assuming the constants will come first
r = a_str[0]
for i in range(1, len(a)):
mulsym = '*' if a[i-1].is_number else '.*'
r = r + mulsym + a_str[i]
return r
if not b:
return sign + multjoin(a, a_str)
elif len(b) == 1:
divsym = '/' if b[0].is_number else './'
return sign + multjoin(a, a_str) + divsym + b_str[0]
else:
divsym = '/' if all([bi.is_number for bi in b]) else './'
return (sign + multjoin(a, a_str) +
divsym + "(%s)" % multjoin(b, b_str))
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_Pow(self, expr):
powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^'
PREC = precedence(expr)
if expr.exp == S.Half:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if expr.exp == -S.Half:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "sqrt(%s)" % self._print(expr.base)
if expr.exp == -S.One:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
self.parenthesize(expr.exp, PREC))
def _print_MatPow(self, expr):
PREC = precedence(expr)
return '%s^%s' % (self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC))
def _print_Pi(self, expr):
if self._settings["inline"]:
return "pi"
else:
return super(JuliaCodePrinter, self)._print_NumberSymbol(expr)
def _print_ImaginaryUnit(self, expr):
return "im"
def _print_Exp1(self, expr):
if self._settings["inline"]:
return "e"
else:
return super(JuliaCodePrinter, self)._print_NumberSymbol(expr)
def _print_EulerGamma(self, expr):
if self._settings["inline"]:
return "eulergamma"
else:
return super(JuliaCodePrinter, self)._print_NumberSymbol(expr)
def _print_Catalan(self, expr):
if self._settings["inline"]:
return "catalan"
else:
return super(JuliaCodePrinter, self)._print_NumberSymbol(expr)
def _print_GoldenRatio(self, expr):
if self._settings["inline"]:
return "golden"
else:
return super(JuliaCodePrinter, self)._print_NumberSymbol(expr)
def _print_Assignment(self, expr):
from sympy.codegen.ast import Assignment
from sympy.functions.elementary.piecewise import Piecewise
from sympy.tensor.indexed import IndexedBase
# Copied from codeprinter, but remove special MatrixSymbol treatment
lhs = expr.lhs
rhs = expr.rhs
# We special case assignments that take multiple lines
if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
# Here we modify Piecewise so each expression is now
# an Assignment, and then continue on the print.
expressions = []
conditions = []
for (e, c) in rhs.args:
expressions.append(Assignment(lhs, e))
conditions.append(c)
temp = Piecewise(*zip(expressions, conditions))
return self._print(temp)
if self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_Infinity(self, expr):
return 'Inf'
def _print_NegativeInfinity(self, expr):
return '-Inf'
def _print_NaN(self, expr):
return 'NaN'
def _print_list(self, expr):
return 'Any[' + ', '.join(self._print(a) for a in expr) + ']'
def _print_tuple(self, expr):
if len(expr) == 1:
return "(%s,)" % self._print(expr[0])
else:
return "(%s)" % self.stringify(expr, ", ")
_print_Tuple = _print_tuple
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_bool(self, expr):
return str(expr).lower()
# Could generate quadrature code for definite Integrals?
#_print_Integral = _print_not_supported
def _print_MatrixBase(self, A):
# Handle zero dimensions:
if A.rows == 0 or A.cols == 0:
return 'zeros(%s, %s)' % (A.rows, A.cols)
elif (A.rows, A.cols) == (1, 1):
return "[%s]" % A[0, 0]
elif A.rows == 1:
return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ')
elif A.cols == 1:
# note .table would unnecessarily equispace the rows
return "[%s]" % ", ".join([self._print(a) for a in A])
return "[%s]" % A.table(self, rowstart='', rowend='',
rowsep=';\n', colsep=' ')
def _print_SparseMatrix(self, A):
from sympy.matrices import Matrix
L = A.col_list();
# make row vectors of the indices and entries
I = Matrix([k[0] + 1 for k in L])
J = Matrix([k[1] + 1 for k in L])
AIJ = Matrix([k[2] for k in L])
return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
self._print(AIJ), A.rows, A.cols)
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
+ '[%s,%s]' % (expr.i + 1, expr.j + 1)
def _print_MatrixSlice(self, expr):
def strslice(x, lim):
l = x[0] + 1
h = x[1]
step = x[2]
lstr = self._print(l)
hstr = 'end' if h == lim else self._print(h)
if step == 1:
if l == 1 and h == lim:
return ':'
if l == h:
return lstr
else:
return lstr + ':' + hstr
else:
return ':'.join((lstr, self._print(step), hstr))
return (self._print(expr.parent) + '[' +
strslice(expr.rowslice, expr.parent.shape[0]) + ',' +
strslice(expr.colslice, expr.parent.shape[1]) + ']')
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s[%s]" % (self._print(expr.base.label), ",".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Identity(self, expr):
return "eye(%s)" % self._print(expr.shape[0])
def _print_HadamardProduct(self, expr):
return '.*'.join([self.parenthesize(arg, precedence(expr))
for arg in expr.args])
def _print_HadamardPower(self, expr):
PREC = precedence(expr)
return '.**'.join([
self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC)
])
# Note: as of 2015, Julia doesn't have spherical Bessel functions
def _print_jn(self, expr):
from sympy.functions import sqrt, besselj
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
return self._print(expr2)
def _print_yn(self, expr):
from sympy.functions import sqrt, bessely
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
return self._print(expr2)
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if self._settings["inline"]:
# Express each (cond, expr) pair in a nested Horner form:
# (condition) .* (expr) + (not cond) .* (<others>)
# Expressions that result in multiple statements won't work here.
ecpairs = ["({0}) ? ({1}) :".format
(self._print(c), self._print(e))
for e, c in expr.args[:-1]]
elast = " (%s)" % self._print(expr.args[-1].expr)
pw = "\n".join(ecpairs) + elast
# Note: current need these outer brackets for 2*pw. Would be
# nicer to teach parenthesize() to do this for us when needed!
return "(" + pw + ")"
else:
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s)" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else")
else:
lines.append("elseif (%s)" % self._print(c))
code0 = self._print(e)
lines.append(code0)
if i == len(expr.args) - 1:
lines.append("end")
return "\n".join(lines)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
# code mostly copied from ccode
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
dec_regex = ('^end$', '^elseif ', '^else$')
# pre-strip left-space from the code
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any([search(re, line) for re in inc_regex]))
for line in code ]
decrease = [ int(any([search(re, line) for re in dec_regex]))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def julia_code(expr, assign_to=None, **settings):
r"""Converts `expr` to a string of Julia code.
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=16].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
inline: bool, optional
If True, we try to create single-statement code instead of multiple
statements. [default=True].
Examples
========
>>> from sympy import julia_code, symbols, sin, pi
>>> x = symbols('x')
>>> julia_code(sin(x).series(x).removeO())
'x.^5/120 - x.^3/6 + x'
>>> from sympy import Rational, ceiling
>>> x, y, tau = symbols("x, y, tau")
>>> julia_code((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau.^(7/2)'
Note that element-wise (Hadamard) operations are used by default between
symbols. This is because its possible in Julia to write "vectorized"
code. It is harmless if the values are scalars.
>>> julia_code(sin(pi*x*y), assign_to="s")
's = sin(pi*x.*y)'
If you need a matrix product "*" or matrix power "^", you can specify the
symbol as a ``MatrixSymbol``.
>>> from sympy import Symbol, MatrixSymbol
>>> n = Symbol('n', integer=True, positive=True)
>>> A = MatrixSymbol('A', n, n)
>>> julia_code(3*pi*A**3)
'(3*pi)*A^3'
This class uses several rules to decide which symbol to use a product.
Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
A HadamardProduct can be used to specify componentwise multiplication ".*"
of two MatrixSymbols. There is currently there is no easy way to specify
scalar symbols, so sometimes the code might have some minor cosmetic
issues. For example, suppose x and y are scalars and A is a Matrix, then
while a human programmer might write "(x^2*y)*A^3", we generate:
>>> julia_code(x**2*y*A**3)
'(x.^2.*y)*A^3'
Matrices are supported using Julia inline notation. When using
``assign_to`` with matrices, the name can be specified either as a string
or as a ``MatrixSymbol``. The dimensions must align in the latter case.
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
>>> julia_code(mat, assign_to='A')
'A = [x.^2 sin(x) ceil(x)]'
``Piecewise`` expressions are implemented with logical masking by default.
Alternatively, you can pass "inline=False" to use if-else conditionals.
Note that if the ``Piecewise`` lacks a default term, represented by
``(expr, True)`` then an error will be thrown. This is to prevent
generating an expression that may not evaluate to anything.
>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> julia_code(pw, assign_to=tau)
'tau = ((x > 0) ? (x + 1) : (x))'
Note that any expression that can be generated normally can also exist
inside a Matrix:
>>> mat = Matrix([[x**2, pw, sin(x)]])
>>> julia_code(mat, assign_to='A')
'A = [x.^2 ((x > 0) ? (x + 1) : (x)) sin(x)]'
Custom printing can be defined for certain types by passing a dictionary of
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
dictionary value can be a list of tuples i.e., [(argument_test,
cfunction_string)]. This can be used to call a custom Julia function.
>>> from sympy import Function
>>> f = Function('f')
>>> g = Function('g')
>>> custom_functions = {
... "f": "existing_julia_fcn",
... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
... (lambda x: not x.is_Matrix, "my_fcn")]
... }
>>> mat = Matrix([[1, x]])
>>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> julia_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])./(t[i + 1] - t[i])'
"""
return JuliaCodePrinter(settings).doprint(expr, assign_to)
def print_julia_code(expr, **settings):
"""Prints the Julia representation of the given expression.
See `julia_code` for the meaning of the optional arguments.
"""
print(julia_code(expr, **settings))
|
295f997d500c747855a48ebe060cb27d8596b81d002edf3919e33e085d674b86 | from typing import Set
from sympy.core import Basic, S
from sympy.core.function import _coeff_isneg, Lambda
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence
from functools import reduce
known_functions = {
'Abs': 'abs',
'sin': 'sin',
'cos': 'cos',
'tan': 'tan',
'acos': 'acos',
'asin': 'asin',
'atan': 'atan',
'atan2': 'atan',
'ceiling': 'ceil',
'floor': 'floor',
'sign': 'sign',
'exp': 'exp',
'log': 'log',
'add': 'add',
'sub': 'sub',
'mul': 'mul',
'pow': 'pow'
}
class GLSLPrinter(CodePrinter):
"""
Rudimentary, generic GLSL printing tools.
Additional settings:
'use_operators': Boolean (should the printer use operators for +,-,*, or functions?)
"""
_not_supported = set() # type: Set[Basic]
printmethod = "_glsl"
language = "GLSL"
_default_settings = {
'use_operators': True,
'mat_nested': False,
'mat_separator': ',\n',
'mat_transpose': False,
'glsl_types': True,
'order': None,
'full_prec': 'auto',
'precision': 9,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'contract': True,
'error_on_reserved': False,
'reserved_word_suffix': '_',
}
def __init__(self, settings={}):
CodePrinter.__init__(self, settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "// {0}".format(text)
def _declare_number_const(self, name, value):
return "float {0} = {1};".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [line.lstrip(' \t') for line in code]
increase = [int(any(map(line.endswith, inc_token))) for line in code]
decrease = [int(any(map(line.startswith, dec_token))) for line in code]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def _print_MatrixBase(self, mat):
mat_separator = self._settings['mat_separator']
mat_transpose = self._settings['mat_transpose']
glsl_types = self._settings['glsl_types']
column_vector = (mat.rows == 1) if mat_transpose else (mat.cols == 1)
A = mat.transpose() if mat_transpose != column_vector else mat
if A.cols == 1:
return self._print(A[0]);
if A.rows <= 4 and A.cols <= 4 and glsl_types:
if A.rows == 1:
return 'vec%s%s' % (A.cols, A.table(self,rowstart='(',rowend=')'))
elif A.rows == A.cols:
return 'mat%s(%s)' % (A.rows, A.table(self,rowsep=', ',
rowstart='',rowend=''))
else:
return 'mat%sx%s(%s)' % (A.cols, A.rows,
A.table(self,rowsep=', ',
rowstart='',rowend=''))
elif A.cols == 1 or A.rows == 1:
return 'float[%s](%s)' % (A.cols*A.rows, A.table(self,rowsep=mat_separator,rowstart='',rowend=''))
elif not self._settings['mat_nested']:
return 'float[%s](\n%s\n) /* a %sx%s matrix */' % (A.cols*A.rows,
A.table(self,rowsep=mat_separator,rowstart='',rowend=''),
A.rows,A.cols)
elif self._settings['mat_nested']:
return 'float[%s][%s](\n%s\n)' % (A.rows,A.cols,A.table(self,rowsep=mat_separator,rowstart='float[](',rowend=')'))
def _print_SparseMatrix(self, mat):
# do not allow sparse matrices to be made dense
return self._print_not_supported(mat)
def _traverse_matrix_indices(self, mat):
mat_transpose = self._settings['mat_transpose']
if mat_transpose:
rows,cols = mat.shape
else:
cols,rows = mat.shape
return ((i, j) for i in range(cols) for j in range(rows))
def _print_MatrixElement(self, expr):
# print('begin _print_MatrixElement')
nest = self._settings['mat_nested'];
glsl_types = self._settings['glsl_types'];
mat_transpose = self._settings['mat_transpose'];
if mat_transpose:
cols,rows = expr.parent.shape
i,j = expr.j,expr.i
else:
rows,cols = expr.parent.shape
i,j = expr.i,expr.j
pnt = self._print(expr.parent)
if glsl_types and ((rows <= 4 and cols <=4) or nest):
# print('end _print_MatrixElement case A',nest,glsl_types)
return "%s[%s][%s]" % (pnt, i, j)
else:
# print('end _print_MatrixElement case B',nest,glsl_types)
return "{0}[{1}]".format(pnt, i + j*rows)
def _print_list(self, expr):
l = ', '.join(self._print(item) for item in expr)
glsl_types = self._settings['glsl_types']
if len(expr) <= 4 and glsl_types:
return 'vec%s(%s)' % (len(expr),l)
else:
return 'float[%s](%s)' % (len(expr),l)
_print_tuple = _print_list
_print_Tuple = _print_list
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
loopstart = "for (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
for i in indices:
# GLSL arrays start at 0 and end at dimension-1
open_lines.append(loopstart % {
'varble': self._print(i.label),
'start': self._print(i.lower),
'end': self._print(i.upper + 1)})
close_lines.append("}")
return open_lines, close_lines
def _print_Function_with_args(self, func, func_args):
if func in self.known_functions:
cond_func = self.known_functions[func]
func = None
if isinstance(cond_func, str):
func = cond_func
else:
for cond, func in cond_func:
if cond(func_args):
break
if func is not None:
try:
return func(*[self.parenthesize(item, 0) for item in func_args])
except TypeError:
return "%s(%s)" % (func, self.stringify(func_args, ", "))
elif isinstance(func, Lambda):
# inlined function
return self._print(func(*func_args))
else:
return self._print_not_supported(func)
def _print_Piecewise(self, expr):
from sympy.codegen.ast import Assignment
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if expr.has(Assignment):
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) {" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else {")
else:
lines.append("else if (%s) {" % self._print(c))
code0 = self._print(e)
lines.append(code0)
lines.append("}")
return "\n".join(lines)
else:
# The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will
# not work for statements that span multiple lines (Matrix or
# Indexed expressions).
ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
self._print(e))
for e, c in expr.args[:-1]]
last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Indexed(self, expr):
# calculate index for 1d array
dims = expr.shape
elem = S.Zero
offset = S.One
for i in reversed(range(expr.rank)):
elem += expr.indices[i]*offset
offset *= dims[i]
return "%s[%s]" % (self._print(expr.base.label),
self._print(elem))
def _print_Pow(self, expr):
PREC = precedence(expr)
if expr.exp == -1:
return '1.0/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp == 0.5:
return 'sqrt(%s)' % self._print(expr.base)
else:
try:
e = self._print(float(expr.exp))
except TypeError:
e = self._print(expr.exp)
# return self.known_functions['pow']+'(%s, %s)' % (self._print(expr.base),e)
return self._print_Function_with_args('pow', (
self._print(expr.base),
e
))
def _print_int(self, expr):
return str(float(expr))
def _print_Rational(self, expr):
return "%s.0/%s.0" % (expr.p, expr.q)
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{0} {1} {2}".format(lhs_code, op, rhs_code)
def _print_Add(self, expr, order=None):
if self._settings['use_operators']:
return CodePrinter._print_Add(self, expr, order=order)
terms = expr.as_ordered_terms()
def partition(p,l):
return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], []))
def add(a,b):
return self._print_Function_with_args('add', (a, b))
# return self.known_functions['add']+'(%s, %s)' % (a,b)
neg, pos = partition(lambda arg: _coeff_isneg(arg), terms)
s = pos = reduce(lambda a,b: add(a,b), map(lambda t: self._print(t),pos))
if neg:
# sum the absolute values of the negative terms
neg = reduce(lambda a,b: add(a,b), map(lambda n: self._print(-n),neg))
# then subtract them from the positive terms
s = self._print_Function_with_args('sub', (pos,neg))
# s = self.known_functions['sub']+'(%s, %s)' % (pos,neg)
return s
def _print_Mul(self, expr, **kwargs):
if self._settings['use_operators']:
return CodePrinter._print_Mul(self, expr, **kwargs)
terms = expr.as_ordered_factors()
def mul(a,b):
# return self.known_functions['mul']+'(%s, %s)' % (a,b)
return self._print_Function_with_args('mul', (a,b))
s = reduce(lambda a,b: mul(a,b), map(lambda t: self._print(t), terms))
return s
def glsl_code(expr,assign_to=None,**settings):
"""Converts an expr to a string of GLSL code
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
use_operators: bool, optional
If set to False, then *,/,+,- operators will be replaced with functions
mul, add, and sub, which must be implemented by the user, e.g. for
implementing non-standard rings or emulated quad/octal precision.
[default=True]
glsl_types: bool, optional
Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat``
types. The printer will instead use arrays (or nested arrays).
[default=True]
mat_nested: bool, optional
GLSL version 4.3 and above support nested arrays (arrays of arrays). Set this to ``True``
to render matrices as nested arrays.
[default=False]
mat_separator: str, optional
By default, matrices are rendered with newlines using this separator,
making them easier to read, but less compact. By removing the newline
this option can be used to make them more vertically compact.
[default=',\n']
mat_transpose: bool, optional
GLSL's matrix multiplication implementation assumes column-major indexing.
By default, this printer ignores that convention. Setting this option to
``True`` transposes all matrix output.
[default=False]
precision : integer, optional
The precision for numbers such as pi [default=15].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, js_function_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
Examples
========
>>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs
>>> x, tau = symbols("x, tau")
>>> glsl_code((2*tau)**Rational(7, 2))
'8*sqrt(2)*pow(tau, 3.5)'
>>> glsl_code(sin(x), assign_to="float y")
'float y = sin(x);'
Various GLSL types are supported:
>>> from sympy import Matrix, glsl_code
>>> glsl_code(Matrix([1,2,3]))
'vec3(1, 2, 3)'
>>> glsl_code(Matrix([[1, 2],[3, 4]]))
'mat2(1, 2, 3, 4)'
Pass ``mat_transpose = True`` to switch to column-major indexing:
>>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True)
'mat2(1, 3, 2, 4)'
By default, larger matrices get collapsed into float arrays:
>>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) ))
float[10](
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
) /* a 2x5 matrix */
Passing ``mat_nested = True`` instead prints out nested float arrays, which are
supported in GLSL 4.3 and above.
>>> mat = Matrix([
... [ 0, 1, 2],
... [ 3, 4, 5],
... [ 6, 7, 8],
... [ 9, 10, 11],
... [12, 13, 14]])
>>> print(glsl_code( mat, mat_nested = True ))
float[5][3](
float[]( 0, 1, 2),
float[]( 3, 4, 5),
float[]( 6, 7, 8),
float[]( 9, 10, 11),
float[](12, 13, 14)
)
Custom printing can be defined for certain types by passing a dictionary of
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
js_function_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "Abs": [(lambda x: not x.is_integer, "fabs"),
... (lambda x: x.is_integer, "ABS")]
... }
>>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions)
'fabs(x) + CEIL(x)'
If further control is needed, addition, subtraction, multiplication and
division operators can be replaced with ``add``, ``sub``, and ``mul``
functions. This is done by passing ``use_operators = False``:
>>> x,y,z = symbols('x,y,z')
>>> glsl_code(x*(y+z), use_operators = False)
'mul(x, add(y, z))'
>>> glsl_code(x*(y+z*(x-y)**z), use_operators = False)
'mul(x, add(y, mul(z, pow(sub(x, y), z))))'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(glsl_code(expr, tau))
if (x > 0) {
tau = x + 1;
}
else {
tau = x;
}
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> glsl_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(glsl_code(mat, A))
A[0][0] = pow(x, 2.0);
if (x > 0) {
A[1][0] = x + 1;
}
else {
A[1][0] = x;
}
A[2][0] = sin(x);
"""
return GLSLPrinter(settings).doprint(expr,assign_to)
def print_glsl(expr, **settings):
"""Prints the GLSL representation of the given expression.
See GLSLPrinter init function for settings.
"""
print(glsl_code(expr, **settings))
|
d1750867cc60b948477cb855598dd4dee76e5df730e039b77f86f404209d088f | """Module for SymPy containers
(SymPy objects that store other SymPy objects)
The containers implemented in this module are subclassed to Basic.
They are supposed to work seamlessly within the SymPy framework.
"""
from collections import OrderedDict
from sympy.core.basic import Basic
from sympy.core.compatibility import as_int, MutableSet
from sympy.core.sympify import _sympify, sympify, converter, SympifyError
from sympy.utilities.iterables import iterable
class Tuple(Basic):
"""
Wrapper around the builtin tuple object
The Tuple is a subclass of Basic, so that it works well in the
SymPy framework. The wrapped tuple is available as self.args, but
you can also access elements or slices with [:] syntax.
Parameters
==========
sympify : bool
If ``False``, ``sympify`` is not called on ``args``. This
can be used for speedups for very large tuples where the
elements are known to already be sympy objects.
Example
=======
>>> from sympy import symbols
>>> from sympy.core.containers import Tuple
>>> a, b, c, d = symbols('a b c d')
>>> Tuple(a, b, c)[1:]
(b, c)
>>> Tuple(a, b, c).subs(a, d)
(d, b, c)
"""
def __new__(cls, *args, **kwargs):
if kwargs.get('sympify', True):
args = (sympify(arg) for arg in args)
obj = Basic.__new__(cls, *args)
return obj
def __getitem__(self, i):
if isinstance(i, slice):
indices = i.indices(len(self))
return Tuple(*(self.args[j] for j in range(*indices)))
return self.args[i]
def __len__(self):
return len(self.args)
def __contains__(self, item):
return item in self.args
def __iter__(self):
return iter(self.args)
def __add__(self, other):
if isinstance(other, Tuple):
return Tuple(*(self.args + other.args))
elif isinstance(other, tuple):
return Tuple(*(self.args + other))
else:
return NotImplemented
def __radd__(self, other):
if isinstance(other, Tuple):
return Tuple(*(other.args + self.args))
elif isinstance(other, tuple):
return Tuple(*(other + self.args))
else:
return NotImplemented
def __mul__(self, other):
try:
n = as_int(other)
except ValueError:
raise TypeError("Can't multiply sequence by non-integer of type '%s'" % type(other))
return self.func(*(self.args*n))
__rmul__ = __mul__
def __eq__(self, other):
if isinstance(other, Basic):
return super().__eq__(other)
return self.args == other
def __ne__(self, other):
if isinstance(other, Basic):
return super().__ne__(other)
return self.args != other
def __hash__(self):
return hash(self.args)
def _to_mpmath(self, prec):
return tuple(a._to_mpmath(prec) for a in self.args)
def __lt__(self, other):
return _sympify(self.args < other.args)
def __le__(self, other):
return _sympify(self.args <= other.args)
# XXX: Basic defines count() as something different, so we can't
# redefine it here. Originally this lead to cse() test failure.
def tuple_count(self, value):
"""T.count(value) -> integer -- return number of occurrences of value"""
return self.args.count(value)
def index(self, value, start=None, stop=None):
"""Searches and returns the first index of the value."""
# XXX: One would expect:
#
# return self.args.index(value, start, stop)
#
# here. Any trouble with that? Yes:
#
# >>> (1,).index(1, None, None)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: slice indices must be integers or None or have an __index__ method
#
# See: http://bugs.python.org/issue13340
if start is None and stop is None:
return self.args.index(value)
elif stop is None:
return self.args.index(value, start)
else:
return self.args.index(value, start, stop)
converter[tuple] = lambda tup: Tuple(*tup)
def tuple_wrapper(method):
"""
Decorator that converts any tuple in the function arguments into a Tuple.
The motivation for this is to provide simple user interfaces. The user can
call a function with regular tuples in the argument, and the wrapper will
convert them to Tuples before handing them to the function.
>>> from sympy.core.containers import tuple_wrapper
>>> def f(*args):
... return args
>>> g = tuple_wrapper(f)
The decorated function g sees only the Tuple argument:
>>> g(0, (1, 2), 3)
(0, (1, 2), 3)
"""
def wrap_tuples(*args, **kw_args):
newargs = []
for arg in args:
if type(arg) is tuple:
newargs.append(Tuple(*arg))
else:
newargs.append(arg)
return method(*newargs, **kw_args)
return wrap_tuples
class Dict(Basic):
"""
Wrapper around the builtin dict object
The Dict is a subclass of Basic, so that it works well in the
SymPy framework. Because it is immutable, it may be included
in sets, but its values must all be given at instantiation and
cannot be changed afterwards. Otherwise it behaves identically
to the Python dict.
>>> from sympy import Symbol
>>> from sympy.core.containers import Dict
>>> D = Dict({1: 'one', 2: 'two'})
>>> for key in D:
... if key == 1:
... print('%s %s' % (key, D[key]))
1 one
The args are sympified so the 1 and 2 are Integers and the values
are Symbols. Queries automatically sympify args so the following work:
>>> 1 in D
True
>>> D.has(Symbol('one')) # searches keys and values
True
>>> 'one' in D # not in the keys
False
>>> D[1]
one
"""
def __new__(cls, *args):
if len(args) == 1 and isinstance(args[0], (dict, Dict)):
items = [Tuple(k, v) for k, v in args[0].items()]
elif iterable(args) and all(len(arg) == 2 for arg in args):
items = [Tuple(k, v) for k, v in args]
else:
raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
elements = frozenset(items)
obj = Basic.__new__(cls, elements)
obj.elements = elements
obj._dict = dict(items) # In case Tuple decides it wants to sympify
return obj
def __getitem__(self, key):
"""x.__getitem__(y) <==> x[y]"""
try:
key = _sympify(key)
except SympifyError:
raise KeyError(key)
return self._dict[key]
def __setitem__(self, key, value):
raise NotImplementedError("SymPy Dicts are Immutable")
@property
def args(self):
"""Returns a tuple of arguments of 'self'.
See Also
========
sympy.core.basic.Basic.args
"""
return tuple(self.elements)
def items(self):
'''Returns a set-like object providing a view on dict's items.
'''
return self._dict.items()
def keys(self):
'''Returns the list of the dict's keys.'''
return self._dict.keys()
def values(self):
'''Returns the list of the dict's values.'''
return self._dict.values()
def __iter__(self):
'''x.__iter__() <==> iter(x)'''
return iter(self._dict)
def __len__(self):
'''x.__len__() <==> len(x)'''
return self._dict.__len__()
def get(self, key, default=None):
'''Returns the value for key if the key is in the dictionary.'''
try:
key = _sympify(key)
except SympifyError:
return default
return self._dict.get(key, default)
def __contains__(self, key):
'''D.__contains__(k) -> True if D has a key k, else False'''
try:
key = _sympify(key)
except SympifyError:
return False
return key in self._dict
def __lt__(self, other):
return _sympify(self.args < other.args)
@property
def _sorted_args(self):
from sympy.utilities import default_sort_key
return tuple(sorted(self.args, key=default_sort_key))
# this handles dict, defaultdict, OrderedDict
converter[dict] = lambda d: Dict(*d.items())
class OrderedSet(MutableSet):
def __init__(self, iterable=None):
if iterable:
self.map = OrderedDict((item, None) for item in iterable)
else:
self.map = OrderedDict()
def __len__(self):
return len(self.map)
def __contains__(self, key):
return key in self.map
def add(self, key):
self.map[key] = None
def discard(self, key):
self.map.pop(key)
def pop(self, last=True):
return self.map.popitem(last=last)[0]
def __iter__(self):
yield from self.map.keys()
def __repr__(self):
if not self.map:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.map.keys()))
def intersection(self, other):
result = []
for val in self:
if val in other:
result.append(val)
return self.__class__(result)
def difference(self, other):
result = []
for val in self:
if val not in other:
result.append(val)
return self.__class__(result)
def update(self, iterable):
for val in iterable:
self.add(val)
|
cc55d811d3d83daf7bb1a83e295e5073366136d2c7337f16d9dbb46ed05d5085 | """
Base class to provide str and repr hooks that `init_printing` can overwrite.
This is exposed publicly in the `printing.defaults` module,
but cannot be defined there without causing circular imports.
"""
class Printable:
"""
The default implementation of printing for SymPy classes.
This implements a hack that allows us to print elements of built-in
Python containers in a readable way. Natively Python uses ``repr()``
even if ``str()`` was explicitly requested. Mix in this trait into
a class to get proper default printing.
This also adds support for LaTeX printing in jupyter notebooks.
"""
# Note, we always use the default ordering (lex) in __str__ and __repr__,
# regardless of the global setting. See issue 5487.
def __str__(self):
from sympy.printing.str import sstr
return sstr(self, order=None)
__repr__ = __str__
def _repr_disabled(self):
"""
No-op repr function used to disable jupyter display hooks.
When :func:`sympy.init_printing` is used to disable certain display
formats, this function is copied into the appropriate ``_repr_*_``
attributes.
While we could just set the attributes to `None``, doing it this way
allows derived classes to call `super()`.
"""
return None
# We don't implement _repr_png_ here because it would add a large amount of
# data to any notebook containing SymPy expressions, without adding
# anything useful to the notebook. It can still enabled manually, e.g.,
# for the qtconsole, with init_printing().
_repr_png_ = _repr_disabled
_repr_svg_ = _repr_disabled
def _repr_latex_(self):
"""
IPython/Jupyter LaTeX printing
To change the behavior of this (e.g., pass in some settings to LaTeX),
use init_printing(). init_printing() will also enable LaTeX printing
for built in numeric types like ints and container types that contain
SymPy objects, like lists and dictionaries of expressions.
"""
from sympy.printing.latex import latex
s = latex(self, mode='plain')
return "$\\displaystyle %s$" % s
|
805ceb88f60a68ef12c54c51090d601cdbe1bb5ad268f83f40c0def6a58393bc | """Tools for setting up printing in interactive sessions. """
import sys
from distutils.version import LooseVersion as V
from io import BytesIO
from sympy import latex as default_latex
from sympy import preview
from sympy.utilities.misc import debug
from sympy.printing.defaults import Printable
def _init_python_printing(stringify_func, **settings):
"""Setup printing in Python interactive session. """
import sys
from sympy.core.compatibility import builtins
def _displayhook(arg):
"""Python's pretty-printer display hook.
This function was adapted from:
http://www.python.org/dev/peps/pep-0217/
"""
if arg is not None:
builtins._ = None
print(stringify_func(arg, **settings))
builtins._ = arg
sys.displayhook = _displayhook
def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor,
backcolor, fontsize, latex_mode, print_builtin,
latex_printer, scale, **settings):
"""Setup printing in IPython interactive session. """
try:
from IPython.lib.latextools import latex_to_png
except ImportError:
pass
# Guess best font color if none was given based on the ip.colors string.
# From the IPython documentation:
# It has four case-insensitive values: 'nocolor', 'neutral', 'linux',
# 'lightbg'. The default is neutral, which should be legible on either
# dark or light terminal backgrounds. linux is optimised for dark
# backgrounds and lightbg for light ones.
if forecolor is None:
color = ip.colors.lower()
if color == 'lightbg':
forecolor = 'Black'
elif color == 'linux':
forecolor = 'White'
else:
# No idea, go with gray.
forecolor = 'Gray'
debug("init_printing: Automatic foreground color:", forecolor)
preamble = "\\documentclass[varwidth,%s]{standalone}\n" \
"\\usepackage{amsmath,amsfonts}%s\\begin{document}"
if euler:
addpackages = '\\usepackage{euler}'
else:
addpackages = ''
if use_latex == "svg":
addpackages = addpackages + "\n\\special{color %s}" % forecolor
preamble = preamble % (fontsize, addpackages)
imagesize = 'tight'
offset = "0cm,0cm"
resolution = round(150*scale)
dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % (
imagesize, resolution, backcolor, forecolor, offset)
dvioptions = dvi.split()
svg_scale = 150/72*scale
dvioptions_svg = ["--no-fonts", "--scale={}".format(svg_scale)]
debug("init_printing: DVIOPTIONS:", dvioptions)
debug("init_printing: DVIOPTIONS_SVG:", dvioptions_svg)
debug("init_printing: PREAMBLE:", preamble)
latex = latex_printer or default_latex
def _print_plain(arg, p, cycle):
"""caller for pretty, for use in IPython 0.11"""
if _can_print(arg):
p.text(stringify_func(arg))
else:
p.text(IPython.lib.pretty.pretty(arg))
def _preview_wrapper(o):
exprbuffer = BytesIO()
try:
preview(o, output='png', viewer='BytesIO',
outputbuffer=exprbuffer, preamble=preamble,
dvioptions=dvioptions)
except Exception as e:
# IPython swallows exceptions
debug("png printing:", "_preview_wrapper exception raised:",
repr(e))
raise
return exprbuffer.getvalue()
def _svg_wrapper(o):
exprbuffer = BytesIO()
try:
preview(o, output='svg', viewer='BytesIO',
outputbuffer=exprbuffer, preamble=preamble,
dvioptions=dvioptions_svg)
except Exception as e:
# IPython swallows exceptions
debug("svg printing:", "_preview_wrapper exception raised:",
repr(e))
raise
return exprbuffer.getvalue().decode('utf-8')
def _matplotlib_wrapper(o):
# mathtext does not understand certain latex flags, so we try to
# replace them with suitable subs
o = o.replace(r'\operatorname', '')
o = o.replace(r'\overline', r'\bar')
# mathtext can't render some LaTeX commands. For example, it can't
# render any LaTeX environments such as array or matrix. So here we
# ensure that if mathtext fails to render, we return None.
try:
try:
return latex_to_png(o, color=forecolor, scale=scale)
except TypeError: # Old IPython version without color and scale
return latex_to_png(o)
except ValueError as e:
debug('matplotlib exception caught:', repr(e))
return None
# Hook methods for builtin sympy printers
printing_hooks = ('_latex', '_sympystr', '_pretty', '_sympyrepr')
def _can_print(o):
"""Return True if type o can be printed with one of the sympy printers.
If o is a container type, this is True if and only if every element of
o can be printed in this way.
"""
try:
# If you're adding another type, make sure you add it to printable_types
# later in this file as well
builtin_types = (list, tuple, set, frozenset)
if isinstance(o, builtin_types):
# If the object is a custom subclass with a custom str or
# repr, use that instead.
if (type(o).__str__ not in (i.__str__ for i in builtin_types) or
type(o).__repr__ not in (i.__repr__ for i in builtin_types)):
return False
return all(_can_print(i) for i in o)
elif isinstance(o, dict):
return all(_can_print(i) and _can_print(o[i]) for i in o)
elif isinstance(o, bool):
return False
elif isinstance(o, Printable):
# types known to sympy
return True
elif any(hasattr(o, hook) for hook in printing_hooks):
# types which add support themselves
return True
elif isinstance(o, (float, int)) and print_builtin:
return True
return False
except RuntimeError:
return False
# This is in case maximum recursion depth is reached.
# Since RecursionError is for versions of Python 3.5+
# so this is to guard against RecursionError for older versions.
def _print_latex_png(o):
"""
A function that returns a png rendered by an external latex
distribution, falling back to matplotlib rendering
"""
if _can_print(o):
s = latex(o, mode=latex_mode, **settings)
if latex_mode == 'plain':
s = '$\\displaystyle %s$' % s
try:
return _preview_wrapper(s)
except RuntimeError as e:
debug('preview failed with:', repr(e),
' Falling back to matplotlib backend')
if latex_mode != 'inline':
s = latex(o, mode='inline', **settings)
return _matplotlib_wrapper(s)
def _print_latex_svg(o):
"""
A function that returns a svg rendered by an external latex
distribution, no fallback available.
"""
if _can_print(o):
s = latex(o, mode=latex_mode, **settings)
if latex_mode == 'plain':
s = '$\\displaystyle %s$' % s
try:
return _svg_wrapper(s)
except RuntimeError as e:
debug('preview failed with:', repr(e),
' No fallback available.')
def _print_latex_matplotlib(o):
"""
A function that returns a png rendered by mathtext
"""
if _can_print(o):
s = latex(o, mode='inline', **settings)
return _matplotlib_wrapper(s)
def _print_latex_text(o):
"""
A function to generate the latex representation of sympy expressions.
"""
if _can_print(o):
s = latex(o, mode=latex_mode, **settings)
if latex_mode == 'plain':
return '$\\displaystyle %s$' % s
return s
def _result_display(self, arg):
"""IPython's pretty-printer display hook, for use in IPython 0.10
This function was adapted from:
ipython/IPython/hooks.py:155
"""
if self.rc.pprint:
out = stringify_func(arg)
if '\n' in out:
print
print(out)
else:
print(repr(arg))
import IPython
if V(IPython.__version__) >= '0.11':
# Printable is our own type, so we handle it with methods instead of
# the approach required by builtin types. This allows downstream
# packages to override the methods in their own subclasses of Printable,
# which avoids the effects of gh-16002.
printable_types = [float, tuple, list, set, frozenset, dict, int]
plaintext_formatter = ip.display_formatter.formatters['text/plain']
# Exception to the rule above: IPython has better dispatching rules
# for plaintext printing (xref ipython/ipython#8938), and we can't
# use `_repr_pretty_` without hitting a recursion error in _print_plain.
for cls in printable_types + [Printable]:
plaintext_formatter.for_type(cls, _print_plain)
svg_formatter = ip.display_formatter.formatters['image/svg+xml']
if use_latex in ('svg', ):
debug("init_printing: using svg formatter")
for cls in printable_types:
svg_formatter.for_type(cls, _print_latex_svg)
Printable._repr_svg_ = _print_latex_svg
else:
debug("init_printing: not using any svg formatter")
for cls in printable_types:
# Better way to set this, but currently does not work in IPython
#png_formatter.for_type(cls, None)
if cls in svg_formatter.type_printers:
svg_formatter.type_printers.pop(cls)
Printable._repr_svg_ = Printable._repr_disabled
png_formatter = ip.display_formatter.formatters['image/png']
if use_latex in (True, 'png'):
debug("init_printing: using png formatter")
for cls in printable_types:
png_formatter.for_type(cls, _print_latex_png)
Printable._repr_png_ = _print_latex_png
elif use_latex == 'matplotlib':
debug("init_printing: using matplotlib formatter")
for cls in printable_types:
png_formatter.for_type(cls, _print_latex_matplotlib)
Printable._repr_png_ = _print_latex_matplotlib
else:
debug("init_printing: not using any png formatter")
for cls in printable_types:
# Better way to set this, but currently does not work in IPython
#png_formatter.for_type(cls, None)
if cls in png_formatter.type_printers:
png_formatter.type_printers.pop(cls)
Printable._repr_png_ = Printable._repr_disabled
latex_formatter = ip.display_formatter.formatters['text/latex']
if use_latex in (True, 'mathjax'):
debug("init_printing: using mathjax formatter")
for cls in printable_types:
latex_formatter.for_type(cls, _print_latex_text)
Printable._repr_latex_ = _print_latex_text
else:
debug("init_printing: not using text/latex formatter")
for cls in printable_types:
# Better way to set this, but currently does not work in IPython
#latex_formatter.for_type(cls, None)
if cls in latex_formatter.type_printers:
latex_formatter.type_printers.pop(cls)
Printable._repr_latex_ = Printable._repr_disabled
else:
ip.set_hook('result_display', _result_display)
def _is_ipython(shell):
"""Is a shell instance an IPython shell?"""
# shortcut, so we don't import IPython if we don't have to
if 'IPython' not in sys.modules:
return False
try:
from IPython.core.interactiveshell import InteractiveShell
except ImportError:
# IPython < 0.11
try:
from IPython.iplib import InteractiveShell
except ImportError:
# Reaching this points means IPython has changed in a backward-incompatible way
# that we don't know about. Warn?
return False
return isinstance(shell, InteractiveShell)
# Used by the doctester to override the default for no_global
NO_GLOBAL = False
def init_printing(pretty_print=True, order=None, use_unicode=None,
use_latex=None, wrap_line=None, num_columns=None,
no_global=False, ip=None, euler=False, forecolor=None,
backcolor='Transparent', fontsize='10pt',
latex_mode='plain', print_builtin=True,
str_printer=None, pretty_printer=None,
latex_printer=None, scale=1.0, **settings):
r"""
Initializes pretty-printer depending on the environment.
Parameters
==========
pretty_print : boolean, default=True
If True, use pretty_print to stringify or the provided pretty
printer; if False, use sstrrepr to stringify or the provided string
printer.
order : string or None, default='lex'
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, default=None
If True, use unicode characters;
if False, do not use unicode characters;
if None, make a guess based on the environment.
use_latex : string, boolean, or None, default=None
If True, use default LaTeX rendering in GUI interfaces (png and
mathjax);
if False, do not use LaTeX rendering;
if None, make a guess based on the environment;
if 'png', enable latex rendering with an external latex compiler,
falling back to matplotlib if external compilation fails;
if 'matplotlib', enable LaTeX rendering with matplotlib;
if 'mathjax', enable LaTeX text generation, for example MathJax
rendering in IPython notebook or text rendering in LaTeX documents;
if 'svg', enable LaTeX rendering with an external latex compiler,
no fallback
wrap_line : boolean
If True, lines will wrap at the end; if False, they will not wrap
but continue as one line. This is only relevant if ``pretty_print`` is
True.
num_columns : int or None, default=None
If int, number of columns before wrapping is set to num_columns; if
None, number of columns before wrapping is set to terminal width.
This is only relevant if ``pretty_print`` is True.
no_global : boolean, default=False
If True, the settings become system wide;
if False, use just for this console/session.
ip : An interactive console
This can either be an instance of IPython,
or a class that derives from code.InteractiveConsole.
euler : boolean, optional, default=False
Loads the euler package in the LaTeX preamble for handwritten style
fonts (http://www.ctan.org/pkg/euler).
forecolor : string or None, optional, default=None
DVI setting for foreground color. None means that either 'Black',
'White', or 'Gray' will be selected based on a guess of the IPython
terminal color setting. See notes.
backcolor : string, optional, default='Transparent'
DVI setting for background color. See notes.
fontsize : string, optional, default='10pt'
A font size to pass to the LaTeX documentclass function in the
preamble. Note that the options are limited by the documentclass.
Consider using scale instead.
latex_mode : string, optional, default='plain'
The mode used in the LaTeX printer. Can be one of:
{'inline'|'plain'|'equation'|'equation*'}.
print_builtin : boolean, optional, default=True
If ``True`` then floats and integers will be printed. If ``False`` the
printer will only print SymPy types.
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().
scale : float, optional, default=1.0
Scale the LaTeX output when using the ``png`` or ``svg`` backends.
Useful for high dpi screens.
settings :
Any additional settings for the ``latex`` and ``pretty`` commands can
be used to fine-tune the output.
Examples
========
>>> from sympy.interactive import init_printing
>>> from sympy import Symbol, sqrt
>>> from sympy.abc import x, y
>>> sqrt(5)
sqrt(5)
>>> init_printing(pretty_print=True) # doctest: +SKIP
>>> sqrt(5) # doctest: +SKIP
___
\/ 5
>>> theta = Symbol('theta') # doctest: +SKIP
>>> init_printing(use_unicode=True) # doctest: +SKIP
>>> theta # doctest: +SKIP
\u03b8
>>> init_printing(use_unicode=False) # doctest: +SKIP
>>> theta # doctest: +SKIP
theta
>>> init_printing(order='lex') # doctest: +SKIP
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
x**2 + x + y**2 + y
>>> init_printing(order='grlex') # doctest: +SKIP
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
x**2 + x + y**2 + y
>>> init_printing(order='grevlex') # doctest: +SKIP
>>> str(y * x**2 + x * y**2) # doctest: +SKIP
x**2*y + x*y**2
>>> init_printing(order='old') # doctest: +SKIP
>>> str(x**2 + y**2 + x + y) # doctest: +SKIP
x**2 + x + y**2 + y
>>> init_printing(num_columns=10) # doctest: +SKIP
>>> x**2 + x + y**2 + y # doctest: +SKIP
x + y +
x**2 + y**2
Notes
=====
The foreground and background colors can be selected when using 'png' or
'svg' LaTeX rendering. Note that before the ``init_printing`` command is
executed, the LaTeX rendering is handled by the IPython console and not SymPy.
The colors can be selected among the 68 standard colors known to ``dvips``,
for a list see [1]_. In addition, the background color can be
set to 'Transparent' (which is the default value).
When using the 'Auto' foreground color, the guess is based on the
``colors`` variable in the IPython console, see [2]_. Hence, if
that variable is set correctly in your IPython console, there is a high
chance that the output will be readable, although manual settings may be
needed.
References
==========
.. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
.. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors
See Also
========
sympy.printing.latex
sympy.printing.pretty
"""
import sys
from sympy.printing.printer import Printer
if pretty_print:
if pretty_printer is not None:
stringify_func = pretty_printer
else:
from sympy.printing import pretty as stringify_func
else:
if str_printer is not None:
stringify_func = str_printer
else:
from sympy.printing import sstrrepr as stringify_func
# Even if ip is not passed, double check that not in IPython shell
in_ipython = False
if ip is None:
try:
ip = get_ipython()
except NameError:
pass
else:
in_ipython = (ip is not None)
if ip and not in_ipython:
in_ipython = _is_ipython(ip)
if in_ipython and pretty_print:
try:
import IPython
# IPython 1.0 deprecates the frontend module, so we import directly
# from the terminal module to prevent a deprecation message from being
# shown.
if V(IPython.__version__) >= '1.0':
from IPython.terminal.interactiveshell import TerminalInteractiveShell
else:
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
from code import InteractiveConsole
except ImportError:
pass
else:
# This will be True if we are in the qtconsole or notebook
if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \
and 'ipython-console' not in ''.join(sys.argv):
if use_unicode is None:
debug("init_printing: Setting use_unicode to True")
use_unicode = True
if use_latex is None:
debug("init_printing: Setting use_latex to True")
use_latex = True
if not NO_GLOBAL and not no_global:
Printer.set_global_settings(order=order, use_unicode=use_unicode,
wrap_line=wrap_line, num_columns=num_columns)
else:
_stringify_func = stringify_func
if pretty_print:
stringify_func = lambda expr, **settings: \
_stringify_func(expr, order=order,
use_unicode=use_unicode,
wrap_line=wrap_line,
num_columns=num_columns,
**settings)
else:
stringify_func = \
lambda expr, **settings: _stringify_func(
expr, order=order, **settings)
if in_ipython:
mode_in_settings = settings.pop("mode", None)
if mode_in_settings:
debug("init_printing: Mode is not able to be set due to internals"
"of IPython printing")
_init_ipython_printing(ip, stringify_func, use_latex, euler,
forecolor, backcolor, fontsize, latex_mode,
print_builtin, latex_printer, scale,
**settings)
else:
_init_python_printing(stringify_func, **settings)
|
d9465d06ab69fa6791950c7fb944d55cd33e503a4d7e7fa3260ce6bc818bbebf | from __future__ import print_function
from sympy.matrices.dense import MutableDenseMatrix
from sympy.polys.polytools import Poly
from sympy.polys.domains import EX
class MutablePolyDenseMatrix(MutableDenseMatrix):
"""
A mutable matrix of objects from poly module or to operate with them.
Examples
========
>>> from sympy.polys.polymatrix import PolyMatrix
>>> from sympy import Symbol, Poly, ZZ
>>> x = Symbol('x')
>>> pm1 = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(x**3, x), Poly(-1 + x, x)]])
>>> v1 = PolyMatrix([[1, 0], [-1, 0]])
>>> pm1*v1
Matrix([
[ Poly(x**2 + x, x, domain='ZZ'), Poly(0, x, domain='ZZ')],
[Poly(x**3 - x + 1, x, domain='ZZ'), Poly(0, x, domain='ZZ')]])
>>> pm1.ring
ZZ[x]
>>> v1*pm1
Matrix([
[ Poly(x**2, x, domain='ZZ'), Poly(-x, x, domain='ZZ')],
[Poly(-x**2, x, domain='ZZ'), Poly(x, x, domain='ZZ')]])
>>> pm2 = PolyMatrix([[Poly(x**2, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(1, x, domain='QQ'), \
Poly(x**3, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**3, x, domain='QQ')]])
>>> v2 = PolyMatrix([1, 0, 0, 0, 0, 0], ring=ZZ)
>>> v2.ring
ZZ
>>> pm2*v2
Matrix([[Poly(x**2, x, domain='QQ')]])
"""
_class_priority = 10
# we don't want to sympify the elements of PolyMatrix
_sympify = staticmethod(lambda x: x)
def __init__(self, *args, **kwargs):
# if any non-Poly element is given as input then
# 'ring' defaults 'EX'
ring = kwargs.get('ring', EX)
if all(isinstance(p, Poly) for p in self._mat) and self._mat:
domain = tuple([p.domain[p.gens] for p in self._mat])
ring = domain[0]
for i in range(1, len(domain)):
ring = ring.unify(domain[i])
self.ring = ring
def _eval_matrix_mul(self, other):
self_cols = self.cols
other_rows, other_cols = other.rows, other.cols
other_len = other_rows*other_cols
new_mat_rows = self.rows
new_mat_cols = other.cols
new_mat = [0]*new_mat_rows*new_mat_cols
if self.cols != 0 and other.rows != 0:
mat = self._mat
other_mat = other._mat
for i in range(len(new_mat)):
row, col = i // new_mat_cols, i % new_mat_cols
row_indices = range(self_cols*row, self_cols*(row+1))
col_indices = range(col, other_len, other_cols)
vec = (mat[a]*other_mat[b] for a,b in zip(row_indices, col_indices))
# 'Add' shouldn't be used here
new_mat[i] = sum(vec)
return self.__class__(new_mat_rows, new_mat_cols, new_mat, copy=False)
def _eval_scalar_mul(self, other):
mat = [Poly(a.as_expr()*other, *a.gens) if isinstance(a, Poly) else a*other for a in self._mat]
return self.__class__(self.rows, self.cols, mat, copy=False)
def _eval_scalar_rmul(self, other):
mat = [Poly(other*a.as_expr(), *a.gens) if isinstance(a, Poly) else other*a for a in self._mat]
return self.__class__(self.rows, self.cols, mat, copy=False)
MutablePolyMatrix = PolyMatrix = MutablePolyDenseMatrix
|
95024ae6c16aa7d32ce2d0991e927e29a9e1e0aac96914dfbcf19ecb8120f4ef | from __future__ import print_function
from operator import mul
from sympy.core.sympify import _sympify
from sympy.matrices.common import (NonInvertibleMatrixError,
NonSquareMatrixError, ShapeError)
from sympy.polys.constructor import construct_domain
class DDMError(Exception):
"""Base class for errors raised by DDM"""
pass
class DDMBadInputError(DDMError):
"""list of lists is inconsistent with shape"""
pass
class DDMDomainError(DDMError):
"""domains do not match"""
pass
class DDMShapeError(DDMError):
"""shapes are inconsistent"""
pass
class DDM(list):
"""Dense matrix based on polys domain elements
This is a list subclass and is a wrapper for a list of lists that supports
basic matrix arithmetic +, -, *, **.
"""
def __init__(self, rowslist, shape, domain):
super().__init__(rowslist)
self.shape = self.rows, self.cols = m, n = shape
self.domain = domain
if not (len(self) == m and all(len(row) == n for row in self)):
raise DDMBadInputError("Inconsistent row-list/shape")
def __str__(self):
cls = type(self).__name__
rows = list.__str__(self)
return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
def __eq__(self, other):
if not isinstance(other, DDM):
return False
return (super().__eq__(other) and self.domain == other.domain)
def __ne__(self, other):
return not self.__eq__(other)
@classmethod
def zeros(cls, shape, domain):
z = domain.zero
m, n = shape
rowslist = ([z] * n for _ in range(m))
return DDM(rowslist, shape, domain)
@classmethod
def eye(cls, size, domain):
one = domain.one
ddm = cls.zeros((size, size), domain)
for i in range(size):
ddm[i][i] = one
return ddm
def copy(self):
copyrows = (row[:] for row in self)
return DDM(copyrows, self.shape, self.domain)
def __add__(a, b):
if not isinstance(b, DDM):
return NotImplemented
return a.add(b)
def __sub__(a, b):
if not isinstance(b, DDM):
return NotImplemented
return a.sub(b)
def __neg__(a):
return a.neg()
def __mul__(a, b):
if b in a.domain:
return a.mul(b)
else:
return NotImplemented
def __matmul__(a, b):
if isinstance(b, DDM):
return a.matmul(b)
else:
return NotImplemented
@classmethod
def _check(cls, a, op, b, ashape, bshape):
if a.domain != b.domain:
msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
raise DDMDomainError(msg)
if ashape != bshape:
msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
raise DDMShapeError(msg)
def add(a, b):
"""a + b"""
a._check(a, '+', b, a.shape, b.shape)
c = a.copy()
ddm_iadd(c, b)
return c
def sub(a, b):
"""a - b"""
a._check(a, '-', b, a.shape, b.shape)
c = a.copy()
ddm_isub(c, b)
return c
def neg(a):
"""-a"""
b = a.copy()
ddm_ineg(b)
return b
def matmul(a, b):
"""a @ b (matrix product)"""
m, o = a.shape
o2, n = b.shape
a._check(a, '*', b, o, o2)
c = a.zeros((m, n), a.domain)
ddm_imatmul(c, a, b)
return c
def rref(a):
"""Reduced-row echelon form of a and list of pivots"""
b = a.copy()
pivots = ddm_irref(b)
return b, pivots
def det(a):
"""Determinant of a"""
m, n = a.shape
if m != n:
raise DDMShapeError("Determinant of non-square matrix")
b = a.copy()
K = b.domain
deta = ddm_idet(b, K)
return deta
def inv(a):
"""Inverse of a"""
m, n = a.shape
if m != n:
raise DDMShapeError("Determinant of non-square matrix")
ainv = a.copy()
K = a.domain
ddm_iinv(ainv, a, K)
return ainv
def lu(a):
"""L, U decomposition of a"""
m, n = a.shape
K = a.domain
U = a.copy()
L = a.eye(m, K)
swaps = ddm_ilu_split(L, U, K)
return L, U, swaps
def lu_solve(a, b):
"""x where a*x = b"""
m, n = a.shape
m2, o = b.shape
a._check(a, 'lu_solve', b, m, m2)
L, U, swaps = a.lu()
x = a.zeros((n, o), a.domain)
ddm_ilu_solve(x, L, U, swaps, b)
return x
def charpoly(a):
"""Coefficients of characteristic polynomial of a"""
K = a.domain
m, n = a.shape
if m != n:
raise DDMShapeError("Charpoly of non-square matrix")
vec = ddm_berk(a, K)
coeffs = [vec[i][0] for i in range(n+1)]
return coeffs
def ddm_iadd(a, b):
"""a += b"""
for ai, bi in zip(a, b):
for j, bij in enumerate(bi):
ai[j] += bij
def ddm_isub(a, b):
"""a -= b"""
for ai, bi in zip(a, b):
for j, bij in enumerate(bi):
ai[j] -= bij
def ddm_ineg(a):
"""a <-- -a"""
for ai in a:
for j, aij in enumerate(ai):
ai[j] = -aij
def ddm_imatmul(a, b, c):
"""a += b @ c"""
cT = list(zip(*c))
for bi, ai in zip(b, a):
for j, cTj in enumerate(cT):
ai[j] = sum(map(mul, bi, cTj), ai[j])
def ddm_irref(a):
"""a <-- rref(a)"""
# a is (m x n)
m = len(a)
if not m:
return []
n = len(a[0])
i = 0
pivots = []
for j in range(n):
# pivot
aij = a[i][j]
# zero-pivot
if not aij:
for ip in range(i+1, m):
aij = a[ip][j]
# row-swap
if aij:
a[i], a[ip] = a[ip], a[i]
break
else:
# next column
continue
# normalise row
ai = a[i]
for l in range(j, n):
ai[l] /= aij # ai[j] = one
# eliminate above and below to the right
for k, ak in enumerate(a):
if k == i or not ak[j]:
continue
akj = ak[j]
ak[j] -= akj # ak[j] = zero
for l in range(j+1, n):
ak[l] -= akj * ai[l]
# next row
pivots.append(j)
i += 1
# no more rows?
if i >= m:
break
return pivots
def ddm_idet(a, K):
"""a <-- echelon(a); return det"""
# Fraction-free Gaussian elimination
# https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
# a is (m x n)
m = len(a)
if not m:
return K.one
n = len(a[0])
is_field = K.is_Field
# uf keeps track of the effect of row swaps and multiplies
uf = K.one
for j in range(n-1):
# if zero on the diagonal need to swap
if not a[j][j]:
for l in range(j+1, n):
if a[l][j]:
a[j], a[l] = a[l], a[j]
uf = -uf
break
else:
# unable to swap: det = 0
return K.zero
for i in range(j+1, n):
if a[i][j]:
if not is_field:
d = K.gcd(a[j][j], a[i][j])
b = a[j][j] // d
c = a[i][j] // d
else:
b = a[j][j]
c = a[i][j]
# account for multiplying row i by b
uf = b * uf
for k in range(j+1, n):
a[i][k] = b*a[i][k] - c*a[j][k]
# triangular det is product of diagonal
prod = K.one
for i in range(n):
prod = prod * a[i][i]
# incorporate swaps and multiplies
if not is_field:
D = prod // uf
else:
D = prod / uf
return D
def ddm_iinv(ainv, a, K):
if not K.is_Field:
raise ValueError('Not a field')
# a is (m x n)
m = len(a)
if not m:
return
n = len(a[0])
if m != n:
raise NonSquareMatrixError
eye = [[K.one if i==j else K.zero for j in range(n)] for i in range(n)]
Aaug = [row + eyerow for row, eyerow in zip(a, eye)]
pivots = ddm_irref(Aaug)
if pivots != list(range(n)):
raise NonInvertibleMatrixError('Matrix det == 0; not invertible.')
ainv[:] = [row[n:] for row in Aaug]
def ddm_ilu_split(L, U, K):
"""L, U <-- LU(U)"""
m = len(U)
if not m:
return []
n = len(U[0])
swaps = ddm_ilu(U)
zeros = [K.zero] * min(m, n)
for i in range(1, m):
j = min(i, n)
L[i][:j] = U[i][:j]
U[i][:j] = zeros[:j]
return swaps
def ddm_ilu(a):
"""a <-- LU(a)"""
m = len(a)
if not m:
return []
n = len(a[0])
swaps = []
for i in range(min(m, n)):
if not a[i][i]:
for ip in range(i+1, m):
if a[ip][i]:
swaps.append((i, ip))
a[i], a[ip] = a[ip], a[i]
break
else:
# M = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]])
continue
for j in range(i+1, m):
l_ji = a[j][i] / a[i][i]
a[j][i] = l_ji
for k in range(i+1, n):
a[j][k] -= l_ji * a[i][k]
return swaps
def ddm_ilu_solve(x, L, U, swaps, b):
"""x <-- solve(L*U*x = swaps(b))"""
m = len(U)
if not m:
return
n = len(U[0])
m2 = len(b)
if not m2:
raise DDMShapeError("Shape mismtch")
o = len(b[0])
if m != m2:
raise DDMShapeError("Shape mismtch")
if m < n:
raise NotImplementedError("Underdetermined")
if swaps:
b = [row[:] for row in b]
for i1, i2 in swaps:
b[i1], b[i2] = b[i2], b[i1]
# solve Ly = b
y = [[None] * o for _ in range(m)]
for k in range(o):
for i in range(m):
rhs = b[i][k]
for j in range(i):
rhs -= L[i][j] * y[j][k]
y[i][k] = rhs
if m > n:
for i in range(n, m):
for j in range(o):
if y[i][j]:
raise NonInvertibleMatrixError
# Solve Ux = y
for k in range(o):
for i in reversed(range(n)):
if not U[i][i]:
raise NonInvertibleMatrixError
rhs = y[i][k]
for j in range(i+1, n):
rhs -= U[i][j] * x[j][k]
x[i][k] = rhs / U[i][i]
def ddm_berk(M, K):
m = len(M)
if not m:
return [[K.one]]
n = len(M[0])
if m != n:
raise DDMShapeError("Not square")
if n == 1:
return [[K.one], [-M[0][0]]]
a = M[0][0]
R = [M[0][1:]]
C = [[row[0]] for row in M[1:]]
A = [row[1:] for row in M[1:]]
q = ddm_berk(A, K)
T = [[K.zero] * n for _ in range(n+1)]
for i in range(n):
T[i][i] = K.one
T[i+1][i] = -a
for i in range(2, n+1):
if i == 2:
AnC = C
else:
C = AnC
AnC = [[K.zero] for row in C]
ddm_imatmul(AnC, A, C)
RAnC = [[K.zero]]
ddm_imatmul(RAnC, R, AnC)
for j in range(0, n+1-i):
T[i+j][j] = -RAnC[0][0]
qout = [[K.zero] for _ in range(n+1)]
ddm_imatmul(qout, T, q)
return qout
class DomainMatrix:
def __init__(self, rows, shape, domain):
self.rep = DDM(rows, shape, domain)
self.shape = shape
self.domain = domain
@classmethod
def from_ddm(cls, ddm):
return cls(ddm, ddm.shape, ddm.domain)
@classmethod
def from_list_sympy(cls, nrows, ncols, rows):
assert len(rows) == nrows
assert all(len(row) == ncols for row in rows)
items_sympy = [_sympify(item) for row in rows for item in row]
domain, items_domain = cls.get_domain(items_sympy)
domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)]
return DomainMatrix(domain_rows, (nrows, ncols), domain)
@classmethod
def get_domain(cls, items_sympy, **kwargs):
K, items_K = construct_domain(items_sympy, **kwargs)
return K, items_K
def convert_to(self, K):
Kold = self.domain
new_rows = [[K.convert_from(e, Kold) for e in row] for row in self.rep]
return DomainMatrix(new_rows, self.shape, K)
def to_field(self):
K = self.domain.get_field()
return self.convert_to(K)
def unify(self, other):
K1 = self.domain
K2 = other.domain
if K1 == K2:
return self, other
K = K1.unify(K2)
if K1 != K:
self = self.convert_to(K)
if K2 != K:
other = other.convert_to(K)
return self, other
def to_Matrix(self):
from sympy.matrices.dense import MutableDenseMatrix
rows_sympy = [[self.domain.to_sympy(e) for e in row] for row in self.rep]
return MutableDenseMatrix(rows_sympy)
def __repr__(self):
rows_str = ['[%s]' % (', '.join(map(str, row))) for row in self.rep]
rowstr = '[%s]' % ', '.join(rows_str)
return 'DomainMatrix(%s, %r, %r)' % (rowstr, self.shape, self.domain)
def __add__(A, B):
if not isinstance(B, DomainMatrix):
return NotImplemented
return A.add(B)
def __sub__(A, B):
if not isinstance(B, DomainMatrix):
return NotImplemented
return A.sub(B)
def __neg__(A):
return A.neg()
def __mul__(A, B):
"""A * B"""
if not isinstance(B, DomainMatrix):
return NotImplemented
return A.matmul(B)
def __pow__(A, n):
"""A ** n"""
if not isinstance(n, int):
return NotImplemented
return A.pow(n)
def add(A, B):
if A.shape != B.shape:
raise ShapeError("shape")
if A.domain != B.domain:
raise ValueError("domain")
return A.from_ddm(A.rep.add(B.rep))
def sub(A, B):
if A.shape != B.shape:
raise ShapeError("shape")
if A.domain != B.domain:
raise ValueError("domain")
return A.from_ddm(A.rep.sub(B.rep))
def neg(A):
return A.from_ddm(A.rep.neg())
def matmul(A, B):
return A.from_ddm(A.rep.matmul(B.rep))
def pow(A, n):
if n < 0:
raise NotImplementedError('Negative powers')
elif n == 0:
m, n = A.shape
rows = [[A.domain.zero] * m for _ in range(m)]
for i in range(m):
rows[i][i] = A.domain.one
return type(A)(rows, A.shape, A.domain)
elif n == 1:
return A
elif n % 2 == 1:
return A * A**(n - 1)
else:
sqrtAn = A ** (n // 2)
return sqrtAn * sqrtAn
def rref(self):
if not self.domain.is_Field:
raise ValueError('Not a field')
rref_ddm, pivots = self.rep.rref()
return self.from_ddm(rref_ddm), tuple(pivots)
def inv(self):
if not self.domain.is_Field:
raise ValueError('Not a field')
m, n = self.shape
if m != n:
raise NonSquareMatrixError
inv = self.rep.inv()
return self.from_ddm(inv)
def det(self):
m, n = self.shape
if m != n:
raise NonSquareMatrixError
return self.rep.det()
def lu(self):
if not self.domain.is_Field:
raise ValueError('Not a field')
L, U, swaps = self.rep.lu()
return self.from_ddm(L), self.from_ddm(U), swaps
def lu_solve(self, rhs):
if self.shape[0] != rhs.shape[0]:
raise ShapeError("Shape")
if not self.domain.is_Field:
raise ValueError('Not a field')
sol = self.rep.lu_solve(rhs.rep)
return self.from_ddm(sol)
def charpoly(self):
m, n = self.shape
if m != n:
raise NonSquareMatrixError("not square")
return self.rep.charpoly()
def __eq__(A, B):
"""A == B"""
if not isinstance(B, DomainMatrix):
return NotImplemented
return A.rep == B.rep
|
bbc53c9e43d9e1893f1f444724b7d2e6ec94fec9d332ea234a9f8ba6a905ea85 | """Sparse rational function fields. """
from __future__ import print_function, division
from typing import Any, Dict
from operator import add, mul, lt, le, gt, ge
from sympy.core.compatibility import is_sequence, reduce
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.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 : :class:`Expr` or sequence of :class:`Expr` (sympifiable)
symbols : sequence of :class:`Symbol`/:class:`Expr`
options : keyword arguments understood by :class:`Options`
Examples
========
>>> from sympy.core import symbols
>>> from sympy.functions import exp, log
>>> from sympy.polys.fields import 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: Dict[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 __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)
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 __nonzero__(f):
return bool(f.numer)
__bool__ = __nonzero__
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)
__div__ = __truediv__
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)
__rdiv__ = __rtruediv__
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
|
0b88a5000fb64fb2d64e3049e282a8527257987a86677e18214b4b62ced34c55 | """Low-level linear systems solver. """
from __future__ import print_function, division
from sympy.utilities.iterables import connected_components
from sympy.matrices import MutableDenseMatrix
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):
_sympify = staticmethod(lambda x: x)
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]:
a = s
sol.append(a)
sols = dict(zip(keys, sol))
else:
sols = {}
g = ring.gens
echelon = echelon.rep
for i, p in enumerate(pivots):
v = echelon[i][-1] - sum(echelon[i][j]*g[j] for j in range(p+1, len(g)))
sols[keys[p]] = v
return sols
|
fd389536eeda25a7286980919fb2614043108b2d54d64b95befe000f493edefb | """Computational algebraic field theory. """
from __future__ import print_function, division
from sympy import (
S, Rational, AlgebraicNumber, GoldenRatio, TribonacciConstant,
Add, Mul, sympify, Dummy, expand_mul, I, pi
)
from sympy.functions import sqrt, cbrt
from sympy.core.compatibility import reduce
from sympy.core.exprtools import Factors
from sympy.core.function import _mexpand
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.ntheory import sieve
from sympy.ntheory.factor_ import divisors
from sympy.polys.domains import ZZ, QQ
from sympy.polys.orthopolys import dup_chebyshevt
from sympy.polys.polyerrors import (
IsomorphismFailed,
CoercionFailed,
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.polytools import (
Poly, PurePoly, invert, factor_list, groebner, resultant,
degree, poly_from_expr, parallel_poly_from_expr, lcm
)
from sympy.polys.polyutils import dict_from_expr, expr_from_dict
from sympy.polys.ring_series import rs_compose_add
from sympy.polys.rings import ring
from sympy.polys.rootoftools import CRootOf
from sympy.polys.specialpolys import cyclotomic_poly
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.pycode import PythonCodePrinter, MpmathPrinter
from sympy.simplify.radsimp import _split_gcd
from sympy.simplify.simplify import _is_sum_surds
from sympy.utilities import (
numbered_symbols, variations, lambdify, public, sift
)
from mpmath import pslq, mp
def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
"""
Return a factor having root ``v``
It is assumed that one of the factors has root ``v``.
"""
if isinstance(factors[0], tuple):
factors = [f[0] for f in factors]
if len(factors) == 1:
return factors[0]
points = {x:v}
symbols = dom.symbols if hasattr(dom, 'symbols') else []
t = QQ(1, 10)
for n in range(bound**len(symbols)):
prec1 = 10
n_temp = n
for s in symbols:
points[s] = n_temp % bound
n_temp = n_temp // bound
while True:
candidates = []
eps = t**(prec1 // 2)
for f in factors:
if abs(f.as_expr().evalf(prec1, points)) < eps:
candidates.append(f)
if candidates:
factors = candidates
if len(factors) == 1:
return factors[0]
if prec1 > prec:
break
prec1 *= 2
raise NotImplementedError("multiple candidates for the minimal polynomial of %s" % v)
def _separate_sq(p):
"""
helper function for ``_minimal_polynomial_sq``
It selects a rational ``g`` such that the polynomial ``p``
consists of a sum of terms whose surds squared have gcd equal to ``g``
and a sum of terms with surds squared prime with ``g``;
then it takes the field norm to eliminate ``sqrt(g)``
See simplify.simplify.split_surds and polytools.sqf_norm.
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x
>>> from sympy.polys.numberfields import _separate_sq
>>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)
>>> p = _separate_sq(p); p
-x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8
>>> p = _separate_sq(p); p
-x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20
>>> p = _separate_sq(p); p
-x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400
"""
from sympy.utilities.iterables import sift
def is_sqrt(expr):
return expr.is_Pow and expr.exp is S.Half
# p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)]
a = []
for y in p.args:
if not y.is_Mul:
if is_sqrt(y):
a.append((S.One, y**2))
elif y.is_Atom:
a.append((y, S.One))
elif y.is_Pow and y.exp.is_integer:
a.append((y, S.One))
else:
raise NotImplementedError
continue
T, F = sift(y.args, is_sqrt, binary=True)
a.append((Mul(*F), Mul(*T)**2))
a.sort(key=lambda z: z[1])
if a[-1][1] is S.One:
# there are no surds
return p
surds = [z for y, z in a]
for i in range(len(surds)):
if surds[i] != 1:
break
g, b1, b2 = _split_gcd(*surds[i:])
a1 = []
a2 = []
for y, z in a:
if z in b1:
a1.append(y*z**S.Half)
else:
a2.append(y*z**S.Half)
p1 = Add(*a1)
p2 = Add(*a2)
p = _mexpand(p1**2) - _mexpand(p2**2)
return p
def _minimal_polynomial_sq(p, n, x):
"""
Returns the minimal polynomial for the ``nth-root`` of a sum of surds
or ``None`` if it fails.
Parameters
==========
p : sum of surds
n : positive integer
x : variable of the returned polynomial
Examples
========
>>> from sympy.polys.numberfields import _minimal_polynomial_sq
>>> from sympy import sqrt
>>> from sympy.abc import x
>>> q = 1 + sqrt(2) + sqrt(3)
>>> _minimal_polynomial_sq(q, 3, x)
x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
"""
from sympy.simplify.simplify import _is_sum_surds
p = sympify(p)
n = sympify(n)
if not n.is_Integer or not n > 0 or not _is_sum_surds(p):
return None
pn = p**Rational(1, n)
# eliminate the square roots
p -= x
while 1:
p1 = _separate_sq(p)
if p1 is p:
p = p1.subs({x:x**n})
break
else:
p = p1
# _separate_sq eliminates field extensions in a minimal way, so that
# if n = 1 then `p = constant*(minimal_polynomial(p))`
# if n > 1 it contains the minimal polynomial as a factor.
if n == 1:
p1 = Poly(p)
if p.coeff(x**p1.degree(x)) < 0:
p = -p
p = p.primitive()[1]
return p
# by construction `p` has root `pn`
# the minimal polynomial is the factor vanishing in x = pn
factors = factor_list(p)[1]
result = _choose_factor(factors, x, pn)
return result
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
"""
return the minimal polynomial for ``op(ex1, ex2)``
Parameters
==========
op : operation ``Add`` or ``Mul``
ex1, ex2 : expressions for the algebraic elements
x : indeterminate of the polynomials
dom: ground domain
mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None
Examples
========
>>> from sympy import sqrt, Add, Mul, QQ
>>> from sympy.polys.numberfields import _minpoly_op_algebraic_element
>>> from sympy.abc import x, y
>>> p1 = sqrt(sqrt(2) + 1)
>>> p2 = sqrt(sqrt(2) - 1)
>>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)
x - 1
>>> q1 = sqrt(y)
>>> q2 = 1 / y
>>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))
x**2*y**2 - 2*x*y - y**3 + 1
References
==========
.. [1] https://en.wikipedia.org/wiki/Resultant
.. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638
"Degrees of sums in a separable field extension".
"""
y = Dummy(str(x))
if mp1 is None:
mp1 = _minpoly_compose(ex1, x, dom)
if mp2 is None:
mp2 = _minpoly_compose(ex2, y, dom)
else:
mp2 = mp2.subs({x: y})
if op is Add:
# mp1a = mp1.subs({x: x - y})
if dom == QQ:
R, X = ring('X', QQ)
p1 = R(dict_from_expr(mp1)[0])
p2 = R(dict_from_expr(mp2)[0])
else:
(p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y)
r = p1.compose(p2)
mp1a = r.as_expr()
elif op is Mul:
mp1a = _muly(mp1, x, y)
else:
raise NotImplementedError('option not available')
if op is Mul or dom != QQ:
r = resultant(mp1a, mp2, gens=[y, x])
else:
r = rs_compose_add(p1, p2)
r = expr_from_dict(r.as_expr_dict(), x)
deg1 = degree(mp1, x)
deg2 = degree(mp2, y)
if op is Mul and deg1 == 1 or deg2 == 1:
# if deg1 = 1, then mp1 = x - a; mp1a = x - y - a;
# r = mp2(x - a), so that `r` is irreducible
return r
r = Poly(r, x, domain=dom)
_, factors = r.factor_list()
res = _choose_factor(factors, x, op(ex1, ex2), dom)
return res.as_expr()
def _invertx(p, x):
"""
Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``
"""
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [c * x**(n - i) for (i,), c in p1.terms()]
return Add(*a)
def _muly(p, x, y):
"""
Returns ``_mexpand(y**deg*p.subs({x:x / y}))``
"""
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [c * x**i * y**(n - i) for (i,), c in p1.terms()]
return Add(*a)
def _minpoly_pow(ex, pw, x, dom, mp=None):
"""
Returns ``minpoly(ex**pw, x)``
Parameters
==========
ex : algebraic element
pw : rational number
x : indeterminate of the polynomial
dom: ground domain
mp : minimal polynomial of ``p``
Examples
========
>>> from sympy import sqrt, QQ, Rational
>>> from sympy.polys.numberfields import _minpoly_pow, minpoly
>>> from sympy.abc import x, y
>>> p = sqrt(1 + sqrt(2))
>>> _minpoly_pow(p, 2, x, QQ)
x**2 - 2*x - 1
>>> minpoly(p**2, x)
x**2 - 2*x - 1
>>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))
x**3 - y
>>> minpoly(y**Rational(1, 3), x)
x**3 - y
"""
pw = sympify(pw)
if not mp:
mp = _minpoly_compose(ex, x, dom)
if not pw.is_rational:
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
if pw < 0:
if mp == x:
raise ZeroDivisionError('%s is zero' % ex)
mp = _invertx(mp, x)
if pw == -1:
return mp
pw = -pw
ex = 1/ex
y = Dummy(str(x))
mp = mp.subs({x: y})
n, d = pw.as_numer_denom()
res = Poly(resultant(mp, x**d - y**n, gens=[y]), x, domain=dom)
_, factors = res.factor_list()
res = _choose_factor(factors, x, ex**pw, dom)
return res.as_expr()
def _minpoly_add(x, dom, *a):
"""
returns ``minpoly(Add(*a), dom, x)``
"""
mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
p = a[0] + a[1]
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
p = p + px
return mp
def _minpoly_mul(x, dom, *a):
"""
returns ``minpoly(Mul(*a), dom, x)``
"""
mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
p = a[0] * a[1]
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
p = p * px
return mp
def _minpoly_sin(ex, x):
"""
Returns the minimal polynomial of ``sin(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
n = c.q
q = sympify(n)
if q.is_prime:
# for a = pi*p/q with q odd prime, using chebyshevt
# write sin(q*a) = mp(sin(a))*sin(a);
# the roots of mp(x) are sin(pi*p/q) for p = 1,..., q - 1
a = dup_chebyshevt(n, ZZ)
return Add(*[x**(n - i - 1)*a[i] for i in range(n)])
if c.p == 1:
if q == 9:
return 64*x**6 - 96*x**4 + 36*x**2 - 3
if n % 2 == 1:
# for a = pi*p/q with q odd, use
# sin(q*a) = 0 to see that the minimal polynomial must be
# a factor of dup_chebyshevt(n, ZZ)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a)
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
expr = ((1 - cos(2*c*pi))/2)**S.Half
res = _minpoly_compose(expr, x, QQ)
return res
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_cos(ex, x):
"""
Returns the minimal polynomial of ``cos(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
from sympy import sqrt
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
if c.p == 1:
if c.q == 7:
return 8*x**3 - 4*x**2 - 4*x + 1
if c.q == 9:
return 8*x**3 - 6*x + 1
elif c.p == 2:
q = sympify(c.q)
if q.is_prime:
s = _minpoly_sin(ex, x)
return _mexpand(s.subs({x:sqrt((1 - x)/2)}))
# for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
n = int(c.q)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a) - (-1)**c.p
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_exp(ex, x):
"""
Returns the minimal polynomial of ``exp(ex)``
"""
c, a = ex.args[0].as_coeff_Mul()
q = sympify(c.q)
if a == I*pi:
if c.is_rational:
if c.p == 1 or c.p == -1:
if q == 3:
return x**2 - x + 1
if q == 4:
return x**4 + 1
if q == 6:
return x**4 - x**2 + 1
if q == 8:
return x**8 + 1
if q == 9:
return x**6 - x**3 + 1
if q == 10:
return x**8 - x**6 + x**4 - x**2 + 1
if q.is_prime:
s = 0
for i in range(q):
s += (-x)**i
return s
# x**(2*q) = product(factors)
factors = [cyclotomic_poly(i, x) for i in divisors(2*q)]
mp = _choose_factor(factors, x, ex)
return mp
else:
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_rootof(ex, x):
"""
Returns the minimal polynomial of a ``CRootOf`` object.
"""
p = ex.expr
p = p.subs({ex.poly.gens[0]:x})
_, factors = factor_list(p, x)
result = _choose_factor(factors, x, ex)
return result
def _minpoly_compose(ex, x, dom):
"""
Computes the minimal polynomial of an algebraic element
using operations on minimal polynomials
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)
x**2 - 2*x - 1
>>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)
x**2*y**2 - 2*x*y - y**3 + 1
"""
if ex.is_Rational:
return ex.q*x - ex.p
if ex is I:
_, factors = factor_list(x**2 + 1, x, domain=dom)
return x**2 + 1 if len(factors) == 1 else x - I
if ex is GoldenRatio:
_, factors = factor_list(x**2 - x - 1, x, domain=dom)
if len(factors) == 1:
return x**2 - x - 1
else:
return _choose_factor(factors, x, (1 + sqrt(5))/2, dom=dom)
if ex is TribonacciConstant:
_, factors = factor_list(x**3 - x**2 - x - 1, x, domain=dom)
if len(factors) == 1:
return x**3 - x**2 - x - 1
else:
fac = (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
return _choose_factor(factors, x, fac, dom=dom)
if hasattr(dom, 'symbols') and ex in dom.symbols:
return x - ex
if dom.is_QQ and _is_sum_surds(ex):
# eliminate the square roots
ex -= x
while 1:
ex1 = _separate_sq(ex)
if ex1 is ex:
return ex
else:
ex = ex1
if ex.is_Add:
res = _minpoly_add(x, dom, *ex.args)
elif ex.is_Mul:
f = Factors(ex).factors
r = sift(f.items(), lambda itx: itx[0].is_Rational and itx[1].is_Rational)
if r[True] and dom == QQ:
ex1 = Mul(*[bx**ex for bx, ex in r[False] + r[None]])
r1 = dict(r[True])
dens = [y.q for y in r1.values()]
lcmdens = reduce(lcm, dens, 1)
neg1 = S.NegativeOne
expn1 = r1.pop(neg1, S.Zero)
nums = [base**(y.p*lcmdens // y.q) for base, y in r1.items()]
ex2 = Mul(*nums)
mp1 = minimal_polynomial(ex1, x)
# use the fact that in SymPy canonicalization products of integers
# raised to rational powers are organized in relatively prime
# bases, and that in ``base**(n/d)`` a perfect power is
# simplified with the root
# Powers of -1 have to be treated separately to preserve sign.
mp2 = ex2.q*x**lcmdens - ex2.p*neg1**(expn1*lcmdens)
ex2 = neg1**expn1 * ex2**Rational(1, lcmdens)
res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2)
else:
res = _minpoly_mul(x, dom, *ex.args)
elif ex.is_Pow:
res = _minpoly_pow(ex.base, ex.exp, x, dom)
elif ex.__class__ is sin:
res = _minpoly_sin(ex, x)
elif ex.__class__ is cos:
res = _minpoly_cos(ex, x)
elif ex.__class__ is exp:
res = _minpoly_exp(ex, x)
elif ex.__class__ is CRootOf:
res = _minpoly_rootof(ex, x)
else:
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
return res
@public
def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
"""
Computes the minimal polynomial of an algebraic element.
Parameters
==========
ex : Expr
Element or expression whose minimal polynomial is to be calculated.
x : Symbol, optional
Independent variable of the minimal polynomial
compose : boolean, optional (default=True)
Method to use for computing minimal polynomial. If ``compose=True``
(default) then ``_minpoly_compose`` is used, if ``compose=False`` then
groebner bases are used.
polys : boolean, optional (default=False)
If ``True`` returns a ``Poly`` object else an ``Expr`` object.
domain : Domain, optional
Ground domain
Notes
=====
By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``
are computed, then the arithmetic operations on them are performed using the resultant
and factorization.
If ``compose=False``, a bottom-up algorithm is used with ``groebner``.
The default algorithm stalls less frequently.
If no ground domain is given, it will be generated automatically from the expression.
Examples
========
>>> from sympy import minimal_polynomial, sqrt, solve, QQ
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2), x)
x**2 - 2
>>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))
x - sqrt(2)
>>> minimal_polynomial(sqrt(2) + sqrt(3), x)
x**4 - 10*x**2 + 1
>>> minimal_polynomial(solve(x**3 + x + 3)[0], x)
x**3 + x + 3
>>> minimal_polynomial(sqrt(y), x)
x**2 - y
"""
from sympy.polys.polytools import degree
from sympy.polys.domains import FractionField
from sympy.core.basic import preorder_traversal
ex = sympify(ex)
if ex.is_number:
# not sure if it's always needed but try it for numbers (issue 8354)
ex = _mexpand(ex, recursive=True)
for expr in preorder_traversal(ex):
if expr.is_AlgebraicNumber:
compose = False
break
if x is not None:
x, cls = sympify(x), Poly
else:
x, cls = Dummy('x'), PurePoly
if not domain:
if ex.free_symbols:
domain = FractionField(QQ, list(ex.free_symbols))
else:
domain = QQ
if hasattr(domain, 'symbols') and x in domain.symbols:
raise GeneratorsError("the variable %s is an element of the ground "
"domain %s" % (x, domain))
if compose:
result = _minpoly_compose(ex, x, domain)
result = result.primitive()[1]
c = result.coeff(x**degree(result, x))
if c.is_negative:
result = expand_mul(-result)
return cls(result, x, field=True) if polys else result.collect(x)
if not domain.is_QQ:
raise NotImplementedError("groebner method only works for QQ")
result = _minpoly_groebner(ex, x, cls)
return cls(result, x, field=True) if polys else result.collect(x)
def _minpoly_groebner(ex, x, cls):
"""
Computes the minimal polynomial of an algebraic number
using Groebner bases
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)
x**2 - 2*x - 1
"""
from sympy.polys.polytools import degree
from sympy.core.function import expand_multinomial
generator = numbered_symbols('a', cls=Dummy)
mapping, symbols = {}, {}
def update_mapping(ex, exp, base=None):
a = next(generator)
symbols[ex] = a
if base is not None:
mapping[ex] = a**exp + base
else:
mapping[ex] = exp.as_expr(a)
return a
def bottom_up_scan(ex):
if ex.is_Atom:
if ex is S.ImaginaryUnit:
if ex not in mapping:
return update_mapping(ex, 2, 1)
else:
return symbols[ex]
elif ex.is_Rational:
return ex
elif ex.is_Add:
return Add(*[ bottom_up_scan(g) for g in ex.args ])
elif ex.is_Mul:
return Mul(*[ bottom_up_scan(g) for g in ex.args ])
elif ex.is_Pow:
if ex.exp.is_Rational:
if ex.exp < 0:
minpoly_base = _minpoly_groebner(ex.base, x, cls)
inverse = invert(x, minpoly_base).as_expr()
base_inv = inverse.subs(x, ex.base).expand()
if ex.exp == -1:
return bottom_up_scan(base_inv)
else:
ex = base_inv**(-ex.exp)
if not ex.exp.is_Integer:
base, exp = (
ex.base**ex.exp.p).expand(), Rational(1, ex.exp.q)
else:
base, exp = ex.base, ex.exp
base = bottom_up_scan(base)
expr = base**exp
if expr not in mapping:
return update_mapping(expr, 1/exp, -base)
else:
return symbols[expr]
elif ex.is_AlgebraicNumber:
if ex.root not in mapping:
return update_mapping(ex.root, ex.minpoly)
else:
return symbols[ex.root]
raise NotAlgebraic("%s doesn't seem to be an algebraic number" % ex)
def simpler_inverse(ex):
"""
Returns True if it is more likely that the minimal polynomial
algorithm works better with the inverse
"""
if ex.is_Pow:
if (1/ex.exp).is_integer and ex.exp < 0:
if ex.base.is_Add:
return True
if ex.is_Mul:
hit = True
for p in ex.args:
if p.is_Add:
return False
if p.is_Pow:
if p.base.is_Add and p.exp > 0:
return False
if hit:
return True
return False
inverted = False
ex = expand_multinomial(ex)
if ex.is_AlgebraicNumber:
return ex.minpoly.as_expr(x)
elif ex.is_Rational:
result = ex.q*x - ex.p
else:
inverted = simpler_inverse(ex)
if inverted:
ex = ex**-1
res = None
if ex.is_Pow and (1/ex.exp).is_Integer:
n = 1/ex.exp
res = _minimal_polynomial_sq(ex.base, n, x)
elif _is_sum_surds(ex):
res = _minimal_polynomial_sq(ex, S.One, x)
if res is not None:
result = res
if res is None:
bus = bottom_up_scan(ex)
F = [x - bus] + list(mapping.values())
G = groebner(F, list(symbols.values()) + [x], order='lex')
_, factors = factor_list(G[-1])
# by construction G[-1] has root `ex`
result = _choose_factor(factors, x, ex)
if inverted:
result = _invertx(result, x)
if result.coeff(x**degree(result, x)) < 0:
result = expand_mul(-result)
return result
minpoly = minimal_polynomial
def _coeffs_generator(n):
"""Generate coefficients for `primitive_element()`. """
for coeffs in variations([1, -1, 2, -2, 3, -3], n, repetition=True):
# Two linear combinations with coeffs of opposite signs are
# opposites of each other. Hence it suffices to test only one.
if coeffs[0] > 0:
yield list(coeffs)
@public
def primitive_element(extension, x=None, **args):
"""Construct a common number field for all extensions. """
if not extension:
raise ValueError("can't compute primitive element for empty extension")
if x is not None:
x, cls = sympify(x), Poly
else:
x, cls = Dummy('x'), PurePoly
if not args.get('ex', False):
gen, coeffs = extension[0], [1]
# XXX when minimal_polynomial is extended to work
# with AlgebraicNumbers this test can be removed
if isinstance(gen, AlgebraicNumber):
g = gen.minpoly.replace(x)
else:
g = minimal_polynomial(gen, x, polys=True)
for ext in extension[1:]:
_, factors = factor_list(g, extension=ext)
g = _choose_factor(factors, x, gen)
s, _, g = g.sqf_norm()
gen += s*ext
coeffs.append(s)
if not args.get('polys', False):
return g.as_expr(), coeffs
else:
return cls(g), coeffs
generator = numbered_symbols('y', cls=Dummy)
F, Y = [], []
for ext in extension:
y = next(generator)
if ext.is_Poly:
if ext.is_univariate:
f = ext.as_expr(y)
else:
raise ValueError("expected minimal polynomial, got %s" % ext)
else:
f = minpoly(ext, y)
F.append(f)
Y.append(y)
coeffs_generator = args.get('coeffs', _coeffs_generator)
for coeffs in coeffs_generator(len(Y)):
f = x - sum([ c*y for c, y in zip(coeffs, Y)])
G = groebner(F + [f], Y + [x], order='lex', field=True)
H, g = G[:-1], cls(G[-1], x, domain='QQ')
for i, (h, y) in enumerate(zip(H, Y)):
try:
H[i] = Poly(y - h, x,
domain='QQ').all_coeffs() # XXX: composite=False
except CoercionFailed: # pragma: no cover
break # G is not a triangular set
else:
break
else: # pragma: no cover
raise RuntimeError("run out of coefficient configurations")
_, g = g.clear_denoms()
if not args.get('polys', False):
return g.as_expr(), coeffs, H
else:
return g, coeffs, H
def is_isomorphism_possible(a, b):
"""Returns `True` if there is a chance for isomorphism. """
n = a.minpoly.degree()
m = b.minpoly.degree()
if m % n != 0:
return False
if n == m:
return True
da = a.minpoly.discriminant()
db = b.minpoly.discriminant()
i, k, half = 1, m//n, db//2
while True:
p = sieve[i]
P = p**k
if P > half:
break
if ((da % p) % 2) and not (db % P):
return False
i += 1
return True
def field_isomorphism_pslq(a, b):
"""Construct field isomorphism using PSLQ algorithm. """
if not a.root.is_real or not b.root.is_real:
raise NotImplementedError("PSLQ doesn't support complex coefficients")
f = a.minpoly
g = b.minpoly.replace(f.gen)
n, m, prev = 100, b.minpoly.degree(), None
for i in range(1, 5):
A = a.root.evalf(n)
B = b.root.evalf(n)
basis = [1, B] + [ B**i for i in range(2, m) ] + [A]
dps, mp.dps = mp.dps, n
coeffs = pslq(basis, maxcoeff=int(1e10), maxsteps=1000)
mp.dps = dps
if coeffs is None:
break
if coeffs != prev:
prev = coeffs
else:
break
coeffs = [S(c)/coeffs[-1] for c in coeffs[:-1]]
while not coeffs[-1]:
coeffs.pop()
coeffs = list(reversed(coeffs))
h = Poly(coeffs, f.gen, domain='QQ')
if f.compose(h).rem(g).is_zero:
d, approx = len(coeffs) - 1, 0
for i, coeff in enumerate(coeffs):
approx += coeff*B**(d - i)
if A*approx < 0:
return [ -c for c in coeffs ]
else:
return coeffs
elif f.compose(-h).rem(g).is_zero:
return [ -c for c in coeffs ]
else:
n *= 2
return None
def field_isomorphism_factor(a, b):
"""Construct field isomorphism via factorization. """
_, factors = factor_list(a.minpoly, extension=b)
for f, _ in factors:
if f.degree() == 1:
coeffs = f.rep.TC().to_sympy_list()
d, terms = len(coeffs) - 1, []
for i, coeff in enumerate(coeffs):
terms.append(coeff*b.root**(d - i))
root = Add(*terms)
if (a.root - root).evalf(chop=True) == 0:
return coeffs
if (a.root + root).evalf(chop=True) == 0:
return [-c for c in coeffs]
return None
@public
def field_isomorphism(a, b, **args):
"""Construct an isomorphism between two number fields. """
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
if a == b:
return a.coeffs()
n = a.minpoly.degree()
m = b.minpoly.degree()
if n == 1:
return [a.root]
if m % n != 0:
return None
if args.get('fast', True):
try:
result = field_isomorphism_pslq(a, b)
if result is not None:
return result
except NotImplementedError:
pass
return field_isomorphism_factor(a, b)
@public
def to_number_field(extension, theta=None, **args):
"""Express `extension` in the field generated by `theta`. """
gen = args.get('gen')
if hasattr(extension, '__iter__'):
extension = list(extension)
else:
extension = [extension]
if len(extension) == 1 and type(extension[0]) is tuple:
return AlgebraicNumber(extension[0])
minpoly, coeffs = primitive_element(extension, gen, polys=True)
root = sum([ coeff*ext for coeff, ext in zip(coeffs, extension) ])
if theta is None:
return AlgebraicNumber((minpoly, root))
else:
theta = sympify(theta)
if not theta.is_AlgebraicNumber:
theta = AlgebraicNumber(theta, gen=gen)
coeffs = field_isomorphism(root, theta)
if coeffs is not None:
return AlgebraicNumber(theta, coeffs)
else:
raise IsomorphismFailed(
"%s is not in a subfield of %s" % (root, theta.root))
class IntervalPrinter(MpmathPrinter, LambdaPrinter):
"""Use ``lambda`` printer but print numbers as ``mpi`` intervals. """
def _print_Integer(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr)
def _print_Rational(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
def _print_Half(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
def _print_Pow(self, expr):
return super(MpmathPrinter, self)._print_Pow(expr, rational=True)
@public
def isolate(alg, eps=None, fast=False):
"""Give a rational isolating interval for an algebraic number. """
alg = sympify(alg)
if alg.is_Rational:
return (alg, alg)
elif not alg.is_real:
raise NotImplementedError(
"complex algebraic numbers are not supported")
func = lambdify((), alg, modules="mpmath", printer=IntervalPrinter())
poly = minpoly(alg, polys=True)
intervals = poly.intervals(sqf=True)
dps, done = mp.dps, False
try:
while not done:
alg = func()
for a, b in intervals:
if a <= alg.a and alg.b <= b:
done = True
break
else:
mp.dps *= 2
finally:
mp.dps = dps
if eps is not None:
a, b = poly.refine_root(a, b, eps=eps, fast=fast)
return (a, b)
|
6732d67b99280489f3066711ef699876aa021739f1bcaea9d5292bd9fabf5ea8 | from sympy.vector.coordsysrect import CoordSys3D, CoordSysCartesian
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.parametricregion import (ParametricRegion, parametric_region_list)
from sympy.vector.implicitregion import ImplicitRegion
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', 'CoordSysCartesian',
'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',
]
|
da63b1f841a69779d8df0e7ca09db237d7315efa06de4fef1d1a970e6c710834 | from sympy import S, Rational, gcd, sqrt, sign, symbols, Complement
from sympy.core import Basic, Tuple, diff, expand, Eq, Integer
from sympy.core.compatibility import ordered
from sympy.core.symbol import _symbol
from sympy.solvers import solveset, nonlinsolve, diophantine
from sympy.polys import total_degree
from sympy.geometry import Point
from sympy.ntheory.factor_ import core
class ImplicitRegion(Basic):
"""
Represents an implicit region in space.
Example
=======
>>> from sympy import Eq
>>> from sympy.abc import x, y, z, t
>>> from sympy.vector import ImplicitRegion
>>> ImplicitRegion((x, y), x**2 + y**2 - 4)
ImplicitRegion((x, y), x**2 + y**2 - 4)
>>> ImplicitRegion((x, y), Eq(y*x, 1))
ImplicitRegion((x, y), x*y - 1)
>>> parabola = ImplicitRegion((x, y), y**2 - 4*x)
>>> parabola.degree
2
>>> parabola.equation
-4*x + y**2
>>> parabola.rational_parametrization(t)
(4/t**2, 4/t)
>>> r = ImplicitRegion((x, y, z), Eq(z, x**2 + y**2))
>>> r.variables
(x, y, z)
>>> r.singular_points()
FiniteSet((0, 0, 0))
>>> r.regular_point()
(-10, -10, 200)
Parameters
==========
variables: tuple to map variables in implicit equation to base scalars.
equation: An expression or Eq denoting the implicit equation of the region.
"""
def __new__(cls, variables, equation):
if not isinstance(variables, Tuple):
variables = Tuple(*variables)
if isinstance(equation, Eq):
equation = equation.lhs - equation.rhs
return super().__new__(cls, variables, equation)
@property
def variables(self):
return self.args[0]
@property
def equation(self):
return self.args[1]
@property
def degree(self):
return total_degree(self.equation)
def regular_point(self):
"""
Returns a point on the implicit region.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.vector import ImplicitRegion
>>> circle = ImplicitRegion((x, y), (x + 2)**2 + (y - 3)**2 - 16)
>>> circle.regular_point()
(-2, -1)
>>> parabola = ImplicitRegion((x, y), x**2 - 4*y)
>>> parabola.regular_point()
(0, 0)
>>> r = ImplicitRegion((x, y, z), (x + y + z)**4)
>>> r.regular_point()
(-10, -10, 20)
References
=========
- Erik Hillgarter, "Rational Points on Conics", Diploma Thesis, RISC-Linz,
J. Kepler Universitat Linz, 1996. Availaible:
https://www3.risc.jku.at/publications/download/risc_1355/Rational%20Points%20on%20Conics.pdf
"""
equation = self.equation
if len(self.variables) == 1:
return (list(solveset(equation, self.variables[0], domain=S.Reals))[0],)
elif len(self.variables) == 2:
if self.degree == 2:
coeffs = a, b, c, d, e, f = conic_coeff(self.variables, equation)
if b**2 == 4*a*c:
x_reg, y_reg = self._regular_point_parabola(*coeffs)
else:
x_reg, y_reg = self._regular_point_ellipse(*coeffs)
return x_reg, y_reg
if len(self.variables) == 3:
x, y, z = self.variables
for x_reg in range(-10, 10):
for y_reg in range(-10, 10):
if not solveset(equation.subs({x: x_reg, y: y_reg}), self.variables[2], domain=S.Reals).is_empty:
return (x_reg, y_reg, list(solveset(equation.subs({x: x_reg, y: y_reg})))[0])
if len(self.singular_points()) != 0:
return list[self.singular_points()][0]
raise NotImplementedError()
def _regular_point_parabola(self, a, b, c, d, e, f):
ok = (a, d) != (0, 0) and (c, e) != (0, 0) and b**2 == 4*a*c and (a, c) != (0, 0)
if not ok:
raise ValueError("Rational Point on the conic does not exist")
if a != 0:
d_dash, f_dash = (4*a*e - 2*b*d, 4*a*f - d**2)
if d_dash != 0:
y_reg = -f_dash/d_dash
x_reg = -(d + b*y_reg)/(2*a)
else:
ok = False
elif c != 0:
d_dash, f_dash = (4*c*d - 2*b*e, 4*c*f - e**2)
if d_dash != 0:
x_reg = -f_dash/d_dash
y_reg = -(e + b*x_reg)/(2*c)
else:
ok = False
if ok:
return x_reg, y_reg
else:
raise ValueError("Rational Point on the conic does not exist")
def _regular_point_ellipse(self, a, b, c, d, e, f):
D = 4*a*c - b**2
ok = D
if not ok:
raise ValueError("Rational Point on the conic does not exist")
if a == 0 and c == 0:
K = -1
L = 4*(d*e - b*f)
elif c != 0:
K = D
L = 4*c**2*d**2 - 4*b*c*d*e + 4*a*c*e**2 + 4*b**2*c*f - 16*a*c**2*f
else:
K = D
L = 4*a**2*e**2 - 4*b*a*d*e + 4*b**2*a*f
ok = L != 0 and not(K > 0 and L < 0)
if not ok:
raise ValueError("Rational Point on the conic does not exist")
K = Rational(K).limit_denominator(10**12)
L = Rational(L).limit_denominator(10**12)
k1, k2 = K.p, K.q
l1, l2 = L.p, L.q
g = gcd(k2, l2)
a1 = (l2*k2)/g
b1 = (k1*l2)/g
c1 = -(l1*k2)/g
a2 = sign(a1)*core(abs(a1), 2)
r1 = sqrt(a1/a2)
b2 = sign(b1)*core(abs(b1), 2)
r2 = sqrt(b1/b2)
c2 = sign(c1)*core(abs(c1), 2)
r3 = sqrt(c1/c2)
g = gcd(gcd(a2, b2), c2)
a2 = a2/g
b2 = b2/g
c2 = c2/g
g1 = gcd(a2, b2)
a2 = a2/g1
b2 = b2/g1
c2 = c2*g1
g2 = gcd(a2,c2)
a2 = a2/g2
b2 = b2*g2
c2 = c2/g2
g3 = gcd(b2, c2)
a2 = a2*g3
b2 = b2/g3
c2 = c2/g3
x, y, z = symbols("x y z")
eq = a2*x**2 + b2*y**2 + c2*z**2
solutions = diophantine(eq)
if len(solutions) == 0:
raise ValueError("Rational Point on the conic does not exist")
flag = False
for sol in solutions:
syms = Tuple(*sol).free_symbols
rep = {s: 3 for s in syms}
sol_z = sol[2]
if sol_z == 0:
flag = True
continue
if not (isinstance(sol_z, Integer) or isinstance(sol_z, int)):
syms_z = sol_z.free_symbols
if len(syms_z) == 1:
p = next(iter(syms_z))
p_values = Complement(S.Integers, solveset(Eq(sol_z, 0), p, S.Integers))
rep[p] = next(iter(p_values))
if len(syms_z) == 2:
p, q = list(ordered(syms_z))
for i in S.Integers:
subs_sol_z = sol_z.subs(p, i)
q_values = Complement(S.Integers, solveset(Eq(subs_sol_z, 0), q, S.Integers))
if not q_values.is_empty:
rep[p] = i
rep[q] = next(iter(q_values))
break
if len(syms) != 0:
x, y, z = tuple(s.subs(rep) for s in sol)
else:
x, y, z = sol
flag = False
break
if flag:
raise ValueError("Rational Point on the conic does not exist")
x = (x*g3)/r1
y = (y*g2)/r2
z = (z*g1)/r3
x = x/z
y = y/z
if a == 0 and c == 0:
x_reg = (x + y - 2*e)/(2*b)
y_reg = (x - y - 2*d)/(2*b)
elif c != 0:
x_reg = (x - 2*d*c + b*e)/K
y_reg = (y - b*x_reg - e)/(2*c)
else:
y_reg = (x - 2*e*a + b*d)/K
x_reg = (y - b*y_reg - d)/(2*a)
return x_reg, y_reg
def singular_points(self):
"""
Returns a set of singular points of the region.
The singular points are those points on the region
where all partial derivatives vanish.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.vector import ImplicitRegion
>>> I = ImplicitRegion((x, y), (y-1)**2 -x**3 + 2*x**2 -x)
>>> I.singular_points()
FiniteSet((1, 1))
"""
eq_list = [self.equation]
for var in self.variables:
eq_list += [diff(self.equation, var)]
return nonlinsolve(eq_list, list(self.variables))
def multiplicity(self, point):
"""
Returns the multiplicity of a singular point on the region.
A singular point (x,y) of region is said to be of multiplicity m
if all the partial derivatives off to order m - 1 vanish there.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.vector import ImplicitRegion
>>> I = ImplicitRegion((x, y, z), x**2 + y**3 - z**4)
>>> I.singular_points()
FiniteSet((0, 0, 0))
>>> I.multiplicity((0, 0, 0))
2
"""
if isinstance(point, Point):
point = point.args
modified_eq = self.equation
for i, var in enumerate(self.variables):
modified_eq = modified_eq.subs(var, var + point[i])
modified_eq = expand(modified_eq)
if len(modified_eq.args) != 0:
terms = modified_eq.args
m = min([total_degree(term) for term in terms])
else:
terms = modified_eq
m = total_degree(terms)
return m
def rational_parametrization(self, parameters=('t', 's'), reg_point=None):
"""
Returns the rational parametrization of implict region.
Examples
========
>>> from sympy import Eq
>>> from sympy.abc import x, y, z, s, t
>>> from sympy.vector import ImplicitRegion
>>> parabola = ImplicitRegion((x, y), y**2 - 4*x)
>>> parabola.rational_parametrization()
(4/t**2, 4/t)
>>> circle = ImplicitRegion((x, y), Eq(x**2 + y**2, 4))
>>> circle.rational_parametrization()
(4*t/(t**2 + 1), 4*t**2/(t**2 + 1) - 2)
>>> I = ImplicitRegion((x, y), x**3 + x**2 - y**2)
>>> I.rational_parametrization()
(t**2 - 1, t*(t**2 - 1))
>>> cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2)
>>> cubic_curve.rational_parametrization(parameters=(t))
(t**2 - 1, t*(t**2 - 1))
>>> sphere = ImplicitRegion((x, y, z), x**2 + y**2 + z**2 - 4)
>>> sphere.rational_parametrization(parameters=(t, s))
(-2 + 4/(s**2 + t**2 + 1), 4*s/(s**2 + t**2 + 1), 4*t/(s**2 + t**2 + 1))
For some conics, regular_points() is unable to find a point on curve.
To calulcate the parametric representation in such cases, user need
to determine a point on the region and pass it using reg_point.
>>> c = ImplicitRegion((x, y), (x - 1/2)**2 + (y)**2 - (1/4)**2)
>>> c.rational_parametrization(reg_point=(3/4, 0))
(0.75 - 0.5/(t**2 + 1), -0.5*t/(t**2 + 1))
References
=========
- Christoph M. Hoffmann, "Conversion Methods between Parametric and
Implicit Curves and Surfaces", Purdue e-Pubs, 1990. Available:
https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1827&context=cstech
"""
equation = self.equation
degree = self.degree
if degree == 1:
if len(self.variables) == 1:
return (equation,)
elif len(self.variables) == 2:
x, y = self.variables
y_par = list(solveset(equation, y))[0]
return x, y_par
else:
raise NotImplementedError()
point = ()
# Finding the (n - 1) fold point of the monoid of degree
if degree == 2:
# For degree 2 curves, either a regular point or a singular point can be used.
if reg_point is not None:
# Using point provided by the user as regular point
if isinstance(point, Point):
point = point.args
point = reg_point
else:
if len(self.singular_points()) != 0:
point = list(self.singular_points())[0]
else:
point = self.regular_point()
if len(self.singular_points()) != 0:
singular_points = self.singular_points()
for spoint in singular_points:
syms = Tuple(*spoint).free_symbols
rep = {s: 2 for s in syms}
if len(syms) != 0:
spoint = tuple(s.subs(rep) for s in spoint)
if self.multiplicity(spoint) == degree - 1:
point = spoint
break
if len(point) == 0:
# The region in not a monoid
raise NotImplementedError()
modified_eq = equation
# Shifting the region such that fold point moves to origin
for i, var in enumerate(self.variables):
modified_eq = modified_eq.subs(var, var + point[i])
modified_eq = expand(modified_eq)
hn = hn_1 = 0
for term in modified_eq.args:
if total_degree(term) == degree:
hn += term
else:
hn_1 += term
hn_1 = -1*hn_1
if not isinstance(parameters, tuple):
parameters = (parameters,)
if len(self.variables) == 2:
parameter1 = parameters[0]
if parameter1 == 's':
# To avoid name conflict between parameters
s = _symbol('s_', real=True)
else:
s = _symbol('s', real=True)
t = _symbol(parameter1, real=True)
hn = hn.subs({self.variables[0]: s, self.variables[1]: t})
hn_1 = hn_1.subs({self.variables[0]: s, self.variables[1]: t})
x_par = (s*(hn_1/hn)).subs(s, 1) + point[0]
y_par = (t*(hn_1/hn)).subs(s, 1) + point[1]
return x_par, y_par
elif len(self.variables) == 3:
parameter1, parameter2 = parameters
if parameter1 == 'r' or parameter2 == 'r':
# To avoid name conflict between parameters
r = _symbol('r_', real=True)
else:
r = _symbol('r', real=True)
s = _symbol(parameter2, real=True)
t = _symbol(parameter1, real=True)
hn = hn.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t})
hn_1 = hn_1.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t})
x_par = (r*(hn_1/hn)).subs(r, 1) + point[0]
y_par = (s*(hn_1/hn)).subs(r, 1) + point[1]
z_par = (t*(hn_1/hn)).subs(r, 1) + point[2]
return x_par, y_par, z_par
raise NotImplementedError()
def conic_coeff(variables, equation):
if total_degree(equation) != 2:
raise ValueError()
x = variables[0]
y = variables[1]
equation = expand(equation)
a = equation.coeff(x**2)
b = equation.coeff(x*y)
c = equation.coeff(y**2)
d = equation.coeff(x, 1).coeff(y, 0)
e = equation.coeff(y, 1).coeff(x, 0)
f = equation.coeff(x, 0).coeff(y, 0)
return a, b, c, d, e, f
|
47c9ffc0a9a0b9f940f795b5d81def118867335a8cf459a3356970de52f56236 | from __future__ import division, print_function
from contextlib import contextmanager
from threading import local
from sympy.core.function import expand_mul
from sympy.simplify.simplify import dotprodsimp as _dotprodsimp
class DotProdSimpState(local):
def __init__(self):
self.state = False
_dotprodsimp_state = DotProdSimpState()
@contextmanager
def dotprodsimp(x):
old = _dotprodsimp_state.state
try:
_dotprodsimp_state.state = x
yield
finally:
_dotprodsimp_state.state = old
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 overriden 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
|
abca347c2f5bca773dadf338873bac2233c1308d38b368cedb6f242dd68055e8 | """A module that handles matrices.
Includes functions for fast creating matrices like zero, one/eye, random
matrix, etc.
"""
from .common import ShapeError, NonSquareMatrixError
from .dense import (
GramSchmidt, casoratian, diag, eye, hessian, jordan_cell,
list2numpy, matrix2numpy, matrix_multiply_elementwise, ones,
randMatrix, rot_axis1, rot_axis2, rot_axis3, symarray, wronskian,
zeros)
from .dense import MutableDenseMatrix
from .matrices import DeferredVector, MatrixBase
Matrix = MutableMatrix = MutableDenseMatrix
from .sparse import MutableSparseMatrix
from .sparsetools import banded
from .immutable import ImmutableDenseMatrix, ImmutableSparseMatrix
ImmutableMatrix = ImmutableDenseMatrix
SparseMatrix = MutableSparseMatrix
from .expressions import (
MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity,
Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace,
Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint,
hadamard_product, HadamardProduct, HadamardPower, Determinant, det,
diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace,
DotProduct, kronecker_product, KroneckerProduct,
PermutationMatrix, MatrixPermute, MatrixSet)
from .utilities import dotprodsimp
__all__ = [
'ShapeError', 'NonSquareMatrixError',
'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell',
'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones',
'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray',
'wronskian', 'zeros',
'MutableDenseMatrix',
'DeferredVector', 'MatrixBase',
'Matrix', 'MutableMatrix',
'MutableSparseMatrix',
'banded',
'ImmutableDenseMatrix', 'ImmutableSparseMatrix',
'ImmutableMatrix', 'SparseMatrix',
'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix',
'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr',
'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix',
'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint',
'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant',
'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix',
'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product',
'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'MatrixSet',
'dotprodsimp',
]
|
01dd54affabf2e44e1f8bcf67bf0bc78bdbc278badfc54d27120aa8be7854dac | """
Basic methods common to all matrices to be used
when creating more advanced matrices (e.g., matrices over rings,
etc.).
"""
from sympy.core.logic import FuzzyBool
from collections import defaultdict
from inspect import isfunction
from sympy.assumptions.refine import refine
from sympy.core import SympifyError, Add
from sympy.core.basic import Atom
from sympy.core.compatibility import (
Iterable, as_int, is_sequence, reduce)
from sympy.core.decorators import call_highest_priority
from sympy.core.logic import fuzzy_and
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions import Abs
from sympy.polys.polytools import Poly
from sympy.simplify import simplify as _simplify
from sympy.simplify.simplify import dotprodsimp as _dotprodsimp
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import filldedent
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 combintion 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,
lambda i, j: entry(i, j))
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,
lambda i, j: entry(i, j))
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,
lambda i, j: entry(i, j))
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
sympy.matrices.dense.MutableDenseMatrix.col_op
sympy.matrices.dense.MutableDenseMatrix.col_swap
col_del
col_join
col_insert
"""
return self[:, j]
def extract(self, rowsList, colsList):
"""Return a submatrix by specifying a list of rows and columns.
Negative indices can be given. All indices must be in the range
-n <= 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.matrices 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
sympy.matrices.dense.MutableDenseMatrix.row_op
sympy.matrices.dense.MutableDenseMatrix.row_swap
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.matrices 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 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.matrices 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):
def entry(i, j):
return cls.one if i == j else cls.zero
return cls._new(rows, cols, entry)
@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):
def entry(i, j):
return cls.zero
return cls._new(rows, cols, entry)
@classmethod
def diag(kls, *args, **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.matrices 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.matrices 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.sparse import SparseMatrix
klass = kwargs.get('cls', kls)
strict = kwargs.get('strict', False) # lists -> Matrices
unpack = kwargs.get('unpack', True) # unpack single sequence
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
rows = kwargs.get('rows', None)
cols = kwargs.get('cols', None)
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
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, **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.
.. note::
This feature will be deprecated in the future.
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
=====
.. note::
This feature will be deprecated in the future.
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:
SymPyDeprecationWarning(
feature="Keyword arguments 'rows' or 'cols'",
issue=16102,
useinstead="a more generic banded matrix constructor",
deprecated_since_version="1.4"
).warn()
klass = kwargs.pop('cls', kls)
band = kwargs.pop('band', 'upper')
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
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)
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.matrices 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.matrices 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 wouldn't
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.matrices 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.matrices 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.matrices 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.matrices 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.matrices 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.matrices 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
from sympy.functions.elementary.complexes import re, im
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.matrices import SparseMatrix
>>> from sympy import 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.matrices 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.matrices 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.matrices 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 sin, cos
>>> from sympy.matrices import SparseMatrix
>>> 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.matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.subs(x, y)
Matrix([[y]])
>>> Matrix(_).subs(y, x)
Matrix([[x]])
"""
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.matrices 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 import trigsimp
return self.applyfunc(lambda x: trigsimp(x, **opts))
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):
from sympy import Mod
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 don't match."""
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('__rdiv__')
def __div__(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.matrices 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.matrices 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)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return self.__div__(other)
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):
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 don't 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))
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 type(j) is not 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__))
|
73aec4d6aadb954865e6f169d90038945db3e14beee90c5eb60a1ab9f5016ab8 | import mpmath as mp
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.compatibility import (
Callable, NotIterable, as_int, is_sequence)
from sympy.core.decorators import deprecated
from sympy.core.expr import Expr
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
from sympy.core.sympify import _sympify
from sympy.functions import exp, factorial, log
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.polys import cancel
from sympy.printing import sstr
from sympy.printing.defaults import Printable
from sympy.simplify import simplify as _simplify
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import filldedent
from .common import (
MatrixCommon, MatrixError, NonSquareMatrixError, NonInvertibleMatrixError,
ShapeError)
from .utilities import _iszero, _is_zero_after_expand_mul
from .determinant import (
_find_reasonable_pivot, _find_reasonable_pivot_naive,
_adjugate, _charpoly, _cofactor, _cofactor_matrix,
_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,
_QRdecomposition)
from .graph import _connected_components, _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 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__
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 doesn't have a {} '{}'".format(error_str, col))
elif op == "n<->m":
# we need two cols to swap. It doesn't 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 doesn't have a {} '{}'".format(error_str, col1))
if not 0 <= col2 < self_cols:
raise ValueError("This matrix doesn't 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 doesn't have a {} '{}'".format(error_str, col))
if not 0 <= col2 < self_cols:
raise ValueError("This matrix doesn't 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)
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.matrices 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 import Derivative
kwargs.setdefault('evaluate', True)
deriv = Derivative(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 _accept_eval_derivative(self, s):
return s._visit_eval_derivative_array(self)
def _visit_eval_derivative_scalar(self, base):
# Types are (base: scalar, self: matrix)
return self.applyfunc(lambda x: base.diff(x))
def _visit_eval_derivative_array(self, base):
# Types are (base: array/matrix, self: matrix)
from sympy import derive_by_array
return derive_by_array(base, self)
def integrate(self, *args, **kwargs):
"""Integrate each element of the matrix. ``args`` will
be passed to the ``integrate`` function.
Examples
========
>>> from sympy.matrices 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.matrices 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')
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
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
from sympy import binomial
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 self.rows == 0 or self.cols == 0:
return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
return "Matrix(%s)" % str(self.tolist())
def _format_str(self, printer=None):
if not printer:
from sympy.printing.str import StrPrinter
printer = StrPrinter()
# Handle zero dimensions:
if self.rows == 0 or self.cols == 0:
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]])
"""
from sympy.core.compatibility import as_int
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.sparse import SparseMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.utilities.iterables import reshape
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]._mat
# 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()._mat
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 do(x):
# make Block and Symbol explicit
if isinstance(x, (list, tuple)):
return type(x)([do(i) for i in x])
if isinstance(x, BlockMatrix) or \
isinstance(x, MatrixSymbol) and \
all(_.is_Integer for _ in x.shape):
return x.as_explicit()
return x
dat = do(dat)
if dat == [] or dat == [[]]:
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(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 type(i) is slice or type(j) is 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._mat)
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) and not isinstance(b, 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) :
SymPyDeprecationWarning(
feature="Dot product of non row/column vectors",
issue=13815,
deprecated_since_version="1.2",
useinstead="* to take matrix products").warn()
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 import LeviCivita
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
"""
from sympy import diff
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
from sympy import re
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 self.rows == 1 or self.cols == 1:
if ord == 2 or ord is 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.matrices 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
>>> from sympy.printing.str import 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 self.rows == 0 or self.cols == 0:
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 QRdecomposition(self):
return _QRdecomposition(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)
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__
QRdecomposition.__doc__ = _QRdecomposition.__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__
@deprecated(
issue=15109,
useinstead="from sympy.matrices.common import classof",
deprecated_since_version="1.3")
def classof(A, B):
from sympy.matrices.common import classof as classof_
return classof_(A, B)
@deprecated(
issue=15109,
deprecated_since_version="1.3",
useinstead="from sympy.matrices.common import a2idx")
def a2idx(j, n=None):
from sympy.matrices.common import a2idx as a2idx_
return a2idx_(j, n)
|
9d80c564ae9db53eca8a020ccdb010144a982688997de87a6ccef4a95e951b0c | from types import FunctionType
from collections import Counter
from mpmath import mp, workprec
from mpmath.libmp.libmpf import prec_to_dps
from sympy.core.compatibility 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
from sympy.simplify import nsimplify, simplify as _simplify
from sympy.utilities.exceptions import SymPyDeprecationWarning
from .common import MatrixError, NonSquareMatrixError
from .determinant import _find_reasonable_pivot
from .utilities import _iszero
def _eigenvals_triangular(M, multiple=False):
"""A fast decision for eigenvalues of an upper or a lower triangular
matrix.
"""
diagonal_entries = [M[i, i] for i in range(M.rows)]
if multiple:
return diagonal_entries
return dict(Counter(diagonal_entries))
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 functions 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"""Return eigenvalues using the Berkowitz agorithm to compute
the characteristic polynomial.
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.matrices 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$
"""
if not M:
if multiple:
return []
return {}
if not M.is_square:
raise NonSquareMatrixError("{} must be a square matrix.".format(M))
if M.is_upper or M.is_lower:
return _eigenvals_triangular(M, multiple=multiple)
if all(x.is_number for x in M) and M.has(Float):
return _eigenvals_mpmath(M, multiple=multiple)
if rational:
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)
def _eigenvals_list(
M, error_when_incomplete=True, simplify=False, **flags):
iblocks = M.connected_components()
all_eigs = []
for b in iblocks:
block = M[b, b]
if isinstance(simplify, FunctionType):
charpoly = block.charpoly(simplify=simplify)
else:
charpoly = block.charpoly()
eigs = roots(charpoly, multiple=True, **flags)
if error_when_incomplete:
if len(eigs) != block.rows:
raise MatrixError(
"Could not compute eigenvalues for {}. if you see this "
"error, please report to SymPy issue tracker."
.format(block))
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.connected_components()
all_eigs = {}
for b in iblocks:
block = M[b, b]
if isinstance(simplify, FunctionType):
charpoly = block.charpoly(simplify=simplify)
else:
charpoly = block.charpoly()
eigs = roots(charpoly, multiple=False, **flags)
if error_when_incomplete:
if sum(eigs.values()) != block.rows:
raise MatrixError(
"Could not compute eigenvalues for {}. if you see this "
"error, please report to SymPy issue tracker."
.format(block))
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
# This functions is a candidate for caching if it gets implemented for matrices.
def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, **flags):
"""Return list of triples (eigenval, multiplicity, eigenspace).
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.matrices 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)
chop = flags.pop('chop', False)
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)
M = M.applyfunc(lambda x: nsimplify(x, rational=True))
eigenvals = M.eigenvals(
rational=False, error_when_incomplete=error_when_incomplete,
**flags)
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))
if primitive:
# if the primitive flag is set, get rid of any common
# integer denominators
def denom_clean(l):
from sympy import gcd
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:
SymPyDeprecationWarning(
feature='clear_cache',
deprecated_since_version=1.4,
issue=15887
).warn()
if 'clear_subproducts' in kwargs:
SymPyDeprecationWarning(
feature='clear_subproducts',
deprecated_since_version=1.4,
issue=15887
).warn()
if not M.is_square:
return False
if all(e.is_real for e in M) and M.is_symmetric():
return True
if all(e.is_complex for e in M) and M.is_hermitian:
return True
return _is_diagonalizable_with_eigen(M, reals_only=reals_only)[0]
#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)
$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. Algorith 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
2. Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization
"""
if type(upper) is not bool:
raise ValueError("upper must be a boolean")
if not upper:
X = _bidiagonal_decmp_hholder(M.H)
return X[2].H, X[1].H, X[0].H
return _bidiagonal_decmp_hholder(M)
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. Algorith 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
2. Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization
"""
if type(upper) is not bool:
raise ValueError("upper must be a boolean")
if not upper:
return _eval_bidiag_hholder(M.H).H
return _eval_bidiag_hholder(M)
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.matrices 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
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, **kwargs):
"""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.matrices 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")
chop = kwargs.pop('chop', False)
mat = M
has_floats = M.has(Float)
if has_floats:
try:
max_prec = max(term._prec for term in M._mat 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:
mat = mat.applyfunc(lambda x: nsimplify(x, rational=True))
# first calculate the jordan block structure
eigs = mat.eigenvals()
# make sure that we found all the roots by counting
# the algebraic multiplicity
if sum(m for m in eigs.values()) != mat.cols:
raise MatrixError("Could not compute eigenvalues for {}".format(mat))
# 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.matrices 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
|
af38c32224bed4463735d96867b58a9bf5056a37781fd33fdbd4cc41065f68f3 | from __future__ import print_function, division
from functools import reduce
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.numbers import oo, Integer
from sympy.core.relational import Eq
from sympy.core.singleton import Singleton, S
from sympy.core.symbol import Dummy, symbols, Symbol
from sympy.core.sympify import _sympify, sympify, converter
from sympy.logic.boolalg import And
from sympy.sets.sets import (Set, Interval, Union, FiniteSet,
ProductSet)
from sympy.utilities.misc import filldedent
from sympy.utilities.iterables import cartes
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
if other.is_Number:
return other.is_Rational
return other.is_rational
def __iter__(self):
from sympy.core.numbers import igcd, Rational
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
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):
from sympy.functions.elementary.integers import floor
return And(Eq(floor(x), x), x >= self.inf, x < oo)
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 as_relational(self, x):
from sympy.functions.elementary.integers import floor
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
"""
def __new__(cls):
return Interval.__new__(cls, S.NegativeInfinity, S.Infinity)
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.sets.sets import FiniteSet, Interval
>>> from sympy.sets.fancysets import ImageSet
>>> 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)
FiniteSet(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)
FiniteSet(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 cartes(*self.base_sets)))
return self
class Range(Set):
"""
Represents a range of integers. Can be called as Range(stop),
Range(start, stop), or Range(start, stop, step); when stop is
not given it defaults to 1.
`Range(stop)` is the same as `Range(0, stop, 1)` and the stop value
(juse 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 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 + 17}
"""
is_iterable = True
def __new__(cls, *args):
from sympy.functions.elementary.integers import ceiling
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:
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)):
if start == stop:
null = True
else:
end = stop
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:
end = start + 1
step = S.One # make it a canonical single 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):
_ = self.size # validate
if not self:
return self
return self.func(
self.stop - self.step, self.start - self.step, -self.step)
def _contains(self, other):
if not self:
return S.false
if other.is_infinite:
return S.false
if not other.is_integer:
return other.is_integer
if self.has(Symbol):
try:
_ = self.size # validate
except ValueError:
return
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 self.size == 1:
return Eq(other, self[0])
res = (ref - other) % self.step
if res == S.Zero:
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):
if self.has(Symbol):
_ = self.size # validate
if self.start in [S.NegativeInfinity, S.Infinity]:
raise TypeError("Cannot iterate over Range with infinite start")
elif self:
i = self.start
step = self.step
while True:
if (step > 0 and not (self.start <= i < self.stop)) or \
(step < 0 and not (self.stop < i <= self.start)):
break
yield i
i += step
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 not self:
return S.Zero
dif = self.stop - self.start
if self.has(Symbol):
if dif.has(Symbol) or self.step.has(Symbol) or (
not self.start.is_integer and not self.stop.is_integer):
raise ValueError('invalid method for symbolic range')
if dif.is_infinite:
return S.Infinity
return Integer(abs(dif//self.step))
@property
def is_finite_set(self):
if self.start.is_integer and self.stop.is_integer:
return True
return self.size.is_finite
def __nonzero__(self):
return self.start != self.stop
__bool__ = __nonzero__
def __getitem__(self, i):
from sympy.functions.elementary.integers import ceiling
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
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 not self:
raise IndexError('Range index out of range')
if i == 0:
if self.start.is_infinite:
raise ValueError(ooslice)
if self.has(Symbol):
if (self.stop > self.start) == self.step.is_positive and self.step.is_positive is not None:
pass
else:
_ = self.size # validate
return self.start
if i == -1:
if self.stop.is_infinite:
raise ValueError(ooslice)
n = self.stop - self.step
if n.is_Integer or (
n.is_integer and (
(n - self.start).is_nonnegative ==
self.step.is_positive)):
return n
_ = self.size # validate
rv = (self.stop if i < 0 else self.start) + i*self.step
if rv.is_infinite:
raise ValueError(ooslice)
if rv < self.inf or rv > self.sup:
raise IndexError("Range index out of range")
return rv
@property
def _inf(self):
if not self:
raise NotImplementedError
if self.has(Symbol):
if self.step.is_positive:
return self[0]
elif self.step.is_negative:
return self[-1]
_ = self.size # validate
if self.step > 0:
return self.start
else:
return self.stop - self.step
@property
def _sup(self):
if not self:
raise NotImplementedError
if self.has(Symbol):
if self.step.is_positive:
return self[-1]
elif self.step.is_negative:
return self[0]
_ = self.size # validate
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. """
from sympy.functions.elementary.integers import floor
if self.size == 1:
return Eq(x, self[0])
else:
return And(
Eq(x, floor(x)),
x >= self.inf if self.inf in self else x > self.inf,
x <= self.sup if self.sup in self else x < self.sup)
converter[range] = lambda r: Range(r.start, r.stop, r.step)
def normalize_theta_set(theta):
"""
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))
FiniteSet(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):
"""
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, & use the flag polar=True.
Z = {z in C | z = r*[cos(theta) + I*sin(theta)], r in [r], theta in [theta]}
* Rectangular Form
Input is in the form of the ProductSet or Union of ProductSets
of interval of x and y the of the Complex numbers in a Plane.
Default input type is in rectangular form.
Z = {z in C | z = x + I*y, x in [Re(z)], y in [Im(z)]}
Examples
========
>>> from sympy.sets.fancysets import ComplexRegion
>>> from sympy.sets import Interval
>>> from sympy import S, I, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 6)
>>> c = Interval(1, 8)
>>> 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.
>>> 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
@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), FiniteSet(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
from sympy.core.containers import Tuple
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) and not isinstance(other, 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):
"""
Set representing a square region of the complex plane.
Z = {z in C | z = x + I*y, x in [Re(z)], y in [Im(z)]}
Examples
========
>>> from sympy.sets.fancysets import ComplexRegion
>>> from sympy.sets.sets import Interval
>>> from sympy import I
>>> 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):
"""
Set representing a polar region of the complex plane.
Z = {z in C | z = r*[cos(theta) + I*sin(theta)], r in [r], theta in [theta]}
Examples
========
>>> from sympy.sets.fancysets import ComplexRegion, Interval
>>> from sympy import 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):
from sympy.functions.elementary.trigonometric import sin, cos
r, theta = self.variables
return r*(cos(theta) + S.ImaginaryUnit*sin(theta))
class Complexes(CartesianComplexRegion, metaclass=Singleton):
"""
The 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)
def __str__(self):
return "S.Complexes"
def __repr__(self):
return "S.Complexes"
|
5fecaf57786964841d08e93da96f1ed481a0896c4a76d7d2f120f8227df153df | from __future__ import unicode_literals
from sympy import (S, Symbol, Interval, exp, Or,
symbols, Eq, cos, And, Tuple, integrate, oo, sin, Sum, Basic, Indexed,
DiracDelta, Lambda, log, pi, FallingFactorial, Rational, Matrix)
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)
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, ignore_warnings
from sympy.external import import_module
from sympy.core.numbers import comp
from sympy.stats.frv_types import BernoulliDistribution
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)) == set((X,))
assert set(random_symbols(2*X + Y)) == set((X, Y))
assert set(random_symbols(2*X + Y.symbol)) == set((X,))
assert set(random_symbols(2)) == set()
def test_characteristic_function():
# Imports I from sympy
from sympy 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')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X)) in [1, 2, 3, 4, 5, 6]
assert isinstance(next(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))
@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, finite=True)
z = Symbol('z', real=True, finite=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(1, 2)
assert a.foo == 1
assert a.bar == 2
raises(AttributeError, lambda: a.baz)
class Bar(Basic, NamedArgsMixin):
pass
raises(AttributeError, lambda: Bar(1, 2).foo)
def test_density_constant():
assert density(3)(2) == 0
assert density(3)(3) == DiracDelta(0)
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
|
e9bb50144f7d29e264885a1162deceab4eddd90634c4578109e14d5e44743f29 | from sympy import (FiniteSet, S, Symbol, sqrt, nan, beta, Rational, symbols,
simplify, Eq, cos, And, Tuple, Or, Dict, sympify, binomial,
cancel, exp, I, Piecewise, Sum, Dummy)
from sympy.external import import_module
from sympy.matrices import Matrix
from sympy.stats import (DiscreteUniform, Die, Bernoulli, Coin, Binomial, BetaBinomial,
Hypergeometric, Rademacher, P, E, variance, covariance, skewness,
sample, density, where, FiniteRV, pspace, cdf, correlation, moment,
cmoment, smoment, characteristic_function, moment_generating_function,
quantile, kurtosis, median, coskewness)
from sympy.stats.frv_types import DieDistribution, BinomialDistribution, \
HypergeometricDistribution
from sympy.stats.rv import Density
from sympy.testing.pytest import raises, skip, ignore_warnings
def BayesTest(A, B):
assert P(A, B) == P(And(A, B)) / P(B)
assert P(A, B) == P(B, A) * P(A) / P(B)
def test_discreteuniform():
# Symbolic
a, b, c, t = symbols('a b c t')
X = DiscreteUniform('X', [a, b, c])
assert E(X) == (a + b + c)/3
assert simplify(variance(X)
- ((a**2 + b**2 + c**2)/3 - (a/3 + b/3 + c/3)**2)) == 0
assert P(Eq(X, a)) == P(Eq(X, b)) == P(Eq(X, c)) == S('1/3')
Y = DiscreteUniform('Y', range(-5, 5))
# Numeric
assert E(Y) == S('-1/2')
assert variance(Y) == S('33/4')
assert median(Y) == FiniteSet(-1, 0)
for x in range(-5, 5):
assert P(Eq(Y, x)) == S('1/10')
assert P(Y <= x) == S(x + 6)/10
assert P(Y >= x) == S(5 - x)/10
assert dict(density(Die('D', 6)).items()) == \
dict(density(DiscreteUniform('U', range(1, 7))).items())
assert characteristic_function(X)(t) == exp(I*a*t)/3 + exp(I*b*t)/3 + exp(I*c*t)/3
assert moment_generating_function(X)(t) == exp(a*t)/3 + exp(b*t)/3 + exp(c*t)/3
# issue 18611
raises(ValueError, lambda: DiscreteUniform('Z', [a, a, a, b, b, c]))
def test_dice():
# TODO: Make iid method!
X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6)
a, b, t, p = symbols('a b t p')
assert E(X) == 3 + S.Half
assert variance(X) == Rational(35, 12)
assert E(X + Y) == 7
assert E(X + X) == 7
assert E(a*X + b) == a*E(X) + b
assert variance(X + Y) == variance(X) + variance(Y) == cmoment(X + Y, 2)
assert variance(X + X) == 4 * variance(X) == cmoment(X + X, 2)
assert cmoment(X, 0) == 1
assert cmoment(4*X, 3) == 64*cmoment(X, 3)
assert covariance(X, Y) is S.Zero
assert covariance(X, X + Y) == variance(X)
assert density(Eq(cos(X*S.Pi), 1))[True] == S.Half
assert correlation(X, Y) == 0
assert correlation(X, Y) == correlation(Y, X)
assert smoment(X + Y, 3) == skewness(X + Y)
assert smoment(X + Y, 4) == kurtosis(X + Y)
assert smoment(X, 0) == 1
assert P(X > 3) == S.Half
assert P(2*X > 6) == S.Half
assert P(X > Y) == Rational(5, 12)
assert P(Eq(X, Y)) == P(Eq(X, 1))
assert E(X, X > 3) == 5 == moment(X, 1, 0, X > 3)
assert E(X, Y > 3) == E(X) == moment(X, 1, 0, Y > 3)
assert E(X + Y, Eq(X, Y)) == E(2*X)
assert moment(X, 0) == 1
assert moment(5*X, 2) == 25*moment(X, 2)
assert quantile(X)(p) == Piecewise((nan, (p > 1) | (p < 0)),\
(S.One, p <= Rational(1, 6)), (S(2), p <= Rational(1, 3)), (S(3), p <= S.Half),\
(S(4), p <= Rational(2, 3)), (S(5), p <= Rational(5, 6)), (S(6), p <= 1))
assert P(X > 3, X > 3) is S.One
assert P(X > Y, Eq(Y, 6)) is S.Zero
assert P(Eq(X + Y, 12)) == Rational(1, 36)
assert P(Eq(X + Y, 12), Eq(X, 6)) == Rational(1, 6)
assert density(X + Y) == density(Y + Z) != density(X + X)
d = density(2*X + Y**Z)
assert d[S(22)] == Rational(1, 108) and d[S(4100)] == Rational(1, 216) and S(3130) not in d
assert pspace(X).domain.as_boolean() == Or(
*[Eq(X.symbol, i) for i in [1, 2, 3, 4, 5, 6]])
assert where(X > 3).set == FiniteSet(4, 5, 6)
assert characteristic_function(X)(t) == exp(6*I*t)/6 + exp(5*I*t)/6 + exp(4*I*t)/6 + exp(3*I*t)/6 + exp(2*I*t)/6 + exp(I*t)/6
assert moment_generating_function(X)(t) == exp(6*t)/6 + exp(5*t)/6 + exp(4*t)/6 + exp(3*t)/6 + exp(2*t)/6 + exp(t)/6
assert median(X) == FiniteSet(3, 4)
D = Die('D', 7)
assert median(D) == FiniteSet(4)
# Bayes test for die
BayesTest(X > 3, X + Y < 5)
BayesTest(Eq(X - Y, Z), Z > Y)
BayesTest(X > 3, X > 2)
# arg test for die
raises(ValueError, lambda: Die('X', -1)) # issue 8105: negative sides.
raises(ValueError, lambda: Die('X', 0))
raises(ValueError, lambda: Die('X', 1.5)) # issue 8103: non integer sides.
# symbolic test for die
n, k = symbols('n, k', positive=True)
D = Die('D', n)
dens = density(D).dict
assert dens == Density(DieDistribution(n))
assert set(dens.subs(n, 4).doit().keys()) == set([1, 2, 3, 4])
assert set(dens.subs(n, 4).doit().values()) == set([Rational(1, 4)])
k = Dummy('k', integer=True)
assert E(D).dummy_eq(
Sum(Piecewise((k/n, k <= n), (0, True)), (k, 1, n)))
assert variance(D).subs(n, 6).doit() == Rational(35, 12)
ki = Dummy('ki')
cumuf = cdf(D)(k)
assert cumuf.dummy_eq(
Sum(Piecewise((1/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, k)))
assert cumuf.subs({n: 6, k: 2}).doit() == Rational(1, 3)
t = Dummy('t')
cf = characteristic_function(D)(t)
assert cf.dummy_eq(
Sum(Piecewise((exp(ki*I*t)/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, n)))
assert cf.subs(n, 3).doit() == exp(3*I*t)/3 + exp(2*I*t)/3 + exp(I*t)/3
mgf = moment_generating_function(D)(t)
assert mgf.dummy_eq(
Sum(Piecewise((exp(ki*t)/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, n)))
assert mgf.subs(n, 3).doit() == exp(3*t)/3 + exp(2*t)/3 + exp(t)/3
def test_given():
X = Die('X', 6)
assert density(X, X > 5) == {S(6): S.One}
assert where(X > 2, X > 5).as_boolean() == Eq(X.symbol, 6)
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X, X > 5)) == 6
def test_domains():
X, Y = Die('x', 6), Die('y', 6)
x, y = X.symbol, Y.symbol
# Domains
d = where(X > Y)
assert d.condition == (x > y)
d = where(And(X > Y, Y > 3))
assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y, 4)), And(Eq(x, 6),
Eq(y, 5)), And(Eq(x, 6), Eq(y, 4)))
assert len(d.elements) == 3
assert len(pspace(X + Y).domain.elements) == 36
Z = Die('x', 4)
raises(ValueError, lambda: P(X > Z)) # Two domains with same internal symbol
assert pspace(X + Y).domain.set == FiniteSet(1, 2, 3, 4, 5, 6)**2
assert where(X > 3).set == FiniteSet(4, 5, 6)
assert X.pspace.domain.dict == FiniteSet(
*[Dict({X.symbol: i}) for i in range(1, 7)])
assert where(X > Y).dict == FiniteSet(*[Dict({X.symbol: i, Y.symbol: j})
for i in range(1, 7) for j in range(1, 7) if i > j])
def test_bernoulli():
p, a, b, t = symbols('p a b t')
X = Bernoulli('B', p, a, b)
assert E(X) == a*p + b*(-p + 1)
assert density(X)[a] == p
assert density(X)[b] == 1 - p
assert characteristic_function(X)(t) == p * exp(I * a * t) + (-p + 1) * exp(I * b * t)
assert moment_generating_function(X)(t) == p * exp(a * t) + (-p + 1) * exp(b * t)
X = Bernoulli('B', p, 1, 0)
z = Symbol("z")
assert E(X) == p
assert simplify(variance(X)) == p*(1 - p)
assert E(a*X + b) == a*E(X) + b
assert simplify(variance(a*X + b)) == simplify(a**2 * variance(X))
assert quantile(X)(z) == Piecewise((nan, (z > 1) | (z < 0)), (0, z <= 1 - p), (1, z <= 1))
Y = Bernoulli('Y', Rational(1, 2))
assert median(Y) == FiniteSet(0, 1)
Z = Bernoulli('Z', Rational(2, 3))
assert median(Z) == FiniteSet(1)
raises(ValueError, lambda: Bernoulli('B', 1.5))
raises(ValueError, lambda: Bernoulli('B', -0.5))
#issue 8248
assert X.pspace.compute_expectation(1) == 1
p = Rational(1, 5)
X = Binomial('X', 5, p)
Y = Binomial('Y', 7, 2*p)
Z = Binomial('Z', 9, 3*p)
assert coskewness(Y + Z, X + Y, X + Z).simplify() == 0
assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y).simplify() == \
sqrt(1529)*Rational(12, 16819)
assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y, X < 2).simplify() \
== -sqrt(357451121)*Rational(2812, 4646864573)
def test_cdf():
D = Die('D', 6)
o = S.One
assert cdf(
D) == sympify({1: o/6, 2: o/3, 3: o/2, 4: 2*o/3, 5: 5*o/6, 6: o})
def test_coins():
C, D = Coin('C'), Coin('D')
H, T = symbols('H, T')
assert P(Eq(C, D)) == S.Half
assert density(Tuple(C, D)) == {(H, H): Rational(1, 4), (H, T): Rational(1, 4),
(T, H): Rational(1, 4), (T, T): Rational(1, 4)}
assert dict(density(C).items()) == {H: S.Half, T: S.Half}
F = Coin('F', Rational(1, 10))
assert P(Eq(F, H)) == Rational(1, 10)
d = pspace(C).domain
assert d.as_boolean() == Or(Eq(C.symbol, H), Eq(C.symbol, T))
raises(ValueError, lambda: P(C > D)) # Can't intelligently compare H to T
def test_binomial_verify_parameters():
raises(ValueError, lambda: Binomial('b', .2, .5))
raises(ValueError, lambda: Binomial('b', 3, 1.5))
def test_binomial_numeric():
nvals = range(5)
pvals = [0, Rational(1, 4), S.Half, Rational(3, 4), 1]
for n in nvals:
for p in pvals:
X = Binomial('X', n, p)
assert E(X) == n*p
assert variance(X) == n*p*(1 - p)
if n > 0 and 0 < p < 1:
assert skewness(X) == (1 - 2*p)/sqrt(n*p*(1 - p))
assert kurtosis(X) == 3 + (1 - 6*p*(1 - p))/(n*p*(1 - p))
for k in range(n + 1):
assert P(Eq(X, k)) == binomial(n, k)*p**k*(1 - p)**(n - k)
def test_binomial_quantile():
X = Binomial('X', 50, S.Half)
assert quantile(X)(0.95) == S(31)
assert median(X) == FiniteSet(25)
X = Binomial('X', 5, S.Half)
p = Symbol("p", positive=True)
assert quantile(X)(p) == Piecewise((nan, p > S.One), (S.Zero, p <= Rational(1, 32)),\
(S.One, p <= Rational(3, 16)), (S(2), p <= S.Half), (S(3), p <= Rational(13, 16)),\
(S(4), p <= Rational(31, 32)), (S(5), p <= S.One))
assert median(X) == FiniteSet(2, 3)
def test_binomial_symbolic():
n = 2
p = symbols('p', positive=True)
X = Binomial('X', n, p)
t = Symbol('t')
assert simplify(E(X)) == n*p == simplify(moment(X, 1))
assert simplify(variance(X)) == n*p*(1 - p) == simplify(cmoment(X, 2))
assert cancel((skewness(X) - (1 - 2*p)/sqrt(n*p*(1 - p)))) == 0
assert cancel((kurtosis(X)) - (3 + (1 - 6*p*(1 - p))/(n*p*(1 - p)))) == 0
assert characteristic_function(X)(t) == p ** 2 * exp(2 * I * t) + 2 * p * (-p + 1) * exp(I * t) + (-p + 1) ** 2
assert moment_generating_function(X)(t) == p ** 2 * exp(2 * t) + 2 * p * (-p + 1) * exp(t) + (-p + 1) ** 2
# Test ability to change success/failure winnings
H, T = symbols('H T')
Y = Binomial('Y', n, p, succ=H, fail=T)
assert simplify(E(Y) - (n*(H*p + T*(1 - p)))) == 0
# test symbolic dimensions
n = symbols('n')
B = Binomial('B', n, p)
raises(NotImplementedError, lambda: P(B > 2))
assert density(B).dict == Density(BinomialDistribution(n, p, 1, 0))
assert set(density(B).dict.subs(n, 4).doit().keys()) == \
set([S.Zero, S.One, S(2), S(3), S(4)])
assert set(density(B).dict.subs(n, 4).doit().values()) == \
set([(1 - p)**4, 4*p*(1 - p)**3, 6*p**2*(1 - p)**2, 4*p**3*(1 - p), p**4])
k = Dummy('k', integer=True)
assert E(B > 2).dummy_eq(
Sum(Piecewise((k*p**k*(1 - p)**(-k + n)*binomial(n, k), (k >= 0)
& (k <= n) & (k > 2)), (0, True)), (k, 0, n)))
def test_beta_binomial():
# verify parameters
raises(ValueError, lambda: BetaBinomial('b', .2, 1, 2))
raises(ValueError, lambda: BetaBinomial('b', 2, -1, 2))
raises(ValueError, lambda: BetaBinomial('b', 2, 1, -2))
assert BetaBinomial('b', 2, 1, 1)
# test numeric values
nvals = range(1,5)
alphavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10]
betavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10]
for n in nvals:
for a in alphavals:
for b in betavals:
X = BetaBinomial('X', n, a, b)
assert E(X) == moment(X, 1)
assert variance(X) == cmoment(X, 2)
# test symbolic
n, a, b = symbols('a b n')
assert BetaBinomial('x', n, a, b)
n = 2 # Because we're using for loops, can't do symbolic n
a, b = symbols('a b', positive=True)
X = BetaBinomial('X', n, a, b)
t = Symbol('t')
assert E(X).expand() == moment(X, 1).expand()
assert variance(X).expand() == cmoment(X, 2).expand()
assert skewness(X) == smoment(X, 3)
assert characteristic_function(X)(t) == exp(2*I*t)*beta(a + 2, b)/beta(a, b) +\
2*exp(I*t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b)
assert moment_generating_function(X)(t) == exp(2*t)*beta(a + 2, b)/beta(a, b) +\
2*exp(t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b)
def test_hypergeometric_numeric():
for N in range(1, 5):
for m in range(0, N + 1):
for n in range(1, N + 1):
X = Hypergeometric('X', N, m, n)
N, m, n = map(sympify, (N, m, n))
assert sum(density(X).values()) == 1
assert E(X) == n * m / N
if N > 1:
assert variance(X) == n*(m/N)*(N - m)/N*(N - n)/(N - 1)
# Only test for skewness when defined
if N > 2 and 0 < m < N and n < N:
assert skewness(X) == simplify((N - 2*m)*sqrt(N - 1)*(N - 2*n)
/ (sqrt(n*m*(N - m)*(N - n))*(N - 2)))
def test_hypergeometric_symbolic():
N, m, n = symbols('N, m, n')
H = Hypergeometric('H', N, m, n)
dens = density(H).dict
expec = E(H > 2)
assert dens == Density(HypergeometricDistribution(N, m, n))
assert dens.subs(N, 5).doit() == Density(HypergeometricDistribution(5, m, n))
assert set(dens.subs({N: 3, m: 2, n: 1}).doit().keys()) == set([S.Zero, S.One])
assert set(dens.subs({N: 3, m: 2, n: 1}).doit().values()) == set([Rational(1, 3), Rational(2, 3)])
k = Dummy('k', integer=True)
assert expec.dummy_eq(
Sum(Piecewise((k*binomial(m, k)*binomial(N - m, -k + n)
/binomial(N, n), k > 2), (0, True)), (k, 0, n)))
def test_rademacher():
X = Rademacher('X')
t = Symbol('t')
assert E(X) == 0
assert variance(X) == 1
assert density(X)[-1] == S.Half
assert density(X)[1] == S.Half
assert characteristic_function(X)(t) == exp(I*t)/2 + exp(-I*t)/2
assert moment_generating_function(X)(t) == exp(t) / 2 + exp(-t) / 2
def test_FiniteRV():
F = FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)})
p = Symbol("p", positive=True)
assert dict(density(F).items()) == {S.One: S.Half, S(2): Rational(1, 4), S(3): Rational(1, 4)}
assert P(F >= 2) == S.Half
assert quantile(F)(p) == Piecewise((nan, p > S.One), (S.One, p <= S.Half),\
(S(2), p <= Rational(3, 4)),(S(3), True))
assert pspace(F).domain.as_boolean() == Or(
*[Eq(F.symbol, i) for i in [1, 2, 3]])
assert F.pspace.domain.set == FiniteSet(1, 2, 3)
raises(ValueError, lambda: FiniteRV('F', {1: S.Half, 2: S.Half, 3: S.Half}))
raises(ValueError, lambda: FiniteRV('F', {1: S.Half, 2: Rational(-1, 2), 3: S.One}))
raises(ValueError, lambda: FiniteRV('F', {1: S.One, 2: Rational(3, 2), 3: S.Zero,\
4: Rational(-1, 2), 5: Rational(-3, 4), 6: Rational(-1, 4)}))
def test_density_call():
from sympy.abc import p
x = Bernoulli('x', p)
d = density(x)
assert d(0) == 1 - p
assert d(S.Zero) == 1 - p
assert d(5) == 0
assert 0 in d
assert 5 not in d
assert d(S.Zero) == d[S.Zero]
def test_DieDistribution():
from sympy.abc import x
X = DieDistribution(6)
assert X.pmf(S.Half) is S.Zero
assert X.pmf(x).subs({x: 1}).doit() == Rational(1, 6)
assert X.pmf(x).subs({x: 7}).doit() == 0
assert X.pmf(x).subs({x: -1}).doit() == 0
assert X.pmf(x).subs({x: Rational(1, 3)}).doit() == 0
raises(ValueError, lambda: X.pmf(Matrix([0, 0])))
raises(ValueError, lambda: X.pmf(x**2 - 1))
def test_FinitePSpace():
X = Die('X', 6)
space = pspace(X)
assert space.density == DieDistribution(6)
def test_symbolic_conditions():
B = Bernoulli('B', Rational(1, 4))
D = Die('D', 4)
b, n = symbols('b, n')
Y = P(Eq(B, b))
Z = E(D > n)
assert Y == \
Piecewise((Rational(1, 4), Eq(b, 1)), (0, True)) + \
Piecewise((Rational(3, 4), Eq(b, 0)), (0, True))
assert Z == \
Piecewise((Rational(1, 4), n < 1), (0, True)) + Piecewise((S.Half, n < 2), (0, True)) + \
Piecewise((Rational(3, 4), n < 3), (0, True)) + Piecewise((S.One, n < 4), (0, True))
def test_sample_numpy():
distribs_numpy = [
Binomial("B", 5, 0.4),
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Die("D"), library='numpy')))
raises(NotImplementedError,
lambda: Die("D").pspace.sample(library='tensorflow'))
def test_sample_scipy():
distribs_scipy = [
FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}),
DiscreteUniform("Y", list(range(5))),
Die("D"),
Bernoulli("Be", 0.3),
Binomial("Bi", 5, 0.4),
BetaBinomial("Bb", 2, 1, 1),
Hypergeometric("H", 1, 1, 1),
Rademacher("R")
]
size = 3
numsamples = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
h_sample = list(sample(Hypergeometric("H", 1, 1, 1), size=size, numsamples=numsamples))
assert len(h_sample) == numsamples
for X in distribs_scipy:
samps = next(sample(X, size=size))
samps2 = next(sample(X, size=(2, 2)))
for sam in samps:
assert sam in X.pspace.domain.set
for i in range(2):
for j in range(2):
assert samps2[i][j] in X.pspace.domain.set
def test_sample_pymc3():
distribs_pymc3 = [
Bernoulli('B', 0.2),
Binomial('N', 5, 0.4)
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Die("D"), library='pymc3')))
|
6a41b983f0493c4f4e1ed858a8565d33ced1fdd91b28fc111269257e65fe3f6f | from sympy import (symbols, pi, oo, S, exp, sqrt, besselk, Indexed, Sum, simplify,
Rational, factorial, gamma, Piecewise, Eq, Product, Interval,
IndexedBase, RisingFactorial, polar_lift, ProductSet, Range)
from sympy.core.numbers import comp
from sympy.integrals.integrals import integrate
from sympy.matrices import Matrix, MatrixSymbol
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, ignore_warnings, skip
from sympy.external import import_module
x, y, z, a, b = symbols('x y z a b')
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])
raises (ValueError,\
lambda: Normal('M',[1, 2], [[0, 0], [0, 1]]))
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(-2/y - 1/(2*x))/(2*pi*sqrt(x*y))
raises (ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]]))
# symbolic
n = symbols('n', natural=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
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*24**(-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])/(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))
def test_JointPSpace_marginal_distribution():
T = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2)
assert marginal_distribution(T, T[1])(x) == sqrt(2)*(x**2 + 2)/(
8*polar_lift(x**2/2 + 1)**Rational(5, 2))
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:
with ignore_warnings(UserWarning):
for X in distribs_numpy:
samps = next(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: next(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:
with ignore_warnings(UserWarning):
for X in distribs_scipy:
samps = next(sample(X, size=size))
samps2 = next(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: next(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:
with ignore_warnings(UserWarning):
for X in distribs_pymc3:
samps = next(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: next(sample(N_c, library='pymc3')))
|
2399a56c49f71d09e5ea9e72fa0da10dc2ea2b777cc5713da360cc908cd51b62 | from sympy import (Symbol, Eq, Ne, simplify, sqrt, exp, pi, symbols,
Piecewise, factorial, gamma, IndexedBase, Add, Pow, Mul,
Indexed, Integer, Integral, DiracDelta, Dummy, Sum, oo)
from sympy.functions.elementary.piecewise import ExprCondPair
from sympy.stats import (Poisson, Beta, Exponential, P,
Multinomial, MultivariateBeta)
from sympy.stats.crv_types import Normal
from sympy.stats.drv_types import PoissonDistribution
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
from sympy.stats.joint_rv import MarginalDistribution
from sympy.stats.rv import pspace, density
from sympy.testing.pytest import ignore_warnings
def test_density():
x = Symbol('x')
l = Symbol('l', positive=True)
rate = Beta(l, 2, 3)
X = Poisson(x, rate)
assert isinstance(pspace(X), CompoundPSpace)
assert density(X, Eq(rate, rate.symbol)) == PoissonDistribution(l)
N1 = Normal('N1', 0, 1)
N2 = Normal('N2', N1, 2)
assert density(N2)(0).doit() == sqrt(10)/(10*sqrt(pi))
assert simplify(density(N2, Eq(N1, 1))(x)) == \
sqrt(2)*exp(-(x - 1)**2/8)/(4*sqrt(pi))
assert simplify(density(N2)(x)) == sqrt(10)*exp(-x**2/10)/(10*sqrt(pi))
def test_MarginalDistribution():
a1, p1, p2 = symbols('a1 p1 p2', positive=True)
C = Multinomial('C', 2, p1, p2)
B = MultivariateBeta('B', a1, C[0])
MGR = MarginalDistribution(B, (C[0],))
mgrc = Mul(Symbol('B'), Piecewise(ExprCondPair(Mul(Integer(2),
Pow(Symbol('p1', positive=True), Indexed(IndexedBase(Symbol('C')),
Integer(0))), Pow(Symbol('p2', positive=True),
Indexed(IndexedBase(Symbol('C')), Integer(1))),
Pow(factorial(Indexed(IndexedBase(Symbol('C')), Integer(0))), Integer(-1)),
Pow(factorial(Indexed(IndexedBase(Symbol('C')), Integer(1))), Integer(-1))),
Eq(Add(Indexed(IndexedBase(Symbol('C')), Integer(0)),
Indexed(IndexedBase(Symbol('C')), Integer(1))), Integer(2))),
ExprCondPair(Integer(0), True)), Pow(gamma(Symbol('a1', positive=True)),
Integer(-1)), gamma(Add(Symbol('a1', positive=True),
Indexed(IndexedBase(Symbol('C')), Integer(0)))),
Pow(gamma(Indexed(IndexedBase(Symbol('C')), Integer(0))), Integer(-1)),
Pow(Indexed(IndexedBase(Symbol('B')), Integer(0)),
Add(Symbol('a1', positive=True), Integer(-1))),
Pow(Indexed(IndexedBase(Symbol('B')), Integer(1)),
Add(Indexed(IndexedBase(Symbol('C')), Integer(0)), Integer(-1))))
assert MGR(C) == mgrc
def test_compound_distribution():
Y = Poisson('Y', 1)
Z = Poisson('Z', Y)
assert isinstance(pspace(Z), CompoundPSpace)
assert isinstance(pspace(Z).distribution, CompoundDistribution)
assert Z.pspace.distribution.pdf(1).doit() == exp(-2)*exp(exp(-1))
def test_mix_expression():
Y, E = Poisson('Y', 1), Exponential('E', 1)
k = Dummy('k')
expr1 = Integral(Sum(exp(-1)*Integral(exp(-k)*DiracDelta(k - 2), (k, 0, oo)
)/factorial(k), (k, 0, oo)), (k, -oo, 0))
expr2 = Integral(Sum(exp(-1)*Integral(exp(-k)*DiracDelta(k - 2), (k, 0, oo)
)/factorial(k), (k, 0, oo)), (k, 0, oo))
assert P(Eq(Y + E, 1)) == 0
assert P(Ne(Y + E, 2)) == 1
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert P(E + Y < 2, evaluate=False).rewrite(Integral).dummy_eq(expr1)
assert P(E + Y > 2, evaluate=False).rewrite(Integral).dummy_eq(expr2)
|
8e9a0a6c6454a989dd3d29813501dde0551a831ffd816f62dda3cbc40c1703bf | from sympy import (S, symbols, FiniteSet, Eq, Matrix, MatrixSymbol, Float, And,
ImmutableMatrix, Ne, Lt, Gt, exp, Not, Rational, Lambda, erf,
Piecewise, factorial, Interval, oo, Contains, sqrt, pi,
gamma, lowergamma, Sum)
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
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
def test_DiscreteMarkovChain():
# pass only the name
X = DiscreteMarkovChain("X")
assert X.state_space == S.Reals
assert X.index_set == S.Naturals0
assert X.transition_probabilities == None
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(ValueError, lambda: sample_stochastic_process(t))
raises(ValueError, lambda: next(sample_stochastic_process(X)))
# pass name and state_space
Y = DiscreteMarkovChain("Y", [1, 2, 3])
assert Y.transition_probabilities == None
assert Y.state_space == FiniteSet(1, 2, 3)
assert P(Eq(Y[2], 1), Eq(Y[0], 2)) == Probability(Eq(Y[2], 1), Eq(Y[0], 2))
assert E(X[0]) == Expectation(X[0])
raises(TypeError, lambda: DiscreteMarkovChain("Y", dict((1, 1))))
raises(ValueError, lambda: next(sample_stochastic_process(Y)))
# 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", [0, 1, 2], TS)
assert YS._transient2transient() == None
assert YS._transient2absorbing() == None
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 str(P(Eq(YS[3], 2), Eq(YS[1], 1))) == \
"T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]"
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)) is S.Zero
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(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(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._transient2absorbing() == None
raises (ValueError, lambda: Y3.fundamental_matrix())
assert Y2.is_absorbing_chain() == True
assert Y3.is_absorbing_chain() == False
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
TS1 = MatrixSymbol('T', 3, 3)
Y5 = DiscreteMarkovChain('Y', trans_probs=TS1)
assert Y5.limiting_distribution(w, TO4).doit() == 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._transient2absorbing() == ImmutableMatrix([[S.Half, 0], [0, 0], [0, S.Half]])
assert Y6._transient2transient() == ImmutableMatrix([[0, S.Half, 0], [S.Half, 0, S.Half], [0, S.Half, 0]])
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_probabilites() == ImmutableMatrix([[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half], [Rational(1, 4), Rational(3, 4)]])
# 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)))
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
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
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)
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}
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(X(t)) == PoissonDistribution(3*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))
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(X(t)) == NormalDistribution(0, sqrt(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
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(X(t)) == GammaDistribution(g*t, 1/l)
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)
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
|
71c84ef03cb562b210f154916e8176c664ec81fc6fc21ccca9196ea635b3f64c | from sympy import exp, S, sqrt, pi, symbols, Product, gamma, Dummy
from sympy.matrices import Determinant, Matrix, Trace, MatrixSymbol, MatrixSet
from sympy.stats import density, sample
from sympy.stats.matrix_distributions import (MatrixGammaDistribution,
MatrixGamma, MatrixPSpace, Wishart, MatrixNormal)
from sympy.testing.pytest import raises, skip, ignore_warnings
from sympy.external import import_module
def test_MatrixPSpace():
M = MatrixGammaDistribution(1, 2, [[2, 1], [1, 2]])
MP = MatrixPSpace('M', M, 2, 2)
assert MP.distribution == M
raises(ValueError, lambda: MatrixPSpace('M', M, 1.2, 2))
def test_MatrixGamma():
M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])
assert M.pspace.distribution.set == MatrixSet(2, 2, S.Reals)
assert isinstance(density(M), MatrixGammaDistribution)
X = MatrixSymbol('X', 2, 2)
num = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X))
assert density(M)(X).doit() == num/(4*pi*sqrt(Determinant(X)))
assert density(M)([[2, 1], [1, 2]]).doit() == sqrt(3)*exp(-2)/(12*pi)
X = MatrixSymbol('X', 1, 2)
Y = MatrixSymbol('Y', 1, 2)
assert density(M)([X, Y]).doit() == exp(-X[0, 0]/2 - Y[0, 1]/2)/(4*pi*sqrt(
X[0, 0]*Y[0, 1] - X[0, 1]*Y[0, 0]))
# symbolic
a, b = symbols('a b', positive=True)
d = symbols('d', positive=True, integer=True)
Y = MatrixSymbol('Y', d, d)
Z = MatrixSymbol('Z', 2, 2)
SM = MatrixSymbol('SM', d, d)
M2 = MatrixGamma('M2', a, b, SM)
M3 = MatrixGamma('M3', 2, 3, [[2, 1], [1, 2]])
k = Dummy('k')
exprd = pi**(-d*(d - 1)/4)*b**(-a*d)*exp(Trace((-1/b)*SM**(-1)*Y)
)*Determinant(SM)**(-a)*Determinant(Y)**(a - d/2 - S(1)/2)/Product(
gamma(-k/2 + a + S(1)/2), (k, 1, d))
assert density(M2)(Y).dummy_eq(exprd)
raises(NotImplementedError, lambda: density(M3 + M)(Z))
raises(ValueError, lambda: density(M)(1))
raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0, 1]]))
raises(ValueError, lambda: MatrixGamma('M', -1, -2, [[1, 0], [0, 1]]))
raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [2, 1]]))
raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0]]))
def test_Wishart():
W = Wishart('W', 5, [[1, 0], [0, 1]])
assert W.pspace.distribution.set == MatrixSet(2, 2, S.Reals)
X = MatrixSymbol('X', 2, 2)
term1 = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X))
assert density(W)(X).doit() == term1 * Determinant(X)/(24*pi)
assert density(W)([[2, 1], [1, 2]]).doit() == exp(-2)/(8*pi)
n = symbols('n', positive=True)
d = symbols('d', positive=True, integer=True)
Y = MatrixSymbol('Y', d, d)
SM = MatrixSymbol('SM', d, d)
W = Wishart('W', n, SM)
k = Dummy('k')
exprd = 2**(-d*n/2)*pi**(-d*(d - 1)/4)*exp(Trace(-(S(1)/2)*SM**(-1)*Y)
)*Determinant(SM)**(-n/2)*Determinant(Y)**(
-d/2 + n/2 - S(1)/2)/Product(gamma(-k/2 + n/2 + S(1)/2), (k, 1, d))
assert density(W)(Y).dummy_eq(exprd)
raises(ValueError, lambda: density(W)(1))
raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [0, 1]]))
raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [2, 1]]))
raises(ValueError, lambda: Wishart('W', 2, [[1, 0], [0]]))
def test_MatrixNormal():
M = MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]])
assert M.pspace.distribution.set == MatrixSet(1, 2, S.Reals)
X = MatrixSymbol('X', 1, 2)
term1 = exp(-Trace(Matrix([[ S(2)/3, -S(1)/3], [-S(1)/3, S(2)/3]])*(
Matrix([[-5], [-6]]) + X.T)*Matrix([[1/4]])*(Matrix([[-5, -6]]) + X))/2)
assert density(M)(X).doit() == term1/(24*pi)
assert density(M)([[7, 8]]).doit() == exp(-S(1)/3)/(24*pi)
d, n = symbols('d n', positive=True, integer=True)
SM2 = MatrixSymbol('SM2', d, d)
SM1 = MatrixSymbol('SM1', n, n)
LM = MatrixSymbol('LM', n, d)
Y = MatrixSymbol('Y', n, d)
M = MatrixNormal('M', LM, SM1, SM2)
exprd = 4*(2*pi)**(-d*n/2)*exp(-Trace(SM2**(-1)*(-LM.T + Y.T)*SM1**(-1)*(-LM + Y)
)/2)*Determinant(SM1)**(-d)*Determinant(SM2)**(-n)
assert density(M)(Y).doit() == exprd
raises(ValueError, lambda: density(M)(1))
raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [2, 1]]))
raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0, 1]]))
raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [0, 1]]))
raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2]], [[1, 0], [0, 1]]))
raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0]]))
raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [[1, 0], [0, 1]], [[1, 0]]))
raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [1], [[1, 0]]))
def test_sample_scipy():
distribs_scipy = [
MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]]),
Wishart('W', 5, [[1, 0], [0, 1]])
]
size = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_scipy:
samps = next(sample(X, size=size))
for sam in samps:
assert Matrix(sam) in X.pspace.distribution.set
M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])
raises(NotImplementedError, lambda: next(sample(M, size=3)))
def test_sample_pymc3():
distribs_pymc3 = [
MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]], [[2, 1], [1, 2]]),
Wishart('W', 7, [[2, 1], [1, 2]])
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert Matrix(sam) in X.pspace.distribution.set
M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])
raises(NotImplementedError, lambda: next(sample(M, size=3)))
|
5ff9e822ed6775c8ffb684f8039cc6acb48d059ecf808b90483fa5dc427f3303 | from sympy import (S, Symbol, Sum, I, lambdify, re, im, log, simplify, sqrt,
zeta, pi, besseli, Dummy, oo, Piecewise, Rational, beta,
floor, FiniteSet)
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,
Poisson, Geometric, Hermite, Logarithmic,
NegativeBinomial, Skellam, YuleSimon, Zeta,
DiscreteRV)
from sympy.stats.rv import sample
from sympy.testing.pytest import slow, nocache_fail, raises, skip, ignore_warnings
from sympy.external import import_module
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 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 variance(x) == l
assert density(x) == PoissonDistribution(l)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert isinstance(E(x, evaluate=False), Expectation)
assert isinstance(E(2*x, evaluate=False), Expectation)
# issue 8248
assert x.pspace.compute_expectation(1) == 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
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)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
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)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
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 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))
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
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
@slow
def test_sample_discrete():
X = Geometric('X', S.Half)
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X)) in X.pspace.domain.set
samps = next(sample(X, size=2)) # This takes long time if ran without scipy
for samp in samps:
assert samp in X.pspace.domain.set
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)
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))))
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)
P(Or(X < 3, X > 4)) == Rational(13, 16)
P(Or(X > 2, X > 1)) == P(X > 1)
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, evaluate=False)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """\
# + """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, -oo, -1))"""
n = Dummy('n')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert P(X1 + X2 < 3, evaluate=False).rewrite(Sum).dummy_eq(Sum(Piecewise((2**(-n)/4,
n + 2 >= 1), (0, True)), (n, -oo, -1))/3)
#assert str(P(X1 + X2 > 3)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """ +\
# """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, 1, oo))"""
assert P(X1 + X2 > 3).dummy_eq(Sum(Piecewise((2**(X2 - n - 2)*(Rational(2, 3))**(X2 - 1)/6,
-X2 + n + 3 >= 1), (0, True)),
(X2, 1, oo), (n, 1, oo)))
# assert str(P(Eq(X1 + X2, 3))) == """Sum(Piecewise((2**(X2 - 2)*(2/3)**(X2 - 1)/6, """ +\
# """X2 <= 2), (0, True)), (X2, 1, oo))"""
assert P(Eq(X1 + X2, 3)) == Rational(1, 12)
def test_sample_numpy():
distribs_numpy = [
Geometric('G', 0.5),
Poisson('P', 1),
Zeta('Z', 2)
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Skellam('S', 1, 1), library='numpy')))
raises(NotImplementedError,
lambda: Skellam('S', 1, 1).pspace.distribution.sample(library='tensorflow'))
def test_sample_scipy():
p = S(2)/3
x = Symbol('x', integer=True, positive=True)
pdf = p*(1 - p)**(x - 1) # pdf of Geometric Distribution
distribs_scipy = [
DiscreteRV(x, pdf, set=S.Naturals),
Geometric('G', 0.5),
Logarithmic('L', 0.5),
NegativeBinomial('N', 5, 0.4),
Poisson('P', 1),
Skellam('S', 1, 1),
YuleSimon('Y', 1),
Zeta('Z', 2)
]
size = 3
numsamples = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
z_sample = list(sample(Zeta("G", 7), size=size, numsamples=numsamples))
assert len(z_sample) == numsamples
for X in distribs_scipy:
samps = next(sample(X, size=size, library='scipy'))
samps2 = next(sample(X, size=(2, 2), library='scipy'))
for sam in samps:
assert sam in X.pspace.domain.set
for i in range(2):
for j in range(2):
assert samps2[i][j] in X.pspace.domain.set
def test_sample_pymc3():
distribs_pymc3 = [
Geometric('G', 0.5),
Poisson('P', 1),
NegativeBinomial('N', 5, 0.4)
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Skellam('S', 1, 1), library='pymc3')))
|
93afc7e674eee8bfe4b1ff1ce51a4d247660558440c8fd141a6fd65bae5bc635 | from sympy import (sqrt, exp, Trace, pi, S, Integral, MatrixSymbol, Lambda,
Dummy, Product, Abs, IndexedBase, Matrix, I, Rational)
from sympy.stats import (GaussianUnitaryEnsemble as GUE, density,
GaussianOrthogonalEnsemble as GOE,
GaussianSymplecticEnsemble as GSE,
joint_eigen_distribution,
CircularUnitaryEnsemble as CUE,
CircularOrthogonalEnsemble as COE,
CircularSymplecticEnsemble as CSE,
JointEigenDistribution,
level_spacing_distribution,
Normal, Beta)
from sympy.stats.joint_rv_types import JointDistributionHandmade
from sympy.stats.rv import RandomMatrixSymbol
from sympy.stats.random_matrix_models import GaussianEnsemble
from sympy.testing.pytest import raises
def test_GaussianEnsemble():
G = GaussianEnsemble('G', 3)
assert density(G) == G.pspace.model
raises(ValueError, lambda: GaussianEnsemble('G', 3.5))
def test_GaussianUnitaryEnsemble():
H = RandomMatrixSymbol('H', 3, 3)
G = GUE('U', 3)
assert density(G)(H) == sqrt(2)*exp(-3*Trace(H**2)/2)/(4*pi**Rational(9, 2))
i, j = (Dummy('i', integer=True, positive=True),
Dummy('j', integer=True, positive=True))
l = IndexedBase('l')
assert joint_eigen_distribution(G).dummy_eq(
Lambda((l[1], l[2], l[3]),
27*sqrt(6)*exp(-3*(l[1]**2)/2 - 3*(l[2]**2)/2 - 3*(l[3]**2)/2)*
Product(Abs(l[i] - l[j])**2, (j, i + 1, 3), (i, 1, 2))/(16*pi**Rational(3, 2))))
s = Dummy('s')
assert level_spacing_distribution(G).dummy_eq(Lambda(s, 32*s**2*exp(-4*s**2/pi)/pi**2))
def test_GaussianOrthogonalEnsemble():
H = RandomMatrixSymbol('H', 3, 3)
_H = MatrixSymbol('_H', 3, 3)
G = GOE('O', 3)
assert density(G)(H) == exp(-3*Trace(H**2)/4)/Integral(exp(-3*Trace(_H**2)/4), _H)
i, j = (Dummy('i', integer=True, positive=True),
Dummy('j', integer=True, positive=True))
l = IndexedBase('l')
assert joint_eigen_distribution(G).dummy_eq(
Lambda((l[1], l[2], l[3]),
9*sqrt(2)*exp(-3*l[1]**2/2 - 3*l[2]**2/2 - 3*l[3]**2/2)*
Product(Abs(l[i] - l[j]), (j, i + 1, 3), (i, 1, 2))/(32*pi)))
s = Dummy('s')
assert level_spacing_distribution(G).dummy_eq(Lambda(s, s*pi*exp(-s**2*pi/4)/2))
def test_GaussianSymplecticEnsemble():
H = RandomMatrixSymbol('H', 3, 3)
_H = MatrixSymbol('_H', 3, 3)
G = GSE('O', 3)
assert density(G)(H) == exp(-3*Trace(H**2))/Integral(exp(-3*Trace(_H**2)), _H)
i, j = (Dummy('i', integer=True, positive=True),
Dummy('j', integer=True, positive=True))
l = IndexedBase('l')
assert joint_eigen_distribution(G).dummy_eq(
Lambda((l[1], l[2], l[3]),
162*sqrt(3)*exp(-3*l[1]**2/2 - 3*l[2]**2/2 - 3*l[3]**2/2)*
Product(Abs(l[i] - l[j])**4, (j, i + 1, 3), (i, 1, 2))/(5*pi**Rational(3, 2))))
s = Dummy('s')
assert level_spacing_distribution(G).dummy_eq(Lambda(s, S(262144)*s**4*exp(-64*s**2/(9*pi))/(729*pi**3)))
def test_CircularUnitaryEnsemble():
CU = CUE('U', 3)
j, k = (Dummy('j', integer=True, positive=True),
Dummy('k', integer=True, positive=True))
t = IndexedBase('t')
assert joint_eigen_distribution(CU).dummy_eq(
Lambda((t[1], t[2], t[3]),
Product(Abs(exp(I*t[j]) - exp(I*t[k]))**2,
(j, k + 1, 3), (k, 1, 2))/(48*pi**3))
)
def test_CircularOrthogonalEnsemble():
CO = COE('U', 3)
j, k = (Dummy('j', integer=True, positive=True),
Dummy('k', integer=True, positive=True))
t = IndexedBase('t')
assert joint_eigen_distribution(CO).dummy_eq(
Lambda((t[1], t[2], t[3]),
Product(Abs(exp(I*t[j]) - exp(I*t[k])),
(j, k + 1, 3), (k, 1, 2))/(48*pi**2))
)
def test_CircularSymplecticEnsemble():
CS = CSE('U', 3)
j, k = (Dummy('j', integer=True, positive=True),
Dummy('k', integer=True, positive=True))
t = IndexedBase('t')
assert joint_eigen_distribution(CS).dummy_eq(
Lambda((t[1], t[2], t[3]),
Product(Abs(exp(I*t[j]) - exp(I*t[k]))**4,
(j, k + 1, 3), (k, 1, 2))/(720*pi**3))
)
def test_JointEigenDistribution():
A = Matrix([[Normal('A00', 0, 1), Normal('A01', 1, 1)],
[Beta('A10', 1, 1), Beta('A11', 1, 1)]])
JointEigenDistribution(A) == \
JointDistributionHandmade(-sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)/2 +
A[0, 0]/2 + A[1, 1]/2, sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)/2 + A[0, 0]/2 + A[1, 1]/2)
raises(ValueError, lambda: JointEigenDistribution(Matrix([[1, 0], [2, 1]])))
|
753c89b3acfd507be2c26b4251ad2696e6a5fd1bb71d671e3647c792d1c827eb | from sympy import E as e
from sympy import (Symbol, Abs, exp, expint, S, pi, simplify, Interval, erf, erfc, Ne,
EulerGamma, Eq, log, lowergamma, uppergamma, symbols, sqrt, And,
gamma, beta, Piecewise, Integral, sin, cos, tan, sinh, cosh,
besseli, floor, expand_func, Rational, I, re, Lambda, asin,
im, lambdify, hyper, diff, Or, Mul, sign, Dummy, Sum,
factorial, binomial, erfi, besselj, besselk)
from sympy.external import import_module
from sympy.functions.special.error_functions import erfinv
from sympy.functions.special.hyper import meijerg
from sympy.sets.sets import Intersection, FiniteSet
from sympy.stats import (P, E, where, density, variance, covariance, skewness, kurtosis, median,
given, pspace, cdf, characteristic_function, moment_generating_function,
ContinuousRV, sample, 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,
LogLogistic, 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, skip, ignore_warnings
from sympy.testing.randtest 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)
assert quantile(Y)(x) == Intersection(S.Reals, FiniteSet(sqrt(2)*sigma*(sqrt(2)*mu/(2*sigma) + erfinv(2*x - 1))))
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
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)
@slow
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*Rational(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_sample_continuous():
Z = ContinuousRV(z, exp(-z), set=Interval(0, oo))
assert density(Z)(-1) == 0
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(Z)) in Z.pspace.domain.set
sym, val = list(Z.pspace.sample().items())[0]
assert sym == Z and val in Interval(0, oo)
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)
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)))
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 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)))
def test_exponential():
rate = Symbol('lambda', positive=True)
X = Exponential('x', rate)
p = Symbol("p", positive=True, real=True, finite=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_sampling_gamma_inverse():
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for sampling of gamma inverse.')
X = GammaInverse("x", 1, 1)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X)) in X.pspace.domain.set
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_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_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)
# Right now, only density function and sampling works
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for i in range(3):
X = LogNormal('x', i, 1)
assert next(sample(X)) in X.pspace.domain.set
size = 5
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
samps = next(sample(X, size=size))
for samp in samps:
assert samp in X.pspace.domain.set
# 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)
def test_Moyal():
mu = Symbol('mu',real=False)
sigma = Symbol('sigma', real=True, positive=True)
raises(ValueError, lambda: Moyal('M',mu, sigma))
mu = Symbol('mu', real=True)
sigma = Symbol('sigma', real=True, negative=True)
raises(ValueError, lambda: Moyal('M',mu, sigma))
sigma = Symbol('sigma', real=True, 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_sampling_gaussian_inverse():
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for sampling of Gaussian inverse.')
X = GaussianInverse("x", 1, 1)
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert next(sample(X, library='scipy')) in X.pspace.domain.set
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
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_prefab_sampling():
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests')
N = Normal('X', 0, 1)
L = LogNormal('L', 0, 1)
E = Exponential('Ex', 1)
P = Pareto('P', 1, 3)
W = Weibull('W', 1, 1)
U = Uniform('U', 0, 1)
B = Beta('B', 2, 5)
G = Gamma('G', 1, 3)
variables = [N, L, E, P, W, U, B, G]
niter = 10
size = 5
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for var in variables:
for i in range(niter):
assert next(sample(var)) in var.pspace.domain.set
samps = next(sample(var, size=size))
for samp in samps:
assert samp in var.pspace.domain.set
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
@slow
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_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((1/2, (x >= 0) & (x < 1)),
(0, (x >= 1) & (x < 2)), (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_sample_numpy():
distribs_numpy = [
Beta("B", 1, 1),
Normal("N", 0, 1),
Gamma("G", 2, 7),
Exponential("E", 2),
LogNormal("LN", 0, 1),
Pareto("P", 1, 1),
ChiSquared("CS", 2),
Uniform("U", 0, 1)
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Chi("C", 1), library='numpy')))
raises(NotImplementedError,
lambda: Chi("C", 1).pspace.distribution.sample(library='tensorflow'))
def test_sample_scipy():
distribs_scipy = [
Beta("B", 1, 1),
BetaPrime("BP", 1, 1),
Cauchy("C", 1, 1),
Chi("C", 1),
Normal("N", 0, 1),
Gamma("G", 2, 7),
GammaInverse("GI", 1, 1),
GaussianInverse("GUI", 1, 1),
Exponential("E", 2),
LogNormal("LN", 0, 1),
Pareto("P", 1, 1),
StudentT("S", 2),
ChiSquared("CS", 2),
Uniform("U", 0, 1)
]
size = 3
numsamples = 5
scipy = import_module('scipy')
if not scipy:
skip('Scipy is not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
g_sample = list(sample(Gamma("G", 2, 7), size=size, numsamples=numsamples))
assert len(g_sample) == numsamples
for X in distribs_scipy:
samps = next(sample(X, size=size, library='scipy'))
samps2 = next(sample(X, size=(2, 2), library='scipy'))
for sam in samps:
assert sam in X.pspace.domain.set
for i in range(2):
for j in range(2):
assert samps2[i][j] in X.pspace.domain.set
def test_sample_pymc3():
distribs_pymc3 = [
Beta("B", 1, 1),
Cauchy("C", 1, 1),
Normal("N", 0, 1),
Gamma("G", 2, 7),
GaussianInverse("GI", 1, 1),
Exponential("E", 2),
LogNormal("LN", 0, 1),
Pareto("P", 1, 1),
ChiSquared("CS", 2),
Uniform("U", 0, 1)
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert sam in X.pspace.domain.set
raises(NotImplementedError,
lambda: next(sample(Chi("C", 1), library='pymc3')))
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}))
|
cc99a9d2f4a04a181113f046513f1ea48a8ffdf9610af7d4576ffd9d842ea93c | from sympy import (symbols, S, erf, sqrt, pi, exp, gamma, Interval, oo, beta,
Eq, Piecewise, Integral, Abs, arg, Dummy, Sum, factorial)
from sympy.stats import (Normal, P, E, density, Gamma, Poisson, Rayleigh,
variance, Bernoulli, Beta, Uniform, cdf)
from sympy.stats.compound_rv import CompoundDistribution, CompoundPSpace
from sympy.stats.crv_types import NormalDistribution
from sympy.stats.drv_types import PoissonDistribution
from sympy.stats.frv_types import BernoulliDistribution
from sympy.testing.pytest import raises, ignore_warnings
from sympy.stats.joint_rv_types import MultivariateNormalDistribution
x = symbols('x')
def test_normal_CompoundDist():
X = Normal('X', 1, 2)
Y = Normal('X', X, 4)
assert density(Y)(x).simplify() == sqrt(10)*exp(-x**2/40 + x/20 - S(1)/40)/(20*sqrt(pi))
assert E(Y) == 1 # it is always equal to mean of X
assert P(Y > 1) == S(1)/2 # as 1 is the mean
assert P(Y > 5).simplify() == S(1)/2 - erf(sqrt(10)/5)/2
assert variance(Y) == variance(X) + 4**2 # 2**2 + 4**2
# https://math.stackexchange.com/questions/1484451/
# (Contains proof of E and variance computation)
def test_poisson_CompoundDist():
k, t, y = symbols('k t y', positive=True, real=True)
G = Gamma('G', k, t)
D = Poisson('P', G)
assert density(D)(y).simplify() == t**y*(t + 1)**(-k - y)*gamma(k + y)/(gamma(k)*gamma(y + 1))
# https://en.wikipedia.org/wiki/Negative_binomial_distribution#Gamma%E2%80%93Poisson_mixture
assert E(D).simplify() == k*t # mean of NegativeBinomialDistribution
def test_bernoulli_CompoundDist():
X = Beta('X', 1, 2)
Y = Bernoulli('Y', X)
assert density(Y).dict == {0: S(2)/3, 1: S(1)/3}
assert E(Y) == P(Eq(Y, 1)) == S(1)/3
assert variance(Y) == S(2)/9
assert cdf(Y) == {0: S(2)/3, 1: 1}
# test issue 8128
a = Bernoulli('a', S(1)/2)
b = Bernoulli('b', a)
assert density(b).dict == {0: S(1)/2, 1: S(1)/2}
assert P(b > 0.5) == S(1)/2
X = Uniform('X', 0, 1)
Y = Bernoulli('Y', X)
assert E(Y) == S(1)/2
assert P(Eq(Y, 1)) == E(Y)
def test_unevaluated_CompoundDist():
# these tests need to be removed once they work with evaluation as they are currently not
# evaluated completely in sympy.
R = Rayleigh('R', 4)
X = Normal('X', 3, R)
_k = Dummy('k')
exprd = Piecewise((exp(S(3)/4 - x/4)/8, 2*Abs(arg(x - 3)) <= pi/2),
(sqrt(2)*Integral(exp(-(_k**4 + 16*(x - 3)**2)/(32*_k**2)),
(_k, 0, oo))/(32*sqrt(pi)), True))
assert (density(X)(x).simplify()).dummy_eq(exprd.simplify())
expre = Integral(_k*Integral(sqrt(2)*exp(-_k**2/32)*exp(-(_k - 3)**2/(2*_k**2)
)/(32*sqrt(pi)), (_k, 0, oo)), (_k, -oo, oo))
with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
assert E(X, evaluate=False).rewrite(Integral).dummy_eq(expre)
X = Poisson('X', 1)
Y = Poisson('Y', X)
Z = Poisson('Z', Y)
exprd = exp(-1)*Sum(exp(-Y)*Y**x*Sum(exp(-X)*X**Y/(factorial(X)*factorial(Y)
), (X, 0, oo)), (Y, 0, oo))/factorial(x)
assert density(Z)(x).simplify() == exprd
N = Normal('N', 1, 2)
M = Normal('M', 3, 4)
D = Normal('D', M, N)
exprd = Integral(sqrt(2)*exp(-(_k - 1)**2/8)*Integral(exp(-(-_k + x
)**2/(2*_k**2))*exp(-(_k - 3)**2/32)/(8*pi*_k)
, (_k, -oo, oo))/(4*sqrt(pi)), (_k, -oo, oo))
assert density(D, evaluate=False)(x).dummy_eq(exprd)
def test_Compound_Distribution():
X = Normal('X', 2, 4)
N = NormalDistribution(X, 4)
C = CompoundDistribution(N)
assert C.is_Continuous
assert C.set == Interval(-oo, oo)
assert C.pdf(x, evaluate=True).simplify() == exp(-x**2/64 + x/16 - S(1)/16)/(8*sqrt(pi))
assert not isinstance(CompoundDistribution(NormalDistribution(2, 3)),
CompoundDistribution)
M = MultivariateNormalDistribution([1, 2], [[2, 1], [1, 2]])
raises(NotImplementedError, lambda: CompoundDistribution(M))
X = Beta('X', 2, 4)
B = BernoulliDistribution(X, 1, 0)
C = CompoundDistribution(B)
assert C.is_Finite
assert C.set == {0, 1}
y = symbols('y', negative=False, integer=True)
assert C.pdf(y, evaluate=True) == Piecewise((S(1)/(30*beta(2, 4)), Eq(y, 0)),
(S(1)/(60*beta(2, 4)), Eq(y, 1)), (0, True))
k, t, z = symbols('k t z', positive=True, real=True)
G = Gamma('G', k, t)
X = PoissonDistribution(G)
C = CompoundDistribution(X)
assert C.is_Discrete
assert C.set == S.Naturals0
assert C.pdf(z, evaluate=True).simplify() == t**z*(t + 1)**(-k - z)*gamma(k \
+ z)/(gamma(k)*gamma(z + 1))
def test_compound_pspace():
X = Normal('X', 2, 4)
Y = Normal('Y', 3, 6)
assert not isinstance(Y.pspace, CompoundPSpace)
N = NormalDistribution(1, 2)
D = PoissonDistribution(3)
B = BernoulliDistribution(0.2, 1, 0)
pspace1 = CompoundPSpace('N', N)
pspace2 = CompoundPSpace('D', D)
pspace3 = CompoundPSpace('B', B)
assert not isinstance(pspace1, CompoundPSpace)
assert not isinstance(pspace2, CompoundPSpace)
assert not isinstance(pspace3, CompoundPSpace)
M = MultivariateNormalDistribution([1, 2], [[2, 1], [1, 2]])
raises(ValueError, lambda: CompoundPSpace('M', M))
Y = Normal('Y', X, 6)
assert isinstance(Y.pspace, CompoundPSpace)
assert Y.pspace.distribution == CompoundDistribution(NormalDistribution(X, 6))
assert Y.pspace.domain.set == Interval(-oo, oo)
|
593cef9f73540abce7047b5312b8acfd7cb26a093ba9f0d1ba7f22f8dfcb86fe | from sympy import (
Abs, And, binomial, Catalan, combsimp, cos, Derivative, E, Eq, exp, EulerGamma,
factorial, Function, harmonic, I, Integral, KroneckerDelta, log,
nan, oo, pi, Piecewise, Product, product, Rational, S, simplify, Identity,
sin, sqrt, Sum, summation, Symbol, symbols, sympify, zeta, gamma,
Indexed, Idx, IndexedBase, prod, Dummy, lowergamma, Range, floor,
RisingFactorial, MatrixSymbol)
from sympy.abc import a, b, c, d, k, m, x, y, z
from sympy.concrete.summations import telescopic, _dummy_with_inherited_properties_concrete
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
n = Symbol('n', integer=True)
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.)
f = Function("f")
# 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_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():
f, g = symbols('f g', cls=Function)
# 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)
f = Function("f")
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() == -((a - b - 1)/(b*(a - 1)))
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():
f = Function("f")
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():
f = Function('f')
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():
from sympy import sin
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}
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(Function('f')(x) * y * z, (x, a, b)) / (y * z)) \
== Sum(Function('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():
f = Function('f')
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()
assert res == Piecewise(
(n*p, p/Abs(p - 1) <= 1),
((-p + 1)**n*Sum(k*p**k*(-p + 1)**(-k)*binomial(n, k), (k, 0, n)),
True))
# Issue #17165: make sure that another simplify does not change/increase
# the result
assert res == res.simplify()
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)))
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
# 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
# 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_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():
raises(NotImplementedError, lambda: Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent())
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))
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)
@XFAIL
def test_issue_14313():
assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent()
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*RisingFactorial(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), Abs(x) < 1),
(x*Sum(x**n, (n, -1, oo)), True))
assert ssimp == ssimp.simplify()
def test__dummy_with_inherited_properties_concrete():
x = Symbol('x')
from sympy 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
@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
|
ea2c0903d53a3046a623d2a349c13593332f77cb5aba0f298e08e9de5e9288b6 | import sympy
import tempfile
import os
from sympy import symbols, Eq, Mod
from sympy.external import import_module
from sympy.tensor import IndexedBase, Idx
from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError
from sympy.testing.pytest import skip
numpy = import_module('numpy', min_module_version='1.6.1')
Cython = import_module('Cython', min_module_version='0.15.1')
f2py = import_module('numpy.f2py', import_kwargs={'fromlist': ['f2py']})
f2pyworks = False
if f2py:
try:
autowrap(symbols('x'), 'f95', 'f2py')
except (CodeWrapError, ImportError, OSError):
f2pyworks = False
else:
f2pyworks = True
a, b, c = symbols('a b c')
n, m, d = symbols('n m d', integer=True)
A, B, C = symbols('A B C', cls=IndexedBase)
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', d)
def has_module(module):
"""
Return True if module exists, otherwise run skip().
module should be a string.
"""
# To give a string of the module name to skip(), this function takes a
# string. So we don't waste time running import_module() more than once,
# just map the three modules tested here in this dict.
modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py}
if modnames[module]:
if module == 'f2py' and not f2pyworks:
skip("Couldn't run f2py.")
return True
skip("Couldn't import %s." % module)
#
# test runners used by several language-backend combinations
#
def runtest_autowrap_twice(language, backend):
f = autowrap((((a + b)/c)**5).expand(), language, backend)
g = autowrap((((a + b)/c)**4).expand(), language, backend)
# check that autowrap updates the module name. Else, g gives the same as f
assert f(1, -2, 1) == -1.0
assert g(1, -2, 1) == 1.0
def runtest_autowrap_trace(language, backend):
has_module('numpy')
trace = autowrap(A[i, i], language, backend)
assert trace(numpy.eye(100)) == 100
def runtest_autowrap_matrix_vector(language, backend):
has_module('numpy')
x, y = symbols('x y', cls=IndexedBase)
expr = Eq(y[i], A[i, j]*x[j])
mv = autowrap(expr, language, backend)
# compare with numpy's dot product
M = numpy.random.rand(10, 20)
x = numpy.random.rand(20)
y = numpy.dot(M, x)
assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13
def runtest_autowrap_matrix_matrix(language, backend):
has_module('numpy')
expr = Eq(C[i, j], A[i, k]*B[k, j])
matmat = autowrap(expr, language, backend)
# compare with numpy's dot product
M1 = numpy.random.rand(10, 20)
M2 = numpy.random.rand(20, 15)
M3 = numpy.dot(M1, M2)
assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13
def runtest_ufuncify(language, backend):
has_module('numpy')
a, b, c = symbols('a b c')
fabc = ufuncify([a, b, c], a*b + c, backend=backend)
facb = ufuncify([a, c, b], a*b + c, backend=backend)
grid = numpy.linspace(-2, 2, 50)
b = numpy.linspace(-5, 4, 50)
c = numpy.linspace(-1, 1, 50)
expected = grid*b + c
numpy.testing.assert_allclose(fabc(grid, b, c), expected)
numpy.testing.assert_allclose(facb(grid, c, b), expected)
def runtest_issue_10274(language, backend):
expr = (a - b + c)**(13)
tmp = tempfile.mkdtemp()
f = autowrap(expr, language, backend, tempdir=tmp,
helpers=('helper', a - b + c, (a, b, c)))
assert f(1, 1, 1) == 1
for file in os.listdir(tmp):
if file.startswith("wrapped_code_") and file.endswith(".c"):
fil = open(tmp + '/' + file)
lines = fil.readlines()
assert lines[0] == "/******************************************************************************\n"
assert "Code generated with sympy " + sympy.__version__ in lines[1]
assert lines[2:] == [
" * *\n",
" * See http://www.sympy.org/ for more information. *\n",
" * *\n",
" * This file is part of 'autowrap' *\n",
" ******************************************************************************/\n",
"#include " + '"' + file[:-1]+ 'h"' + "\n",
"#include <math.h>\n",
"\n",
"double helper(double a, double b, double c) {\n",
"\n",
" double helper_result;\n",
" helper_result = a - b + c;\n",
" return helper_result;\n",
"\n",
"}\n",
"\n",
"double autofunc(double a, double b, double c) {\n",
"\n",
" double autofunc_result;\n",
" autofunc_result = pow(helper(a, b, c), 13);\n",
" return autofunc_result;\n",
"\n",
"}\n",
]
def runtest_issue_15337(language, backend):
has_module('numpy')
# NOTE : autowrap was originally designed to only accept an iterable for
# the kwarg "helpers", but in issue 10274 the user mistakenly thought that
# if there was only a single helper it did not need to be passed via an
# iterable that wrapped the helper tuple. There were no tests for this
# behavior so when the code was changed to accept a single tuple it broke
# the original behavior. These tests below ensure that both now work.
a, b, c, d, e = symbols('a, b, c, d, e')
expr = (a - b + c - d + e)**13
exp_res = (1. - 2. + 3. - 4. + 5.)**13
f = autowrap(expr, language, backend, args=(a, b, c, d, e),
helpers=('f1', a - b + c, (a, b, c)))
numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
f = autowrap(expr, language, backend, args=(a, b, c, d, e),
helpers=(('f1', a - b, (a, b)), ('f2', c - d, (c, d))))
numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
def test_issue_15230():
has_module('f2py')
x, y = symbols('x, y')
expr = Mod(x, 3.0) - Mod(y, -2.0)
f = autowrap(expr, args=[x, y], language='F95')
exp_res = float(expr.xreplace({x: 3.5, y: 2.7}).evalf())
assert abs(f(3.5, 2.7) - exp_res) < 1e-14
x, y = symbols('x, y', integer=True)
expr = Mod(x, 3) - Mod(y, -2)
f = autowrap(expr, args=[x, y], language='F95')
assert f(3, 2) == expr.xreplace({x: 3, y: 2})
#
# tests of language-backend combinations
#
# f2py
def test_wrap_twice_f95_f2py():
has_module('f2py')
runtest_autowrap_twice('f95', 'f2py')
def test_autowrap_trace_f95_f2py():
has_module('f2py')
runtest_autowrap_trace('f95', 'f2py')
def test_autowrap_matrix_vector_f95_f2py():
has_module('f2py')
runtest_autowrap_matrix_vector('f95', 'f2py')
def test_autowrap_matrix_matrix_f95_f2py():
has_module('f2py')
runtest_autowrap_matrix_matrix('f95', 'f2py')
def test_ufuncify_f95_f2py():
has_module('f2py')
runtest_ufuncify('f95', 'f2py')
def test_issue_15337_f95_f2py():
has_module('f2py')
runtest_issue_15337('f95', 'f2py')
# Cython
def test_wrap_twice_c_cython():
has_module('Cython')
runtest_autowrap_twice('C', 'cython')
def test_autowrap_trace_C_Cython():
has_module('Cython')
runtest_autowrap_trace('C99', 'cython')
def test_autowrap_matrix_vector_C_cython():
has_module('Cython')
runtest_autowrap_matrix_vector('C99', 'cython')
def test_autowrap_matrix_matrix_C_cython():
has_module('Cython')
runtest_autowrap_matrix_matrix('C99', 'cython')
def test_ufuncify_C_Cython():
has_module('Cython')
runtest_ufuncify('C99', 'cython')
def test_issue_10274_C_cython():
has_module('Cython')
runtest_issue_10274('C89', 'cython')
def test_issue_15337_C_cython():
has_module('Cython')
runtest_issue_15337('C89', 'cython')
def test_autowrap_custom_printer():
has_module('Cython')
from sympy import pi
from sympy.utilities.codegen import C99CodeGen
from sympy.printing.c import C99CodePrinter
class PiPrinter(C99CodePrinter):
def _print_Pi(self, expr):
return "S_PI"
printer = PiPrinter()
gen = C99CodeGen(printer=printer)
gen.preprocessor_statements.append('#include "shortpi.h"')
expr = pi * a
expected = (
'#include "%s"\n'
'#include <math.h>\n'
'#include "shortpi.h"\n'
'\n'
'double autofunc(double a) {\n'
'\n'
' double autofunc_result;\n'
' autofunc_result = S_PI*a;\n'
' return autofunc_result;\n'
'\n'
'}\n'
)
tmpdir = tempfile.mkdtemp()
# write a trivial header file to use in the generated code
open(os.path.join(tmpdir, 'shortpi.h'), 'w').write('#define S_PI 3.14')
func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen)
assert func(4.2) == 3.14 * 4.2
# check that the generated code is correct
for filename in os.listdir(tmpdir):
if filename.startswith('wrapped_code') and filename.endswith('.c'):
with open(os.path.join(tmpdir, filename)) as f:
lines = f.readlines()
expected = expected % filename.replace('.c', '.h')
assert ''.join(lines[7:]) == expected
# Numpy
def test_ufuncify_numpy():
# This test doesn't use Cython, but if Cython works, then there is a valid
# C compiler, which is needed.
has_module('Cython')
runtest_ufuncify('C99', 'numpy')
|
4185da6c29339406ea0a1bb9f4c2f9e8cc38c628a4a0068a8d2ffa86eb521129 | from sympy import (symbols, Symbol, oo, Sum, harmonic, exp, Add, S, binomial,
factorial, log, fibonacci, subfactorial, sin, cos, pi, I, sqrt, Rational, gamma)
from sympy.series.limitseq import limit_seq
from sympy.series.limitseq import difference_delta as dd
from sympy.testing.pytest import raises, XFAIL
from sympy.calculus.util import AccumulationBounds
n, m, k = symbols('n m k', integer=True)
def test_difference_delta():
e = n*(n + 1)
e2 = e * k
assert dd(e) == 2*n + 2
assert dd(e2, n, 2) == k*(4*n + 6)
raises(ValueError, lambda: dd(e2))
raises(ValueError, lambda: dd(e2, n, oo))
def test_difference_delta__Sum():
e = Sum(1/k, (k, 1, n))
assert dd(e, n) == 1/(n + 1)
assert dd(e, n, 5) == Add(*[1/(i + n + 1) for i in range(5)])
e = Sum(1/k, (k, 1, 3*n))
assert dd(e, n) == Add(*[1/(i + 3*n + 1) for i in range(3)])
e = n * Sum(1/k, (k, 1, n))
assert dd(e, n) == 1 + Sum(1/k, (k, 1, n))
e = Sum(1/k, (k, 1, n), (m, 1, n))
assert dd(e, n) == harmonic(n)
def test_difference_delta__Add():
e = n + n*(n + 1)
assert dd(e, n) == 2*n + 3
assert dd(e, n, 2) == 4*n + 8
e = n + Sum(1/k, (k, 1, n))
assert dd(e, n) == 1 + 1/(n + 1)
assert dd(e, n, 5) == 5 + Add(*[1/(i + n + 1) for i in range(5)])
def test_difference_delta__Pow():
e = 4**n
assert dd(e, n) == 3*4**n
assert dd(e, n, 2) == 15*4**n
e = 4**(2*n)
assert dd(e, n) == 15*4**(2*n)
assert dd(e, n, 2) == 255*4**(2*n)
e = n**4
assert dd(e, n) == (n + 1)**4 - n**4
e = n**n
assert dd(e, n) == (n + 1)**(n + 1) - n**n
def test_limit_seq():
e = binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n))
assert limit_seq(e) == S(3) / 4
assert limit_seq(e, m) == e
e = (5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5)
assert limit_seq(e, n) == S(5) / 3
e = (harmonic(n) * Sum(harmonic(k), (k, 1, n))) / (n * harmonic(2*n)**2)
assert limit_seq(e, n) == 1
e = Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n)
assert limit_seq(e, n) == 4
e = (Sum(binomial(3*k, k) * binomial(5*k, k), (k, 1, n)) /
(binomial(3*n, n) * binomial(5*n, n)))
assert limit_seq(e, n) == S(84375) / 83351
e = Sum(harmonic(k)**2/k, (k, 1, 2*n)) / harmonic(n)**3
assert limit_seq(e, n) == S.One / 3
raises(ValueError, lambda: limit_seq(e * m))
def test_alternating_sign():
assert limit_seq((-1)**n/n**2, n) == 0
assert limit_seq((-2)**(n+1)/(n + 3**n), n) == 0
assert limit_seq((2*n + (-1)**n)/(n + 1), n) == 2
assert limit_seq(sin(pi*n), n) == 0
assert limit_seq(cos(2*pi*n), n) == 1
assert limit_seq((S.NegativeOne/5)**n, n) == 0
assert limit_seq((Rational(-1, 5))**n, n) == 0
assert limit_seq((I/3)**n, n) == 0
assert limit_seq(sqrt(n)*(I/2)**n, n) == 0
assert limit_seq(n**7*(I/3)**n, n) == 0
assert limit_seq(n/(n + 1) + (I/2)**n, n) == 1
def test_accum_bounds():
assert limit_seq((-1)**n, n) == AccumulationBounds(-1, 1)
assert limit_seq(cos(pi*n), n) == AccumulationBounds(-1, 1)
assert limit_seq(sin(pi*n/2)**2, n) == AccumulationBounds(0, 1)
assert limit_seq(2*(-3)**n/(n + 3**n), n) == AccumulationBounds(-2, 2)
assert limit_seq(3*n/(n + 1) + 2*(-1)**n, n) == AccumulationBounds(1, 5)
def test_limitseq_sum():
from sympy.abc import x, y, z
assert limit_seq(Sum(1/x, (x, 1, y)) - log(y), y) == S.EulerGamma
assert limit_seq(Sum(1/x, (x, 1, y)) - 1/y, y) is S.Infinity
assert (limit_seq(binomial(2*x, x) / Sum(binomial(2*y, y), (y, 1, x)), x) ==
S(3) / 4)
assert (limit_seq(Sum(y**2 * Sum(2**z/z, (z, 1, y)), (y, 1, x)) /
(2**x*x), x) == 4)
def test_issue_9308():
assert limit_seq(subfactorial(n)/factorial(n), n) == exp(-1)
def test_issue_10382():
n = Symbol('n', integer=True)
assert limit_seq(fibonacci(n+1)/fibonacci(n), n) == S.GoldenRatio
def test_issue_11672():
assert limit_seq(Rational(-1, 2)**n, n) == 0
def test_issue_16735():
assert limit_seq(5**n/factorial(n), n) == 0
def test_issue_19868():
assert limit_seq(1/gamma(n + S.One/2), n) == 0
@XFAIL
def test_limit_seq_fail():
# improve Summation algorithm or add ad-hoc criteria
e = (harmonic(n)**3 * Sum(1/harmonic(k), (k, 1, n)) /
(n * Sum(harmonic(k)/k, (k, 1, n))))
assert limit_seq(e, n) == 2
# No unique dominant term
e = (Sum(2**k * binomial(2*k, k) / k**2, (k, 1, n)) /
(Sum(2**k/k*2, (k, 1, n)) * Sum(binomial(2*k, k), (k, 1, n))))
assert limit_seq(e, n) == S(3) / 7
# Simplifications of summations needs to be improved.
e = n**3*Sum(2**k/k**2, (k, 1, n))**2 / (2**n * Sum(2**k/k, (k, 1, n)))
assert limit_seq(e, n) == 2
e = (harmonic(n) * Sum(2**k/k, (k, 1, n)) /
(n * Sum(2**k*harmonic(k)/k**2, (k, 1, n))))
assert limit_seq(e, n) == 1
e = (Sum(2**k*factorial(k) / k**2, (k, 1, 2*n)) /
(Sum(4**k/k**2, (k, 1, n)) * Sum(factorial(k), (k, 1, 2*n))))
assert limit_seq(e, n) == S(3) / 16
|
ee1f2a3aa87631157aa4ba74708c6e3bac5ff82a0f7038e92a0b05424a74058a | from sympy import sin, cos, exp, E, series, oo, S, Derivative, O, Integral, \
Function, PoleError, log, sqrt, N, Symbol, Subs, pi, symbols, atan, LambertW, Rational
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 x, y, 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 import Sum, 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_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_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)
|
38b5585b6a8587d9fd6465dfd5ea391d137bfaedc1284ffe7e9a15d62cc6398a | from itertools import product as cartes
from sympy import (
limit, exp, oo, log, sqrt, Limit, sin, floor, cos, ceiling,
atan, Abs, gamma, Symbol, S, pi, Integral, Rational, I,
tan, cot, integrate, Sum, sign, Function, subfactorial, symbols,
binomial, simplify, frac, Float, sec, zoo, fresnelc, fresnels,
acos, erf, erfc, erfi, LambertW, factorial, digamma, Ei, EulerGamma,
asin, atanh, acot, acoth, asec, acsc, cbrt)
from sympy.calculus.util import AccumBounds
from sympy.core.add import Add
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((x + y + 1)**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
# 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*sign((-1)**(-pi))
assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
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_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)
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
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
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_abs():
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)
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_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
t1 = Mul(S.Half, 1/(-1 + cos(1)), Add(AccumBounds(-3, 1), cos(1)))
assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1
t2 = Mul(S.Half, Add(AccumBounds(-2, 2), sin(1)), 1/(-cos(1) + 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)
assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo)
# Possible improvement: AccumBounds(0, 1)
@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_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(cartes([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(cartes([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) is -oo
assert limit(oo - x, x, -oo) is oo
assert limit(x**2/(x - 5) - oo, x, oo) is -oo
assert limit(1/(x + sin(x)) - oo, x, 0) is -oo
assert limit(oo/x, x, oo) is oo
assert limit(x - oo + 1/x, x, oo) is -oo
assert limit(x - oo + 1/x, x, 0) is -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) == n/2
def test_factorial():
from sympy import factorial, E
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)
assert limit(f, x, x**2) == factorial(x**2)
assert limit(f, x, -x**2) == factorial(-x**2)
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 + 3*x**2 - 3*x - 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).simplify() == 2/cos(2*a)
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', real=True, positive=True)
limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0
def test_issue_8730():
assert limit(subfactorial(x), x, oo) is 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) == Float(0.3)
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_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
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).cancel().together() == limit(fx, K, F0).together()
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*(x - 2)*(x - 1)/24
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_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='-').doit() == 0
def test_issue_13575():
assert limit(acos(erfi(x)), x, 1).cancel() == acos(-I*erf(I))
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
@XFAIL
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)*y**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_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_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_18482():
assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1)
def test_issue_18501():
assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo
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_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_18997():
assert limit(Abs(log(x)), x, 0) == oo
assert limit(Abs(log(Abs(x))), x, 0) == oo
def test_issue_19026():
x = Symbol('x', positive=True)
assert limit(Abs(log(x) + 1)/log(x), x, oo) == 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) == p
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_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
|
14903e7542682b28ca5522f62a8d89e8ef81555c4b8bea34558d4b961f0b8ed5 | from sympy import (residue, Symbol, Function, sin, I, exp, log, pi,
factorial, sqrt, Rational)
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, z, a, s
def test_basic1():
assert residue(1/x, x, 0) == 1
assert residue(-2/x, x, 0) == -2
assert residue(81/x, x, 0) == 81
assert residue(1/x**2, x, 0) == 0
assert residue(0, x, 0) == 0
assert residue(5, x, 0) == 0
assert residue(x, x, 0) == 0
assert residue(x**2, x, 0) == 0
def test_basic2():
assert residue(1/x, x, 1) == 0
assert residue(-2/x, x, 1) == 0
assert residue(81/x, x, -1) == 0
assert residue(1/x**2, x, 1) == 0
assert residue(0, x, 1) == 0
assert residue(5, x, 1) == 0
assert residue(x, x, 1) == 0
assert residue(x**2, x, 5) == 0
def test_f():
f = Function("f")
assert residue(f(x)/x**5, x, 0) == f(x).diff(x, 4).subs(x, 0)/24
def test_functions():
assert residue(1/sin(x), x, 0) == 1
assert residue(2/sin(x), x, 0) == 2
assert residue(1/sin(x)**2, x, 0) == 0
assert residue(1/sin(x)**5, x, 0) == Rational(3, 8)
def test_expressions():
assert residue(1/(x + 1), x, 0) == 0
assert residue(1/(x + 1), x, -1) == 1
assert residue(1/(x**2 + 1), x, -1) == 0
assert residue(1/(x**2 + 1), x, I) == -I/2
assert residue(1/(x**2 + 1), x, -I) == I/2
assert residue(1/(x**4 + 1), x, 0) == 0
assert residue(1/(x**4 + 1), x, exp(I*pi/4)).equals(-(Rational(1, 4) + I/4)/sqrt(2))
assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/4/a**3
@XFAIL
def test_expressions_failing():
n = Symbol('n', integer=True, positive=True)
assert residue(exp(z)/(z - pi*I/4*a)**n, z, I*pi*a) == \
exp(I*pi*a/4)/factorial(n - 1)
def test_NotImplemented():
raises(NotImplementedError, lambda: residue(exp(1/z), z, 0))
def test_bug():
assert residue(2**(z)*(s + z)*(1 - s - z)/z**2, z, 0) == \
1 + s*log(2) - s**2*log(2) - 2*s
def test_issue_5654():
assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/(4*a**3)
def test_issue_6499():
assert residue(1/(exp(z) - 1), z, 0) == 1
def test_issue_14037():
assert residue(sin(x**50)/x**51, x, 0) == 1
|
d381b2b5cc61ea8ad71b8393df596248d6dc251e79c43b72f6470aeb114ce97b | from sympy import (
sqrt, root, Symbol, sqrtdenest, Integral, cos, Rational, I, Integer)
from sympy.simplify.sqrtdenest import (
_subsets as subsets, _sqrt_numeric_denest)
from sympy.testing.pytest import slow
r2, r3, r5, r6, r7, r10, r15, r29 = [sqrt(x) for x in [2, 3, 5, 6, 7, 10,
15, 29]]
def test_sqrtdenest():
d = {sqrt(5 + 2 * r6): r2 + r3,
sqrt(5. + 2 * r6): sqrt(5. + 2 * r6),
sqrt(5. + 4*sqrt(5 + 2 * r6)): sqrt(5.0 + 4*r2 + 4*r3),
sqrt(r2): sqrt(r2),
sqrt(5 + r7): sqrt(5 + r7),
sqrt(3 + sqrt(5 + 2*r7)):
3*r2*(5 + 2*r7)**Rational(1, 4)/(2*sqrt(6 + 3*r7)) +
r2*sqrt(6 + 3*r7)/(2*(5 + 2*r7)**Rational(1, 4)),
sqrt(3 + 2*r3): 3**Rational(3, 4)*(r6/2 + 3*r2/2)/3}
for i in d:
assert sqrtdenest(i) == d[i], i
def test_sqrtdenest2():
assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \
r5 + sqrt(11 - 2*r29)
e = sqrt(-r5 + sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16))
assert sqrtdenest(e) == root(-2*r29 + 11, 4)
r = sqrt(1 + r7)
assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r)
e = sqrt(((1 + sqrt(1 + 2*sqrt(3 + r2 + r5)))**2).expand())
assert sqrtdenest(e) == 1 + sqrt(1 + 2*sqrt(r2 + r5 + 3))
assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \
sqrt(2)*root(3, 4) + root(3, 4)**3
assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \
1 + r5 + sqrt(1 + r3)
assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \
1 + sqrt(1 + r3) + r5 + r7
e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand())
assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3)
e = sqrt(-2*r10 + 2*r2*sqrt(-2*r10 + 11) + 14)
assert sqrtdenest(e) == sqrt(-2*r10 - 2*r2 + 4*r5 + 14)
# check that the result is not more complicated than the input
z = sqrt(-2*r29 + cos(2) + 2*sqrt(-10*r29 + 55) + 16)
assert sqrtdenest(z) == z
assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15))
z = sqrt(15 - 2*sqrt(31) + 2*sqrt(55 - 10*r29))
assert sqrtdenest(z) == z
def test_sqrtdenest_rec():
assert sqrtdenest(sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 33)) == \
-r2 + r3 + 2*r7
assert sqrtdenest(sqrt(-28*r7 - 14*r5 + 4*sqrt(35) + 82)) == \
-7 + r5 + 2*r7
assert sqrtdenest(sqrt(6*r2/11 + 2*sqrt(22)/11 + 6*sqrt(11)/11 + 2)) == \
sqrt(11)*(r2 + 3 + sqrt(11))/11
assert sqrtdenest(sqrt(468*r3 + 3024*r2 + 2912*r6 + 19735)) == \
9*r3 + 26 + 56*r6
z = sqrt(-490*r3 - 98*sqrt(115) - 98*sqrt(345) - 2107)
assert sqrtdenest(z) == sqrt(-1)*(7*r5 + 7*r15 + 7*sqrt(23))
z = sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 34)
assert sqrtdenest(z) == z
assert sqrtdenest(sqrt(-8*r2 - 2*r5 + 18)) == -r10 + 1 + r2 + r5
assert sqrtdenest(sqrt(8*r2 + 2*r5 - 18)) == \
sqrt(-1)*(-r10 + 1 + r2 + r5)
assert sqrtdenest(sqrt(8*r2/3 + 14*r5/3 + Rational(154, 9))) == \
-r10/3 + r2 + r5 + 3
assert sqrtdenest(sqrt(sqrt(2*r6 + 5) + sqrt(2*r7 + 8))) == \
sqrt(1 + r2 + r3 + r7)
assert sqrtdenest(sqrt(4*r15 + 8*r5 + 12*r3 + 24)) == 1 + r3 + r5 + r15
w = 1 + r2 + r3 + r5 + r7
assert sqrtdenest(sqrt((w**2).expand())) == w
z = sqrt((w**2).expand() + 1)
assert sqrtdenest(z) == z
z = sqrt(2*r10 + 6*r2 + 4*r5 + 12 + 10*r15 + 30*r3)
assert sqrtdenest(z) == z
def test_issue_6241():
z = sqrt( -320 + 32*sqrt(5) + 64*r15)
assert sqrtdenest(z) == z
def test_sqrtdenest3():
z = sqrt(13 - 2*r10 + 2*r2*sqrt(-2*r10 + 11))
assert sqrtdenest(z) == -1 + r2 + r10
assert sqrtdenest(z, max_iter=1) == -1 + sqrt(2) + sqrt(10)
z = sqrt(sqrt(r2 + 2) + 2)
assert sqrtdenest(z) == z
assert sqrtdenest(sqrt(-2*r10 + 4*r2*sqrt(-2*r10 + 11) + 20)) == \
sqrt(-2*r10 - 4*r2 + 8*r5 + 20)
assert sqrtdenest(sqrt((112 + 70*r2) + (46 + 34*r2)*r5)) == \
r10 + 5 + 4*r2 + 3*r5
z = sqrt(5 + sqrt(2*r6 + 5)*sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16))
r = sqrt(-2*r29 + 11)
assert sqrtdenest(z) == sqrt(r2*r + r3*r + r10 + r15 + 5)
@slow
def test_sqrtdenest3_slow():
# Slow because of the equals, not the sqrtdenest
# Using == does not work as 7*(sqrt(-2*r29 + 11) + r5) is expanded
# automatically
n = sqrt(2*r6/7 + 2*r7/7 + 2*sqrt(42)/7 + 2)
d = sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))
assert sqrtdenest(n/d).equals(
r7*(1 + r6 + r7)/(7*(sqrt(-2*r29 + 11) + r5)))
def test_sqrtdenest4():
# see Denest_en.pdf in https://github.com/sympy/sympy/issues/3192
z = sqrt(8 - r2*sqrt(5 - r5) - sqrt(3)*(1 + r5))
z1 = sqrtdenest(z)
c = sqrt(-r5 + 5)
z1 = ((-r15*c - r3*c + c + r5*c - r6 - r2 + r10 + sqrt(30))/4).expand()
assert sqrtdenest(z) == z1
z = sqrt(2*r2*sqrt(r2 + 2) + 5*r2 + 4*sqrt(r2 + 2) + 8)
assert sqrtdenest(z) == r2 + sqrt(r2 + 2) + 2
w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3)
z = sqrt((w**2).expand())
assert sqrtdenest(z) == w.expand()
def test_sqrt_symbolic_denest():
x = Symbol('x')
z = sqrt(((1 + sqrt(sqrt(2 + x) + 3))**2).expand())
assert sqrtdenest(z) == sqrt((1 + sqrt(sqrt(2 + x) + 3))**2)
z = sqrt(((1 + sqrt(sqrt(2 + cos(1)) + 3))**2).expand())
assert sqrtdenest(z) == 1 + sqrt(sqrt(2 + cos(1)) + 3)
z = ((1 + cos(2))**4 + 1).expand()
assert sqrtdenest(z) == z
z = sqrt(((1 + sqrt(sqrt(2 + cos(3*x)) + 3))**2 + 1).expand())
assert sqrtdenest(z) == z
c = cos(3)
c2 = c**2
assert sqrtdenest(sqrt(2*sqrt(1 + r3)*c + c2 + 1 + r3*c2)) == \
-1 - sqrt(1 + r3)*c
ra = sqrt(1 + r3)
z = sqrt(20*ra*sqrt(3 + 3*r3) + 12*r3*ra*sqrt(3 + 3*r3) + 64*r3 + 112)
assert sqrtdenest(z) == z
def test_issue_5857():
from sympy.abc import x, y
z = sqrt(1/(4*r3 + 7) + 1)
ans = (r2 + r6)/(r3 + 2)
assert sqrtdenest(z) == ans
assert sqrtdenest(1 + z) == 1 + ans
assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \
Integral(1 + ans, (x, 1, 2))
assert sqrtdenest(x + sqrt(y)) == x + sqrt(y)
ans = (r2 + r6)/(r3 + 2)
assert sqrtdenest(z) == ans
assert sqrtdenest(1 + z) == 1 + ans
assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \
Integral(1 + ans, (x, 1, 2))
assert sqrtdenest(x + sqrt(y)) == x + sqrt(y)
def test_subsets():
assert subsets(1) == [[1]]
assert subsets(4) == [
[1, 0, 0, 0], [0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [1, 0, 1, 0],
[0, 1, 1, 0], [1, 1, 1, 0], [0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1],
[1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]]
def test_issue_5653():
assert sqrtdenest(
sqrt(2 + sqrt(2 + sqrt(2)))) == sqrt(2 + sqrt(2 + sqrt(2)))
def test_issue_12420():
assert sqrtdenest((3 - sqrt(2)*sqrt(4 + 3*I) + 3*I)/2) == I
e = 3 - sqrt(2)*sqrt(4 + I) + 3*I
assert sqrtdenest(e) == e
def test_sqrt_ratcomb():
assert sqrtdenest(sqrt(1 + r3) + sqrt(3 + 3*r3) - sqrt(10 + 6*r3)) == 0
def test_issue_18041():
e = -sqrt(-2 + 2*sqrt(3)*I)
assert sqrtdenest(e) == -1 - sqrt(3)*I
def test_issue_19914():
a = Integer(-8)
b = Integer(-1)
r = Integer(63)
d2 = a*a - b*b*r
assert _sqrt_numeric_denest(a, b, r, d2) == \
sqrt(14)*I/2 + 3*sqrt(2)*I/2
assert sqrtdenest(sqrt(-8-sqrt(63))) == sqrt(14)*I/2 + 3*sqrt(2)*I/2
|
2f37a09d16d1399dd39c54618536359e75276af6d62729a4779724be53989154 | from sympy.core.symbol import symbols
from sympy.printing import ccode
from sympy.codegen.ast import Declaration, Variable, float64, int64, String
from sympy.codegen.cnodes import (
alignof, CommaOperator, goto, Label, PreDecrement, PostDecrement, PreIncrement, PostIncrement,
sizeof, union, struct
)
x, y = symbols('x y')
def test_alignof():
ax = alignof(x)
assert ccode(ax) == 'alignof(x)'
assert ax.func(*ax.args) == ax
def test_CommaOperator():
expr = CommaOperator(PreIncrement(x), 2*x)
assert ccode(expr) == '(++(x), 2*x)'
assert expr.func(*expr.args) == expr
def test_goto_Label():
s = 'early_exit'
g = goto(s)
assert g.func(*g.args) == g
assert g != goto('foobar')
assert ccode(g) == 'goto early_exit'
l = Label(s)
assert l.is_Atom
assert ccode(l) == 'early_exit:'
assert g.label == l
assert l == Label(s)
assert l != Label('foobar')
def test_PreDecrement():
p = PreDecrement(x)
assert p.func(*p.args) == p
assert ccode(p) == '--(x)'
def test_PostDecrement():
p = PostDecrement(x)
assert p.func(*p.args) == p
assert ccode(p) == '(x)--'
def test_PreIncrement():
p = PreIncrement(x)
assert p.func(*p.args) == p
assert ccode(p) == '++(x)'
def test_PostIncrement():
p = PostIncrement(x)
assert p.func(*p.args) == p
assert ccode(p) == '(x)++'
def test_sizeof():
typename = 'unsigned int'
sz = sizeof(typename)
assert ccode(sz) == 'sizeof(%s)' % typename
assert sz.func(*sz.args) == sz
assert not sz.is_Atom
assert sz.atoms() == {String('unsigned int'), String('sizeof')}
def test_struct():
vx, vy = Variable(x, type=float64), Variable(y, type=float64)
s = struct('vec2', [vx, vy])
assert s.func(*s.args) == s
assert s == struct('vec2', (vx, vy))
assert s != struct('vec2', (vy, vx))
assert str(s.name) == 'vec2'
assert len(s.declarations) == 2
assert all(isinstance(arg, Declaration) for arg in s.declarations)
assert ccode(s) == (
"struct vec2 {\n"
" double x;\n"
" double y;\n"
"}")
def test_union():
vx, vy = Variable(x, type=float64), Variable(y, type=int64)
u = union('dualuse', [vx, vy])
assert u.func(*u.args) == u
assert u == union('dualuse', (vx, vy))
assert str(u.name) == 'dualuse'
assert len(u.declarations) == 2
assert all(isinstance(arg, Declaration) for arg in u.declarations)
assert ccode(u) == (
"union dualuse {\n"
" double x;\n"
" int64_t y;\n"
"}")
|
c57c253d4b5bc688e955edf4a89c8ad178585871e8ba4df0757858ee42695a63 | import os
import tempfile
from sympy import Symbol, symbols
from sympy.codegen.ast import (
Assignment, Print, Declaration, FunctionDefinition, Return, real,
FunctionCall, Variable, Element, integer
)
from sympy.codegen.fnodes import (
allocatable, ArrayConstructor, isign, dsign, cmplx, kind, literal_dp,
Program, Module, use, Subroutine, dimension, assumed_extent, ImpliedDoLoop,
intent_out, size, Do, SubroutineCall, sum_, array, bind_C
)
from sympy.codegen.futils import render_as_module
from sympy.core.expr import unchanged
from sympy.external import import_module
from sympy.printing import fcode
from sympy.utilities._compilation import has_fortran, compile_run_strings, compile_link_import_strings
from sympy.utilities._compilation.util import may_xfail
from sympy.testing.pytest import skip
cython = import_module('cython')
np = import_module('numpy')
def test_size():
x = Symbol('x', real=True)
sx = size(x)
assert fcode(sx, source_format='free') == 'size(x)'
@may_xfail
def test_size_assumed_shape():
if not has_fortran():
skip("No fortran compiler found.")
a = Symbol('a', real=True)
body = [Return((sum_(a**2)/size(a))**.5)]
arr = array(a, dim=[':'], intent='in')
fd = FunctionDefinition(real, 'rms', [arr], body)
render_as_module([fd], 'mod_rms')
(stdout, stderr), info = compile_run_strings([
('rms.f90', render_as_module([fd], 'mod_rms')),
('main.f90', (
'program myprog\n'
'use mod_rms, only: rms\n'
'real*8, dimension(4), parameter :: x = [4, 2, 2, 2]\n'
'print *, dsqrt(7d0) - rms(x)\n'
'end program\n'
))
], clean=True)
assert '0.00000' in stdout
assert stderr == ''
assert info['exit_status'] == os.EX_OK
@may_xfail
def test_ImpliedDoLoop():
if not has_fortran():
skip("No fortran compiler found.")
a, i = symbols('a i', integer=True)
idl = ImpliedDoLoop(i**3, i, -3, 3, 2)
ac = ArrayConstructor([-28, idl, 28])
a = array(a, dim=[':'], attrs=[allocatable])
prog = Program('idlprog', [
a.as_Declaration(),
Assignment(a, ac),
Print([a])
])
fsrc = fcode(prog, standard=2003, source_format='free')
(stdout, stderr), info = compile_run_strings([('main.f90', fsrc)], clean=True)
for numstr in '-28 -27 -1 1 27 28'.split():
assert numstr in stdout
assert stderr == ''
assert info['exit_status'] == os.EX_OK
@may_xfail
def test_Program():
x = Symbol('x', real=True)
vx = Variable.deduced(x, 42)
decl = Declaration(vx)
prnt = Print([x, x+1])
prog = Program('foo', [decl, prnt])
if not has_fortran():
skip("No fortran compiler found.")
(stdout, stderr), info = compile_run_strings([('main.f90', fcode(prog, standard=90))], clean=True)
assert '42' in stdout
assert '43' in stdout
assert stderr == ''
assert info['exit_status'] == os.EX_OK
@may_xfail
def test_Module():
x = Symbol('x', real=True)
v_x = Variable.deduced(x)
sq = FunctionDefinition(real, 'sqr', [v_x], [Return(x**2)])
mod_sq = Module('mod_sq', [], [sq])
sq_call = FunctionCall('sqr', [42.])
prg_sq = Program('foobar', [
use('mod_sq', only=['sqr']),
Print(['"Square of 42 = "', sq_call])
])
if not has_fortran():
skip("No fortran compiler found.")
(stdout, stderr), info = compile_run_strings([
('mod_sq.f90', fcode(mod_sq, standard=90)),
('main.f90', fcode(prg_sq, standard=90))
], clean=True)
assert '42' in stdout
assert str(42**2) in stdout
assert stderr == ''
@may_xfail
def test_Subroutine():
# Code to generate the subroutine in the example from
# http://www.fortran90.org/src/best-practices.html#arrays
r = Symbol('r', real=True)
i = Symbol('i', integer=True)
v_r = Variable.deduced(r, attrs=(dimension(assumed_extent), intent_out))
v_i = Variable.deduced(i)
v_n = Variable('n', integer)
do_loop = Do([
Assignment(Element(r, [i]), literal_dp(1)/i**2)
], i, 1, v_n)
sub = Subroutine("f", [v_r], [
Declaration(v_n),
Declaration(v_i),
Assignment(v_n, size(r)),
do_loop
])
x = Symbol('x', real=True)
v_x3 = Variable.deduced(x, attrs=[dimension(3)])
mod = Module('mymod', definitions=[sub])
prog = Program('foo', [
use(mod, only=[sub]),
Declaration(v_x3),
SubroutineCall(sub, [v_x3]),
Print([sum_(v_x3), v_x3])
])
if not has_fortran():
skip("No fortran compiler found.")
(stdout, stderr), info = compile_run_strings([
('a.f90', fcode(mod, standard=90)),
('b.f90', fcode(prog, standard=90))
], clean=True)
ref = [1.0/i**2 for i in range(1, 4)]
assert str(sum(ref))[:-3] in stdout
for _ in ref:
assert str(_)[:-3] in stdout
assert stderr == ''
def test_isign():
x = Symbol('x', integer=True)
assert unchanged(isign, 1, x)
assert fcode(isign(1, x), standard=95, source_format='free') == 'isign(1, x)'
def test_dsign():
x = Symbol('x')
assert unchanged(dsign, 1, x)
assert fcode(dsign(literal_dp(1), x), standard=95, source_format='free') == 'dsign(1d0, x)'
def test_cmplx():
x = Symbol('x')
assert unchanged(cmplx, 1, x)
def test_kind():
x = Symbol('x')
assert unchanged(kind, x)
def test_literal_dp():
assert fcode(literal_dp(0), source_format='free') == '0d0'
@may_xfail
def test_bind_C():
if not has_fortran():
skip("No fortran compiler found.")
if not cython:
skip("Cython not found.")
if not np:
skip("NumPy not found.")
a = Symbol('a', real=True)
s = Symbol('s', integer=True)
body = [Return((sum_(a**2)/s)**.5)]
arr = array(a, dim=[s], intent='in')
fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')])
f_mod = render_as_module([fd], 'mod_rms')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('rms.f90', f_mod),
('_rms.pyx', (
"#cython: language_level={}\n".format("3") +
"cdef extern double rms(double*, int*)\n"
"def py_rms(double[::1] x):\n"
" cdef int s = x.size\n"
" return rms(&x[0], &s)\n"))
], build_dir=folder)
assert abs(mod.py_rms(np.array([2., 4., 2., 2.])) - 7**0.5) < 1e-14
|
d897d8fb32a8c49f4c59a4e88823d9042dd11d4232223b3904eedb4bf0041e52 | from sympy.core.symbol import Symbol
from sympy.codegen.ast import Type
from sympy.codegen.cxxnodes import using
from sympy.printing import cxxcode
x = Symbol('x')
def test_using():
v = Type('std::vector')
u1 = using(v)
assert cxxcode(u1) == 'using std::vector'
u2 = using(v, 'vec')
assert cxxcode(u2) == 'using vec = std::vector'
|
cf24ae024b8dcdcf85286964402ea8dd208088885db31050d325be364e470c75 | from sympy import log, exp, Symbol, Pow, sin, MatrixSymbol
from sympy.assumptions import assuming, Q
from sympy.printing import ccode
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.codegen.cfunctions import log2, exp2, expm1, log1p
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.rewriting import (
optimize, log2_opt, exp2_opt, expm1_opt, log1p_opt, optims_c99,
create_expand_pow_optimization, matinv_opt, logaddexp_opt, logaddexp2_opt
)
from sympy.testing.pytest import XFAIL
def test_log2_opt():
x = Symbol('x')
expr1 = 7*log(3*x + 5)/(log(2))
opt1 = optimize(expr1, [log2_opt])
assert opt1 == 7*log2(3*x + 5)
assert opt1.rewrite(log) == expr1
expr2 = 3*log(5*x + 7)/(13*log(2))
opt2 = optimize(expr2, [log2_opt])
assert opt2 == 3*log2(5*x + 7)/13
assert opt2.rewrite(log) == expr2
expr3 = log(x)/log(2)
opt3 = optimize(expr3, [log2_opt])
assert opt3 == log2(x)
assert opt3.rewrite(log) == expr3
expr4 = log(x)/log(2) + log(x+1)
opt4 = optimize(expr4, [log2_opt])
assert opt4 == log2(x) + log(2)*log2(x+1)
assert opt4.rewrite(log) == expr4
expr5 = log(17)
opt5 = optimize(expr5, [log2_opt])
assert opt5 == expr5
expr6 = log(x + 3)/log(2)
opt6 = optimize(expr6, [log2_opt])
assert str(opt6) == 'log2(x + 3)'
assert opt6.rewrite(log) == expr6
def test_exp2_opt():
x = Symbol('x')
expr1 = 1 + 2**x
opt1 = optimize(expr1, [exp2_opt])
assert opt1 == 1 + exp2(x)
assert opt1.rewrite(Pow) == expr1
expr2 = 1 + 3**x
assert expr2 == optimize(expr2, [exp2_opt])
def test_expm1_opt():
x = Symbol('x')
expr1 = exp(x) - 1
opt1 = optimize(expr1, [expm1_opt])
assert expm1(x) - opt1 == 0
assert opt1.rewrite(exp) == expr1
expr2 = 3*exp(x) - 3
opt2 = optimize(expr2, [expm1_opt])
assert 3*expm1(x) == opt2
assert opt2.rewrite(exp) == expr2
expr3 = 3*exp(x) - 5
assert expr3 == optimize(expr3, [expm1_opt])
expr4 = 3*exp(x) + log(x) - 3
opt4 = optimize(expr4, [expm1_opt])
assert 3*expm1(x) + log(x) == opt4
assert opt4.rewrite(exp) == expr4
expr5 = 3*exp(2*x) - 3
opt5 = optimize(expr5, [expm1_opt])
assert 3*expm1(2*x) == opt5
assert opt5.rewrite(exp) == expr5
@XFAIL
def test_expm1_two_exp_terms():
x, y = map(Symbol, 'x y'.split())
expr1 = exp(x) + exp(y) - 2
opt1 = optimize(expr1, [expm1_opt])
assert opt1 == expm1(x) + expm1(y)
def test_log1p_opt():
x = Symbol('x')
expr1 = log(x + 1)
opt1 = optimize(expr1, [log1p_opt])
assert log1p(x) - opt1 == 0
assert opt1.rewrite(log) == expr1
expr2 = log(3*x + 3)
opt2 = optimize(expr2, [log1p_opt])
assert log1p(x) + log(3) == opt2
assert (opt2.rewrite(log) - expr2).simplify() == 0
expr3 = log(2*x + 1)
opt3 = optimize(expr3, [log1p_opt])
assert log1p(2*x) - opt3 == 0
assert opt3.rewrite(log) == expr3
expr4 = log(x+3)
opt4 = optimize(expr4, [log1p_opt])
assert str(opt4) == 'log(x + 3)'
def test_optims_c99():
x = Symbol('x')
expr1 = 2**x + log(x)/log(2) + log(x + 1) + exp(x) - 1
opt1 = optimize(expr1, optims_c99).simplify()
assert opt1 == exp2(x) + log2(x) + log1p(x) + expm1(x)
assert opt1.rewrite(exp).rewrite(log).rewrite(Pow) == expr1
expr2 = log(x)/log(2) + log(x + 1)
opt2 = optimize(expr2, optims_c99)
assert opt2 == log2(x) + log1p(x)
assert opt2.rewrite(log) == expr2
expr3 = log(x)/log(2) + log(17*x + 17)
opt3 = optimize(expr3, optims_c99)
delta3 = opt3 - (log2(x) + log(17) + log1p(x))
assert delta3 == 0
assert (opt3.rewrite(log) - expr3).simplify() == 0
expr4 = 2**x + 3*log(5*x + 7)/(13*log(2)) + 11*exp(x) - 11 + log(17*x + 17)
opt4 = optimize(expr4, optims_c99).simplify()
delta4 = opt4 - (exp2(x) + 3*log2(5*x + 7)/13 + 11*expm1(x) + log(17) + log1p(x))
assert delta4 == 0
assert (opt4.rewrite(exp).rewrite(log).rewrite(Pow) - expr4).simplify() == 0
expr5 = 3*exp(2*x) - 3
opt5 = optimize(expr5, optims_c99)
delta5 = opt5 - 3*expm1(2*x)
assert delta5 == 0
assert opt5.rewrite(exp) == expr5
expr6 = exp(2*x) - 3
opt6 = optimize(expr6, optims_c99)
delta6 = opt6 - (exp(2*x) - 3)
assert delta6 == 0
expr7 = log(3*x + 3)
opt7 = optimize(expr7, optims_c99)
delta7 = opt7 - (log(3) + log1p(x))
assert delta7 == 0
assert (opt7.rewrite(log) - expr7).simplify() == 0
expr8 = log(2*x + 3)
opt8 = optimize(expr8, optims_c99)
assert opt8 == expr8
def test_create_expand_pow_optimization():
cc = lambda x: ccode(
optimize(x, [create_expand_pow_optimization(4)]))
x = Symbol('x')
assert cc(x**4) == 'x*x*x*x'
assert cc(x**4 + x**2) == 'x*x + x*x*x*x'
assert cc(x**5 + x**4) == 'pow(x, 5) + x*x*x*x'
assert cc(sin(x)**4) == 'pow(sin(x), 4)'
# gh issue 15335
assert cc(x**(-4)) == '1.0/(x*x*x*x)'
assert cc(x**(-5)) == 'pow(x, -5)'
assert cc(-x**4) == '-x*x*x*x'
assert cc(x**4 - x**2) == '-x*x + x*x*x*x'
i = Symbol('i', integer=True)
assert cc(x**i - x**2) == 'pow(x, i) - x*x'
def test_matsolve():
n = Symbol('n', integer=True)
A = MatrixSymbol('A', n, n)
x = MatrixSymbol('x', n, 1)
with assuming(Q.fullrank(A)):
assert optimize(A**(-1) * x, [matinv_opt]) == MatrixSolve(A, x)
assert optimize(A**(-1) * x + x, [matinv_opt]) == MatrixSolve(A, x) + x
def test_logaddexp_opt():
x, y = map(Symbol, 'x y'.split())
expr1 = log(exp(x) + exp(y))
opt1 = optimize(expr1, [logaddexp_opt])
assert logaddexp(x, y) - opt1 == 0
assert logaddexp(y, x) - opt1 == 0
assert opt1.rewrite(log) == expr1
def test_logaddexp2_opt():
x, y = map(Symbol, 'x y'.split())
expr1 = log(2**x + 2**y)/log(2)
opt1 = optimize(expr1, [logaddexp2_opt])
assert logaddexp2(x, y) - opt1 == 0
assert logaddexp2(y, x) - opt1 == 0
assert opt1.rewrite(log) == expr1
|
f7ebbb4483bfa39e597d4c14012fba664e3b5da9e9ef851bf6ba0a517381fa34 | import tempfile
import sympy as sp
from sympy.core.compatibility import exec_
from sympy.codegen.ast import Assignment
from sympy.codegen.algorithms import newtons_method, newtons_method_function
from sympy.codegen.fnodes import bind_C
from sympy.codegen.futils import render_as_module as f_module
from sympy.codegen.pyutils import render_as_module as py_module
from sympy.external import import_module
from sympy.printing import ccode
from sympy.utilities._compilation import compile_link_import_strings, has_c, has_fortran
from sympy.utilities._compilation.util import may_xfail
from sympy.testing.pytest import skip, raises
cython = import_module('cython')
wurlitzer = import_module('wurlitzer')
def test_newtons_method():
x, dx, atol = sp.symbols('x dx atol')
expr = sp.cos(x) - x**3
algo = newtons_method(expr, x, atol, dx)
assert algo.has(Assignment(dx, -expr/expr.diff(x)))
@may_xfail
def test_newtons_method_function__ccode():
x = sp.Symbol('x', real=True)
expr = sp.cos(x) - x**3
func = newtons_method_function(expr, x)
if not cython:
skip("cython not installed.")
if not has_c():
skip("No C compiler found.")
compile_kw = dict(std='c99')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('newton.c', ('#include <math.h>\n'
'#include <stdio.h>\n') + ccode(func)),
('_newton.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern double newton(double)\n"
"def py_newton(x):\n"
" return newton(x)\n"))
], build_dir=folder, compile_kwargs=compile_kw)
assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
@may_xfail
def test_newtons_method_function__fcode():
x = sp.Symbol('x', real=True)
expr = sp.cos(x) - x**3
func = newtons_method_function(expr, x, attrs=[bind_C(name='newton')])
if not cython:
skip("cython not installed.")
if not has_fortran():
skip("No Fortran compiler found.")
f_mod = f_module([func], 'mod_newton')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('newton.f90', f_mod),
('_newton.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern double newton(double*)\n"
"def py_newton(double x):\n"
" return newton(&x)\n"))
], build_dir=folder)
assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
def test_newtons_method_function__pycode():
x = sp.Symbol('x', real=True)
expr = sp.cos(x) - x**3
func = newtons_method_function(expr, x)
py_mod = py_module(func)
namespace = {}
exec_(py_mod, namespace, namespace)
res = eval('newton(0.5)', namespace)
assert abs(res - 0.865474033102) < 1e-12
@may_xfail
def test_newtons_method_function__ccode_parameters():
args = x, A, k, p = sp.symbols('x A k p')
expr = A*sp.cos(k*x) - p*x**3
raises(ValueError, lambda: newtons_method_function(expr, x))
use_wurlitzer = wurlitzer
func = newtons_method_function(expr, x, args, debug=use_wurlitzer)
if not has_c():
skip("No C compiler found.")
if not cython:
skip("cython not installed.")
compile_kw = dict(std='c99')
with tempfile.TemporaryDirectory() as folder:
mod, info = compile_link_import_strings([
('newton_par.c', ('#include <math.h>\n'
'#include <stdio.h>\n') + ccode(func)),
('_newton_par.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern double newton(double, double, double, double)\n"
"def py_newton(x, A=1, k=1, p=1):\n"
" return newton(x, A, k, p)\n"))
], compile_kwargs=compile_kw, build_dir=folder)
if use_wurlitzer:
with wurlitzer.pipes() as (out, err):
result = mod.py_newton(0.5)
else:
result = mod.py_newton(0.5)
assert abs(result - 0.865474033102) < 1e-12
if not use_wurlitzer:
skip("C-level output only tested when package 'wurlitzer' is available.")
out, err = out.read(), err.read()
assert err == ''
assert out == """\
x= 0.5 d_x= 0.61214
x= 1.1121 d_x= -0.20247
x= 0.90967 d_x= -0.042409
x= 0.86726 d_x= -0.0017867
x= 0.86548 d_x= -3.1022e-06
x= 0.86547 d_x= -9.3421e-12
x= 0.86547 d_x= 3.6902e-17
""" # try to run tests with LC_ALL=C if this assertion fails
|
182ed3232ab5f7a85ebb6f9a7fd1273c1b24ab71e38faa52f73ff5c51c75e7ad | from itertools import product
from sympy import symbols, exp, log, S
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
x, y, z = symbols('x y z')
def test_logaddexp():
lae_xy = logaddexp(x, y)
ref_xy = log(exp(x) + exp(y))
for wrt, deriv_order in product([x, y, z], range(0, 3)):
assert (
lae_xy.diff(wrt, deriv_order) -
ref_xy.diff(wrt, deriv_order)
).rewrite(log).simplify() == 0
one_third_e = 1*exp(1)/3
two_thirds_e = 2*exp(1)/3
logThirdE = log(one_third_e)
logTwoThirdsE = log(two_thirds_e)
lae_sum_to_e = logaddexp(logThirdE, logTwoThirdsE)
assert lae_sum_to_e.rewrite(log) == 1
assert lae_sum_to_e.simplify() == 1
assert logaddexp(2, 3).simplify() == logaddexp(2, 3) # cannot simplify with 2, 3
def test_logaddexp2():
lae2_xy = logaddexp2(x, y)
ref2_xy = log(2**x + 2**y)/log(2)
for wrt, deriv_order in product([x, y, z], range(0, 3)):
assert (
lae2_xy.diff(wrt, deriv_order) -
ref2_xy.diff(wrt, deriv_order)
).rewrite(log).simplify() == 0
def lb(x):
return log(x)/log(2)
two_thirds = S.One*2/3
four_thirds = 2*two_thirds
lbTwoThirds = lb(two_thirds)
lbFourThirds = lb(four_thirds)
lae2_sum_to_2 = logaddexp2(lbTwoThirds, lbFourThirds)
assert lae2_sum_to_2.rewrite(log) == 1
assert lae2_sum_to_2.simplify() == 1
assert logaddexp2(x, y).simplify() == logaddexp2(x, y) # cannot simplify with x, y
|
d48fc83272d49b8a9328fc4e5952add190444cad489ecdf6f304d6d47ea1e881 | # This file contains tests that exercise multiple AST nodes
import tempfile
from sympy.external import import_module
from sympy.printing import ccode
from sympy.utilities._compilation import compile_link_import_strings, has_c
from sympy.utilities._compilation.util import may_xfail
from sympy.testing.pytest import skip
from sympy.codegen.ast import (
FunctionDefinition, FunctionPrototype, Variable, Pointer, real, Assignment,
integer, CodeBlock, While
)
from sympy.codegen.cnodes import void, PreIncrement
from sympy.codegen.cutils import render_as_source_file
cython = import_module('cython')
np = import_module('numpy')
def _mk_func1():
declars = n, inp, out = Variable('n', integer), Pointer('inp', real), Pointer('out', real)
i = Variable('i', integer)
whl = While(i<n, [Assignment(out[i], inp[i]), PreIncrement(i)])
body = CodeBlock(i.as_Declaration(value=0), whl)
return FunctionDefinition(void, 'our_test_function', declars, body)
def _render_compile_import(funcdef, build_dir):
code_str = render_as_source_file(funcdef, settings=dict(contract=False))
declar = ccode(FunctionPrototype.from_FunctionDefinition(funcdef))
return compile_link_import_strings([
('our_test_func.c', code_str),
('_our_test_func.pyx', ("#cython: language_level={}\n".format("3") +
"cdef extern {declar}\n"
"def _{fname}({typ}[:] inp, {typ}[:] out):\n"
" {fname}(inp.size, &inp[0], &out[0])").format(
declar=declar, fname=funcdef.name, typ='double'
))
], build_dir=build_dir)
@may_xfail
def test_copying_function():
if not np:
skip("numpy not installed.")
if not has_c():
skip("No C compiler found.")
if not cython:
skip("Cython not found.")
info = None
with tempfile.TemporaryDirectory() as folder:
mod, info = _render_compile_import(_mk_func1(), build_dir=folder)
inp = np.arange(10.0)
out = np.empty_like(inp)
mod._our_test_function(inp, out)
assert np.allclose(inp, out)
|
38a14793ebd2018bd0b3991f2f36870e92854e19fec9cd9bfac1011927c8548c | from sympy.core.add import Add
from sympy.core.basic import sympify, cacheit
from sympy.core.function import Function, ArgumentIndexError, PoleError, expand_mul
from sympy.core.logic import fuzzy_not, fuzzy_or, FuzzyBool
from sympy.core.numbers import igcdex, Rational, pi
from sympy.core.relational import Ne
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.elementary.exponential import log, exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh,
coth, HyperbolicFunction, sinh, tanh)
from sympy.functions.elementary.miscellaneous import sqrt, Min, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.sets.sets import FiniteSet
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):
"""
Split ARG into two parts, a "rest" and a multiple of pi/2.
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 as peel
>>> from sympy import pi
>>> from sympy.abc import x, y
>>> peel(x + pi/2)
(x, pi/2)
>>> peel(x + 2*pi/3 + pi*y)
(x + pi*y + pi/6, pi/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)*S.Pi
m2 = pi_coeff*S.Pi - m1
final_coeff = m2 / S.Pi
if final_coeff.is_integer or ((2*final_coeff).is_integer
and final_coeff.is_even is False):
return Add(*(rest_terms + [m1])), m2
return arg, S.Zero
def _pi_coeff(arg, cycles=1):
"""
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 as coeff
>>> from sympy import pi, Dummy
>>> from sympy.abc import x
>>> coeff(3*x*pi)
3*x
>>> coeff(11*pi/7)
11/7
>>> coeff(-11*pi/7)
3/7
>>> coeff(4*pi)
0
>>> coeff(5*pi)
1
>>> coeff(5.0*pi)
1
>>> coeff(5.5*pi)
3/2
>>> coeff(2 + pi)
>>> coeff(2*Dummy(integer=True)*pi)
2
>>> 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 S(2)
else:
return c2*x
return cx
elif arg.is_zero:
return S.Zero
class sin(TrigonometricFunction):
"""
The sine function.
Returns the sine of x (measured in radians).
Notes
=====
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 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 is S.Infinity or arg is S.NegativeInfinity:
return AccumBounds(-1, 1)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
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:
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:
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 (-1)**(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
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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):
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 import expand_mul
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
else:
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 (-1)**((n - 1)/2)*chebyshevt(n, sin(x))
else:
return expand_mul((-1)**(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, cdir=0):
from sympy 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:
if not arg.subs(x, 0).is_finite:
return self
else:
return self.func(arg)
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):
arg = self.args[0]
if arg.is_zero:
return True
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).
Notes
=====
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.util 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 is S.Infinity or arg is 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:
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 == nvala or None == 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:
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 (-1)**(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
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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):
from sympy.ntheory import factorint
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):
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
else:
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, cdir=0):
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 ((-1)**n)*lt
if not x0.is_finite:
return self
return self.func(x0)
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
class tan(TrigonometricFunction):
"""
The tangent function.
Returns the tangent of x (measured in radians).
Notes
=====
See :func:`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.util import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.Zero
elif arg is S.Infinity or arg is 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
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:
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 == 5 or q == 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 == nvala or None == 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)
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):
from sympy import bernoulli
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 (-1)**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:
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):
from sympy import im, re
arg = self.args[0]
x = None
if arg.is_Add:
from sympy import symmetric_poly
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)))
else:
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
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0)
n = x0/S.Pi
if n.is_integer:
lt = (arg - n*S.Pi).as_leading_term(x)
return lt if n.is_even else -1/lt
if not x0.is_finite:
return self
return self.func(x0)
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):
arg = self.args[0]
if arg.is_zero:
return True
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).
Notes
=====
See :func:`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.util import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
if arg.is_zero:
return S.ComplexInfinity
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:
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 == 5 or pi_coeff.q == 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 == nvala or None == 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)
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):
from sympy import bernoulli
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 (-1)**((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:
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):
I = S.ImaginaryUnit
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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, cdir=0):
from sympy 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_is_extended_real(self):
return self.args[0].is_extended_real
def _eval_expand_trig(self, **hints):
from sympy import im, re
arg = self.args[0]
x = None
if arg.is_Add:
from sympy import symmetric_poly
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)))
else:
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)
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_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, 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).
Notes
=====
See :func:`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/
from sympy.functions.combinatorial.numbers import euler
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
k = n//2
return (-1)**k*euler(2*k)/factorial(2*k)*x**(2*k)
def _eval_as_leading_term(self, x, cdir=0):
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 ((-1)**n)/lt
return self.func(x0)
class csc(ReciprocalTrigonometricFunction):
"""
The cosecant function.
Returns the cosecant of x (measured in radians).
Notes
=====
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):
from sympy import bernoulli
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 ((-1)**(k - 1)*2*(2**(2*k - 1) - 1)*
bernoulli(2*k)*x**(2*k - 1)/factorial(2*k))
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()
Piecewise(((x*cos(x) - sin(x))/x**2, Ne(x, 0)), (0, True))
* 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)
References
==========
.. [1] https://en.wikipedia.org/wiki/Sinc_function
"""
_singularities = (S.ComplexInfinity,)
def fdiff(self, argindex=1):
x = self.args[0]
if argindex == 1:
return Piecewise(((x*cos(x) - sin(x))/x**2, Ne(x, S.Zero)), (S.Zero, S.true))
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))
###############################################################################
########################### TRIGONOMETRIC INVERSES ############################
###############################################################################
class InverseTrigonometricFunction(Function):
"""Base class for inverse trigonometric functions."""
_singularities = (1, -1, 0, S.ComplexInfinity)
@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):
"""
The inverse sine function.
Returns the arcsine of x in radians.
Notes
=====
``asin(x)`` will evaluate automatically in the cases ``oo``, ``-oo``,
``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:
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, cdir=0):
from sympy import I, im, log
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 I*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 import Dummy, im, 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):
"""
The inverse cosine function.
Returns the arc cosine of x (measured in radians).
Notes
=====
``acos(x)`` will evaluate automatically in the cases
``oo``, ``-oo``, ``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, cdir=0):
from sympy import I, im, log
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 I*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 import Dummy, im, 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):
"""
The inverse tangent function.
Returns the arc tangent of x (measured in radians).
Notes
=====
``atan(x)`` will evaluate automatically in the cases
``oo``, ``-oo``, ``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
"""
_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.util 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:
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 (-1)**((n - 1)//2)*x**n/n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import im, re
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
from sympy import im, re
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).
Notes
=====
``acot(x)`` will evaluate automatically in the cases ``oo``, ``-oo``,
``zoo``, ``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:
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 (-1)**((n + 1)//2)*x**n/n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import im, re
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
from sympy import im, re
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).
Notes
=====
``asec(x)`` will evaluate automatically in the cases ``oo``, ``-oo``,
``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, cdir=0):
from sympy import I, im, log
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 I*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 import Dummy, im, 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):
"""
The inverse cosecant function.
Returns the arc cosecant of x (measured in radians).
Notes
=====
``acsc(x)`` will evaluate automatically in the cases ``oo``, ``-oo``,
``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, cdir=0):
from sympy import I, im, log
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return I*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 import Dummy, im, 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 import Heaviside, im, re
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):
from sympy import re
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):
from sympy import arg
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)
|
6f3b3674305b96900c607614fddbf19bad917d5edf7ed3b22c909999e5c511e3 | """Hypergeometric and Meijer G-functions"""
from sympy.core import S, I, pi, oo, zoo, ilcm, Mod
from sympy.core.function import Function, Derivative, ArgumentIndexError
from sympy.core.compatibility import reduce
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.symbol import Dummy
from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan,
sinh, cosh, asinh, acosh, atanh, acoth, Abs)
from sympy.utilities.iterables import default_sort_key
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)
"""
from sympy import unpolarify
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.functions 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):
from sympy import unpolarify
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 import gamma, 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.functions import factorial, RisingFactorial, Piecewise
from sympy 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_nseries(self, x, n, logx, cdir=0):
from sympy.functions import factorial, RisingFactorial
from sympy import Order, Add
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.functions 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. """
from sympy import And, Or, re, Ne, oo
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)
def _sage_(self):
import sage.all as sage
ap = [arg._sage_() for arg in self.args[0]]
bq = [arg._sage_() for arg in self.args[1]]
return sage.hypergeometric(ap, bq, self.argument._sage_())
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.functions import meijerg
>>> from sympy.abc import x, a
>>> from sympy.core.containers import Tuple
>>> from sympy import pprint
>>> 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.functions.special.hyper import meijerg
>>> from sympy.abc import z
>>> from sympy import pi, S
>>> 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 beta == oo or alpha == oo:
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 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).
from sympy.functions import exp_polar, ceiling
from sympy import Expr
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 integrand(self, s):
""" Get the defining integrand D(s). """
from sympy 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):
from sympy import unpolarify
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):
from sympy import Piecewise
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.functions.special.hyper import appellf1
>>> from sympy import 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)
|
05f12600ae303128dc03cb00be14cd71a0c832360aebe15e449b4dd0fbfba7cb | from sympy import pi, I
from sympy.core import Dummy, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.singleton import S
from sympy.functions import assoc_legendre
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import Abs
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
from sympy import Expr
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 _sage_(self):
import sage.all as sage
return sage.spherical_harmonic(self.args[0]._sage_(),
self.args[1]._sage_(),
self.args[2]._sage_(),
self.args[3]._sage_())
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/
"""
from sympy import conjugate
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
|
b71cbbeb487f799cd76088f50c2196b05fc93ff592cd943424b34cfe27e46eb4 | from sympy.core import Add, Mul
from sympy.core.containers import Tuple
from sympy.core.compatibility import iterable
from sympy.core.exprtools import factor_terms
from sympy.core.numbers import I
from sympy.core.relational import Eq, Equality
from sympy.core.symbol import Dummy, Symbol
from sympy.core.function import expand_mul, expand, Derivative, AppliedUndef
from sympy.functions import exp, im, cos, sin, re, Piecewise, piecewise_fold
from sympy.functions.combinatorial.factorials import factorial
from sympy.matrices import zeros, Matrix, NonSquareMatrixError, MatrixBase
from sympy.polys import Poly
from sympy.simplify import simplify, collect, powsimp, ratsimp
from sympy.solvers.deutils import ode_order
from sympy.solvers.solveset import NonlinearError
from sympy.utilities import default_sort_key
from sympy.utilities.iterables import ordered
from sympy.utilities.misc import filldedent
from sympy.integrals.integrals import Integral, integrate
def _get_func_order(eqs, funcs):
return {func: max(ode_order(eq, func) for eq in eqs) for func in funcs}
class ODEOrderError(ValueError):
"""Raised by linear_ode_to_matrix if the system has the wrong order"""
pass
class ODENonlinearError(NonlinearError):
"""Raised by linear_ode_to_matrix if the system is nonlinear"""
pass
def _simpsol(soleq):
lhs = soleq.lhs
sol = soleq.rhs
sol = powsimp(sol)
gens = list(sol.atoms(exp))
p = Poly(sol, *gens, expand=False)
gens = [factor_terms(g) for g in gens]
if not gens:
gens = p.gens
syms = [Symbol('C1'), Symbol('C2')]
terms = []
for coeff, monom in zip(p.coeffs(), p.monoms()):
coeff = piecewise_fold(coeff)
if type(coeff) is Piecewise:
coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args))
else:
coeff = ratsimp(coeff).collect(syms)
monom = Mul(*(g ** i for g, i in zip(gens, monom)))
terms.append(coeff * monom)
return Eq(lhs, Add(*terms))
def _solsimp(e, t):
no_t, has_t = powsimp(expand_mul(e)).as_independent(t)
no_t = ratsimp(no_t)
has_t = has_t.replace(exp, lambda a: exp(factor_terms(a)))
return no_t + has_t
def linodesolve_type(A, t, b=None):
r"""
Helper function that determines the type of the system of ODEs for solving with :obj:`sympy.solvers.ode.systems.linodesolve()`
Explanation
===========
This function takes in the coefficient matrix and/or the non-homogeneous term
and returns the type of the equation that can be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`.
If the system is constant coefficient homogeneous, then "type1" is returned
If the system is constant coefficient non-homogeneous, then "type2" is returned
If the system is non-constant coefficient homogeneous, then "type3" is returned
If the system is non-constnt coefficient non-homogeneous, then "type4" is returned
Note that, if the system of ODEs is of "type3" or "type4", then along with the type,
the commutative antiderivative of the coefficient matrix is also returned.
If the system cannot be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`, then
NotImplementedError is raised.
Parameters
==========
A : Matrix
Coefficient matrix of the system of ODEs
b : Matrix or None
Non-homogeneous term of the system. The default value is None.
If this argument is None, then the system is assumed to be homogeneous.
Examples
========
>>> from sympy import symbols, Matrix
>>> from sympy.solvers.ode.systems import linodesolve_type
>>> t = symbols("t")
>>> A = Matrix([[1, 1], [2, 3]])
>>> b = Matrix([t, 1])
>>> linodesolve_type(A, t)
{'antiderivative': None, 'type': 'type1'}
>>> linodesolve_type(A, t, b=b)
{'antiderivative': None, 'type': 'type2'}
>>> A_t = Matrix([[1, t], [-t, 1]])
>>> linodesolve_type(A_t, t)
{'antiderivative': Matrix([
[ t, t**2/2],
[-t**2/2, t]]), 'type': 'type3'}
>>> linodesolve_type(A_t, t, b=b)
{'antiderivative': Matrix([
[ t, t**2/2],
[-t**2/2, t]]), 'type': 'type4'}
>>> A_non_commutative = Matrix([[1, t], [t, -1]])
>>> linodesolve_type(A_non_commutative, t)
Traceback (most recent call last):
...
NotImplementedError:
The system doesn't have a commutative antiderivative, it can't be
solved by linodesolve.
Returns
=======
Dict
Raises
======
NotImplementedError
When the coefficient matrix doesn't have a commutative antiderivative
See Also
========
linodesolve: Function for which linodesolve_type gets the information
"""
is_non_constant = not _matrix_is_constant(A, t)
is_non_homogeneous = not (b is None or b.is_zero_matrix)
type = "type{}".format(int("{}{}".format(int(is_non_constant), int(is_non_homogeneous)), 2) + 1)
B = None
if is_non_constant:
B, is_commuting = _is_commutative_anti_derivative(A, t)
if not is_commuting:
raise NotImplementedError(filldedent('''
The system doesn't have a commutative antiderivative, it can't be solved
by linodesolve.
'''))
return {"type": type, "antiderivative": B}
def linear_ode_to_matrix(eqs, funcs, t, order):
r"""
Convert a linear system of ODEs to matrix form
Explanation
===========
Express a system of linear ordinary differential equations as a single
matrix differential equation [1]. For example the system $x' = x + y + 1$
and $y' = x - y$ can be represented as
.. math:: A_1 X' = A0 X + b
where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are
$2 \times 1$ matrices with $X = [x, y]^T$.
Higher-order systems are represented with additional matrices e.g. a
second-order system would look like
.. math:: A_2 X'' = A_1 X' + A_0 X + b
Examples
========
>>> from sympy import (Function, Symbol, Matrix, Eq)
>>> from sympy.solvers.ode.systems import linear_ode_to_matrix
>>> t = Symbol('t')
>>> x = Function('x')
>>> y = Function('y')
We can create a system of linear ODEs like
>>> eqs = [
... Eq(x(t).diff(t), x(t) + y(t) + 1),
... Eq(y(t).diff(t), x(t) - y(t)),
... ]
>>> funcs = [x(t), y(t)]
>>> order = 1 # 1st order system
Now ``linear_ode_to_matrix`` can represent this as a matrix
differential equation.
>>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order)
>>> A1
Matrix([
[1, 0],
[0, 1]])
>>> A0
Matrix([
[1, 1],
[1, -1]])
>>> b
Matrix([
[1],
[0]])
The original equations can be recovered from these matrices:
>>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs])
>>> X = Matrix(funcs)
>>> A1 * X.diff(t) - A0 * X - b == eqs_mat
True
If the system of equations has a maximum order greater than the
order of the system specified, a ODEOrderError exception is raised.
>>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))]
>>> linear_ode_to_matrix(eqs, funcs, t, 1)
Traceback (most recent call last):
...
ODEOrderError: Cannot represent system in 1-order form
If the system of equations is nonlinear, then ODENonlinearError is
raised.
>>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))]
>>> linear_ode_to_matrix(eqs, funcs, t, 1)
Traceback (most recent call last):
...
ODENonlinearError: The system of ODEs is nonlinear.
Parameters
==========
eqs : list of sympy expressions or equalities
The equations as expressions (assumed equal to zero).
funcs : list of applied functions
The dependent variables of the system of ODEs.
t : symbol
The independent variable.
order : int
The order of the system of ODEs.
Returns
=======
The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the
the matrix representing the rhs of the matrix equation.
Raises
======
ODEOrderError
When the system of ODEs have an order greater than what was specified
ODENonlinearError
When the system of ODEs is nonlinear
See Also
========
linear_eq_to_matrix: for systems of linear algebraic equations.
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation
"""
from sympy.solvers.solveset import linear_eq_to_matrix
if any(ode_order(eq, func) > order for eq in eqs for func in funcs):
msg = "Cannot represent system in {}-order form"
raise ODEOrderError(msg.format(order))
As = []
for o in range(order, -1, -1):
# Work from the highest derivative down
funcs_deriv = [func.diff(t, o) for func in funcs]
# linear_eq_to_matrix expects a proper symbol so substitute e.g.
# Derivative(x(t), t) for a Dummy.
rep = {func_deriv: Dummy() for func_deriv in funcs_deriv}
eqs = [eq.subs(rep) for eq in eqs]
syms = [rep[func_deriv] for func_deriv in funcs_deriv]
# Ai is the matrix for X(t).diff(t, o)
# eqs is minus the remainder of the equations.
try:
Ai, b = linear_eq_to_matrix(eqs, syms)
except NonlinearError:
raise ODENonlinearError("The system of ODEs is nonlinear.")
Ai = Ai.applyfunc(expand_mul)
As.append(Ai if o == order else -Ai)
if o:
eqs = [-eq for eq in b]
else:
rhs = b
return As, rhs
def matrix_exp(A, t):
r"""
Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``.
Explanation
===========
This functions returns the $\exp(A*t)$ by doing a simple
matrix multiplication:
.. math:: \exp(A*t) = P * expJ * P^{-1}
where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal
form of $A$ and $P$ is matrix such that:
.. math:: A = P * J * P^{-1}
The matrix exponential $\exp(A*t)$ appears in the solution of linear
differential equations. For example if $x$ is a vector and $A$ is a matrix
then the initial value problem
.. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0
has the unique solution
.. math:: x(t) = \exp(A t) x0
Examples
========
>>> from sympy import Symbol, Matrix, pprint
>>> from sympy.solvers.ode.systems import matrix_exp
>>> t = Symbol('t')
We will consider a 2x2 matrix for comupting the exponential
>>> A = Matrix([[2, -5], [2, -4]])
>>> pprint(A)
[2 -5]
[ ]
[2 -4]
Now, exp(A*t) is given as follows:
>>> pprint(matrix_exp(A, t))
[ -t -t -t ]
[3*e *sin(t) + e *cos(t) -5*e *sin(t) ]
[ ]
[ -t -t -t ]
[ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)]
Parameters
==========
A : Matrix
The matrix $A$ in the expression $\exp(A*t)$
t : Symbol
The independent variable
See Also
========
matrix_exp_jordan_form: For exponential of Jordan normal form
References
==========
.. [1] https://en.wikipedia.org/wiki/Jordan_normal_form
.. [2] https://en.wikipedia.org/wiki/Matrix_exponential
"""
P, expJ = matrix_exp_jordan_form(A, t)
return P * expJ * P.inv()
def matrix_exp_jordan_form(A, t):
r"""
Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.
Explanation
===========
Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:
.. math::
\exp(A*t) = P * expJ * P^{-1}
Examples
========
>>> from sympy import Matrix, Symbol
>>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
>>> t = Symbol('t')
We will consider a 2x2 defective matrix. This shows that our method
works even for defective matrices.
>>> A = Matrix([[1, 1], [0, 1]])
It can be observed that this function gives us the Jordan normal form
and the required invertible matrix P.
>>> P, expJ = matrix_exp_jordan_form(A, t)
Here, it is shown that P and expJ returned by this function is correct
as they satisfy the formula: P * expJ * P_inverse = exp(A*t).
>>> P * expJ * P.inv() == matrix_exp(A, t)
True
Parameters
==========
A : Matrix
The matrix $A$ in the expression $\exp(A*t)$
t : Symbol
The independent variable
References
==========
.. [1] https://en.wikipedia.org/wiki/Defective_matrix
.. [2] https://en.wikipedia.org/wiki/Jordan_matrix
.. [3] https://en.wikipedia.org/wiki/Jordan_normal_form
"""
N, M = A.shape
if N != M:
raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M))
elif A.has(t):
raise ValueError('Matrix A should not depend on t')
def jordan_chains(A):
'''Chains from Jordan normal form analogous to M.eigenvects().
Returns a dict with eignevalues as keys like:
{e1: [[v111,v112,...], [v121, v122,...]], e2:...}
where vijk is the kth vector in the jth chain for eigenvalue i.
'''
P, blocks = A.jordan_cells()
basis = [P[:,i] for i in range(P.shape[1])]
n = 0
chains = {}
for b in blocks:
eigval = b[0, 0]
size = b.shape[0]
if eigval not in chains:
chains[eigval] = []
chains[eigval].append(basis[n:n+size])
n += size
return chains
eigenchains = jordan_chains(A)
# Needed for consistency across Python versions:
eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key)
isreal = not A.has(I)
blocks = []
vectors = []
seen_conjugate = set()
for e, chains in eigenchains_iter:
for chain in chains:
n = len(chain)
if isreal and e != e.conjugate() and e.conjugate() in eigenchains:
if e in seen_conjugate:
continue
seen_conjugate.add(e.conjugate())
exprt = exp(re(e) * t)
imrt = im(e) * t
imblock = Matrix([[cos(imrt), sin(imrt)],
[-sin(imrt), cos(imrt)]])
expJblock2 = Matrix(n, n, lambda i,j:
imblock * t**(j-i) / factorial(j-i) if j >= i
else zeros(2, 2))
expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2])
blocks.append(exprt * expJblock)
for i in range(n):
vectors.append(re(chain[i]))
vectors.append(im(chain[i]))
else:
vectors.extend(chain)
fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0
expJblock = Matrix(n, n, fun)
blocks.append(exp(e * t) * expJblock)
expJ = Matrix.diag(*blocks)
P = Matrix(N, N, lambda i,j: vectors[j][i])
return P, expJ
def linodesolve(A, t, b=None, B=None, type="auto", doit=False):
r"""
System of n equations linear first-order differential equations
Explanation
===========
This solver solves the system of ODEs of the follwing form:
.. math::
X'(t) = A(t) X(t) + b(t)
Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
$b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$
Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
differently.
When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
the solution is:
.. math::
X(t) = \exp(A t) C
Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.
When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
the solution is:
.. math::
X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)
When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
$b(t)$ is a zero vector i.e. system is homogeneous, the solution is:
.. math::
X(t) = \exp(B(t)) C
When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
non-homogeneous, the solution is:
.. math::
X(t) = e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)
The final solution is the general solution for all the four equations since a constant coefficient
matrix is always commutative with its antidervative.
Parameters
==========
A : Matrix
Coefficient matrix of the system of linear first order ODEs.
t : Symbol
Independent variable in the system of ODEs.
b : Matrix or None
Non-homogeneous term in the system of ODEs. If None is passed,
a homogeneous system of ODEs is assumed.
B : Matrix or None
Antiderivative of the coefficient matrix. If the antiderivative
is not passed and the solution requires the term, then the solver
would compute it internally.
type : String
Type of the system of ODEs passed. Depending on the type, the
solution is evaluated. The type values allowed and the corresponding
system it solves are: "type1" for constant coefficient homogeneous
"type2" for constant coefficient non-homogeneous, "type3" for non-constant
coefficient homogeneous and "type4" for non-constant coefficient non-homogeneous.
The default value is "auto" which will let the solver decide the correct type of
the system passed.
doit : Boolean
Evaluate the solution if True, default value is False
Examples
========
To solve the system of ODEs using this function directly, several things must be
done in the right order. Wrong inputs to the function will lead to incorrect results.
>>> from sympy import symbols, Function, Eq
>>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
>>> from sympy.solvers.ode.subscheck import checkodesol
>>> f, g = symbols("f, g", cls=Function)
>>> x, a = symbols("x, a")
>>> funcs = [f(x), g(x)]
>>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]
Here, it is important to note that before we derive the coefficient matrix, it is
important to get the system of ODEs into the desired form. For that we will use
:obj:`sympy.solvers.ode.systems.canonical_odes()`.
>>> eqs = canonical_odes(eqs, funcs, x)
>>> eqs
[[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]]
Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
non-homogeneous term if it is there.
>>> eqs = eqs[0]
>>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
>>> A = A0
We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
:obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
to finally pass it to the solver.
>>> system_info = linodesolve_type(A, x, b=b)
>>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type'])
Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()`
>>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
>>> checkodesol(eqs, sol)
(True, [0, 0])
We can also use the doit method to evaluate the solutions passed by the function.
>>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)
Now, we will look at a system of ODEs which is non-constant.
>>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]
The system defined above is already in the desired form, so we don't have to convert it.
>>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
>>> A = A0
A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs.
Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
If it does have a commutative antiderivative, then the function just returns the information about the system.
>>> system_info = linodesolve_type(A, x, b=b)
Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
passed, then the solver will compute the required arguments internally.
>>> sol_vector = linodesolve(A, x, b=b)
Once again, we can verify the solution obtained.
>>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
>>> checkodesol(eqs, sol)
(True, [0, 0])
Returns
=======
List
Raises
======
ValueError
This error is raised when the coefficient matrix, non-homogeneous term
or the antiderivative, if passed, aren't a matrix or
don't have correct dimensions
NonSquareMatrixError
When the coefficient matrix or its antiderivative, if passed isn't a square
matrix
NotImplementedError
If the coefficient matrix doesn't have a commutative antiderivative
See Also
========
linear_ode_to_matrix: Coefficient matrix computation function
canonical_odes: System of ODEs representation change
linodesolve_type: Getting information about systems of ODEs to pass in this solver
"""
if not isinstance(A, MatrixBase):
raise ValueError(filldedent('''\
The coefficients of the system of ODEs should be of type Matrix
'''))
if not A.is_square:
raise NonSquareMatrixError(filldedent('''\
The coefficient matrix must be a square
'''))
if b is not None:
if not isinstance(b, MatrixBase):
raise ValueError(filldedent('''\
The non-homogeneous terms of the system of ODEs should be of type Matrix
'''))
if A.rows != b.rows:
raise ValueError(filldedent('''\
The system of ODEs should have the same number of non-homogeneous terms and the number of
equations
'''))
if B is not None:
if not isinstance(B, MatrixBase):
raise ValueError(filldedent('''\
The antiderivative of coefficients of the system of ODEs should be of type Matrix
'''))
if not B.is_square:
raise NonSquareMatrixError(filldedent('''\
The antiderivative of the coefficient matrix must be a square
'''))
if A.rows != B.rows:
raise ValueError(filldedent('''\
The coefficient matrix and its antiderivative should have same dimensions
'''))
if not any(type == "type{}".format(i) for i in range(1, 5)) and not type == "auto":
raise ValueError(filldedent('''\
The input type should be a valid one
'''))
n = A.rows
# constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1)
Cvect = Matrix(list(Dummy() for _ in range(n)))
if (type == "type2" or type == "type4") and b is None:
b = zeros(n, 1)
if type == "auto":
system_info = linodesolve_type(A, t, b=b)
type = system_info["type"]
B = system_info["antiderivative"]
if type == "type1" or type == "type2":
P, J = matrix_exp_jordan_form(A, t)
P = simplify(P)
if type == "type1":
sol_vector = P * (J * Cvect)
else:
sol_vector = P * J * ((J.inv() * P.inv() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)
else:
if B is None:
B, _ = _is_commutative_anti_derivative(A, t)
if type == "type3":
sol_vector = B.exp() * Cvect
else:
sol_vector = B.exp() * (((-B).exp() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)
gens = sol_vector.atoms(exp)
if type != "type1":
sol_vector = [expand_mul(s) for s in sol_vector]
sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector]
if doit:
sol_vector = [s.doit() for s in sol_vector]
return sol_vector
def _matrix_is_constant(M, t):
"""Checks if the matrix M is independent of t or not."""
return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M)
def canonical_odes(eqs, funcs, t):
r"""
Function that solves for highest order derivatives in a system
Explanation
===========
This function inputs a system of ODEs and based on the system,
the dependent variables and their highest order, returns the system
in the following form:
.. math::
X'(t) = A(t) X(t) + b(t)
Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is
the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the
vector of dependent variables in their respective highest order. We use the term
canonical form to imply the system of ODEs which is of the above form.
If the system passed has a non-linear term with multiple solutions, then a list of
systems is returned in its canonical form.
Parameters
==========
eqs : List
List of the ODEs
funcs : List
List of dependent variables
t : Symbol
Independent variable
Examples
========
>>> from sympy import symbols, Function, Eq, Derivative
>>> from sympy.solvers.ode.systems import canonical_odes
>>> f, g = symbols("f g", cls=Function)
>>> x, y = symbols("x y")
>>> funcs = [f(x), g(x)]
>>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))]
>>> canonical_eqs = canonical_odes(eqs, funcs, x)
>>> canonical_eqs
[[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]]
>>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)]
>>> canonical_system = canonical_odes(system, funcs, x)
>>> canonical_system
[[Eq(Derivative(f(x), x), -1), Eq(Derivative(g(x), x), y*f(x))], [Eq(Derivative(f(x), x), 3), Eq(Derivative(g(x), x), y*f(x))]]
Returns
=======
List
"""
from sympy.solvers.solvers import solve
order = _get_func_order(eqs, funcs)
canon_eqs = solve(eqs, *[func.diff(t, order[func]) for func in funcs], dict=True)
systems = []
for eq in canon_eqs:
system = [Eq(func.diff(t, order[func]), eq[func.diff(t, order[func])]) for func in funcs]
systems.append(system)
return systems
def _is_commutative_anti_derivative(A, t):
r"""
Helper function for determining if the Matrix passed is commutative with its antiderivative
Explanation
===========
This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect
to the independent variable $t$.
.. math::
B(t) = \int A(t) dt
The function outputs two values, first one being the antiderivative $B(t)$, second one being a
boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix
passed isn't commutative with $B(t)$.
Parameters
==========
A : Matrix
The matrix which has to be checked
t : Symbol
Independent variable
Examples
========
>>> from sympy import symbols, Matrix
>>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative
>>> t = symbols("t")
>>> A = Matrix([[1, t], [-t, 1]])
>>> B, is_commuting = _is_commutative_anti_derivative(A, t)
>>> is_commuting
True
Returns
=======
Matrix, Boolean
"""
B = integrate(A, t)
is_commuting = (B*A - A*B).applyfunc(expand).applyfunc(factor_terms).is_zero_matrix
is_commuting = False if is_commuting is None else is_commuting
return B, is_commuting
def neq_nth_linear_constant_coeff_match(eqs, funcs, t, is_canon=False):
r"""
Returns a dictionary with details of the eqs if every equation is constant coefficient
and linear else returns None
Explanation
===========
This function takes the eqs, converts it into a form Ax = b where x is a vector of terms
containing dependent variables and their derivatives till their maximum order. If it is
possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise
they are non-linear.
To check if the equations are constant coefficient, we need to check if all the terms in
A obtained above are constant or not.
To check if the equations are homogeneous or not, we need to check if b is a zero matrix
or not.
Parameters
==========
eqs: List
List of ODEs
funcs: List
List of dependent variables
t: Symbol
Independent variable of the equations in eqs
is_canon: Boolean
If True, then this function won't try to get the
system in canonical form. Default value is False
Returns
=======
match = {
'no_of_equation': len(eqs),
'eq': eqs,
'func': funcs,
'order': order,
'is_linear': is_linear,
'is_constant': is_constant,
'is_homogeneous': is_homogeneous,
}
Dict or list of Dicts or None
Dict with values for keys:
1. no_of_equation: Number of equations
2. eq: The set of equations
3. func: List of dependent variables
4. order: A dictionary that gives the order of the
dependent variable in eqs
5. is_linear: Boolean value indicating if the set of
equations are linear or not.
6. is_constant: Boolean value indicating if the set of
equations have constant coefficients or not.
7. is_homogeneous: Boolean value indicating if the set of
equations are homogeneous or not.
8. commutative_antiderivative: Antiderivative of the coefficient
matrix if the coefficient matrix is non-constant
and commutative with its antiderivative. This key
may or may not exist.
9. is_general: Boolean value indicating if the system of ODEs is
solvable using one of the general case solvers or not.
10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This
key may or may not exist.
This Dict is the answer returned if the eqs are linear and constant
coefficient. Otherwise, None is returned.
"""
# Error for i == 0 can be added but isn't for now
# Check for len(funcs) == len(eqs)
if len(funcs) != len(eqs):
raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
# ValueError when functions have more than one arguments
for func in funcs:
if len(func.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
# Getting the func_dict and order using the helper
# function
order = _get_func_order(eqs, funcs)
if not all(order[func] == 1 for func in funcs):
return None
else:
# TO be changed when this function is updated.
# This will in future be updated as the maximum
# order in the system found.
system_order = 1
# Not adding the check if the len(func.args) for
# every func in funcs is 1
# Linearity check
try:
# Note: We can add a is_canon parameter to this
# function to check if the equation passed is
# already in its canonical form or not. This
# can be used to solve big linear first order
# system of ODEs using component division.
canon_eqs = canonical_odes(eqs, funcs, t) if not is_canon else [eqs]
if len(canon_eqs) == 1:
As, b = linear_ode_to_matrix(canon_eqs[0], funcs, t, system_order)
A = As[1]
else:
match = {
'is_implicit': True,
'canon_eqs': canon_eqs
}
return match
# When the system of ODEs is non-linear, an ODENonlinearError is raised.
# This function catches the error and None is returned.
except ODENonlinearError:
return None
is_linear = True
# Constant coefficient check
is_constant = _matrix_is_constant(A, t)
# Homogeneous check
is_homogeneous = True if b.is_zero_matrix else False
# Is general key is used to identify if the system of ODEs can be solved by
# one of the general case solvers or not.
match = {
'no_of_equation': len(eqs),
'eq': eqs,
'func': funcs,
'order': order,
'is_linear': is_linear,
'is_constant': is_constant,
'is_homogeneous': is_homogeneous,
'is_general': True
}
# The match['is_linear'] check will be added in the future when this
# function becomes ready to deal with non-linear systems of ODEs
if all([order[func] == 1 for func in funcs]):
match['func_coeff'] = A
if not is_homogeneous:
match['rhs'] = b
try:
system_info = linodesolve_type(A, t, b=b)
except NotImplementedError:
return None
if not is_constant:
match['commutative_antiderivative'] = system_info["antiderivative"]
match['type_of_equation'] = system_info["type"]
return match
return None
def _preprocess_eqs(eqs):
processed_eqs = []
for eq in eqs:
processed_eqs.append(eq if isinstance(eq, Equality) else Eq(eq, 0))
return processed_eqs
def _eqs2dict(eqs, funcs):
eqsorig = {}
eqsmap = {}
funcset = set(funcs)
for eq in eqs:
f1, = eq.lhs.atoms(AppliedUndef)
f2s = (eq.rhs.atoms(AppliedUndef) - {f1}) & funcset
eqsmap[f1] = f2s
eqsorig[f1] = eq
return eqsmap, eqsorig
def _dict2graph(d):
nodes = list(d)
edges = [(f1, f2) for f1, f2s in d.items() for f2 in f2s]
G = (nodes, edges)
return G
def _is_type1(scc, t):
eqs, funcs = scc
try:
(A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 1)
except (ODENonlinearError, ODEOrderError):
return False
if _matrix_is_constant(A0, t) and b.is_zero_matrix:
return True
return False
def _combine_type1_subsystems(subsystem, funcs, t):
indices = [i for i, sys in enumerate(zip(subsystem, funcs)) if _is_type1(sys, t)]
remove = set()
for ip, i in enumerate(indices):
for j in indices[ip+1:]:
if any(eq2.has(funcs[i]) for eq2 in subsystem[j]):
subsystem[j] = subsystem[i] + subsystem[j]
remove.add(i)
subsystem = [sys for i, sys in enumerate(subsystem) if i not in remove]
return subsystem
def _component_division(eqs, funcs, t):
from sympy.utilities.iterables import connected_components, strongly_connected_components
# Assuming that each eq in eqs is in canonical form,
# that is, [f(x).diff(x) = .., g(x).diff(x) = .., etc]
# and that the system passed is in its first order
eqsmap, eqsorig = _eqs2dict(eqs, funcs)
subsystems = []
for cc in connected_components(_dict2graph(eqsmap)):
eqsmap_c = {f: eqsmap[f] for f in cc}
sccs = strongly_connected_components(_dict2graph(eqsmap_c))
subsystem = [[eqsorig[f] for f in scc] for scc in sccs]
subsystem = _combine_type1_subsystems(subsystem, sccs, t)
subsystems.append(subsystem)
return subsystems
# Returns: List of equations
def _linear_ode_solver(match):
t = match['t']
funcs = match['func']
rhs = match.get('rhs', None)
A = match['func_coeff']
B = match.get('commutative_antiderivative', None)
type_of_equation = match['type_of_equation']
sol_vector = linodesolve(A, t, b=rhs, B=B,
type=type_of_equation)
sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
return sol
# Returns: List of equations or None
# If None is returned by this solver, then the system
# of ODEs cannot be solved by dsolve_system.
def _strong_component_solver(eqs, funcs, t):
match = neq_nth_linear_constant_coeff_match(eqs, funcs, t, is_canon=True)
# Assuming that we can't get an implicit system
# since we are already canonical equations from
# dsolve_system
if match:
if match.get('is_linear', False):
match['t'] = t
return _linear_ode_solver(match)
# To add non-linear case here in future
return None
def _get_funcs_from_canon(eqs):
return [eq.lhs.args[0] for eq in eqs]
# Returns: List of Equations(a solution)
def _weak_component_solver(wcc, t):
# We will divide the systems into sccs
# only when the wcc cannot be solved as
# a whole
eqs = []
for scc in wcc:
eqs += scc
funcs = _get_funcs_from_canon(eqs)
sol = _strong_component_solver(eqs, funcs, t)
if sol:
return sol
sol = []
for j, scc in enumerate(wcc):
eqs = scc
funcs = _get_funcs_from_canon(eqs)
# Substituting solutions for the dependent
# variables solved in previous SCC, if any solved.
comp_eqs = [eq.subs({s.lhs: s.rhs for s in sol}) for eq in eqs]
scc_sol = _strong_component_solver(comp_eqs, funcs, t)
if scc_sol is None:
raise NotImplementedError(filldedent('''
The system of ODEs passed cannot be solved by dsolve_system.
'''))
# scc_sol: List of equations
# scc_sol is a solution
sol += scc_sol
return sol
# Returns: List of Equations(a solution)
# To add test cases for component division
# when we have a nonlinear sysode solver
def _component_solver(eqs, funcs, t):
components = _component_division(eqs, funcs, t)
sol = []
for wcc in components:
# wcc_sol: List of Equations
sol += _weak_component_solver(wcc, t)
# sol: List of Equations
return sol
def dsolve_system(eqs, funcs=None, t=None, ics=None, doit=False):
r"""
Solves any(supported) system of Ordinary Differential Equations
Explanation
===========
This function takes a system of ODEs as an input, determines if the
it is solvable by this function, and returns the solution if found any.
This function can handle:
1. Linear, First Order, Constant coefficient homogeneous system of ODEs
2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs
3. Linear, First Order, non-constant coefficient homogeneous system of ODEs
4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs
5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms
The types of systems described above aren't limited by the number of equations, i.e. this
function can solve the above types irrespective of the number of equations in the system passed.
This function returns a list of solutions. Each solution is a list of equations where LHS is
the dependent variable and RHS is an expression in terms of the independent variable.
Parameters
==========
eqs : List
system of ODEs to be solved
funcs : List or None
List of dependent variables that make up the system of ODEs
t : Symbol
Independent variable in the system of ODEs
ics : Dict or None
Set of initial boundary/conditions for the system of ODEs
doit : Boolean
Evaluate the solutions if True. Default value is False
Examples
========
>>> from sympy import symbols, Eq, Function
>>> from sympy.solvers.ode.systems import dsolve_system
>>> f, g = symbols("f g", cls=Function)
>>> x = symbols("x")
>>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))]
>>> dsolve_system(eqs)
[[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
You can also pass the initial conditions for the system of ODEs:
>>> dsolve_system(eqs, ics={f(0): 1, g(0): 0})
[[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]]
Optionally, you can pass the dependent variables and the independent
variable for which the system is to be solved:
>>> funcs = [f(x), g(x)]
>>> dsolve_system(eqs, funcs=funcs, t=x)
[[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
Lets look at an implicit system of ODEs:
>>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))]
>>> dsolve_system(eqs)
[[Eq(f(x), C1 - C2*exp(x)), Eq(g(x), C2*exp(x))], [Eq(f(x), C1 + C2*exp(x)), Eq(g(x), C2*exp(x))]]
Returns
=======
List of List of Equations
Raises
======
NotImplementedError
When the system of ODEs is not solvable by this function.
ValueError
When the parameters passed aren't in the required form.
"""
from sympy.solvers.ode.ode import solve_ics, _extract_funcs, constant_renumber
if not iterable(eqs):
raise ValueError(filldedent('''
List of equations should be passed. The input is not valid.
'''))
eqs = _preprocess_eqs(eqs)
if funcs is not None and not isinstance(funcs, list):
raise ValueError(filldedent('''
Input to the funcs should be a list of functions.
'''))
if funcs is None:
funcs = _extract_funcs(eqs)
if any(len(func.args) != 1 for func in funcs):
raise ValueError(filldedent('''
dsolve_system can solve a system of ODEs with only one independent
variable.
'''))
if len(eqs) != len(funcs):
raise ValueError(filldedent('''
Number of equations and number of functions don't match
'''))
if t is not None and not isinstance(t, Symbol):
raise ValueError(filldedent('''
The indepedent variable must be of type Symbol
'''))
if t is None:
t = list(list(eqs[0].atoms(Derivative))[0].atoms(Symbol))[0]
sys_order = _get_func_order(eqs, funcs)
# To add higher order to first order reduction later
if not all(sys_order[func] == 1 for func in funcs):
raise NotImplementedError(filldedent('''
Higher order ODEs aren't solvable by dsolve_system
'''))
canon_eqs = canonical_odes(eqs, funcs, t)
sols = []
for canon_eq in canon_eqs:
sol = _strong_component_solver(canon_eq, funcs, t)
if sol is None:
sol = _component_solver(canon_eq, funcs, t)
sols.append(sol)
if sols:
final_sols = []
for sol in sols:
# To preserve the order corresponding to the
# funcs list.
sol_dict = {s.lhs: s.rhs for s in sol}
sol = [Eq(var, sol_dict[var]) for var in funcs]
variables = Tuple(*eqs).free_symbols
sol = constant_renumber(sol, variables=variables)
if ics:
constants = Tuple(*sol).free_symbols - variables
solved_constants = solve_ics(sol, funcs, constants, ics)
sol = [s.subs(solved_constants) for s in sol]
if doit:
sol = [s.doit() for s in sol]
final_sols.append(sol)
sols = final_sols
return sols
|
9b19be1f68e57933f1cae2e3bbc4507c4ed12223206be070a751b7ca89580baf | from sympy import (acos, acosh, asinh, atan, cos, Derivative, diff,
Dummy, Eq, Ne, exp, Function, I, Integral, LambertW, log, O, pi,
Rational, rootof, S, sin, sqrt, Subs, Symbol, tan, asin, sinh,
Piecewise, symbols, Poly, sec, re, im, atan2, collect, hyper, integrate)
from sympy.solvers.ode import (classify_ode,
homogeneous_order, infinitesimals, checkinfsol,
dsolve)
from sympy.solvers.ode.subscheck import checkodesol, checksysodesol
from sympy.solvers.ode.ode import (_linear_coeff_match,
_undetermined_coefficients_match, classify_sysode,
constant_renumber, constantsimp, get_numbered_constants, solve_ics)
from sympy.functions import airyai, airybi, besselj, bessely
from sympy.solvers.deutils import ode_order
from sympy.testing.pytest import XFAIL, skip, raises, slow, ON_TRAVIS, SKIP
from sympy.utilities.misc import filldedent
C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11')
u, x, y, z = symbols('u,x:z', real=True)
f = Function('f')
g = Function('g')
h = Function('h')
# Note: the tests below may fail (but still be correct) if ODE solver,
# the integral engine, solve(), or even simplify() changes. Also, in
# differently formatted solutions, the arbitrary constants might not be
# equal. Using specific hints in tests can help to avoid this.
# Tests of order higher than 1 should run the solutions through
# constant_renumber because it will normalize it (constant_renumber causes
# dsolve() to return different results on different machines)
def test_get_numbered_constants():
with raises(ValueError):
get_numbered_constants(None)
def test_dsolve_all_hint():
eq = f(x).diff(x)
output = dsolve(eq, hint='all')
# Match the Dummy variables:
sol1 = output['separable_Integral']
_y = sol1.lhs.args[1][0]
sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral']
_u1 = sol1.rhs.args[1].args[1][0]
expected = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)),
'1st_homogeneous_coeff_best': Eq(f(x), C1),
'Bernoulli': Eq(f(x), C1),
'nth_algebraic': Eq(f(x), C1),
'nth_linear_euler_eq_homogeneous': Eq(f(x), C1),
'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1),
'separable': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1),
'nth_algebraic_Integral': Eq(f(x), C1),
'1st_linear': Eq(f(x), C1),
'1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)),
'lie_group': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))),
'1st_power_series': Eq(f(x), C1),
'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)),
'1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1),
'best': Eq(f(x), C1),
'best_hint': 'nth_algebraic',
'default': 'nth_algebraic',
'order': 1}
assert output == expected
assert dsolve(eq, hint='best') == Eq(f(x), C1)
def test_dsolve_ics():
# Maybe this should just use one of the solutions instead of raising...
with raises(NotImplementedError):
dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1})
@slow
@XFAIL
def test_nonlinear_3eq_order1_type1():
if ON_TRAVIS:
skip("Too slow for travis.")
a, b, c = symbols('a b c')
eqs = [
a * f(x).diff(x) - (b - c) * g(x) * h(x),
b * g(x).diff(x) - (c - a) * h(x) * f(x),
c * h(x).diff(x) - (a - b) * f(x) * g(x),
]
assert dsolve(eqs) # NotImplementedError
def test_dsolve_euler_rootof():
eq = x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x)
sol = Eq(f(x),
C1*x
+ C2*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 0)
+ C3*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 1)
+ C4*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 2)
+ C5*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 3)
+ C6*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 4)
)
assert dsolve(eq) == sol
def test_linear_2eq_order1_type6_path1_broken():
eqs = [Eq(diff(f(x), x), f(x) + x*g(x)),
Eq(diff(g(x), x), 2*(1 + 2/x)*f(x) + 2*(x - 1/x) * g(x))]
# FIXME: This is not the correct solution:
sol = [
Eq(f(x), (C1 + Integral(C2*x*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))),
Eq(g(x), C1*exp(-2*Integral(1/x, x))
+ 2*(C1 + Integral(C2*x*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x)))
]
dsolve_sol = dsolve(eqs)
# FIXME: Comparing solutions with == doesn't work in this case...
assert [ds.lhs for ds in dsolve_sol] == [f(x), g(x)]
assert [ds.rhs.equals(ss.rhs) for ds, ss in zip(dsolve_sol, sol)]
# FIXME: checked in XFAIL test_linear_2eq_order1_type6_path1_broken_check below
@XFAIL
def test_linear_2eq_order1_type6_path1_broken_check():
# See test_linear_2eq_order1_type6_path1_broken above
eqs = [Eq(diff(f(x), x), f(x) + x*g(x)),
Eq(diff(g(x), x), 2*(1 + 2/x)*f(x) + 2*(x - 1/x) * g(x))]
# FIXME: This is not the correct solution:
sol = [
Eq(f(x), (C1 + Integral(C2*x*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))),
Eq(g(x), C1*exp(-2*Integral(1/x, x))
+ 2*(C1 + Integral(C2*x*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x)))
]
assert checksysodesol(eqs, sol) == (True, [0, 0]) # XFAIL
def test_linear_2eq_order1_type6_path2_broken():
# This is the reverse of the equations above and should also be handled by
# type6.
eqs = [Eq(diff(g(x), x), 2*(1 + 2/x)*g(x) + 2*(x - 1/x) * f(x)),
Eq(diff(f(x), x), g(x) + x*f(x))]
# FIXME: This is not the correct solution:
sol = [
Eq(g(x), C1*exp(-2*Integral(1/x, x))
+ 2*(C1 + Integral(-C2*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))),
Eq(f(x), (C1 + Integral(-C2*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x)))
]
dsolve_sol = dsolve(eqs)
# Comparing solutions with == doesn't work in this case...
assert [ds.lhs for ds in dsolve_sol] == [g(x), f(x)]
assert [ds.rhs.equals(ss.rhs) for ds, ss in zip(dsolve_sol, sol)]
# FIXME: checked in XFAIL test_linear_2eq_order1_type6_path2_broken_check below
@XFAIL
def test_linear_2eq_order1_type6_path2_broken_check():
# See test_linear_2eq_order1_type6_path2_broken above
eqs = [Eq(diff(g(x), x), 2*(1 + 2/x)*g(x) + 2*(x - 1/x) * f(x)),
Eq(diff(f(x), x), g(x) + x*f(x))]
sol = [
Eq(g(x), C1*exp(-2*Integral(1/x, x))
+ 2*(C1 + Integral(-C2*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))),
Eq(f(x), (C1 + Integral(-C2*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x)))
]
assert checksysodesol(eqs, sol) == (True, [0, 0]) # XFAIL
def test_nth_euler_imroot():
eq = x**2 * f(x).diff(x, 2) + x * f(x).diff(x) + 4 * f(x) - 1/x
sol = Eq(f(x), C1*sin(2*log(x)) + C2*cos(2*log(x)) + 1/(5*x))
dsolve_sol = dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters')
assert dsolve_sol == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
def test_constant_coeff_circular_atan2():
eq = f(x).diff(x, x) + y*f(x)
sol = Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y)))
assert dsolve(eq) == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
def test_linear_2eq_order2_type1_broken1():
eqs = [Eq(f(x).diff(x, 2), 2*f(x) + g(x)),
Eq(g(x).diff(x, 2), -f(x))]
# FIXME: This is not the correct solution:
sol = [
Eq(f(x), 2*C1*(x + 2)*exp(x) + 2*C2*(x + 2)*exp(-x) + 2*C3*x*exp(x) + 2*C4*x*exp(-x)),
Eq(g(x), -2*C1*x*exp(x) - 2*C2*x*exp(-x) + C3*(-2*x + 4)*exp(x) + C4*(-2*x - 4)*exp(-x))
]
assert dsolve(eqs) == sol
# FIXME: checked in XFAIL test_linear_2eq_order2_type1_broken1_check below
@XFAIL
def test_linear_2eq_order2_type1_broken1_check():
# See test_linear_2eq_order2_type1_broken1 above
eqs = [Eq(f(x).diff(x, 2), 2*f(x) + g(x)),
Eq(g(x).diff(x, 2), -f(x))]
# This is the returned solution but it isn't correct:
sol = [
Eq(f(x), 2*C1*(x + 2)*exp(x) + 2*C2*(x + 2)*exp(-x) + 2*C3*x*exp(x) + 2*C4*x*exp(-x)),
Eq(g(x), -2*C1*x*exp(x) - 2*C2*x*exp(-x) + C3*(-2*x + 4)*exp(x) + C4*(-2*x - 4)*exp(-x))
]
assert checksysodesol(eqs, sol) == (True, [0, 0])
@XFAIL
def test_linear_2eq_order2_type1_broken2():
eqs = [Eq(f(x).diff(x, 2), 0),
Eq(g(x).diff(x, 2), f(x))]
sol = [
Eq(f(x), C1 + C2*x),
Eq(g(x), C4 + C3*x + C2*x**3/6 + C1*x**2/2)
]
assert dsolve(eqs) == sol # UnboundLocalError
def test_linear_2eq_order2_type1_broken2_check():
eqs = [Eq(f(x).diff(x, 2), 0),
Eq(g(x).diff(x, 2), f(x))]
sol = [
Eq(f(x), C1 + C2*x),
Eq(g(x), C4 + C3*x + C2*x**3/6 + C1*x**2/2)
]
assert checksysodesol(eqs, sol) == (True, [0, 0])
def test_linear_2eq_order2_type1():
eqs = [Eq(f(x).diff(x, 2), 2*f(x)),
Eq(g(x).diff(x, 2), -f(x) + 2*g(x))]
sol = [
Eq(f(x), 2*sqrt(2)*C1*exp(sqrt(2)*x) + 2*sqrt(2)*C2*exp(-sqrt(2)*x)),
Eq(g(x), -C1*x*exp(sqrt(2)*x) + C2*x*exp(-sqrt(2)*x) + C3*exp(sqrt(2)*x) + C4*exp(-sqrt(2)*x))
]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
eqs = [Eq(f(x).diff(x, 2), 2*f(x) + g(x)),
Eq(g(x).diff(x, 2), + 2*g(x))]
sol = [
Eq(f(x), C1*x*exp(sqrt(2)*x) - C2*x*exp(-sqrt(2)*x) + C3*exp(sqrt(2)*x) + C4*exp(-sqrt(2)*x)),
Eq(g(x), 2*sqrt(2)*C1*exp(sqrt(2)*x) + 2*sqrt(2)*C2*exp(-sqrt(2)*x))
]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
eqs = [Eq(f(x).diff(x, 2), f(x)),
Eq(g(x).diff(x, 2), f(x))]
sol = [Eq(f(x), C1*exp(x) + C2*exp(-x)),
Eq(g(x), C1*exp(x) + C2*exp(-x) - C3*x - C4)]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
eqs = [Eq(f(x).diff(x, 2), f(x) + g(x)),
Eq(g(x).diff(x, 2), -f(x) - g(x))]
sol = [Eq(f(x), C1*x**3 + C2*x**2 + C3*x + C4),
Eq(g(x), -C1*x**3 + 6*C1*x - C2*x**2 + 2*C2 - C3*x - C4)]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
def test_linear_2eq_order2_type2():
eqs = [Eq(f(x).diff(x, 2), f(x) + g(x) + 1),
Eq(g(x).diff(x, 2), f(x) + g(x) + 1)]
sol = [Eq(f(x), C1*exp(sqrt(2)*x) + C2*exp(-sqrt(2)*x) + C3*x + C4 - S.Half),
Eq(g(x), C1*exp(sqrt(2)*x) + C2*exp(-sqrt(2)*x) - C3*x - C4 - S.Half)]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
eqs = [Eq(f(x).diff(x, 2), f(x) + g(x) + 1),
Eq(g(x).diff(x, 2), -f(x) - g(x) + 1)]
sol = [Eq(f(x), C1*x**3 + C2*x**2 + C3*x + C4 + x**4/12 + x**2/2),
Eq(g(x), -C1*x**3 + 6*C1*x - C2*x**2 + 2*C2 - C3*x - C4 - x**4/12 + x**2/2)]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
def test_linear_2eq_order2_type4_broken():
Ca, Cb, Ra, Rb = symbols('Ca, Cb, Ra, Rb')
eq = [f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) + g(x) - 2*exp(I*x),
g(x).diff(x, 2) + 2*g(x).diff(x) + f(x) + g(x) - 2*exp(I*x)]
# FIXME: This is not the correct solution:
# Solution returned with Ca, Ra etc symbols is clearly incorrect:
sol = [
Eq(f(x), C1 + C2*exp(2*x) + C3*exp(x*(1 + sqrt(3))) + C4*exp(x*(-sqrt(3) + 1)) + (I*Ca + Ra)*exp(I*x)),
Eq(g(x), -C1 - 3*C2*exp(2*x) + C3*(-3*sqrt(3) - 4 + (1 + sqrt(3))**2)*exp(x*(1 + sqrt(3)))
+ C4*(-4 + (-sqrt(3) + 1)**2 + 3*sqrt(3))*exp(x*(-sqrt(3) + 1)) + (I*Cb + Rb)*exp(I*x))
]
dsolve_sol = dsolve(eq)
assert dsolve_sol == sol
# FIXME: checked in XFAIL test_linear_2eq_order2_type4_broken_check below
@XFAIL
def test_linear_2eq_order2_type4_broken_check():
# See test_linear_2eq_order2_type4_broken above
Ca, Cb, Ra, Rb = symbols('Ca, Cb, Ra, Rb')
eq = [f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) + g(x) - 2*exp(I*x),
g(x).diff(x, 2) + 2*g(x).diff(x) + f(x) + g(x) - 2*exp(I*x)]
# Solution returned with Ca, Ra etc symbols is clearly incorrect:
sol = [
Eq(f(x), C1 + C2*exp(2*x) + C3*exp(x*(1 + sqrt(3))) + C4*exp(x*(-sqrt(3) + 1)) + (I*Ca + Ra)*exp(I*x)),
Eq(g(x), -C1 - 3*C2*exp(2*x) + C3*(-3*sqrt(3) - 4 + (1 + sqrt(3))**2)*exp(x*(1 + sqrt(3)))
+ C4*(-4 + (-sqrt(3) + 1)**2 + 3*sqrt(3))*exp(x*(-sqrt(3) + 1)) + (I*Cb + Rb)*exp(I*x))
]
assert checksysodesol(eq, sol) == (True, [0, 0]) # Fails here
def test_linear_2eq_order2_type5():
eqs = [Eq(f(x).diff(x, 2), 2*(x*g(x).diff(x) - g(x))),
Eq(g(x).diff(x, 2),-2*(x*f(x).diff(x) - f(x)))]
sol = [Eq(f(x), C3*x + x*Integral((2*C1*cos(x**2) + 2*C2*sin(x**2))/x**2, x)),
Eq(g(x), C4*x + x*Integral((-2*C1*sin(x**2) + 2*C2*cos(x**2))/x**2, x))]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0])
def test_linear_2eq_order2_type8():
eqs = [Eq(f(x).diff(x, 2), 2/x *(x*g(x).diff(x) - g(x))),
Eq(g(x).diff(x, 2),-2/x *(x*f(x).diff(x) - f(x)))]
# FIXME: This is what is returned but it does not seem correct:
sol = [Eq(f(x), C3*x + x*Integral((-C1*cos(Integral(-2, x)) - C2*sin(Integral(-2, x)))/x**2, x)),
Eq(g(x), C4*x + x*Integral((-C1*sin(Integral(-2, x)) + C2*cos(Integral(-2, x)))/x**2, x))]
assert dsolve(eqs) == sol
assert checksysodesol(eqs, sol) == (True, [0, 0]) # Fails here
@XFAIL
def test_nonlinear_3eq_order1_type4():
eqs = [
Eq(f(x).diff(x), (2*h(x)*g(x) - 3*g(x)*h(x))),
Eq(g(x).diff(x), (4*f(x)*h(x) - 2*h(x)*f(x))),
Eq(h(x).diff(x), (3*g(x)*f(x) - 4*f(x)*g(x))),
]
dsolve(eqs) # KeyError when matching
# sol = ?
# assert dsolve_sol == sol
# assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0])
@slow
@XFAIL
def test_nonlinear_3eq_order1_type3():
if ON_TRAVIS:
skip("Too slow for travis.")
eqs = [
Eq(f(x).diff(x), (2*f(x)**2 - 3 )),
Eq(g(x).diff(x), (4 - 2*h(x) )),
Eq(h(x).diff(x), (3*h(x) - 4*f(x)**2)),
]
dsolve(eqs) # Not sure if this finishes...
# sol = ?
# assert dsolve_sol == sol
# assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0])
@XFAIL
def test_nonlinear_3eq_order1_type5():
eqs = [
Eq(f(x).diff(x), f(x)*(2*f(x) - 3*g(x))),
Eq(g(x).diff(x), g(x)*(4*g(x) - 2*h(x))),
Eq(h(x).diff(x), h(x)*(3*h(x) - 4*f(x))),
]
dsolve(eqs) # KeyError
# sol = ?
# assert dsolve_sol == sol
# assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0])
def test_linear_2eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
k, l, m, n = symbols('k, l, m, n', Integer=True)
t = Symbol('t')
x0, y0 = symbols('x0, y0', cls=Function)
eq1 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23))
sol1 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \
Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))]
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23))
sol2 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \
Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))]
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t)))
sol3 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
sol4 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t)))
sol5 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \
C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \
C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t)))
sol6 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \
Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \
exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))]
s = dsolve(eq6)
assert s == sol6 # too complicated to test with subs and simplify
# assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails
@slow
def test_linear_2eq_order2():
x, y, z = symbols('x, y, z', cls=Function)
k, l, m, n = symbols('k, l, m, n', Integer=True)
t, l = symbols('t, l')
x0, y0 = symbols('x0, y0', cls=Function)
eq1 = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t)))
sol1 = [Eq(x(t), 43*C1*exp(t*rootof(l**4 - 14*l**2 + 2, 0)) + 43*C2*exp(t*rootof(l**4 - 14*l**2 + 2, 1)) + \
43*C3*exp(t*rootof(l**4 - 14*l**2 + 2, 2)) + 43*C4*exp(t*rootof(l**4 - 14*l**2 + 2, 3))), \
Eq(y(t), C1*(rootof(l**4 - 14*l**2 + 2, 0)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 0)) + \
C2*(rootof(l**4 - 14*l**2 + 2, 1)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 1)) + \
C3*(rootof(l**4 - 14*l**2 + 2, 2)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 2)) + \
C4*(rootof(l**4 - 14*l**2 + 2, 3)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 3)))]
assert dsolve(eq1) == sol1
# FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0]) # this one fails
eq2 = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12))
sol2 = [Eq(x(t), 3*C1*exp(t*rootof(l**4 - 15*l**2 + 29, 0)) + 3*C2*exp(t*rootof(l**4 - 15*l**2 + 29, 1)) + \
3*C3*exp(t*rootof(l**4 - 15*l**2 + 29, 2)) + 3*C4*exp(t*rootof(l**4 - 15*l**2 + 29, 3)) - Rational(181, 29)), \
Eq(y(t), C1*(rootof(l**4 - 15*l**2 + 29, 0)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 0)) + \
C2*(rootof(l**4 - 15*l**2 + 29, 1)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 1)) + \
C3*(rootof(l**4 - 15*l**2 + 29, 2)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 2)) + \
C4*(rootof(l**4 - 15*l**2 + 29, 3)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 3)) + Rational(183, 29))]
assert dsolve(eq2) == sol2
# FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0]) # this one fails
eq3 = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0))
sol3 = [Eq(x(t), C1*cos(t*(Rational(9, 2) + sqrt(109)/2)) + C2*sin(t*(Rational(9, 2) + sqrt(109)/2)) + C3*cos(t*(-sqrt(109)/2 + Rational(9, 2))) + \
C4*sin(t*(-sqrt(109)/2 + Rational(9, 2)))), Eq(y(t), -C1*sin(t*(Rational(9, 2) + sqrt(109)/2)) + C2*cos(t*(Rational(9, 2) + sqrt(109)/2)) - \
C3*sin(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*cos(t*(-sqrt(109)/2 + Rational(9, 2))))]
assert dsolve(eq3) == sol3
assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t)))
sol4 = [Eq(x(t), C3*t + t*Integral((9*C1*exp(3*sqrt(7)*t**2/2) + 9*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t)), \
Eq(y(t), C4*t + t*Integral((3*sqrt(7)*C1*exp(3*sqrt(7)*t**2/2) - 3*sqrt(7)*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t))]
assert dsolve(eq4) == sol4
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(diff(x(t),t,t), (log(t)+t**2)*diff(x(t),t)+(log(t)+t**2)*3*diff(y(t),t)), Eq(diff(y(t),t,t), \
(log(t)+t**2)*2*diff(x(t),t)+(log(t)+t**2)*9*diff(y(t),t)))
sol5 = [Eq(x(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2 - \
C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4 - \
(sqrt(22) + 5)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2) + \
(-sqrt(22) + 5)*(C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C4))/88), \
Eq(y(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + \
C2 - C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4)/44)]
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t,t), log(t)*t*diff(y(t),t) - log(t)*y(t)), Eq(diff(y(t),t,t), log(t)*t*diff(x(t),t) - log(t)*x(t)))
sol6 = [Eq(x(t), C3*t + t*Integral((C1*exp(Integral(t*log(t), t)) + \
C2*exp(-Integral(t*log(t), t)))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*exp(Integral(t*log(t), t)) - \
C2*exp(-Integral(t*log(t), t)))/t**2, t))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0])
eq7 = (Eq(diff(x(t),t,t), log(t)*(t*diff(x(t),t) - x(t)) + exp(t)*(t*diff(y(t),t) - y(t))), \
Eq(diff(y(t),t,t), (t**2)*(t*diff(x(t),t) - x(t)) + (t)*(t*diff(y(t),t) - y(t))))
sol7 = [Eq(x(t), C3*t + t*Integral((C1*x0(t) + C2*x0(t)*Integral(t*exp(t)*exp(Integral(t**2, t))*\
exp(Integral(t*log(t), t))/x0(t)**2, t))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*y0(t) + \
C2*(y0(t)*Integral(t*exp(t)*exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0(t)**2, t) + \
exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0(t)))/t**2, t))]
assert dsolve(eq7) == sol7
# FIXME: assert checksysodesol(eq7, sol7) == (True, [0, 0])
eq8 = (Eq(diff(x(t),t,t), t*(4*x(t) + 9*y(t))), Eq(diff(y(t),t,t), t*(12*x(t) - 6*y(t))))
sol8 = [Eq(x(t), -sqrt(133)*(-4*C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + 4*C1*airyai(-t*(1 + \
sqrt(133))**(S(1)/3)) - 4*C2*airybi(t*(-1 + sqrt(133))**(S(1)/3)) + 4*C2*airybi(-t*(1 + sqrt(133))**(S(1)/3)) +\
(-sqrt(133) - 1)*(C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + C2*airybi(t*(-1 + sqrt(133))**(S(1)/3))) - (-1 +\
sqrt(133))*(C1*airyai(-t*(1 + sqrt(133))**(S(1)/3)) + C2*airybi(-t*(1 + sqrt(133))**(S(1)/3))))/3192), \
Eq(y(t), -sqrt(133)*(-C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + C1*airyai(-t*(1 + sqrt(133))**(S(1)/3)) -\
C2*airybi(t*(-1 + sqrt(133))**(S(1)/3)) + C2*airybi(-t*(1 + sqrt(133))**(S(1)/3)))/266)]
assert dsolve(eq8) == sol8
assert checksysodesol(eq8, sol8) == (True, [0, 0])
assert filldedent(dsolve(eq8)) == filldedent('''
[Eq(x(t), -sqrt(133)*(-4*C1*airyai(t*(-1 + sqrt(133))**(1/3)) +
4*C1*airyai(-t*(1 + sqrt(133))**(1/3)) - 4*C2*airybi(t*(-1 +
sqrt(133))**(1/3)) + 4*C2*airybi(-t*(1 + sqrt(133))**(1/3)) +
(-sqrt(133) - 1)*(C1*airyai(t*(-1 + sqrt(133))**(1/3)) +
C2*airybi(t*(-1 + sqrt(133))**(1/3))) - (-1 +
sqrt(133))*(C1*airyai(-t*(1 + sqrt(133))**(1/3)) + C2*airybi(-t*(1 +
sqrt(133))**(1/3))))/3192), Eq(y(t), -sqrt(133)*(-C1*airyai(t*(-1 +
sqrt(133))**(1/3)) + C1*airyai(-t*(1 + sqrt(133))**(1/3)) -
C2*airybi(t*(-1 + sqrt(133))**(1/3)) + C2*airybi(-t*(1 +
sqrt(133))**(1/3)))/266)]''')
assert checksysodesol(eq8, sol8) == (True, [0, 0])
eq9 = (Eq(diff(x(t),t,t), t*(4*diff(x(t),t) + 9*diff(y(t),t))), Eq(diff(y(t),t,t), t*(12*diff(x(t),t) - 6*diff(y(t),t))))
sol9 = [Eq(x(t), -sqrt(133)*(4*C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + 4*C2 - \
4*C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - 4*C4 - (-1 + sqrt(133))*(C1*Integral(exp((-sqrt(133) - \
1)*Integral(t, t)), t) + C2) + (-sqrt(133) - 1)*(C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) + \
C4))/3192), Eq(y(t), -sqrt(133)*(C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + C2 - \
C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - C4)/266)]
assert dsolve(eq9) == sol9
assert checksysodesol(eq9, sol9) == (True, [0, 0])
eq10 = (t**2*diff(x(t),t,t) + 3*t*diff(x(t),t) + 4*t*diff(y(t),t) + 12*x(t) + 9*y(t), \
t**2*diff(y(t),t,t) + 2*t*diff(x(t),t) - 5*t*diff(y(t),t) + 15*x(t) + 8*y(t))
sol10 = [Eq(x(t), -C1*(-2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 13 + 2*sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \
346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) - \
C2*(-2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
13 - 2*sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) - C3*t**(1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*(2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 13 + 2*sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))) - C4*t**(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2)*(-2*sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))) + 2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 13)), Eq(y(t), C1*(-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14 + (-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) + C2*(-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))) + (-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2)*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) + C3*t**(1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*(sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))) + 14 + (1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2) + C4*t**(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \
346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2)*(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + \
8 + 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))) + (-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \
346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2)**2 + sqrt(-346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14))]
assert dsolve(eq10) == sol10
# FIXME: assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this hangs or at least takes a while...
def test_nonlinear_2eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol1 = [
Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq1) == sol1
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5))
sol2 = [
Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq2) == sol2
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3))
tt = Rational(2, 3)
sol3 = [
Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)),
Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)]
assert dsolve(eq3) == sol3
# FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2))
sol4 = set([Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))])
assert dsolve(eq4) == sol4
# FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2))
sol5 = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)])
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol6 = [
Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0])
@slow
def test_nonlinear_3eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t, u = symbols('t u')
eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t))
sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))),
C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)),
(u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)*
sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)]
assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)]
# FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0])
eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t))
sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 +
sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)),
(u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)*
sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)]
assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)]
# FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0])
@slow
def test_dsolve_options():
eq = x*f(x).diff(x) + f(x)
a = dsolve(eq, hint='all')
b = dsolve(eq, hint='all', simplify=False)
c = dsolve(eq, hint='all_Integral')
keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear',
'1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral',
'almost_linear', 'almost_linear_Integral', 'best', 'best_hint',
'default', 'lie_group',
'nth_linear_euler_eq_homogeneous', 'order',
'separable', 'separable_Integral']
Integral_keys = ['1st_exact_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral',
'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default',
'nth_linear_euler_eq_homogeneous',
'order', 'separable_Integral']
assert sorted(a.keys()) == keys
assert a['order'] == ode_order(eq, f(x))
assert a['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best') == Eq(f(x), C1/x)
assert a['default'] == 'separable'
assert a['best_hint'] == 'separable'
assert not a['1st_exact'].has(Integral)
assert not a['separable'].has(Integral)
assert not a['1st_homogeneous_coeff_best'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not a['1st_linear'].has(Integral)
assert a['1st_linear_Integral'].has(Integral)
assert a['1st_exact_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert a['separable_Integral'].has(Integral)
assert sorted(b.keys()) == keys
assert b['order'] == ode_order(eq, f(x))
assert b['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x)
assert b['default'] == 'separable'
assert b['best_hint'] == '1st_linear'
assert a['separable'] != b['separable']
assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \
b['1st_homogeneous_coeff_subs_dep_div_indep']
assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \
b['1st_homogeneous_coeff_subs_indep_div_dep']
assert not b['1st_exact'].has(Integral)
assert not b['separable'].has(Integral)
assert not b['1st_homogeneous_coeff_best'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not b['1st_linear'].has(Integral)
assert b['1st_linear_Integral'].has(Integral)
assert b['1st_exact_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert b['separable_Integral'].has(Integral)
assert sorted(c.keys()) == Integral_keys
raises(ValueError, lambda: dsolve(eq, hint='notarealhint'))
raises(ValueError, lambda: dsolve(eq, hint='Liouville'))
assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \
dsolve(f(x).diff(x) - 1/f(x)**2, hint='best')
assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x),
hint="1st_linear_Integral") == \
Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)*
exp(Integral(1, x)), x))*exp(-Integral(1, x)))
def test_classify_ode():
assert classify_ode(f(x).diff(x, 2), f(x)) == \
(
'nth_algebraic',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'Liouville',
'2nd_power_series_ordinary',
'nth_algebraic_Integral',
'Liouville_Integral',
)
assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral')
assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == (
'nth_algebraic',
'separable',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable',
'nth_algebraic',
'separable',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
# issue 4749: f(x) should be cleared from highest derivative before classifying
a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x))
b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x))
c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x))
assert a == ('1st_linear',
'Bernoulli',
'almost_linear',
'1st_power_series', "lie_group",
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert b == ('factorable',
'1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert c == ('1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert classify_ode(
2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x)
) == ('Bernoulli', 'almost_linear', 'lie_group',
'Bernoulli_Integral', 'almost_linear_Integral')
assert 'Riccati_special_minus2' in \
classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x))
raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff(
y), f(x, y)))
# issue 5176
k = Symbol('k')
assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) +
k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \
('separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
# preprocessing
ans = ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_algebraic_Integral',
'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral')
# w/o f(x) given
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans
# w/ f(x) and prep=True
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x),
prep=True) == ans
assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_linear',
'Bernoulli', '1st_power_series',
'lie_group', 'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_linear', 'Bernoulli',
'1st_power_series', 'lie_group', 'nth_algebraic_Integral',
'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral')
# test issue 13864
assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \
('1st_power_series', 'lie_group')
assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict)
def test_classify_ode_ics():
# Dummy
eq = f(x).diff(x, x) - f(x)
# Not f(0) or f'(0)
ics = {x: 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
############################
# f(0) type (AppliedUndef) #
############################
# Wrong function
ics = {g(0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(0, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(0): f(1)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(0): 1}
classify_ode(eq, f(x), ics=ics)
#####################
# f'(0) type (Subs) #
#####################
# Wrong function
ics = {g(x).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Wrong variable
ics = {f(y).diff(y).subs(y, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, y).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, 0): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, 0): 1}
classify_ode(eq, f(x), ics=ics)
###########################
# f'(y) type (Derivative) #
###########################
# Wrong function
ics = {g(x).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, z).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, y): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, y): 1}
classify_ode(eq, f(x), ics=ics)
def test_classify_sysode():
# Here x is assumed to be x(t) and y as y(t) for simplicity.
# Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively.
k, l, m, n = symbols('k, l, m, n', Integer=True)
k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True)
P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function)
P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function)
x, y, z = symbols('x, y, z', cls=Function)
t = symbols('t')
x1 = diff(x(t),t) ; y1 = diff(y(t),t) ;
x2 = diff(x(t),t,t) ; y2 = diff(y(t),t,t)
eq2 = (Eq(x2, k*x(t) - l*y1), Eq(y2, l*x1 + k*y(t)))
sol2 = {'order': {y(t): 2, x(t): 2}, 'type_of_equation': 'type3', 'is_linear': True, 'eq': \
[-k*x(t) + l*Derivative(y(t), t) + Derivative(x(t), t, t), -k*y(t) - l*Derivative(x(t), t) + \
Derivative(y(t), t, t)], 'no_of_equation': 2, 'func_coeff': {(0, y(t), 0): 0, (0, x(t), 2): 1, \
(1, y(t), 1): 0, (1, y(t), 2): 1, (1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -k, (1, x(t), 1): \
-l, (0, x(t), 1): 0, (0, y(t), 1): l, (1, x(t), 0): 0, (1, y(t), 0): -k}, 'func': [x(t), y(t)]}
assert classify_sysode(eq2) == sol2
eq3 = (Eq(x2+4*x1+3*y1+9*x(t)+7*y(t), 11*exp(I*t)), Eq(y2+5*x1+8*y1+3*x(t)+12*y(t), 2*exp(I*t)))
sol3 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): 9, \
(1, x(t), 1): 5, (0, x(t), 1): 4, (0, y(t), 1): 3, (1, x(t), 0): 3, (1, y(t), 0): 12, (0, y(t), 0): 7, \
(0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): 8}, 'type_of_equation': 'type4', 'func': [x(t), y(t)], \
'is_linear': True, 'eq': [9*x(t) + 7*y(t) - 11*exp(I*t) + 4*Derivative(x(t), t) + 3*Derivative(y(t), t) + \
Derivative(x(t), t, t), 3*x(t) + 12*y(t) - 2*exp(I*t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + \
Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}}
assert classify_sysode(eq3) == sol3
eq4 = (Eq((4*t**2 + 7*t + 1)**2*x2, 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*y2, x(t) + 9*y(t)))
sol4 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -5, \
(1, x(t), 1): 0, (0, x(t), 1): 0, (0, y(t), 1): 0, (1, x(t), 0): -1, (1, y(t), 0): -9, (0, y(t), 0): -35, \
(0, x(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, (1, y(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, \
(1, y(t), 1): 0}, 'type_of_equation': 'type10', 'func': [x(t), y(t)], 'is_linear': True, \
'eq': [(4*t**2 + 7*t + 1)**2*Derivative(x(t), t, t) - 5*x(t) - 35*y(t), (4*t**2 + 7*t + 1)**2*Derivative(y(t), t, t)\
- x(t) - 9*y(t)], 'order': {y(t): 2, x(t): 2}}
assert classify_sysode(eq4) == sol4
eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t))))
sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \
[x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \
y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq6) == sol6
eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t)))
sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \
'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \
Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq7) == sol7
eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)))
sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \
[-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \
Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \
(1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2}
assert classify_sysode(eq8) == sol8
eq10 = (x2 + log(t)*(t*x1 - x(t)) + exp(t)*(t*y1 - y(t)), y2 + (t**2)*(t*x1 - x(t)) + (t)*(t*y1 - y(t)))
sol10 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -log(t), \
(1, x(t), 1): t**3, (0, x(t), 1): t*log(t), (0, y(t), 1): t*exp(t), (1, x(t), 0): -t**2, (1, y(t), 0): -t, \
(0, y(t), 0): -exp(t), (0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): t**2}, 'type_of_equation': 'type11', \
'func': [x(t), y(t)], 'is_linear': True, 'eq': [(t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - \
y(t))*exp(t) + Derivative(x(t), t, t), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) \
+ Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}}
assert classify_sysode(eq10) == sol10
eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5))
sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \
'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \
-y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq11) == sol11
eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2))
sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \
'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \
Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq13) == sol13
def test_solve_ics():
# Basic tests that things work from dsolve.
assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \
Eq(f(x), sqrt(2 * x + 2))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1,
f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x))
assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)],
[f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))]
# Test cases where dsolve returns two solutions.
eq = (x**2*f(x)**2 - x).diff(x)
assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x),
-sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)]
assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x),
-sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)]
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \
{C2: 1}
# Some more complicated tests Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)}
K, r, f0 = symbols('K r f0')
sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1)))
assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol
#Order dependent issues Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
# XXX: Ought to be ValueError
raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1}))
# Degenerate case. f'(0) is identically 0.
raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0}))
EI, q, L = symbols('EI q L')
# eq = Eq(EI*diff(f(x), x, 4), q)
sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))]
funcs = [f(x)]
constants = [C1, C2, C3, C4]
# Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)),
# and Subs
ics1 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
f(L).diff(L, 2): 0,
f(L).diff(L, 3): 0}
ics2 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
Subs(f(x).diff(x, 2), x, L): 0,
Subs(f(x).diff(x, 3), x, L): 0}
solved_constants1 = solve_ics(sols, funcs, constants, ics1)
solved_constants2 = solve_ics(sols, funcs, constants, ics2)
assert solved_constants1 == solved_constants2 == {
C1: 0,
C2: 0,
C3: L**2*q/(4*EI),
C4: -L*q/(6*EI)}
def test_ode_order():
f = Function('f')
g = Function('g')
x = Symbol('x')
assert ode_order(3*x*exp(f(x)), f(x)) == 0
assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1
assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2
assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3
assert ode_order(diff(f(x), x, x), g(x)) == 0
assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2
assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0
# issue 5835: ode_order has to also work for unevaluated derivatives
# (ie, without using doit()).
assert ode_order(Derivative(x*f(x), x), f(x)) == 1
assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2
assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0
assert ode_order(Derivative(f(x), x, x), g(x)) == 0
assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1
assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3
assert ode_order(
x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3
# In all tests below, checkodesol has the order option set to prevent
# superfluous calls to ode_order(), and the solve_for_func flag set to False
# because dsolve() already tries to solve for the function, unless the
# simplify=False option is set.
def test_old_ode_tests():
# These are simple tests from the old ode module
eq1 = Eq(f(x).diff(x), 0)
eq2 = Eq(3*f(x).diff(x) - 5, 0)
eq3 = Eq(3*f(x).diff(x), 5)
eq4 = Eq(9*f(x).diff(x, x) + f(x), 0)
eq5 = Eq(9*f(x).diff(x, x), f(x))
# Type: a(x)f'(x)+b(x)*f(x)+c(x)=0
eq6 = Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0)
eq7 = Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0)
# Type: 2nd order, constant coefficients (two real different roots)
eq8 = Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0)
# Type: 2nd order, constant coefficients (two real equal roots)
eq9 = Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0)
# Type: 2nd order, constant coefficients (two complex roots)
eq10 = Eq(3*f(x).diff(x) - 1, 0)
eq11 = Eq(x*f(x).diff(x) - 1, 0)
sol1 = Eq(f(x), C1)
sol2 = Eq(f(x), C1 + x*Rational(5, 3))
sol3 = Eq(f(x), C1 + x*Rational(5, 3))
sol4 = Eq(f(x), C1*sin(x/3) + C2*cos(x/3))
sol5 = Eq(f(x), C1*exp(-x/3) + C2*exp(x/3))
sol6 = Eq(f(x), (C1 - cos(x))/x**3)
sol7 = Eq(f(x), (C1 + C2*exp(x))*exp(x))
sol8 = Eq(f(x), (C1 + C2*x)*exp(2*x))
sol9 = Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x))
sol10 = Eq(f(x), C1 + x/3)
sol11 = Eq(f(x), C1 + log(x))
assert dsolve(eq1) == sol1
assert dsolve(eq1.lhs) == sol1
assert dsolve(eq2) == sol2
assert dsolve(eq3) == sol3
assert dsolve(eq4) == sol4
assert dsolve(eq5) == sol5
assert dsolve(eq6) == sol6
assert dsolve(eq7) == sol7
assert dsolve(eq8) == sol8
assert dsolve(eq9) == sol9
assert dsolve(eq10) == sol10
assert dsolve(eq11) == sol11
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0]
@slow
def test_1st_exact1():
# Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0,
# where dp/df == dq/dx
eq1 = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
eq2 = (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x)
eq3 = 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x)
eq4 = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
eq5 = 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x)
sol1 = [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
sol2 = Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2))))
sol2b = Eq(log(f(x)) + x/f(x) + x**2, C1)
sol3 = Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1)
sol4 = Eq(x*cos(f(x)) + f(x)**3/3, C1)
sol5 = Eq(x**2*f(x) + f(x)**3/3, C1)
assert dsolve(eq1, f(x), hint='1st_exact') == sol1
assert dsolve(eq2, f(x), hint='1st_exact') == sol2
assert dsolve(eq3, f(x), hint='1st_exact') == sol3
assert dsolve(eq4, hint='1st_exact') == sol4
assert dsolve(eq5, hint='1st_exact', simplify=False) == sol5
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
# issue 5080 blocks the testing of this solution
# FIXME: assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2b, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0]
@slow
@XFAIL
def test_1st_exact2_broken():
"""
This is an exact equation that fails under the exact engine. It is caught
by first order homogeneous albeit with a much contorted solution. The
exact engine fails because of a poorly simplified integral of q(0,y)dy,
where q is the function multiplying f'. The solutions should be
Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is
equivalent, but it is so complex that checkodesol fails, and takes a long
time to do so.
"""
if ON_TRAVIS:
skip("Too slow for travis.")
eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) -
sqrt(x**2 + f(x)**2)))*f(x).diff(x))
sol = Eq(log(x),
C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x +
27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)*
log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) +
9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) +
9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))))
assert dsolve(eq) == sol # Slow
# FIXME: Checked in test_1st_exact2_broken_check below
@slow
def test_1st_exact2_broken_check():
# See test_1st_exact2_broken above
eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) -
sqrt(x**2 + f(x)**2)))*f(x).diff(x))
sol = Eq(log(x),
C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x +
27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)*
log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) +
9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) +
9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))))
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_homogeneous_order():
assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0
assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None
assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1
assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/
(pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6)
assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0
assert homogeneous_order(f(x), x, f(x)) == 1
assert homogeneous_order(f(x)**2, x, f(x)) == 2
assert homogeneous_order(x*y*z, x, y) == 2
assert homogeneous_order(x*y*z, x, y, z) == 3
assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2
assert homogeneous_order(f(x, y)**2, x, f(x), y) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None
assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None
assert homogeneous_order(f(y), f(x), x) is None
assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0
assert homogeneous_order(log(1/y) + log(x**2), x, y) is None
assert homogeneous_order(log(1/y) + log(x), x, y) == 0
assert homogeneous_order(log(x/y), x, y) == 0
assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0
a = Symbol('a')
assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0
assert homogeneous_order(f(x).diff(x), x, y) is None
assert homogeneous_order(-f(x).diff(x) + x, x, y) is None
assert homogeneous_order(O(x), x, y) is None
assert homogeneous_order(x + O(x**2), x, y) is None
assert homogeneous_order(x**pi, x) == pi
assert homogeneous_order(x**x, x) is None
raises(ValueError, lambda: homogeneous_order(x*y))
@slow
def test_1st_homogeneous_coeff_ode():
# Type: First order homogeneous, y'=f(y/x)
eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x)
eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x)
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x)
eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x)
eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x)
eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x)
eq8 = x + f(x) - (x - f(x))*f(x).diff(x)
sol1 = Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x))
sol2 = Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2)
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1)))
sol4 = Eq(log(f(x)), C1 - 2*exp(x/f(x)))
sol5 = Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x)
sol6 = Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2)
sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))
sol8 = Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x))
# indep_div_dep actually has a simpler solution for eq2,
# but it runs too slow
assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1
assert dsolve(eq2, hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False) == sol2
assert dsolve(eq3, hint='1st_homogeneous_coeff_best') == sol3
assert dsolve(eq4, hint='1st_homogeneous_coeff_best') == sol4
assert dsolve(eq5, hint='1st_homogeneous_coeff_best') == sol5
assert dsolve(eq6, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol6
assert dsolve(eq7, hint='1st_homogeneous_coeff_best') == sol7
assert dsolve(eq8, hint='1st_homogeneous_coeff_best') == sol8
# FIXME: sol3 and sol5 don't work with checkodesol (because of LambertW?)
# previous code was testing with these other solutions:
sol3b = Eq(-f(x)/(1 + log(x/f(x))), C1)
sol5b = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0]
assert checkodesol(eq5, sol5b, order=1, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check2():
eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x)
sol2 = Eq(x/tan(f(x)/(2*x)), C1)
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check3():
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
# This solution is correct:
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(1 - C1)))
assert dsolve(eq3) == sol3
# FIXME: Checked in test_1st_homogeneous_coeff_ode_check3_check below
# Alternate form:
sol3a = Eq(f(x), x*exp(1 - LambertW(C1*x)))
assert checkodesol(eq3, sol3a, solve_for_func=True)[0]
@XFAIL
def test_1st_homogeneous_coeff_ode_check3_check():
# See test_1st_homogeneous_coeff_ode_check3 above
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(1 - C1)))
assert checkodesol(eq3, sol3) == (True, 0) # XFAIL
def test_1st_homogeneous_coeff_ode_check7():
eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x)
sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))
assert dsolve(eq7) == sol7
assert checkodesol(eq7, sol7, order=1, solve_for_func=False) == (True, 0)
def test_1st_homogeneous_coeff_ode2():
eq1 = f(x).diff(x) - f(x)/x + 1/sin(f(x)/x)
eq2 = x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x)
eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x)
sol1 = [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))]
sol2 = Eq(log(f(x)), log(C1) + log(x/f(x)) - log(x**2/f(x)**2 - 1))
sol3 = Eq(f(x), log((1/(C1 - log(x)))**x))
# specific hints are applied for speed reasons
assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1
assert dsolve(eq2, hint='1st_homogeneous_coeff_best', simplify=False) == sol2
assert dsolve(eq3, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol3
# FIXME: sol3 doesn't work with checkodesol (because of **x?)
# previous code was testing with this other solution:
sol3b = Eq(f(x), log(log(C1/x)**(-x)))
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check9():
_u2 = Dummy('u2')
__a = Dummy('a')
eq9 = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x)
sol9 = Eq(-Integral(-1/(-(1 - sqrt(1 - _u2**2))*_u2 + _u2), (_u2, __a,
x/f(x))) + log(C1*f(x)), 0)
assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode3():
# The standard integration engine cannot handle one of the integrals
# involved (see issue 4551). meijerg code comes up with an answer, but in
# unconventional form.
# checkodesol fails for this equation, so its test is in
# test_1st_homogeneous_coeff_ode_check9 above. It has to compare string
# expressions because u2 is a dummy variable.
eq = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x)
sol = Eq(log(f(x)), C1 + Piecewise(
(acosh(f(x)/x), abs(f(x)**2)/x**2 > 1),
(-I*asin(f(x)/x), True)))
assert dsolve(eq, hint='1st_homogeneous_coeff_subs_indep_div_dep') == sol
def test_1st_homogeneous_coeff_corner_case():
eq1 = f(x).diff(x) - f(x)/x
c1 = classify_ode(eq1, f(x))
eq2 = x*f(x).diff(x) - f(x)
c2 = classify_ode(eq2, f(x))
sdi = "1st_homogeneous_coeff_subs_dep_div_indep"
sid = "1st_homogeneous_coeff_subs_indep_div_dep"
assert sid not in c1 and sdi not in c1
assert sid not in c2 and sdi not in c2
@slow
def test_nth_linear_constant_coeff_homogeneous():
# From Exercise 20, in Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 220
a = Symbol('a', positive=True)
k = Symbol('k', real=True)
eq1 = f(x).diff(x, 2) + 2*f(x).diff(x)
eq2 = f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x)
eq3 = f(x).diff(x, 2) - f(x)
eq4 = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x)
eq5 = 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x)
eq6 = Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0)
eq7 = diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x)
eq8 = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x)
eq9 = f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \
4*f(x).diff(x) - 2*f(x)
eq10 = f(x).diff(x, 4) - a**2*f(x)
eq11 = f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x)
eq12 = f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x)
eq13 = f(x).diff(x, 4)
eq14 = f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x)
eq15 = 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x)
eq16 = f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x)
eq17 = f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x)
eq18 = f(x).diff(x, 4) + 3*f(x).diff(x, 3)
eq19 = f(x).diff(x, 4) - 2*f(x).diff(x, 2)
eq20 = f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \
12*f(x).diff(x) + 36*f(x)
eq21 = 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x)
eq22 = f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x)
eq23 = f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x)
eq24 = f(x).diff(x, 2) - f(x).diff(x) + f(x)
eq25 = f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x)
eq26 = f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x)
eq27 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x)
eq28 = f(x).diff(x, 3) + 8*f(x)
eq29 = f(x).diff(x, 4) + 4*f(x).diff(x, 2)
eq30 = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x)
eq31 = f(x).diff(x, 4) + f(x).diff(x, 2) + f(x)
eq32 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x)
sol1 = Eq(f(x), C1 + C2*exp(-2*x))
sol2 = Eq(f(x), (C1 + C2*exp(x))*exp(x))
sol3 = Eq(f(x), C1*exp(x) + C2*exp(-x))
sol4 = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))
sol5 = Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3)))
sol6 = Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1)))
sol7 = Eq(f(x), C3*exp(3*x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))
sol8 = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x))
sol9 = Eq(f(x), C3*exp(-x) + C4*exp(x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))
sol10 = Eq(f(x),
C1*sin(x*sqrt(a)) + C2*cos(x*sqrt(a)) + C3*exp(x*sqrt(a)) +
C4*exp(-x*sqrt(a)))
sol11 = Eq(f(x),
C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2))))
sol12 = Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x))
sol13 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3)
sol14 = Eq(f(x), (C1 + C2*x)*exp(-2*x))
sol15 = Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3))
sol16 = Eq(f(x), (C1 + x*(C2 + C3*x))*exp(2*x))
sol17 = Eq(f(x), (C1 + C2*x)*exp(a*x))
sol18 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))
sol19 = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2)))
sol20 = Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x))
sol21 = Eq(f(x), C1*exp(x/2) + C2*exp(-x) + C3*exp(-x/3) + C4*exp(x*Rational(5, 6)))
sol22 = Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x))
sol23 = Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x))
sol24 = Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2))
sol25 = Eq(f(x),
C1*cos(x*sqrt(3)) + C2*sin(x*sqrt(3)) + C3*sin(x*sqrt(2)) +
C4*cos(x*sqrt(2)))
sol26 = Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x))
sol27 = Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2)))
sol28 = Eq(f(x),
(C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x))
sol29 = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x)
sol30 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))
sol31 = Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))/sqrt(exp(x))
+ (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*sqrt(exp(x)))
sol32 = Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2))
+ C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2)))
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
sol6s = constant_renumber(sol6)
sol7s = constant_renumber(sol7)
sol8s = constant_renumber(sol8)
sol9s = constant_renumber(sol9)
sol10s = constant_renumber(sol10)
sol11s = constant_renumber(sol11)
sol12s = constant_renumber(sol12)
sol13s = constant_renumber(sol13)
sol14s = constant_renumber(sol14)
sol15s = constant_renumber(sol15)
sol16s = constant_renumber(sol16)
sol17s = constant_renumber(sol17)
sol18s = constant_renumber(sol18)
sol19s = constant_renumber(sol19)
sol20s = constant_renumber(sol20)
sol21s = constant_renumber(sol21)
sol22s = constant_renumber(sol22)
sol23s = constant_renumber(sol23)
sol24s = constant_renumber(sol24)
sol25s = constant_renumber(sol25)
sol26s = constant_renumber(sol26)
sol27s = constant_renumber(sol27)
sol28s = constant_renumber(sol28)
sol29s = constant_renumber(sol29)
sol30s = constant_renumber(sol30)
assert dsolve(eq1) in (sol1, sol1s)
assert dsolve(eq2) in (sol2, sol2s)
assert dsolve(eq3) in (sol3, sol3s)
assert dsolve(eq4) in (sol4, sol4s)
assert dsolve(eq5) in (sol5, sol5s)
assert dsolve(eq6) in (sol6, sol6s)
got = dsolve(eq7)
assert got in (sol7, sol7s), got
assert dsolve(eq8) in (sol8, sol8s)
got = dsolve(eq9)
assert got in (sol9, sol9s), got
assert dsolve(eq10) in (sol10, sol10s)
assert dsolve(eq11) in (sol11, sol11s)
assert dsolve(eq12) in (sol12, sol12s)
assert dsolve(eq13) in (sol13, sol13s)
assert dsolve(eq14) in (sol14, sol14s)
assert dsolve(eq15) in (sol15, sol15s)
got = dsolve(eq16)
assert got in (sol16, sol16s), got
assert dsolve(eq17) in (sol17, sol17s)
assert dsolve(eq18) in (sol18, sol18s)
assert dsolve(eq19) in (sol19, sol19s)
assert dsolve(eq20) in (sol20, sol20s)
assert dsolve(eq21) in (sol21, sol21s)
assert dsolve(eq22) in (sol22, sol22s)
assert dsolve(eq23) in (sol23, sol23s)
assert dsolve(eq24) in (sol24, sol24s)
assert dsolve(eq25) in (sol25, sol25s)
assert dsolve(eq26) in (sol26, sol26s)
assert dsolve(eq27) in (sol27, sol27s)
assert dsolve(eq28) in (sol28, sol28s)
assert dsolve(eq29) in (sol29, sol29s)
assert dsolve(eq30) in (sol30, sol30s)
assert dsolve(eq31) in (sol31,)
assert dsolve(eq32) in (sol32,)
assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=3, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=3, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=4, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=4, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=4, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=2, solve_for_func=False)[0]
assert checkodesol(eq13, sol13, order=4, solve_for_func=False)[0]
assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0]
assert checkodesol(eq15, sol15, order=3, solve_for_func=False)[0]
assert checkodesol(eq16, sol16, order=3, solve_for_func=False)[0]
assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0]
assert checkodesol(eq18, sol18, order=4, solve_for_func=False)[0]
assert checkodesol(eq19, sol19, order=4, solve_for_func=False)[0]
assert checkodesol(eq20, sol20, order=4, solve_for_func=False)[0]
assert checkodesol(eq21, sol21, order=4, solve_for_func=False)[0]
assert checkodesol(eq22, sol22, order=4, solve_for_func=False)[0]
assert checkodesol(eq23, sol23, order=2, solve_for_func=False)[0]
assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0]
assert checkodesol(eq25, sol25, order=4, solve_for_func=False)[0]
assert checkodesol(eq26, sol26, order=2, solve_for_func=False)[0]
assert checkodesol(eq27, sol27, order=4, solve_for_func=False)[0]
assert checkodesol(eq28, sol28, order=3, solve_for_func=False)[0]
assert checkodesol(eq29, sol29, order=4, solve_for_func=False)[0]
assert checkodesol(eq30, sol30, order=5, solve_for_func=False)[0]
assert checkodesol(eq31, sol31, order=4, solve_for_func=False)[0]
assert checkodesol(eq32, sol32, order=4, solve_for_func=False)[0]
# Issue #15237
eqn = Derivative(x*f(x), x, x, x)
hint = 'nth_linear_constant_coeff_homogeneous'
raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=True))
raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=False))
def test_nth_linear_constant_coeff_homogeneous_rootof():
# One real root, two complex conjugate pairs
eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)]
sol = Eq(f(x),
C5*exp(r1*x)
+ exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x))
+ exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Three real roots, one complex conjugate pair
eq = f(x).diff(x,5) - 3*f(x).diff(x) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - 3*x + 1, n) for n in range(5)]
sol = Eq(f(x),
C3*exp(r1*x) + C4*exp(r2*x) + C5*exp(r3*x)
+ exp(re(r4)*x) * (C1*sin(im(r4)*x) + C2*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Five distinct real roots
eq = f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)]
sol = Eq(f(x), C1*exp(r1*x) + C2*exp(r2*x) + C3*exp(r3*x) + C4*exp(r4*x) + C5*exp(r5*x))
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Rational root and unsolvable quintic
eq = f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x)
r2, r3, r4, r5, r6 = [rootof(x**5 - x**4 + 10, n) for n in range(5)]
sol = Eq(f(x),
C5*exp(5*x)
+ C6*exp(x*r2)
+ exp(re(r3)*x) * (C1*sin(im(r3)*x) + C2*cos(im(r3)*x))
+ exp(re(r5)*x) * (C3*sin(im(r5)*x) + C4*cos(im(r5)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Five double roots (this is (x**5 - x + 1)**2)
eq = f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5) + f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - x + 1, n) for n in range(5)]
sol = Eq(f(x), (C1 + C2*x)*exp(x*r1) + (C10*sin(x*im(r4)) + C7*x*sin(x*im(r4)) + (
C8 + C9*x)*cos(x*im(r4)))*exp(x*re(r4)) + (C3*x*sin(x*im(r2)) + C6*sin(x*im(r2)
) + (C4 + C5*x)*cos(x*im(r2)))*exp(x*re(r2)))
got = dsolve(eq)
assert sol == got, got
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
def test_nth_linear_constant_coeff_homogeneous_irrational():
our_hint='nth_linear_constant_coeff_homogeneous'
eq = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
E = exp(1)
eq = Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E)))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
eq = Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi)))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
eq = Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
@XFAIL
@slow
def test_nth_linear_constant_coeff_homogeneous_rootof_sol():
# See https://github.com/sympy/sympy/issues/15753
if ON_TRAVIS:
skip("Too slow for travis.")
eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x)
sol = Eq(f(x),
C1*exp(x*rootof(x**5 + 11*x - 2, 0)) +
C2*exp(x*rootof(x**5 + 11*x - 2, 1)) +
C3*exp(x*rootof(x**5 + 11*x - 2, 2)) +
C4*exp(x*rootof(x**5 + 11*x - 2, 3)) +
C5*exp(x*rootof(x**5 + 11*x - 2, 4)))
assert checkodesol(eq, sol, order=5, solve_for_func=False)[0]
@XFAIL
def test_noncircularized_real_imaginary_parts():
# If this passes, lines numbered 3878-3882 (at the time of this commit)
# of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous
# should be removed.
y = sqrt(1+x)
i, r = im(y), re(y)
assert not (i.has(atan2) and r.has(atan2))
def test_collect_respecting_exponentials():
# If this test passes, lines 1306-1311 (at the time of this commit)
# of sympy/solvers/ode.py should be removed.
sol = 1 + exp(x/2)
assert sol == collect( sol, exp(x/3))
def test_undetermined_coefficients_match():
assert _undetermined_coefficients_match(g(x), x) == {'test': False}
assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \
{'test': True, 'trialset':
set([cos(2*x + sqrt(5)), sin(2*x + sqrt(5))])}
assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \
{'test': False}
s = set([cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)])
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
exp(2*x)*sin(x)*(x**2 + x + 1), x
) == {
'test': True, 'trialset': set([exp(2*x)*sin(x), x**2*exp(2*x)*sin(x),
cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x),
x*exp(2*x)*sin(x)])}
assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False}
assert _undetermined_coefficients_match(log(x), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': set([2**x, x*2**x, x**2*2**x])}
assert _undetermined_coefficients_match(x**y, x) == {'test': False}
assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \
{'test': True, 'trialset': set([exp(1 + 3*x)])}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': set([x*cos(x), x*sin(x), x**2*cos(x),
x**2*sin(x), cos(x), sin(x)])}
assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \
{'test': False}
assert _undetermined_coefficients_match(
x**2*sin(x)*exp(x) + x*sin(x) + x, x
) == {
'test': True, 'trialset': set([x**2*cos(x)*exp(x), x, cos(x), S.One,
exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x),
x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)])}
assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == {
'trialset': set([x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)]),
'test': True,
}
assert _undetermined_coefficients_match(2**x*x, x) == \
{'test': True, 'trialset': set([2**x, x*2**x])}
assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \
{'test': True, 'trialset': set([2**x*exp(2*x)])}
assert _undetermined_coefficients_match(exp(-x)/x, x) == \
{'test': False}
# Below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
assert _undetermined_coefficients_match(S(4), x) == \
{'test': True, 'trialset': set([S.One])}
assert _undetermined_coefficients_match(12*exp(x), x) == \
{'test': True, 'trialset': set([exp(x)])}
assert _undetermined_coefficients_match(exp(I*x), x) == \
{'test': True, 'trialset': set([exp(I*x)])}
assert _undetermined_coefficients_match(sin(x), x) == \
{'test': True, 'trialset': set([cos(x), sin(x)])}
assert _undetermined_coefficients_match(cos(x), x) == \
{'test': True, 'trialset': set([cos(x), sin(x)])}
assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \
{'test': True, 'trialset': set([S.One, cos(x), sin(x), exp(x)])}
assert _undetermined_coefficients_match(x**2, x) == \
{'test': True, 'trialset': set([S.One, x, x**2])}
assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(x), exp(x), exp(-x)])}
assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \
{'test': True, 'trialset': set([exp(2*x)*sin(x), cos(x)*exp(2*x)])}
assert _undetermined_coefficients_match(x - sin(x), x) == \
{'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])}
assert _undetermined_coefficients_match(x**2 + 2*x, x) == \
{'test': True, 'trialset': set([S.One, x, x**2])}
assert _undetermined_coefficients_match(4*x*sin(x), x) == \
{'test': True, 'trialset': set([x*cos(x), x*sin(x), cos(x), sin(x)])}
assert _undetermined_coefficients_match(x*sin(2*x), x) == \
{'test': True, 'trialset':
set([x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)])}
assert _undetermined_coefficients_match(x**2*exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])}
assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])}
assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \
{'test': True, 'trialset': set([S.One, x, x**2, exp(-2*x)])}
assert _undetermined_coefficients_match(x*exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(-x), exp(-x)])}
assert _undetermined_coefficients_match(x + exp(2*x), x) == \
{'test': True, 'trialset': set([S.One, x, exp(2*x)])}
assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \
{'test': True, 'trialset': set([cos(x), sin(x), exp(-x)])}
assert _undetermined_coefficients_match(exp(x), x) == \
{'test': True, 'trialset': set([exp(x)])}
# converted from sin(x)**2
assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \
{'test': True, 'trialset': set([S.One, cos(2*x), sin(2*x)])}
# converted from exp(2*x)*sin(x)**2
assert _undetermined_coefficients_match(
exp(2*x)*(S.Half + cos(2*x)/2), x
) == {
'test': True, 'trialset': set([exp(2*x)*sin(2*x), cos(2*x)*exp(2*x),
exp(2*x)])}
assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \
{'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])}
# converted from sin(2*x)*sin(x)
assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \
{'test': True, 'trialset': set([cos(x), cos(3*x), sin(x), sin(3*x)])}
assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False}
def test_issue_12623():
t = symbols("t")
u = symbols("u",cls=Function)
R, L, C, E_0, alpha = symbols("R L C E_0 alpha",positive=True)
omega = Symbol('omega')
eqRLC_1 = Eq( u(t).diff(t,t) + R /L*u(t).diff(t) + 1/(L*C)*u(t), alpha)
sol_1 = Eq(u(t), C*L*alpha + C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)))
assert dsolve(eqRLC_1) == sol_1
assert checkodesol(eqRLC_1, sol_1) == (True, 0)
eqRLC_2 = Eq( L*C*u(t).diff(t,t) + R*C*u(t).diff(t) + u(t), E_0*exp(I*omega*t) )
sol_2 = Eq(u(t),
C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ E_0*exp(I*omega*t)/(-C*L*omega**2 + I*C*R*omega + 1))
assert dsolve(eqRLC_2) == sol_2
assert checkodesol(eqRLC_2, sol_2) == (True, 0)
#issue-https://github.com/sympy/sympy/issues/12623
def test_issue_5787():
# This test case is to show the classification of imaginary constants under
# nth_linear_constant_coeff_undetermined_coefficients
eq = Eq(diff(f(x), x), I*f(x) + S.Half - I)
our_hint = 'nth_linear_constant_coeff_undetermined_coefficients'
assert our_hint in classify_ode(eq)
def test_nth_linear_constant_coeff_undetermined_coefficients_imaginary_exp():
# Equivalent to eq26 in
# test_nth_linear_constant_coeff_undetermined_coefficients above. This
# previously failed because the algorithm for undetermined coefficients
# didn't know to multiply exp(I*x) by sufficient x because it is linearly
# dependent on sin(x) and cos(x).
hint = 'nth_linear_constant_coeff_undetermined_coefficients'
eq26a = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol26 = Eq(f(x), C1 + x**2*(I*exp(I*x)/8 + 1) + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))
assert dsolve(eq26a, hint=hint) == sol26
assert checkodesol(eq26a, sol26) == (True, 0)
@slow
def test_nth_linear_constant_coeff_variation_of_parameters():
hint = 'nth_linear_constant_coeff_variation_of_parameters'
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
eq1 = c - x*g
eq2 = c - g
eq3 = f(x).diff(x) - 1
eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 4
eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x)
eq6 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x)
eq7 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x)
eq8 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x)
eq9 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x)
eq10 = f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x
eq11 = f2 + f(x) - 1/sin(x)*1/cos(x)
eq12 = f(x).diff(x, 4) - 1/x
sol1 = Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)
sol2 = Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)
sol3 = Eq(f(x), C1 + x)
sol4 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x))
sol5 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x))
sol6 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))
sol7 = Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))
sol8 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)
sol9 = Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))
sol10 = Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x))
sol11 = Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2
)*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x))
sol12 = Eq(f(x), C1 + C2*x + x**3*(C3 + log(x)/6) + C4*x**2)
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
sol6s = constant_renumber(sol6)
sol7s = constant_renumber(sol7)
sol8s = constant_renumber(sol8)
sol9s = constant_renumber(sol9)
sol10s = constant_renumber(sol10)
sol11s = constant_renumber(sol11)
sol12s = constant_renumber(sol12)
got = dsolve(eq1, hint=hint)
assert got in (sol1, sol1s), got
got = dsolve(eq2, hint=hint)
assert got in (sol2, sol2s), got
assert dsolve(eq3, hint=hint) in (sol3, sol3s)
assert dsolve(eq4, hint=hint) in (sol4, sol4s)
assert dsolve(eq5, hint=hint) in (sol5, sol5s)
assert dsolve(eq6, hint=hint) in (sol6, sol6s)
got = dsolve(eq7, hint=hint)
assert got in (sol7, sol7s), got
assert dsolve(eq8, hint=hint) in (sol8, sol8s)
got = dsolve(eq9, hint=hint)
assert got in (sol9, sol9s), got
assert dsolve(eq10, hint=hint) in (sol10, sol10s)
assert dsolve(eq11, hint=hint + '_Integral').doit() in (sol11, sol11s)
assert dsolve(eq12, hint=hint) in (sol12, sol12s)
assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=3, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0]
@slow
def test_nth_linear_constant_coeff_variation_of_parameters_simplify_False():
# solve_variation_of_parameters shouldn't attempt to simplify the
# Wronskian if simplify=False. If wronskian() ever gets good enough
# to simplify the result itself, this test might fail.
our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral'
eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True)
sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False)
assert sol_simp != sol_nsimp
assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0)
assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0)
def test_unexpanded_Liouville_ODE():
# This is the same as eq1 from test_Liouville_ODE() above.
eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2
eq2 = eq1*exp(-f(x))/exp(f(x))
sol2 = Eq(f(x), C1 + log(x) - log(C2 + x))
sol2s = constant_renumber(sol2)
assert dsolve(eq2) in (sol2, sol2s)
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
def test_issue_4785():
from sympy.abc import A
eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2
assert classify_ode(eq, f(x)) == ('1st_linear', 'almost_linear',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral', 'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
# issue 4864
eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x)
assert classify_ode(eq, f(x)) == ('1st_exact',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group', '1st_exact_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
def test_issue_4825():
raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x)))
assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
# See also issue 3793, test Z13.
raises(ValueError, lambda: dsolve(f(x).diff(x), f(y)))
assert classify_ode(f(x).diff(x), f(y), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
def test_constant_renumber_order_issue_5308():
from sympy.utilities.iterables import variations
assert constant_renumber(C1*x + C2*y) == \
constant_renumber(C1*y + C2*x) == \
C1*x + C2*y
e = C1*(C2 + x)*(C3 + y)
for a, b, c in variations([C1, C2, C3], 3):
assert constant_renumber(a*(b + x)*(c + y)) == e
def test_constant_renumber():
e1, e2, x, y = symbols("e1:3 x y")
exprs = [e2*x, e1*x + e2*y]
assert constant_renumber(exprs[0]) == e2*x
assert constant_renumber(exprs[0], variables=[x]) == C1*x
assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x
assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x]
assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x]
def test_issue_5770():
k = Symbol("k", real=True)
t = Symbol('t')
w = Function('w')
sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t))
assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6
assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), set([C1, C2])) == \
C1*cos(x)*exp(x)
assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), set([C1, C2, C3])) == \
C1*cos(x) + C3*sin(x)
assert constantsimp(exp(C1 + x), set([C1])) == C1*exp(x)
assert constantsimp(x + C1 + y, set([C1, y])) == C1 + x
assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), set([C1])) == C1 + x
def test_issue_5112_5430():
assert homogeneous_order(-log(x) + acosh(x), x) is None
assert homogeneous_order(y - log(x), x, y) is None
def test_issue_5095():
f = Function('f')
raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf'))
def test_exact_enhancement():
f = Function('f')(x)
df = Derivative(f, x)
eq = f/x**2 + ((f*x - 1)/x)*df
sol = [Eq(f, (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
eq = (x*f - 1) + df*(x**2 - x*f)
sol = [Eq(f, x - sqrt(C1 + x**2 - 2*log(x))),
Eq(f, x + sqrt(C1 + x**2 - 2*log(x)))]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
eq = (x + 2)*sin(f) + df*x*cos(f)
sol = [Eq(f, -asin(C1*exp(-x)/x**2) + pi),
Eq(f, asin(C1*exp(-x)/x**2))]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
@slow
def test_separable_reduced():
f = Function('f')
x = Symbol('x')
df = f(x).diff(x)
eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
eq = x* df + f(x)* (1 / (x**2*f(x) - 1))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
sol = dsolve(eq, hint = 'separable_reduced', simplify=False)
assert sol.lhs == log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6
assert sol.rhs == C1 + log(x)
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = f(x).diff(x) + (f(x) / (x**4*f(x) - x))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
sol = dsolve(eq, hint = 'separable_reduced')
# FIXME: This one hangs
#assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0)] * 4
assert len(sol) == 4
eq = x*df + f(x)*(x**2*f(x))
sol = dsolve(eq, hint = 'separable_reduced', simplify=False)
assert sol == Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x))
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = Eq(f(x).diff(x) + f(x)/x * (1 + (x**(S(2)/3)*f(x))**2), 0)
sol = dsolve(eq, hint = 'separable_reduced', simplify=False)
assert sol == Eq(-3*log(x**(S(2)/3)*f(x)) + 3*log(3*x**(S(4)/3)*f(x)**2 + 1)/2, C1 + log(x))
assert checkodesol(eq, sol, solve_for_func=False) == (True, 0)
eq = Eq(f(x).diff(x) + f(x)/x * (1 + (x*f(x))**2), 0)
sol = dsolve(eq, hint = 'separable_reduced')
assert sol == [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x)),\
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x))]
assert checkodesol(eq, sol) == [(True, 0)]*2
eq = Eq(f(x).diff(x) + (x**4*f(x)**2 + x**2*f(x))*f(x)/(x*(x**6*f(x)**3 + x**4*f(x)**2)), 0)
sol = dsolve(eq, hint = 'separable_reduced')
assert sol == Eq(f(x), C1 + 1/(2*x**2))
assert checkodesol(eq, sol) == (True, 0)
eq = Eq(f(x).diff(x) + (f(x)**2)*f(x)/(x), 0)
sol = dsolve(eq, hint = 'separable_reduced')
assert sol == [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/2),\
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/2)]
assert checkodesol(eq, sol) == [(True, 0), (True, 0)]
eq = Eq(f(x).diff(x) + (f(x)+3)*f(x)/(x*(f(x)+2)), 0)
sol = dsolve(eq, hint = 'separable_reduced', simplify=False)
assert sol == Eq(-log(f(x) + 3)/3 - 2*log(f(x))/3, C1 + log(x))
assert checkodesol(eq, sol, solve_for_func=False) == (True, 0)
eq = Eq(f(x).diff(x) + (f(x)+3)*f(x)/x, 0)
sol = dsolve(eq, hint = 'separable_reduced')
assert sol == Eq(f(x), 3/(C1*x**3 - 1))
assert checkodesol(eq, sol) == (True, 0)
eq = Eq(f(x).diff(x) + (f(x)**2+f(x))*f(x)/(x), 0)
sol = dsolve(eq, hint='separable_reduced', simplify=False)
assert sol == Eq(-log(f(x) + 1) + log(f(x)) + 1/f(x), C1 + log(x))
assert checkodesol(eq, sol, solve_for_func=False) == (True, 0)
def test_homogeneous_function():
f = Function('f')
eq1 = tan(x + f(x))
eq2 = sin((3*x)/(4*f(x)))
eq3 = cos(x*f(x)*Rational(3, 4))
eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x))
eq5 = exp((2*x**2)/(3*f(x)**2))
eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2)))
eq7 = sin((3*x)/(5*f(x) + x**2))
assert homogeneous_order(eq1, x, f(x)) == None
assert homogeneous_order(eq2, x, f(x)) == 0
assert homogeneous_order(eq3, x, f(x)) == None
assert homogeneous_order(eq4, x, f(x)) == 0
assert homogeneous_order(eq5, x, f(x)) == 0
assert homogeneous_order(eq6, x, f(x)) == 0
assert homogeneous_order(eq7, x, f(x)) == None
def test_linear_coeff_match():
n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11)
rat = n/d
eq1 = sin(rat) + cos(rat.expand())
eq2 = rat
eq3 = log(sin(rat))
ans = (4, Rational(-13, 3))
assert _linear_coeff_match(eq1, f(x)) == ans
assert _linear_coeff_match(eq2, f(x)) == ans
assert _linear_coeff_match(eq3, f(x)) == ans
# no c
eq4 = (3*x)/f(x)
# not x and f(x)
eq5 = (3*x + 2)/x
# denom will be zero
eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5)
# not rational coefficient
eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5)
assert _linear_coeff_match(eq4, f(x)) is None
assert _linear_coeff_match(eq5, f(x)) is None
assert _linear_coeff_match(eq6, f(x)) is None
assert _linear_coeff_match(eq7, f(x)) is None
def test_linear_coefficients():
f = Function('f')
sol = Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2))
eq = f(x).diff(x) + (3 + 2*f(x))/(x + 3)
assert dsolve(eq, hint='linear_coefficients') == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_constantsimp_take_problem():
c = exp(C1) + 2
assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2
def test_issue_6879():
f = Function('f')
eq = Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x))
sol = (C1 + C2*x)*exp(x) + cos(x)/2
assert dsolve(eq).rhs == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_issue_6989():
f = Function('f')
k = Symbol('k')
eq = f(x).diff(x) - x*exp(-k*x)
csol = Eq(f(x), C1 + Piecewise(
((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),
(x**2/2, True)
))
sol = dsolve(eq, f(x))
assert sol == csol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = -f(x).diff(x) + x*exp(-k*x)
csol = Eq(f(x), C1 + Piecewise(
((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),
(x**2/2, True)
))
sol = dsolve(eq, f(x))
assert sol == csol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_heuristic1():
y, a, b, c, a4, a3, a2, a1, a0 = symbols("y a b c a4 a3 a2 a1 a0")
f = Function('f')
xi = Function('xi')
eta = Function('eta')
df = f(x).diff(x)
eq = Eq(df, x**2*f(x))
eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x)
eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2)
eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x))
eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**Rational(-1, 2)
eq5 = x**2*df - f(x) + x**2*exp(x - (1/x))
eqlist = [eq, eq1, eq2, eq3, eq4, eq5]
i = infinitesimals(eq, hint='abaco1_simple')
assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0},
{eta(x, f(x)): f(x), xi(x, f(x)): 0},
{eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}]
i1 = infinitesimals(eq1, hint='abaco1_simple')
assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}]
i2 = infinitesimals(eq2, hint='abaco1_simple')
assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}]
i3 = infinitesimals(eq3, hint='abaco1_simple')
assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1},
{eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}]
i4 = infinitesimals(eq4, hint='abaco1_simple')
assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0},
{eta(x, f(x)): 0,
xi(x, f(x)): sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4)}]
i5 = infinitesimals(eq5, hint='abaco1_simple')
assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}]
ilist = [i, i1, i2, i3, i4, i5]
for eq, i in (zip(eqlist, ilist)):
check = checkinfsol(eq, i)
assert check[0]
def test_issue_6247():
eq = x**2*f(x)**2 + x*Derivative(f(x), x)
sol = Eq(f(x), 2*C1/(C1*x**2 - 1))
assert dsolve(eq, hint = 'separable_reduced') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x, x) + 4*f(x)
sol = Eq(f(x), C1*sin(2*x) + C2*cos(2*x))
assert dsolve(eq) == sol
assert checkodesol(eq, sol, order=1)[0]
def test_heuristic2():
xi = Function('xi')
eta = Function('eta')
df = f(x).diff(x)
# This ODE can be solved by the Lie Group method, when there are
# better assumptions
eq = df - (f(x)/x)*(x*log(x**2/f(x)) + 2)
i = infinitesimals(eq, hint='abaco1_product')
assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}]
assert checkinfsol(eq, i)[0]
@slow
def test_heuristic3():
xi = Function('xi')
eta = Function('eta')
a, b = symbols("a b")
df = f(x).diff(x)
eq = x**2*df + x*f(x) + f(x)**2 + x**2
i = infinitesimals(eq, hint='bivariate')
assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}]
assert checkinfsol(eq, i)[0]
eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x
i = infinitesimals(eq, hint='bivariate')
assert checkinfsol(eq, i)[0]
def test_heuristic_4():
y, a = symbols("y a")
eq = x*(f(x).diff(x)) + 1 - f(x)**2
i = infinitesimals(eq, hint='chi')
assert checkinfsol(eq, i)[0]
def test_heuristic_function_sum():
xi = Function('xi')
eta = Function('eta')
eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x +
(1 - 3*f(x))*(x/f(x)**2))
i = infinitesimals(eq, hint='function_sum')
assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}]
assert checkinfsol(eq, i)[0]
def test_heuristic_abaco2_similar():
xi = Function('xi')
eta = Function('eta')
F = Function('F')
a, b = symbols("a b")
eq = f(x).diff(x) - F(a*x + b*f(x))
i = infinitesimals(eq, hint='abaco2_similar')
assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}]
assert checkinfsol(eq, i)[0]
eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x)))
i = infinitesimals(eq, hint='abaco2_similar')
assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}]
assert checkinfsol(eq, i)[0]
def test_heuristic_abaco2_unique_unknown():
xi = Function('xi')
eta = Function('eta')
F = Function('F')
a, b = symbols("a b")
x = Symbol("x", positive=True)
eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b)
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}]
assert checkinfsol(eq, i)[0]
eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x)))
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}]
assert checkinfsol(eq, i)[0]
eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert checkinfsol(eq, i)[0]
def test_heuristic_linear():
a, b, m, n = symbols("a b m n")
eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1))
i = infinitesimals(eq, hint='linear')
assert checkinfsol(eq, i)[0]
@XFAIL
def test_kamke():
a, b, alpha, c = symbols("a b alpha c")
eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c
i = infinitesimals(eq, hint='sum_function') # XFAIL
assert checkinfsol(eq, i)[0]
def test_series():
C1 = Symbol("C1")
eq = f(x).diff(x) - f(x)
sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 +
C1*x**5/120 + O(x**6))
assert dsolve(eq, hint='1st_power_series') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - x*f(x)
sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6))
assert dsolve(eq, hint='1st_power_series') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - sin(x*f(x))
sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3))
assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol
# FIXME: The solution here should be O((x-2)**3) so is incorrect
#assert checkodesol(eq, sol, order=1)[0]
@XFAIL
@SKIP
def test_lie_group_issue17322_1():
eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x
sol = dsolve(eq, f(x)) # Hangs
assert checkodesol(eq, sol) == (True, 0)
@XFAIL
@SKIP
def test_lie_group_issue17322_2():
eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x
sol = dsolve(eq) # Hangs
assert checkodesol(eq, sol) == (True, 0)
@XFAIL
@SKIP
def test_lie_group_issue17322_3():
eq=Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0)
sol = dsolve(eq) # Hangs
assert checkodesol(eq, sol) == (True, 0)
@XFAIL
def test_lie_group_issue17322_4():
eq=f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x)
sol = dsolve(eq) # NotImplementedError
assert checkodesol(eq, sol) == (True, 0)
@slow
def test_lie_group():
C1 = Symbol("C1")
x = Symbol("x") # assuming x is real generates an error!
a, b, c = symbols("a b c")
eq = f(x).diff(x)**2
sol = dsolve(eq, f(x), hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = Eq(f(x).diff(x), x**2*f(x))
sol = dsolve(eq, f(x), hint='lie_group')
assert sol == Eq(f(x), C1*exp(x**3)**Rational(1, 3))
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) + a*f(x) - c*exp(b*x)
sol = dsolve(eq, f(x), hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2)
sol = dsolve(eq, f(x), hint='lie_group')
actual_sol = Eq(f(x), (C1 + x**2/2)*exp(-x**2))
errstr = str(eq)+' : '+str(sol)+' == '+str(actual_sol)
assert sol == actual_sol, errstr
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x))
sol = dsolve(eq, f(x), hint='lie_group')
assert sol == Eq(f(x), log(C1/(2*x + 1) + 2))
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x))
sol = dsolve(eq, f(x), hint='lie_group')
assert checkodesol(eq, sol)[0]
eq = x**2*f(x)**2 + x*Derivative(f(x), x)
sol = dsolve(eq, f(x), hint='lie_group')
assert sol == Eq(f(x), 2/(C1 + x**2))
assert checkodesol(eq, sol) == (True, 0)
eq=diff(f(x),x) + 2*x*f(x) - x*exp(-x**2)
sol = Eq(f(x), exp(-x**2)*(C1 + x**2/2))
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x),x) + f(x)*cos(x) - exp(2*x)
sol = Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x)))
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2
sol = Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1)
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = x*diff(f(x),x) + f(x) - x*sin(x)
sol = Eq(f(x), (C1 - x*cos(x) + sin(x))/x)
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = x*diff(f(x),x) - f(x) - x/log(x)
sol = Eq(f(x), x*(C1 + log(log(x))))
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x))
sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol[0]) == (True, 0)
assert checkodesol(eq, sol[1]) == (True, 0)
eq = f(x).diff(x) * (f(x).diff(x) - f(x))
sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1)]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol[0]) == (True, 0)
assert checkodesol(eq, sol[1]) == (True, 0)
@XFAIL
def test_lie_group_issue15219():
eqn = exp(f(x).diff(x)-f(x))
assert 'lie_group' not in classify_ode(eqn, f(x))
def test_user_infinitesimals():
x = Symbol("x") # assuming x is real generates an error
eq = x*(f(x).diff(x)) + 1 - f(x)**2
sol = Eq(f(x), (C1 + x**2)/(C1 - x**2))
infinitesimals = {'xi':sqrt(f(x) - 1)/sqrt(f(x) + 1), 'eta':0}
assert dsolve(eq, hint='lie_group', **infinitesimals) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_7081():
eq = x*(f(x).diff(x)) + 1 - f(x)**2
s = Eq(f(x), -1/(-C1 + x**2)*(C1 + x**2))
assert dsolve(eq) == s
assert checkodesol(eq, s) == (True, 0)
@slow
def test_2nd_power_series_ordinary():
C1, C2 = symbols("C1 C2")
eq = f(x).diff(x, 2) - x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary') == sol
assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1)
+ C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2))
+ O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol
# FIXME: Solution should be O((x+2)**6)
# assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2*x + C1 + O(x**2))
assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6))
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1)
+ C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6))
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7))
assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_Airy_equation():
eq = f(x).diff(x, 2) - x*f(x)
sol = Eq(f(x), C1*airyai(x) + C2*airybi(x))
sols = constant_renumber(sol)
assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary')
assert checkodesol(eq, sol) == (True, 0)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols)
eq = f(x).diff(x, 2) + 2*x*f(x)
sol = Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x))
sols = constant_renumber(sol)
assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary')
assert checkodesol(eq, sol) == (True, 0)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols)
def test_2nd_power_series_regular():
C1, C2 = symbols("C1 C2")
eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x)
sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 +
1)*f(x)
sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + (
x**2 - 2)*f(x)
sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x +
C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x)
sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) +
C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
def test_2nd_linear_bessel_equation():
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x)
sol = Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x)
sol = Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x)
sol = Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x)
sol = Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x)
sol = Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x)
sol = Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x)
sol = Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x)
sol = Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x))))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x)
sol = Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2)))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x)
sol = Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4)))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
def test_issue_7093():
x = Symbol("x") # assuming x is real leads to an error
sol = [Eq(f(x), C1 - 2*x*sqrt(x**3)/5),
Eq(f(x), C1 + 2*x*sqrt(x**3)/5)]
eq = Derivative(f(x), x)**2 - x**3
assert set(dsolve(eq)) == set(sol)
assert checkodesol(eq, sol) == [(True, 0)] * 2
def test_dsolve_linsystem_symbol():
eps = Symbol('epsilon', positive=True)
eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x)))
sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)),
Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))]
assert checksysodesol(eq1, sol1) == (True, [0, 0])
def test_C1_function_9239():
t = Symbol('t')
C1 = Function('C1')
C2 = Function('C2')
C3 = Symbol('C3')
C4 = Symbol('C4')
eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t)))
sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)),
Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))]
assert checksysodesol(eq, sol) == (True, [0, 0])
def test_issue_15056():
t = Symbol('t')
C3 = Symbol('C3')
assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3
def test_issue_10379():
t,y = symbols('t,y')
eq = f(t).diff(t)-(1-51.05*y*f(t))
sol = Eq(f(t), (0.019588638589618*exp(y*(C1 - 51.05*t)) + 0.019588638589618)/y)
dsolve_sol = dsolve(eq, rational=False)
assert str(dsolve_sol) == str(sol)
assert checkodesol(eq, dsolve_sol)[0]
def test_issue_10867():
x = Symbol('x')
eq = Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3)
sol = Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2)
assert dsolve(eq, g(x)) == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
def test_issue_11290():
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral')
sol_0 = dsolve(eq, f(x), simplify=False, hint='1st_exact')
assert sol_1.dummy_eq(Eq(Subs(
Integral(u**2 - x*sin(u) - Integral(-sin(u), x), u) +
Integral(cos(u), x), u, f(x)), C1))
assert sol_1.doit() == sol_0
assert checkodesol(eq, sol_0, order=1, solve_for_func=False)
assert checkodesol(eq, sol_1, order=1, solve_for_func=False)
def test_issue_4838():
# Issue #15999
eq = f(x).diff(x) - C1*f(x)
sol = Eq(f(x), C2*exp(C1*x))
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0)
# Issue #13691
eq = f(x).diff(x) - C1*g(x).diff(x)
sol = Eq(f(x), C2 + C1*g(x))
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, f(x), order=1, solve_for_func=False) == (True, 0)
# Issue #4838
eq = f(x).diff(x) - 3*C1 - 3*x**2
sol = Eq(f(x), C2 + 3*C1*x + x**3)
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0)
@slow
def test_issue_14395():
eq = Derivative(f(x), x, x) + 9*f(x) - sec(x)
sol = Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x))
- 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x))
assert dsolve(eq, f(x)) == sol
# FIXME: assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
# Needs to be a way to know how to combine derivatives in the expression
def test_factoring_ode():
from sympy import Mul
eqn = Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x)
# 2-arg Mul!
soln = Eq(f(x), C1 + C2*x + C3/Mul(2, (x + 1), evaluate=False))
assert checkodesol(eqn, soln, order=2, solve_for_func=False)[0]
assert soln == dsolve(eqn, f(x))
def test_issue_11542():
m = 96
g = 9.8
k = .2
f1 = g * m
t = Symbol('t')
v = Function('v')
v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0)
assert str(v_equation) == \
'Eq(v(t), -68.585712797929/tanh(C1 - 0.142886901662352*t))'
def test_issue_15913():
eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x)
sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x)
assert checkodesol(eq, sol) == (True, 0)
sol = C1 + C2*exp(-x*y)
eq = Derivative(y*f(x), x) + f(x).diff(x, 2)
assert checkodesol(eq, sol, f(x)) == (True, 0)
def test_issue_16146():
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)]))
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)]))
def test_dsolve_remove_redundant_solutions():
eq = (f(x)-2)*f(x).diff(x)
sol = Eq(f(x), C1)
assert dsolve(eq) == sol
eq = (f(x)-sin(x))*(f(x).diff(x, 2))
sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))}
assert set(dsolve(eq)) == sol
eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3)
sol = Eq(f(x), C1 + C2*x + C3*x**2)
assert dsolve(eq) == sol
def test_issue_17322():
eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x))
sol = [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
eq = f(x).diff(x)*(f(x).diff(x)+f(x))
sol = [Eq(f(x), C1), Eq(f(x), C1*exp(-x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
def test_2nd_2F1_hypergeometric():
eq = x*(x-1)*f(x).diff(x, 2) + (S(3)/2 -2*x)*f(x).diff(x) + 2*f(x)
sol = Eq(f(x), C1*x**(S(5)/2)*hyper((S(3)/2, S(1)/2), (S(7)/2,), x) + C2*hyper((-1, -2), (-S(3)/2,), x))
assert sol == dsolve(eq, hint='2nd_hypergeometric')
assert checkodesol(eq, sol) == (True, 0)
eq = x*(x-1)*f(x).diff(x, 2) + (S(7)/2*x)*f(x).diff(x) + f(x)
sol = Eq(f(x), (C1*(1 - x)**(S(5)/2)*hyper((S(1)/2, 2), (S(7)/2,), 1 - x) +
C2*hyper((-S(1)/2, -2), (-S(3)/2,), 1 - x))/(x - 1)**(S(5)/2))
assert sol == dsolve(eq, hint='2nd_hypergeometric')
assert checkodesol(eq, sol) == (True, 0)
eq = x*(x-1)*f(x).diff(x, 2) + (S(3)+ S(7)/2*x)*f(x).diff(x) + f(x)
sol = Eq(f(x), (C1*(1 - x)**(S(11)/2)*hyper((S(1)/2, 2), (S(13)/2,), 1 - x) +
C2*hyper((-S(7)/2, -5), (-S(9)/2,), 1 - x))/(x - 1)**(S(11)/2))
assert sol == dsolve(eq, hint='2nd_hypergeometric')
assert checkodesol(eq, sol) == (True, 0)
eq = x*(x-1)*f(x).diff(x, 2) + (-1+ S(7)/2*x)*f(x).diff(x) + f(x)
sol = Eq(f(x), (C1 + C2*Integral(exp(Integral((1 - x/2)/(x*(x - 1)), x))/(1 -
x/2)**2, x))*exp(Integral(1/(x - 1), x)/4)*exp(-Integral(7/(x -
1), x)/4)*hyper((S(1)/2, -1), (1,), x))
assert sol == dsolve(eq, hint='2nd_hypergeometric_Integral')
assert checkodesol(eq, sol) == (True, 0)
eq = -x**(S(5)/7)*(-416*x**(S(9)/7)/9 - 2385*x**(S(5)/7)/49 + S(298)*x/3)*f(x)/(196*(-x**(S(6)/7) +
x)**2*(x**(S(6)/7) + x)**2) + Derivative(f(x), (x, 2))
sol = Eq(f(x), x**(S(45)/98)*(C1*x**(S(4)/49)*hyper((S(1)/3, -S(1)/2), (S(9)/7,), x**(S(2)/7)) +
C2*hyper((S(1)/21, -S(11)/14), (S(5)/7,), x**(S(2)/7)))/(x**(S(2)/7) - 1)**(S(19)/84))
assert sol == dsolve(eq, hint='2nd_hypergeometric')
# assert checkodesol(eq, sol) == (True, 0) #issue-https://github.com/sympy/sympy/issues/17702
def test_issue_5096():
eq = f(x).diff(x, x) + f(x) - x*sin(x - 2)
sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x**2*cos(x - 2)/4 + x*sin(x - 2)/4)
assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + f(x) - x**4*sin(x-1)
sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x**5*cos(x - 1)/10 + x**4*sin(x - 1)/4 + x**3*cos(x - 1)/2 - 3*x**2*sin(x - 1)/4 - 3*x*cos(x - 1)/4)
assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) - f(x) - exp(x - 1)
sol = Eq(f(x), C2*exp(-x) + (C1 + x*exp(-1)/2)*exp(x))
got = dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert sol == got, got
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2)+f(x)-(sin(x-2)+1)
sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x*cos(x - 2)/2 + 1)
assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
eq = 2*x**2*f(x).diff(x, 2) + f(x) + sqrt(2*x)*sin(log(2*x)/2)
sol = Eq(f(x), sqrt(x)*(C1*sin(log(x)/2) + C2*cos(log(x)/2) + sqrt(2)*log(x)*cos(log(2*x)/2)/2))
assert sol == dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
eq = 2*x**2*f(x).diff(x, 2) + f(x) + sin(log(2*x)/2)
sol = Eq(f(x), C1*sqrt(x)*sin(log(x)/2) + C2*sqrt(x)*cos(log(x)/2) - 2*sin(log(2*x)/2)/5 - 4*cos(log(2*x)/2)/5)
assert sol == dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
def test_issue_15996():
eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol = Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8 + 3*exp(I*x)/2 + 3*exp(-I*x)/2) + 5*exp(2*I*x)/16 + 2*I*exp(I*x) - 2*I*exp(-I*x))*sin(x) + (C4 + x*(C5 + I*x/8 + 3*I*exp(I*x)/2 - 3*I*exp(-I*x)/2) + 5*I*exp(2*I*x)/16 - 2*exp(I*x) - 2*exp(-I*x))*cos(x) - I*exp(I*x))
got = dsolve(eq, hint='nth_linear_constant_coeff_variation_of_parameters')
assert sol == got, got
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - exp(I*x)
sol = Eq(f(x), C1 + (C2 + x*(C3 - x/8) + 5*exp(2*I*x)/16)*sin(x) + (C4 + x*(C5 + I*x/8) + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x))
got = dsolve(eq, hint='nth_linear_constant_coeff_variation_of_parameters')
assert sol == got, got
assert checkodesol(eq, sol) == (True, 0)
def test_issue_18408():
eq = f(x).diff(x, 3) - f(x).diff(x) - sinh(x)
sol = Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + x*sinh(x)/2)
assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) - 49*f(x) - sinh(3*x)
sol = Eq(f(x), C1*exp(-7*x) + C2*exp(7*x) - sinh(3*x)/40)
assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 3) - f(x).diff(x) - sinh(x) - exp(x)
sol = Eq(f(x), C1 + C3*exp(-x) + x*sinh(x)/2 + (C2 + x/2)*exp(x))
assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients')
assert checkodesol(eq, sol) == (True, 0)
def test_issue_9446():
f = Function('f')
assert dsolve(Eq(f(2 * x), sin(Derivative(f(x)))), f(x)) == \
[Eq(f(x), C1 + pi*x - Integral(asin(f(2*x)), x)), Eq(f(x), C1 + Integral(asin(f(2*x)), x))]
assert integrate(-asin(f(2*x)+pi), x) == -Integral(asin(pi + f(2*x)), x)
|
195468ab74632d66d10072548e487eb86330577e73d30cef96a01aa675f5fd1b | from sympy import (symbols, Symbol, diff, Function, Derivative, Matrix, Rational, S,
I, Eq, sqrt)
from sympy.core.containers import Tuple
from sympy.functions import exp, cos, sin, log
from sympy.matrices import dotprodsimp, NonSquareMatrixError
from sympy.solvers.ode import dsolve
from sympy.solvers.ode.ode import constant_renumber
from sympy.solvers.ode.subscheck import checksysodesol
from sympy.solvers.ode.systems import (neq_nth_linear_constant_coeff_match, linear_ode_to_matrix,
ODEOrderError, ODENonlinearError, _simpsol, _solsimp,
_is_commutative_anti_derivative, linodesolve,
canonical_odes, dsolve_system, _component_division,
_eqs2dict, _dict2graph)
from sympy.integrals.integrals import Integral
from sympy.testing.pytest import ON_TRAVIS, raises, slow, skip, XFAIL
C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11')
def test_linear_ode_to_matrix():
f, g, h = symbols("f, g, h", cls=Function)
t = Symbol("t")
funcs = [f(t), g(t), h(t)]
f1 = f(t).diff(t)
g1 = g(t).diff(t)
h1 = h(t).diff(t)
f2 = f(t).diff(t, 2)
g2 = g(t).diff(t, 2)
h2 = h(t).diff(t, 2)
eqs_1 = [Eq(f1, g(t)), Eq(g1, f(t))]
sol_1 = ([Matrix([[1, 0], [0, 1]]), Matrix([[ 0, 1], [1, 0]])], Matrix([[0],[0]]))
assert linear_ode_to_matrix(eqs_1, funcs[:-1], t, 1) == sol_1
eqs_2 = [Eq(f1, f(t) + 2*g(t)), Eq(g1, h(t)), Eq(h1, g(t) + h(t) + f(t))]
sol_2 = ([Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), Matrix([[1, 2, 0], [ 0, 0, 1], [1, 1, 1]])],
Matrix([[0], [0], [0]]))
assert linear_ode_to_matrix(eqs_2, funcs, t, 1) == sol_2
eqs_3 = [Eq(2*f1 + 3*h1, f(t) + g(t)), Eq(4*h1 + 5*g1, f(t) + h(t)), Eq(5*f1 + 4*g1, g(t) + h(t))]
sol_3 = ([Matrix([[2, 0, 3], [0, 5, 4], [5, 4, 0]]), Matrix([[1, 1, 0], [1, 0, 1], [0, 1, 1]])],
Matrix([[0], [0], [0]]))
assert linear_ode_to_matrix(eqs_3, funcs, t, 1) == sol_3
eqs_4 = [Eq(f2 + h(t), f1 + g(t)), Eq(2*h2 + g2 + g1 + g(t), 0), Eq(3*h1, 4)]
sol_4 = ([Matrix([[1, 0, 0], [0, 1, 2], [0, 0, 0]]), Matrix([[1, 0, 0], [0, -1, 0], [0, 0, -3]]),
Matrix([[0, 1, -1], [0, -1, 0], [0, 0, 0]])], Matrix([[0], [0], [4]]))
assert linear_ode_to_matrix(eqs_4, funcs, t, 2) == sol_4
eqs_5 = [Eq(f2, g(t)), Eq(f1 + g1, f(t))]
raises(ODEOrderError, lambda: linear_ode_to_matrix(eqs_5, funcs[:-1], t, 1))
eqs_6 = [Eq(f1, f(t)**2), Eq(g1, f(t) + g(t))]
raises(ODENonlinearError, lambda: linear_ode_to_matrix(eqs_6, funcs[:-1], t, 1))
def test_neq_nth_linear_constant_coeff_match():
x, y, z, w = symbols('x, y, z, w', cls=Function)
t = Symbol('t')
x1 = diff(x(t), t)
y1 = diff(y(t), t)
z1 = diff(z(t), t)
w1 = diff(w(t), t)
x2 = diff(x(t), t, t)
funcs = [x(t), y(t)]
funcs_2 = funcs + [z(t), w(t)]
eqs_1 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * t * x(t) + 3 * y(t) + t))
assert neq_nth_linear_constant_coeff_match(eqs_1, funcs, t) is None
eqs_2 = (5 * (x1**2) + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * t * x(t) + 3 * y(t) + t))
sol2 = {'is_implicit': True,
'canon_eqs': [[Eq(Derivative(x(t), t), -sqrt(-12*x(t)/5 + 6*y(t)/5)),
Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)],
[Eq(Derivative(x(t), t), sqrt(-12*x(t)/5 + 6*y(t)/5)),
Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)]]}
assert neq_nth_linear_constant_coeff_match(eqs_2, funcs, t) == sol2
eqs_2_1 = [Eq(Derivative(x(t), t), -sqrt(-12*x(t)/5 + 6*y(t)/5)),
Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)]
assert neq_nth_linear_constant_coeff_match(eqs_2_1, funcs, t) is None
eqs_2_2 = [Eq(Derivative(x(t), t), sqrt(-12*x(t)/5 + 6*y(t)/5)),
Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)]
assert neq_nth_linear_constant_coeff_match(eqs_2_2, funcs, t) is None
eqs_3 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * x(t) + 3 * y(t)), (5 * w1 + z(t)), (z1 + w(t)))
answer_3 = {'no_of_equation': 4,
'eq': (12*x(t) - 6*y(t) + 5*Derivative(x(t), t),
-11*x(t) + 3*y(t) + 2*Derivative(y(t), t),
z(t) + 5*Derivative(w(t), t),
w(t) + Derivative(z(t), t)),
'func': [x(t), y(t), z(t), w(t)],
'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1},
'is_linear': True,
'is_constant': True,
'is_homogeneous': True,
'func_coeff': -Matrix([
[Rational(12, 5), Rational(-6, 5), 0, 0],
[Rational(-11, 2), Rational(3, 2), 0, 0],
[0, 0, 0, 1],
[0, 0, Rational(1, 5), 0]]),
'type_of_equation': 'type1',
'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_3, funcs_2, t) == answer_3
eqs_4 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * x(t) + 3 * y(t)), (z1 - w(t)), (w1 - z(t)))
answer_4 = {'no_of_equation': 4,
'eq': (12 * x(t) - 6 * y(t) + 5 * Derivative(x(t), t),
-11 * x(t) + 3 * y(t) + 2 * Derivative(y(t), t),
-w(t) + Derivative(z(t), t),
-z(t) + Derivative(w(t), t)),
'func': [x(t), y(t), z(t), w(t)],
'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1},
'is_linear': True,
'is_constant': True,
'is_homogeneous': True,
'func_coeff': -Matrix([
[Rational(12, 5), Rational(-6, 5), 0, 0],
[Rational(-11, 2), Rational(3, 2), 0, 0],
[0, 0, 0, -1],
[0, 0, -1, 0]]),
'type_of_equation': 'type1',
'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_4, funcs_2, t) == answer_4
eqs_5 = (5*x1 + 12*x(t) - 6*(y(t)) + x2, (2*y1 - 11*x(t) + 3*y(t)), (z1 - w(t)), (w1 - z(t)))
assert neq_nth_linear_constant_coeff_match(eqs_5, funcs_2, t) is None
eqs_6 = (Eq(x1, 3*y(t) - 11*z(t)), Eq(y1, 7*z(t) - 3*x(t)), Eq(z1, 11*x(t) - 7*y(t)))
answer_6 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)),
Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1},
'is_linear': True, 'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[ 0, -3, 11],
[ 3, 0, -7],
[-11, 7, 0]]),
'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_6, funcs_2[:-1], t) == answer_6
eqs_7 = (Eq(x1, y(t)), Eq(y1, x(t)))
answer_7 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))),
'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True,
'is_homogeneous': True, 'func_coeff': -Matrix([
[ 0, -1],
[-1, 0]]),
'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_7, funcs, t) == answer_7
eqs_8 = (Eq(x1, 21*x(t)), Eq(y1, 17*x(t) + 3*y(t)), Eq(z1, 5*x(t) + 7*y(t) + 9*z(t)))
answer_8 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 21*x(t)), Eq(Derivative(y(t), t), 17*x(t) + 3*y(t)),
Eq(Derivative(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1},
'is_linear': True, 'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[-21, 0, 0],
[-17, -3, 0],
[ -5, -7, -9]]),
'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_8, funcs_2[:-1], t) == answer_8
eqs_9 = (Eq(x1, 4*x(t) + 5*y(t) + 2*z(t)), Eq(y1, x(t) + 13*y(t) + 9*z(t)), Eq(z1, 32*x(t) + 41*y(t) + 11*z(t)))
answer_9 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 4*x(t) + 5*y(t) + 2*z(t)),
Eq(Derivative(y(t), t), x(t) + 13*y(t) + 9*z(t)), Eq(Derivative(z(t), t), 32*x(t) + 41*y(t) + 11*z(t))),
'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True,
'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[ -4, -5, -2],
[ -1, -13, -9],
[-32, -41, -11]]),
'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_9, funcs_2[:-1], t) == answer_9
eqs_10 = (Eq(3*x1, 4*5*(y(t) - z(t))), Eq(4*y1, 3*5*(z(t) - x(t))), Eq(5*z1, 3*4*(x(t) - y(t))))
answer_10 = {'no_of_equation': 3, 'eq': (Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)),
Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))),
'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True,
'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[ 0, Rational(-20, 3), Rational(20, 3)],
[Rational(15, 4), 0, Rational(-15, 4)],
[Rational(-12, 5), Rational(12, 5), 0]]),
'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eqs_10, funcs_2[:-1], t) == answer_10
eq11 = (Eq(x1, 3*y(t) - 11*z(t)), Eq(y1, 7*z(t) - 3*x(t)), Eq(z1, 11*x(t) - 7*y(t)))
sol11 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)),
Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1},
'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([
[ 0, -3, 11], [ 3, 0, -7], [-11, 7, 0]]), 'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eq11, funcs_2[:-1], t) == sol11
eq12 = (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t)))
sol12 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))),
'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True,
'is_homogeneous': True, 'func_coeff': -Matrix([
[0, -1],
[-1, 0]]), 'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eq12, [x(t), y(t)], t) == sol12
eq13 = (Eq(Derivative(x(t), t), 21*x(t)), Eq(Derivative(y(t), t), 17*x(t) + 3*y(t)),
Eq(Derivative(z(t), t), 5*x(t) + 7*y(t) + 9*z(t)))
sol13 = {'no_of_equation': 3, 'eq': (
Eq(Derivative(x(t), t), 21 * x(t)), Eq(Derivative(y(t), t), 17 * x(t) + 3 * y(t)),
Eq(Derivative(z(t), t), 5 * x(t) + 7 * y(t) + 9 * z(t))), 'func': [x(t), y(t), z(t)],
'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[-21, 0, 0],
[-17, -3, 0],
[-5, -7, -9]]), 'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eq13, [x(t), y(t), z(t)], t) == sol13
eq14 = (
Eq(Derivative(x(t), t), 4*x(t) + 5*y(t) + 2*z(t)), Eq(Derivative(y(t), t), x(t) + 13*y(t) + 9*z(t)),
Eq(Derivative(z(t), t), 32*x(t) + 41*y(t) + 11*z(t)))
sol14 = {'no_of_equation': 3, 'eq': (
Eq(Derivative(x(t), t), 4 * x(t) + 5 * y(t) + 2 * z(t)), Eq(Derivative(y(t), t), x(t) + 13 * y(t) + 9 * z(t)),
Eq(Derivative(z(t), t), 32 * x(t) + 41 * y(t) + 11 * z(t))), 'func': [x(t), y(t), z(t)],
'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[-4, -5, -2],
[-1, -13, -9],
[-32, -41, -11]]), 'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eq14, [x(t), y(t), z(t)], t) == sol14
eq15 = (Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)),
Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t)))
sol15 = {'no_of_equation': 3, 'eq': (
Eq(3 * Derivative(x(t), t), 20 * y(t) - 20 * z(t)), Eq(4 * Derivative(y(t), t), -15 * x(t) + 15 * z(t)),
Eq(5 * Derivative(z(t), t), 12 * x(t) - 12 * y(t))), 'func': [x(t), y(t), z(t)],
'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True,
'func_coeff': -Matrix([
[0, Rational(-20, 3), Rational(20, 3)],
[Rational(15, 4), 0, Rational(-15, 4)],
[Rational(-12, 5), Rational(12, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eq15, [x(t), y(t), z(t)], t) == sol15
# Constant coefficient homogeneous ODEs
eq1 = (Eq(diff(x(t), t), x(t) + y(t) + 9), Eq(diff(y(t), t), 2*x(t) + 5*y(t) + 23))
sol1 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), x(t) + y(t) + 9),
Eq(Derivative(y(t), t), 2*x(t) + 5*y(t) + 23)), 'func': [x(t), y(t)],
'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': False, 'is_general': True,
'func_coeff': -Matrix([[-1, -1], [-2, -5]]), 'rhs': Matrix([[ 9], [23]]), 'type_of_equation': 'type2'}
assert neq_nth_linear_constant_coeff_match(eq1, funcs, t) == sol1
# Non constant coefficient homogeneous ODEs
eq1 = (Eq(diff(x(t), t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t), t), 2*x(t) + 5*t*y(t)))
sol1 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), 5*t*x(t) + 2*y(t)), Eq(Derivative(y(t), t), 5*t*y(t) + 2*x(t))),
'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': False,
'is_homogeneous': True, 'func_coeff': -Matrix([ [-5*t, -2], [ -2, -5*t]]), 'commutative_antiderivative': Matrix([
[5*t**2/2, 2*t], [ 2*t, 5*t**2/2]]), 'type_of_equation': 'type3', 'is_general': True}
assert neq_nth_linear_constant_coeff_match(eq1, funcs, t) == sol1
# Non constant coefficient non-homogeneous ODEs
eq1 = [Eq(x1, x(t) + t*y(t) + t), Eq(y1, t*x(t) + y(t))]
sol1 = {'no_of_equation': 2, 'eq': [Eq(Derivative(x(t), t), t*y(t) + t + x(t)), Eq(Derivative(y(t), t),
t*x(t) + y(t))], 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True,
'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-1, -t],
[-t, -1]]), 'commutative_antiderivative': Matrix([ [ t, t**2/2], [t**2/2, t]]), 'rhs':
Matrix([ [t], [0]]), 'type_of_equation': 'type4'}
assert neq_nth_linear_constant_coeff_match(eq1, funcs, t) == sol1
eq2 = [Eq(x1, t*x(t) + t*y(t) + t), Eq(y1, t*x(t) + t*y(t) + cos(t))]
sol2 = {'no_of_equation': 2, 'eq': [Eq(Derivative(x(t), t), t*x(t) + t*y(t) + t), Eq(Derivative(y(t), t),
t*x(t) + t*y(t) + cos(t))], 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True,
'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t],
[-t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2], [t**2/2, t**2/2]]), 'rhs':
Matrix([ [ t], [cos(t)]]), 'type_of_equation': 'type4'}
assert neq_nth_linear_constant_coeff_match(eq2, funcs, t) == sol2
eq3 = [Eq(x1, t*(x(t) + y(t) + z(t) + 1)), Eq(y1, t*(x(t) + y(t) + z(t))), Eq(z1, t*(x(t) + y(t) + z(t)))]
sol3 = {'no_of_equation': 3, 'eq': [Eq(Derivative(x(t), t), t*(x(t) + y(t) + z(t) + 1)),
Eq(Derivative(y(t), t), t*(x(t) + y(t) + z(t))), Eq(Derivative(z(t), t), t*(x(t) + y(t) + z(t)))],
'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant':
False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t, -t], [-t, -t,
-t], [-t, -t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2, t**2/2], [t**2/2,
t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2]]), 'rhs': Matrix([ [t], [0], [0]]), 'type_of_equation':
'type4'}
assert neq_nth_linear_constant_coeff_match(eq3, funcs_2[:-1], t) == sol3
eq4 = [Eq(x1, x(t) + y(t) + t*z(t) + 1), Eq(y1, x(t) + t*y(t) + z(t) + 10), Eq(z1, t*x(t) + y(t) + z(t) + t)]
sol4 = {'no_of_equation': 3, 'eq': [Eq(Derivative(x(t), t), t*z(t) + x(t) + y(t) + 1), Eq(Derivative(y(t),
t), t*y(t) + x(t) + z(t) + 10), Eq(Derivative(z(t), t), t*x(t) + t + y(t) + z(t))], 'func': [x(t),
y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': False,
'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-1, -1, -t], [-1, -t, -1], [-t,
-1, -1]]), 'commutative_antiderivative': Matrix([ [ t, t, t**2/2], [ t, t**2/2,
t], [t**2/2, t, t]]), 'rhs': Matrix([ [ 1], [10], [ t]]), 'type_of_equation': 'type4'}
assert neq_nth_linear_constant_coeff_match(eq4, funcs_2[:-1], t) == sol4
sum_terms = t*(x(t) + y(t) + z(t) + w(t))
eq5 = [Eq(x1, sum_terms), Eq(y1, sum_terms), Eq(z1, sum_terms + 1), Eq(w1, sum_terms)]
sol5 = {'no_of_equation': 4, 'eq': [Eq(Derivative(x(t), t), t*(w(t) + x(t) + y(t) + z(t))),
Eq(Derivative(y(t), t), t*(w(t) + x(t) + y(t) + z(t))), Eq(Derivative(z(t), t), t*(w(t) + x(t) +
y(t) + z(t)) + 1), Eq(Derivative(w(t), t), t*(w(t) + x(t) + y(t) + z(t)))], 'func': [x(t), y(t),
z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': False,
'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t, -t, -t], [-t, -t, -t,
-t], [-t, -t, -t, -t], [-t, -t, -t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2,
t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2,
t**2/2, t**2/2, t**2/2]]), 'rhs': Matrix([ [0], [0], [1], [0]]), 'type_of_equation': 'type4'}
assert neq_nth_linear_constant_coeff_match(eq5, funcs_2, t) == sol5
# Multiple matchs
f, g = symbols("f g", cls=Function)
y = symbols("y")
funcs = [f(t), g(t)]
eq1 = [Eq(Derivative(f(t), t)**2 - 2*Derivative(f(t), t) + 1, 4),
Eq(-y*f(t) + Derivative(g(t), t), 0)]
sol1 = {'is_implicit': True,
'canon_eqs': [[Eq(Derivative(f(t), t), -1), Eq(Derivative(g(t), t), y*f(t))],
[Eq(Derivative(f(t), t), 3), Eq(Derivative(g(t), t), y*f(t))]]}
assert neq_nth_linear_constant_coeff_match(eq1, funcs, t) == sol1
raises(ValueError, lambda: neq_nth_linear_constant_coeff_match(eq1, funcs[:1], t))
def test_matrix_exp():
from sympy.matrices.dense import Matrix, eye, zeros
from sympy.solvers.ode.systems import matrix_exp
t = Symbol('t')
for n in range(1, 6+1):
assert matrix_exp(zeros(n), t) == eye(n)
for n in range(1, 6+1):
A = eye(n)
expAt = exp(t) * eye(n)
assert matrix_exp(A, t) == expAt
for n in range(1, 6+1):
A = Matrix(n, n, lambda i,j: i+1 if i==j else 0)
expAt = Matrix(n, n, lambda i,j: exp((i+1)*t) if i==j else 0)
assert matrix_exp(A, t) == expAt
A = Matrix([[0, 1], [-1, 0]])
expAt = Matrix([[cos(t), sin(t)], [-sin(t), cos(t)]])
assert matrix_exp(A, t) == expAt
A = Matrix([[2, -5], [2, -4]])
expAt = Matrix([
[3*exp(-t)*sin(t) + exp(-t)*cos(t), -5*exp(-t)*sin(t)],
[2*exp(-t)*sin(t), -3*exp(-t)*sin(t) + exp(-t)*cos(t)]
])
assert matrix_exp(A, t) == expAt
A = Matrix([[21, 17, 6], [-5, -1, -6], [4, 4, 16]])
# TO update this.
# expAt = Matrix([
# [(8*t*exp(12*t) + 5*exp(12*t) - 1)*exp(4*t)/4,
# (8*t*exp(12*t) + 5*exp(12*t) - 5)*exp(4*t)/4,
# (exp(12*t) - 1)*exp(4*t)/2],
# [(-8*t*exp(12*t) - exp(12*t) + 1)*exp(4*t)/4,
# (-8*t*exp(12*t) - exp(12*t) + 5)*exp(4*t)/4,
# (-exp(12*t) + 1)*exp(4*t)/2],
# [4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)]])
expAt = Matrix([
[2*t*exp(16*t) + 5*exp(16*t)/4 - exp(4*t)/4, 2*t*exp(16*t) + 5*exp(16*t)/4 - 5*exp(4*t)/4, exp(16*t)/2 - exp(4*t)/2],
[ -2*t*exp(16*t) - exp(16*t)/4 + exp(4*t)/4, -2*t*exp(16*t) - exp(16*t)/4 + 5*exp(4*t)/4, -exp(16*t)/2 + exp(4*t)/2],
[ 4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)]
])
assert matrix_exp(A, t) == expAt
A = Matrix([[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, -S(1)/8],
[0, 0, S(1)/2, S(1)/2]])
expAt = Matrix([
[exp(t), t*exp(t), 4*t*exp(3*t/4) + 8*t*exp(t) + 48*exp(3*t/4) - 48*exp(t),
-2*t*exp(3*t/4) - 2*t*exp(t) - 16*exp(3*t/4) + 16*exp(t)],
[0, exp(t), -t*exp(3*t/4) - 8*exp(3*t/4) + 8*exp(t), t*exp(3*t/4)/2 + 2*exp(3*t/4) - 2*exp(t)],
[0, 0, t*exp(3*t/4)/4 + exp(3*t/4), -t*exp(3*t/4)/8],
[0, 0, t*exp(3*t/4)/2, -t*exp(3*t/4)/4 + exp(3*t/4)]
])
assert matrix_exp(A, t) == expAt
A = Matrix([
[ 0, 1, 0, 0],
[-1, 0, 0, 0],
[ 0, 0, 0, 1],
[ 0, 0, -1, 0]])
expAt = Matrix([
[ cos(t), sin(t), 0, 0],
[-sin(t), cos(t), 0, 0],
[ 0, 0, cos(t), sin(t)],
[ 0, 0, -sin(t), cos(t)]])
assert matrix_exp(A, t) == expAt
A = Matrix([
[ 0, 1, 1, 0],
[-1, 0, 0, 1],
[ 0, 0, 0, 1],
[ 0, 0, -1, 0]])
expAt = Matrix([
[ cos(t), sin(t), t*cos(t), t*sin(t)],
[-sin(t), cos(t), -t*sin(t), t*cos(t)],
[ 0, 0, cos(t), sin(t)],
[ 0, 0, -sin(t), cos(t)]])
assert matrix_exp(A, t) == expAt
# This case is unacceptably slow right now but should be solvable...
#a, b, c, d, e, f = symbols('a b c d e f')
#A = Matrix([
#[-a, b, c, d],
#[ a, -b, e, 0],
#[ 0, 0, -c - e - f, 0],
#[ 0, 0, f, -d]])
A = Matrix([[0, I], [I, 0]])
expAt = Matrix([
[exp(I*t)/2 + exp(-I*t)/2, exp(I*t)/2 - exp(-I*t)/2],
[exp(I*t)/2 - exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]])
assert matrix_exp(A, t) == expAt
# Testing Errors
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 7, 7]])
M1 = Matrix([[t, 1], [1, 1]])
raises(ValueError, lambda: matrix_exp(M[:, :2], t))
raises(ValueError, lambda: matrix_exp(M[:2, :], t))
raises(ValueError, lambda: matrix_exp(M1, t))
raises(ValueError, lambda: matrix_exp(M1[:1, :1], t))
def test_canonical_odes():
f, g, h = symbols('f g h', cls=Function)
x = symbols('x')
funcs = [f(x), g(x), h(x)]
eqs1 = [Eq(f(x).diff(x, x), f(x) + 2*g(x)), Eq(g(x) + 1, g(x).diff(x) + f(x))]
sol1 = [[Eq(Derivative(f(x), (x, 2)), f(x) + 2*g(x)), Eq(Derivative(g(x), x), -f(x) + g(x) + 1)]]
assert canonical_odes(eqs1, funcs[:2], x) == sol1
eqs2 = [Eq(f(x).diff(x), h(x).diff(x) + f(x)), Eq(g(x).diff(x)**2, f(x) + h(x)), Eq(h(x).diff(x), f(x))]
sol2 = [[Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), -sqrt(f(x) + h(x))), Eq(Derivative(h(x), x), f(x))],
[Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), sqrt(f(x) + h(x))), Eq(Derivative(h(x), x), f(x))]]
assert canonical_odes(eqs2, funcs, x) == sol2
def test_sysode_linear_neq_order1_type1():
f, g, x, y, h = symbols('f g x y h', cls=Function)
a, b, c, t = symbols('a b c t')
eq1 = [Eq(x(t).diff(t), x(t)), Eq(y(t).diff(t), y(t))]
sol1 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t))]
assert dsolve(eq1) == sol1
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = [Eq(x(t).diff(t), 2*x(t)), Eq(y(t).diff(t), 3*y(t))]
#sol2 = [Eq(x(t), C1*exp(2*t)), Eq(y(t), C2*exp(3*t))]
sol2 = [Eq(x(t), C1*exp(2*t)), Eq(y(t), C2*exp(3*t))]
assert dsolve(eq2) == sol2
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = [Eq(x(t).diff(t), a*x(t)), Eq(y(t).diff(t), a*y(t))]
sol3 = [Eq(x(t), C1*exp(a*t)), Eq(y(t), C2*exp(a*t))]
assert dsolve(eq3) == sol3
assert checksysodesol(eq3, sol3) == (True, [0, 0])
# Regression test case for issue #15474
# https://github.com/sympy/sympy/issues/15474
eq4 = [Eq(x(t).diff(t), a*x(t)), Eq(y(t).diff(t), b*y(t))]
sol4 = [Eq(x(t), C1*exp(a*t)), Eq(y(t), C2*exp(b*t))]
assert dsolve(eq4) == sol4
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = [Eq(x(t).diff(t), -y(t)), Eq(y(t).diff(t), x(t))]
sol5 = [Eq(x(t), -C1*sin(t) - C2*cos(t)), Eq(y(t), C1*cos(t) - C2*sin(t))]
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = [Eq(x(t).diff(t), -2*y(t)), Eq(y(t).diff(t), 2*x(t))]
sol6 = [Eq(x(t), -C1*sin(2*t) - C2*cos(2*t)), Eq(y(t), C1*cos(2*t) - C2*sin(2*t))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0])
eq7 = [Eq(x(t).diff(t), I*y(t)), Eq(y(t).diff(t), I*x(t))]
sol7 = [Eq(x(t), -C1*exp(-I*t) + C2*exp(I*t)), Eq(y(t), C1*exp(-I*t) + C2*exp(I*t))]
assert dsolve(eq7) == sol7
assert checksysodesol(eq7, sol7) == (True, [0, 0])
eq8 = [Eq(x(t).diff(t), -a*y(t)), Eq(y(t).diff(t), a*x(t))]
sol8 = [Eq(x(t), -I*C1*exp(-I*a*t) + I*C2*exp(I*a*t)), Eq(y(t), C1*exp(-I*a*t) + C2*exp(I*a*t))]
assert dsolve(eq8) == sol8
assert checksysodesol(eq8, sol8) == (True, [0, 0])
eq9 = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), x(t) - y(t))]
sol9 = [Eq(x(t), C1*(1 - sqrt(2))*exp(-sqrt(2)*t) + C2*(1 + sqrt(2))*exp(sqrt(2)*t)),
Eq(y(t), C1*exp(-sqrt(2)*t) + C2*exp(sqrt(2)*t))]
assert dsolve(eq9) == sol9
assert checksysodesol(eq9, sol9) == (True, [0, 0])
eq10 = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), x(t) + y(t))]
sol10 = [Eq(x(t), -C1 + C2*exp(2*t)), Eq(y(t), C1 + C2*exp(2*t))]
assert dsolve(eq10) == sol10
assert checksysodesol(eq10, sol10) == (True, [0, 0])
eq11 = [Eq(x(t).diff(t), 2*x(t) + y(t)), Eq(y(t).diff(t), -x(t) + 2*y(t))]
sol11 = [Eq(x(t), (C1*sin(t) + C2*cos(t))*exp(2*t)),
Eq(y(t), (C1*cos(t) - C2*sin(t))*exp(2*t))]
assert dsolve(eq11) == sol11
assert checksysodesol(eq11, sol11) == (True, [0, 0])
eq12 = [Eq(x(t).diff(t), x(t) + 2*y(t)), Eq(y(t).diff(t), 2*x(t) + y(t))]
sol12 = [Eq(x(t), -C1*exp(-t) + C2*exp(3*t)), Eq(y(t), C1*exp(-t) + C2*exp(3*t))]
assert dsolve(eq12) == sol12
assert checksysodesol(eq12, sol12) == (True, [0, 0])
eq13 = [Eq(x(t).diff(t), 4*x(t) + y(t)), Eq(y(t).diff(t), -x(t) + 2*y(t))]
sol13 = [Eq(x(t), (C1 + C2*t + C2)*exp(3*t)), Eq(y(t), (-C1 - C2*t)*exp(3*t))]
assert dsolve(eq13) == sol13
assert checksysodesol(eq13, sol13) == (True, [0, 0])
eq14 = [Eq(x(t).diff(t), a*y(t)), Eq(y(t).diff(t), a*x(t))]
sol14 = [Eq(x(t), -C1*exp(-a*t) + C2*exp(a*t)), Eq(y(t), C1*exp(-a*t) + C2*exp(a*t))]
assert dsolve(eq14) == sol14
assert checksysodesol(eq14, sol14) == (True, [0, 0])
eq15 = [Eq(x(t).diff(t), a*y(t)), Eq(y(t).diff(t), b*x(t))]
sol15 = [Eq(x(t), -C1*a*exp(-t*sqrt(a*b))/sqrt(a*b) + C2*a*exp(t*sqrt(a*b))/sqrt(a*b)),
Eq(y(t), C1*exp(-t*sqrt(a*b)) + C2*exp(t*sqrt(a*b)))]
assert dsolve(eq15) == sol15
assert checksysodesol(eq15, sol15) == (True, [0, 0])
eq16 = [Eq(x(t).diff(t), a*x(t) + b*y(t)), Eq(y(t).diff(t), c*x(t))]
sol16 = [Eq(x(t), -2*C1*b*exp(t*(a/2 + sqrt(a**2 + 4*b*c)/2))/(a - sqrt(a**2 + 4*b*c)) - 2*C2*b*exp(t*(a/2 - sqrt(a**2 + 4*b*c)/2))/(a + sqrt(a**2 + 4*b*c))),
Eq(y(t), C1*exp(t*(a/2 + sqrt(a**2 + 4*b*c)/2)) + C2*exp(t*(a/2 - sqrt(a**2 + 4*b*c)/2)))]
assert dsolve(eq16) == sol16
assert checksysodesol(eq16, sol16) == (True, [0, 0])
# Regression test case for issue #18562
# https://github.com/sympy/sympy/issues/18562
eq17 = [Eq(x(t).diff(t), x(t) + a*y(t)), Eq(y(t).diff(t), x(t)*a - y(t))]
sol17 = [Eq(x(t), C1*a*exp(t*sqrt(a**2 + 1))/(sqrt(a**2 + 1) - 1) - C2*a*exp(-t*sqrt(a**2 + 1))/(sqrt(a**2 + 1) + 1)),
Eq(y(t), C1*exp(t*sqrt(a**2 + 1)) + C2*exp(-t*sqrt(a**2 + 1)))]
assert dsolve(eq17) == sol17
assert checksysodesol(eq17, sol17) == (True, [0, 0])
eq18 = [Eq(x(t).diff(t), 0), Eq(y(t).diff(t), 0)]
sol18 = [Eq(x(t), C1), Eq(y(t), C2)]
assert dsolve(eq18) == sol18
assert checksysodesol(eq18, sol18) == (True, [0, 0])
eq19 = [Eq(x(t).diff(t), 2*x(t) - y(t)), Eq(y(t).diff(t), x(t))]
sol19 = [Eq(x(t), (C1 + C2*t + C2)*exp(t)), Eq(y(t), (C1 + C2*t)*exp(t))]
assert dsolve(eq19) == sol19
assert checksysodesol(eq19, sol19) == (True, [0, 0])
eq20 = [Eq(x(t).diff(t), x(t)), Eq(y(t).diff(t), x(t) + y(t))]
sol20 = [Eq(x(t), C1*exp(t)), Eq(y(t), (C1*t + C2)*exp(t))]
assert dsolve(eq20) == sol20
assert checksysodesol(eq20, sol20) == (True, [0, 0])
eq21 = [Eq(Derivative(x(t), t), 3*x(t)), Eq(Derivative(y(t), t), x(t) + y(t))]
sol21 = [Eq(x(t), 2*C1*exp(3*t)), Eq(y(t), C1*exp(3*t) + C2*exp(t))]
assert dsolve(eq21) == sol21
assert checksysodesol(eq21, sol21) == (True, [0, 0])
eq22 = [Eq(Derivative(x(t), t), 3*x(t)), Eq(Derivative(y(t), t), y(t))]
sol22 = [Eq(x(t), C1*exp(3*t)), Eq(y(t), C2*exp(t))]
assert dsolve(eq22) == sol22
assert checksysodesol(eq22, sol22) == (True, [0, 0])
Z0 = Function('Z0')
Z1 = Function('Z1')
Z2 = Function('Z2')
Z3 = Function('Z3')
k01, k10, k20, k21, k23, k30 = symbols('k01 k10 k20 k21 k23 k30')
eq1 = (Eq(Derivative(Z0(t), t), -k01*Z0(t) + k10*Z1(t) + k20*Z2(t) + k30*Z3(t)),
Eq(Derivative(Z1(t), t), k01*Z0(t) - k10*Z1(t) + k21*Z2(t)),
Eq(Derivative(Z2(t), t), -(k20 + k21 + k23)*Z2(t)), Eq(Derivative(Z3(t), t), k23*Z2(t) - k30*Z3(t)))
sol1 = [Eq(Z0(t), C1*k10/k01 + C2*(-k10 + k30)*exp(-k30*t)/(k01 + k10 - k30) + C3*(k10*k20 + k10*k21 - k10*k30 -
k20**2 - k20*k21 - k20*k23 + k20*k30 + k23*k30)*exp(t*(-k20 - k21 - k23))/(k23*(k01 + k10 - k20 - k21 -
k23)) - C4*exp(t*(-k01 - k10))),
Eq(Z1(t), C1 - C2*k01*exp(-k30*t)/(k01 + k10 - k30) + C3*(k01*k20 + k01*k21 - k01*k30 - k20*k21 - k21**2 -
k21*k23 + k21*k30)*exp(t*(-k20 - k21 - k23))/(k23*(k01 + k10 - k20 - k21 - k23)) + C4*exp(t*(-k01 - k10))),
Eq(Z2(t), C3*(-k20 - k21 - k23 + k30)*exp(t*(-k20 - k21 - k23))/k23),
Eq(Z3(t), C2*exp(-k30*t) + C3*exp(t*(-k20 - k21 - k23)))]
assert dsolve(eq1, simplify=False) == sol1
assert checksysodesol(eq1, sol1) == (True, [0, 0, 0, 0])
x, y, z, u, v, w = symbols('x y z u v w', cls=Function)
k2, k3 = symbols('k2 k3')
a_b, a_c = symbols('a_b a_c', real=True)
eq2 = (
Eq(Derivative(z(t), t), k2*y(t)),
Eq(Derivative(x(t), t), k3*y(t)),
Eq(Derivative(y(t), t), (-k2 - k3)*y(t))
)
sol2 = [Eq(z(t), C1 - C2*k2*exp(t*(-k2 - k3))/(k2 + k3)),
Eq(x(t), -C2*k3*exp(t*(-k2 - k3))/(k2 + k3) + C3),
Eq(y(t), C2*exp(t*(-k2 - k3)))]
assert dsolve(eq2) == sol2
assert checksysodesol(eq2, sol2) == (True, [0, 0, 0])
eq3 = [4*u(t) - v(t) - 2*w(t) + Derivative(u(t), t),
2*u(t) + v(t) - 2*w(t) + Derivative(v(t), t),
5*u(t) + v(t) - 3*w(t) + Derivative(w(t), t)]
sol3 = [Eq(u(t), C1*cos(sqrt(3)*t)/2 - C2*sin(sqrt(3)*t)/2 + C3*exp(-2*t) + sqrt(3)*(C1*sin(sqrt(3)*t) + C2*cos(sqrt(3)*t))/6),
Eq(v(t), C1*cos(sqrt(3)*t)/2 - C2*sin(sqrt(3)*t)/2 + sqrt(3)*(C1*sin(sqrt(3)*t) + C2*cos(sqrt(3)*t))/6),
Eq(w(t), C1*cos(sqrt(3)*t) - C2*sin(sqrt(3)*t) + C3*exp(-2*t))]
assert dsolve(eq3) == sol3
assert checksysodesol(eq3, sol3) == (True, [0, 0, 0])
tw = Rational(2, 9)
eq4 = [Eq(x(t).diff(t), 2*x(t) + y(t) - tw*4*z(t) - tw*w(t)),
Eq(y(t).diff(t), 2*y(t) + 8*tw*z(t) + 2*tw*w(t)),
Eq(z(t).diff(t), Rational(37, 9)*z(t) - tw*w(t)),
Eq(w(t).diff(t), 22*tw*w(t) - 2*tw*z(t))]
sol4 = [Eq(x(t), (C1 + C2*t)*exp(2*t)),
Eq(y(t), C2*exp(2*t) + 2*C3*exp(4*t)),
Eq(z(t), 2*C3*exp(4*t) - C4*exp(5*t)/4),
Eq(w(t), C3*exp(4*t) + C4*exp(5*t))]
assert dsolve(eq4) == sol4
assert checksysodesol(eq4, sol4) == (True, [0, 0, 0, 0])
# Regression test case for issue #15574
# https://github.com/sympy/sympy/issues/15574
eq5 = [Eq(x(t).diff(t), x(t)), Eq(y(t).diff(t), y(t)), Eq(z(t).diff(t), z(t)), Eq(w(t).diff(t), w(t))]
sol5 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t)), Eq(w(t), C4*exp(t))]
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0, 0, 0])
eq6 = [Eq(Derivative(x(t), t), x(t) + y(t)),
Eq(Derivative(y(t), t), y(t) + z(t)),
Eq(Derivative(z(t), t), -w(t)/8 + z(t)),
Eq(Derivative(w(t), t), w(t)/2 + z(t)/2)]
sol6 = [Eq(x(t), (C1 + C2*t)*exp(t) + (4*C3 + 4*C4*t + 48*C4)*exp(3*t/4)),
Eq(y(t), C2*exp(t) + (-C3 - C4*t - 8*C4)*exp(3*t/4)),
Eq(z(t), (C3/4 + C4*t/4 + C4)*exp(3*t/4)),
Eq(w(t), (C3/2 + C4*t/2)*exp(3*t/4))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0, 0, 0])
# Regression test case for issue #15574
# https://github.com/sympy/sympy/issues/15574
eq7 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t)), Eq(Derivative(z(t), t), z(t)),
Eq(Derivative(w(t), t), w(t)), Eq(Derivative(u(t), t), u(t))]
sol7 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t)), Eq(w(t), C4*exp(t)),
Eq(u(t), C5*exp(t))]
assert dsolve(eq7) == sol7
assert checksysodesol(eq7, sol7) == (True, [0, 0, 0, 0, 0])
eq8 = [Eq(Derivative(x(t), t), 2*x(t) + y(t)), Eq(Derivative(y(t), t), 2*y(t)),
Eq(Derivative(z(t), t), 4*z(t)),
Eq(Derivative(w(t), t), u(t) + 5*w(t)), Eq(Derivative(u(t), t), 5*u(t))]
sol8 = [Eq(x(t), (C1 + C2*t)*exp(2*t)), Eq(y(t), C2*exp(2*t)), Eq(z(t), C3*exp(4*t)),
Eq(w(t), (C4 + C5*t)*exp(5*t)),
Eq(u(t), C5*exp(5*t))]
assert dsolve(eq8) == sol8
assert checksysodesol(eq8, sol8) == (True, [0, 0, 0, 0, 0])
# Regression test case for issue #15574
# https://github.com/sympy/sympy/issues/15574
eq9 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t)), Eq(Derivative(z(t), t), z(t))]
sol9 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t))]
assert dsolve(eq9) == sol9
assert checksysodesol(eq9, sol9) == (True, [0, 0, 0])
# Regression test case for issue #15407
# https://github.com/sympy/sympy/issues/15407
eq10 = [Eq(Derivative(x(t), t), (-a_b - a_c)*x(t)), Eq(Derivative(y(t), t), a_b*y(t)), Eq(Derivative(z(t), t),
a_c*x(t))]
sol10 = [Eq(x(t), -C1*(a_b + a_c)*exp(t*(-a_b - a_c))/a_c),
Eq(y(t), C2*exp(a_b*t)),
Eq(z(t), C1*exp(t*(-a_b - a_c)) + C3)]
assert dsolve(eq10) == sol10
assert checksysodesol(eq10, sol10) == (True, [0, 0, 0])
# Regression test case for issue #14312
# https://github.com/sympy/sympy/issues/14312
eq11 = (Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t)), Eq(Derivative(z(t), t), k2*y(t)))
sol11 = [Eq(x(t), C1 + C2*k3*exp(t*(-k2 - k3))/k2),
Eq(y(t), -C2*(k2 + k3)*exp(t*(-k2 - k3))/k2),
Eq(z(t), C2*exp(t*(-k2 - k3)) + C3)]
assert dsolve(eq11) == sol11
assert checksysodesol(eq11, sol11) == (True, [0, 0, 0])
# Regression test case for issue #14312
# https://github.com/sympy/sympy/issues/14312
eq12 = (Eq(Derivative(z(t), t), k2*y(t)), Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t)))
sol12 = [Eq(z(t), C1 - C2*k2*exp(t*(-k2 - k3))/(k2 + k3)),
Eq(x(t), -C2*k3*exp(t*(-k2 - k3))/(k2 + k3) + C3),
Eq(y(t), C2*exp(t*(-k2 - k3)))]
assert dsolve(eq12) == sol12
assert checksysodesol(eq12, sol12) == (True, [0, 0, 0])
# Regression test case for issue #15474
# https://github.com/sympy/sympy/issues/15474
eq13 = [Eq(Derivative(f(t), t), 2*f(t) + g(t)), Eq(Derivative(g(t), t), a*f(t))]
sol13 = [Eq(f(t), C1*exp(t*(sqrt(a + 1) + 1))/(sqrt(a + 1) - 1) - C2*exp(t*(1 - sqrt(a + 1)))/(sqrt(a + 1) + 1)),
Eq(g(t), C1*exp(t*(sqrt(a + 1) + 1)) + C2*exp(t*(1 - sqrt(a + 1))))]
assert dsolve(eq13) == sol13
assert checksysodesol(eq13, sol13) == (True, [0, 0])
eq14 = [Eq(f(t).diff(t), 2*g(t) - 3*h(t)),
Eq(g(t).diff(t), 4*h(t) - 2*f(t)),
Eq(h(t).diff(t), 3*f(t) - 4*g(t))]
sol14 = [Eq(f(t), 2*C1 - 8*C2*cos(sqrt(29)*t)/25 + 8*C3*sin(sqrt(29)*t)/25 - 3*sqrt(29)*(C2*sin(sqrt(29)*t)
+ C3*cos(sqrt(29)*t))/25),
Eq(g(t), 3*C1/2 - 6*C2*cos(sqrt(29)*t)/25 + 6*C3*sin(sqrt(29)*t)/25
+ 4*sqrt(29)*(C2*sin(sqrt(29)*t) + C3*cos(sqrt(29)*t))/25),
Eq(h(t), C1 + C2*cos(sqrt(29)*t)
- C3*sin(sqrt(29)*t))]
assert dsolve(eq14) == sol14
assert checksysodesol(eq14, sol14) == (True, [0, 0, 0])
eq15 = [Eq(2*f(t).diff(t), 3*4*(g(t) - h(t))),
Eq(3*g(t).diff(t), 2*4*(h(t) - f(t))),
Eq(4*h(t).diff(t), 2*3*(f(t) - g(t)))]
sol15 = [Eq(f(t), C1 - 16*C2*cos(sqrt(29)*t)/13 + 16*C3*sin(sqrt(29)*t)/13 - 6*sqrt(29)*(
C2*sin(sqrt(29)*t) + C3*cos(sqrt(29)*t))/13),
Eq(g(t), C1 - 16*C2*cos(sqrt(29)*t)/13 + 16*C3*sin(sqrt(29)*t)/13 + 8*sqrt(29)*(C2*sin(sqrt(29)*t) +
C3*cos(sqrt(29)*t))/39),
Eq(h(t), C1 + C2*cos(sqrt(29)*t) - C3*sin(sqrt(29)*t))]
assert dsolve(eq15) == sol15
assert checksysodesol(eq15, sol15) == (True, [0, 0, 0])
eq16 = (Eq(diff(x(t), t), 21*x(t)), Eq(diff(y(t), t), 17*x(t) + 3*y(t)),
Eq(diff(z(t), t), 5*x(t) + 7*y(t) + 9*z(t)))
sol16 = [Eq(x(t), 216*C1*exp(21*t)/209),
Eq(y(t), 204*C1*exp(21*t)/209 - 6*C2*exp(3*t)/7),
Eq(z(t), C1*exp(21*t) + C2*exp(3*t) + C3*exp(9*t))]
assert dsolve(eq16) == sol16
assert checksysodesol(eq16, sol16) == (True, [0, 0, 0])
eq17 = (Eq(diff(x(t), t), 3*y(t) - 11*z(t)), Eq(diff(y(t), t), 7*z(t) - 3*x(t)), Eq(diff(z(t), t), 11*x(t) - 7*y(t)))
sol17 = [Eq(x(t), 7*C1/3 - 21*C2*cos(sqrt(179)*t)/170 + 21*C3*sin(sqrt(179)*t)/170 - 11*sqrt(179)*(
C2*sin(sqrt(179)*t) + C3*cos(sqrt(179)*t))/170),
Eq(y(t), 11*C1/3 - 33*C2*cos(sqrt(179)*t)/170 + 33*C3*sin(sqrt(179)*t)/170 + 7*sqrt(179)*(
C2*sin(sqrt(179)*t) + C3*cos(sqrt(179)*t))/170),
Eq(z(t), C1 + C2*cos(sqrt(179)*t) - C3*sin(sqrt(179)*t))]
assert dsolve(eq17) == sol17
assert checksysodesol(eq17, sol17) == (True, [0, 0, 0])
eq18 = (Eq(3*diff(x(t), t), 4*5*(y(t) - z(t))), Eq(4*diff(y(t), t), 3*5*(z(t) - x(t))),
Eq(5*diff(z(t), t), 3*4*(x(t) - y(t))))
sol18 = [Eq(x(t), C1 - C2*cos(5*sqrt(2)*t) + C3*sin(5*sqrt(2)*t) - 4*sqrt(2)*(C2*sin(5*sqrt(2)*t) + C3*cos(5*sqrt(2)*t))/3),
Eq(y(t), C1 - C2*cos(5*sqrt(2)*t) + C3*sin(5*sqrt(2)*t) + 3*sqrt(2)*(C2*sin(5*sqrt(2)*t) + C3*cos(5*sqrt(2)*t))/4),
Eq(z(t), C1 + C2*cos(5*sqrt(2)*t) - C3*sin(5*sqrt(2)*t))]
assert dsolve(eq18) == sol18
assert checksysodesol(eq18, sol18) == (True, [0, 0, 0])
eq19 = (Eq(diff(x(t), t), 4*x(t) - z(t)), Eq(diff(y(t), t), 2*x(t) + 2*y(t) - z(t)), Eq(diff(z(t), t), 3*x(t) + y(t)))
sol19 = [Eq(x(t), (C1 + C2*t**2/2 + 2*C2*t + C2 + C3*t + 2*C3)*exp(2*t)),
Eq(y(t), (C1 + C2*t**2/2 + 2*C2*t + C3*t + 2*C3)*exp(2*t)),
Eq(z(t), (2*C1 + C2*t**2 + 3*C2*t + 2*C3*t + 3*C3)*exp(2*t))]
assert dsolve(eq19) == sol19
assert checksysodesol(eq19, sol19) == (True, [0, 0, 0])
eq20 = (Eq(diff(x(t), t), 4*x(t) - y(t) - 2*z(t)), Eq(diff(y(t), t), 2*x(t) + y(t) - 2*z(t)),
Eq(diff(z(t), t), 5*x(t) - 3*z(t)))
sol20 = [Eq(x(t), C1*exp(2*t) - 3*C2*sin(t)/5 - C2*cos(t)/5 - C3*sin(t)/5 + 3*C3*cos(t)/5),
Eq(y(t), -3*C2*sin(t)/5 - C2*cos(t)/5 - C3*sin(t)/5 + 3*C3*cos(t)/5),
Eq(z(t), C1*exp(2*t) - C2*sin(t) + C3*cos(t))]
assert dsolve(eq20) == sol20
assert checksysodesol(eq20, sol20) == (True, [0, 0, 0])
eq21 = (Eq(diff(x(t), t), 9*y(t)), Eq(diff(y(t), t), 12*x(t)))
sol21 = [Eq(x(t), -sqrt(3)*C1*exp(-6*sqrt(3)*t)/2 + sqrt(3)*C2*exp(6*sqrt(3)*t)/2),
Eq(y(t), C1*exp(-6*sqrt(3)*t) + C2*exp(6*sqrt(3)*t))]
assert dsolve(eq21) == sol21
assert checksysodesol(eq21, sol21) == (True, [0, 0])
eq22 = (Eq(Derivative(x(t), t), 2*x(t) + 4*y(t)), Eq(Derivative(y(t), t), 12*x(t) + 41*y(t)))
sol22 = [Eq(x(t), C1*(-Rational(13, 8) + sqrt(1713)/24)*exp(t*(sqrt(1713)/2 + Rational(43, 2))) + C2*(
- sqrt(1713)/24 - Rational(13, 8))*exp(t*(Rational(43, 2) - sqrt(1713)/2))),
Eq(y(t), C1*exp(t*(sqrt(1713)/2 + Rational(43, 2))) + C2*exp(t*(Rational(43, 2) - sqrt(1713)/2)))]
assert dsolve(eq22) == sol22
assert checksysodesol(eq22, sol22) == (True, [0, 0])
eq23 = (Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), -2*x(t) + 2*y(t)))
sol23 = [
Eq(x(t), (C1*cos(sqrt(7)*t/2)/4 - C2*sin(sqrt(7)*t/2)/4 + sqrt(7)*(C1*sin(sqrt(7)*t/2) + C2*cos(
sqrt(7)*t/2))/4)*exp(3*t/2)),
Eq(y(t), (C1*cos(sqrt(7)*t/2) - C2*sin(sqrt(7)*t/2))*exp(3*t/2))
]
assert dsolve(eq23) == sol23
assert checksysodesol(eq23, sol23) == (True, [0, 0])
# Regression test case for issue #15474
# https://github.com/sympy/sympy/issues/15474
a = Symbol("a", real=True)
eq24 = [x(t).diff(t) - a*y(t), y(t).diff(t) + a*x(t)]
sol24 = [Eq(x(t), C1*sin(a*t) + C2*cos(a*t)), Eq(y(t), C1*cos(a*t) - C2*sin(a*t))]
assert dsolve(eq24) == sol24
assert checksysodesol(eq24, sol24) == (True, [0, 0])
# Regression test case for issue #19150
# https://github.com/sympy/sympy/issues/19150
eq25 = [Eq(Derivative(f(t), t), 0),
Eq(Derivative(g(t), t), 1/(c*b)*(-2*g(t) + x(t) + f(t))),
Eq(Derivative(x(t), t), 1/(c*b)*(-2*x(t) + g(t) + y(t))),
Eq(Derivative(y(t), t), 1/(c*b)*(-2*y(t) + x(t) + h(t))),
Eq(Derivative(h(t), t), 0)]
sol25 = [Eq(f(t), -3*C1 + 4*C2),
Eq(g(t), -2*C1 + 3*C2 - C3*exp(-2*t/(b*c)) + C4*exp(t*(-2 - sqrt(2))/(b*c)) +
C5*exp(t*(-2 + sqrt(2))/(b*c))),
Eq(x(t), -C1 + 2*C2 - sqrt(2)*C4*exp(t*(-2 - sqrt(2))/(b*c)) + sqrt(2)*C5*exp(t*(-2 + sqrt(2))/(b*c))),
Eq(y(t), C2 + C3*exp(-2*t/(b*c)) + C4*exp(t*(-2 - sqrt(2))/(b*c)) + C5*exp(
t*(-2 + sqrt(2))/(b*c))),
Eq(h(t), C1)]
assert dsolve(eq25) == sol25
assert checksysodesol(eq25, sol25) == (True, [0, 0, 0, 0, 0])
eq26 = [Eq(Derivative(f(t), t), 2*f(t)), Eq(Derivative(g(t), t), 3*f(t) + 7*g(t))]
sol26 = [Eq(f(t), -5*C1*exp(2*t)/3), Eq(g(t), C1*exp(2*t) + C2*exp(7*t))]
assert dsolve(eq26) == sol26
assert checksysodesol(eq26, sol26) == (True, [0, 0])
eq27 = [Eq(Derivative(f(t), t), -9*I*f(t) - 4*g(t)), Eq(Derivative(g(t), t), -4*I*g(t))]
sol27 = [Eq(f(t), 4*I*C1*exp(-4*I*t)/5 + C2*exp(-9*I*t)), Eq(g(t), C1*exp(-4*I*t))]
assert dsolve(eq27) == sol27
assert checksysodesol(eq27, sol27) == (True, [0, 0])
eq28 = [Eq(Derivative(f(t), t), -9*I*f(t)), Eq(Derivative(g(t), t), -4*I*g(t))]
sol28 = [Eq(f(t), C1*exp(-9*I*t)), Eq(g(t), C2*exp(-4*I*t))]
assert dsolve(eq28) == sol28
assert checksysodesol(eq28, sol28) == (True, [0, 0])
eq29 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), 0)]
sol29 = [Eq(f(t), C1), Eq(g(t), C2)]
assert dsolve(eq29) == sol29
assert checksysodesol(eq29, sol29) == (True, [0, 0])
eq30 = [Eq(Derivative(f(t), t), f(t)), Eq(Derivative(g(t), t), 0)]
sol30 = [Eq(f(t), C1*exp(t)), Eq(g(t), C2)]
assert dsolve(eq30) == sol30
assert checksysodesol(eq30, sol30) == (True, [0, 0])
eq31 = [Eq(Derivative(f(t), t), g(t)), Eq(Derivative(g(t), t), 0)]
sol31 = [Eq(f(t), C1 + C2*t), Eq(g(t), C2)]
assert dsolve(eq31) == sol31
assert checksysodesol(eq31, sol31) == (True, [0, 0])
eq32 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), f(t))]
sol32 = [Eq(f(t), C1), Eq(g(t), C1*t + C2)]
assert dsolve(eq32) == sol32
assert checksysodesol(eq32, sol32) == (True, [0, 0])
eq33 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), g(t))]
sol33 = [Eq(f(t), C1), Eq(g(t), C2*exp(t))]
assert dsolve(eq33) == sol33
assert checksysodesol(eq33, sol33) == (True, [0, 0])
eq34 = [Eq(Derivative(f(t), t), f(t)), Eq(Derivative(g(t), t), I*g(t))]
sol34 = [Eq(f(t), C1*exp(t)), Eq(g(t), C2*exp(I*t))]
assert dsolve(eq34) == sol34
assert checksysodesol(eq34, sol34) == (True, [0, 0])
eq35 = [Eq(Derivative(f(t), t), I*f(t)), Eq(Derivative(g(t), t), -I*g(t))]
sol35 = [Eq(f(t), C1*exp(I*t)), Eq(g(t), C2*exp(-I*t))]
assert dsolve(eq35) == sol35
assert checksysodesol(eq35, sol35) == (True, [0, 0])
eq36 = [Eq(Derivative(f(t), t), I*g(t)), Eq(Derivative(g(t), t), 0)]
sol36 = [Eq(f(t), I*(C1 + C2*t)), Eq(g(t), C2)]
assert dsolve(eq36) == sol36
assert checksysodesol(eq36, sol36) == (True, [0, 0])
eq37 = [Eq(Derivative(f(t), t), I*g(t)), Eq(Derivative(g(t), t), I*f(t))]
sol37 = [Eq(f(t), -C1*exp(-I*t) + C2*exp(I*t)), Eq(g(t), C1*exp(-I*t) + C2*exp(I*t))]
assert dsolve(eq37) == sol37
assert checksysodesol(eq37, sol37) == (True, [0, 0])
# Multiple systems
eq1 = [Eq(Derivative(f(t), t)**2, g(t)**2), Eq(-f(t) + Derivative(g(t), t), 0)]
sol1 = [[Eq(f(t), -C1*sin(t) - C2*cos(t)),
Eq(g(t), C1*cos(t) - C2*sin(t))],
[Eq(f(t), -C1*exp(-t) + C2*exp(t)),
Eq(g(t), C1*exp(-t) + C2*exp(t))]]
assert dsolve(eq1) == sol1
for sol in sol1:
assert checksysodesol(eq1, sol) == (True, [0, 0])
def test_sysode_linear_neq_order1_type2():
f, g, h, k = symbols('f g h k', cls=Function)
x, t, a, b, c, d, y = symbols('x t a b c d y')
eq1 = [Eq(diff(f(x), x), f(x) + g(x) + 5),
Eq(diff(g(x), x), -f(x) - g(x) + 7)]
sol1 = [Eq(f(x), C1 + C2*x + C2 + x*Integral(12, x) + Integral(12, x) + Integral(-12*x - 7, x)),
Eq(g(x), -C1 - C2*x - x*Integral(12, x) - Integral(-12*x - 7, x))]
assert dsolve(eq1) == sol1
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = [Eq(diff(f(x), x), f(x) + g(x) + 5),
Eq(diff(g(x), x), f(x) + g(x) + 7)]
sol2 = [Eq(f(x), -C1 + C2*exp(2*x) + exp(2*x)*Integral(6*exp(-2*x), x) - Integral(1, x)),
Eq(g(x), C1 + C2*exp(2*x) + exp(2*x)*Integral(6*exp(-2*x), x) + Integral(1, x))]
assert dsolve(eq2) == sol2
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = [Eq(diff(f(x), x), f(x) + 5), Eq(diff(g(x), x), f(x) + 7)]
sol3 = [Eq(f(x), C1*exp(x) + exp(x)*Integral(5*exp(-x), x)),
Eq(g(x), C1*exp(x) + C2 + exp(x)*Integral(5*exp(-x), x) + Integral(2, x))]
assert dsolve(eq3) == sol3
assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = [Eq(diff(f(x), x), f(x) + exp(x)), Eq(diff(g(x), x), f(x) + g(x) + x*exp(x))]
sol4 = [Eq(f(x), (C1 + Integral(1, x))*exp(x)), Eq(g(x), (C1*x + C2 + x*Integral(1, x) + Integral(0, x))*exp(x))]
assert dsolve(eq4) == sol4
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = [Eq(diff(f(x), x), f(x) + g(x) + 5*x), Eq(diff(g(x), x), f(x) - g(x))]
sol5 = [Eq(f(x), C1*exp(sqrt(2)*x) + sqrt(2)*C1*exp(sqrt(2)*x) + (-sqrt(2)*C2 + C2 - sqrt(2)*Integral(
-5*sqrt(2)*x*exp(sqrt(2)*x)/4, x) + Integral(-5*sqrt(2)*x*exp(sqrt(2)*x)/4, x))*exp(-sqrt(2)*x) +
exp(sqrt(2)*x)*Integral(5*sqrt(2)*x*exp(-sqrt(2)*x)/4, x) + sqrt(2)*exp(sqrt(2)*x)*Integral(
5*sqrt(2)*x*exp(-sqrt(2)*x)/4, x)),
Eq(g(x), C1*exp(sqrt(2)*x) + (C2 + Integral(-5*sqrt(2)*x*exp(sqrt(2)*x)/4, x))*exp(-sqrt(2)*x) + exp(
sqrt(2)*x)*Integral(5*sqrt(2)*x*exp(-sqrt(2)*x)/4, x))]
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = [Eq(diff(f(x), x), -9*f(x) - 4*g(x)),
Eq(diff(g(x), x), -4*g(x)),
Eq(diff(h(x), x), h(x) + exp(x))]
sol6 = [Eq(f(x), (-4*C1/5 - 4*Integral(0, x)/5)*exp(-4*x) + (C2 + Integral(0, x))*exp(-9*x)),
Eq(g(x), (C1 + Integral(0, x))*exp(-4*x)), Eq(h(x), (C3 + Integral(1, x))*exp(x))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0, 0])
# Regression test case for issue #8859
# https://github.com/sympy/sympy/issues/8859
eq7 = [Eq(diff(f(t), t), f(t) + 3*t), Eq(diff(g(t), t), g(t))]
sol7 = [Eq(f(t), C1*exp(t) + exp(t)*Integral(3*t*exp(-t), t)), Eq(g(t), C2*exp(t) + exp(t)*Integral(0, t))]
assert dsolve(eq7) == sol7
assert checksysodesol(eq7, sol7) == (True, [0, 0])
# Regression test case for issue #8567
# https://github.com/sympy/sympy/issues/8567
eq8 = [Eq(f(t).diff(t), f(t) + 2*g(t)), Eq(g(t).diff(t), -2*f(t) + g(t) + 2*exp(t))]
sol8 = [Eq(f(t), (C1*sin(2*t) + C2*cos(2*t) + sin(2*t)*Integral(-2*sin(2*t)**2/cos(2*t) + 2/cos(2*t), t) +
cos(2*t)*Integral(-2*sin(2*t), t))*exp(t)),
Eq(g(t), (C1*cos(2*t) - C2*sin(2*t) - sin(2*t)*Integral(-2*sin(2*t), t) +
cos(2*t)*Integral(-2*sin(2*t)**2/cos(2*t) + 2/cos(2*t), t))*exp(t))]
assert dsolve(eq8) == sol8
assert checksysodesol(eq8, sol8) == (True, [0, 0])
# Regression test case for issue #19150
# https://github.com/sympy/sympy/issues/19150
eq9 = [Eq(Derivative(f(t), t), 1/(a*b)*(-2*f(t) + g(t) + c)),
Eq(Derivative(g(t), t), 1/(a*b)*(-2*g(t) + f(t) + h(t))),
Eq(Derivative(h(t), t), 1/(a*b)*(-2*h(t) + g(t) + d))]
sol9 = [Eq(f(t), (-C1 + C2*exp(-sqrt(2)*t/(a*b)) + C3*exp(sqrt(2)*t/(a*b)) + exp(sqrt(2)*t/(a*b))*Integral(
c*exp(-sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b) + d*exp(-sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b), t) - Integral(
-c*exp(2*t/(a*b))/(2*a*b) + d*exp(2*t/(a*b))/(2*a*b), t) + exp(-sqrt(2)*t/(a*b))*Integral(
c*exp(sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b) + d*exp(sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b), t))*exp(
-2*t/(a*b))),
Eq(g(t), (-sqrt(2)*C2*exp(-sqrt(2)*t/(a*b)) + sqrt(2)*C3*exp(sqrt(2)*t/(a*b)) +
sqrt(2)*exp(sqrt(2)*t/(a*b))*Integral(c*exp(-sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b) + d*exp(-sqrt(2)*t/(a*b) +
2*t/(a*b))/(4*a*b), t) - sqrt(2)*exp(-sqrt(2)*t/(a*b))*Integral(c*exp(sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b) +
d*exp(sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b), t))*exp(-2*t/(a*b))),
Eq(h(t), (C1 + C2*exp(-sqrt(2)*t/(a*b)) +
C3*exp(sqrt(2)*t/(a*b)) + exp(sqrt(2)*t/(a*b))*Integral(c*exp(-sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b) +
d*exp(-sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b), t) + Integral(-c*exp(2*t/(a*b))/(2*a*b) + d*exp(2*t/(a*b))/(
2*a*b), t) + exp(-sqrt(2)*t/(a*b))*Integral(c*exp(sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b) + d*exp(
sqrt(2)*t/(a*b) + 2*t/(a*b))/(4*a*b), t))*exp(-2*t/(a*b)))]
assert dsolve(eq9) == sol9
assert checksysodesol(eq9, sol9) == (True, [0, 0, 0])
# Simpsol and Solsimp testing
_x1 = sqrt(2)
_x2 = exp(2*_x1*t/(a*b))
_x3 = 4*C3*_x2*a*b
_x4 = exp(2*t/(a*b))
_x5 = exp(_x1*t/(a*b))
_x6 = Integral(_x4*_x5, t)
_x7 = exp(-2*t/(a*b))
_x8 = exp(-_x1*t/(a*b))
_x9 = Integral(_x4*_x8, t)
_x10 = _x2*_x9*d
_x11 = 4*C2*a*b
sol9_simpsol = [
Eq(f(t), _x7*_x8*(-4*C1*_x5*a*b + _x10 + _x11 + _x2*_x9*c + _x3 + 2*_x5*c*Integral(_x4,
t) - 2*_x5*d*Integral(
_x4, t) + _x6*c + _x6*d)/(4*a*b)),
Eq(g(t), _x7*_x8*(
-4*C2*_x1*a*b + 4*C3*_x1*_x2*a*b + _x1*_x2*_x9*c + _x1*_x2*_x9*d - _x1*_x6*c - _x1*_x6*d)/(
4*a*b)),
Eq(h(t), _x7*_x8*(4*C1*_x5*a*b + _x10 + _x11 + _x2*_x9*c + _x3 - 2*_x5*c*Integral(_x4,
t) + 2*_x5*d*Integral(
_x4, t) + _x6*c + _x6*d)/(4*a*b)),
]
assert [_simpsol(s) for s in sol9] == sol9_simpsol
_x1 = sqrt(2)
_x2 = 1/b
_x3 = exp(_x2*t*(2 - _x1)/a)
_x4 = exp(_x2*t*(_x1 + 2)/a)
_x5 = exp(-2*_x2*t/a)
_x6 = exp(2*_x2*t/a)
_x7 = Integral(-_x2*_x6*c/(2*a) + _x2*_x6*d/(2*a), t)
_x8 = exp(_x2*t*(_x1 - 2)/a)
_x9 = exp(-_x2*t*(_x1 + 2)/a)
_x10 = Integral(_x2*_x3*c/(4*a) + _x2*_x3*d/(4*a), t)
_x11 = Integral(_x2*_x4*c/(4*a) + _x2*_x4*d/(4*a), t)
sol9_solsimp = [
Eq(f(t), -C1*_x5 + C2*_x9 + C3*_x8 + _x10*_x8 + _x11*_x9 - _x5*_x7),
Eq(g(t), -C2*_x1*_x9 + C3*_x1*_x8 + _x1*_x10*_x8 - _x1*_x11*_x9),
Eq(h(t), C1*_x5 + C2*_x9 + C3*_x8 + _x10*_x8 + _x11*_x9 + _x5*_x7),
]
assert [Eq(s.lhs, _solsimp(s.rhs, t)) for s in sol9] == sol9_solsimp
# Regression test case for issue #16635
# https://github.com/sympy/sympy/issues/16635
eq10 = [Eq(f(t).diff(t), f(t) - g(t) + 15*t - 10), Eq(g(t).diff(t), f(t) - g(t) - 15*t - 5)]
sol10 = [Eq(f(t), C1 + C2*t + C2 + t*Integral(30*t - 5, t) + Integral(30*t - 5, t) + Integral(-30*t**2 - 10*t - 5, t)),
Eq(g(t), C1 + C2*t + t*Integral(30*t - 5, t) + Integral(-30*t**2 - 10*t - 5, t))]
assert dsolve(eq10) == sol10
assert checksysodesol(eq10, sol10) == (True, [0, 0])
# Multiple equations
eq1 = [Eq(Derivative(f(t), t)**2 - 2*Derivative(f(t), t) + 1, 4),
Eq(-y*f(t) + Derivative(g(t), t), 0)]
sol1 = [[Eq(f(t), C1 + Integral(-1, t)),
Eq(g(t), C1*t*y + C2*y + t*y*Integral(-1, t) + y*Integral(t, t))],
[Eq(f(t), C1 + Integral(3, t)),
Eq(g(t), C1*t*y + C2*y + t*y*Integral(3, t) + y*Integral(-3*t, t))]]
assert dsolve(eq1) == sol1
for sol in sol1:
assert checksysodesol(eq1, sol) == (True, [0, 0])
# test case for issue #19831
# https://github.com/sympy/sympy/issues/19831
n = symbols('n', positive=True)
x0 = symbols('x_0')
t0 = symbols('t_0')
x_0 = symbols('x_0')
t_0 = symbols('t_0')
t = symbols('t')
x = Function('x')
y = Function('y')
T = symbols('T')
eq8 = (Eq(Derivative(y(t), t), x(t)),
Eq(Derivative(x(t), t), n*( y(t) + 1)))
sol = [
Eq(y(t),
(-((-T*sqrt(n)*exp(sqrt(n)*t_0)/2 - n*Integral(exp(sqrt(n)*t_0), t_0)/2 +
x_0*exp(sqrt(n)*t_0)/2)/sqrt(n) + Integral(n*exp(sqrt(n)*t)/2, t)/sqrt(n)))
*exp(-sqrt(n)*t) + (T*sqrt(n)*exp(-sqrt(n)*t_0)/2 - n*Integral(exp(-sqrt(n)*t_0)
, t_0)/2 + x_0*exp(-sqrt(n)*t_0)/2)*exp(sqrt(n)*t)/sqrt(n)
+ exp(sqrt(n)*t)*Integral(n*exp(-sqrt(n)*t)/2, t)/sqrt(n)
),
Eq(x(t),
(T*sqrt(n)*exp(-sqrt(n)*t_0)/2 - n*Integral(exp(-sqrt(n)*t_0), t_0)/2 +
x_0*exp(-sqrt(n)*t_0)/2)*exp(sqrt(n)*t) + (-T*sqrt(n)*exp(sqrt(n)*t_0)/2 -
n*Integral(exp(sqrt(n)*t_0), t_0)/2 + x_0*exp(sqrt(n)*t_0)/2 +
Integral(n*exp(sqrt(n)*t)/2, t))*exp(-sqrt(n)*t)+ exp(sqrt(n)*t)
*Integral(n*exp(-sqrt(n)*t)/2, t)
),
]
assert dsolve(eq8, ics={y(t0): T, x(t0): x0}) == sol
assert checksysodesol(eq8, sol) == (True, [0, 0])
def test_sysode_linear_neq_order1_type3():
f, g, h, k = symbols('f g h k', cls=Function)
x, t, a = symbols('x t a')
r = symbols('r', real=True)
eqs1 = [Eq(diff(f(r), r), f(r) + r*g(r)),
Eq(diff(g(r), r),-r*f(r) + g(r))]
sol1 = [Eq(f(r), (C1*sin(r**2/2) + C2*cos(r**2/2))*exp(r)), Eq(g(r), (C1*cos(r**2/2) - C2*sin(r**2/2))*exp(r))]
assert dsolve(eqs1) == sol1
assert checksysodesol(eqs1, sol1) == (True, [0, 0])
eqs2 = [Eq(diff(f(x), x), x*f(x) + x**2*g(x)),
Eq(diff(g(x), x), 2*x**2*f(x) + (x + 3*x**2)*g(x))]
sol2 = [Eq(f(x), (3*C1/17 + 4*C2/17 + (8*C1 - 12*C2)/(51 + 17*sqrt(17)))*exp(x**2*(3*x + sqrt(17)*x + 3)/6) + (13*C1/51 +
2*C2/17 + (16*C1 - 24*C2)/(-663 + 153*sqrt(17)))*exp(x**2*(-sqrt(17)*x + 3*x + 3)/6)),
Eq(g(x), (4*C1/17 - 6*C2/17 + (12*C1 + 16*C2)/(-51 + 17*sqrt(17)))*exp(x**2*(3*x + sqrt(17)*x + 3)/6) + (
13*C1/17 + 6*C2/17 + (-12*C1 - 16*C2)/(-51 + 17*sqrt(17)))*exp(x**2*(-sqrt(17)*x + 3*x + 3)/6))]
assert [_simpsol(s) for s in dsolve(eqs2)] == sol2
assert checksysodesol(eqs2, sol2) == (True, [0, 0])
eqs3 = [Eq(f(x).diff(x), x*f(x) + g(x)), Eq(g(x).diff(x), -f(x) + x*g(x))]
sol3 = [Eq(f(x), (C1/2 - I*C2/2)*exp(x**2/2 + I*x) + (C1/2 + I*C2/2)*exp(x**2/2 - I*x)),
Eq(g(x), (-I*C1/2 + C2/2)*exp(x**2/2 - I*x) + (I*C1/2 + C2/2)*exp(x**2/2 + I*x))]
assert dsolve(eqs3) == sol3
assert checksysodesol(eqs3, sol3) == (True, [0, 0])
eqs4 = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x))), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x))),
Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)))]
sol4 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)),
Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)),
Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2))]
assert dsolve(eqs4) == sol4
assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0])
eqs5 = [Eq(f(x).diff(x), x**2*(f(x) + g(x) + h(x))), Eq(g(x).diff(x), x**2*(f(x) + g(x) + h(x))),
Eq(h(x).diff(x), x**2*(f(x) + g(x) + h(x)))]
sol5 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3)),
Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3)),
Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3))]
assert dsolve(eqs5) == sol5
assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0])
eqs6 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x) + k(x))),
Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x) + k(x))),
Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x) + k(x))),
Eq(Derivative(k(x), x), x*(f(x) + g(x) + h(x) + k(x)))]
sol6 = [Eq(f(x), -C1/4 - C2/4 - C3/4 + 3*C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)),
Eq(g(x), 3*C1/4 - C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)),
Eq(h(x), -C1/4 + 3*C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)),
Eq(k(x), -C1/4 - C2/4 + 3*C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2))]
assert dsolve(eqs6) == sol6
assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0])
y = symbols("y", real=True)
eqs7 = [Eq(Derivative(f(y), y), y*f(y) + g(y)), Eq(Derivative(g(y), y), y*g(y) - f(y))]
sol7 = [Eq(f(y), (C1*sin(y) + C2*cos(y))*exp(y**2/2)), Eq(g(y), (C1*cos(y) - C2*sin(y))*exp(y**2/2))]
assert dsolve(eqs7) == sol7
assert checksysodesol(eqs7, sol7) == (True, [0, 0])
def test_sysode_linear_neq_order1_type4():
f, g, h, k = symbols('f g h k', cls=Function)
x, t, a = symbols('x t a')
r = symbols('r', real=True)
eqs1 = [Eq(diff(f(r), r), f(r) + r*g(r) + r**2), Eq(diff(g(r), r), -r*f(r) + g(r) + r)]
sol1 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2) + exp(r)*sin(r**2/2)*Integral(r**2*exp(-r)*sin(r**2/2) +
r*exp(-r)*cos(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r**2*exp(-r)*cos(r**2/2) - r*exp(-r)*sin(r**2/2), r)),
Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2) - exp(r)*sin(r**2/2)*Integral(r**2*exp(-r)*cos(r**2/2) -
r*exp(-r)*sin(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r**2*exp(-r)*sin(r**2/2) + r*exp(-r)*cos(r**2/2), r))]
assert dsolve(eqs1) == sol1
assert checksysodesol(eqs1, sol1) == (True, [0, 0])
eqs2 = [Eq(diff(f(r), r), f(r) + r*g(r) + r), Eq(diff(g(r), r), -r*f(r) + g(r) + log(r))]
sol2 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2) + exp(r)*sin(r**2/2)*Integral(r*exp(-r)*sin(r**2/2) +
exp(-r)*log(r)*cos(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r*exp(-r)*cos(r**2/2) - exp(-r)*log(r)*sin(
r**2/2), r)),
Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2) - exp(r)*sin(r**2/2)*Integral(r*exp(-r)*cos(r**2/2) -
exp(-r)*log(r)*sin(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r*exp(-r)*sin(r**2/2) + exp(-r)*log(r)*cos(
r**2/2), r))]
assert dsolve(eqs2) == sol2
assert checksysodesol(eqs2, sol2) == (True, [0, 0])
eqs3 = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x)) + x), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x)) + x),
Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)) + 1)]
_x1 = exp(-3*x**2/2)
_x2 = exp(3*x**2/2)
_x3 = Integral(2*_x1*x/3 + _x1/3 + x/3 - Rational(1, 3), x)
_x4 = Integral(2*_x1*x/3 + _x1/3 - 2*x/3 + Rational(2, 3), x)
sol3 = [
Eq(f(x),
C1*_x2/3 - C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 + 2*C3/3 + 2*_x2*_x3/3 + _x2*_x4/3 + _x3/3 - _x4/3),
Eq(g(x),
C1*_x2/3 + 2*C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 - C3/3 + 2*_x2*_x3/3 + _x2*_x4/3 + _x3/3 - _x4/3),
Eq(h(x),
C1*_x2/3 - C1/3 + C2*_x2/3 + 2*C2/3 + C3*_x2/3 - C3/3 + 2*_x2*_x3/3 + _x2*_x4/3 - 2*_x3/3 + 2*_x4/3),
]
assert dsolve(eqs3) == sol3
assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0])
eqs4 = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x)) + sin(x)), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x)) + sin(x)),
Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)) + sin(x))]
sol4 = [Eq(f(x), C1*exp(3*x**2/2)/3 - C1/3 + C2*exp(3*x**2/2)/3 - C2/3 + C3*exp(3*x**2/2)/3 + 2*C3/3 +
exp(3*x**2/2)*Integral(exp(-3*x**2/2)*sin(x), x)),
Eq(g(x), C1*exp(3*x**2/2)/3 + 2*C1/3 + C2*exp(3*x**2/2)/3 - C2/3 +
C3*exp(3*x**2/2)/3 - C3/3 + exp(3*x**2/2)*Integral(exp(-3*x**2/2)*sin(x), x)),
Eq(h(x), C1*exp(3*x**2/2)/3 - C1/3 + C2*exp(3*x**2/2)/3 + 2*C2/3 + C3*exp(3*x**2/2)/3 - C3/3 + exp(
3*x**2/2)*Integral(exp(-3*x**2/2)*sin(x), x))]
assert dsolve(eqs4) == sol4
assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0])
eqs5 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(g(x), x), x*(f(x) + g(x)
+ h(x) + k(x) + 1)), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(k(x),
x), x*(f(x) + g(x) + h(x) + k(x) + 1))]
sol5 = [Eq(f(x), C1*exp(2*x**2)/4 - C1/4 + C2*exp(2*x**2)/4 - C2/4 + C3*exp(2*x**2)/4 - C3/4 + C4*exp(2*x**2)/4 + 3*C4/4 +
exp(2*x**2)*Integral(x*exp(-2*x**2), x)),
Eq(g(x), C1*exp(2*x**2)/4 + 3*C1/4 + C2*exp(2*x**2)/4 - C2/4 +
C3*exp(2*x**2)/4 - C3/4 + C4*exp(2*x**2)/4 - C4/4 + exp(2*x**2)*Integral(x*exp(-2*x**2), x)),
Eq(h(x), C1*exp(2*x**2)/4 - C1/4 + C2*exp(2*x**2)/4 + 3*C2/4 + C3*exp(2*x**2)/4 - C3/4 + C4*exp(2*x**2)/4 - C4/4 +
exp(2*x**2)*Integral(x*exp(-2*x**2), x)),
Eq(k(x), C1*exp(2*x**2)/4 - C1/4 + C2*exp(2*x**2)/4 - C2/4 + C3*exp(2*x**2)/4
+ 3*C3/4 + C4*exp(2*x**2)/4 - C4/4 + exp(2*x**2)*Integral(x*exp(-2*x**2), x))]
assert dsolve(eqs5) == sol5
assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0, 0])
eqs6 = [Eq(Derivative(f(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(g(x), x), x**2*(f(x) +
g(x) + h(x) + k(x) + 1)), Eq(Derivative(h(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)),
Eq(Derivative(k(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1))]
sol6 = [Eq(f(x), C1*exp(4*x**3/3)/4 - C1/4 + C2*exp(4*x**3/3)/4 - C2/4 + C3*exp(4*x**3/3)/4 - C3/4 + C4*exp(4*x**3/3)/4 +
3*C4/4 + exp(4*x**3/3)*Integral(x**2*exp(-4*x**3/3), x)),
Eq(g(x), C1*exp(4*x**3/3)/4 + 3*C1/4 + C2*exp(4*x**3/3)/4 - C2/4 + C3*exp(4*x**3/3)/4 - C3/4 + C4*exp(
4*x**3/3)/4 - C4/4 + exp(4*x**3/3)*Integral(x**2*exp(-4*x**3/3), x)),
Eq(h(x), C1*exp(4*x**3/3)/4 - C1/4 + C2*exp(4*x**3/3)/4 + 3*C2/4 + C3*exp(4*x**3/3)/4 - C3/4 + C4*exp(
4*x**3/3)/4 - C4/4 + exp(4*x**3/3)*Integral(x**2*exp(-4*x**3/3), x)),
Eq(k(x), C1*exp(4*x**3/3)/4 - C1/4 + C2*exp(4*x**3/3)/4 - C2/4 +
C3*exp(4*x**3/3)/4 + 3*C3/4 + C4*exp(4*x**3/3)/4 - C4/4 + exp(4*x**3/3)*Integral(x**2*exp(-4*x**3/3), x))]
assert dsolve(eqs6) == sol6
assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0])
eqs7 = [Eq(Derivative(f(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x)), Eq(Derivative(g(x), x), (f(x) + g(x)
+ h(x))*log(x) + sin(x)), Eq(Derivative(h(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x))]
sol7 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3 + Integral(exp(-3*x*log(x) + 3*x)*sin(x), x))*exp(3*x*log(x) -
3*x)),
Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3 + Integral(exp(-3*x*log(x) + 3*x)*sin(x), x))*exp(3*x*log(x)
- 3*x)),
Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3 + Integral(exp(-3*x*log(x) + 3*x)*sin(x),
x))*exp(3*x*log(x) - 3*x))]
with dotprodsimp(True):
assert dsolve(eqs7) == sol7
assert checksysodesol(eqs7, sol7) == (True, [0, 0, 0])
eqs8 = [Eq(Derivative(f(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(g(x), x), (f(x)
+ g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(h(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) +
sin(x)), Eq(Derivative(k(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x))]
sol8 = [Eq(f(x), -C1/4 - C2/4 - C3/4 + 3*C4/4 + (C1/4 + C2/4 + C3/4 + C4/4 + Integral(exp(-4*x*log(x) + 4*x)*sin(x),
x))*exp(4*x*log(x) - 4*x)),
Eq(g(x), 3*C1/4 - C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4 + Integral(exp(-4*x*log(x)
+ 4*x)*sin(x), x))*exp(4*x*log(x) - 4*x)),
Eq(h(x), -C1/4 + 3*C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4 +
Integral(exp(-4*x*log(x) + 4*x)*sin(x), x))*exp(4*x*log(x) - 4*x)),
Eq(k(x), -C1/4 - C2/4 + 3*C3/4 - C4/4 + (C1/4 + C2/4
+ C3/4 + C4/4 + Integral(exp(-4*x*log(x) + 4*x)*sin(x), x))*exp(4*x*log(x) - 4*x))]
with dotprodsimp(True):
assert dsolve(eqs8) == sol8
assert checksysodesol(eqs8, sol8) == (True, [0, 0, 0, 0])
def test_component_division():
f, g, h, k = symbols('f g h k', cls=Function)
x = symbols("x")
funcs = [f(x), g(x), h(x), k(x)]
eqs1 = [Eq(Derivative(f(x), x), 2*f(x)),
Eq(Derivative(g(x), x), f(x)),
Eq(Derivative(h(x), x), h(x)),
Eq(Derivative(k(x), x), h(x)**4 + k(x))]
sol1 = [Eq(f(x), 2*C1*exp(2*x)),
Eq(g(x), C1*exp(2*x) + C2),
Eq(h(x), C3*exp(x)),
Eq(k(x), (C4 + Integral(C3**4*exp(3*x), x))*exp(x))]
components1 = {((Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), f(x)),)),
((Eq(Derivative(h(x), x), h(x)),), (Eq(Derivative(k(x), x), h(x)**4 + k(x)),))}
eqsdict1 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {h(x)}},
{f(x): Eq(Derivative(f(x), x), 2*f(x)),
g(x): Eq(Derivative(g(x), x), f(x)),
h(x): Eq(Derivative(h(x), x), h(x)),
k(x): Eq(Derivative(k(x), x), h(x)**4 + k(x))})
graph1 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), h(x))}]
assert {tuple(tuple(scc) for scc in wcc) for wcc in _component_division(eqs1, funcs, x)} == components1
assert _eqs2dict(eqs1, funcs) == eqsdict1
assert [set(element) for element in _dict2graph(eqsdict1[0])] == graph1
assert dsolve(eqs1) == sol1
assert checksysodesol(eqs1, sol1) == (True, [0, 0, 0, 0])
eqs2 = [Eq(Derivative(f(x), x), 2*f(x)),
Eq(Derivative(g(x), x), f(x)),
Eq(Derivative(h(x), x), h(x)),
Eq(Derivative(k(x), x), f(x)**4 + k(x))]
sol2 = [Eq(f(x), C1*exp(2*x)),
Eq(g(x), C2 + Integral(C1*exp(2*x), x)),
Eq(h(x), C3*exp(x)),
Eq(k(x), (C4 + Integral(C1**4*exp(7*x), x))*exp(x))]
components2 = {frozenset([(Eq(Derivative(f(x), x), 2*f(x)),),
(Eq(Derivative(g(x), x), f(x)),),
(Eq(Derivative(k(x), x), f(x)**4 + k(x)),)]),
frozenset([(Eq(Derivative(h(x), x), h(x)),)])}
eqsdict2 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {f(x)}},
{f(x): Eq(Derivative(f(x), x), 2*f(x)),
g(x): Eq(Derivative(g(x), x), f(x)),
h(x): Eq(Derivative(h(x), x), h(x)),
k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))})
graph2 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), f(x))}]
assert {frozenset(tuple(scc) for scc in wcc) for wcc in _component_division(eqs2, funcs, x)} == components2
assert _eqs2dict(eqs2, funcs) == eqsdict2
assert [set(element) for element in _dict2graph(eqsdict2[0])] == graph2
assert dsolve(eqs2) == sol2
assert checksysodesol(eqs2, sol2) == (True, [0, 0, 0, 0])
eqs3 = [Eq(Derivative(f(x), x), 2*f(x)),
Eq(Derivative(g(x), x), f(x) + x),
Eq(Derivative(h(x), x), h(x)),
Eq(Derivative(k(x), x), f(x)**4 + k(x))]
sol3 = [Eq(f(x), C1*exp(2*x)),
Eq(g(x), C2 + Integral(C1*exp(2*x) + x, x)),
Eq(h(x), C3*exp(x)),
Eq(k(x), (C4 + Integral(C1**4*exp(7*x), x))*exp(x))]
components3 = {frozenset([(Eq(Derivative(f(x), x), 2*f(x)),),
(Eq(Derivative(g(x), x), x + f(x)),),
(Eq(Derivative(k(x), x), f(x)**4 + k(x)),)]),
frozenset([(Eq(Derivative(h(x), x), h(x)),),])}
eqsdict3 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {f(x)}},
{f(x): Eq(Derivative(f(x), x), 2*f(x)),
g(x): Eq(Derivative(g(x), x), x + f(x)),
h(x): Eq(Derivative(h(x), x), h(x)),
k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))})
graph3 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), f(x))}]
assert {frozenset(tuple(scc) for scc in wcc) for wcc in _component_division(eqs3, funcs, x)} == components3
assert _eqs2dict(eqs3, funcs) == eqsdict3
assert [set(l) for l in _dict2graph(eqsdict3[0])] == graph3
assert dsolve(eqs3) == sol3
assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0, 0])
eqs4 = [Eq(Derivative(f(x), x), x*f(x) + 2*g(x)),
Eq(Derivative(g(x), x), f(x) + x*g(x) + x),
Eq(Derivative(h(x), x), h(x)),
Eq(Derivative(k(x), x), f(x)**4 + k(x))]
sol4 = [Eq(f(x), (C1/2 - sqrt(2)*C2/2 - sqrt(2)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 +\
sqrt(2)*x)/2, x)/2 + Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 +\
sqrt(2)*x)/2, x)/2)*exp(x**2/2 - sqrt(2)*x) + (C1/2 + sqrt(2)*C2/2 + sqrt(2)*Integral(x*exp(-x**2/2
- sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2
- sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2)*exp(x**2/2 + sqrt(2)*x)),
Eq(g(x), (-sqrt(2)*C1/4 + C2/2 + Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 -\
sqrt(2)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2,
x)/4)*exp(x**2/2 - sqrt(2)*x) + (sqrt(2)*C1/4 + C2/2 + Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 +
x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + sqrt(2)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 -
sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/4)*exp(x**2/2 + sqrt(2)*x)),
Eq(h(x), C3*exp(x)),
Eq(k(x), C4*exp(x) + exp(x)*Integral((C1*exp(x**2/2 - sqrt(2)*x)/2 + C1*exp(x**2/2 + sqrt(2)*x)/2 -
sqrt(2)*C2*exp(x**2/2 - sqrt(2)*x)/2 + sqrt(2)*C2*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*exp(x**2/2 -
sqrt(2)*x)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + exp(x**2/2 -
sqrt(2)*x)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2,
x)/2 + sqrt(2)*exp(x**2/2 + sqrt(2)*x)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 +
sqrt(2)*x)/2, x)/2 + exp(x**2/2 + sqrt(2)*x)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 -
sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2)**4*exp(-x), x))]
components4 = {(frozenset([Eq(Derivative(f(x), x), x*f(x) + 2*g(x)),
Eq(Derivative(g(x), x), x*g(x) + x + f(x))]),
frozenset([Eq(Derivative(k(x), x), f(x)**4 + k(x)),])),
(frozenset([Eq(Derivative(h(x), x), h(x)),]),)}
eqsdict4 = ({f(x): {g(x)}, g(x): {f(x)}, h(x): set(), k(x): {f(x)}},
{f(x): Eq(Derivative(f(x), x), x*f(x) + 2*g(x)),
g(x): Eq(Derivative(g(x), x), x*g(x) + x + f(x)),
h(x): Eq(Derivative(h(x), x), h(x)),
k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))})
graph4 = [{f(x), g(x), h(x), k(x)}, {(f(x), g(x)), (g(x), f(x)), (k(x), f(x))}]
assert {tuple(frozenset(scc) for scc in wcc) for wcc in _component_division(eqs4, funcs, x)} == components4
assert _eqs2dict(eqs4, funcs) == eqsdict4
assert [set(element) for element in _dict2graph(eqsdict4[0])] == graph4
assert dsolve(eqs4) == sol4
assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0, 0])
eqs5 = [Eq(Derivative(f(x), x), x*f(x) + 2*g(x)),
Eq(Derivative(g(x), x), x*g(x) + f(x)),
Eq(Derivative(h(x), x), h(x)),
Eq(Derivative(k(x), x), f(x)**4 + k(x))]
sol5 = [Eq(f(x), (C1/2 - sqrt(2)*C2/2)*exp(x**2/2 - sqrt(2)*x) + (C1/2 + sqrt(2)*C2/2)*exp(x**2/2 + sqrt(2)*x)),
Eq(g(x), (-sqrt(2)*C1/4 + C2/2)*exp(x**2/2 - sqrt(2)*x) + (sqrt(2)*C1/4 + C2/2)*exp(x**2/2 + sqrt(2)*x)),
Eq(h(x), C3*exp(x)),
Eq(k(x), C4*exp(x) + exp(x)*Integral((C1*exp(x**2/2 - sqrt(2)*x)/2 + C1*exp(x**2/2 + sqrt(2)*x)/2 -
sqrt(2)*C2*exp(x**2/2 - sqrt(2)*x)/2 + sqrt(2)*C2*exp(x**2/2 + sqrt(2)*x)/2)**4*exp(-x), x))]
components5 = {(frozenset([Eq(Derivative(f(x), x), x*f(x) + 2*g(x)),
Eq(Derivative(g(x), x), x*g(x) + f(x))]),
frozenset([Eq(Derivative(k(x), x), f(x)**4 + k(x)),])),
(frozenset([Eq(Derivative(h(x), x), h(x)),]),)}
eqsdict5 = ({f(x): {g(x)}, g(x): {f(x)}, h(x): set(), k(x): {f(x)}},
{f(x): Eq(Derivative(f(x), x), x*f(x) + 2*g(x)),
g(x): Eq(Derivative(g(x), x), x*g(x) + f(x)),
h(x): Eq(Derivative(h(x), x), h(x)),
k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))})
graph5 = [{f(x), g(x), h(x), k(x)}, {(f(x), g(x)), (g(x), f(x)), (k(x), f(x))}]
assert {tuple(frozenset(scc) for scc in wcc) for wcc in _component_division(eqs5, funcs, x)} == components5
assert _eqs2dict(eqs5, funcs) == eqsdict5
assert [set(element) for element in _dict2graph(eqsdict5[0])] == graph5
assert dsolve(eqs5) == sol5
assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0, 0])
def test_linodesolve():
t, x, a = symbols("t x a")
f, g, h = symbols("f g h", cls=Function)
# Testing the Errors
raises(ValueError, lambda: linodesolve(1, t))
raises(ValueError, lambda: linodesolve(a, t))
A1 = Matrix([[1, 2], [2, 4], [4, 6]])
raises(NonSquareMatrixError, lambda: linodesolve(A1, t))
A2 = Matrix([[1, 2, 1], [3, 1, 2]])
raises(NonSquareMatrixError, lambda: linodesolve(A2, t))
# Testing auto functionality
func = [f(t), g(t)]
eq = [Eq(f(t).diff(t) + g(t).diff(t), g(t)), Eq(g(t).diff(t), f(t))]
ceq = canonical_odes(eq, func, t)
(A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1)
A = A0
sol = [C1*(-Rational(1, 2) + sqrt(5)/2)*exp(t*(-Rational(1, 2) + sqrt(5)/2)) + C2*(-sqrt(5)/2 - Rational(1, 2))*
exp(t*(-sqrt(5)/2 - Rational(1, 2))),
C1*exp(t*(-Rational(1, 2) + sqrt(5)/2)) + C2*exp(t*(-sqrt(5)/2 - Rational(1, 2)))]
assert constant_renumber(linodesolve(A, t), variables=Tuple(*eq).free_symbols) == sol
# Testing the Errors
raises(ValueError, lambda: linodesolve(1, t, b=Matrix([t+1])))
raises(ValueError, lambda: linodesolve(a, t, b=Matrix([log(t) + sin(t)])))
raises(ValueError, lambda: linodesolve(Matrix([7]), t, b=t**2))
raises(ValueError, lambda: linodesolve(Matrix([a+10]), t, b=log(t)*cos(t)))
raises(ValueError, lambda: linodesolve(7, t, b=t**2))
raises(ValueError, lambda: linodesolve(a, t, b=log(t) + sin(t)))
A1 = Matrix([[1, 2], [2, 4], [4, 6]])
b1 = Matrix([t, 1, t**2])
raises(NonSquareMatrixError, lambda: linodesolve(A1, t, b=b1))
A2 = Matrix([[1, 2, 1], [3, 1, 2]])
b2 = Matrix([t, t**2])
raises(NonSquareMatrixError, lambda: linodesolve(A2, t, b=b2))
raises(ValueError, lambda: linodesolve(A1[:2, :], t, b=b1))
raises(ValueError, lambda: linodesolve(A1[:2, :], t, b=b1[:1]))
# DOIT check
A1 = Matrix([[1, -1], [1, -1]])
b1 = Matrix([15*t - 10, -15*t - 5])
sol1 = [C1 + C2*t + C2 - 10*t**3 + 10*t**2 + t*(15*t**2 - 5*t) - 10*t,
C1 + C2*t - 10*t**3 - 5*t**2 + t*(15*t**2 - 5*t) - 5*t]
assert constant_renumber(linodesolve(A1, t, b=b1, type="type2", doit=True),
variables=[t]) == sol1
# Testing auto functionality
func = [f(t), g(t)]
eq = [Eq(f(t).diff(t) + g(t).diff(t), g(t) + t), Eq(g(t).diff(t), f(t))]
ceq = canonical_odes(eq, func, t)
(A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1)
A = A0
sol = [-C1*exp(-t/2 + sqrt(5)*t/2)/2 + sqrt(5)*C1*exp(-t/2 + sqrt(5)*t/2)/2 - sqrt(5)*C2*exp(-sqrt(5)*t/2
- t/2)/2 - C2*exp(-sqrt(5)*t/2 - t/2)/2 - exp(-t/2 +
sqrt(5)*t/2)*Integral(sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/5, t)/2 + sqrt(5)*exp(-t/2 +
sqrt(5)*t/2)*Integral(sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/5, t)/2 - sqrt(5)*exp(-sqrt(5)*t/2 -
t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)/2 - exp(-sqrt(5)*t/2 -
t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)/2,
C1*exp(-t/2 + sqrt(5)*t/2) +
C2*exp(-sqrt(5)*t/2 - t/2) + exp(-t/2 + sqrt(5)*t/2)*Integral(sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/5,
t) + exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)]
assert constant_renumber(linodesolve(A, t, b=b), variables=[t]) == sol
# non-homogeneous term assumed to be 0
sol1 = [-C1*exp(-t/2 + sqrt(5)*t/2)/2 + sqrt(5)*C1*exp(-t/2 + sqrt(5)*t/2)/2 - sqrt(5)*C2*exp(-sqrt(5)*t/2
- t/2)/2 - C2*exp(-sqrt(5)*t/2 - t/2)/2 - exp(-t/2 + sqrt(5)*t/2)*Integral(0, t)/2 +
sqrt(5)*exp(-t/2 + sqrt(5)*t/2)*Integral(0, t)/2 - sqrt(5)*exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)/2
- exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)/2,
C1*exp(-t/2 + sqrt(5)*t/2) + C2*exp(-sqrt(5)*t/2 - t/2)
+ exp(-t/2 + sqrt(5)*t/2)*Integral(0, t) + exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)]
assert constant_renumber(linodesolve(A, t, type="type2"), variables=[t]) == sol1
# Testing the Errors
raises(ValueError, lambda: linodesolve(t+10, t))
raises(ValueError, lambda: linodesolve(a*t, t))
A1 = Matrix([[1, t], [-t, 1]])
B1, _ = _is_commutative_anti_derivative(A1, t)
raises(NonSquareMatrixError, lambda: linodesolve(A1[:, :1], t, B=B1))
raises(ValueError, lambda: linodesolve(A1, t, B=1))
A2 = Matrix([[t, t, t], [t, t, t], [t, t, t]])
B2, _ = _is_commutative_anti_derivative(A2, t)
raises(NonSquareMatrixError, lambda: linodesolve(A2, t, B=B2[:2, :]))
raises(ValueError, lambda: linodesolve(A2, t, B=2))
raises(ValueError, lambda: linodesolve(A2, t, B=B2, type="type31"))
raises(ValueError, lambda: linodesolve(A1, t, B=B2))
raises(ValueError, lambda: linodesolve(A2, t, B=B1))
# Testing auto functionality
func = [f(t), g(t)]
eq = [Eq(f(t).diff(t), f(t) + t*g(t)), Eq(g(t).diff(t), -t*f(t) + g(t))]
ceq = canonical_odes(eq, func, t)
(A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1)
A = A0
sol = [(C1/2 - I*C2/2)*exp(I*t**2/2 + t) + (C1/2 + I*C2/2)*exp(-I*t**2/2 + t),
(-I*C1/2 + C2/2)*exp(-I*t**2/2 + t) + (I*C1/2 + C2/2)*exp(I*t**2/2 + t)]
assert constant_renumber(linodesolve(A, t), variables=Tuple(*eq).free_symbols) == sol
assert constant_renumber(linodesolve(A, t, type="type3"), variables=Tuple(*eq).free_symbols) == sol
A1 = Matrix([[t, 1], [t, -1]])
raises(NotImplementedError, lambda: linodesolve(A1, t))
# Testing the Errors
raises(ValueError, lambda: linodesolve(t+10, t, b=Matrix([t+1])))
raises(ValueError, lambda: linodesolve(a*t, t, b=Matrix([log(t) + sin(t)])))
raises(ValueError, lambda: linodesolve(Matrix([7*t]), t, b=t**2))
raises(ValueError, lambda: linodesolve(Matrix([a + 10*log(t)]), t, b=log(t)*cos(t)))
raises(ValueError, lambda: linodesolve(7*t, t, b=t**2))
raises(ValueError, lambda: linodesolve(a*t**2, t, b=log(t) + sin(t)))
A1 = Matrix([[1, t], [-t, 1]])
b1 = Matrix([t, t ** 2])
B1, _ = _is_commutative_anti_derivative(A1, t)
raises(NonSquareMatrixError, lambda: linodesolve(A1[:, :1], t, b=b1))
A2 = Matrix([[t, t, t], [t, t, t], [t, t, t]])
b2 = Matrix([t, 1, t**2])
B2, _ = _is_commutative_anti_derivative(A2, t)
raises(NonSquareMatrixError, lambda: linodesolve(A2[:2, :], t, b=b2))
raises(ValueError, lambda: linodesolve(A1, t, b=b2))
raises(ValueError, lambda: linodesolve(A2, t, b=b1))
raises(ValueError, lambda: linodesolve(A1, t, b=b1, B=B2))
raises(ValueError, lambda: linodesolve(A2, t, b=b2, B=B1))
# Testing auto functionality
func = [f(x), g(x), h(x)]
eq = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x)) + x),
Eq(g(x).diff(x), x*(f(x) + g(x) + h(x)) + x),
Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)) + 1)]
ceq = canonical_odes(eq, func, x)
(A1, A0), b = linear_ode_to_matrix(ceq[0], func, x, 1)
A = A0
_x1 = exp(-3*x**2/2)
_x2 = exp(3*x**2/2)
_x3 = Integral(2*_x1*x/3 + _x1/3 + x/3 - Rational(1, 3), x)
_x4 = 2*_x2*_x3/3
_x5 = Integral(2*_x1*x/3 + _x1/3 - 2*x/3 + Rational(2, 3), x)
sol = [
C1*_x2/3 - C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 + 2*C3/3 + _x2*_x5/3 + _x3/3 + _x4 - _x5/3,
C1*_x2/3 + 2*C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 - C3/3 + _x2*_x5/3 + _x3/3 + _x4 - _x5/3,
C1*_x2/3 - C1/3 + C2*_x2/3 + 2*C2/3 + C3*_x2/3 - C3/3 + _x2*_x5/3 - 2*_x3/3 + _x4 + 2*_x5/3,
]
assert constant_renumber(linodesolve(A, x, b=b), variables=Tuple(*eq).free_symbols) == sol
assert constant_renumber(linodesolve(A, x, b=b, type="type4"),
variables=Tuple(*eq).free_symbols) == sol
A1 = Matrix([[t, 1], [t, -1]])
raises(NotImplementedError, lambda: linodesolve(A1, t, b=b1))
# non-homogeneous term not passed
sol1 = [-C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2),
-C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)]
assert constant_renumber(linodesolve(A, x, type="type4", doit=True), variables=Tuple(*eq).free_symbols) == sol1
@slow
def test_linear_3eq_order1_type4_slow():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
f = t ** 3 + log(t)
g = t ** 2 + sin(t)
eq1 = (Eq(diff(x(t), t), (4 * f + g) * x(t) - f * y(t) - 2 * f * z(t)),
Eq(diff(y(t), t), 2 * f * x(t) + (f + g) * y(t) - 2 * f * z(t)), Eq(diff(z(t), t), 5 * f * x(t) + f * y(
t) + (-3 * f + g) * z(t)))
with dotprodsimp(True):
dsolve(eq1)
@slow
def test_linear_neq_order1_type2_slow1():
i, r1, c1, r2, c2, t = symbols('i, r1, c1, r2, c2, t')
x1 = Function('x1')
x2 = Function('x2')
eq1 = r1*c1*Derivative(x1(t), t) + x1(t) - x2(t) - r1*i
eq2 = r2*c1*Derivative(x1(t), t) + r2*c2*Derivative(x2(t), t) + x2(t) - r2*i
eq = [eq1, eq2]
_x1 = sqrt(
c1**2*r1**2 + 2*c1**2*r1*r2 + c1**2*r2**2 - 2*c1*c2*r1*r2 + 2*c1*c2*r2**2 + c2**2*r2**2)
_x2 = -_x1*t/(2*c1*c2*r1*r2)
_x3 = 1/(_x1 - c1*r1 - c1*r2 + c2*r2)
_x4 = 1/(_x1 + c1*r1 + c1*r2 - c2*r2)
_x5 = 1/(2*_x3*c1*c2*r2 + 2*_x4*c1*c2*r2)
_x6 = Integral(_x5*i*exp(_x2 + t/(2*c2*r2) + t/(2*c2*r1) + t/(2*c1*r1)), t)
_x7 = Integral(
-_x5*i*exp(_x1*t/(2*c1*c2*r1*r2) + t/(2*c2*r2) + t/(2*c2*r1) + t/(2*c1*r1)),
t)
_x8 = exp(_x1*t/(2*c1*c2*r1*r2) - t/(2*c2*r2) - t/(2*c2*r1) - t/(2*c1*r1))
_x9 = exp(_x2 - t/(2*c2*r2) - t/(2*c2*r1) - t/(2*c1*r1))
sol = [
Eq(x1(t),
2*C1*_x3*_x8*c2*r2 - 2*C2*_x4*_x9*c2*r2 + 2*_x3*_x6*_x8*c2*r2 - 2*_x4*_x7*_x9*c2*r2),
Eq(x2(t), C1*_x8 + C2*_x9 + _x6*_x8 + _x7*_x9),
]
assert dsolve(eq) == sol
assert checksysodesol(eq, sol) == (True, [0, 0])
def _de_lorentz_solution():
m = Symbol("m", real=True)
q = Symbol("q", real=True)
t = Symbol("t", real=True)
e1, e2, e3 = symbols("e1:4", real=True)
b1, b2, b3 = symbols("b1:4", real=True)
v1, v2, v3 = symbols("v1:4", cls=Function, real=True)
eqs = [
-e1*q + m*Derivative(v1(t), t) - q*(-b2*v3(t) + b3*v2(t)),
-e2*q + m*Derivative(v2(t), t) - q*(b1*v3(t) - b3*v1(t)),
-e3*q + m*Derivative(v3(t), t) - q*(-b1*v2(t) + b2*v1(t))
]
# The code for the solution here is made using
# printsol from https://github.com/sympy/sympy/issues/19574
_x1 = 1/m
_x2 = b1**2
_x3 = b2**2
_x4 = b3**2
_x5 = sqrt(-_x2 - _x3 - _x4)
_x6 = exp(2*_x1*_x5*q*t)
_x7 = exp(_x1*_x5*q*t)
_x8 = 1/(-_x2*_x7*b3 - _x3*_x7*b3)
_x9 = sqrt(_x2 + _x3 + _x4)
_x10 = 1/(_x2*m + _x3*m + _x4*m)
_x11 = Integral(_x10*_x4*e3*q + _x10*b1*b3*e1*q + _x10*b2*b3*e2*q, t)
_x12 = b1**3
_x13 = b2**3
_x14 = 1/(-2*I*_x2*_x7*_x9*m - 2*I*_x3*_x7*_x9*m - 2*I*_x4*_x7*_x9*m)
_x15 = Integral(
_x12*_x14*e2*q - _x13*_x14*e1*q - I*_x14*_x2*_x9*e3*q - _x14*_x2*b2*e1*q - I*_x14*_x3*_x9*e3*q + _x14*_x3*b1*e2*q + _x14*_x4*b1*e2*q - _x14*_x4*b2*e1*q + I*_x14*_x9*b1*b3*e1*q + I*_x14*_x9*b2*b3*e2*q,
t)
_x16 = 1/(
-2*_x12*b3*m - 2*I*_x13*_x9*m - 2*I*_x2*_x9*b2*m - 2*_x3*b1*b3*m - 2*I*_x4*_x9*b2*m - 2*b1*b3**3*m)
_x17 = Integral(
-_x12*_x16*_x7*b2*e2*q - _x12*_x16*_x7*b3*e3*q - I*_x13*_x16*_x7*_x9*e3*q - _x13*_x16*_x7*b1*e2*q + _x16*_x2*_x3*_x7*e1*q + _x16*_x2*_x4*_x7*e1*q - I*_x16*_x2*_x7*_x9*b2*e3*q + I*_x16*_x2*_x7*_x9*b3*e2*q + _x16*_x3*_x4*_x7*e1*q + I*_x16*_x3*_x7*_x9*b3*e2*q - _x16*_x3*_x7*b1*b3*e3*q + _x16*_x7*b2**4*e1*q,
t)
_x18 = 1/(_x2*_x7*b3 + _x3*_x7*b3)
sol = [
Eq(v1(t),
-C1*_x18*_x4*b1 - I*C1*_x18*_x9*b2*b3 + C2*_x12*_x18*_x7 + C2*_x18*_x3*_x7*b1 - C3*_x18*_x4*_x6*b1 + I*C3*_x18*_x6*_x9*b2*b3 + _x11*_x12*_x18*_x7 + _x11*_x18*_x3*_x7*b1 - _x15*_x18*_x4*_x6*b1 + I*_x15*_x18*_x6*_x9*b2*b3 - _x17*_x18*_x4*b1 - I*_x17*_x18*_x9*b2*b3),
Eq(v2(t),
C1*_x4*_x8*b2 - I*C1*_x8*_x9*b1*b3 - C2*_x13*_x7*_x8 - C2*_x2*_x7*_x8*b2 + C3*_x4*_x6*_x8*b2 + I*C3*_x6*_x8*_x9*b1*b3 - _x11*_x13*_x7*_x8 - _x11*_x2*_x7*_x8*b2 + _x15*_x4*_x6*_x8*b2 + I*_x15*_x6*_x8*_x9*b1*b3 + _x17*_x4*_x8*b2 - I*_x17*_x8*_x9*b1*b3),
Eq(v3(t), C2 + C3*_x7 + _x11 + _x15*_x7 + (C1 + _x17)*exp(-_x1*_x5*q*t)),
]
return eqs, sol
# Regression test case for issue #9204
# https://github.com/sympy/sympy/issues/9204
# A very big solution is obtained for this
# test case. To be simplified in future.
@slow
def test_linear_new_order1_type2_de_lorentz():
if ON_TRAVIS:
skip("Too slow for travis.")
eqs, sol = _de_lorentz_solution()
with dotprodsimp(True):
assert dsolve(eqs) == sol
@slow
def test_linear_new_order1_type2_de_lorentz_slow_check():
if ON_TRAVIS:
skip("Too slow for travis.")
eqs, sol = _de_lorentz_solution()
assert checksysodesol(eqs, sol) == (True, [0, 0, 0])
def _neq_order1_type2_slow():
RC, t, C, Vs, L, R1, V0, I0 = symbols("RC t C Vs L R1 V0 I0")
V = Function("V")
I = Function("I")
system = [Eq(V(t).diff(t), -1/RC*V(t) + I(t)/C), Eq(I(t).diff(t), -R1/L*I(t) - 1/L*V(t) + Vs/L)]
z1 = sqrt(C**2*L**2 - 2*C**2*L*R1*RC + C**2*R1**2*RC**2 - 4*C*L*RC**2)
z2 = 1/(C*L - C*R1*RC - z1)
z3 = 1/(C*L - C*R1*RC + z1)
z4 = exp(-t/(2*RC) - R1*t/(2*L) + t*z1/(2*C*L*RC))
z5 = exp(-t/(2*RC) - R1*t/(2*L) - t*z1/(2*C*L*RC))
z6 = Integral(2*RC*Vs*exp(t/(2*RC) + R1*t/(2*L) +
t*z1/(2*C*L*RC))/(-2*C*L**2*RC*z2 + 2*C*L**2*RC*z3 + 2*C*L*R1*RC**2*z2
- 2*C*L*R1*RC**2*z3 - 2*L*RC*z1*z2 + 2*L*RC*z1*z3), t)
z7 = Integral(-2*RC*Vs*exp(t/(2*RC) + R1*t/(2*L) -
t*z1/(2*C*L*RC))/(-2*C*L**2*RC*z2 + 2*C*L**2*RC*z3 + 2*C*L*R1*RC**2*z2
- 2*C*L*R1*RC**2*z3 + 2*L*RC*z1*z2 - 2*L*RC*z1*z3), t)
sol = [
Eq(V(t), 2*C1*L*RC*z2*z5 + 2*C2*L*RC*z3*z4 + 2*L*RC*z2*z5*z6 + 2*L*RC*z3*z4*z7),
Eq(I(t), C1*z5 + C2*z4 + z4*z7 + z5*z6),
]
return system, sol
# A very big solution is obtained for this
# test case. To be simplified in future.
def test_linear_neq_order1_type2_slow():
system, sol = _neq_order1_type2_slow()
assert dsolve(system) == sol
# Regression test case for issue #14001
# https://github.com/sympy/sympy/issues/14001
@slow
def test_linear_neq_order1_type2_slow_check():
if ON_TRAVIS:
skip("Too slow for travis.")
system, sol = _neq_order1_type2_slow()
assert checksysodesol(system, sol) == (True, [0, 0])
def _linear_3eq_order1_type4_long():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
f = t ** 3 + log(t)
g = t ** 2 + sin(t)
eq1 = (Eq(diff(x(t), t), (4*f + g)*x(t) - f*y(t) - 2*f*z(t)),
Eq(diff(y(t), t), 2*f*x(t) + (f + g)*y(t) - 2*f*z(t)), Eq(diff(z(t), t), 5*f*x(t) + f*y(
t) + (-3*f + g)*z(t)))
dsolve_sol = dsolve(eq1)
dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol]
x_1 = sqrt(-t**6 - 8*t**3*log(t) + 8*t**3 - 16*log(t)**2 + 32*log(t) - 16)
x_2 = sqrt(3)
x_3 = 8324372644*C1*x_1*x_2 + 4162186322*C2*x_1*x_2 - 8324372644*C3*x_1*x_2
x_4 = 1 / (1903457163*t**3 + 3825881643*x_1*x_2 + 7613828652*log(t) - 7613828652)
x_5 = exp(t**3/3 + t*x_1*x_2/4 - cos(t))
x_6 = exp(t**3/3 - t*x_1*x_2/4 - cos(t))
x_7 = exp(t**4/2 + t**3/3 + 2*t*log(t) - 2*t - cos(t))
x_8 = 91238*C1*x_1*x_2 + 91238*C2*x_1*x_2 - 91238*C3*x_1*x_2
x_9 = 1 / (66049*t**3 - 50629*x_1*x_2 + 264196*log(t) - 264196)
x_10 = 50629 * C1 / 25189 + 37909*C2/25189 - 50629*C3/25189 - x_3*x_4
x_11 = -50629*C1/25189 - 12720*C2/25189 + 50629*C3/25189 + x_3*x_4
sol = [Eq(x(t), x_10*x_5 + x_11*x_6 + x_7*(C1 - C2)), Eq(y(t), x_10*x_5 + x_11*x_6), Eq(z(t), x_5*(
-424*C1/257 - 167*C2/257 + 424*C3/257 - x_8*x_9) + x_6*(167*C1/257 + 424*C2/257 -
167*C3/257 + x_8*x_9) + x_7*(C1 - C2))]
assert dsolve_sol1 == sol
assert checksysodesol(eq1, dsolve_sol1) == (True, [0, 0, 0])
def _neq_order1_type4_slow1():
f, g = symbols("f, g", cls=Function)
x = Symbol("x")
eqs = [Eq(diff(f(x), x), x*f(x) + x**2*g(x) + x),
Eq(diff(g(x), x), 2*x**2*f(x) + (x + 3*x**2)*g(x) + 1)]
_x1 = sqrt(17)
_x2 = 1/(45*_x1 + 187)
_x3 = 1/(161*_x1 + 663)
_x4 = 1/(51*_x1 - 221)
_x5 = 1/(161*_x1 - 663)
_x6 = -x**3/2
_x7 = _x1*x**3/6
_x8 = exp(_x6 + _x7 - x**2/2)
_x9 = -_x1*x**3/6
_x10 = exp(_x6 + _x9 - x**2/2)
_x11 = Integral(
22*_x1*_x10*_x3*x + 39*_x1*_x10*_x3 + 139*_x1*_x3*_x8*x - 39*_x1*_x3*_x8 + 90*_x10*_x3*x + 161*_x10*_x3 + 573*_x3*_x8*x - 161*_x3*_x8,
x)
_x12 = exp(_x9 + x**3/2 + x**2/2)
_x13 = exp(_x7 + x**3/2 + x**2/2)
_x14 = Integral(
22*_x1*_x10*_x2*x + 39*_x1*_x10*_x2 - 22*_x1*_x2*_x8*x + 6*_x1*_x2*_x8 + 90*_x10*_x2*x + 161*_x10*_x2 - 90*_x2*_x8*x + 26*_x2*_x8,
x)
sol = [
Eq(f(x), _x12*(
39*C1*_x1*_x5 - 161*C1*_x5 + 22*C2*_x1*_x5 - 90*C2*_x5 + 22*_x1*_x11*_x5 + 39*_x1*_x14*_x5 - 90*_x11*_x5 - 161*_x14*_x5) + _x13*(
-39*C1*_x1*_x5 + 161*C1*_x5 + 139*C2*_x1*_x5 - 573*C2*_x5 + 139*_x1*_x11*_x5 - 39*_x1*_x14*_x5 - 573*_x11*_x5 + 161*_x14*_x5)),
Eq(g(x), _x12*(
45*C1*_x1*_x4 - 187*C1*_x4 + 26*C2*_x1*_x4 - 102*C2*_x4 + 26*_x1*_x11*_x4 + 45*_x1*_x14*_x4 - 102*_x11*_x4 - 187*_x14*_x4) + _x13*(
6*C1*_x1*_x4 - 34*C1*_x4 - 26*C2*_x1*_x4 + 102*C2*_x4 - 26*_x1*_x11*_x4 + 6*_x1*_x14*_x4 + 102*_x11*_x4 - 34*_x14*_x4)),
]
return eqs, sol
def test_neq_order1_type4_slow1():
eqs, sol = _neq_order1_type4_slow1()
with dotprodsimp(True):
assert dsolve(eqs) == sol
@slow
def test_neq_order1_type4_slow_check1():
if ON_TRAVIS:
skip("Too slow for travis.")
eqs, sol = _neq_order1_type4_slow1()
assert checksysodesol(eqs, sol) == (True, [0, 0])
def _neq_order1_type4_slow2():
f, g, h = symbols("f, g, h", cls=Function)
x = Symbol("x")
eqs = [Eq(Derivative(f(x), x), x*h(x) + f(x) + g(x) + 1), Eq(Derivative(g(x), x), x*g(x) + f(x) + h(x) +
10), Eq(Derivative(h(x), x), x*f(x) + x + g(x) + h(x))]
_x1 = -x**2/2
_x2 = Integral(x*exp(_x1 - 2*x)/3 - x*exp(_x1 + x)/3 + 11*exp(_x1 - 2*x)/3 + 19*exp(_x1 + x)/3,
x)
_x3 = Integral(x*exp(_x1 - 2*x)/3 + x*exp(_x1 + x)/6 - x*exp(x**2/2 - x)/2 + 11*exp(
_x1 - 2*x)/3 - 19*exp(_x1 + x)/6 + exp(x**2/2 - x)/2, x)
_x4 = Integral(x*exp(_x1 - 2*x)/3 + x*exp(_x1 + x)/6 + x*exp(x**2/2 - x)/2 + 11*exp(
_x1 - 2*x)/3 - 19*exp(_x1 + x)/6 - exp(x**2/2 - x)/2, x)
_x5 = (C1/3 + C2/3 + C3/3 + _x2/3 + _x3/3 + _x4/3)*exp(x**2/2 + 2*x)
sol = [
Eq(f(x), _x5 + (-C1/2 + C2/2 + _x3/2 - _x4/2)*exp(_x1 + x) + (
C1/6 + C2/6 - C3/3 - _x2/3 + _x3/6 + _x4/6)*exp(x**2/2 - x)),
Eq(g(x), _x5 + (-C1/3 - C2/3 + 2*C3/3 + 2*_x2/3 - _x3/3 - _x4/3)*exp(x**2/2 - x)),
Eq(h(x), _x5 + (C1/2 - C2/2 - _x3/2 + _x4/2)*exp(_x1 + x) + (
C1/6 + C2/6 - C3/3 - _x2/3 + _x3/6 + _x4/6)*exp(x**2/2 - x)),
]
return eqs, sol
def test_neq_order1_type4_slow2():
eqs, sol = _neq_order1_type4_slow2()
with dotprodsimp(True):
assert dsolve(eqs) == sol
@slow
def test_neq_order1_type4_slow_check2():
eqs, sol = _neq_order1_type4_slow2()
assert checksysodesol(eqs, sol) == (True, [0, 0, 0])
def _neq_order1_type4_slow3():
f, g = symbols("f g", cls=Function)
x = symbols("x")
eqs = [Eq(Derivative(f(x), x), x*f(x) + g(x) + sin(x)), Eq(Derivative(g(x), x), x**2 + x*g(x) - f(x))]
_x1 = exp(x**2/2 + I*x)
_x2 = exp(-x**2/2 + I*x)
_x3 = exp(-x**2/2 - I*x)
_x4 = Integral(_x2*x**2/2 - I*_x2*sin(x)/2 + _x3*x**2/2 + I*_x3*sin(x)/2, x)
_x5 = Integral(I*_x2*x**2/2 + _x2*sin(x)/2 - I*_x3*x**2/2 + _x3*sin(x)/2, x)
sol = [
Eq(f(x),
_x1*(C1/2 - I*C2/2 - I*_x4/2 + _x5/2) + (C1/2 + I*C2/2 + I*_x4/2 + _x5/2)*exp(
x**2/2 - I*x)),
Eq(g(x),
_x1*(I*C1/2 + C2/2 + _x4/2 + I*_x5/2) + (-I*C1/2 + C2/2 + _x4/2 - I*_x5/2)*exp(
x**2/2 - I*x)),
]
return eqs, sol
def test_neq_order1_type4_slow3():
eqs, sol = _neq_order1_type4_slow3()
assert dsolve(eqs) == sol
@slow
def test_neq_order1_type4_slow_check3():
eqs, sol = _neq_order1_type4_slow3()
assert checksysodesol(eqs, sol) == (True, [0, 0])
@XFAIL
@slow
def test_linear_3eq_order1_type4_long_dsolve_slow_xfail():
if ON_TRAVIS:
skip("Too slow for travis.")
eq, sol = _linear_3eq_order1_type4_long()
dsolve_sol = dsolve(eq)
dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol]
assert dsolve_sol1 == sol
@slow
def test_linear_3eq_order1_type4_long_dsolve_dotprodsimp():
if ON_TRAVIS:
skip("Too slow for travis.")
eq, sol = _linear_3eq_order1_type4_long()
# XXX: Only works with dotprodsimp see
# test_linear_3eq_order1_type4_long_dsolve_slow_xfail which is too slow
with dotprodsimp(True):
dsolve_sol = dsolve(eq)
dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol]
assert dsolve_sol1 == sol
@slow
def test_linear_3eq_order1_type4_long_check():
if ON_TRAVIS:
skip("Too slow for travis.")
eq, sol = _linear_3eq_order1_type4_long()
assert checksysodesol(eq, sol) == (True, [0, 0, 0])
def test_dsolve_system():
f, g = symbols("f g", cls=Function)
x = symbols("x")
eqs = [Eq(f(x).diff(x), f(x) + g(x)), Eq(g(x).diff(x), f(x) + g(x))]
funcs = [f(x), g(x)]
sol = [[Eq(f(x), -C1 + C2*exp(2*x)), Eq(g(x), C1 + C2*exp(2*x))]]
assert dsolve_system(eqs, funcs=funcs, t=x, doit=True) == sol
raises(ValueError, lambda: dsolve_system(1))
raises(ValueError, lambda: dsolve_system(eqs, 1))
raises(ValueError, lambda: dsolve_system(eqs, funcs, 1))
raises(ValueError, lambda: dsolve_system(eqs, funcs[:1], x))
eq = (Eq(f(x).diff(x), 12 * f(x) - 6 * g(x)), Eq(g(x).diff(x) ** 2, 11 * f(x) + 3 * g(x)))
raises(NotImplementedError, lambda: dsolve_system(eq) == ([], []))
raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)]) == ([], []))
raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], t=x) == ([], []))
raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], t=x, ics={f(0): 1, g(0): 1}) == ([], []))
raises(NotImplementedError, lambda: dsolve_system(eq, t=x, ics={f(0): 1, g(0): 1}) == ([], []))
raises(NotImplementedError, lambda: dsolve_system(eq, ics={f(0): 1, g(0): 1}) == ([], []))
raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], ics={f(0): 1, g(0): 1}) == ([], []))
def test_dsolve():
f, g = symbols('f g', cls=Function)
x, y = symbols('x y')
eqs = [f(x).diff(x, 2), g(x).diff(x)]
with raises(ValueError):
dsolve(eqs) # NotImplementedError would be better
eqs = [f(x).diff(x) - x, f(x).diff(x) + x]
with raises(ValueError):
dsolve(eqs)
eqs = [f(x, y).diff(x)]
with raises(ValueError):
dsolve(eqs)
eqs = [f(x, y).diff(x)+g(x).diff(x), g(x).diff(x)]
with raises(ValueError):
dsolve(eqs)
|
6c116d3b571791747246fc0d72d3ecf5e9f4312715288339842880efb1bf7875 | import glob
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from distutils.errors import CompileError
from distutils.sysconfig import get_config_var
from .runners import (
CCompilerRunner,
CppCompilerRunner,
FortranCompilerRunner
)
from .util import (
get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob,
glob_at_depth, import_module_from_file, pyx_is_cplus,
sha256_of_string, sha256_of_file
)
sharedext = get_config_var('EXT_SUFFIX')
if os.name == 'posix':
objext = '.o'
elif os.name == 'nt':
objext = '.obj'
else:
warnings.warn("Unknown os.name: {}".format(os.name))
objext = '.o'
def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False,
per_file_kwargs=None, **kwargs):
""" Compile source code files to object files.
Parameters
==========
files : iterable of str
Paths to source files, if ``cwd`` is given, the paths are taken as relative.
Runner: CompilerRunner subclass (optional)
Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename
extensions if missing.
destdir: str
Output directory, if cwd is given, the path is taken as relative.
cwd: str
Working directory. Specify to have compiler run in other directory.
also used as root of relative paths.
keep_dir_struct: bool
Reproduce directory structure in `destdir`. default: ``False``
per_file_kwargs: dict
Dict mapping instances in ``files`` to keyword arguments.
\\*\\*kwargs: dict
Default keyword arguments to pass to ``Runner``.
"""
_per_file_kwargs = {}
if per_file_kwargs is not None:
for k, v in per_file_kwargs.items():
if isinstance(k, Glob):
for path in glob.glob(k.pathname):
_per_file_kwargs[path] = v
elif isinstance(k, ArbitraryDepthGlob):
for path in glob_at_depth(k.filename, cwd):
_per_file_kwargs[path] = v
else:
_per_file_kwargs[k] = v
# Set up destination directory
destdir = destdir or '.'
if not os.path.isdir(destdir):
if os.path.exists(destdir):
raise OSError("{} is not a directory".format(destdir))
else:
make_dirs(destdir)
if cwd is None:
cwd = '.'
for f in files:
copy(f, destdir, only_update=True, dest_is_dir=True)
# Compile files and return list of paths to the objects
dstpaths = []
for f in files:
if keep_dir_struct:
name, ext = os.path.splitext(f)
else:
name, ext = os.path.splitext(os.path.basename(f))
file_kwargs = kwargs.copy()
file_kwargs.update(_per_file_kwargs.get(f, {}))
dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs))
return dstpaths
def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None):
vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu')
if vendor.lower() == 'intel':
if cplus:
return (FortranCompilerRunner,
{'flags': ['-nofor_main', '-cxxlib']}, vendor)
else:
return (FortranCompilerRunner,
{'flags': ['-nofor_main']}, vendor)
elif vendor.lower() == 'gnu' or 'llvm':
if cplus:
return (CppCompilerRunner,
{'lib_options': ['fortran']}, vendor)
else:
return (FortranCompilerRunner,
{}, vendor)
else:
raise ValueError("No vendor found.")
def link(obj_files, out_file=None, shared=False, Runner=None,
cwd=None, cplus=False, fort=False, **kwargs):
""" Link object files.
Parameters
==========
obj_files: iterable of str
Paths to object files.
out_file: str (optional)
Path to executable/shared library, if ``None`` it will be
deduced from the last item in obj_files.
shared: bool
Generate a shared library?
Runner: CompilerRunner subclass (optional)
If not given the ``cplus`` and ``fort`` flags will be inspected
(fallback is the C compiler).
cwd: str
Path to the root of relative paths and working directory for compiler.
cplus: bool
C++ objects? default: ``False``.
fort: bool
Fortran objects? default: ``False``.
\\*\\*kwargs: dict
Keyword arguments passed to ``Runner``.
Returns
=======
The absolute path to the generated shared object / executable.
"""
if out_file is None:
out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
if shared:
out_file += sharedext
if not Runner:
if fort:
Runner, extra_kwargs, vendor = \
get_mixed_fort_c_linker(
vendor=kwargs.get('vendor', None),
cplus=cplus,
cwd=cwd,
)
for k, v in extra_kwargs.items():
if k in kwargs:
kwargs[k].expand(v)
else:
kwargs[k] = v
else:
if cplus:
Runner = CppCompilerRunner
else:
Runner = CCompilerRunner
flags = kwargs.pop('flags', [])
if shared:
if '-shared' not in flags:
flags.append('-shared')
run_linker = kwargs.pop('run_linker', True)
if not run_linker:
raise ValueError("run_linker was set to False (nonsensical).")
out_file = get_abspath(out_file, cwd=cwd)
runner = Runner(obj_files, out_file, flags, cwd=cwd, **kwargs)
runner.run()
return out_file
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None,
cplus=False, fort=False, **kwargs):
""" Link python extension module (shared object) for importing
Parameters
==========
obj_files: iterable of str
Paths to object files to be linked.
so_file: str
Name (path) of shared object file to create. If not specified it will
have the basname of the last object file in `obj_files` but with the
extension '.so' (Unix).
cwd: path string
Root of relative paths and working directory of linker.
libraries: iterable of strings
Libraries to link against, e.g. ['m'].
cplus: bool
Any C++ objects? default: ``False``.
fort: bool
Any Fortran objects? default: ``False``.
kwargs**: dict
Keyword arguments passed to ``link(...)``.
Returns
=======
Absolute path to the generate shared object.
"""
libraries = libraries or []
include_dirs = kwargs.pop('include_dirs', [])
library_dirs = kwargs.pop('library_dirs', [])
# from distutils/command/build_ext.py:
if sys.platform == "win32":
warnings.warn("Windows not yet supported.")
elif sys.platform == 'darwin':
# Don't use the default code below
pass
elif sys.platform[:3] == 'aix':
# Don't use the default code below
pass
else:
from distutils import sysconfig
if sysconfig.get_config_var('Py_ENABLE_SHARED'):
ABIFLAGS = sysconfig.get_config_var('ABIFLAGS')
pythonlib = 'python{}.{}{}'.format(
sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff,
ABIFLAGS or '')
libraries += [pythonlib]
else:
pass
flags = kwargs.pop('flags', [])
needed_flags = ('-pthread',)
for flag in needed_flags:
if flag not in flags:
flags.append(flag)
return link(obj_files, shared=True, flags=flags, cwd=cwd,
cplus=cplus, fort=fort, include_dirs=include_dirs,
libraries=libraries, library_dirs=library_dirs, **kwargs)
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
""" Generates a C file from a Cython source file.
Parameters
==========
src: str
Path to Cython source.
destdir: str (optional)
Path to output directory (default: '.').
cwd: path string (optional)
Root of relative paths (default: '.').
**cy_kwargs:
Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
else a .c file.
"""
from Cython.Compiler.Main import (
default_options, CompilationOptions
)
from Cython.Compiler.Main import compile as cy_compile
assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
cwd = cwd or '.'
destdir = destdir or '.'
ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
c_name = os.path.splitext(os.path.basename(src))[0] + ext
dstfile = os.path.join(destdir, c_name)
if cwd:
ori_dir = os.getcwd()
else:
ori_dir = '.'
os.chdir(cwd)
try:
cy_options = CompilationOptions(default_options)
cy_options.__dict__.update(cy_kwargs)
cy_result = cy_compile([src], cy_options)
if cy_result.num_errors > 0:
raise ValueError("Cython compilation failed.")
if os.path.abspath(os.path.dirname(src)) != os.path.abspath(destdir):
if os.path.exists(dstfile):
os.unlink(dstfile)
shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
finally:
os.chdir(ori_dir)
return dstfile
extension_mapping = {
'.c': (CCompilerRunner, None),
'.cpp': (CppCompilerRunner, None),
'.cxx': (CppCompilerRunner, None),
'.f': (FortranCompilerRunner, None),
'.for': (FortranCompilerRunner, None),
'.ftn': (FortranCompilerRunner, None),
'.f90': (FortranCompilerRunner, None), # ifort only knows about .f90
'.f95': (FortranCompilerRunner, 'f95'),
'.f03': (FortranCompilerRunner, 'f2003'),
'.f08': (FortranCompilerRunner, 'f2008'),
}
def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs):
""" Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
==========
srcpath: str
Path to source file.
Runner: CompilerRunner subclass (optional)
If ``None``: deduced from extension of srcpath.
objpath : str (optional)
Path to generated object. If ``None``: deduced from ``srcpath``.
cwd: str (optional)
Working directory and root of relative paths. If ``None``: current dir.
inc_py: bool
Add Python include path to kwarg "include_dirs". Default: False
\\*\\*kwargs: dict
keyword arguments passed to Runner or pyx2obj
"""
name, ext = os.path.splitext(os.path.basename(srcpath))
if objpath is None:
if os.path.isabs(srcpath):
objpath = '.'
else:
objpath = os.path.dirname(srcpath)
objpath = objpath or '.' # avoid objpath == ''
if os.path.isdir(objpath):
objpath = os.path.join(objpath, name + objext)
include_dirs = kwargs.pop('include_dirs', [])
if inc_py:
from distutils.sysconfig import get_python_inc
py_inc_dir = get_python_inc()
if py_inc_dir not in include_dirs:
include_dirs.append(py_inc_dir)
if ext.lower() == '.pyx':
return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd,
**kwargs)
if Runner is None:
Runner, std = extension_mapping[ext.lower()]
if 'std' not in kwargs:
kwargs['std'] = std
flags = kwargs.pop('flags', [])
needed_flags = ('-fPIC',)
for flag in needed_flags:
if flag not in flags:
flags.append(flag)
# src2obj implies not running the linker...
run_linker = kwargs.pop('run_linker', False)
if run_linker:
raise CompileError("src2obj called with run_linker=True")
runner = Runner([srcpath], objpath, include_dirs=include_dirs,
run_linker=run_linker, cwd=cwd, flags=flags, **kwargs)
runner.run()
return objpath
def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None,
include_dirs=None, cy_kwargs=None, cplus=None, **kwargs):
"""
Convenience function
If cwd is specified, pyxpath and dst are taken to be relative
If only_update is set to `True` the modification time is checked
and compilation is only run if the source is newer than the
destination
Parameters
==========
pyxpath: str
Path to Cython source file.
objpath: str (optional)
Path to object file to generate.
destdir: str (optional)
Directory to put generated C file. When ``None``: directory of ``objpath``.
cwd: str (optional)
Working directory and root of relative paths.
include_dirs: iterable of path strings (optional)
Passed onto src2obj and via cy_kwargs['include_path']
to simple_cythonize.
cy_kwargs: dict (optional)
Keyword arguments passed onto `simple_cythonize`
cplus: bool (optional)
Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``.
compile_kwargs: dict
keyword arguments passed onto src2obj
Returns
=======
Absolute path of generated object file.
"""
assert pyxpath.endswith('.pyx')
cwd = cwd or '.'
objpath = objpath or '.'
destdir = destdir or os.path.dirname(objpath)
abs_objpath = get_abspath(objpath, cwd=cwd)
if os.path.isdir(abs_objpath):
pyx_fname = os.path.basename(pyxpath)
name, ext = os.path.splitext(pyx_fname)
objpath = os.path.join(objpath, name + objext)
cy_kwargs = cy_kwargs or {}
cy_kwargs['output_dir'] = cwd
if cplus is None:
cplus = pyx_is_cplus(pyxpath)
cy_kwargs['cplus'] = cplus
interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs)
include_dirs = include_dirs or []
flags = kwargs.pop('flags', [])
needed_flags = ('-fwrapv', '-pthread', '-fPIC')
for flag in needed_flags:
if flag not in flags:
flags.append(flag)
options = kwargs.pop('options', [])
if kwargs.pop('strict_aliasing', False):
raise CompileError("Cython requires strict aliasing to be disabled.")
# Let's be explicit about standard
if cplus:
std = kwargs.pop('std', 'c++98')
else:
std = kwargs.pop('std', 'c99')
return src2obj(interm_c_file, objpath=objpath, cwd=cwd,
include_dirs=include_dirs, flags=flags, std=std,
options=options, inc_py=True, strict_aliasing=False,
**kwargs)
def _any_X(srcs, cls):
for src in srcs:
name, ext = os.path.splitext(src)
key = ext.lower()
if key in extension_mapping:
if extension_mapping[key][0] == cls:
return True
return False
def any_fortran_src(srcs):
return _any_X(srcs, FortranCompilerRunner)
def any_cplus_src(srcs):
return _any_X(srcs, CppCompilerRunner)
def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None,
link_kwargs=None):
""" Compiles sources to a shared object (python extension) and imports it
Sources in ``sources`` which is imported. If shared object is newer than the sources, they
are not recompiled but instead it is imported.
Parameters
==========
sources : string
List of paths to sources.
extname : string
Name of extension (default: ``None``).
If ``None``: taken from the last file in ``sources`` without extension.
build_dir: str
Path to directory in which objects files etc. are generated.
compile_kwargs: dict
keyword arguments passed to ``compile_sources``
link_kwargs: dict
keyword arguments passed to ``link_py_so``
Returns
=======
The imported module from of the python extension.
"""
if extname is None:
extname = os.path.splitext(os.path.basename(sources[-1]))[0]
compile_kwargs = compile_kwargs or {}
link_kwargs = link_kwargs or {}
try:
mod = import_module_from_file(os.path.join(build_dir, extname), sources)
except ImportError:
objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir,
cwd=build_dir, **compile_kwargs)
so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources),
cplus=any_cplus_src(sources), **link_kwargs)
mod = import_module_from_file(so)
return mod
def _write_sources_to_build_dir(sources, build_dir):
build_dir = build_dir or tempfile.mkdtemp()
if not os.path.isdir(build_dir):
raise OSError("Non-existent directory: ", build_dir)
source_files = []
for name, src in sources:
dest = os.path.join(build_dir, name)
differs = True
sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest()
if os.path.exists(dest):
if os.path.exists(dest + '.sha256'):
sha256_on_disk = open(dest + '.sha256').read()
else:
sha256_on_disk = sha256_of_file(dest).hexdigest()
differs = sha256_on_disk != sha256_in_mem
if differs:
with open(dest, 'wt') as fh:
fh.write(src)
open(dest + '.sha256', 'wt').write(sha256_in_mem)
source_files.append(dest)
return source_files, build_dir
def compile_link_import_strings(sources, build_dir=None, **kwargs):
""" Compiles, links and imports extension module from source.
Parameters
==========
sources : iterable of name/source pair tuples
build_dir : string (default: None)
Path. ``None`` implies use a temporary directory.
**kwargs:
Keyword arguments passed onto `compile_link_import_py_ext`.
Returns
=======
mod : module
The compiled and imported extension module.
info : dict
Containing ``build_dir`` as 'build_dir'.
"""
source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs)
info = dict(build_dir=build_dir)
return mod, info
def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None):
""" Compiles, links and runs a program built from sources.
Parameters
==========
sources : iterable of name/source pair tuples
build_dir : string (default: None)
Path. ``None`` implies use a temporary directory.
clean : bool
Whether to remove build_dir after use. This will only have an
effect if ``build_dir`` is ``None`` (which creates a temporary directory).
Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``.
This will also set ``build_dir`` in returned info dictionary to ``None``.
compile_kwargs: dict
Keyword arguments passed onto ``compile_sources``
link_kwargs: dict
Keyword arguments passed onto ``link``
Returns
=======
(stdout, stderr): pair of strings
info: dict
Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir'
"""
if clean and build_dir is not None:
raise ValueError("Automatic removal of build_dir is only available for temporary directory.")
try:
source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir,
cwd=build_dir, **(compile_kwargs or {}))
prog = link(objs, cwd=build_dir,
fort=any_fortran_src(source_files),
cplus=any_cplus_src(source_files), **(link_kwargs or {}))
p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
exit_status = p.wait()
stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()]
finally:
if clean and os.path.isdir(build_dir):
shutil.rmtree(build_dir)
build_dir = None
info = dict(exit_status=exit_status, build_dir=build_dir)
return (stdout, stderr), info
|
71581b96f72c0c66f85ab13849f6db03173d498b26d75822a630a1e5abe8b734 | from typing import Callable, Dict, Optional, Tuple, Union
from collections import OrderedDict
from distutils.errors import CompileError
import os
import re
import subprocess
from .util import (
find_binary_of_command, unique_list
)
class CompilerRunner:
""" CompilerRunner base class.
Parameters
==========
sources : list of str
Paths to sources.
out : str
flags : iterable of str
Compiler flags.
run_linker : bool
compiler_name_exe : (str, str) tuple
Tuple of compiler name & command to call.
cwd : str
Path of root of relative paths.
include_dirs : list of str
Include directories.
libraries : list of str
Libraries to link against.
library_dirs : list of str
Paths to search for shared libraries.
std : str
Standard string, e.g. ``'c++11'``, ``'c99'``, ``'f2003'``.
define: iterable of strings
macros to define
undef : iterable of strings
macros to undefine
preferred_vendor : string
name of preferred vendor e.g. 'gnu' or 'intel'
Methods
=======
run():
Invoke compilation as a subprocess.
"""
# Subclass to vendor/binary dict
compiler_dict = None # type: Dict[str, str]
# Standards should be a tuple of supported standards
# (first one will be the default)
standards = None # type: Tuple[Union[None, str], ...]
# Subclass to dict of binary/formater-callback
std_formater = None # type: Dict[str, Callable[[Optional[str]], str]]
# subclass to be e.g. {'gcc': 'gnu', ...}
compiler_name_vendor_mapping = None # type: Dict[str, str]
def __init__(self, sources, out, flags=None, run_linker=True, compiler=None, cwd='.',
include_dirs=None, libraries=None, library_dirs=None, std=None, define=None,
undef=None, strict_aliasing=None, preferred_vendor=None, **kwargs):
if isinstance(sources, str):
raise ValueError("Expected argument sources to be a list of strings.")
self.sources = list(sources)
self.out = out
self.flags = flags or []
self.cwd = cwd
if compiler:
self.compiler_name, self.compiler_binary = compiler
else:
# Find a compiler
if preferred_vendor is None:
preferred_vendor = os.environ.get('SYMPY_COMPILER_VENDOR', None)
self.compiler_name, self.compiler_binary, self.compiler_vendor = self.find_compiler(preferred_vendor)
if self.compiler_binary is None:
raise ValueError("No compiler found (searched: {})".format(', '.join(self.compiler_dict.values())))
self.define = define or []
self.undef = undef or []
self.include_dirs = include_dirs or []
self.libraries = libraries or []
self.library_dirs = library_dirs or []
self.std = std or self.standards[0]
self.run_linker = run_linker
if self.run_linker:
# both gnu and intel compilers use '-c' for disabling linker
self.flags = list(filter(lambda x: x != '-c', self.flags))
else:
if '-c' not in self.flags:
self.flags.append('-c')
if self.std:
self.flags.append(self.std_formater[
self.compiler_name](self.std))
self.linkline = []
if strict_aliasing is not None:
nsa_re = re.compile("no-strict-aliasing$")
sa_re = re.compile("strict-aliasing$")
if strict_aliasing is True:
if any(map(nsa_re.match, flags)):
raise CompileError("Strict aliasing cannot be both enforced and disabled")
elif any(map(sa_re.match, flags)):
pass # already enforced
else:
flags.append('-fstrict-aliasing')
elif strict_aliasing is False:
if any(map(nsa_re.match, flags)):
pass # already disabled
else:
if any(map(sa_re.match, flags)):
raise CompileError("Strict aliasing cannot be both enforced and disabled")
else:
flags.append('-fno-strict-aliasing')
else:
msg = "Expected argument strict_aliasing to be True/False, got {}"
raise ValueError(msg.format(strict_aliasing))
@classmethod
def find_compiler(cls, preferred_vendor=None):
""" Identify a suitable C/fortran/other compiler. """
candidates = list(cls.compiler_dict.keys())
if preferred_vendor:
if preferred_vendor in candidates:
candidates = [preferred_vendor]+candidates
else:
raise ValueError("Unknown vendor {}".format(preferred_vendor))
name, path = find_binary_of_command([cls.compiler_dict[x] for x in candidates])
return name, path, cls.compiler_name_vendor_mapping[name]
def cmd(self):
""" List of arguments (str) to be passed to e.g. ``subprocess.Popen``. """
cmd = (
[self.compiler_binary] +
self.flags +
['-U'+x for x in self.undef] +
['-D'+x for x in self.define] +
['-I'+x for x in self.include_dirs] +
self.sources
)
if self.run_linker:
cmd += (['-L'+x for x in self.library_dirs] +
['-l'+x for x in self.libraries] +
self.linkline)
counted = []
for envvar in re.findall(r'\$\{(\w+)\}', ' '.join(cmd)):
if os.getenv(envvar) is None:
if envvar not in counted:
counted.append(envvar)
msg = "Environment variable '{}' undefined.".format(envvar)
raise CompileError(msg)
return cmd
def run(self):
self.flags = unique_list(self.flags)
# Append output flag and name to tail of flags
self.flags.extend(['-o', self.out])
env = os.environ.copy()
env['PWD'] = self.cwd
# NOTE: intel compilers seems to need shell=True
p = subprocess.Popen(' '.join(self.cmd()),
shell=True,
cwd=self.cwd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env)
comm = p.communicate()
try:
self.cmd_outerr = comm[0].decode('utf-8')
except UnicodeDecodeError:
self.cmd_outerr = comm[0].decode('iso-8859-1') # win32
self.cmd_returncode = p.returncode
# Error handling
if self.cmd_returncode != 0:
msg = "Error executing '{}' in {} (exited status {}):\n {}\n".format(
' '.join(self.cmd()), self.cwd, str(self.cmd_returncode), self.cmd_outerr
)
raise CompileError(msg)
return self.cmd_outerr, self.cmd_returncode
class CCompilerRunner(CompilerRunner):
compiler_dict = OrderedDict([
('gnu', 'gcc'),
('intel', 'icc'),
('llvm', 'clang'),
])
standards = ('c89', 'c90', 'c99', 'c11') # First is default
std_formater = {
'gcc': '-std={}'.format,
'icc': '-std={}'.format,
'clang': '-std={}'.format,
}
compiler_name_vendor_mapping = {
'gcc': 'gnu',
'icc': 'intel',
'clang': 'llvm'
}
def _mk_flag_filter(cmplr_name): # helper for class initialization
not_welcome = {'g++': ("Wimplicit-interface",)} # "Wstrict-prototypes",)}
if cmplr_name in not_welcome:
def fltr(x):
for nw in not_welcome[cmplr_name]:
if nw in x:
return False
return True
else:
def fltr(x):
return True
return fltr
class CppCompilerRunner(CompilerRunner):
compiler_dict = OrderedDict([
('gnu', 'g++'),
('intel', 'icpc'),
('llvm', 'clang++'),
])
# First is the default, c++0x == c++11
standards = ('c++98', 'c++0x')
std_formater = {
'g++': '-std={}'.format,
'icpc': '-std={}'.format,
'clang++': '-std={}'.format,
}
compiler_name_vendor_mapping = {
'g++': 'gnu',
'icpc': 'intel',
'clang++': 'llvm'
}
class FortranCompilerRunner(CompilerRunner):
standards = (None, 'f77', 'f95', 'f2003', 'f2008')
std_formater = {
'gfortran': lambda x: '-std=gnu' if x is None else '-std=legacy' if x == 'f77' else '-std={}'.format(x),
'ifort': lambda x: '-stand f08' if x is None else '-stand f{}'.format(x[-2:]), # f2008 => f08
}
compiler_dict = OrderedDict([
('gnu', 'gfortran'),
('intel', 'ifort'),
])
compiler_name_vendor_mapping = {
'gfortran': 'gnu',
'ifort': 'intel',
}
|
f1a612dcda2cbc54e17a232a227f4d81d6f284d1026f55bf7ef47b01b9f3a1ae | from collections import namedtuple
from hashlib import sha256
import os
import shutil
import sys
import fnmatch
from sympy.testing.pytest import XFAIL
def may_xfail(func):
if sys.platform.lower() == 'darwin' or os.name == 'nt':
# sympy.utilities._compilation needs more testing on Windows and macOS
# once those two platforms are reliably supported this xfail decorator
# may be removed.
return XFAIL(func)
else:
return func
class CompilerNotFoundError(FileNotFoundError):
pass
def get_abspath(path, cwd='.'):
""" Returns the aboslute path.
Parameters
==========
path : str
(relative) path.
cwd : str
Path to root of relative path.
"""
if os.path.isabs(path):
return path
else:
if not os.path.isabs(cwd):
cwd = os.path.abspath(cwd)
return os.path.abspath(
os.path.join(cwd, path)
)
def make_dirs(path):
""" Create directories (equivalent of ``mkdir -p``). """
if path[-1] == '/':
parent = os.path.dirname(path[:-1])
else:
parent = os.path.dirname(path)
if len(parent) > 0:
if not os.path.exists(parent):
make_dirs(parent)
if not os.path.exists(path):
os.mkdir(path, 0o777)
else:
assert os.path.isdir(path)
def copy(src, dst, only_update=False, copystat=True, cwd=None,
dest_is_dir=False, create_dest_dirs=False):
""" Variation of ``shutil.copy`` with extra options.
Parameters
==========
src : str
Path to source file.
dst : str
Path to destination.
only_update : bool
Only copy if source is newer than destination
(returns None if it was newer), default: ``False``.
copystat : bool
See ``shutil.copystat``. default: ``True``.
cwd : str
Path to working directory (root of relative paths).
dest_is_dir : bool
Ensures that dst is treated as a directory. default: ``False``
create_dest_dirs : bool
Creates directories if needed.
Returns
=======
Path to the copied file.
"""
if cwd: # Handle working directory
if not os.path.isabs(src):
src = os.path.join(cwd, src)
if not os.path.isabs(dst):
dst = os.path.join(cwd, dst)
if not os.path.exists(src): # Make sure source file extists
raise FileNotFoundError("Source: `{}` does not exist".format(src))
# We accept both (re)naming destination file _or_
# passing a (possible non-existent) destination directory
if dest_is_dir:
if not dst[-1] == '/':
dst = dst+'/'
else:
if os.path.exists(dst) and os.path.isdir(dst):
dest_is_dir = True
if dest_is_dir:
dest_dir = dst
dest_fname = os.path.basename(src)
dst = os.path.join(dest_dir, dest_fname)
else:
dest_dir = os.path.dirname(dst)
dest_fname = os.path.basename(dst)
if not os.path.exists(dest_dir):
if create_dest_dirs:
make_dirs(dest_dir)
else:
raise FileNotFoundError("You must create directory first.")
if only_update:
# This function is not defined:
# XXX: This branch is clearly not tested!
if not missing_or_other_newer(dst, src): # noqa
return
if os.path.islink(dst):
dst = os.path.abspath(os.path.realpath(dst), cwd=cwd)
shutil.copy(src, dst)
if copystat:
shutil.copystat(src, dst)
return dst
Glob = namedtuple('Glob', 'pathname')
ArbitraryDepthGlob = namedtuple('ArbitraryDepthGlob', 'filename')
def glob_at_depth(filename_glob, cwd=None):
if cwd is not None:
cwd = '.'
globbed = []
for root, dirs, filenames in os.walk(cwd):
for fn in filenames:
# This is not tested:
if fnmatch.fnmatch(fn, filename_glob):
globbed.append(os.path.join(root, fn))
return globbed
def sha256_of_file(path, nblocks=128):
""" Computes the SHA256 hash of a file.
Parameters
==========
path : string
Path to file to compute hash of.
nblocks : int
Number of blocks to read per iteration.
Returns
=======
hashlib sha256 hash object. Use ``.digest()`` or ``.hexdigest()``
on returned object to get binary or hex encoded string.
"""
sh = sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(nblocks*sh.block_size), b''):
sh.update(chunk)
return sh
def sha256_of_string(string):
""" Computes the SHA256 hash of a string. """
sh = sha256()
sh.update(string)
return sh
def pyx_is_cplus(path):
"""
Inspect a Cython source file (.pyx) and look for comment line like:
# distutils: language = c++
Returns True if such a file is present in the file, else False.
"""
for line in open(path):
if line.startswith('#') and '=' in line:
splitted = line.split('=')
if len(splitted) != 2:
continue
lhs, rhs = splitted
if lhs.strip().split()[-1].lower() == 'language' and \
rhs.strip().split()[0].lower() == 'c++':
return True
return False
def import_module_from_file(filename, only_if_newer_than=None):
""" Imports python extension (from shared object file)
Provide a list of paths in `only_if_newer_than` to check
timestamps of dependencies. import_ raises an ImportError
if any is newer.
Word of warning: The OS may cache shared objects which makes
reimporting same path of an shared object file very problematic.
It will not detect the new time stamp, nor new checksum, but will
instead silently use old module. Use unique names for this reason.
Parameters
==========
filename : str
Path to shared object.
only_if_newer_than : iterable of strings
Paths to dependencies of the shared object.
Raises
======
``ImportError`` if any of the files specified in ``only_if_newer_than`` are newer
than the file given by filename.
"""
path, name = os.path.split(filename)
name, ext = os.path.splitext(name)
name = name.split('.')[0]
if sys.version_info[0] == 2:
from imp import find_module, load_module
fobj, filename, data = find_module(name, [path])
if only_if_newer_than:
for dep in only_if_newer_than:
if os.path.getmtime(filename) < os.path.getmtime(dep):
raise ImportError("{} is newer than {}".format(dep, filename))
mod = load_module(name, fobj, filename, data)
else:
import importlib.util
spec = importlib.util.spec_from_file_location(name, filename)
if spec is None:
raise ImportError("Failed to import: '%s'" % filename)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def find_binary_of_command(candidates):
""" Finds binary first matching name among candidates.
Calls `find_executable` from distuils for provided candidates and returns
first hit.
Parameters
==========
candidates : iterable of str
Names of candidate commands
Raises
======
CompilerNotFoundError if no candidates match.
"""
from distutils.spawn import find_executable
for c in candidates:
binary_path = find_executable(c)
if c and binary_path:
return c, binary_path
raise CompilerNotFoundError('No binary located for candidates: {}'.format(candidates))
def unique_list(l):
""" Uniquify a list (skip duplicate items). """
result = []
for x in l:
if x not in result:
result.append(x)
return result
|
d7ebcc78107aa4c358a751cfe79c7c4a38c57a9f86b1dbc3fdc6dba3c7b05136 | from itertools import product
import math
import inspect
import mpmath
from sympy.testing.pytest import raises
from sympy import (
symbols, lambdify, sqrt, sin, cos, tan, pi, acos, acosh, Rational,
Float, Lambda, Piecewise, exp, E, Integral, oo, I, Abs, Function,
true, false, And, Or, Not, ITE, Min, Max, floor, diff, IndexedBase, Sum,
DotProduct, Eq, Dummy, sinc, erf, erfc, factorial, gamma, loggamma,
digamma, RisingFactorial, besselj, bessely, besseli, besselk, S, beta,
fresnelc, fresnels)
from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.functions.elementary.complexes import re, im, arg
from sympy.functions.special.polynomials import \
chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \
assoc_legendre, assoc_laguerre, jacobi
from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.pycode import NumPyPrinter
from sympy.utilities.lambdify import implemented_function, lambdastr
from sympy.testing.pytest import skip
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.external import import_module
from sympy.functions.special.gamma_functions import uppergamma, lowergamma
import sympy
MutableDenseMatrix = Matrix
numpy = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
numexpr = import_module('numexpr')
tensorflow = import_module('tensorflow')
if tensorflow:
# Hide Tensorflow warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
w, x, y, z = symbols('w,x,y,z')
#================== Test different arguments =======================
def test_no_args():
f = lambdify([], 1)
raises(TypeError, lambda: f(-1))
assert f() == 1
def test_single_arg():
f = lambdify(x, 2*x)
assert f(1) == 2
def test_list_args():
f = lambdify([x, y], x + y)
assert f(1, 2) == 3
def test_nested_args():
f1 = lambdify([[w, x]], [w, x])
assert f1([91, 2]) == [91, 2]
raises(TypeError, lambda: f1(1, 2))
f2 = lambdify([(w, x), (y, z)], [w, x, y, z])
assert f2((18, 12), (73, 4)) == [18, 12, 73, 4]
raises(TypeError, lambda: f2(3, 4))
f3 = lambdify([w, [[[x]], y], z], [w, x, y, z])
assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44]
def test_str_args():
f = lambdify('x,y,z', 'z,y,x')
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_own_namespace_1():
myfunc = lambda x: 1
f = lambdify(x, sin(x), {"sin": myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_namespace_2():
def myfunc(x):
return 1
f = lambdify(x, sin(x), {'sin': myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_module():
f = lambdify(x, sin(x), math)
assert f(0) == 0.0
def test_bad_args():
# no vargs given
raises(TypeError, lambda: lambdify(1))
# same with vector exprs
raises(TypeError, lambda: lambdify([1, 2]))
def test_atoms():
# Non-Symbol atoms should not be pulled out from the expression namespace
f = lambdify(x, pi + x, {"pi": 3.14})
assert f(0) == 3.14
f = lambdify(x, I + x, {"I": 1j})
assert f(1) == 1 + 1j
#================== Test different modules =========================
# high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted
@conserve_mpmath_dps
def test_sympy_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "sympy")
assert f(x) == sin(x)
prec = 1e-15
assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
# arctan is in numpy module and should not be available
# The arctan below gives NameError. What is this supposed to test?
# raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
@conserve_mpmath_dps
def test_math_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "math")
prec = 1e-15
assert -prec < f(0.2) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a python math function
@conserve_mpmath_dps
def test_mpmath_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a mpmath function
@conserve_mpmath_dps
def test_number_precision():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin02, "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(0) - sin02 < prec
@conserve_mpmath_dps
def test_mpmath_precision():
mpmath.mp.dps = 100
assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100))
#================== Test Translations ==============================
# We can only check if all translated functions are valid. It has to be checked
# by hand if they are complete.
def test_math_transl():
from sympy.utilities.lambdify import MATH_TRANSLATIONS
for sym, mat in MATH_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert mat in math.__dict__
def test_mpmath_transl():
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
for sym, mat in MPMATH_TRANSLATIONS.items():
assert sym in sympy.__dict__ or sym == 'Matrix'
assert mat in mpmath.__dict__
def test_numpy_transl():
if not numpy:
skip("numpy not installed.")
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
for sym, nump in NUMPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert nump in numpy.__dict__
def test_scipy_transl():
if not scipy:
skip("scipy not installed.")
from sympy.utilities.lambdify import SCIPY_TRANSLATIONS
for sym, scip in SCIPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert scip in scipy.__dict__ or scip in scipy.special.__dict__
def test_numpy_translation_abs():
if not numpy:
skip("numpy not installed.")
f = lambdify(x, Abs(x), "numpy")
assert f(-1) == 1
assert f(1) == 1
def test_numexpr_printer():
if not numexpr:
skip("numexpr not installed.")
# if translation/printing is done incorrectly then evaluating
# a lambdified numexpr expression will throw an exception
from sympy.printing.lambdarepr import NumExprPrinter
blacklist = ('where', 'complex', 'contains')
arg_tuple = (x, y, z) # some functions take more than one argument
for sym in NumExprPrinter._numexpr_functions.keys():
if sym in blacklist:
continue
ssym = S(sym)
if hasattr(ssym, '_nargs'):
nargs = ssym._nargs[0]
else:
nargs = 1
args = arg_tuple[:nargs]
f = lambdify(args, ssym(*args), modules='numexpr')
assert f(*(1, )*nargs) is not None
def test_issue_9334():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
expr = S('b*a - sqrt(a**2)')
a, b = sorted(expr.free_symbols, key=lambda s: s.name)
func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False)
foo, bar = numpy.random.random((2, 4))
func_numexpr(foo, bar)
def test_issue_12984():
import warnings
if not numexpr:
skip("numexpr not installed.")
func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
assert func_numexpr(1, 24, 42) == 24
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
assert str(func_numexpr(-1, 24, 42)) == 'nan'
#================== Test some functions ============================
def test_exponentiation():
f = lambdify(x, x**2)
assert f(-1) == 1
assert f(0) == 0
assert f(1) == 1
assert f(-2) == 4
assert f(2) == 4
assert f(2.5) == 6.25
def test_sqrt():
f = lambdify(x, sqrt(x))
assert f(0) == 0.0
assert f(1) == 1.0
assert f(4) == 2.0
assert abs(f(2) - 1.414) < 0.001
assert f(6.25) == 2.5
def test_trig():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
prec = 1e-11
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
d = f(3.14159)
prec = 1e-5
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
#================== Test vectors ===================================
def test_vector_simple():
f = lambdify((x, y, z), (z, y, x))
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_vector_discontinuous():
f = lambdify(x, (-1/x, 1/x))
raises(ZeroDivisionError, lambda: f(0))
assert f(1) == (-1.0, 1.0)
assert f(2) == (-0.5, 0.5)
assert f(-2) == (0.5, -0.5)
def test_trig_symbolic():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_trig_float():
f = lambdify([x], [cos(x), sin(x)])
d = f(3.14159)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_docs():
f = lambdify(x, x**2)
assert f(2) == 4
f = lambdify([x, y, z], [z, y, x])
assert f(1, 2, 3) == [3, 2, 1]
f = lambdify(x, sqrt(x))
assert f(4) == 2.0
f = lambdify((x, y), sin(x*y)**2)
assert f(0, 5) == 0
def test_math():
f = lambdify((x, y), sin(x), modules="math")
assert f(0, 5) == 0
def test_sin():
f = lambdify(x, sin(x)**2)
assert isinstance(f(2), float)
f = lambdify(x, sin(x)**2, modules="math")
assert isinstance(f(2), float)
def test_matrix():
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol = Matrix([[1, 2], [sin(3) + 4, 1]])
f = lambdify((x, y, z), A, modules="sympy")
assert f(1, 2, 3) == sol
f = lambdify((x, y, z), (A, [A]), modules="sympy")
assert f(1, 2, 3) == (sol, [sol])
J = Matrix((x, x + y)).jacobian((x, y))
v = Matrix((x, y))
sol = Matrix([[1, 0], [1, 1]])
assert lambdify(v, J, modules='sympy')(1, 2) == sol
assert lambdify(v.T, J, modules='sympy')(1, 2) == sol
def test_numpy_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
#Lambdify array first, to ensure return to array as default
f = lambdify((x, y, z), A, ['numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
#Check that the types are arrays and matrices
assert isinstance(f(1, 2, 3), numpy.ndarray)
# gh-15071
class dot(Function):
pass
x_dot_mtx = dot(x, Matrix([[2], [1], [0]]))
f_dot1 = lambdify(x, x_dot_mtx)
inp = numpy.zeros((17, 3))
assert numpy.all(f_dot1(inp) == 0)
strict_kw = dict(allow_unknown_functions=False, inline=True, fully_qualified_modules=False)
p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw))
f_dot2 = lambdify(x, x_dot_mtx, printer=p2)
assert numpy.all(f_dot2(inp) == 0)
p3 = NumPyPrinter(strict_kw)
# The line below should probably fail upon construction (before calling with "(inp)"):
raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp))
def test_numpy_transpose():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A.T, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
def test_numpy_dotproduct():
if not numpy:
skip("numpy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
numpy.array([14])
def test_numpy_inverse():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A**-1, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]]))
def test_numpy_old_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)
def test_scipy_sparse_matrix():
if not scipy:
skip("scipy not installed.")
A = SparseMatrix([[x, 0], [0, y]])
f = lambdify((x, y), A, modules="scipy")
B = f(1, 2)
assert isinstance(B, scipy.sparse.coo_matrix)
def test_python_div_zero_issue_11306():
if not numpy:
skip("numpy not installed.")
p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True))
f = lambdify([x, y], p, modules='numpy')
numpy.seterr(divide='ignore')
assert float(f(numpy.array([0]),numpy.array([0.5]))) == 0
assert str(float(f(numpy.array([0]),numpy.array([1])))) == 'inf'
numpy.seterr(divide='warn')
def test_issue9474():
mods = [None, 'math']
if numpy:
mods.append('numpy')
if mpmath:
mods.append('mpmath')
for mod in mods:
f = lambdify(x, S.One/x, modules=mod)
assert f(2) == 0.5
f = lambdify(x, floor(S.One/x), modules=mod)
assert f(2) == 0
for absfunc, modules in product([Abs, abs], mods):
f = lambdify(x, absfunc(x), modules=modules)
assert f(-1) == 1
assert f(1) == 1
assert f(3+4j) == 5
def test_issue_9871():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
r = sqrt(x**2 + y**2)
expr = diff(1/r, x)
xn = yn = numpy.linspace(1, 10, 16)
# expr(xn, xn) = -xn/(sqrt(2)*xn)^3
fv_exact = -numpy.sqrt(2.)**-3 * xn**-2
fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn)
fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn)
numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10)
numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10)
def test_numpy_piecewise():
if not numpy:
skip("numpy not installed.")
pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True))
f = lambdify(x, pieces, modules="numpy")
numpy.testing.assert_array_equal(f(numpy.arange(10)),
numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81]))
# If we evaluate somewhere all conditions are False, we should get back NaN
nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0)))
numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])),
numpy.array([1, numpy.nan, 1]))
def test_numpy_logical_ops():
if not numpy:
skip("numpy not installed.")
and_func = lambdify((x, y), And(x, y), modules="numpy")
and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy")
or_func = lambdify((x, y), Or(x, y), modules="numpy")
or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy")
not_func = lambdify((x), Not(x), modules="numpy")
arr1 = numpy.array([True, True])
arr2 = numpy.array([False, True])
arr3 = numpy.array([True, False])
numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True]))
numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False]))
numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True]))
numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True]))
numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
def test_numpy_matmul():
if not numpy:
skip("numpy not installed.")
xmat = Matrix([[x, y], [z, 1+z]])
ymat = Matrix([[x**2], [Abs(x)]])
mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy")
numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]]))
numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]]))
# Multiple matrices chained together in multiplication
f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy")
numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25],
[159, 251]]))
def test_numpy_numexpr():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b, c = numpy.random.randn(3, 128, 128)
# ensure that numpy and numexpr return same value for complicated expression
expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \
Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2)
npfunc = lambdify((x, y, z), expr, modules='numpy')
nefunc = lambdify((x, y, z), expr, modules='numexpr')
assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c))
def test_numexpr_userfunctions():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b = numpy.random.randn(2, 10)
uf = type('uf', (Function, ),
{'eval' : classmethod(lambda x, y : y**2+1)})
func = lambdify(x, 1-uf(x), modules='numexpr')
assert numpy.allclose(func(a), -(a**2))
uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1)
func = lambdify((x, y), uf(x, y), modules='numexpr')
assert numpy.allclose(func(a, b), 2*a*b+1)
def test_tensorflow_basic_math():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.constant(0, dtype=tensorflow.float32)
assert func(a).eval(session=s) == 0.5
def test_tensorflow_placeholders():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_variables():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.Variable(0, dtype=tensorflow.float32)
s.run(a.initializer)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_logical_operations():
if not tensorflow:
skip("tensorflow not installed.")
expr = Not(And(Or(x, y), y))
func = lambdify([x, y], expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(False, True).eval(session=s) == False
def test_tensorflow_piecewise():
if not tensorflow:
skip("tensorflow not installed.")
expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-1).eval(session=s) == -1
assert func(0).eval(session=s) == 0
assert func(1).eval(session=s) == 1
def test_tensorflow_multi_max():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == 4
def test_tensorflow_multi_min():
if not tensorflow:
skip("tensorflow not installed.")
expr = Min(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == -2
def test_tensorflow_relational():
if not tensorflow:
skip("tensorflow not installed.")
expr = x >= 0
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(1).eval(session=s) == True
def test_tensorflow_complexes():
if not tensorflow:
skip("tensorflow not installed")
func1 = lambdify(x, re(x), modules="tensorflow")
func2 = lambdify(x, im(x), modules="tensorflow")
func3 = lambdify(x, Abs(x), modules="tensorflow")
func4 = lambdify(x, arg(x), modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
# For versions before
# https://github.com/tensorflow/tensorflow/issues/30029
# resolved, using python numeric types may not work
a = tensorflow.constant(1+2j)
assert func1(a).eval(session=s) == 1
assert func2(a).eval(session=s) == 2
tensorflow_result = func3(a).eval(session=s)
sympy_result = Abs(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
tensorflow_result = func4(a).eval(session=s)
sympy_result = arg(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
def test_tensorflow_array_arg():
# Test for issue 14655 (tensorflow part)
if not tensorflow:
skip("tensorflow not installed.")
f = lambdify([[x, y]], x*x + y, 'tensorflow')
with tensorflow.compat.v1.Session() as s:
fcall = f(tensorflow.constant([2.0, 1.0]))
assert fcall.eval(session=s) == 5.0
#================== Test symbolic ==================================
def test_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
assert l(x) == Integral(exp(-x**2), (x, -oo, oo))
def test_sym_single_arg():
f = lambdify(x, x * y)
assert f(z) == z * y
def test_sym_list_args():
f = lambdify([x, y], x + y + z)
assert f(1, 2) == 3 + z
def test_sym_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
assert l(y).doit() == sqrt(pi)
def test_namespace_order():
# lambdify had a bug, such that module dictionaries or cached module
# dictionaries would pull earlier namespaces into themselves.
# Because the module dictionaries form the namespace of the
# generated lambda, this meant that the behavior of a previously
# generated lambda function could change as a result of later calls
# to lambdify.
n1 = {'f': lambda x: 'first f'}
n2 = {'f': lambda x: 'second f',
'g': lambda x: 'function g'}
f = sympy.Function('f')
g = sympy.Function('g')
if1 = lambdify(x, f(x), modules=(n1, "sympy"))
assert if1(1) == 'first f'
if2 = lambdify(x, g(x), modules=(n2, "sympy"))
# previously gave 'second f'
assert if1(1) == 'first f'
assert if2(1) == 'function g'
def test_namespace_type():
# lambdify had a bug where it would reject modules of type unicode
# on Python 2.
x = sympy.Symbol('x')
lambdify(x, x, modules='math')
def test_imps():
# Here we check if the default returned functions are anonymous - in
# the sense that we can have more than one function with the same name
f = implemented_function('f', lambda x: 2*x)
g = implemented_function('f', lambda x: math.sqrt(x))
l1 = lambdify(x, f(x))
l2 = lambdify(x, g(x))
assert str(f(x)) == str(g(x))
assert l1(3) == 6
assert l2(3) == math.sqrt(3)
# check that we can pass in a Function as input
func = sympy.Function('myfunc')
assert not hasattr(func, '_imp_')
my_f = implemented_function(func, lambda x: 2*x)
assert hasattr(my_f, '_imp_')
# Error for functions with same name and different implementation
f2 = implemented_function("f", lambda x: x + 101)
raises(ValueError, lambda: lambdify(x, f(f2(x))))
def test_imps_errors():
# Test errors that implemented functions can return, and still be able to
# form expressions.
# See: https://github.com/sympy/sympy/issues/10810
#
# XXX: Removed AttributeError here. This test was added due to issue 10810
# but that issue was about ValueError. It doesn't seem reasonable to
# "support" catching AttributeError in the same context...
for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)):
def myfunc(a):
if a == 0:
raise error_class
return 1
f = implemented_function('f', myfunc)
expr = f(val)
assert expr == f(val)
def test_imps_wrong_args():
raises(ValueError, lambda: implemented_function(sin, lambda x: x))
def test_lambdify_imps():
# Test lambdify with implemented functions
# first test basic (sympy) lambdify
f = sympy.cos
assert lambdify(x, f(x))(0) == 1
assert lambdify(x, 1 + f(x))(0) == 2
assert lambdify((x, y), y + f(x))(0, 1) == 2
# make an implemented function and test
f = implemented_function("f", lambda x: x + 100)
assert lambdify(x, f(x))(0) == 100
assert lambdify(x, 1 + f(x))(0) == 101
assert lambdify((x, y), y + f(x))(0, 1) == 101
# Can also handle tuples, lists, dicts as expressions
lam = lambdify(x, (f(x), x))
assert lam(3) == (103, 3)
lam = lambdify(x, [f(x), x])
assert lam(3) == [103, 3]
lam = lambdify(x, [f(x), (f(x), x)])
assert lam(3) == [103, (103, 3)]
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {x: f(x)})
assert lam(3) == {3: 103}
# Check that imp preferred to other namespaces by default
d = {'f': lambda x: x + 99}
lam = lambdify(x, f(x), d)
assert lam(3) == 103
# Unless flag passed
lam = lambdify(x, f(x), d, use_imps=False)
assert lam(3) == 102
def test_dummification():
t = symbols('t')
F = Function('F')
G = Function('G')
#"\alpha" is not a valid python variable name
#lambdify should sub in a dummy for it, and return
#without a syntax error
alpha = symbols(r'\alpha')
some_expr = 2 * F(t)**2 / G(t)
lam = lambdify((F(t), G(t)), some_expr)
assert lam(3, 9) == 2
lam = lambdify(sin(t), 2 * sin(t)**2)
assert lam(F(t)) == 2 * F(t)**2
#Test that \alpha was properly dummified
lam = lambdify((alpha, t), 2*alpha + t)
assert lam(2, 1) == 5
raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5))
def test_curly_matrix_symbol():
# Issue #15009
curlyv = sympy.MatrixSymbol("{v}", 2, 1)
lam = lambdify(curlyv, curlyv)
assert lam(1)==1
lam = lambdify(curlyv, curlyv, dummify=True)
assert lam(1)==1
def test_python_keywords():
# Test for issue 7452. The automatic dummification should ensure use of
# Python reserved keywords as symbol names will create valid lambda
# functions. This is an additional regression test.
python_if = symbols('if')
expr = python_if / 2
f = lambdify(python_if, expr)
assert f(4.0) == 2.0
def test_lambdify_docstring():
func = lambdify((w, x, y, z), w + x + y + z)
ref = (
"Created with lambdify. Signature:\n\n"
"func(w, x, y, z)\n\n"
"Expression:\n\n"
"w + x + y + z"
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
syms = symbols('a1:26')
func = lambdify(syms, sum(syms))
ref = (
"Created with lambdify. Signature:\n\n"
"func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n"
" a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n"
"Expression:\n\n"
"a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..."
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
#================== Test special printers ==========================
def test_special_printers():
from sympy.polys.numberfields import IntervalPrinter
def intervalrepr(expr):
return IntervalPrinter().doprint(expr)
expr = sqrt(sqrt(2) + sqrt(3)) + S.Half
func0 = lambdify((), expr, modules="mpmath", printer=intervalrepr)
func1 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter)
func2 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter())
mpi = type(mpmath.mpi(1, 2))
assert isinstance(func0(), mpi)
assert isinstance(func1(), mpi)
assert isinstance(func2(), mpi)
def test_true_false():
# We want exact is comparison here, not just ==
assert lambdify([], true)() is True
assert lambdify([], false)() is False
def test_issue_2790():
assert lambdify((x, (y, z)), x + y)(1, (2, 4)) == 3
assert lambdify((x, (y, (w, z))), w + x + y + z)(1, (2, (3, 4))) == 10
assert lambdify(x, x + 1, dummify=False)(1) == 2
def test_issue_12092():
f = implemented_function('f', lambda x: x**2)
assert f(f(2)).evalf() == Float(16)
def test_issue_14911():
class Variable(sympy.Symbol):
def _sympystr(self, printer):
return printer.doprint(self.name)
_lambdacode = _sympystr
_numpycode = _sympystr
x = Variable('x')
y = 2 * x
code = LambdaPrinter().doprint(y)
assert code.replace(' ', '') == '2*x'
def test_ITE():
assert lambdify((x, y, z), ITE(x, y, z))(True, 5, 3) == 5
assert lambdify((x, y, z), ITE(x, y, z))(False, 5, 3) == 3
def test_Min_Max():
# see gh-10375
assert lambdify((x, y, z), Min(x, y, z))(1, 2, 3) == 1
assert lambdify((x, y, z), Max(x, y, z))(1, 2, 3) == 3
def test_Indexed():
# Issue #10934
if not numpy:
skip("numpy not installed")
a = IndexedBase('a')
i, j = symbols('i j')
b = numpy.array([[1, 2], [3, 4]])
assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10
def test_issue_12173():
#test for issue 12173
expr1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2)
expr2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2)
assert expr1 == uppergamma(1, 2).evalf()
assert expr2 == lowergamma(1, 2).evalf()
def test_issue_13642():
if not numpy:
skip("numpy not installed")
f = lambdify(x, sinc(x))
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_sinc_mpmath():
f = lambdify(x, sinc(x), "mpmath")
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_lambdify_dummy_arg():
d1 = Dummy()
f1 = lambdify(d1, d1 + 1, dummify=False)
assert f1(2) == 3
f1b = lambdify(d1, d1 + 1)
assert f1b(2) == 3
d2 = Dummy('x')
f2 = lambdify(d2, d2 + 1)
assert f2(2) == 3
f3 = lambdify([[d2]], d2 + 1)
assert f3([2]) == 3
def test_lambdify_mixed_symbol_dummy_args():
d = Dummy()
# Contrived example of name clash
dsym = symbols(str(d))
f = lambdify([d, dsym], d - dsym)
assert f(4, 1) == 3
def test_numpy_array_arg():
# Test for issue 14655 (numpy part)
if not numpy:
skip("numpy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
assert f(numpy.array([2.0, 1.0])) == 5
def test_scipy_fns():
if not scipy:
skip("scipy not installed")
single_arg_sympy_fns = [erf, erfc, factorial, gamma, loggamma, digamma]
single_arg_scipy_fns = [scipy.special.erf, scipy.special.erfc,
scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln,
scipy.special.psi]
numpy.random.seed(0)
for (sympy_fn, scipy_fn) in zip(single_arg_sympy_fns, single_arg_scipy_fns):
f = lambdify(x, sympy_fn(x), modules="scipy")
for i in range(20):
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy thinks that factorial(z) is 0 when re(z) < 0 and
# does not support complex numbers.
# SymPy does not think so.
if sympy_fn == factorial:
tv = numpy.abs(tv)
# SciPy supports gammaln for real arguments only,
# and there is also a branch cut along the negative real axis
if sympy_fn == loggamma:
tv = numpy.abs(tv)
# SymPy's digamma evaluates as polygamma(0, z)
# which SciPy supports for real arguments only
if sympy_fn == digamma:
tv = numpy.real(tv)
sympy_result = sympy_fn(tv).evalf()
assert abs(f(tv) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv) - scipy_fn(tv)) < 1e-13*(1 + abs(sympy_result))
double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli,
besselk]
double_arg_scipy_fns = [scipy.special.poch, scipy.special.jv,
scipy.special.yv, scipy.special.iv, scipy.special.kv]
for (sympy_fn, scipy_fn) in zip(double_arg_sympy_fns, double_arg_scipy_fns):
f = lambdify((x, y), sympy_fn(x, y), modules="scipy")
for i in range(20):
# SciPy supports only real orders of Bessel functions
tv1 = numpy.random.uniform(-10, 10)
tv2 = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports poch for real arguments only
if sympy_fn == RisingFactorial:
tv2 = numpy.real(tv2)
sympy_result = sympy_fn(tv1, tv2).evalf()
assert abs(f(tv1, tv2) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv1, tv2) - scipy_fn(tv1, tv2)) < 1e-13*(1 + abs(sympy_result))
def test_scipy_polys():
if not scipy:
skip("scipy not installed")
numpy.random.seed(0)
params = symbols('n k a b')
# list polynomials with the number of parameters
polys = [
(chebyshevt, 1),
(chebyshevu, 1),
(legendre, 1),
(hermite, 1),
(laguerre, 1),
(gegenbauer, 2),
(assoc_legendre, 2),
(assoc_laguerre, 2),
(jacobi, 3)
]
msg = \
"The random test of the function {func} with the arguments " \
"{args} had failed because the SymPy result {sympy_result} " \
"and SciPy result {scipy_result} had failed to converge " \
"within the tolerance {tol} " \
"(Actual absolute difference : {diff})"
for sympy_fn, num_params in polys:
args = params[:num_params] + (x,)
f = lambdify(args, sympy_fn(*args))
for _ in range(10):
tn = numpy.random.randint(3, 10)
tparams = tuple(numpy.random.uniform(0, 5, size=num_params-1))
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports hermite for real arguments only
if sympy_fn == hermite:
tv = numpy.real(tv)
# assoc_legendre needs x in (-1, 1) and integer param at most n
if sympy_fn == assoc_legendre:
tv = numpy.random.uniform(-1, 1)
tparams = tuple(numpy.random.randint(1, tn, size=1))
vals = (tn,) + tparams + (tv,)
scipy_result = f(*vals)
sympy_result = sympy_fn(*vals).evalf()
atol = 1e-9*(1 + abs(sympy_result))
diff = abs(scipy_result - sympy_result)
try:
assert diff < atol
except TypeError:
raise AssertionError(
msg.format(
func=repr(sympy_fn),
args=repr(vals),
sympy_result=repr(sympy_result),
scipy_result=repr(scipy_result),
diff=diff,
tol=atol)
)
def test_lambdify_inspect():
f = lambdify(x, x**2)
# Test that inspect.getsource works but don't hard-code implementation
# details
assert 'x**2' in inspect.getsource(f)
def test_issue_14941():
x, y = Dummy(), Dummy()
# test dict
f1 = lambdify([x, y], {x: 3, y: 3}, 'sympy')
assert f1(2, 3) == {2: 3, 3: 3}
# test tuple
f2 = lambdify([x, y], (y, x), 'sympy')
assert f2(2, 3) == (3, 2)
# test list
f3 = lambdify([x, y], [y, x], 'sympy')
assert f3(2, 3) == [3, 2]
def test_lambdify_Derivative_arg_issue_16468():
f = Function('f')(x)
fx = f.diff()
assert lambdify((f, fx), f + fx)(10, 5) == 15
assert eval(lambdastr((f, fx), f/fx))(10, 5) == 2
raises(SyntaxError, lambda:
eval(lambdastr((f, fx), f/fx, dummify=False)))
assert eval(lambdastr((f, fx), f/fx, dummify=True))(10, 5) == 2
assert eval(lambdastr((fx, f), f/fx, dummify=True))(S(10), 5) == S.Half
assert lambdify(fx, 1 + fx)(41) == 42
assert eval(lambdastr(fx, 1 + fx, dummify=True))(41) == 42
def test_imag_real():
f_re = lambdify([z], sympy.re(z))
val = 3+2j
assert f_re(val) == val.real
f_im = lambdify([z], sympy.im(z)) # see #15400
assert f_im(val) == val.imag
def test_MatrixSymbol_issue_15578():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol('A', 2, 2)
A0 = numpy.array([[1, 2], [3, 4]])
f = lambdify(A, A**(-1))
assert numpy.allclose(f(A0), numpy.array([[-2., 1.], [1.5, -0.5]]))
g = lambdify(A, A**3)
assert numpy.allclose(g(A0), numpy.array([[37, 54], [81, 118]]))
def test_issue_15654():
if not scipy:
skip("scipy not installed")
from sympy.abc import n, l, r, Z
from sympy.physics import hydrogen
nv, lv, rv, Zv = 1, 0, 3, 1
sympy_value = hydrogen.R_nl(nv, lv, rv, Zv).evalf()
f = lambdify((n, l, r, Z), hydrogen.R_nl(n, l, r, Z))
scipy_value = f(nv, lv, rv, Zv)
assert abs(sympy_value - scipy_value) < 1e-15
def test_issue_15827():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 2, 3)
C = MatrixSymbol("C", 3, 4)
D = MatrixSymbol("D", 4, 5)
k=symbols("k")
f = lambdify(A, (2*k)*A)
g = lambdify(A, (2+k)*A)
h = lambdify(A, 2*A)
i = lambdify((B, C, D), 2*B*C*D)
assert numpy.array_equal(f(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2*k, 4*k, 6*k], [2*k, 4*k, 6*k], [2*k, 4*k, 6*k]], dtype=object))
assert numpy.array_equal(g(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[k + 2, 2*k + 4, 3*k + 6], [k + 2, 2*k + 4, 3*k + 6], \
[k + 2, 2*k + 4, 3*k + 6]], dtype=object))
assert numpy.array_equal(h(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2, 4, 6], [2, 4, 6], [2, 4, 6]]))
assert numpy.array_equal(i(numpy.array([[1, 2, 3], [1, 2, 3]]), numpy.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]), \
numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])), numpy.array([[ 120, 240, 360, 480, 600], \
[ 120, 240, 360, 480, 600]]))
def test_issue_16930():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f = lambda x: S.GoldenRatio * x**2
f_ = lambdify(x, f(x), modules='scipy')
assert f_(1) == scipy.constants.golden_ratio
def test_issue_17898():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f_ = lambdify([x], sympy.LambertW(x,-1), modules='scipy')
assert f_(0.1) == mpmath.lambertw(0.1, -1)
def test_single_e():
f = lambdify(x, E)
assert f(23) == exp(1.0)
def test_issue_16536():
if not scipy:
skip("scipy not installed")
a = symbols('a')
f1 = lowergamma(a, x)
F = lambdify((a, x), f1, modules='scipy')
assert abs(lowergamma(1, 3) - F(1, 3)) <= 1e-10
f2 = uppergamma(a, x)
F = lambdify((a, x), f2, modules='scipy')
assert abs(uppergamma(1, 3) - F(1, 3)) <= 1e-10
def test_fresnel_integrals_scipy():
if not scipy:
skip("scipy not installed")
f1 = fresnelc(x)
f2 = fresnels(x)
F1 = lambdify(x, f1, modules='scipy')
F2 = lambdify(x, f2, modules='scipy')
assert abs(fresnelc(1.3) - F1(1.3)) <= 1e-10
assert abs(fresnels(1.3) - F2(1.3)) <= 1e-10
def test_beta_scipy():
if not scipy:
skip("scipy not installed")
f = beta(x, y)
F = lambdify((x, y), f, modules='scipy')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_beta_math():
f = beta(x, y)
F = lambdify((x, y), f, modules='math')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_numpy_special_math():
if not numpy:
skip("numpy not installed")
funcs = [expm1, log1p, exp2, log2, log10, hypot, logaddexp, logaddexp2]
for func in funcs:
if 2 in func.nargs:
expr = func(x, y)
args = (x, y)
num_args = (0.3, 0.4)
elif 1 in func.nargs:
expr = func(x)
args = (x,)
num_args = (0.3,)
else:
raise NotImplementedError("Need to handle other than unary & binary functions in test")
f = lambdify(args, expr)
result = f(*num_args)
reference = expr.subs(dict(zip(args, num_args))).evalf()
assert numpy.allclose(result, float(reference))
lae2 = lambdify((x, y), logaddexp2(log2(x), log2(y)))
assert abs(2.0**lae2(1e-50, 2.5e-50) - 3.5e-50) < 1e-62 # from NumPy's docstring
|
2daef951c3e2c53b10b7a5b1da68944574ea904726604de248bd1525bb535999 | from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy
from sympy.core.compatibility import StringIO
from sympy import erf, Integral, Symbol
from sympy import Equality
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import (
codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument,
CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument,
InOutArgument)
from sympy.testing.pytest import raises
from sympy.utilities.lambdify import implemented_function
#FIXME: Fails due to circular import in with core
# from sympy import codegen
def get_string(dump_fn, routines, prefix="file", header=False, empty=False):
"""Wrapper for dump_fn. dump_fn writes its results to a stream object and
this wrapper returns the contents of that stream as a string. This
auxiliary function is used by many tests below.
The header and the empty lines are not generated to facilitate the
testing of the output.
"""
output = StringIO()
dump_fn(routines, output, prefix, header, empty)
source = output.getvalue()
output.close()
return source
def test_Routine_argument_order():
a, x, y, z = symbols('a x y z')
expr = (x + y)*z
raises(CodeGenArgumentListError, lambda: make_routine("test", expr,
argument_sequence=[z, x]))
raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a,
expr), argument_sequence=[z, x, y]))
r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
assert [ type(arg) for arg in r.arguments ] == [
InputArgument, InputArgument, OutputArgument, InputArgument ]
r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y])
assert [ type(arg) for arg in r.arguments ] == [
InOutArgument, InputArgument, InputArgument ]
from sympy.tensor import IndexedBase, Idx
A, B = map(IndexedBase, ['A', 'B'])
m = symbols('m', integer=True)
i = Idx('i', m)
r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m])
assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m]
expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3))
r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
def test_empty_c_code():
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [])
assert source == "#include \"file.h\"\n#include <math.h>\n"
def test_empty_c_code_with_comment():
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [], header=True)
assert source[:82] == (
"/******************************************************************************\n *"
)
# " Code generated with sympy 0.7.2-git "
assert source[158:] == ( "*\n"
" * *\n"
" * See http://www.sympy.org/ for more information. *\n"
" * *\n"
" * This file is part of 'project' *\n"
" ******************************************************************************/\n"
"#include \"file.h\"\n"
"#include <math.h>\n"
)
def test_empty_c_header():
code_gen = C99CodeGen()
source = get_string(code_gen.dump_h, [])
assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n"
def test_simple_c_code():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double x, double y, double z) {\n"
" double test_result;\n"
" test_result = z*(x + y);\n"
" return test_result;\n"
"}\n"
)
assert source == expected
def test_c_code_reserved_words():
x, y, z = symbols('if, typedef, while')
expr = (x + y) * z
routine = make_routine("test", expr)
code_gen = C99CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double if_, double typedef_, double while_) {\n"
" double test_result;\n"
" test_result = while_*(if_ + typedef_);\n"
" return test_result;\n"
"}\n"
)
assert source == expected
def test_numbersymbol_c_code():
routine = make_routine("test", pi**Catalan)
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test() {\n"
" double test_result;\n"
" double const Catalan = %s;\n"
" test_result = pow(M_PI, Catalan);\n"
" return test_result;\n"
"}\n"
) % Catalan.evalf(17)
assert source == expected
def test_c_code_argument_order():
x, y, z = symbols('x,y,z')
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y])
code_gen = C89CodeGen()
source = get_string(code_gen.dump_c, [routine])
expected = (
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double z, double x, double y) {\n"
" double test_result;\n"
" test_result = x + y;\n"
" return test_result;\n"
"}\n"
)
assert source == expected
def test_simple_c_header():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = C89CodeGen()
source = get_string(code_gen.dump_h, [routine])
expected = (
"#ifndef PROJECT__FILE__H\n"
"#define PROJECT__FILE__H\n"
"double test(double x, double y, double z);\n"
"#endif\n"
)
assert source == expected
def test_simple_c_codegen():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
expected = [
("file.c",
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double x, double y, double z) {\n"
" double test_result;\n"
" test_result = z*(x + y);\n"
" return test_result;\n"
"}\n"),
("file.h",
"#ifndef PROJECT__FILE__H\n"
"#define PROJECT__FILE__H\n"
"double test(double x, double y, double z);\n"
"#endif\n")
]
result = codegen(("test", expr), "C", "file", header=False, empty=False)
assert result == expected
def test_multiple_results_c():
x, y, z = symbols('x,y,z')
expr1 = (x + y)*z
expr2 = (x - y)*z
routine = make_routine(
"test",
[expr1, expr2]
)
code_gen = C99CodeGen()
raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine]))
def test_no_results_c():
raises(ValueError, lambda: make_routine("test", []))
def test_ansi_math1_codegen():
# not included: log10
from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln,
sin, sinh, sqrt, tan, tanh, Abs)
x = symbols('x')
name_expr = [
("test_fabs", Abs(x)),
("test_acos", acos(x)),
("test_asin", asin(x)),
("test_atan", atan(x)),
("test_ceil", ceiling(x)),
("test_cos", cos(x)),
("test_cosh", cosh(x)),
("test_floor", floor(x)),
("test_log", log(x)),
("test_ln", ln(x)),
("test_sin", sin(x)),
("test_sinh", sinh(x)),
("test_sqrt", sqrt(x)),
("test_tan", tan(x)),
("test_tanh", tanh(x)),
]
result = codegen(name_expr, "C89", "file", header=False, empty=False)
assert result[0][0] == "file.c"
assert result[0][1] == (
'#include "file.h"\n#include <math.h>\n'
'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n'
'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n'
'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n'
'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n'
'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n'
'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n'
'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n'
'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n'
'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n'
'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n'
'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n'
'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n'
'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n'
'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n'
'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n'
)
assert result[1][0] == "file.h"
assert result[1][1] == (
'#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n'
'double test_fabs(double x);\ndouble test_acos(double x);\n'
'double test_asin(double x);\ndouble test_atan(double x);\n'
'double test_ceil(double x);\ndouble test_cos(double x);\n'
'double test_cosh(double x);\ndouble test_floor(double x);\n'
'double test_log(double x);\ndouble test_ln(double x);\n'
'double test_sin(double x);\ndouble test_sinh(double x);\n'
'double test_sqrt(double x);\ndouble test_tan(double x);\n'
'double test_tanh(double x);\n#endif\n'
)
def test_ansi_math2_codegen():
# not included: frexp, ldexp, modf, fmod
from sympy import atan2
x, y = symbols('x,y')
name_expr = [
("test_atan2", atan2(x, y)),
("test_pow", x**y),
]
result = codegen(name_expr, "C89", "file", header=False, empty=False)
assert result[0][0] == "file.c"
assert result[0][1] == (
'#include "file.h"\n#include <math.h>\n'
'double test_atan2(double x, double y) {\n double test_atan2_result;\n test_atan2_result = atan2(x, y);\n return test_atan2_result;\n}\n'
'double test_pow(double x, double y) {\n double test_pow_result;\n test_pow_result = pow(x, y);\n return test_pow_result;\n}\n'
)
assert result[1][0] == "file.h"
assert result[1][1] == (
'#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n'
'double test_atan2(double x, double y);\n'
'double test_pow(double x, double y);\n'
'#endif\n'
)
def test_complicated_codegen():
from sympy import sin, cos, tan
x, y, z = symbols('x,y,z')
name_expr = [
("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
]
result = codegen(name_expr, "C89", "file", header=False, empty=False)
assert result[0][0] == "file.c"
assert result[0][1] == (
'#include "file.h"\n#include <math.h>\n'
'double test1(double x, double y, double z) {\n'
' double test1_result;\n'
' test1_result = '
'pow(sin(x), 7) + '
'7*pow(sin(x), 6)*cos(y) + '
'7*pow(sin(x), 6)*tan(z) + '
'21*pow(sin(x), 5)*pow(cos(y), 2) + '
'42*pow(sin(x), 5)*cos(y)*tan(z) + '
'21*pow(sin(x), 5)*pow(tan(z), 2) + '
'35*pow(sin(x), 4)*pow(cos(y), 3) + '
'105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + '
'105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + '
'35*pow(sin(x), 4)*pow(tan(z), 3) + '
'35*pow(sin(x), 3)*pow(cos(y), 4) + '
'140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + '
'210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + '
'140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + '
'35*pow(sin(x), 3)*pow(tan(z), 4) + '
'21*pow(sin(x), 2)*pow(cos(y), 5) + '
'105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + '
'210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + '
'210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + '
'105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + '
'21*pow(sin(x), 2)*pow(tan(z), 5) + '
'7*sin(x)*pow(cos(y), 6) + '
'42*sin(x)*pow(cos(y), 5)*tan(z) + '
'105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + '
'140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + '
'105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + '
'42*sin(x)*cos(y)*pow(tan(z), 5) + '
'7*sin(x)*pow(tan(z), 6) + '
'pow(cos(y), 7) + '
'7*pow(cos(y), 6)*tan(z) + '
'21*pow(cos(y), 5)*pow(tan(z), 2) + '
'35*pow(cos(y), 4)*pow(tan(z), 3) + '
'35*pow(cos(y), 3)*pow(tan(z), 4) + '
'21*pow(cos(y), 2)*pow(tan(z), 5) + '
'7*cos(y)*pow(tan(z), 6) + '
'pow(tan(z), 7);\n'
' return test1_result;\n'
'}\n'
'double test2(double x, double y, double z) {\n'
' double test2_result;\n'
' test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n'
' return test2_result;\n'
'}\n'
)
assert result[1][0] == "file.h"
assert result[1][1] == (
'#ifndef PROJECT__FILE__H\n'
'#define PROJECT__FILE__H\n'
'double test1(double x, double y, double z);\n'
'double test2(double x, double y, double z);\n'
'#endif\n'
)
def test_loops_c():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False)
assert f1 == 'file.c'
expected = (
'#include "file.h"\n'
'#include <math.h>\n'
'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n'
' for (int i=0; i<m; i++){\n'
' y[i] = 0;\n'
' }\n'
' for (int i=0; i<m; i++){\n'
' for (int j=0; j<n; j++){\n'
' y[i] = %(rhs)s + y[i];\n'
' }\n'
' }\n'
'}\n'
)
assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*n + j)} or
code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*n)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (i*n + j)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*n)})
assert f2 == 'file.h'
assert interface == (
'#ifndef PROJECT__FILE__H\n'
'#define PROJECT__FILE__H\n'
'void matrix_vector(double *A, int m, int n, double *x, double *y);\n'
'#endif\n'
)
def test_dummy_loops_c():
from sympy.tensor import IndexedBase, Idx
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'#include "file.h"\n'
'#include <math.h>\n'
'void test_dummies(int m_%(mno)i, double *x, double *y) {\n'
' for (int i_%(ino)i=0; i_%(ino)i<m_%(mno)i; i_%(ino)i++){\n'
' y[i_%(ino)i] = x[i_%(ino)i];\n'
' }\n'
'}\n'
) % {'ino': i.label.dummy_index, 'mno': m.dummy_index}
r = make_routine('test_dummies', Eq(y[i], x[i]))
c89 = C89CodeGen()
c99 = C99CodeGen()
code = get_string(c99.dump_c, [r])
assert code == expected
with raises(NotImplementedError):
get_string(c89.dump_c, [r])
def test_partial_loops_c():
# check that loop boundaries are determined by Idx, and array strides
# determined by shape of IndexedBase object.
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A', shape=(m, p))
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', (o, m - 5)) # Note: bounds are inclusive
j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False)
assert f1 == 'file.c'
expected = (
'#include "file.h"\n'
'#include <math.h>\n'
'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n'
' for (int i=o; i<%(upperi)s; i++){\n'
' y[i] = 0;\n'
' }\n'
' for (int i=o; i<%(upperi)s; i++){\n'
' for (int j=0; j<n; j++){\n'
' y[i] = %(rhs)s + y[i];\n'
' }\n'
' }\n'
'}\n'
) % {'upperi': m - 4, 'rhs': '%(rhs)s'}
assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*p + j)} or
code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*p)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (i*p + j)} or
code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*p)})
assert f2 == 'file.h'
assert interface == (
'#ifndef PROJECT__FILE__H\n'
'#define PROJECT__FILE__H\n'
'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y);\n'
'#endif\n'
)
def test_output_arg_c():
from sympy import sin, cos, Equality
x, y, z = symbols("x,y,z")
r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
c = C89CodeGen()
result = c.write([r], "test", header=False, empty=False)
assert result[0][0] == "test.c"
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'double foo(double x, double *y) {\n'
' (*y) = sin(x);\n'
' double foo_result;\n'
' foo_result = cos(x);\n'
' return foo_result;\n'
'}\n'
)
assert result[0][1] == expected
def test_output_arg_c_reserved_words():
from sympy import sin, cos, Equality
x, y, z = symbols("if, while, z")
r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
c = C89CodeGen()
result = c.write([r], "test", header=False, empty=False)
assert result[0][0] == "test.c"
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'double foo(double if_, double *while_) {\n'
' (*while_) = sin(if_);\n'
' double foo_result;\n'
' foo_result = cos(if_);\n'
' return foo_result;\n'
'}\n'
)
assert result[0][1] == expected
def test_ccode_results_named_ordered():
x, y, z = symbols('x,y,z')
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(A, Matrix([[1, 2, x]]))
expr2 = Equality(C, (x + y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'void test(double x, double *C, double z, double y, double *A, double *B) {\n'
' (*C) = z*(x + y);\n'
' A[0] = 1;\n'
' A[1] = 2;\n'
' A[2] = x;\n'
' (*B) = 2*x;\n'
'}\n'
)
result = codegen(name_expr, "c", "test", header=False, empty=False,
argument_sequence=(x, C, z, y, A, B))
source = result[0][1]
assert source == expected
def test_ccode_matrixsymbol_slice():
A = MatrixSymbol('A', 5, 3)
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 1, 3)
D = MatrixSymbol('D', 5, 1)
name_expr = ("test", [Equality(B, A[0, :]),
Equality(C, A[1, :]),
Equality(D, A[:, 2])])
result = codegen(name_expr, "c99", "test", header=False, empty=False)
source = result[0][1]
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'void test(double *A, double *B, double *C, double *D) {\n'
' B[0] = A[0];\n'
' B[1] = A[1];\n'
' B[2] = A[2];\n'
' C[0] = A[3];\n'
' C[1] = A[4];\n'
' C[2] = A[5];\n'
' D[0] = A[2];\n'
' D[1] = A[5];\n'
' D[2] = A[8];\n'
' D[3] = A[11];\n'
' D[4] = A[14];\n'
'}\n'
)
assert source == expected
def test_ccode_cse():
a, b, c, d = symbols('a b c d')
e = MatrixSymbol('e', 3, 1)
name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))])
generator = CCodeGen(cse=True)
result = codegen(name_expr, code_gen=generator, header=False, empty=False)
source = result[0][1]
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'void test(double a, double b, double c, double d, double *e) {\n'
' const double x0 = a*b;\n'
' const double x1 = c*d;\n'
' e[0] = x0;\n'
' e[1] = x0 + x1;\n'
' e[2] = x0*x1;\n'
'}\n'
)
assert source == expected
def test_ccode_unused_array_arg():
x = MatrixSymbol('x', 2, 1)
# x does not appear in output
name_expr = ("test", 1.0)
generator = CCodeGen()
result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,))
source = result[0][1]
# note: x should appear as (double *)
expected = (
'#include "test.h"\n'
'#include <math.h>\n'
'double test(double *x) {\n'
' double test_result;\n'
' test_result = 1.0;\n'
' return test_result;\n'
'}\n'
)
assert source == expected
def test_empty_f_code():
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [])
assert source == ""
def test_empty_f_code_with_header():
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [], header=True)
assert source[:82] == (
"!******************************************************************************\n!*"
)
# " Code generated with sympy 0.7.2-git "
assert source[158:] == ( "*\n"
"!* *\n"
"!* See http://www.sympy.org/ for more information. *\n"
"!* *\n"
"!* This file is part of 'project' *\n"
"!******************************************************************************\n"
)
def test_empty_f_header():
code_gen = FCodeGen()
source = get_string(code_gen.dump_h, [])
assert source == ""
def test_simple_f_code():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"test = z*(x + y)\n"
"end function\n"
)
assert source == expected
def test_numbersymbol_f_code():
routine = make_routine("test", pi**Catalan)
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test()\n"
"implicit none\n"
"REAL*8, parameter :: Catalan = %sd0\n"
"REAL*8, parameter :: pi = %sd0\n"
"test = pi**Catalan\n"
"end function\n"
) % (Catalan.evalf(17), pi.evalf(17))
assert source == expected
def test_erf_f_code():
x = symbols('x')
routine = make_routine("test", erf(x) - erf(-2 * x))
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test(x)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"test = erf(x) + erf(2.0d0*x)\n"
"end function\n"
)
assert source == expected, source
def test_f_code_argument_order():
x, y, z = symbols('x,y,z')
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y])
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = (
"REAL*8 function test(z, x, y)\n"
"implicit none\n"
"REAL*8, intent(in) :: z\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"test = x + y\n"
"end function\n"
)
assert source == expected
def test_simple_f_header():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = FCodeGen()
source = get_string(code_gen.dump_h, [routine])
expected = (
"interface\n"
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"end function\n"
"end interface\n"
)
assert source == expected
def test_simple_f_codegen():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
result = codegen(
("test", expr), "F95", "file", header=False, empty=False)
expected = [
("file.f90",
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"test = z*(x + y)\n"
"end function\n"),
("file.h",
"interface\n"
"REAL*8 function test(x, y, z)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"end function\n"
"end interface\n")
]
assert result == expected
def test_multiple_results_f():
x, y, z = symbols('x,y,z')
expr1 = (x + y)*z
expr2 = (x - y)*z
routine = make_routine(
"test",
[expr1, expr2]
)
code_gen = FCodeGen()
raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine]))
def test_no_results_f():
raises(ValueError, lambda: make_routine("test", []))
def test_intrinsic_math_codegen():
# not included: log10
from sympy import (acos, asin, atan, cos, cosh, log, ln, sin, sinh, sqrt,
tan, tanh, Abs)
x = symbols('x')
name_expr = [
("test_abs", Abs(x)),
("test_acos", acos(x)),
("test_asin", asin(x)),
("test_atan", atan(x)),
("test_cos", cos(x)),
("test_cosh", cosh(x)),
("test_log", log(x)),
("test_ln", ln(x)),
("test_sin", sin(x)),
("test_sinh", sinh(x)),
("test_sqrt", sqrt(x)),
("test_tan", tan(x)),
("test_tanh", tanh(x)),
]
result = codegen(name_expr, "F95", "file", header=False, empty=False)
assert result[0][0] == "file.f90"
expected = (
'REAL*8 function test_abs(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_abs = abs(x)\n'
'end function\n'
'REAL*8 function test_acos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_acos = acos(x)\n'
'end function\n'
'REAL*8 function test_asin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_asin = asin(x)\n'
'end function\n'
'REAL*8 function test_atan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_atan = atan(x)\n'
'end function\n'
'REAL*8 function test_cos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_cos = cos(x)\n'
'end function\n'
'REAL*8 function test_cosh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_cosh = cosh(x)\n'
'end function\n'
'REAL*8 function test_log(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_log = log(x)\n'
'end function\n'
'REAL*8 function test_ln(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_ln = log(x)\n'
'end function\n'
'REAL*8 function test_sin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_sin = sin(x)\n'
'end function\n'
'REAL*8 function test_sinh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_sinh = sinh(x)\n'
'end function\n'
'REAL*8 function test_sqrt(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_sqrt = sqrt(x)\n'
'end function\n'
'REAL*8 function test_tan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_tan = tan(x)\n'
'end function\n'
'REAL*8 function test_tanh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'test_tanh = tanh(x)\n'
'end function\n'
)
assert result[0][1] == expected
assert result[1][0] == "file.h"
expected = (
'interface\n'
'REAL*8 function test_abs(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_acos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_asin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_atan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_cos(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_cosh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_log(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_ln(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_sin(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_sinh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_sqrt(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_tan(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_tanh(x)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'end function\n'
'end interface\n'
)
assert result[1][1] == expected
def test_intrinsic_math2_codegen():
# not included: frexp, ldexp, modf, fmod
from sympy import atan2
x, y = symbols('x,y')
name_expr = [
("test_atan2", atan2(x, y)),
("test_pow", x**y),
]
result = codegen(name_expr, "F95", "file", header=False, empty=False)
assert result[0][0] == "file.f90"
expected = (
'REAL*8 function test_atan2(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'test_atan2 = atan2(x, y)\n'
'end function\n'
'REAL*8 function test_pow(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'test_pow = x**y\n'
'end function\n'
)
assert result[0][1] == expected
assert result[1][0] == "file.h"
expected = (
'interface\n'
'REAL*8 function test_atan2(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test_pow(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'end function\n'
'end interface\n'
)
assert result[1][1] == expected
def test_complicated_codegen_f95():
from sympy import sin, cos, tan
x, y, z = symbols('x,y,z')
name_expr = [
("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
]
result = codegen(name_expr, "F95", "file", header=False, empty=False)
assert result[0][0] == "file.f90"
expected = (
'REAL*8 function test1(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n'
' **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n'
' **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n'
' 105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n'
' x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n'
' cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n'
' **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n'
' tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n'
' **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n'
' (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n'
' sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n'
' *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n'
' x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n'
' z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n'
' y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n'
'end function\n'
'REAL*8 function test2(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n'
'end function\n'
)
assert result[0][1] == expected
assert result[1][0] == "file.h"
expected = (
'interface\n'
'REAL*8 function test1(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'end function\n'
'end interface\n'
'interface\n'
'REAL*8 function test2(x, y, z)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(in) :: y\n'
'REAL*8, intent(in) :: z\n'
'end function\n'
'end interface\n'
)
assert result[1][1] == expected
def test_loops():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n,m', integer=True)
A, x, y = map(IndexedBase, 'Axy')
i = Idx('i', m)
j = Idx('j', n)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False)
assert f1 == 'file.f90'
expected = (
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'INTEGER*4 :: i\n'
'INTEGER*4 :: j\n'
'do i = 1, m\n'
' y(i) = 0\n'
'end do\n'
'do i = 1, m\n'
' do j = 1, n\n'
' y(i) = %(rhs)s + y(i)\n'
' end do\n'
'end do\n'
'end subroutine\n'
)
assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\
code == expected % {'rhs': 'x(j)*A(i, j)'}
assert f2 == 'file.h'
assert interface == (
'interface\n'
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'end subroutine\n'
'end interface\n'
)
def test_dummy_loops_f95():
from sympy.tensor import IndexedBase, Idx
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'subroutine test_dummies(m_%(mcount)i, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m_%(mcount)i\n'
'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n'
'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n'
'INTEGER*4 :: i_%(icount)i\n'
'do i_%(icount)i = 1, m_%(mcount)i\n'
' y(i_%(icount)i) = x(i_%(icount)i)\n'
'end do\n'
'end subroutine\n'
) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
r = make_routine('test_dummies', Eq(y[i], x[i]))
c = FCodeGen()
code = get_string(c.dump_f95, [r])
assert code == expected
def test_loops_InOut():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
i, j, n, m = symbols('i,j,n,m', integer=True)
A, x, y = symbols('A,x,y')
A = IndexedBase(A)[Idx(i, m), Idx(j, n)]
x = IndexedBase(x)[Idx(j, n)]
y = IndexedBase(y)[Idx(i, m)]
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False)
assert f1 == 'file.f90'
expected = (
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(inout), dimension(1:m) :: y\n'
'INTEGER*4 :: i\n'
'INTEGER*4 :: j\n'
'do i = 1, m\n'
' do j = 1, n\n'
' y(i) = %(rhs)s + y(i)\n'
' end do\n'
'end do\n'
'end subroutine\n'
)
assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or
code == expected % {'rhs': 'x(j)*A(i, j)'})
assert f2 == 'file.h'
assert interface == (
'interface\n'
'subroutine matrix_vector(A, m, n, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(inout), dimension(1:m) :: y\n'
'end subroutine\n'
'end interface\n'
)
def test_partial_loops_f():
# check that loop boundaries are determined by Idx, and array strides
# determined by shape of IndexedBase object.
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A', shape=(m, p))
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', (o, m - 5)) # Note: bounds are inclusive
j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1)
(f1, code), (f2, interface) = codegen(
('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False)
expected = (
'subroutine matrix_vector(A, m, n, o, p, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'INTEGER*4, intent(in) :: n\n'
'INTEGER*4, intent(in) :: o\n'
'INTEGER*4, intent(in) :: p\n'
'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n'
'REAL*8, intent(in), dimension(1:n) :: x\n'
'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n'
'INTEGER*4 :: i\n'
'INTEGER*4 :: j\n'
'do i = %(ilow)s, %(iup)s\n'
' y(i) = 0\n'
'end do\n'
'do i = %(ilow)s, %(iup)s\n'
' do j = 1, n\n'
' y(i) = %(rhs)s + y(i)\n'
' end do\n'
'end do\n'
'end subroutine\n'
) % {
'rhs': '%(rhs)s',
'iup': str(m - 4),
'ilow': str(1 + o),
'iup-ilow': str(m - 4 - o)
}
assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\
code == expected % {'rhs': 'x(j)*A(i, j)'}
def test_output_arg_f():
from sympy import sin, cos, Equality
x, y, z = symbols("x,y,z")
r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
c = FCodeGen()
result = c.write([r], "test", header=False, empty=False)
assert result[0][0] == "test.f90"
assert result[0][1] == (
'REAL*8 function foo(x, y)\n'
'implicit none\n'
'REAL*8, intent(in) :: x\n'
'REAL*8, intent(out) :: y\n'
'y = sin(x)\n'
'foo = cos(x)\n'
'end function\n'
)
def test_inline_function():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m = symbols('n m', integer=True)
A, x, y = map(IndexedBase, 'Axy')
i = Idx('i', m)
p = FCodeGen()
func = implemented_function('func', Lambda(n, n*(n + 1)))
routine = make_routine('test_inline', Eq(y[i], func(x[i])))
code = get_string(p.dump_f95, [routine])
expected = (
'subroutine test_inline(m, x, y)\n'
'implicit none\n'
'INTEGER*4, intent(in) :: m\n'
'REAL*8, intent(in), dimension(1:m) :: x\n'
'REAL*8, intent(out), dimension(1:m) :: y\n'
'INTEGER*4 :: i\n'
'do i = 1, m\n'
' y(i) = %s*%s\n'
'end do\n'
'end subroutine\n'
)
args = ('x(i)', '(x(i) + 1)')
assert code == expected % args or\
code == expected % args[::-1]
def test_f_code_call_signature_wrap():
# Issue #7934
x = symbols('x:20')
expr = 0
for sym in x:
expr += sym
routine = make_routine("test", expr)
code_gen = FCodeGen()
source = get_string(code_gen.dump_f95, [routine])
expected = """\
REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, &
x19, x2, x3, x4, x5, x6, x7, x8, x9)
implicit none
REAL*8, intent(in) :: x0
REAL*8, intent(in) :: x1
REAL*8, intent(in) :: x10
REAL*8, intent(in) :: x11
REAL*8, intent(in) :: x12
REAL*8, intent(in) :: x13
REAL*8, intent(in) :: x14
REAL*8, intent(in) :: x15
REAL*8, intent(in) :: x16
REAL*8, intent(in) :: x17
REAL*8, intent(in) :: x18
REAL*8, intent(in) :: x19
REAL*8, intent(in) :: x2
REAL*8, intent(in) :: x3
REAL*8, intent(in) :: x4
REAL*8, intent(in) :: x5
REAL*8, intent(in) :: x6
REAL*8, intent(in) :: x7
REAL*8, intent(in) :: x8
REAL*8, intent(in) :: x9
test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + &
x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
end function
"""
assert source == expected
def test_check_case():
x, X = symbols('x,X')
raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix'))
def test_check_case_false_positive():
# The upper case/lower case exception should not be triggered by SymPy
# objects that differ only because of assumptions. (It may be useful to
# have a check for that as well, but here we only want to test against
# false positives with respect to case checking.)
x1 = symbols('x')
x2 = symbols('x', my_assumption=True)
try:
codegen(('test', x1*x2), 'f95', 'prefix')
except CodeGenError as e:
if e.args[0].startswith("Fortran ignores case."):
raise AssertionError("This exception should not be raised!")
def test_c_fortran_omit_routine_name():
x, y = symbols("x,y")
name_expr = [("foo", 2*x)]
result = codegen(name_expr, "F95", header=False, empty=False)
expresult = codegen(name_expr, "F95", "foo", header=False, empty=False)
assert result[0][1] == expresult[0][1]
name_expr = ("foo", x*y)
result = codegen(name_expr, "F95", header=False, empty=False)
expresult = codegen(name_expr, "F95", "foo", header=False, empty=False)
assert result[0][1] == expresult[0][1]
name_expr = ("foo", Matrix([[x, y], [x+y, x-y]]))
result = codegen(name_expr, "C89", header=False, empty=False)
expresult = codegen(name_expr, "C89", "foo", header=False, empty=False)
assert result[0][1] == expresult[0][1]
def test_fcode_matrix_output():
x, y, z = symbols('x,y,z')
e1 = x + y
e2 = Matrix([[x, y], [z, 16]])
name_expr = ("test", (e1, e2))
result = codegen(name_expr, "f95", "test", header=False, empty=False)
source = result[0][1]
expected = (
"REAL*8 function test(x, y, z, out_%(hash)s)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(in) :: z\n"
"REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n"
"out_%(hash)s(1, 1) = x\n"
"out_%(hash)s(2, 1) = z\n"
"out_%(hash)s(1, 2) = y\n"
"out_%(hash)s(2, 2) = 16\n"
"test = x + y\n"
"end function\n"
)
# look for the magic number
a = source.splitlines()[5]
b = a.split('_')
out = b[1]
expected = expected % {'hash': out}
assert source == expected
def test_fcode_results_named_ordered():
x, y, z = symbols('x,y,z')
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(A, Matrix([[1, 2, x]]))
expr2 = Equality(C, (x + y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "f95", "test", header=False, empty=False,
argument_sequence=(x, z, y, C, A, B))
source = result[0][1]
expected = (
"subroutine test(x, z, y, C, A, B)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: z\n"
"REAL*8, intent(in) :: y\n"
"REAL*8, intent(out) :: C\n"
"REAL*8, intent(out) :: B\n"
"REAL*8, intent(out), dimension(1:1, 1:3) :: A\n"
"C = z*(x + y)\n"
"A(1, 1) = 1\n"
"A(1, 2) = 2\n"
"A(1, 3) = x\n"
"B = 2*x\n"
"end subroutine\n"
)
assert source == expected
def test_fcode_matrixsymbol_slice():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 1, 3)
D = MatrixSymbol('D', 2, 1)
name_expr = ("test", [Equality(B, A[0, :]),
Equality(C, A[1, :]),
Equality(D, A[:, 2])])
result = codegen(name_expr, "f95", "test", header=False, empty=False)
source = result[0][1]
expected = (
"subroutine test(A, B, C, D)\n"
"implicit none\n"
"REAL*8, intent(in), dimension(1:2, 1:3) :: A\n"
"REAL*8, intent(out), dimension(1:1, 1:3) :: B\n"
"REAL*8, intent(out), dimension(1:1, 1:3) :: C\n"
"REAL*8, intent(out), dimension(1:2, 1:1) :: D\n"
"B(1, 1) = A(1, 1)\n"
"B(1, 2) = A(1, 2)\n"
"B(1, 3) = A(1, 3)\n"
"C(1, 1) = A(2, 1)\n"
"C(1, 2) = A(2, 2)\n"
"C(1, 3) = A(2, 3)\n"
"D(1, 1) = A(1, 3)\n"
"D(2, 1) = A(2, 3)\n"
"end subroutine\n"
)
assert source == expected
def test_fcode_matrixsymbol_slice_autoname():
# see issue #8093
A = MatrixSymbol('A', 2, 3)
name_expr = ("test", A[:, 1])
result = codegen(name_expr, "f95", "test", header=False, empty=False)
source = result[0][1]
expected = (
"subroutine test(A, out_%(hash)s)\n"
"implicit none\n"
"REAL*8, intent(in), dimension(1:2, 1:3) :: A\n"
"REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n"
"out_%(hash)s(1, 1) = A(1, 2)\n"
"out_%(hash)s(2, 1) = A(2, 2)\n"
"end subroutine\n"
)
# look for the magic number
a = source.splitlines()[3]
b = a.split('_')
out = b[1]
expected = expected % {'hash': out}
assert source == expected
def test_global_vars():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "F95", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"REAL*8 function f(x)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"f = x*y\n"
"end function\n"
)
assert source == expected
expected = (
'#include "f.h"\n'
'#include <math.h>\n'
'double f(double x, double y) {\n'
' double f_result;\n'
' f_result = x*y + z;\n'
' return f_result;\n'
'}\n'
)
result = codegen(('f', x*y+z), "C", header=False, empty=False,
global_vars=(z, t))
source = result[0][1]
assert source == expected
def test_custom_codegen():
from sympy.printing.c import C99CodePrinter
from sympy.functions.elementary.exponential import exp
printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}})
x, y = symbols('x y')
expr = exp(x + y)
# replace math.h with a different header
gen = C99CodeGen(printer=printer,
preprocessor_statements=['#include "fastexp.h"'])
expected = (
'#include "expr.h"\n'
'#include "fastexp.h"\n'
'double expr(double x, double y) {\n'
' double expr_result;\n'
' expr_result = fastexp(x + y);\n'
' return expr_result;\n'
'}\n'
)
result = codegen(('expr', expr), header=False, empty=False, code_gen=gen)
source = result[0][1]
assert source == expected
# use both math.h and an external header
gen = C99CodeGen(printer=printer)
gen.preprocessor_statements.append('#include "fastexp.h"')
expected = (
'#include "expr.h"\n'
'#include <math.h>\n'
'#include "fastexp.h"\n'
'double expr(double x, double y) {\n'
' double expr_result;\n'
' expr_result = fastexp(x + y);\n'
' return expr_result;\n'
'}\n'
)
result = codegen(('expr', expr), header=False, empty=False, code_gen=gen)
source = result[0][1]
assert source == expected
def test_c_with_printer():
#issue 13586
from sympy.printing.c import C99CodePrinter
class CustomPrinter(C99CodePrinter):
def _print_Pow(self, expr):
return "fastpow({}, {})".format(self._print(expr.base),
self._print(expr.exp))
x = symbols('x')
expr = x**3
expected =[
("file.c",
"#include \"file.h\"\n"
"#include <math.h>\n"
"double test(double x) {\n"
" double test_result;\n"
" test_result = fastpow(x, 3);\n"
" return test_result;\n"
"}\n"),
("file.h",
"#ifndef PROJECT__FILE__H\n"
"#define PROJECT__FILE__H\n"
"double test(double x);\n"
"#endif\n")
]
result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter())
assert result == expected
def test_fcode_complex():
import sympy.utilities.codegen
sympy.utilities.codegen.COMPLEX_ALLOWED = True
x = Symbol('x', real=True)
y = Symbol('y',real=True)
result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False)
source = (result[0][1])
expected = (
"REAL*8 function test(x, y)\n"
"implicit none\n"
"REAL*8, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"test = x + y\n"
"end function\n")
assert source == expected
x = Symbol('x')
y = Symbol('y',real=True)
result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False)
source = (result[0][1])
expected = (
"COMPLEX*16 function test(x, y)\n"
"implicit none\n"
"COMPLEX*16, intent(in) :: x\n"
"REAL*8, intent(in) :: y\n"
"test = x + y\n"
"end function\n"
)
assert source==expected
sympy.utilities.codegen.COMPLEX_ALLOWED = False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.