I am done

This commit is contained in:
2024-10-30 22:14:35 +01:00
parent 720dc28c09
commit 40e2a747cf
36901 changed files with 5011519 additions and 0 deletions

View File

@ -0,0 +1,469 @@
# Tests that require installed backends go into
# sympy/test_external/test_autowrap
import os
import tempfile
import shutil
from io import StringIO
from sympy.core import symbols, Eq
from sympy.utilities.autowrap import (autowrap, binary_function,
CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper)
from sympy.utilities.codegen import (
CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine
)
from sympy.testing.pytest import raises
from sympy.testing.tmpfiles import TmpFileManager
def get_string(dump_fn, routines, prefix="file", **kwargs):
"""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 generator to facilitate the
testing of the output.
"""
output = StringIO()
dump_fn(routines, output, prefix, **kwargs)
source = output.getvalue()
output.close()
return source
def test_cython_wrapper_scalar_function():
x, y, z = symbols('x,y,z')
expr = (x + y)*z
routine = make_routine("test", expr)
code_gen = CythonCodeWrapper(CCodeGen())
source = get_string(code_gen.dump_pyx, [routine])
expected = (
"cdef extern from 'file.h':\n"
" double test(double x, double y, double z)\n"
"\n"
"def test_c(double x, double y, double z):\n"
"\n"
" return test(x, y, z)")
assert source == expected
def test_cython_wrapper_outarg():
from sympy.core.relational import Equality
x, y, z = symbols('x,y,z')
code_gen = CythonCodeWrapper(C99CodeGen())
routine = make_routine("test", Equality(z, x + y))
source = get_string(code_gen.dump_pyx, [routine])
expected = (
"cdef extern from 'file.h':\n"
" void test(double x, double y, double *z)\n"
"\n"
"def test_c(double x, double y):\n"
"\n"
" cdef double z = 0\n"
" test(x, y, &z)\n"
" return z")
assert source == expected
def test_cython_wrapper_inoutarg():
from sympy.core.relational import Equality
x, y, z = symbols('x,y,z')
code_gen = CythonCodeWrapper(C99CodeGen())
routine = make_routine("test", Equality(z, x + y + z))
source = get_string(code_gen.dump_pyx, [routine])
expected = (
"cdef extern from 'file.h':\n"
" void test(double x, double y, double *z)\n"
"\n"
"def test_c(double x, double y, double z):\n"
"\n"
" test(x, y, &z)\n"
" return z")
assert source == expected
def test_cython_wrapper_compile_flags():
from sympy.core.relational import Equality
x, y, z = symbols('x,y,z')
routine = make_routine("test", Equality(z, x + y))
code_gen = CythonCodeWrapper(CCodeGen())
expected = """\
from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
cy_opts = {'compiler_directives': {'language_level': '3'}}
ext_mods = [Extension(
'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
include_dirs=[],
library_dirs=[],
libraries=[],
extra_compile_args=['-std=c99'],
extra_link_args=[]
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
""" % {'num': CodeWrapper._module_counter}
temp_dir = tempfile.mkdtemp()
TmpFileManager.tmp_folder(temp_dir)
setup_file_path = os.path.join(temp_dir, 'setup.py')
code_gen._prepare_files(routine, build_dir=temp_dir)
with open(setup_file_path) as f:
setup_text = f.read()
assert setup_text == expected
code_gen = CythonCodeWrapper(CCodeGen(),
include_dirs=['/usr/local/include', '/opt/booger/include'],
library_dirs=['/user/local/lib'],
libraries=['thelib', 'nilib'],
extra_compile_args=['-slow-math'],
extra_link_args=['-lswamp', '-ltrident'],
cythonize_options={'compiler_directives': {'boundscheck': False}}
)
expected = """\
from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
cy_opts = {'compiler_directives': {'boundscheck': False}}
ext_mods = [Extension(
'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
include_dirs=['/usr/local/include', '/opt/booger/include'],
library_dirs=['/user/local/lib'],
libraries=['thelib', 'nilib'],
extra_compile_args=['-slow-math', '-std=c99'],
extra_link_args=['-lswamp', '-ltrident']
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
""" % {'num': CodeWrapper._module_counter}
code_gen._prepare_files(routine, build_dir=temp_dir)
with open(setup_file_path) as f:
setup_text = f.read()
assert setup_text == expected
expected = """\
from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
cy_opts = {'compiler_directives': {'boundscheck': False}}
import numpy as np
ext_mods = [Extension(
'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()],
library_dirs=['/user/local/lib'],
libraries=['thelib', 'nilib'],
extra_compile_args=['-slow-math', '-std=c99'],
extra_link_args=['-lswamp', '-ltrident']
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
""" % {'num': CodeWrapper._module_counter}
code_gen._need_numpy = True
code_gen._prepare_files(routine, build_dir=temp_dir)
with open(setup_file_path) as f:
setup_text = f.read()
assert setup_text == expected
TmpFileManager.cleanup()
def test_cython_wrapper_unique_dummyvars():
from sympy.core.relational import Equality
from sympy.core.symbol import Dummy
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]]
expr = Equality(z, x + y)
routine = make_routine("test", expr)
code_gen = CythonCodeWrapper(CCodeGen())
source = get_string(code_gen.dump_pyx, [routine])
expected_template = (
"cdef extern from 'file.h':\n"
" void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n"
"\n"
"def test_c(double x_{x_id}, double y_{y_id}):\n"
"\n"
" cdef double z_{z_id} = 0\n"
" test(x_{x_id}, y_{y_id}, &z_{z_id})\n"
" return z_{z_id}")
expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id)
assert source == expected
def test_autowrap_dummy():
x, y, z = symbols('x y z')
# Uses DummyWrapper to test that codegen works as expected
f = autowrap(x + y, backend='dummy')
assert f() == str(x + y)
assert f.args == "x, y"
assert f.returns == "nameless"
f = autowrap(Eq(z, x + y), backend='dummy')
assert f() == str(x + y)
assert f.args == "x, y"
assert f.returns == "z"
f = autowrap(Eq(z, x + y + z), backend='dummy')
assert f() == str(x + y + z)
assert f.args == "x, y, z"
assert f.returns == "z"
def test_autowrap_args():
x, y, z = symbols('x y z')
raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y),
backend='dummy', args=[x]))
f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x])
assert f() == str(x + y)
assert f.args == "y, x"
assert f.returns == "z"
raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z),
backend='dummy', args=[x, y]))
f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z])
assert f() == str(x + y + z)
assert f.args == "y, x, z"
assert f.returns == "z"
f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z))
assert f() == str(x + y + z)
assert f.args == "y, x, z"
assert f.returns == "z"
def test_autowrap_store_files():
x, y = symbols('x y')
tmp = tempfile.mkdtemp()
TmpFileManager.tmp_folder(tmp)
f = autowrap(x + y, backend='dummy', tempdir=tmp)
assert f() == str(x + y)
assert os.access(tmp, os.F_OK)
TmpFileManager.cleanup()
def test_autowrap_store_files_issue_gh12939():
x, y = symbols('x y')
tmp = './tmp'
saved_cwd = os.getcwd()
temp_cwd = tempfile.mkdtemp()
try:
os.chdir(temp_cwd)
f = autowrap(x + y, backend='dummy', tempdir=tmp)
assert f() == str(x + y)
assert os.access(tmp, os.F_OK)
finally:
os.chdir(saved_cwd)
shutil.rmtree(temp_cwd)
def test_binary_function():
x, y = symbols('x y')
f = binary_function('f', x + y, backend='dummy')
assert f._imp_() == str(x + y)
def test_ufuncify_source():
x, y, z = symbols('x,y,z')
code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"))
routine = make_routine("test", x + y + z)
source = get_string(code_wrapper.dump_c, [routine])
expected = """\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include "file.h"
static PyMethodDef wrapper_module_%(num)sMethods[] = {
{NULL, NULL, 0, NULL}
};
#ifdef NPY_1_19_API_VERSION
static void test_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data)
#else
static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
#endif
{
npy_intp i;
npy_intp n = dimensions[0];
char *in0 = args[0];
char *in1 = args[1];
char *in2 = args[2];
char *out0 = args[3];
npy_intp in0_step = steps[0];
npy_intp in1_step = steps[1];
npy_intp in2_step = steps[2];
npy_intp out0_step = steps[3];
for (i = 0; i < n; i++) {
*((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2);
in0 += in0_step;
in1 += in1_step;
in2 += in2_step;
out0 += out0_step;
}
}
PyUFuncGenericFunction test_funcs[1] = {&test_ufunc};
static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};
static void *test_data[1] = {NULL};
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"wrapper_module_%(num)s",
NULL,
-1,
wrapper_module_%(num)sMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "test", ufunc0);
Py_DECREF(ufunc0);
return m;
}
#else
PyMODINIT_FUNC initwrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "test", ufunc0);
Py_DECREF(ufunc0);
}
#endif""" % {'num': CodeWrapper._module_counter}
assert source == expected
def test_ufuncify_source_multioutput():
x, y, z = symbols('x,y,z')
var_symbols = (x, y, z)
expr = x + y**3 + 10*z**2
code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"))
routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))]
source = get_string(code_wrapper.dump_c, routines, funcname='multitest')
expected = """\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include "file.h"
static PyMethodDef wrapper_module_%(num)sMethods[] = {
{NULL, NULL, 0, NULL}
};
#ifdef NPY_1_19_API_VERSION
static void multitest_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data)
#else
static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
#endif
{
npy_intp i;
npy_intp n = dimensions[0];
char *in0 = args[0];
char *in1 = args[1];
char *in2 = args[2];
char *out0 = args[3];
char *out1 = args[4];
char *out2 = args[5];
npy_intp in0_step = steps[0];
npy_intp in1_step = steps[1];
npy_intp in2_step = steps[2];
npy_intp out0_step = steps[3];
npy_intp out1_step = steps[4];
npy_intp out2_step = steps[5];
for (i = 0; i < n; i++) {
*((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2);
*((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2);
*((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2);
in0 += in0_step;
in1 += in1_step;
in2 += in2_step;
out0 += out0_step;
out1 += out1_step;
out2 += out2_step;
}
}
PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc};
static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};
static void *multitest_data[1] = {NULL};
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"wrapper_module_%(num)s",
NULL,
-1,
wrapper_module_%(num)sMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "multitest", ufunc0);
Py_DECREF(ufunc0);
return m;
}
#else
PyMODINIT_FUNC initwrapper_module_%(num)s(void)
{
PyObject *m, *d;
PyObject *ufunc0;
m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3,
PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
PyDict_SetItemString(d, "multitest", ufunc0);
Py_DECREF(ufunc0);
}
#endif""" % {'num': CodeWrapper._module_counter}
assert source == expected

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,620 @@
from io import StringIO
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
from sympy.core.relational import Equality
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_jl_code():
code_gen = JuliaCodeGen()
output = StringIO()
code_gen.dump_jl([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_jl_simple_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0] == "test.jl"
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = z .* (x + y)\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_simple_code_with_header():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Julia", header=True, empty=False)
assert result[0] == "test.jl"
source = result[1]
expected = (
"# Code generated with SymPy " + sympy.__version__ + "\n"
"#\n"
"# See http://www.sympy.org/ for more information.\n"
"#\n"
"# This file is part of 'project'\n"
"function test(x, y, z)\n"
" out1 = z .* (x + y)\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_simple_code_nameout():
expr = Equality(z, (x + y))
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y)\n"
" z = x + y\n"
" return z\n"
"end\n"
)
assert source == expected
def test_jl_numbersymbol():
name_expr = ("test", pi**Catalan)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test()\n"
" out1 = pi ^ catalan\n"
" return out1\n"
"end\n"
)
assert source == expected
@XFAIL
def test_jl_numbersymbol_no_inline():
# FIXME: how to pass inline=False to the JuliaCodePrinter?
name_expr = ("test", [pi**Catalan, EulerGamma])
result, = codegen(name_expr, "Julia", header=False,
empty=False, inline=False)
source = result[1]
expected = (
"function test()\n"
" Catalan = 0.915965594177219\n"
" EulerGamma = 0.5772156649015329\n"
" out1 = pi ^ Catalan\n"
" out2 = EulerGamma\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_code_argument_order():
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia")
code_gen = JuliaCodeGen()
output = StringIO()
code_gen.dump_jl([routine], output, "test", header=False, empty=False)
source = output.getvalue()
expected = (
"function test(z, x, y)\n"
" out1 = x + y\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_multiple_results_m():
# Here the output order is the input order
expr1 = (x + y)*z
expr2 = (x - y)*z
name_expr = ("test", [expr1, expr2])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = z .* (x + y)\n"
" out2 = z .* (x - y)\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_results_named_unordered():
# Here output order is based on name_expr
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" C = z .* (x + y)\n"
" A = z .* (x - y)\n"
" B = 2 * x\n"
" return C, A, B\n"
"end\n"
)
assert source == expected
def test_results_named_ordered():
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "Julia", header=False, empty=False,
argument_sequence=(x, z, y))
assert result[0][0] == "test.jl"
source = result[0][1]
expected = (
"function test(x, z, y)\n"
" C = z .* (x + y)\n"
" A = z .* (x - y)\n"
" B = 2 * x\n"
" return C, A, B\n"
"end\n"
)
assert source == expected
def test_complicated_jl_codegen():
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
name_expr = ("testlong",
[ ((sin(x) + cos(y) + tan(z))**3).expand(),
cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
])
result = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0][0] == "testlong.jl"
source = result[0][1]
expected = (
"function testlong(x, y, z)\n"
" out1 = sin(x) .^ 3 + 3 * sin(x) .^ 2 .* cos(y) + 3 * sin(x) .^ 2 .* tan(z)"
" + 3 * sin(x) .* cos(y) .^ 2 + 6 * sin(x) .* cos(y) .* tan(z) + 3 * sin(x) .* tan(z) .^ 2"
" + cos(y) .^ 3 + 3 * cos(y) .^ 2 .* tan(z) + 3 * cos(y) .* tan(z) .^ 2 + tan(z) .^ 3\n"
" out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_output_arg_mixed_unordered():
# named outputs are alphabetical, unnamed output appear in the given order
from sympy.functions.elementary.trigonometric import (cos, sin)
a = symbols("a")
name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
result, = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0] == "foo.jl"
source = result[1];
expected = (
'function foo(x)\n'
' out1 = cos(2 * x)\n'
' y = sin(x)\n'
' out3 = cos(x)\n'
' a = sin(2 * x)\n'
' return out1, y, out3, a\n'
'end\n'
)
assert source == expected
def test_jl_piecewise_():
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function pwtest(x)\n"
" out1 = ((x < -1) ? (0) :\n"
" (x <= 1) ? (x .^ 2) :\n"
" (x > 1) ? (2 - x) : (1))\n"
" return out1\n"
"end\n"
)
assert source == expected
@XFAIL
def test_jl_piecewise_no_inline():
# FIXME: how to pass inline=False to the JuliaCodePrinter?
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Julia", header=False, empty=False,
inline=False)
source = result[1]
expected = (
"function pwtest(x)\n"
" if (x < -1)\n"
" out1 = 0\n"
" elseif (x <= 1)\n"
" out1 = x .^ 2\n"
" elseif (x > 1)\n"
" out1 = -x + 2\n"
" else\n"
" out1 = 1\n"
" end\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_multifcns_per_file():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0][0] == "foo.jl"
source = result[0][1];
expected = (
"function foo(x, y)\n"
" out1 = 2 * x\n"
" out2 = 3 * y\n"
" return out1, out2\n"
"end\n"
"function bar(y)\n"
" out1 = y .^ 2\n"
" out2 = 4 * y\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_multifcns_per_file_w_header():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Julia", header=True, empty=False)
assert result[0][0] == "foo.jl"
source = result[0][1];
expected = (
"# Code generated with SymPy " + sympy.__version__ + "\n"
"#\n"
"# See http://www.sympy.org/ for more information.\n"
"#\n"
"# This file is part of 'project'\n"
"function foo(x, y)\n"
" out1 = 2 * x\n"
" out2 = 3 * y\n"
" return out1, out2\n"
"end\n"
"function bar(y)\n"
" out1 = y .^ 2\n"
" out2 = 4 * y\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_jl_filename_match_prefix():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result, = codegen(name_expr, "Julia", prefix="baz", header=False,
empty=False)
assert result[0] == "baz.jl"
def test_jl_matrix_named():
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
result = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0][0] == "test.jl"
source = result[0][1]
expected = (
"function test(x, y, z)\n"
" myout1 = [x 2 * y pi * z]\n"
" return myout1\n"
"end\n"
)
assert source == expected
def test_jl_matrix_named_matsym():
myout1 = MatrixSymbol('myout1', 1, 3)
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(myout1, e2, evaluate=False))
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" myout1 = [x 2 * y pi * z]\n"
" return myout1\n"
"end\n"
)
assert source == expected
def test_jl_matrix_output_autoname():
expr = Matrix([[x, x+y, 3]])
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y)\n"
" out1 = [x x + y 3]\n"
" return out1\n"
"end\n"
)
assert source == expected
def test_jl_matrix_output_autoname_2():
e1 = (x + y)
e2 = Matrix([[2*x, 2*y, 2*z]])
e3 = Matrix([[x], [y], [z]])
e4 = Matrix([[x, y], [z, 16]])
name_expr = ("test", (e1, e2, e3, e4))
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = x + y\n"
" out2 = [2 * x 2 * y 2 * z]\n"
" out3 = [x, y, z]\n"
" out4 = [x y;\n"
" z 16]\n"
" return out1, out2, out3, out4\n"
"end\n"
)
assert source == expected
def test_jl_results_matrix_named_ordered():
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, Matrix([[1, 2, x]]))
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Julia", header=False, empty=False,
argument_sequence=(x, z, y))
source = result[1]
expected = (
"function test(x, z, y)\n"
" C = z .* (x + y)\n"
" A = [1 2 x]\n"
" B = 2 * x\n"
" return C, A, B\n"
"end\n"
)
assert source == expected
def test_jl_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, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[1,:]\n"
" C = A[2,:]\n"
" D = A[:,3]\n"
" return B, C, D\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice2():
A = MatrixSymbol('A', 3, 4)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 2, 2)
name_expr = ("test", [Equality(B, A[0:2, 0:2]),
Equality(C, A[0:2, 1:3])])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[1:2,1:2]\n"
" C = A[1:2,2:3]\n"
" return B, C\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice3():
A = MatrixSymbol('A', 8, 7)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 4, 2)
name_expr = ("test", [Equality(B, A[6:, 1::3]),
Equality(C, A[::2, ::3])])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[7:end,2:3:end]\n"
" C = A[1:2:end,1:3:end]\n"
" return B, C\n"
"end\n"
)
assert source == expected
def test_jl_matrixsymbol_slice_autoname():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(A)\n"
" B = A[1,:]\n"
" out2 = A[2,:]\n"
" out3 = A[:,1]\n"
" out4 = A[:,2]\n"
" return B, out2, out3, out4\n"
"end\n"
)
assert source == expected
def test_jl_loops():
# Note: an Julia programmer would probably vectorize this across one or
# more dimensions. Also, size(A) would be used rather than passing in m
# and n. Perhaps users would expect us to vectorize automatically here?
# Or is it possible to represent such things using IndexedBase?
from sympy.tensor import IndexedBase, Idx
from sympy.core.symbol 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)
result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Julia",
header=False, empty=False)
source = result[1]
expected = (
'function mat_vec_mult(y, A, m, n, x)\n'
' for i = 1:m\n'
' y[i] = 0\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' y[i] = %(rhs)s + y[i]\n'
' end\n'
' end\n'
' return y\n'
'end\n'
)
assert (source == expected % {'rhs': 'A[%s,%s] .* x[j]' % (i, j)} or
source == expected % {'rhs': 'x[j] .* A[%s,%s]' % (i, j)})
def test_jl_tensor_loops_multiple_contractions():
# see comments in previous test about vectorizing
from sympy.tensor import IndexedBase, Idx
from sympy.core.symbol import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A')
B = IndexedBase('B')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
"Julia", header=False, empty=False)
source = result[1]
expected = (
'function tensorthing(y, A, B, m, n, o, p)\n'
' for i = 1:m\n'
' y[i] = 0\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' for k = 1:o\n'
' for l = 1:p\n'
' y[i] = A[i,j,k,l] .* B[j,k,l] + y[i]\n'
' end\n'
' end\n'
' end\n'
' end\n'
' return y\n'
'end\n'
)
assert source == expected
def test_jl_InOutArgument():
expr = Equality(x, x**2)
name_expr = ("mysqr", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function mysqr(x)\n"
" x = x .^ 2\n"
" return x\n"
"end\n"
)
assert source == expected
def test_jl_InOutArgument_order():
# can specify the order as (x, y)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False,
empty=False, argument_sequence=(x,y))
source = result[1]
expected = (
"function test(x, y)\n"
" x = x .^ 2 + y\n"
" return x\n"
"end\n"
)
assert source == expected
# make sure it gives (x, y) not (y, x)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x, y)\n"
" x = x .^ 2 + y\n"
" return x\n"
"end\n"
)
assert source == expected
def test_jl_not_supported():
f = Function('f')
name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
result, = codegen(name_expr, "Julia", header=False, empty=False)
source = result[1]
expected = (
"function test(x)\n"
" # unsupported: Derivative(f(x), x)\n"
" # unsupported: zoo\n"
" out1 = Derivative(f(x), x)\n"
" out2 = zoo\n"
" return out1, out2\n"
"end\n"
)
assert source == expected
def test_global_vars_octave():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Julia", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"function f(x)\n"
" out1 = x .* y\n"
" return out1\n"
"end\n"
)
assert source == expected
result = codegen(('f', x*y+z), "Julia", header=False, empty=False,
argument_sequence=(x, y), global_vars=(z, t))
source = result[0][1]
expected = (
"function f(x, y)\n"
" out1 = x .* y + z\n"
" return out1\n"
"end\n"
)
assert source == expected

View File

@ -0,0 +1,589 @@
from io import StringIO
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
from sympy.core.relational import Equality
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import OctaveCodeGen, codegen, make_routine
from sympy.testing.pytest import raises
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_m_code():
code_gen = OctaveCodeGen()
output = StringIO()
code_gen.dump_m([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_m_simple_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0] == "test.m"
source = result[1]
expected = (
"function out1 = test(x, y, z)\n"
" out1 = z.*(x + y);\n"
"end\n"
)
assert source == expected
def test_m_simple_code_with_header():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Octave", header=True, empty=False)
assert result[0] == "test.m"
source = result[1]
expected = (
"function out1 = test(x, y, z)\n"
" %TEST Autogenerated by SymPy\n"
" % Code generated with SymPy " + sympy.__version__ + "\n"
" %\n"
" % See http://www.sympy.org/ for more information.\n"
" %\n"
" % This file is part of 'project'\n"
" out1 = z.*(x + y);\n"
"end\n"
)
assert source == expected
def test_m_simple_code_nameout():
expr = Equality(z, (x + y))
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function z = test(x, y)\n"
" z = x + y;\n"
"end\n"
)
assert source == expected
def test_m_numbersymbol():
name_expr = ("test", pi**Catalan)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function out1 = test()\n"
" out1 = pi^%s;\n"
"end\n"
) % Catalan.evalf(17)
assert source == expected
@XFAIL
def test_m_numbersymbol_no_inline():
# FIXME: how to pass inline=False to the OctaveCodePrinter?
name_expr = ("test", [pi**Catalan, EulerGamma])
result, = codegen(name_expr, "Octave", header=False,
empty=False, inline=False)
source = result[1]
expected = (
"function [out1, out2] = test()\n"
" Catalan = 0.915965594177219; % constant\n"
" EulerGamma = 0.5772156649015329; % constant\n"
" out1 = pi^Catalan;\n"
" out2 = EulerGamma;\n"
"end\n"
)
assert source == expected
def test_m_code_argument_order():
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y], language="octave")
code_gen = OctaveCodeGen()
output = StringIO()
code_gen.dump_m([routine], output, "test", header=False, empty=False)
source = output.getvalue()
expected = (
"function out1 = test(z, x, y)\n"
" out1 = x + y;\n"
"end\n"
)
assert source == expected
def test_multiple_results_m():
# Here the output order is the input order
expr1 = (x + y)*z
expr2 = (x - y)*z
name_expr = ("test", [expr1, expr2])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [out1, out2] = test(x, y, z)\n"
" out1 = z.*(x + y);\n"
" out2 = z.*(x - y);\n"
"end\n"
)
assert source == expected
def test_results_named_unordered():
# Here output order is based on name_expr
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [C, A, B] = test(x, y, z)\n"
" C = z.*(x + y);\n"
" A = z.*(x - y);\n"
" B = 2*x;\n"
"end\n"
)
assert source == expected
def test_results_named_ordered():
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "Octave", header=False, empty=False,
argument_sequence=(x, z, y))
assert result[0][0] == "test.m"
source = result[0][1]
expected = (
"function [C, A, B] = test(x, z, y)\n"
" C = z.*(x + y);\n"
" A = z.*(x - y);\n"
" B = 2*x;\n"
"end\n"
)
assert source == expected
def test_complicated_m_codegen():
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
name_expr = ("testlong",
[ ((sin(x) + cos(y) + tan(z))**3).expand(),
cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
])
result = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0][0] == "testlong.m"
source = result[0][1]
expected = (
"function [out1, out2] = testlong(x, y, z)\n"
" out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)"
" + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2"
" + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3;\n"
" out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n"
"end\n"
)
assert source == expected
def test_m_output_arg_mixed_unordered():
# named outputs are alphabetical, unnamed output appear in the given order
from sympy.functions.elementary.trigonometric import (cos, sin)
a = symbols("a")
name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
result, = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0] == "foo.m"
source = result[1];
expected = (
'function [out1, y, out3, a] = foo(x)\n'
' out1 = cos(2*x);\n'
' y = sin(x);\n'
' out3 = cos(x);\n'
' a = sin(2*x);\n'
'end\n'
)
assert source == expected
def test_m_piecewise_():
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function out1 = pwtest(x)\n"
" out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n"
" (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n"
" (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n"
"end\n"
)
assert source == expected
@XFAIL
def test_m_piecewise_no_inline():
# FIXME: how to pass inline=False to the OctaveCodePrinter?
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Octave", header=False, empty=False,
inline=False)
source = result[1]
expected = (
"function out1 = pwtest(x)\n"
" if (x < -1)\n"
" out1 = 0;\n"
" elseif (x <= 1)\n"
" out1 = x.^2;\n"
" elseif (x > 1)\n"
" out1 = -x + 2;\n"
" else\n"
" out1 = 1;\n"
" end\n"
"end\n"
)
assert source == expected
def test_m_multifcns_per_file():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0][0] == "foo.m"
source = result[0][1];
expected = (
"function [out1, out2] = foo(x, y)\n"
" out1 = 2*x;\n"
" out2 = 3*y;\n"
"end\n"
"function [out1, out2] = bar(y)\n"
" out1 = y.^2;\n"
" out2 = 4*y;\n"
"end\n"
)
assert source == expected
def test_m_multifcns_per_file_w_header():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Octave", header=True, empty=False)
assert result[0][0] == "foo.m"
source = result[0][1];
expected = (
"function [out1, out2] = foo(x, y)\n"
" %FOO Autogenerated by SymPy\n"
" % Code generated with SymPy " + sympy.__version__ + "\n"
" %\n"
" % See http://www.sympy.org/ for more information.\n"
" %\n"
" % This file is part of 'project'\n"
" out1 = 2*x;\n"
" out2 = 3*y;\n"
"end\n"
"function [out1, out2] = bar(y)\n"
" out1 = y.^2;\n"
" out2 = 4*y;\n"
"end\n"
)
assert source == expected
def test_m_filename_match_first_fcn():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
raises(ValueError, lambda: codegen(name_expr,
"Octave", prefix="bar", header=False, empty=False))
def test_m_matrix_named():
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
result = codegen(name_expr, "Octave", header=False, empty=False)
assert result[0][0] == "test.m"
source = result[0][1]
expected = (
"function myout1 = test(x, y, z)\n"
" myout1 = [x 2*y pi*z];\n"
"end\n"
)
assert source == expected
def test_m_matrix_named_matsym():
myout1 = MatrixSymbol('myout1', 1, 3)
e2 = Matrix([[x, 2*y, pi*z]])
name_expr = ("test", Equality(myout1, e2, evaluate=False))
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function myout1 = test(x, y, z)\n"
" myout1 = [x 2*y pi*z];\n"
"end\n"
)
assert source == expected
def test_m_matrix_output_autoname():
expr = Matrix([[x, x+y, 3]])
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function out1 = test(x, y)\n"
" out1 = [x x + y 3];\n"
"end\n"
)
assert source == expected
def test_m_matrix_output_autoname_2():
e1 = (x + y)
e2 = Matrix([[2*x, 2*y, 2*z]])
e3 = Matrix([[x], [y], [z]])
e4 = Matrix([[x, y], [z, 16]])
name_expr = ("test", (e1, e2, e3, e4))
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [out1, out2, out3, out4] = test(x, y, z)\n"
" out1 = x + y;\n"
" out2 = [2*x 2*y 2*z];\n"
" out3 = [x; y; z];\n"
" out4 = [x y; z 16];\n"
"end\n"
)
assert source == expected
def test_m_results_matrix_named_ordered():
B, C = symbols('B,C')
A = MatrixSymbol('A', 1, 3)
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, Matrix([[1, 2, x]]))
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Octave", header=False, empty=False,
argument_sequence=(x, z, y))
source = result[1]
expected = (
"function [C, A, B] = test(x, z, y)\n"
" C = z.*(x + y);\n"
" A = [1 2 x];\n"
" B = 2*x;\n"
"end\n"
)
assert source == expected
def test_m_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, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, C, D] = test(A)\n"
" B = A(1, :);\n"
" C = A(2, :);\n"
" D = A(:, 3);\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice2():
A = MatrixSymbol('A', 3, 4)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 2, 2)
name_expr = ("test", [Equality(B, A[0:2, 0:2]),
Equality(C, A[0:2, 1:3])])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, C] = test(A)\n"
" B = A(1:2, 1:2);\n"
" C = A(1:2, 2:3);\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice3():
A = MatrixSymbol('A', 8, 7)
B = MatrixSymbol('B', 2, 2)
C = MatrixSymbol('C', 4, 2)
name_expr = ("test", [Equality(B, A[6:, 1::3]),
Equality(C, A[::2, ::3])])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, C] = test(A)\n"
" B = A(7:end, 2:3:end);\n"
" C = A(1:2:end, 1:3:end);\n"
"end\n"
)
assert source == expected
def test_m_matrixsymbol_slice_autoname():
A = MatrixSymbol('A', 2, 3)
B = MatrixSymbol('B', 1, 3)
name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [B, out2, out3, out4] = test(A)\n"
" B = A(1, :);\n"
" out2 = A(2, :);\n"
" out3 = A(:, 1);\n"
" out4 = A(:, 2);\n"
"end\n"
)
assert source == expected
def test_m_loops():
# Note: an Octave programmer would probably vectorize this across one or
# more dimensions. Also, size(A) would be used rather than passing in m
# and n. Perhaps users would expect us to vectorize automatically here?
# Or is it possible to represent such things using IndexedBase?
from sympy.tensor import IndexedBase, Idx
from sympy.core.symbol 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)
result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Octave",
header=False, empty=False)
source = result[1]
expected = (
'function y = mat_vec_mult(A, m, n, x)\n'
' for i = 1:m\n'
' y(i) = 0;\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' y(i) = %(rhs)s + y(i);\n'
' end\n'
' end\n'
'end\n'
)
assert (source == expected % {'rhs': 'A(%s, %s).*x(j)' % (i, j)} or
source == expected % {'rhs': 'x(j).*A(%s, %s)' % (i, j)})
def test_m_tensor_loops_multiple_contractions():
# see comments in previous test about vectorizing
from sympy.tensor import IndexedBase, Idx
from sympy.core.symbol import symbols
n, m, o, p = symbols('n m o p', integer=True)
A = IndexedBase('A')
B = IndexedBase('B')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
"Octave", header=False, empty=False)
source = result[1]
expected = (
'function y = tensorthing(A, B, m, n, o, p)\n'
' for i = 1:m\n'
' y(i) = 0;\n'
' end\n'
' for i = 1:m\n'
' for j = 1:n\n'
' for k = 1:o\n'
' for l = 1:p\n'
' y(i) = A(i, j, k, l).*B(j, k, l) + y(i);\n'
' end\n'
' end\n'
' end\n'
' end\n'
'end\n'
)
assert source == expected
def test_m_InOutArgument():
expr = Equality(x, x**2)
name_expr = ("mysqr", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function x = mysqr(x)\n"
" x = x.^2;\n"
"end\n"
)
assert source == expected
def test_m_InOutArgument_order():
# can specify the order as (x, y)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False,
empty=False, argument_sequence=(x,y))
source = result[1]
expected = (
"function x = test(x, y)\n"
" x = x.^2 + y;\n"
"end\n"
)
assert source == expected
# make sure it gives (x, y) not (y, x)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function x = test(x, y)\n"
" x = x.^2 + y;\n"
"end\n"
)
assert source == expected
def test_m_not_supported():
f = Function('f')
name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
result, = codegen(name_expr, "Octave", header=False, empty=False)
source = result[1]
expected = (
"function [out1, out2] = test(x)\n"
" % unsupported: Derivative(f(x), x)\n"
" % unsupported: zoo\n"
" out1 = Derivative(f(x), x);\n"
" out2 = zoo;\n"
"end\n"
)
assert source == expected
def test_global_vars_octave():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Octave", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"function out1 = f(x)\n"
" global y\n"
" out1 = x.*y;\n"
"end\n"
)
assert source == expected
result = codegen(('f', x*y+z), "Octave", header=False, empty=False,
argument_sequence=(x, y), global_vars=(z, t))
source = result[0][1]
expected = (
"function out1 = f(x, y)\n"
" global t z\n"
" out1 = x.*y + z;\n"
"end\n"
)
assert source == expected

View File

@ -0,0 +1,401 @@
from io import StringIO
from sympy.core import S, symbols, pi, Catalan, EulerGamma, Function
from sympy.core.relational import Equality
from sympy.functions.elementary.piecewise import Piecewise
from sympy.utilities.codegen import RustCodeGen, codegen, make_routine
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_rust_code():
code_gen = RustCodeGen()
output = StringIO()
code_gen.dump_rs([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_simple_rust_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0] == "test.rs"
source = result[1]
expected = (
"fn test(x: f64, y: f64, z: f64) -> f64 {\n"
" let out1 = z*(x + y);\n"
" out1\n"
"}\n"
)
assert source == expected
def test_simple_code_with_header():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Rust", header=True, empty=False)
assert result[0] == "test.rs"
source = result[1]
version_str = "Code generated with SymPy %s" % sympy.__version__
version_line = version_str.center(76).rstrip()
expected = (
"/*\n"
" *%(version_line)s\n"
" *\n"
" * See http://www.sympy.org/ for more information.\n"
" *\n"
" * This file is part of 'project'\n"
" */\n"
"fn test(x: f64, y: f64, z: f64) -> f64 {\n"
" let out1 = z*(x + y);\n"
" out1\n"
"}\n"
) % {'version_line': version_line}
assert source == expected
def test_simple_code_nameout():
expr = Equality(z, (x + y))
name_expr = ("test", expr)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64) -> f64 {\n"
" let z = x + y;\n"
" z\n"
"}\n"
)
assert source == expected
def test_numbersymbol():
name_expr = ("test", pi**Catalan)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test() -> f64 {\n"
" const Catalan: f64 = %s;\n"
" let out1 = PI.powf(Catalan);\n"
" out1\n"
"}\n"
) % Catalan.evalf(17)
assert source == expected
@XFAIL
def test_numbersymbol_inline():
# FIXME: how to pass inline to the RustCodePrinter?
name_expr = ("test", [pi**Catalan, EulerGamma])
result, = codegen(name_expr, "Rust", header=False,
empty=False, inline=True)
source = result[1]
expected = (
"fn test() -> (f64, f64) {\n"
" const Catalan: f64 = %s;\n"
" const EulerGamma: f64 = %s;\n"
" let out1 = PI.powf(Catalan);\n"
" let out2 = EulerGamma);\n"
" (out1, out2)\n"
"}\n"
) % (Catalan.evalf(17), EulerGamma.evalf(17))
assert source == expected
def test_argument_order():
expr = x + y
routine = make_routine("test", expr, argument_sequence=[z, x, y], language="rust")
code_gen = RustCodeGen()
output = StringIO()
code_gen.dump_rs([routine], output, "test", header=False, empty=False)
source = output.getvalue()
expected = (
"fn test(z: f64, x: f64, y: f64) -> f64 {\n"
" let out1 = x + y;\n"
" out1\n"
"}\n"
)
assert source == expected
def test_multiple_results_rust():
# Here the output order is the input order
expr1 = (x + y)*z
expr2 = (x - y)*z
name_expr = ("test", [expr1, expr2])
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64, z: f64) -> (f64, f64) {\n"
" let out1 = z*(x + y);\n"
" let out2 = z*(x - y);\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_results_named_unordered():
# Here output order is based on name_expr
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64, z: f64) -> (f64, f64, f64) {\n"
" let C = z*(x + y);\n"
" let A = z*(x - y);\n"
" let B = 2*x;\n"
" (C, A, B)\n"
"}\n"
)
assert source == expected
def test_results_named_ordered():
A, B, C = symbols('A,B,C')
expr1 = Equality(C, (x + y)*z)
expr2 = Equality(A, (x - y)*z)
expr3 = Equality(B, 2*x)
name_expr = ("test", [expr1, expr2, expr3])
result = codegen(name_expr, "Rust", header=False, empty=False,
argument_sequence=(x, z, y))
assert result[0][0] == "test.rs"
source = result[0][1]
expected = (
"fn test(x: f64, z: f64, y: f64) -> (f64, f64, f64) {\n"
" let C = z*(x + y);\n"
" let A = z*(x - y);\n"
" let B = 2*x;\n"
" (C, A, B)\n"
"}\n"
)
assert source == expected
def test_complicated_rs_codegen():
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
name_expr = ("testlong",
[ ((sin(x) + cos(y) + tan(z))**3).expand(),
cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
])
result = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0][0] == "testlong.rs"
source = result[0][1]
expected = (
"fn testlong(x: f64, y: f64, z: f64) -> (f64, f64) {\n"
" let out1 = x.sin().powi(3) + 3*x.sin().powi(2)*y.cos()"
" + 3*x.sin().powi(2)*z.tan() + 3*x.sin()*y.cos().powi(2)"
" + 6*x.sin()*y.cos()*z.tan() + 3*x.sin()*z.tan().powi(2)"
" + y.cos().powi(3) + 3*y.cos().powi(2)*z.tan()"
" + 3*y.cos()*z.tan().powi(2) + z.tan().powi(3);\n"
" let out2 = (x + y + z).cos().cos().cos().cos()"
".cos().cos().cos().cos();\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_output_arg_mixed_unordered():
# named outputs are alphabetical, unnamed output appear in the given order
from sympy.functions.elementary.trigonometric import (cos, sin)
a = symbols("a")
name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
result, = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0] == "foo.rs"
source = result[1];
expected = (
"fn foo(x: f64) -> (f64, f64, f64, f64) {\n"
" let out1 = (2*x).cos();\n"
" let y = x.sin();\n"
" let out3 = x.cos();\n"
" let a = (2*x).sin();\n"
" (out1, y, out3, a)\n"
"}\n"
)
assert source == expected
def test_piecewise_():
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn pwtest(x: f64) -> f64 {\n"
" let out1 = if (x < -1) {\n"
" 0\n"
" } else if (x <= 1) {\n"
" x.powi(2)\n"
" } else if (x > 1) {\n"
" 2 - x\n"
" } else {\n"
" 1\n"
" };\n"
" out1\n"
"}\n"
)
assert source == expected
@XFAIL
def test_piecewise_inline():
# FIXME: how to pass inline to the RustCodePrinter?
pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
name_expr = ("pwtest", pw)
result, = codegen(name_expr, "Rust", header=False, empty=False,
inline=True)
source = result[1]
expected = (
"fn pwtest(x: f64) -> f64 {\n"
" let out1 = if (x < -1) { 0 } else if (x <= 1) { x.powi(2) }"
" else if (x > 1) { -x + 2 } else { 1 };\n"
" out1\n"
"}\n"
)
assert source == expected
def test_multifcns_per_file():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Rust", header=False, empty=False)
assert result[0][0] == "foo.rs"
source = result[0][1];
expected = (
"fn foo(x: f64, y: f64) -> (f64, f64) {\n"
" let out1 = 2*x;\n"
" let out2 = 3*y;\n"
" (out1, out2)\n"
"}\n"
"fn bar(y: f64) -> (f64, f64) {\n"
" let out1 = y.powi(2);\n"
" let out2 = 4*y;\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_multifcns_per_file_w_header():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result = codegen(name_expr, "Rust", header=True, empty=False)
assert result[0][0] == "foo.rs"
source = result[0][1];
version_str = "Code generated with SymPy %s" % sympy.__version__
version_line = version_str.center(76).rstrip()
expected = (
"/*\n"
" *%(version_line)s\n"
" *\n"
" * See http://www.sympy.org/ for more information.\n"
" *\n"
" * This file is part of 'project'\n"
" */\n"
"fn foo(x: f64, y: f64) -> (f64, f64) {\n"
" let out1 = 2*x;\n"
" let out2 = 3*y;\n"
" (out1, out2)\n"
"}\n"
"fn bar(y: f64) -> (f64, f64) {\n"
" let out1 = y.powi(2);\n"
" let out2 = 4*y;\n"
" (out1, out2)\n"
"}\n"
) % {'version_line': version_line}
assert source == expected
def test_filename_match_prefix():
name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
result, = codegen(name_expr, "Rust", prefix="baz", header=False,
empty=False)
assert result[0] == "baz.rs"
def test_InOutArgument():
expr = Equality(x, x**2)
name_expr = ("mysqr", expr)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn mysqr(x: f64) -> f64 {\n"
" let x = x.powi(2);\n"
" x\n"
"}\n"
)
assert source == expected
def test_InOutArgument_order():
# can specify the order as (x, y)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Rust", header=False,
empty=False, argument_sequence=(x,y))
source = result[1]
expected = (
"fn test(x: f64, y: f64) -> f64 {\n"
" let x = x.powi(2) + y;\n"
" x\n"
"}\n"
)
assert source == expected
# make sure it gives (x, y) not (y, x)
expr = Equality(x, x**2 + y)
name_expr = ("test", expr)
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64, y: f64) -> f64 {\n"
" let x = x.powi(2) + y;\n"
" x\n"
"}\n"
)
assert source == expected
def test_not_supported():
f = Function('f')
name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
result, = codegen(name_expr, "Rust", header=False, empty=False)
source = result[1]
expected = (
"fn test(x: f64) -> (f64, f64) {\n"
" // unsupported: Derivative(f(x), x)\n"
" // unsupported: zoo\n"
" let out1 = Derivative(f(x), x);\n"
" let out2 = zoo;\n"
" (out1, out2)\n"
"}\n"
)
assert source == expected
def test_global_vars_rust():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Rust", header=False, empty=False,
global_vars=(y,))
source = result[0][1]
expected = (
"fn f(x: f64) -> f64 {\n"
" let out1 = x*y;\n"
" out1\n"
"}\n"
)
assert source == expected
result = codegen(('f', x*y+z), "Rust", header=False, empty=False,
argument_sequence=(x, y), global_vars=(z, t))
source = result[0][1]
expected = (
"fn f(x: f64, y: f64) -> f64 {\n"
" let out1 = x*y + z;\n"
" out1\n"
"}\n"
)
assert source == expected

View File

@ -0,0 +1,129 @@
from functools import wraps
from sympy.utilities.decorator import threaded, xthreaded, memoize_property, deprecated
from sympy.testing.pytest import warns_deprecated_sympy
from sympy.core.basic import Basic
from sympy.core.relational import Eq
from sympy.matrices.dense import Matrix
from sympy.abc import x, y
def test_threaded():
@threaded
def function(expr, *args):
return 2*expr + sum(args)
assert function(Matrix([[x, y], [1, x]]), 1, 2) == \
Matrix([[2*x + 3, 2*y + 3], [5, 2*x + 3]])
assert function(Eq(x, y), 1, 2) == Eq(2*x + 3, 2*y + 3)
assert function([x, y], 1, 2) == [2*x + 3, 2*y + 3]
assert function((x, y), 1, 2) == (2*x + 3, 2*y + 3)
assert function({x, y}, 1, 2) == {2*x + 3, 2*y + 3}
@threaded
def function(expr, n):
return expr**n
assert function(x + y, 2) == x**2 + y**2
assert function(x, 2) == x**2
def test_xthreaded():
@xthreaded
def function(expr, n):
return expr**n
assert function(x + y, 2) == (x + y)**2
def test_wraps():
def my_func(x):
"""My function. """
my_func.is_my_func = True
new_my_func = threaded(my_func)
new_my_func = wraps(my_func)(new_my_func)
assert new_my_func.__name__ == 'my_func'
assert new_my_func.__doc__ == 'My function. '
assert hasattr(new_my_func, 'is_my_func')
assert new_my_func.is_my_func is True
def test_memoize_property():
class TestMemoize(Basic):
@memoize_property
def prop(self):
return Basic()
member = TestMemoize()
obj1 = member.prop
obj2 = member.prop
assert obj1 is obj2
def test_deprecated():
@deprecated('deprecated_function is deprecated',
deprecated_since_version='1.10',
# This is the target at the top of the file, which will never
# go away.
active_deprecations_target='active-deprecations')
def deprecated_function(x):
return x
with warns_deprecated_sympy():
assert deprecated_function(1) == 1
@deprecated('deprecated_class is deprecated',
deprecated_since_version='1.10',
active_deprecations_target='active-deprecations')
class deprecated_class:
pass
with warns_deprecated_sympy():
assert isinstance(deprecated_class(), deprecated_class)
# Ensure the class decorator works even when the class never returns
# itself
@deprecated('deprecated_class_new is deprecated',
deprecated_since_version='1.10',
active_deprecations_target='active-deprecations')
class deprecated_class_new:
def __new__(cls, arg):
return arg
with warns_deprecated_sympy():
assert deprecated_class_new(1) == 1
@deprecated('deprecated_class_init is deprecated',
deprecated_since_version='1.10',
active_deprecations_target='active-deprecations')
class deprecated_class_init:
def __init__(self, arg):
self.arg = 1
with warns_deprecated_sympy():
assert deprecated_class_init(1).arg == 1
@deprecated('deprecated_class_new_init is deprecated',
deprecated_since_version='1.10',
active_deprecations_target='active-deprecations')
class deprecated_class_new_init:
def __new__(cls, arg):
if arg == 0:
return arg
return object.__new__(cls)
def __init__(self, arg):
self.arg = 1
with warns_deprecated_sympy():
assert deprecated_class_new_init(0) == 0
with warns_deprecated_sympy():
assert deprecated_class_new_init(1).arg == 1

View File

@ -0,0 +1,13 @@
from sympy.testing.pytest import warns_deprecated_sympy
# See https://github.com/sympy/sympy/pull/18095
def test_deprecated_utilities():
with warns_deprecated_sympy():
import sympy.utilities.pytest # noqa:F401
with warns_deprecated_sympy():
import sympy.utilities.runtests # noqa:F401
with warns_deprecated_sympy():
import sympy.utilities.randtest # noqa:F401
with warns_deprecated_sympy():
import sympy.utilities.tmpfiles # noqa:F401

View File

@ -0,0 +1,178 @@
from itertools import zip_longest
from sympy.utilities.enumerative import (
list_visitor,
MultisetPartitionTraverser,
multiset_partitions_taocp
)
from sympy.utilities.iterables import _set_partitions
# first some functions only useful as test scaffolding - these provide
# straightforward, but slow reference implementations against which to
# compare the real versions, and also a comparison to verify that
# different versions are giving identical results.
def part_range_filter(partition_iterator, lb, ub):
"""
Filters (on the number of parts) a multiset partition enumeration
Arguments
=========
lb, and ub are a range (in the Python slice sense) on the lpart
variable returned from a multiset partition enumeration. Recall
that lpart is 0-based (it points to the topmost part on the part
stack), so if you want to return parts of sizes 2,3,4,5 you would
use lb=1 and ub=5.
"""
for state in partition_iterator:
f, lpart, pstack = state
if lpart >= lb and lpart < ub:
yield state
def multiset_partitions_baseline(multiplicities, components):
"""Enumerates partitions of a multiset
Parameters
==========
multiplicities
list of integer multiplicities of the components of the multiset.
components
the components (elements) themselves
Returns
=======
Set of partitions. Each partition is tuple of parts, and each
part is a tuple of components (with repeats to indicate
multiplicity)
Notes
=====
Multiset partitions can be created as equivalence classes of set
partitions, and this function does just that. This approach is
slow and memory intensive compared to the more advanced algorithms
available, but the code is simple and easy to understand. Hence
this routine is strictly for testing -- to provide a
straightforward baseline against which to regress the production
versions. (This code is a simplified version of an earlier
production implementation.)
"""
canon = [] # list of components with repeats
for ct, elem in zip(multiplicities, components):
canon.extend([elem]*ct)
# accumulate the multiset partitions in a set to eliminate dups
cache = set()
n = len(canon)
for nc, q in _set_partitions(n):
rv = [[] for i in range(nc)]
for i in range(n):
rv[q[i]].append(canon[i])
canonical = tuple(
sorted([tuple(p) for p in rv]))
cache.add(canonical)
return cache
def compare_multiset_w_baseline(multiplicities):
"""
Enumerates the partitions of multiset with AOCP algorithm and
baseline implementation, and compare the results.
"""
letters = "abcdefghijklmnopqrstuvwxyz"
bl_partitions = multiset_partitions_baseline(multiplicities, letters)
# The partitions returned by the different algorithms may have
# their parts in different orders. Also, they generate partitions
# in different orders. Hence the sorting, and set comparison.
aocp_partitions = set()
for state in multiset_partitions_taocp(multiplicities):
p1 = tuple(sorted(
[tuple(p) for p in list_visitor(state, letters)]))
aocp_partitions.add(p1)
assert bl_partitions == aocp_partitions
def compare_multiset_states(s1, s2):
"""compare for equality two instances of multiset partition states
This is useful for comparing different versions of the algorithm
to verify correctness."""
# Comparison is physical, the only use of semantics is to ignore
# trash off the top of the stack.
f1, lpart1, pstack1 = s1
f2, lpart2, pstack2 = s2
if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]):
if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]:
return True
return False
def test_multiset_partitions_taocp():
"""Compares the output of multiset_partitions_taocp with a baseline
(set partition based) implementation."""
# Test cases should not be too large, since the baseline
# implementation is fairly slow.
multiplicities = [2,2]
compare_multiset_w_baseline(multiplicities)
multiplicities = [4,3,1]
compare_multiset_w_baseline(multiplicities)
def test_multiset_partitions_versions():
"""Compares Knuth-based versions of multiset_partitions"""
multiplicities = [5,2,2,1]
m = MultisetPartitionTraverser()
for s1, s2 in zip_longest(m.enum_all(multiplicities),
multiset_partitions_taocp(multiplicities)):
assert compare_multiset_states(s1, s2)
def subrange_exercise(mult, lb, ub):
"""Compare filter-based and more optimized subrange implementations
Helper for tests, called with both small and larger multisets.
"""
m = MultisetPartitionTraverser()
assert m.count_partitions(mult) == \
m.count_partitions_slow(mult)
# Note - multiple traversals from the same
# MultisetPartitionTraverser object cannot execute at the same
# time, hence make several instances here.
ma = MultisetPartitionTraverser()
mc = MultisetPartitionTraverser()
md = MultisetPartitionTraverser()
# Several paths to compute just the size two partitions
a_it = ma.enum_range(mult, lb, ub)
b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub)
c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult))
d_it = part_range_filter(md.enum_large(mult, lb), 0, ub)
for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it):
assert compare_multiset_states(sa, sb)
assert compare_multiset_states(sa, sc)
assert compare_multiset_states(sa, sd)
def test_subrange():
# Quick, but doesn't hit some of the corner cases
mult = [4,4,2,1] # mississippi
lb = 1
ub = 2
subrange_exercise(mult, lb, ub)
def test_subrange_large():
# takes a second or so, depending on cpu, Python version, etc.
mult = [6,3,2,1]
lb = 4
ub = 7
subrange_exercise(mult, lb, ub)

View File

@ -0,0 +1,12 @@
from sympy.testing.pytest import raises
from sympy.utilities.exceptions import sympy_deprecation_warning
# Only test exceptions here because the other cases are tested in the
# warns_deprecated_sympy tests
def test_sympy_deprecation_warning():
raises(TypeError, lambda: sympy_deprecation_warning('test',
deprecated_since_version=1.10,
active_deprecations_target='active-deprecations'))
raises(ValueError, lambda: sympy_deprecation_warning('test',
deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)='))

View File

@ -0,0 +1,945 @@
from textwrap import dedent
from itertools import islice, product
from sympy.core.basic import Basic
from sympy.core.numbers import Integer
from sympy.core.sorting import ordered
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.combinatorial.factorials import factorial
from sympy.matrices.dense import Matrix
from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation
from sympy.utilities.iterables import (
_partition, _set_partitions, binary_partitions, bracelets, capture,
cartes, common_prefix, common_suffix, connected_components, dict_merge,
filter_symbols, flatten, generate_bell, generate_derangements,
generate_involutions, generate_oriented_forest, group, has_dups, ibin,
iproduct, kbins, minlex, multiset, multiset_combinations,
multiset_partitions, multiset_permutations, necklaces, numbered_symbols,
partitions, permutations, postfixes,
prefixes, reshape, rotate_left, rotate_right, runs, sift,
strongly_connected_components, subsets, take, topological_sort, unflatten,
uniq, variations, ordered_partitions, rotations, is_palindromic, iterable,
NotIterable, multiset_derangements, signed_permutations,
sequence_partitions, sequence_partitions_empty)
from sympy.utilities.enumerative import (
factoring_visitor, multiset_partitions_taocp )
from sympy.core.singleton import S
from sympy.testing.pytest import raises, warns_deprecated_sympy
w, x, y, z = symbols('w,x,y,z')
def test_deprecated_iterables():
from sympy.utilities.iterables import default_sort_key, ordered
with warns_deprecated_sympy():
assert list(ordered([y, x])) == [x, y]
with warns_deprecated_sympy():
assert sorted([y, x], key=default_sort_key) == [x, y]
def test_is_palindromic():
assert is_palindromic('')
assert is_palindromic('x')
assert is_palindromic('xx')
assert is_palindromic('xyx')
assert not is_palindromic('xy')
assert not is_palindromic('xyzx')
assert is_palindromic('xxyzzyx', 1)
assert not is_palindromic('xxyzzyx', 2)
assert is_palindromic('xxyzzyx', 2, -1)
assert is_palindromic('xxyzzyx', 2, 6)
assert is_palindromic('xxyzyx', 1)
assert not is_palindromic('xxyzyx', 2)
assert is_palindromic('xxyzyx', 2, 2 + 3)
def test_flatten():
assert flatten((1, (1,))) == [1, 1]
assert flatten((x, (x,))) == [x, x]
ls = [[(-2, -1), (1, 2)], [(0, 0)]]
assert flatten(ls, levels=0) == ls
assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)]
assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0]
assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0]
raises(ValueError, lambda: flatten(ls, levels=-1))
class MyOp(Basic):
pass
assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z]
assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z]
assert flatten({1, 11, 2}) == list({1, 11, 2})
def test_iproduct():
assert list(iproduct()) == [()]
assert list(iproduct([])) == []
assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)]
assert sorted(iproduct([1, 2], [3, 4, 5])) == [
(1,3),(1,4),(1,5),(2,3),(2,4),(2,5)]
assert sorted(iproduct([0,1],[0,1],[0,1])) == [
(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)]
assert iterable(iproduct(S.Integers)) is True
assert iterable(iproduct(S.Integers, S.Integers)) is True
assert (3,) in iproduct(S.Integers)
assert (4, 5) in iproduct(S.Integers, S.Integers)
assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers)
triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000))
for n1, n2, n3 in triples:
assert isinstance(n1, Integer)
assert isinstance(n2, Integer)
assert isinstance(n3, Integer)
for t in set(product(*([range(-2, 3)]*3))):
assert t in iproduct(S.Integers, S.Integers, S.Integers)
def test_group():
assert group([]) == []
assert group([], multiple=False) == []
assert group([1]) == [[1]]
assert group([1], multiple=False) == [(1, 1)]
assert group([1, 1]) == [[1, 1]]
assert group([1, 1], multiple=False) == [(1, 2)]
assert group([1, 1, 1]) == [[1, 1, 1]]
assert group([1, 1, 1], multiple=False) == [(1, 3)]
assert group([1, 2, 1]) == [[1], [2], [1]]
assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)]
assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]]
assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2),
(2, 3), (1, 1), (3, 2)]
def test_subsets():
# combinations
assert list(subsets([1, 2, 3], 0)) == [()]
assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)]
assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)]
assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)]
l = list(range(4))
assert list(subsets(l, 0, repetition=True)) == [()]
assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
(0, 3), (1, 1), (1, 2),
(1, 3), (2, 2), (2, 3),
(3, 3)]
assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1),
(0, 0, 2), (0, 0, 3),
(0, 1, 1), (0, 1, 2),
(0, 1, 3), (0, 2, 2),
(0, 2, 3), (0, 3, 3),
(1, 1, 1), (1, 1, 2),
(1, 1, 3), (1, 2, 2),
(1, 2, 3), (1, 3, 3),
(2, 2, 2), (2, 2, 3),
(2, 3, 3), (3, 3, 3)]
assert len(list(subsets(l, 4, repetition=True))) == 35
assert list(subsets(l[:2], 3, repetition=False)) == []
assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(1, 1, 1)]
assert list(subsets([1, 2], repetition=True)) == \
[(), (1,), (2,), (1, 1), (1, 2), (2, 2)]
assert list(subsets([1, 2], repetition=False)) == \
[(), (1,), (2,), (1, 2)]
assert list(subsets([1, 2, 3], 2)) == \
[(1, 2), (1, 3), (2, 3)]
assert list(subsets([1, 2, 3], 2, repetition=True)) == \
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
def test_variations():
# permutations
l = list(range(4))
assert list(variations(l, 0, repetition=False)) == [()]
assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)]
assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]
assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)]
assert list(variations(l, 0, repetition=True)) == [()]
assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
(0, 3), (1, 0), (1, 1),
(1, 2), (1, 3), (2, 0),
(2, 1), (2, 2), (2, 3),
(3, 0), (3, 1), (3, 2),
(3, 3)]
assert len(list(variations(l, 3, repetition=True))) == 64
assert len(list(variations(l, 4, repetition=True))) == 256
assert list(variations(l[:2], 3, repetition=False)) == []
assert list(variations(l[:2], 3, repetition=True)) == [
(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)
]
def test_cartes():
assert list(cartes([1, 2], [3, 4, 5])) == \
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
assert list(cartes()) == [()]
assert list(cartes('a')) == [('a',)]
assert list(cartes('a', repeat=2)) == [('a', 'a')]
assert list(cartes(list(range(2)))) == [(0,), (1,)]
def test_filter_symbols():
s = numbered_symbols()
filtered = filter_symbols(s, symbols("x0 x2 x3"))
assert take(filtered, 3) == list(symbols("x1 x4 x5"))
def test_numbered_symbols():
s = numbered_symbols(cls=Dummy)
assert isinstance(next(s), Dummy)
assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \
symbols('C2')
def test_sift():
assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]}
assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]}
assert sift([S.One], lambda _: _.has(x)) == {False: [1]}
assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == (
[1, 3], [0, 2])
assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == (
[1], [0, 2, 3])
raises(ValueError, lambda:
sift([0, 1, 2, 3], lambda x: x % 3, binary=True))
def test_take():
X = numbered_symbols()
assert take(X, 5) == list(symbols('x0:5'))
assert take(X, 5) == list(symbols('x5:10'))
assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_dict_merge():
assert dict_merge({}, {1: x, y: z}) == {1: x, y: z}
assert dict_merge({1: x, y: z}, {}) == {1: x, y: z}
assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z}
def test_prefixes():
assert list(prefixes([])) == []
assert list(prefixes([1])) == [[1]]
assert list(prefixes([1, 2])) == [[1], [1, 2]]
assert list(prefixes([1, 2, 3, 4, 5])) == \
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
def test_postfixes():
assert list(postfixes([])) == []
assert list(postfixes([1])) == [[1]]
assert list(postfixes([1, 2])) == [[2], [1, 2]]
assert list(postfixes([1, 2, 3, 4, 5])) == \
[[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]]
def test_topological_sort():
V = [2, 3, 5, 7, 8, 9, 10, 11]
E = [(7, 11), (7, 8), (5, 11),
(3, 8), (3, 10), (11, 2),
(11, 9), (11, 10), (8, 9)]
assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10]
assert topological_sort((V, E), key=lambda v: -v) == \
[7, 5, 11, 3, 10, 8, 9, 2]
raises(ValueError, lambda: topological_sort((V, E + [(10, 7)])))
def test_strongly_connected_components():
assert strongly_connected_components(([], [])) == []
assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]]
V = [1, 2, 3]
E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)]
assert strongly_connected_components((V, E)) == [[1, 2, 3]]
V = [1, 2, 3, 4]
E = [(1, 2), (2, 3), (3, 2), (3, 4)]
assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]]
V = [1, 2, 3, 4]
E = [(1, 2), (2, 1), (3, 4), (4, 3)]
assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]]
def test_connected_components():
assert connected_components(([], [])) == []
assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]]
V = [1, 2, 3]
E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)]
assert connected_components((V, E)) == [[1, 2, 3]]
V = [1, 2, 3, 4]
E = [(1, 2), (2, 3), (3, 2), (3, 4)]
assert connected_components((V, E)) == [[1, 2, 3, 4]]
V = [1, 2, 3, 4]
E = [(1, 2), (3, 4)]
assert connected_components((V, E)) == [[1, 2], [3, 4]]
def test_rotate():
A = [0, 1, 2, 3, 4]
assert rotate_left(A, 2) == [2, 3, 4, 0, 1]
assert rotate_right(A, 1) == [4, 0, 1, 2, 3]
A = []
B = rotate_right(A, 1)
assert B == []
B.append(1)
assert A == []
B = rotate_left(A, 1)
assert B == []
B.append(1)
assert A == []
def test_multiset_partitions():
A = [0, 1, 2, 3, 4]
assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]]
assert len(list(multiset_partitions(A, 4))) == 10
assert len(list(multiset_partitions(A, 3))) == 25
assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [
[[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]],
[[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]]
assert list(multiset_partitions([1, 1, 2, 2], 2)) == [
[[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]],
[[1, 2], [1, 2]]]
assert list(multiset_partitions([1, 2, 3, 4], 2)) == [
[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
[[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
[[1], [2, 3, 4]]]
assert list(multiset_partitions([1, 2, 2], 2)) == [
[[1, 2], [2]], [[1], [2, 2]]]
assert list(multiset_partitions(3)) == [
[[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]],
[[0], [1], [2]]]
assert list(multiset_partitions(3, 2)) == [
[[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]]
assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]]
assert list(multiset_partitions([1] * 3)) == [
[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
a = [3, 2, 1]
assert list(multiset_partitions(a)) == \
list(multiset_partitions(sorted(a)))
assert list(multiset_partitions(a, 5)) == []
assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]]
assert list(multiset_partitions(a + [4], 5)) == []
assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]]
assert list(multiset_partitions(2, 5)) == []
assert list(multiset_partitions(2, 1)) == [[[0, 1]]]
assert list(multiset_partitions('a')) == [[['a']]]
assert list(multiset_partitions('a', 2)) == []
assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]]
assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]]
assert list(multiset_partitions('aaa', 1)) == [['aaa']]
assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]]
ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'),
('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'),
('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'),
('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'),
('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'),
('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'),
('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'),
('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'),
('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'),
('m', 'py', 's', 'y'), ('m', 'p', 'syy'),
('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'),
('m', 'p', 's', 'y', 'y')]
assert [tuple("".join(part) for part in p)
for p in multiset_partitions('sympy')] == ans
factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3],
[6, 2, 2], [2, 2, 2, 3]]
assert [factoring_visitor(p, [2,3]) for
p in multiset_partitions_taocp([3, 1])] == factorings
def test_multiset_combinations():
ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips',
'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss']
assert [''.join(i) for i in
list(multiset_combinations('mississippi', 3))] == ans
M = multiset('mississippi')
assert [''.join(i) for i in
list(multiset_combinations(M, 3))] == ans
assert [''.join(i) for i in multiset_combinations(M, 30)] == []
assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]]
assert len(list(multiset_combinations('a', 3))) == 0
assert len(list(multiset_combinations('a', 0))) == 1
assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']]
raises(ValueError, lambda: list(multiset_combinations({0: 3, 1: -1}, 2)))
def test_multiset_permutations():
ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab',
'byba', 'yabb', 'ybab', 'ybba']
assert [''.join(i) for i in multiset_permutations('baby')] == ans
assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans
assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]]
assert list(multiset_permutations([0, 2, 1], 2)) == [
[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
assert len(list(multiset_permutations('a', 0))) == 1
assert len(list(multiset_permutations('a', 3))) == 0
for nul in ([], {}, ''):
assert list(multiset_permutations(nul)) == [[]]
assert list(multiset_permutations(nul, 0)) == [[]]
# impossible requests give no result
assert list(multiset_permutations(nul, 1)) == []
assert list(multiset_permutations(nul, -1)) == []
def test():
for i in range(1, 7):
print(i)
for p in multiset_permutations([0, 0, 1, 0, 1], i):
print(p)
assert capture(lambda: test()) == dedent('''\
1
[0]
[1]
2
[0, 0]
[0, 1]
[1, 0]
[1, 1]
3
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
4
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 1, 0, 0]
5
[0, 0, 0, 1, 1]
[0, 0, 1, 0, 1]
[0, 0, 1, 1, 0]
[0, 1, 0, 0, 1]
[0, 1, 0, 1, 0]
[0, 1, 1, 0, 0]
[1, 0, 0, 0, 1]
[1, 0, 0, 1, 0]
[1, 0, 1, 0, 0]
[1, 1, 0, 0, 0]
6\n''')
raises(ValueError, lambda: list(multiset_permutations({0: 3, 1: -1})))
def test_partitions():
ans = [[{}], [(0, {})]]
for i in range(2):
assert list(partitions(0, size=i)) == ans[i]
assert list(partitions(1, 0, size=i)) == ans[i]
assert list(partitions(6, 2, 2, size=i)) == ans[i]
assert list(partitions(6, 2, None, size=i)) != ans[i]
assert list(partitions(6, None, 2, size=i)) != ans[i]
assert list(partitions(6, 2, 0, size=i)) == ans[i]
assert list(partitions(6, k=2)) == [
{2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]
assert list(partitions(6, k=3)) == [
{3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2},
{1: 4, 2: 1}, {1: 6}]
assert list(partitions(8, k=4, m=3)) == [
{4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [
i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i)
and sum(i.values()) <=3]
assert list(partitions(S(3), m=2)) == [
{3: 1}, {1: 1, 2: 1}]
assert list(partitions(4, k=3)) == [
{1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [
i for i in partitions(4) if all(k <= 3 for k in i)]
# Consistency check on output of _partitions and RGS_unrank.
# This provides a sanity test on both routines. Also verifies that
# the total number of partitions is the same in each case.
# (from pkrathmann2)
for n in range(2, 6):
i = 0
for m, q in _set_partitions(n):
assert q == RGS_unrank(i, n)
i += 1
assert i == RGS_enum(n)
def test_binary_partitions():
assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1],
[4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1],
[4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2],
[2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1],
[2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
assert len([j[:] for j in binary_partitions(16)]) == 36
def test_bell_perm():
assert [len(set(generate_bell(i))) for i in range(1, 7)] == [
factorial(i) for i in range(1, 7)]
assert list(generate_bell(3)) == [
(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)]
# generate_bell and trotterjohnson are advertised to return the same
# permutations; this is not technically necessary so this test could
# be removed
for n in range(1, 5):
p = Permutation(range(n))
b = generate_bell(n)
for bi in b:
assert bi == tuple(p.array_form)
p = p.next_trotterjohnson()
raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms?
def test_involutions():
lengths = [1, 2, 4, 10, 26, 76]
for n, N in enumerate(lengths):
i = list(generate_involutions(n + 1))
assert len(i) == N
assert len({Permutation(j)**2 for j in i}) == 1
def test_derangements():
assert len(list(generate_derangements(list(range(6))))) == 265
assert ''.join(''.join(i) for i in generate_derangements('abcde')) == (
'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd'
'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab'
'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb'
'edbacedbca')
assert list(generate_derangements([0, 1, 2, 3])) == [
[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1],
[2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]]
assert list(generate_derangements([0, 1, 2, 2])) == [
[2, 2, 0, 1], [2, 2, 1, 0]]
assert list(generate_derangements('ba')) == [list('ab')]
# multiset_derangements
D = multiset_derangements
assert list(D('abb')) == []
assert [''.join(i) for i in D('ab')] == ['ba']
assert [''.join(i) for i in D('abc')] == ['bca', 'cab']
assert [''.join(i) for i in D('aabb')] == ['bbaa']
assert [''.join(i) for i in D('aabbcccc')] == [
'ccccaabb', 'ccccabab', 'ccccabba', 'ccccbaab', 'ccccbaba',
'ccccbbaa']
assert [''.join(i) for i in D('aabbccc')] == [
'cccabba', 'cccabab', 'cccaabb', 'ccacbba', 'ccacbab',
'ccacabb', 'cbccbaa', 'cbccaba', 'cbccaab', 'bcccbaa',
'bcccaba', 'bcccaab']
assert [''.join(i) for i in D('books')] == ['kbsoo', 'ksboo',
'sbkoo', 'skboo', 'oksbo', 'oskbo', 'okbso', 'obkso', 'oskob',
'oksob', 'osbok', 'obsok']
assert list(generate_derangements([[3], [2], [2], [1]])) == [
[[2], [1], [3], [2]], [[2], [3], [1], [2]]]
def test_necklaces():
def count(n, k, f):
return len(list(necklaces(n, k, f)))
m = []
for i in range(1, 8):
m.append((
i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1)))
assert Matrix(m) == Matrix([
[1, 2, 2, 3],
[2, 3, 3, 6],
[3, 4, 4, 10],
[4, 6, 6, 21],
[5, 8, 8, 39],
[6, 14, 13, 92],
[7, 20, 18, 198]])
def test_bracelets():
bc = list(bracelets(2, 4))
assert Matrix(bc) == Matrix([
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 1],
[1, 2],
[1, 3],
[2, 2],
[2, 3],
[3, 3]
])
bc = list(bracelets(4, 2))
assert Matrix(bc) == Matrix([
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1]
])
def test_generate_oriented_forest():
assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4],
[0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0],
[0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2],
[0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0],
[0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0],
[0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
assert len(list(generate_oriented_forest(10))) == 1842
def test_unflatten():
r = list(range(10))
assert unflatten(r) == list(zip(r[::2], r[1::2]))
assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])]
raises(ValueError, lambda: unflatten(list(range(10)), 3))
raises(ValueError, lambda: unflatten(list(range(10)), -2))
def test_common_prefix_suffix():
assert common_prefix([], [1]) == []
assert common_prefix(list(range(3))) == [0, 1, 2]
assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2]
assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2]
assert common_prefix([1, 2, 3], [1, 3, 5]) == [1]
assert common_suffix([], [1]) == []
assert common_suffix(list(range(3))) == [0, 1, 2]
assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2]
assert common_suffix(list(range(3)), list(range(4))) == []
assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3]
assert common_suffix([1, 2, 3], [9, 7, 3]) == [3]
def test_minlex():
assert minlex([1, 2, 0]) == (0, 1, 2)
assert minlex((1, 2, 0)) == (0, 1, 2)
assert minlex((1, 0, 2)) == (0, 2, 1)
assert minlex((1, 0, 2), directed=False) == (0, 1, 2)
assert minlex('aba') == 'aab'
assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa')
def test_ordered():
assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]]
assert list(ordered((x, y), hash, default=False)) == \
list(ordered((y, x), hash, default=False))
assert list(ordered((x, y))) == [x, y]
seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]],
(lambda x: len(x), lambda x: sum(x))]
assert list(ordered(seq, keys, default=False, warn=False)) == \
[[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
raises(ValueError, lambda:
list(ordered(seq, keys, default=False, warn=True)))
def test_runs():
assert runs([]) == []
assert runs([1]) == [[1]]
assert runs([1, 1]) == [[1], [1]]
assert runs([1, 1, 2]) == [[1], [1, 2]]
assert runs([1, 2, 1]) == [[1, 2], [1]]
assert runs([2, 1, 1]) == [[2], [1], [1]]
from operator import lt
assert runs([2, 1, 1], lt) == [[2, 1], [1]]
def test_reshape():
seq = list(range(1, 9))
assert reshape(seq, [4]) == \
[[1, 2, 3, 4], [5, 6, 7, 8]]
assert reshape(seq, (4,)) == \
[(1, 2, 3, 4), (5, 6, 7, 8)]
assert reshape(seq, (2, 2)) == \
[(1, 2, 3, 4), (5, 6, 7, 8)]
assert reshape(seq, (2, [2])) == \
[(1, 2, [3, 4]), (5, 6, [7, 8])]
assert reshape(seq, ((2,), [2])) == \
[((1, 2), [3, 4]), ((5, 6), [7, 8])]
assert reshape(seq, (1, [2], 1)) == \
[(1, [2, 3], 4), (5, [6, 7], 8)]
assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
assert reshape(tuple(seq), ([1], 1, (2,))) == \
(([1], 2, (3, 4)), ([5], 6, (7, 8)))
assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \
[[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]
raises(ValueError, lambda: reshape([0, 1], [-1]))
raises(ValueError, lambda: reshape([0, 1], [3]))
def test_uniq():
assert list(uniq(p for p in partitions(4))) == \
[{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}]
assert list(uniq(x % 2 for x in range(5))) == [0, 1]
assert list(uniq('a')) == ['a']
assert list(uniq('ababc')) == list('abc')
assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]]
assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \
[([1], 2, 2), (2, [1], 2), (2, 2, [1])]
assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \
[2, 3, 4, [2], [1], [3]]
f = [1]
raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)])
f = [[1]]
raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)])
def test_kbins():
assert len(list(kbins('1123', 2, ordered=1))) == 24
assert len(list(kbins('1123', 2, ordered=11))) == 36
assert len(list(kbins('1123', 2, ordered=10))) == 10
assert len(list(kbins('1123', 2, ordered=0))) == 5
assert len(list(kbins('1123', 2, ordered=None))) == 3
def test1():
for orderedval in [None, 0, 1, 10, 11]:
print('ordered =', orderedval)
for p in kbins([0, 0, 1], 2, ordered=orderedval):
print(' ', p)
assert capture(lambda : test1()) == dedent('''\
ordered = None
[[0], [0, 1]]
[[0, 0], [1]]
ordered = 0
[[0, 0], [1]]
[[0, 1], [0]]
ordered = 1
[[0], [0, 1]]
[[0], [1, 0]]
[[1], [0, 0]]
ordered = 10
[[0, 0], [1]]
[[1], [0, 0]]
[[0, 1], [0]]
[[0], [0, 1]]
ordered = 11
[[0], [0, 1]]
[[0, 0], [1]]
[[0], [1, 0]]
[[0, 1], [0]]
[[1], [0, 0]]
[[1, 0], [0]]\n''')
def test2():
for orderedval in [None, 0, 1, 10, 11]:
print('ordered =', orderedval)
for p in kbins(list(range(3)), 2, ordered=orderedval):
print(' ', p)
assert capture(lambda : test2()) == dedent('''\
ordered = None
[[0], [1, 2]]
[[0, 1], [2]]
ordered = 0
[[0, 1], [2]]
[[0, 2], [1]]
[[0], [1, 2]]
ordered = 1
[[0], [1, 2]]
[[0], [2, 1]]
[[1], [0, 2]]
[[1], [2, 0]]
[[2], [0, 1]]
[[2], [1, 0]]
ordered = 10
[[0, 1], [2]]
[[2], [0, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[0], [1, 2]]
[[1, 2], [0]]
ordered = 11
[[0], [1, 2]]
[[0, 1], [2]]
[[0], [2, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[1, 0], [2]]
[[1], [2, 0]]
[[1, 2], [0]]
[[2], [0, 1]]
[[2, 0], [1]]
[[2], [1, 0]]
[[2, 1], [0]]\n''')
def test_has_dups():
assert has_dups(set()) is False
assert has_dups(list(range(3))) is False
assert has_dups([1, 2, 1]) is True
assert has_dups([[1], [1]]) is True
assert has_dups([[1], [2]]) is False
def test__partition():
assert _partition('abcde', [1, 0, 1, 2, 0]) == [
['b', 'e'], ['a', 'c'], ['d']]
assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [
['b', 'e'], ['a', 'c'], ['d']]
output = (3, [1, 0, 1, 2, 0])
assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']]
def test_ordered_partitions():
from sympy.functions.combinatorial.numbers import nT
f = ordered_partitions
assert list(f(0, 1)) == [[]]
assert list(f(1, 0)) == [[]]
for i in range(1, 7):
for j in [None] + list(range(1, i)):
assert (
sum(1 for p in f(i, j, 1)) ==
sum(1 for p in f(i, j, 0)) ==
nT(i, j))
def test_rotations():
assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']]
assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]]
assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]]
def test_ibin():
assert ibin(3) == [1, 1]
assert ibin(3, 3) == [0, 1, 1]
assert ibin(3, str=True) == '11'
assert ibin(3, 3, str=True) == '011'
assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)]
assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11']
raises(ValueError, lambda: ibin(-.5))
raises(ValueError, lambda: ibin(2, 1))
def test_iterable():
assert iterable(0) is False
assert iterable(1) is False
assert iterable(None) is False
class Test1(NotIterable):
pass
assert iterable(Test1()) is False
class Test2(NotIterable):
_iterable = True
assert iterable(Test2()) is True
class Test3:
pass
assert iterable(Test3()) is False
class Test4:
_iterable = True
assert iterable(Test4()) is True
class Test5:
def __iter__(self):
yield 1
assert iterable(Test5()) is True
class Test6(Test5):
_iterable = False
assert iterable(Test6()) is False
def test_sequence_partitions():
assert list(sequence_partitions([1], 1)) == [[[1]]]
assert list(sequence_partitions([1, 2], 1)) == [[[1, 2]]]
assert list(sequence_partitions([1, 2], 2)) == [[[1], [2]]]
assert list(sequence_partitions([1, 2, 3], 1)) == [[[1, 2, 3]]]
assert list(sequence_partitions([1, 2, 3], 2)) == \
[[[1], [2, 3]], [[1, 2], [3]]]
assert list(sequence_partitions([1, 2, 3], 3)) == [[[1], [2], [3]]]
# Exceptional cases
assert list(sequence_partitions([], 0)) == []
assert list(sequence_partitions([], 1)) == []
assert list(sequence_partitions([1, 2], 0)) == []
assert list(sequence_partitions([1, 2], 3)) == []
def test_sequence_partitions_empty():
assert list(sequence_partitions_empty([], 1)) == [[[]]]
assert list(sequence_partitions_empty([], 2)) == [[[], []]]
assert list(sequence_partitions_empty([], 3)) == [[[], [], []]]
assert list(sequence_partitions_empty([1], 1)) == [[[1]]]
assert list(sequence_partitions_empty([1], 2)) == [[[], [1]], [[1], []]]
assert list(sequence_partitions_empty([1], 3)) == \
[[[], [], [1]], [[], [1], []], [[1], [], []]]
assert list(sequence_partitions_empty([1, 2], 1)) == [[[1, 2]]]
assert list(sequence_partitions_empty([1, 2], 2)) == \
[[[], [1, 2]], [[1], [2]], [[1, 2], []]]
assert list(sequence_partitions_empty([1, 2], 3)) == [
[[], [], [1, 2]], [[], [1], [2]], [[], [1, 2], []],
[[1], [], [2]], [[1], [2], []], [[1, 2], [], []]
]
assert list(sequence_partitions_empty([1, 2, 3], 1)) == [[[1, 2, 3]]]
assert list(sequence_partitions_empty([1, 2, 3], 2)) == \
[[[], [1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3], []]]
assert list(sequence_partitions_empty([1, 2, 3], 3)) == [
[[], [], [1, 2, 3]], [[], [1], [2, 3]],
[[], [1, 2], [3]], [[], [1, 2, 3], []],
[[1], [], [2, 3]], [[1], [2], [3]],
[[1], [2, 3], []], [[1, 2], [], [3]],
[[1, 2], [3], []], [[1, 2, 3], [], []]
]
# Exceptional cases
assert list(sequence_partitions([], 0)) == []
assert list(sequence_partitions([1], 0)) == []
assert list(sequence_partitions([1, 2], 0)) == []
def test_signed_permutations():
ans = [(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1),
(1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1),
(1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0)]
assert list(signed_permutations((0, 1, 1))) == ans
assert list(signed_permutations((1, 0, 1))) == ans
assert list(signed_permutations((1, 1, 0))) == ans

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,164 @@
import pickle
from sympy.core.relational import (Eq, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.external import import_module
from sympy.testing.pytest import skip
from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar, Replacer
matchpy = import_module("matchpy")
x, y, z = symbols("x y z")
def _get_first_match(expr, pattern):
from matchpy import ManyToOneMatcher, Pattern
matcher = ManyToOneMatcher()
matcher.add(Pattern(pattern))
return next(iter(matcher.match(expr)))
def test_matchpy_connector():
if matchpy is None:
skip("matchpy not installed")
from multiset import Multiset
from matchpy import Pattern, Substitution
w_ = WildDot("w_")
w__ = WildPlus("w__")
w___ = WildStar("w___")
expr = x + y
pattern = x + w_
p, subst = _get_first_match(expr, pattern)
assert p == Pattern(pattern)
assert subst == Substitution({'w_': y})
expr = x + y + z
pattern = x + w__
p, subst = _get_first_match(expr, pattern)
assert p == Pattern(pattern)
assert subst == Substitution({'w__': Multiset([y, z])})
expr = x + y + z
pattern = x + y + z + w___
p, subst = _get_first_match(expr, pattern)
assert p == Pattern(pattern)
assert subst == Substitution({'w___': Multiset()})
def test_matchpy_optional():
if matchpy is None:
skip("matchpy not installed")
from matchpy import Pattern, Substitution
from matchpy import ManyToOneReplacer, ReplacementRule
p = WildDot("p", optional=1)
q = WildDot("q", optional=0)
pattern = p*x + q
expr1 = 2*x
pa, subst = _get_first_match(expr1, pattern)
assert pa == Pattern(pattern)
assert subst == Substitution({'p': 2, 'q': 0})
expr2 = x + 3
pa, subst = _get_first_match(expr2, pattern)
assert pa == Pattern(pattern)
assert subst == Substitution({'p': 1, 'q': 3})
expr3 = x
pa, subst = _get_first_match(expr3, pattern)
assert pa == Pattern(pattern)
assert subst == Substitution({'p': 1, 'q': 0})
expr4 = x*y + z
pa, subst = _get_first_match(expr4, pattern)
assert pa == Pattern(pattern)
assert subst == Substitution({'p': y, 'q': z})
replacer = ManyToOneReplacer()
replacer.add(ReplacementRule(Pattern(pattern), lambda p, q: sin(p)*cos(q)))
assert replacer.replace(expr1) == sin(2)*cos(0)
assert replacer.replace(expr2) == sin(1)*cos(3)
assert replacer.replace(expr3) == sin(1)*cos(0)
assert replacer.replace(expr4) == sin(y)*cos(z)
def test_replacer():
if matchpy is None:
skip("matchpy not installed")
for info in [True, False]:
for lambdify in [True, False]:
_perform_test_replacer(info, lambdify)
def _perform_test_replacer(info, lambdify):
x1_ = WildDot("x1_")
x2_ = WildDot("x2_")
a_ = WildDot("a_", optional=S.One)
b_ = WildDot("b_", optional=S.One)
c_ = WildDot("c_", optional=S.Zero)
replacer = Replacer(common_constraints=[
matchpy.CustomConstraint(lambda a_: not a_.has(x)),
matchpy.CustomConstraint(lambda b_: not b_.has(x)),
matchpy.CustomConstraint(lambda c_: not c_.has(x)),
], lambdify=lambdify, info=info)
# Rewrite the equation into implicit form, unless it's already solved:
replacer.add(Eq(x1_, x2_), Eq(x1_ - x2_, 0), conditions_nonfalse=[Ne(x2_, 0), Ne(x1_, 0), Ne(x1_, x), Ne(x2_, x)], info=1)
# Simple equation solver for real numbers:
replacer.add(Eq(a_*x + b_, 0), Eq(x, -b_/a_), info=2)
disc = b_**2 - 4*a_*c_
replacer.add(
Eq(a_*x**2 + b_*x + c_, 0),
Eq(x, (-b_ - sqrt(disc))/(2*a_)) | Eq(x, (-b_ + sqrt(disc))/(2*a_)),
conditions_nonfalse=[disc >= 0],
info=3
)
replacer.add(
Eq(a_*x**2 + c_, 0),
Eq(x, sqrt(-c_/a_)) | Eq(x, -sqrt(-c_/a_)),
conditions_nonfalse=[-c_*a_ > 0],
info=4
)
g = lambda expr, infos: (expr, infos) if info else expr
assert replacer.replace(Eq(3*x, y)) == g(Eq(x, y/3), [1, 2])
assert replacer.replace(Eq(x**2 + 1, 0)) == g(Eq(x**2 + 1, 0), [])
assert replacer.replace(Eq(x**2, 4)) == g((Eq(x, 2) | Eq(x, -2)), [1, 4])
assert replacer.replace(Eq(x**2 + 4*y*x + 4*y**2, 0)) == g(Eq(x, -2*y), [3])
def test_matchpy_object_pickle():
if matchpy is None:
return
a1 = WildDot("a")
a2 = pickle.loads(pickle.dumps(a1))
assert a1 == a2
a1 = WildDot("a", S(1))
a2 = pickle.loads(pickle.dumps(a1))
assert a1 == a2
a1 = WildPlus("a", S(1))
a2 = pickle.loads(pickle.dumps(a1))
assert a1 == a2
a1 = WildStar("a", S(1))
a2 = pickle.loads(pickle.dumps(a1))
assert a1 == a2

View File

@ -0,0 +1,33 @@
import os
from textwrap import dedent
from sympy.external import import_module
from sympy.testing.pytest import skip
from sympy.utilities.mathml import apply_xsl
lxml = import_module('lxml')
path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_xxe.py"))
def test_xxe():
assert os.path.isfile(path)
if not lxml:
skip("lxml not installed.")
mml = dedent(
rf"""
<!--?xml version="1.0" ?-->
<!DOCTYPE replace [<!ENTITY ent SYSTEM "file://{path}"> ]>
<userInfo>
<firstName>John</firstName>
<lastName>&ent;</lastName>
</userInfo>
"""
)
xsl = 'mathml/data/simple_mmlctop.xsl'
res = apply_xsl(mml, xsl)
assert res == \
'<?xml version="1.0"?>\n<userInfo>\n<firstName>John</firstName>\n<lastName/>\n</userInfo>\n'

View File

@ -0,0 +1,151 @@
from textwrap import dedent
import sys
from subprocess import Popen, PIPE
import os
from sympy.core.singleton import S
from sympy.testing.pytest import (raises, warns_deprecated_sympy,
skip_under_pyodide)
from sympy.utilities.misc import (translate, replace, ordinal, rawlines,
strlines, as_int, find_executable)
from sympy.external import import_module
pyodide_js = import_module('pyodide_js')
def test_translate():
abc = 'abc'
assert translate(abc, None, 'a') == 'bc'
assert translate(abc, None, '') == 'abc'
assert translate(abc, {'a': 'x'}, 'c') == 'xb'
assert translate(abc, {'a': 'bc'}, 'c') == 'bcb'
assert translate(abc, {'ab': 'x'}, 'c') == 'x'
assert translate(abc, {'ab': ''}, 'c') == ''
assert translate(abc, {'bc': 'x'}, 'c') == 'ab'
assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x'
u = chr(4096)
assert translate(abc, 'a', 'x', u) == 'xbc'
assert (u in translate(abc, 'a', u, u)) is True
def test_replace():
assert replace('abc', ('a', 'b')) == 'bbc'
assert replace('abc', {'a': 'Aa'}) == 'Aabc'
assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC'
def test_ordinal():
assert ordinal(-1) == '-1st'
assert ordinal(0) == '0th'
assert ordinal(1) == '1st'
assert ordinal(2) == '2nd'
assert ordinal(3) == '3rd'
assert all(ordinal(i).endswith('th') for i in range(4, 21))
assert ordinal(100) == '100th'
assert ordinal(101) == '101st'
assert ordinal(102) == '102nd'
assert ordinal(103) == '103rd'
assert ordinal(104) == '104th'
assert ordinal(200) == '200th'
assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203))
def test_rawlines():
assert rawlines('a a\na') == "dedent('''\\\n a a\n a''')"
assert rawlines('a a') == "'a a'"
assert rawlines(strlines('\\le"ft')) == (
'(\n'
" '(\\n'\n"
' \'r\\\'\\\\le"ft\\\'\\n\'\n'
" ')'\n"
')')
def test_strlines():
q = 'this quote (") is in the middle'
# the following assert rhs was prepared with
# print(rawlines(strlines(q, 10)))
assert strlines(q, 10) == dedent('''\
(
'this quo'
'te (") i'
's in the'
' middle'
)''')
assert q == (
'this quo'
'te (") i'
's in the'
' middle'
)
q = "this quote (') is in the middle"
assert strlines(q, 20) == dedent('''\
(
"this quote (') is "
"in the middle"
)''')
assert strlines('\\left') == (
'(\n'
"r'\\left'\n"
')')
assert strlines('\\left', short=True) == r"r'\left'"
assert strlines('\\le"ft') == (
'(\n'
'r\'\\le"ft\'\n'
')')
q = 'this\nother line'
assert strlines(q) == rawlines(q)
def test_translate_args():
try:
translate(None, None, None, 'not_none')
except ValueError:
pass # Exception raised successfully
else:
assert False
assert translate('s', None, None, None) == 's'
try:
translate('s', 'a', 'bc')
except ValueError:
pass # Exception raised successfully
else:
assert False
@skip_under_pyodide("Cannot create subprocess under pyodide.")
def test_debug_output():
env = os.environ.copy()
env['SYMPY_DEBUG'] = 'True'
cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))'
cmdline = [sys.executable, '-c', cmd]
proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
out = out.decode('ascii') # utf-8?
err = err.decode('ascii')
expected = 'substituted: -x*(1 - cos(x)), u: 1/x, u_var: _u'
assert expected in err, err
def test_as_int():
raises(ValueError, lambda : as_int(True))
raises(ValueError, lambda : as_int(1.1))
raises(ValueError, lambda : as_int([]))
raises(ValueError, lambda : as_int(S.NaN))
raises(ValueError, lambda : as_int(S.Infinity))
raises(ValueError, lambda : as_int(S.NegativeInfinity))
raises(ValueError, lambda : as_int(S.ComplexInfinity))
# for the following, limited precision makes int(arg) == arg
# but the int value is not necessarily what a user might have
# expected; Q.prime is more nuanced in its response for
# expressions which might be complex representations of an
# integer. This is not -- by design -- as_ints role.
raises(ValueError, lambda : as_int(1e23))
raises(ValueError, lambda : as_int(S('1.'+'0'*20+'1')))
assert as_int(True, strict=False) == 1
def test_deprecated_find_executable():
with warns_deprecated_sympy():
find_executable('python')

View File

@ -0,0 +1,717 @@
import inspect
import copy
import pickle
from sympy.physics.units import meter
from sympy.testing.pytest import XFAIL, raises, ignore_warnings
from sympy.core.basic import Atom, Basic
from sympy.core.singleton import SingletonRegistry
from sympy.core.symbol import Str, Dummy, Symbol, Wild
from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer,
Rational, Float, AlgebraicNumber)
from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational,
StrictGreaterThan, StrictLessThan, Unequality)
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \
WildFunction
from sympy.sets.sets import Interval
from sympy.core.multidimensional import vectorize
from sympy.external.gmpy import gmpy as _gmpy
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.external import import_module
cloudpickle = import_module('cloudpickle')
not_equal_attrs = {
'_assumptions', # This is a local cache that isn't automatically filled on creation
'_mhash', # Cached after __hash__ is called but set to None after creation
}
deprecated_attrs = {
'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed.
'expr_free_symbols', # Deprecated from SymPy 1.9. This can be removed when exr_free_symbols is removed.
}
def check(a, exclude=[], check_attr=True, deprecated=()):
""" Check that pickling and copying round-trips.
"""
# Pickling with protocols 0 and 1 is disabled for Basic instances:
if isinstance(a, Basic):
for protocol in [0, 1]:
raises(NotImplementedError, lambda: pickle.dumps(a, protocol))
protocols = [2, copy.copy, copy.deepcopy, 3, 4]
if cloudpickle:
protocols.extend([cloudpickle])
for protocol in protocols:
if protocol in exclude:
continue
if callable(protocol):
if isinstance(a, type):
# Classes can't be copied, but that's okay.
continue
b = protocol(a)
elif inspect.ismodule(protocol):
b = protocol.loads(protocol.dumps(a))
else:
b = pickle.loads(pickle.dumps(a, protocol))
d1 = dir(a)
d2 = dir(b)
assert set(d1) == set(d2)
if not check_attr:
continue
def c(a, b, d):
for i in d:
if i in not_equal_attrs:
if hasattr(a, i):
assert hasattr(b, i), i
elif i in deprecated_attrs or i in deprecated:
with ignore_warnings(SymPyDeprecationWarning):
assert getattr(a, i) == getattr(b, i), i
elif not hasattr(a, i):
continue
else:
attr = getattr(a, i)
if not hasattr(attr, "__call__"):
assert hasattr(b, i), i
assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol)
c(a, b, d1)
c(b, a, d2)
#================== core =========================
def test_core_basic():
for c in (Atom, Atom(), Basic, Basic(), SingletonRegistry, S):
check(c)
def test_core_Str():
check(Str('x'))
def test_core_symbol():
# make the Symbol a unique name that doesn't class with any other
# testing variable in this file since after this test the symbol
# having the same name will be cached as noncommutative
for c in (Dummy, Dummy("x", commutative=False), Symbol,
Symbol("_issue_3130", commutative=False), Wild, Wild("x")):
check(c)
def test_core_numbers():
for c in (Integer(2), Rational(2, 3), Float("1.2")):
check(c)
for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))):
check(c, check_attr=False)
def test_core_float_copy():
# See gh-7457
y = Symbol("x") + 1.0
check(y) # does not raise TypeError ("argument is not an mpz")
def test_core_relational():
x = Symbol("x")
y = Symbol("y")
for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y),
LessThan, LessThan(x, y), Relational, Relational(x, y),
StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan,
StrictLessThan(x, y), Unequality, Unequality(x, y)):
check(c)
def test_core_add():
x = Symbol("x")
for c in (Add, Add(x, 4)):
check(c)
def test_core_mul():
x = Symbol("x")
for c in (Mul, Mul(x, 4)):
check(c)
def test_core_power():
x = Symbol("x")
for c in (Pow, Pow(x, 4)):
check(c)
def test_core_function():
x = Symbol("x")
for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda,
WildFunction):
check(f)
def test_core_undefinedfunctions():
f = Function("f")
# Full XFAILed test below
exclude = list(range(5))
# https://github.com/cloudpipe/cloudpickle/issues/65
# https://github.com/cloudpipe/cloudpickle/issues/190
exclude.append(cloudpickle)
check(f, exclude=exclude)
@XFAIL
def test_core_undefinedfunctions_fail():
# This fails because f is assumed to be a class at sympy.basic.function.f
f = Function("f")
check(f)
def test_core_interval():
for c in (Interval, Interval(0, 2)):
check(c)
def test_core_multidimensional():
for c in (vectorize, vectorize(0)):
check(c)
def test_Singletons():
protocols = [0, 1, 2, 3, 4]
copiers = [copy.copy, copy.deepcopy]
copiers += [lambda x: pickle.loads(pickle.dumps(x, proto))
for proto in protocols]
if cloudpickle:
copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))]
for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I,
oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant,
S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction):
for func in copiers:
assert func(obj) is obj
#================== functions ===================
from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu,
chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth,
tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs,
uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell,
hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh,
dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci,
tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin,
atan, ff, lucas, atan2, polygamma, exp)
def test_functions():
one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh,
sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot,
gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh,
acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci,
tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp)
two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial,
atan2, polygamma, hermite, legendre, uppergamma)
x, y, z = symbols("x,y,z")
others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z),
Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)),
assoc_legendre)
for cls in one_var:
check(cls)
c = cls(x)
check(c)
for cls in two_var:
check(cls)
c = cls(x, y)
check(c)
for cls in others:
check(cls)
#================== geometry ====================
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
from sympy.geometry.ellipse import Circle, Ellipse
from sympy.geometry.line import Line, LinearEntity, Ray, Segment
from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle
def test_geometry():
p1 = Point(1, 2)
p2 = Point(2, 3)
p3 = Point(0, 0)
p4 = Point(0, 1)
for c in (
GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2),
Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity,
LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2),
Polygon, Polygon(p1, p2, p3, p4), RegularPolygon,
RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)):
check(c, check_attr=False)
#================== integrals ====================
from sympy.integrals.integrals import Integral
def test_integrals():
x = Symbol("x")
for c in (Integral, Integral(x)):
check(c)
#==================== logic =====================
from sympy.core.logic import Logic
def test_logic():
for c in (Logic, Logic(1)):
check(c)
#================== matrices ====================
from sympy.matrices import Matrix, SparseMatrix
def test_matrices():
for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])):
check(c, deprecated=['_smat', '_mat'])
#================== ntheory =====================
from sympy.ntheory.generate import Sieve
def test_ntheory():
for c in (Sieve, Sieve()):
check(c)
#================== physics =====================
from sympy.physics.paulialgebra import Pauli
from sympy.physics.units import Unit
def test_physics():
for c in (Unit, meter, Pauli, Pauli(1)):
check(c)
#================== plotting ====================
# XXX: These tests are not complete, so XFAIL them
@XFAIL
def test_plotting():
from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme
from sympy.plotting.pygletplot.managed_window import ManagedWindow
from sympy.plotting.plot import Plot, ScreenShot
from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
from sympy.plotting.pygletplot.plot_camera import PlotCamera
from sympy.plotting.pygletplot.plot_controller import PlotController
from sympy.plotting.pygletplot.plot_curve import PlotCurve
from sympy.plotting.pygletplot.plot_interval import PlotInterval
from sympy.plotting.pygletplot.plot_mode import PlotMode
from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
from sympy.plotting.pygletplot.plot_object import PlotObject
from sympy.plotting.pygletplot.plot_surface import PlotSurface
from sympy.plotting.pygletplot.plot_window import PlotWindow
for c in (
ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow,
ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase,
PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController,
PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D,
Cylindrical, ParametricCurve2D, ParametricCurve3D,
ParametricSurface, Polar, Spherical, PlotObject, PlotSurface,
PlotWindow):
check(c)
@XFAIL
def test_plotting2():
#from sympy.plotting.color_scheme import ColorGradient
from sympy.plotting.pygletplot.color_scheme import ColorScheme
#from sympy.plotting.managed_window import ManagedWindow
from sympy.plotting.plot import Plot
#from sympy.plotting.plot import ScreenShot
from sympy.plotting.pygletplot.plot_axes import PlotAxes
#from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
#from sympy.plotting.plot_camera import PlotCamera
#from sympy.plotting.plot_controller import PlotController
#from sympy.plotting.plot_curve import PlotCurve
#from sympy.plotting.plot_interval import PlotInterval
#from sympy.plotting.plot_mode import PlotMode
#from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
# ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
#from sympy.plotting.plot_object import PlotObject
#from sympy.plotting.plot_surface import PlotSurface
# from sympy.plotting.plot_window import PlotWindow
check(ColorScheme("rainbow"))
check(Plot(1, visible=False))
check(PlotAxes())
#================== polys =======================
from sympy.polys.domains.integerring import ZZ
from sympy.polys.domains.rationalfield import QQ
from sympy.polys.orderings import lex
from sympy.polys.polytools import Poly
def test_pickling_polys_polytools():
from sympy.polys.polytools import PurePoly
# from sympy.polys.polytools import GroebnerBasis
x = Symbol('x')
for c in (Poly, Poly(x, x)):
check(c)
for c in (PurePoly, PurePoly(x)):
check(c)
# TODO: fix pickling of Options class (see GroebnerBasis._options)
# for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)):
# check(c)
def test_pickling_polys_polyclasses():
from sympy.polys.polyclasses import DMP, DMF, ANP
for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
check(c, deprecated=['rep'])
for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
check(c)
for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
check(c)
@XFAIL
def test_pickling_polys_rings():
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of rings works properly.
from sympy.polys.rings import PolyRing
ring = PolyRing("x,y,z", ZZ, lex)
for c in (PolyRing, ring):
check(c, exclude=[0, 1])
for c in (ring.dtype, ring.one):
check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k
def test_pickling_polys_fields():
pass
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of fields works properly.
# from sympy.polys.fields import FracField
# field = FracField("x,y,z", ZZ, lex)
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (FracField, field):
# check(c, exclude=[0, 1])
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (field.dtype, field.one):
# check(c, exclude=[0, 1])
def test_pickling_polys_elements():
from sympy.polys.domains.pythonrational import PythonRational
#from sympy.polys.domains.pythonfinitefield import PythonFiniteField
#from sympy.polys.domains.mpelements import MPContext
for c in (PythonRational, PythonRational(1, 7)):
check(c)
#gf = PythonFiniteField(17)
# TODO: fix pickling of ModularInteger
# for c in (gf.dtype, gf(5)):
# check(c)
#mp = MPContext()
# TODO: fix pickling of RealElement
# for c in (mp.mpf, mp.mpf(1.0)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (mp.mpc, mp.mpc(1.0, -1.5)):
# check(c)
def test_pickling_polys_domains():
# from sympy.polys.domains.pythonfinitefield import PythonFiniteField
from sympy.polys.domains.pythonintegerring import PythonIntegerRing
from sympy.polys.domains.pythonrationalfield import PythonRationalField
# TODO: fix pickling of ModularInteger
# for c in (PythonFiniteField, PythonFiniteField(17)):
# check(c)
for c in (PythonIntegerRing, PythonIntegerRing()):
check(c, check_attr=False)
for c in (PythonRationalField, PythonRationalField()):
check(c, check_attr=False)
if _gmpy is not None:
# from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField
from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
from sympy.polys.domains.gmpyrationalfield import GMPYRationalField
# TODO: fix pickling of ModularInteger
# for c in (GMPYFiniteField, GMPYFiniteField(17)):
# check(c)
for c in (GMPYIntegerRing, GMPYIntegerRing()):
check(c, check_attr=False)
for c in (GMPYRationalField, GMPYRationalField()):
check(c, check_attr=False)
#from sympy.polys.domains.realfield import RealField
#from sympy.polys.domains.complexfield import ComplexField
from sympy.polys.domains.algebraicfield import AlgebraicField
#from sympy.polys.domains.polynomialring import PolynomialRing
#from sympy.polys.domains.fractionfield import FractionField
from sympy.polys.domains.expressiondomain import ExpressionDomain
# TODO: fix pickling of RealElement
# for c in (RealField, RealField(100)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (ComplexField, ComplexField(100)):
# check(c)
for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))):
check(c, check_attr=False)
# TODO: AssertionError
# for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")):
# check(c)
# TODO: AttributeError: 'PolyElement' object has no attribute 'ring'
# for c in (FractionField, FractionField(ZZ, "x,y,z")):
# check(c)
for c in (ExpressionDomain, ExpressionDomain()):
check(c, check_attr=False)
def test_pickling_polys_orderings():
from sympy.polys.orderings import (LexOrder, GradedLexOrder,
ReversedGradedLexOrder, InverseOrder)
# from sympy.polys.orderings import ProductOrder
for c in (LexOrder, LexOrder()):
check(c)
for c in (GradedLexOrder, GradedLexOrder()):
check(c)
for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()):
check(c)
# TODO: Argh, Python is so naive. No lambdas nor inner function support in
# pickling module. Maybe someone could figure out what to do with this.
#
# for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]),
# (GradedLexOrder(), lambda m: m[2:]))):
# check(c)
for c in (InverseOrder, InverseOrder(LexOrder())):
check(c)
def test_pickling_polys_monomials():
from sympy.polys.monomials import MonomialOps, Monomial
x, y, z = symbols("x,y,z")
for c in (MonomialOps, MonomialOps(3)):
check(c)
for c in (Monomial, Monomial((1, 2, 3), (x, y, z))):
check(c)
def test_pickling_polys_errors():
from sympy.polys.polyerrors import (HeuristicGCDFailed,
HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
NotReversible, NotAlgebraic, DomainError, PolynomialError,
UnificationFailed, GeneratorsError, GeneratorsNeeded,
UnivariatePolynomialError, MultivariatePolynomialError, OptionError,
FlagError)
# from sympy.polys.polyerrors import (ExactQuotientFailed,
# OperationNotSupported, ComputationFailed, PolificationFailed)
# x = Symbol('x')
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
# check(c)
# TODO: TypeError: can't pickle instancemethod objects
# for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
# check(c)
for c in (HeuristicGCDFailed, HeuristicGCDFailed()):
check(c)
for c in (HomomorphismFailed, HomomorphismFailed()):
check(c)
for c in (IsomorphismFailed, IsomorphismFailed()):
check(c)
for c in (ExtraneousFactors, ExtraneousFactors()):
check(c)
for c in (EvaluationFailed, EvaluationFailed()):
check(c)
for c in (RefinementFailed, RefinementFailed()):
check(c)
for c in (CoercionFailed, CoercionFailed()):
check(c)
for c in (NotInvertible, NotInvertible()):
check(c)
for c in (NotReversible, NotReversible()):
check(c)
for c in (NotAlgebraic, NotAlgebraic()):
check(c)
for c in (DomainError, DomainError()):
check(c)
for c in (PolynomialError, PolynomialError()):
check(c)
for c in (UnificationFailed, UnificationFailed()):
check(c)
for c in (GeneratorsError, GeneratorsError()):
check(c)
for c in (GeneratorsNeeded, GeneratorsNeeded()):
check(c)
# TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda>
# for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
# check(c)
for c in (UnivariatePolynomialError, UnivariatePolynomialError()):
check(c)
for c in (MultivariatePolynomialError, MultivariatePolynomialError()):
check(c)
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
# check(c)
for c in (OptionError, OptionError()):
check(c)
for c in (FlagError, FlagError()):
check(c)
#def test_pickling_polys_options():
#from sympy.polys.polyoptions import Options
# TODO: fix pickling of `symbols' flag
# for c in (Options, Options((), dict(domain='ZZ', polys=False))):
# check(c)
# TODO: def test_pickling_polys_rootisolation():
# RealInterval
# ComplexInterval
def test_pickling_polys_rootoftools():
from sympy.polys.rootoftools import CRootOf, RootSum
x = Symbol('x')
f = x**3 + x + 3
for c in (CRootOf, CRootOf(f, 0)):
check(c)
for c in (RootSum, RootSum(f, exp)):
check(c)
#================== printing ====================
from sympy.printing.latex import LatexPrinter
from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.printer import Printer
from sympy.printing.python import PythonPrinter
def test_printing():
for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter,
MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict,
stringPict("a"), Printer, Printer(), PythonPrinter,
PythonPrinter()):
check(c)
@XFAIL
def test_printing1():
check(MathMLContentPrinter())
@XFAIL
def test_printing2():
check(MathMLPresentationPrinter())
@XFAIL
def test_printing3():
check(PrettyPrinter())
#================== series ======================
from sympy.series.limits import Limit
from sympy.series.order import Order
def test_series():
e = Symbol("e")
x = Symbol("x")
for c in (Limit, Limit(e, x, 1), Order, Order(e)):
check(c)
#================== concrete ==================
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
def test_concrete():
x = Symbol("x")
for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))):
check(c)
def test_deprecation_warning():
w = SymPyDeprecationWarning("message", deprecated_since_version='1.0', active_deprecations_target="active-deprecations")
check(w)
def test_issue_18438():
assert pickle.loads(pickle.dumps(S.Half)) == S.Half
#================= old pickles =================
def test_unpickle_from_older_versions():
data = (
b'\x80\x04\x95^\x00\x00\x00\x00\x00\x00\x00\x8c\x10sympy.core.power'
b'\x94\x8c\x03Pow\x94\x93\x94\x8c\x12sympy.core.numbers\x94\x8c'
b'\x07Integer\x94\x93\x94K\x02\x85\x94R\x94}\x94bh\x03\x8c\x04Half'
b'\x94\x93\x94)R\x94}\x94b\x86\x94R\x94}\x94b.'
)
assert pickle.loads(data) == sqrt(2)

View File

@ -0,0 +1,11 @@
from sympy.utilities.source import get_mod_func, get_class
def test_get_mod_func():
assert get_mod_func(
'sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic')
def test_get_class():
_basic = get_class('sympy.core.basic.Basic')
assert _basic.__name__ == 'Basic'

View File

@ -0,0 +1,10 @@
"""Tests for simple tools for timing functions' execution. """
from sympy.utilities.timeutils import timed
def test_timed():
result = timed(lambda: 1 + 1, limit=100000)
assert result[0] == 100000 and result[3] == "ns", str(result)
result = timed("1 + 1", limit=100000)
assert result[0] == 100000 and result[3] == "ns"

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
# A test file for XXE injection
# Username: Test
# Password: Test