NumPy 源码解析(三十四)
.\numpy\numpy\polynomial\tests\test_hermite.py
"""Tests for hermite module.
"""
from functools import reduce
import numpy as np
import numpy.polynomial.hermite as herm
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_,
)
H0 = np.array([1])
H1 = np.array([0, 2])
H2 = np.array([-2, 0, 4])
H3 = np.array([0, -12, 0, 8])
H4 = np.array([12, 0, -48, 0, 16])
H5 = np.array([0, 120, 0, -160, 0, 32])
H6 = np.array([-120, 0, 720, 0, -480, 0, 64])
H7 = np.array([0, -1680, 0, 3360, 0, -1344, 0, 128])
H8 = np.array([1680, 0, -13440, 0, 13440, 0, -3584, 0, 256])
H9 = np.array([0, 30240, 0, -80640, 0, 48384, 0, -9216, 0, 512])
Hlist = [H0, H1, H2, H3, H4, H5, H6, H7, H8, H9]
def trim(x):
return herm.hermtrim(x, tol=1e-6)
class TestConstants:
def test_hermdomain(self):
assert_equal(herm.hermdomain, [-1, 1])
def test_hermzero(self):
assert_equal(herm.hermzero, [0])
def test_hermone(self):
assert_equal(herm.hermone, [1])
def test_hermx(self):
assert_equal(herm.hermx, [0, .5])
class TestArithmetic:
x = np.linspace(-3, 3, 100)
def test_hermadd(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] += 1
res = herm.hermadd([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermsub(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] -= 1
res = herm.hermsub([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermmulx(self):
assert_equal(herm.hermmulx([0]), [0])
assert_equal(herm.hermmulx([1]), [0, .5])
for i in range(1, 5):
ser = [0]*i + [1]
tgt = [0]*(i - 1) + [i, 0, .5]
assert_equal(herm.hermmulx(ser), tgt)
def test_hermmul(self):
for i in range(5):
pol1 = [0]*i + [1]
val1 = herm.hermval(self.x, pol1)
for j in range(5):
msg = f"At i={i}, j={j}"
pol2 = [0]*j + [1]
val2 = herm.hermval(self.x, pol2)
pol3 = herm.hermmul(pol1, pol2)
val3 = herm.hermval(self.x, pol3)
assert_(len(pol3) == i + j + 1, msg)
assert_almost_equal(val3, val1*val2, err_msg=msg)
def test_hermdiv(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
ci = [0]*i + [1]
cj = [0]*j + [1]
tgt = herm.hermadd(ci, cj)
quo, rem = herm.hermdiv(tgt, ci)
res = herm.hermadd(herm.hermmul(quo, ci), rem)
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermpow(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
c = np.arange(i + 1)
tgt = reduce(herm.hermmul, [c]*j, np.array([1]))
res = herm.hermpow(c, j)
assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
c1d = np.array([2.5, 1., .75])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
x = np.random.random((3, 5))*2 - 1
y = polyval(x, [1., 2., 3.])
def test_hermval(self):
assert_equal(herm.hermval([], [1]).size, 0)
x = np.linspace(-1, 1)
y = [polyval(x, c) for c in Hlist]
for i in range(10):
msg = f"At i={i}"
tgt = y[i]
res = herm.hermval(x, [0]*i + [1])
assert_almost_equal(res, tgt, err_msg=msg)
for i in range(3):
dims = [2]*i
x = np.zeros(dims)
assert_equal(herm.hermval(x, [1]).shape, dims)
assert_equal(herm.hermval(x, [1, 0]).shape, dims)
assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)
def test_hermval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, herm.hermval2d, x1, x2[:2], self.c2d)
tgt = y1 * y2
res = herm.hermval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = herm.hermval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_hermval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, herm.hermval3d, x1, x2, x3[:2], self.c3d)
tgt = y1 * y2 * y3
res = herm.hermval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = herm.hermval3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3))
def test_hermgrid2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j->ij', y1, y2)
res = herm.hermgrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = herm.hermgrid2d(z, z, self.c2d)
assert_(res.shape == (2, 3)*2)
def test_hermgrid3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = herm.hermgrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = herm.hermgrid3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3)*3)
def test_hermint_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([herm.hermint(c) for c in c2d.T]).T
res = herm.hermint(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([herm.hermint(c) for c in c2d])
res = herm.hermint(c2d, axis=1)
assert_almost_equal(res, tgt)
tgt = np.vstack([herm.hermint(c, k=3) for c in c2d])
res = herm.hermint(c2d, k=3, axis=1)
assert_almost_equal(res, tgt)
class TestDerivative:
def test_hermder(self):
assert_raises(TypeError, herm.hermder, [0], .5)
assert_raises(ValueError, herm.hermder, [0], -1)
for i in range(5):
tgt = [0]*i + [1]
res = herm.hermder(tgt, m=0)
assert_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = herm.hermder(herm.hermint(tgt, m=j), m=j)
assert_almost_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = herm.hermder(herm.hermint(tgt, m=j, scl=2), m=j, scl=.5)
assert_almost_equal(trim(res), trim(tgt))
def test_hermder_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([herm.hermder(c) for c in c2d.T]).T
res = herm.hermder(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([herm.hermder(c) for c in c2d])
res = herm.hermder(c2d, axis=1)
assert_almost_equal(res, tgt)
class TestVander:
x = np.random.random((3, 5))*2 - 1
def test_hermvander(self):
x = np.arange(3)
v = herm.hermvander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], herm.hermval(x, coef))
x = np.array([[1, 2], [3, 4], [5, 6]])
v = herm.hermvander(x, 3)
assert_(v.shape == (3, 2, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], herm.hermval(x, coef))
def test_hermvander2d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3))
van = herm.hermvander2d(x1, x2, [1, 2])
tgt = herm.hermval2d(x1, x2, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = herm.hermvander2d([x1], [x2], [1, 2])
assert_(van.shape == (1, 5, 6))
def test_hermvander3d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3, 4))
van = herm.hermvander3d(x1, x2, x3, [1, 2, 3])
tgt = herm.hermval3d(x1, x2, x3, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = herm.hermvander3d([x1], [x2], [x3], [1, 2, 3])
assert_(van.shape == (1, 5, 24))
class TestFitting:
class TestCompanion:
def test_raises(self):
assert_raises(ValueError, herm.hermcompanion, [])
def test_dimensions(self):
for i in range(1, 5):
coef = [0]*i + [1]
assert_(herm.hermcompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(herm.hermcompanion([1, 2])[0, 0] == -.25)
class TestGauss:
def test_100(self):
x, w = herm.hermgauss(100)
v = herm.hermvander(x, 99)
vv = np.dot(v.T * w, v)
vd = 1/np.sqrt(vv.diagonal())
vv = vd[:, None] * vv * vd
assert_almost_equal(vv, np.eye(100))
tgt = np.sqrt(np.pi)
assert_almost_equal(w.sum(), tgt)
class TestMisc:
def test_hermfromroots(self):
res = herm.hermfromroots([])
assert_almost_equal(trim(res), [1])
for i in range(1, 5):
roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
pol = herm.hermfromroots(roots)
res = herm.hermval(roots, pol)
tgt = 0
assert_(len(pol) == i + 1)
assert_almost_equal(herm.herm2poly(pol)[-1], 1)
assert_almost_equal(res, tgt)
def test_hermroots(self):
assert_almost_equal(herm.hermroots([1]), [])
assert_almost_equal(herm.hermroots([1, 1]), [-.5])
for i in range(2, 5):
tgt = np.linspace(-1, 1, i)
res = herm.hermroots(herm.hermfromroots(tgt))
assert_almost_equal(trim(res), trim(tgt))
def test_hermtrim(self):
coef = [2, -1, 1, 0]
assert_raises(ValueError, herm.hermtrim, coef, -1)
assert_equal(herm.hermtrim(coef), coef[:-1])
assert_equal(herm.hermtrim(coef, 1), coef[:-3])
assert_equal(herm.hermtrim(coef, 2), [0])
def test_hermline(self):
assert_equal(herm.hermline(3, 4), [3, 2])
def test_herm2poly(self):
for i in range(10):
assert_almost_equal(herm.herm2poly([0]*i + [1]), Hlist[i])
def test_poly2herm(self):
for i in range(10):
assert_almost_equal(herm.poly2herm(Hlist[i]), [0]*i + [1])
def test_weight(self):
x = np.linspace(-5, 5, 11)
tgt = np.exp(-x**2)
res = herm.hermweight(x)
assert_almost_equal(res, tgt)
.\numpy\numpy\polynomial\tests\test_hermite_e.py
"""Tests for hermite_e module.
"""
from functools import reduce
import numpy as np
import numpy.polynomial.hermite_e as herme
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_,
)
He0 = np.array([1])
He1 = np.array([0, 1])
He2 = np.array([-1, 0, 1])
He3 = np.array([0, -3, 0, 1])
He4 = np.array([3, 0, -6, 0, 1])
He5 = np.array([0, 15, 0, -10, 0, 1])
He6 = np.array([-15, 0, 45, 0, -15, 0, 1])
He7 = np.array([0, -105, 0, 105, 0, -21, 0, 1])
He8 = np.array([105, 0, -420, 0, 210, 0, -28, 0, 1])
He9 = np.array([0, 945, 0, -1260, 0, 378, 0, -36, 0, 1])
Helist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9]
def trim(x):
return herme.hermetrim(x, tol=1e-6)
class TestConstants:
def test_hermedomain(self):
assert_equal(herme.hermedomain, [-1, 1])
def test_hermezero(self):
assert_equal(herme.hermezero, [0])
def test_hermeone(self):
assert_equal(herme.hermeone, [1])
def test_hermex(self):
assert_equal(herme.hermex, [0, 1])
class TestArithmetic:
x = np.linspace(-3, 3, 100)
def test_hermeadd(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] += 1
res = herme.hermeadd([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermesub(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] -= 1
res = herme.hermesub([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermemulx(self):
assert_equal(herme.hermemulx([0]), [0])
assert_equal(herme.hermemulx([1]), [0, 1])
for i in range(1, 5):
ser = [0]*i + [1]
tgt = [0]*(i - 1) + [i, 0, 1]
assert_equal(herme.hermemulx(ser), tgt)
def test_hermemul(self):
for i in range(5):
pol1 = [0]*i + [1]
val1 = herme.hermeval(self.x, pol1)
for j in range(5):
msg = f"At i={i}, j={j}"
pol2 = [0]*j + [1]
val2 = herme.hermeval(self.x, pol2)
pol3 = herme.hermemul(pol1, pol2)
val3 = herme.hermeval(self.x, pol3)
assert_(len(pol3) == i + j + 1, msg)
assert_almost_equal(val3, val1 * val2, err_msg=msg)
def test_hermediv(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
ci = [0]*i + [1]
cj = [0]*j + [1]
tgt = herme.hermeadd(ci, cj)
quo, rem = herme.hermediv(tgt, ci)
res = herme.hermeadd(herme.hermemul(quo, ci), rem)
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermepow(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
c = np.arange(i + 1)
tgt = reduce(herme.hermemul, [c]*j, np.array([1]))
res = herme.hermepow(c, j)
assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
c1d = np.array([4., 2., 3.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
x = np.random.random((3, 5))*2 - 1
y = polyval(x, [1., 2., 3.])
def test_hermeval(self):
assert_equal(herme.hermeval([], [1]).size, 0)
x = np.linspace(-1, 1)
y = [polyval(x, c) for c in Helist]
for i in range(10):
msg = f"At i={i}"
tgt = y[i]
res = herme.hermeval(x, [0]*i + [1])
assert_almost_equal(res, tgt, err_msg=msg)
for i in range(3):
dims = [2]*i
x = np.zeros(dims)
assert_equal(herme.hermeval(x, [1]).shape, dims)
assert_equal(herme.hermeval(x, [1, 0]).shape, dims)
assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)
def test_hermeval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)
tgt = y1 * y2
res = herme.hermeval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
assert_(res.shape == (2, 3))
def test_hermeval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)
tgt = y1 * y2 * y3
res = herme.hermeval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
assert_(res.shape == (2, 3))
def test_hermegrid2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j->ij', y1, y2)
res = herme.hermegrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
assert_(res.shape == (2, 3) * 2)
def test_hermegrid3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = herme.hermegrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
assert_(res.shape == (2, 3) * 3)
class TestIntegral:
def test_hermeint_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T
res = herme.hermeint(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([herme.hermeint(c) for c in c2d])
res = herme.hermeint(c2d, axis=1)
assert_almost_equal(res, tgt)
tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d])
res = herme.hermeint(c2d, k=3, axis=1)
assert_almost_equal(res, tgt)
class TestDerivative:
def test_hermeder(self):
assert_raises(TypeError, herme.hermeder, [0], .5)
assert_raises(ValueError, herme.hermeder, [0], -1)
for i in range(5):
tgt = [0]*i + [1]
res = herme.hermeder(tgt, m=0)
assert_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)
assert_almost_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = herme.hermeder(
herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5)
assert_almost_equal(trim(res), trim(tgt))
def test_hermeder_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T
res = herme.hermeder(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([herme.hermeder(c) for c in c2d])
res = herme.hermeder(c2d, axis=1)
assert_almost_equal(res, tgt)
class TestVander:
x = np.random.random((3, 5))*2 - 1
def test_hermevander(self):
x = np.arange(3)
v = herme.hermevander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], herme.hermeval(x, coef))
x = np.array([[1, 2], [3, 4], [5, 6]])
v = herme.hermevander(x, 3)
assert_(v.shape == (3, 2, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], herme.hermeval(x, coef))
def test_hermevander2d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3))
van = herme.hermevander2d(x1, x2, [1, 2])
tgt = herme.hermeval2d(x1, x2, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = herme.hermevander2d([x1], [x2], [1, 2])
assert_(van.shape == (1, 5, 6))
def test_hermevander3d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3, 4))
van = herme.hermevander3d(x1, x2, x3, [1, 2, 3])
tgt = herme.hermeval3d(x1, x2, x3, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3])
assert_(van.shape == (1, 5, 24))
class TestFitting:
class TestCompanion:
def test_raises(self):
assert_raises(ValueError, herme.hermecompanion, [])
assert_raises(ValueError, herme.hermecompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0]*i + [1]
assert_(herme.hermecompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(herme.hermecompanion([1, 2])[0, 0] == -.5)
class TestGauss:
def test_100(self):
x, w = herme.hermegauss(100)
v = herme.hermevander(x, 99)
vv = np.dot(v.T * w, v)
vd = 1/np.sqrt(vv.diagonal())
vv = vd[:, None] * vv * vd
assert_almost_equal(vv, np.eye(100))
tgt = np.sqrt(2*np.pi)
assert_almost_equal(w.sum(), tgt)
class TestMisc:
def test_hermefromroots(self):
res = herme.hermefromroots([])
assert_almost_equal(trim(res), [1])
for i in range(1, 5):
roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
pol = herme.hermefromroots(roots)
res = herme.hermeval(roots, pol)
tgt = 0
assert_(len(pol) == i + 1)
assert_almost_equal(herme.herme2poly(pol)[-1], 1)
assert_almost_equal(res, tgt)
def test_hermeroots(self):
assert_almost_equal(herme.hermeroots([1]), [])
assert_almost_equal(herme.hermeroots([1, 1]), [-1])
for i in range(2, 5):
tgt = np.linspace(-1, 1, i)
res = herme.hermeroots(herme.hermefromroots(tgt))
assert_almost_equal(trim(res), trim(tgt))
def test_hermetrim(self):
coef = [2, -1, 1, 0]
assert_raises(ValueError, herme.hermetrim, coef, -1)
assert_equal(herme.hermetrim(coef), coef[:-1])
assert_equal(herme.hermetrim(coef, 1), coef[:-3])
assert_equal(herme.hermetrim(coef, 2), [0])
def test_hermeline(self):
assert_equal(herme.hermeline(3, 4), [3, 4])
def test_herme2poly(self):
for i in range(10):
assert_almost_equal(herme.herme2poly([0]*i + [1]), Helist[i])
def test_poly2herme(self):
for i in range(10):
assert_almost_equal(herme.poly2herme(Helist[i]), [0]*i + [1])
def test_weight(self):
x = np.linspace(-5, 5, 11)
tgt = np.exp(-.5*x**2)
res = herme.hermeweight(x)
assert_almost_equal(res, tgt)
.\numpy\numpy\polynomial\tests\test_laguerre.py
"""Tests for laguerre module.
"""
from functools import reduce
import numpy as np
import numpy.polynomial.laguerre as lag
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_,
)
L0 = np.array([1])/1
L1 = np.array([1, -1])/1
L2 = np.array([2, -4, 1])/2
L3 = np.array([6, -18, 9, -1])/6
L4 = np.array([24, -96, 72, -16, 1])/24
L5 = np.array([120, -600, 600, -200, 25, -1])/120
L6 = np.array([720, -4320, 5400, -2400, 450, -36, 1])/720
Llist = [L0, L1, L2, L3, L4, L5, L6]
def trim(x):
return lag.lagtrim(x, tol=1e-6)
class TestConstants:
def test_lagdomain(self):
assert_equal(lag.lagdomain, [0, 1])
def test_lagzero(self):
assert_equal(lag.lagzero, [0])
def test_lagone(self):
assert_equal(lag.lagone, [1])
def test_lagx(self):
assert_equal(lag.lagx, [1, -1])
class TestArithmetic:
x = np.linspace(-3, 3, 100)
def test_lagadd(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] += 1
res = lag.lagadd([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_lagsub(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] -= 1
res = lag.lagsub([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_lagmulx(self):
assert_equal(lag.lagmulx([0]), [0])
assert_equal(lag.lagmulx([1]), [1, -1])
for i in range(1, 5):
ser = [0]*i + [1]
tgt = [0]*(i - 1) + [-i, 2*i + 1, -(i + 1)]
assert_almost_equal(lag.lagmulx(ser), tgt)
def test_lagmul(self):
for i in range(5):
pol1 = [0]*i + [1]
val1 = lag.lagval(self.x, pol1)
for j in range(5):
msg = f"At i={i}, j={j}"
pol2 = [0]*j + [1]
val2 = lag.lagval(self.x, pol2)
pol3 = lag.lagmul(pol1, pol2)
val3 = lag.lagval(self.x, pol3)
assert_(len(pol3) == i + j + 1, msg)
assert_almost_equal(val3, val1*val2, err_msg=msg)
def test_lagdiv(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
ci = [0]*i + [1]
cj = [0]*j + [1]
tgt = lag.lagadd(ci, cj)
quo, rem = lag.lagdiv(tgt, ci)
res = lag.lagadd(lag.lagmul(quo, ci), rem)
assert_almost_equal(trim(res), trim(tgt), err_msg=msg)
def test_lagpow(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
c = np.arange(i + 1)
tgt = reduce(lag.lagmul, [c]*j, np.array([1]))
res = lag.lagpow(c, j)
assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
c1d = np.array([9., -14., 6.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
x = np.random.random((3, 5))*2 - 1
y = polyval(x, [1., 2., 3.])
def test_lagval(self):
assert_equal(lag.lagval([], [1]).size, 0)
x = np.linspace(-1, 1)
y = [polyval(x, c) for c in Llist]
for i in range(7):
msg = f"At i={i}"
tgt = y[i]
res = lag.lagval(x, [0]*i + [1])
assert_almost_equal(res, tgt, err_msg=msg)
for i in range(3):
dims = [2]*i
x = np.zeros(dims)
assert_equal(lag.lagval(x, [1]).shape, dims)
assert_equal(lag.lagval(x, [1, 0]).shape, dims)
assert_equal(lag.lagval(x, [1, 0, 0]).shape, dims)
def test_lagval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, lag.lagval2d, x1, x2[:2], self.c2d)
tgt = y1*y2
res = lag.lagval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = lag.lagval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_lagval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, lag.lagval3d, x1, x2, x3[:2], self.c3d)
tgt = y1*y2*y3
res = lag.lagval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = lag.lagval3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3))
def test_laggrid2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j->ij', y1, y2)
res = lag.laggrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = lag.laggrid2d(z, z, self.c2d)
assert_(res.shape == (2, 3)*2)
def test_laggrid3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = lag.laggrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = lag.laggrid3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3)*3)
class TestIntegral:
def test_lagint_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([lag.lagint(c) for c in c2d.T]).T
res = lag.lagint(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([lag.lagint(c) for c in c2d])
res = lag.lagint(c2d, axis=1)
assert_almost_equal(res, tgt)
tgt = np.vstack([lag.lagint(c, k=3) for c in c2d])
res = lag.lagint(c2d, k=3, axis=1)
assert_almost_equal(res, tgt)
class TestDerivative:
def test_lagder(self):
assert_raises(TypeError, lag.lagder, [0], .5)
assert_raises(ValueError, lag.lagder, [0], -1)
for i in range(5):
tgt = [0]*i + [1]
res = lag.lagder(tgt, m=0)
assert_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = lag.lagder(lag.lagint(tgt, m=j), m=j)
assert_almost_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = lag.lagder(lag.lagint(tgt, m=j, scl=2), m=j, scl=.5)
assert_almost_equal(trim(res), trim(tgt))
def test_lagder_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([lag.lagder(c) for c in c2d.T]).T
res = lag.lagder(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([lag.lagder(c) for c in c2d])
res = lag.lagder(c2d, axis=1)
assert_almost_equal(res, tgt)
class TestVander:
x = np.random.random((3, 5))*2 - 1
def test_lagvander(self):
x = np.arange(3)
v = lag.lagvander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], lag.lagval(x, coef))
x = np.array([[1, 2], [3, 4], [5, 6]])
v = lag.lagvander(x, 3)
assert_(v.shape == (3, 2, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], lag.lagval(x, coef))
def test_lagvander2d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3))
van = lag.lagvander2d(x1, x2, [1, 2])
tgt = lag.lagval2d(x1, x2, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = lag.lagvander2d([x1], [x2], [1, 2])
assert_(van.shape == (1, 5, 6))
def test_lagvander3d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3, 4))
van = lag.lagvander3d(x1, x2, x3, [1, 2, 3])
tgt = lag.lagval3d(x1, x2, x3, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = lag.lagvander3d([x1], [x2], [x3], [1, 2, 3])
assert_(van.shape == (1, 5, 24))
class TestFitting:
pass
def test_lagfit(self):
def f(x):
return x*(x - 1)*(x - 2)
assert_raises(ValueError, lag.lagfit, [1], [1], -1)
assert_raises(TypeError, lag.lagfit, [[1]], [1], 0)
assert_raises(TypeError, lag.lagfit, [], [1], 0)
assert_raises(TypeError, lag.lagfit, [1], [[[1]]], 0)
assert_raises(TypeError, lag.lagfit, [1, 2], [1], 0)
assert_raises(TypeError, lag.lagfit, [1], [1, 2], 0)
assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[[1]])
assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[1, 1])
assert_raises(ValueError, lag.lagfit, [1], [1], [-1,])
assert_raises(ValueError, lag.lagfit, [1], [1], [2, -1, 6])
assert_raises(TypeError, lag.lagfit, [1], [1], [])
x = np.linspace(0, 2)
y = f(x)
coef3 = lag.lagfit(x, y, 3)
assert_equal(len(coef3), 4)
assert_almost_equal(lag.lagval(x, coef3), y)
coef3 = lag.lagfit(x, y, [0, 1, 2, 3])
assert_equal(len(coef3), 4)
assert_almost_equal(lag.lagval(x, coef3), y)
coef4 = lag.lagfit(x, y, 4)
assert_equal(len(coef4), 5)
assert_almost_equal(lag.lagval(x, coef4), y)
coef4 = lag.lagfit(x, y, [0, 1, 2, 3, 4])
assert_equal(len(coef4), 5)
assert_almost_equal(lag.lagval(x, coef4), y)
coef2d = lag.lagfit(x, np.array([y, y]).T, 3)
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
coef2d = lag.lagfit(x, np.array([y, y]).T, [0, 1, 2, 3])
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
w = np.zeros_like(x)
yw = y.copy()
w[1::2] = 1
y[0::2] = 0
wcoef3 = lag.lagfit(x, yw, 3, w=w)
assert_almost_equal(wcoef3, coef3)
wcoef3 = lag.lagfit(x, yw, [0, 1, 2, 3], w=w)
assert_almost_equal(wcoef3, coef3)
wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, 3, w=w)
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
x = [1, 1j, -1, -1j]
assert_almost_equal(lag.lagfit(x, x, 1), [1, -1])
assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1])
class TestCompanion:
def test_raises(self):
assert_raises(ValueError, lag.lagcompanion, [])
assert_raises(ValueError, lag.lagcompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0]*i + [1]
assert_(lag.lagcompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5)
class TestGauss:
def test_100(self):
x, w = lag.laggauss(100)
v = lag.lagvander(x, 99)
vv = np.dot(v.T * w, v)
vd = 1/np.sqrt(vv.diagonal())
vv = vd[:, None] * vv * vd
assert_almost_equal(vv, np.eye(100))
tgt = 1.0
assert_almost_equal(w.sum(), tgt)
class TestMisc:
def test_lagfromroots(self):
res = lag.lagfromroots([])
assert_almost_equal(trim(res), [1])
for i in range(1, 5):
roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
pol = lag.lagfromroots(roots)
res = lag.lagval(roots, pol)
tgt = 0
assert_(len(pol) == i + 1)
assert_almost_equal(lag.lag2poly(pol)[-1], 1)
assert_almost_equal(res, tgt)
def test_lagroots(self):
assert_almost_equal(lag.lagroots([1]), [])
assert_almost_equal(lag.lagroots([0, 1]), [1])
for i in range(2, 5):
tgt = np.linspace(0, 3, i)
res = lag.lagroots(lag.lagfromroots(tgt))
assert_almost_equal(trim(res), trim(tgt))
def test_lagtrim(self):
coef = [2, -1, 1, 0]
assert_raises(ValueError, lag.lagtrim, coef, -1)
assert_equal(lag.lagtrim(coef), coef[:-1])
assert_equal(lag.lagtrim(coef, 1), coef[:-3])
assert_equal(lag.lagtrim(coef, 2), [0])
def test_lagline(self):
assert_equal(lag.lagline(3, 4), [7, -4])
def test_lag2poly(self):
for i in range(7):
assert_almost_equal(lag.lag2poly([0]*i + [1]), Llist[i])
def test_poly2lag(self):
for i in range(7):
assert_almost_equal(lag.poly2lag(Llist[i]), [0]*i + [1])
def test_weight(self):
x = np.linspace(0, 10, 11)
tgt = np.exp(-x)
res = lag.lagweight(x)
assert_almost_equal(res, tgt)
.\numpy\numpy\polynomial\tests\test_legendre.py
"""Tests for legendre module.
"""
from functools import reduce
import numpy as np
import numpy.polynomial.legendre as leg
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_
)
L0 = np.array([1])
L1 = np.array([0, 1])
L2 = np.array([-1, 0, 3])/2
L3 = np.array([0, -3, 0, 5])/2
L4 = np.array([3, 0, -30, 0, 35])/8
L5 = np.array([0, 15, 0, -70, 0, 63])/8
L6 = np.array([-5, 0, 105, 0, -315, 0, 231])/16
L7 = np.array([0, -35, 0, 315, 0, -693, 0, 429])/16
L8 = np.array([35, 0, -1260, 0, 6930, 0, -12012, 0, 6435])/128
L9 = np.array([0, 315, 0, -4620, 0, 18018, 0, -25740, 0, 12155])/128
Llist = [L0, L1, L2, L3, L4, L5, L6, L7, L8, L9]
def trim(x):
return leg.legtrim(x, tol=1e-6)
class TestConstants:
def test_legdomain(self):
assert_equal(leg.legdomain, [-1, 1])
def test_legzero(self):
assert_equal(leg.legzero, [0])
def test_legone(self):
assert_equal(leg.legone, [1])
def test_legx(self):
assert_equal(leg.legx, [0, 1])
class TestArithmetic:
x = np.linspace(-1, 1, 100)
def test_legadd(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] += 1
res = leg.legadd([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_legsub(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] -= 1
res = leg.legsub([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_legmulx(self):
assert_equal(leg.legmulx([0]), [0])
assert_equal(leg.legmulx([1]), [0, 1])
for i in range(1, 5):
tmp = 2*i + 1
ser = [0]*i + [1]
tgt = [0]*(i - 1) + [i/tmp, 0, (i + 1)/tmp]
assert_equal(leg.legmulx(ser), tgt)
def test_legmul(self):
for i in range(5):
pol1 = [0]*i + [1]
val1 = leg.legval(self.x, pol1)
for j in range(5):
msg = f"At i={i}, j={j}"
pol2 = [0]*j + [1]
val2 = leg.legval(self.x, pol2)
pol3 = leg.legmul(pol1, pol2)
val3 = leg.legval(self.x, pol3)
assert_(len(pol3) == i + j + 1, msg)
assert_almost_equal(val3, val1*val2, err_msg=msg)
def test_legdiv(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
ci = [0]*i + [1]
cj = [0]*j + [1]
tgt = leg.legadd(ci, cj)
quo, rem = leg.legdiv(tgt, ci)
res = leg.legadd(leg.legmul(quo, ci), rem)
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_legpow(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
c = np.arange(i + 1)
tgt = reduce(leg.legmul, [c]*j, np.array([1]))
res = leg.legpow(c, j)
assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
c1d = np.array([2., 2., 2.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
x = np.random.random((3, 5))*2 - 1
y = polyval(x, [1., 2., 3.])
def test_legval(self):
assert_equal(leg.legval([], [1]).size, 0)
x = np.linspace(-1, 1)
y = [polyval(x, c) for c in Llist]
for i in range(10):
msg = f"At i={i}"
tgt = y[i]
res = leg.legval(x, [0]*i + [1])
assert_almost_equal(res, tgt, err_msg=msg)
for i in range(3):
dims = [2]*i
x = np.zeros(dims)
assert_equal(leg.legval(x, [1]).shape, dims)
assert_equal(leg.legval(x, [1, 0]).shape, dims)
assert_equal(leg.legval(x, [1, 0, 0]).shape, dims)
def test_legval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, leg.legval2d, x1, x2[:2], self.c2d)
tgt = y1 * y2
res = leg.legval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = leg.legval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_legval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises(ValueError, leg.legval3d, x1, x2, x3[:2], self.c3d)
tgt = y1 * y2 * y3
res = leg.legval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = leg.legval3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3))
def test_leggrid2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j->ij', y1, y2)
res = leg.leggrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = leg.leggrid2d(z, z, self.c2d)
assert_(res.shape == (2, 3)*2)
def test_leggrid3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = leg.leggrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = leg.leggrid3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3)*3)
class TestIntegral:
def test_legint_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([leg.legint(c) for c in c2d.T]).T
res = leg.legint(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([leg.legint(c) for c in c2d])
res = leg.legint(c2d, axis=1)
assert_almost_equal(res, tgt)
tgt = np.vstack([leg.legint(c, k=3) for c in c2d])
res = leg.legint(c2d, k=3, axis=1)
assert_almost_equal(res, tgt)
def test_legint_zerointord(self):
assert_equal(leg.legint((1, 2, 3), 0), (1, 2, 3))
class TestDerivative:
def test_legder(self):
assert_raises(TypeError, leg.legder, [0], .5)
assert_raises(ValueError, leg.legder, [0], -1)
for i in range(5):
tgt = [0]*i + [1]
res = leg.legder(tgt, m=0)
assert_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = leg.legder(leg.legint(tgt, m=j), m=j)
assert_almost_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5)
assert_almost_equal(trim(res), trim(tgt))
def test_legder_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([leg.legder(c) for c in c2d.T]).T
res = leg.legder(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([leg.legder(c) for c in c2d])
res = leg.legder(c2d, axis=1)
assert_almost_equal(res, tgt)
def test_legder_orderhigherthancoeff(self):
c = (1, 2, 3, 4)
assert_equal(leg.legder(c, 4), [0])
class TestVander:
x = np.random.random((3, 5))*2 - 1
def test_legvander(self):
x = np.arange(3)
v = leg.legvander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], leg.legval(x, coef))
x = np.array([[1, 2], [3, 4], [5, 6]])
v = leg.legvander(x, 3)
assert_(v.shape == (3, 2, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], leg.legval(x, coef))
def test_legvander2d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3))
van = leg.legvander2d(x1, x2, [1, 2])
tgt = leg.legval2d(x1, x2, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = leg.legvander2d([x1], [x2], [1, 2])
assert_(van.shape == (1, 5, 6))
def test_legvander3d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3, 4))
van = leg.legvander3d(x1, x2, x3, [1, 2, 3])
tgt = leg.legval3d(x1, x2, x3, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = leg.legvander3d([x1], [x2], [x3], [1, 2, 3])
assert_(van.shape == (1, 5, 24))
def test_legvander_negdeg(self):
assert_raises(ValueError, leg.legvander, (1, 2, 3), -1)
class TestFitting:
pass
class TestCompanion:
def test_raises(self):
assert_raises(ValueError, leg.legcompanion, [])
assert_raises(ValueError, leg.legcompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0]*i + [1]
assert_(leg.legcompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(leg.legcompanion([1, 2])[0, 0] == -.5)
class TestGauss:
def test_100(self):
x, w = leg.leggauss(100)
v = leg.legvander(x, 99)
vv = np.dot(v.T * w, v)
vd = 1/np.sqrt(vv.diagonal())
vv = vd[:, None] * vv * vd
assert_almost_equal(vv, np.eye(100))
tgt = 2.0
assert_almost_equal(w.sum(), tgt)
class TestMisc:
def test_legfromroots(self):
res = leg.legfromroots([])
assert_almost_equal(trim(res), [1])
for i in range(1, 5):
roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
pol = leg.legfromroots(roots)
res = leg.legval(roots, pol)
tgt = 0
assert_(len(pol) == i + 1)
assert_almost_equal(leg.leg2poly(pol)[-1], 1)
assert_almost_equal(res, tgt)
def test_legroots(self):
assert_almost_equal(leg.legroots([1]), [])
assert_almost_equal(leg.legroots([1, 2]), [-.5])
for i in range(2, 5):
tgt = np.linspace(-1, 1, i)
res = leg.legroots(leg.legfromroots(tgt))
assert_almost_equal(trim(res), trim(tgt))
def test_legtrim(self):
coef = [2, -1, 1, 0]
assert_raises(ValueError, leg.legtrim, coef, -1)
assert_equal(leg.legtrim(coef), coef[:-1])
assert_equal(leg.legtrim(coef, 1), coef[:-3])
assert_equal(leg.legtrim(coef, 2), [0])
def test_legline(self):
assert_equal(leg.legline(3, 4))
def test_legline_zeroscl(self):
assert_equal(leg.legline(3, 0))
def test_leg2poly(self):
for i in range(10):
assert_almost_equal(leg.leg2poly([0]*i + [1]), Llist[i])
def test_poly2leg(self):
for i in range(10):
assert_almost_equal(leg.poly2leg(Llist[i]), [0]*i + [1])
def test_weight(self):
x = np.linspace(-1, 1, 11)
tgt = 1.
res = leg.legweight(x)
assert_almost_equal(res, tgt)
.\numpy\numpy\polynomial\tests\test_polynomial.py
"""Tests for polynomial module.
"""
从 functools 模块导入 reduce 函数,用于多项式操作
从 fractions 模块导入 Fraction 类,处理有理数
导入 numpy 库并将其重命名为 np,用于数值计算
从 numpy.polynomial.polynomial 模块导入 poly 对象,用于多项式操作
导入 pickle 模块,用于序列化和反序列化对象
从 copy 模块导入 deepcopy 函数,用于深拷贝对象
从 numpy.testing 模块导入多个断言函数,用于单元测试断言
定义函数 trim,接受参数 x,调用 poly.polytrim 函数并传入 tol=1e-6 参数,用于修剪多项式的小系数
定义一系列多项式 T0 到 T9,每个多项式都是一个列表,表示多项式的系数
将多项式 T0 到 T9 组成一个列表 Tlist
定义类 TestConstants,用于测试多项式模块中的常数和常量
定义方法 test_polydomain,断言 poly.polydomain 的值为 [-1, 1]
定义方法 test_polyzero,断言 poly.polyzero 的值为 [0]
定义方法 test_polyone,断言 poly.polyone 的值为 [1]
定义方法 test_polyx,断言 poly.polyx 的值为 [0, 1]
定义方法 test_copy,创建多项式对象 x,深拷贝 x 并赋值给 y,断言 x 和 y 的值相等
定义方法 test_pickle,创建多项式对象 x,使用 pickle 序列化和反序列化 x,断言 x 和 y 的值相等
定义类 TestArithmetic,用于测试多项式模块中的算术运算
定义方法 test_polyadd,使用嵌套的循环遍历范围在 0 到 4 的整数 i 和 j,并生成详细的错误消息。
创建目标数组 tgt,对于每次迭代,调用 poly.polyadd 函数计算两个多项式的和,并使用 trim 函数修剪结果,断言结果等于目标数组 tgt。
定义方法 test_polysub,使用嵌套的循环遍历范围在 0 到 4 的整数 i 和 j,并生成详细的错误消息。
创建目标数组 tgt,对于每次迭代,调用 poly.polysub 函数计算两个多项式的差,并使用 trim 函数修剪结果,断言结果等于目标数组 tgt。
定义方法 test_polymulx,断言 poly.polymulx([0]) 的结果为 [0],poly.polymulx([1]) 的结果为 [0, 1]。
使用循环遍历范围在 1 到 4 的整数 i,创建系数数组 ser,创建目标数组 tgt,并断言 poly.polymulx 函数计算结果等于目标数组 tgt。
定义方法 test_polymul,使用嵌套的循环遍历范围在 0 到 4 的整数 i 和 j,并生成详细的错误消息。
创建目标数组 tgt,对于每次迭代,调用 poly.polymul 函数计算两个多项式的乘积,并使用 trim 函数修剪结果,断言结果等于目标数组 tgt。
def test_polydiv(self):
assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])
quo, rem = poly.polydiv([2], [2])
assert_equal((quo, rem), (1, 0))
quo, rem = poly.polydiv([2, 2], [2])
assert_equal((quo, rem), ((1, 1), 0))
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
ci = [0]*i + [1, 2]
cj = [0]*j + [1, 2]
tgt = poly.polyadd(ci, cj)
quo, rem = poly.polydiv(tgt, ci)
res = poly.polyadd(poly.polymul(quo, ci), rem)
assert_equal(res, tgt, err_msg=msg)
def test_polypow(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
c = np.arange(i + 1)
tgt = reduce(poly.polymul, [c]*j, np.array([1]))
res = poly.polypow(c, j)
assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestFraction:
def test_Fraction(self):
f = Fraction(2, 3)
one = Fraction(1, 1)
zero = Fraction(0, 1)
p = poly.Polynomial([f, f], domain=[zero, one], window=[zero, one])
x = 2 * p + p ** 2
assert_equal(x.coef, np.array([Fraction(16, 9), Fraction(20, 9),
Fraction(4, 9)], dtype=object))
assert_equal(p.domain, [zero, one])
assert_equal(p.coef.dtype, np.dtypes.ObjectDType())
assert_(isinstance(p(f), Fraction))
assert_equal(p(f), Fraction(10, 9))
p_deriv = poly.Polynomial([Fraction(2, 3)], domain=[zero, one],
window=[zero, one])
assert_equal(p.deriv(), p_deriv)
class TestEvaluation:
c1d = np.array([1., 2., 3.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
x = np.random.random((3, 5))*2 - 1
y = poly.polyval(x, [1., 2., 3.])
def test_polyval(self):
assert_equal(poly.polyval([], [1]).size, 0)
x = np.linspace(-1, 1)
y = [x**i for i in range(5)]
for i in range(5):
tgt = y[i]
res = poly.polyval(x, [0]*i + [1])
assert_almost_equal(res, tgt)
tgt = x*(x**2 - 1)
res = poly.polyval(x, [0, -1, 0, 1])
assert_almost_equal(res, tgt)
for i in range(3):
dims = [2]*i
x = np.zeros(dims)
assert_equal(poly.polyval(x, [1]).shape, dims)
assert_equal(poly.polyval(x, [1, 0]).shape, dims)
assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims)
mask = [False, True, False]
mx = np.ma.array([1, 2, 3], mask=mask)
res = np.polyval([7, 5, 3], mx)
assert_array_equal(res.mask, mask)
class C(np.ndarray):
pass
cx = np.array([1, 2, 3]).view(C)
assert_equal(type(np.polyval([2, 3, 4], cx)), C)
def test_polyvalfromroots(self):
assert_raises(ValueError, poly.polyvalfromroots,
[1], [1], tensor=False)
assert_equal(poly.polyvalfromroots([], [1]).size, 0)
assert_(poly.polyvalfromroots([], [1]).shape == (0,))
assert_equal(poly.polyvalfromroots([], [[1] * 5]).size, 0)
assert_(poly.polyvalfromroots([], [[1] * 5]).shape == (5, 0))
assert_equal(poly.polyvalfromroots(1, 1), 0)
assert_(poly.polyvalfromroots(1, np.ones((3, 3))).shape == (3,))
x = np.linspace(-1, 1)
y = [x**i for i in range(5)]
for i in range(1, 5):
tgt = y[i]
res = poly.polyvalfromroots(x, [0]*i)
assert_almost_equal(res, tgt)
tgt = x*(x - 1)*(x + 1)
res = poly.polyvalfromroots(x, [-1, 0, 1])
assert_almost_equal(res, tgt)
for i in range(3):
dims = [2]*i
x = np.zeros(dims)
assert_equal(poly.polyvalfromroots(x, [1]).shape, dims)
assert_equal(poly.polyvalfromroots(x, [1, 0]).shape, dims)
assert_equal(poly.polyvalfromroots(x, [1, 0, 0]).shape, dims)
ptest = [15, 2, -16, -2, 1]
r = poly.polyroots(ptest)
x = np.linspace(-1, 1)
assert_almost_equal(poly.polyval(x, ptest),
poly.polyvalfromroots(x, r))
rshape = (3, 5)
x = np.arange(-3, 2)
r = np.random.randint(-5, 5, size=rshape)
res = poly.polyvalfromroots(x, r, tensor=False)
tgt = np.empty(r.shape[1:])
for ii in range(tgt.size):
tgt[ii] = poly.polyvalfromroots(x[ii], r[:, ii])
assert_equal(res, tgt)
x = np.vstack([x, 2*x])
res = poly.polyvalfromroots(x, r, tensor=True)
tgt = np.empty(r.shape[1:] + x.shape)
for ii in range(r.shape[1]):
for jj in range(x.shape[0]):
tgt[ii, jj, :] = poly.polyvalfromroots(x[jj], r[:, ii])
assert_equal(res, tgt)
def test_polyval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
assert_raises_regex(ValueError, 'incompatible',
poly.polyval2d, x1, x2[:2], self.c2d)
tgt = y1*y2
res = poly.polyval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = poly.polyval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_polyval3d(self):
x1, x2, x3 = self.x
assert_raises_regex(ValueError, 'incompatible',
poly.polyval3d, x1, x2, x3[:2], self.c3d)
tgt = y1 * y2 * y3
res = poly.polyval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = poly.polyval3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3))
def test_polygrid2d(self):
x1, x2, x3 = self.x
tgt = np.einsum('i,j->ij', y1, y2)
res = poly.polygrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = poly.polygrid2d(z, z, self.c2d)
assert_(res.shape == (2, 3)*2)
def test_polygrid3d(self):
x1, x2, x3 = self.x
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = poly.polygrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
z = np.ones((2, 3))
res = poly.polygrid3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3)*3)
class TestIntegral:
def test_polyint_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([poly.polyint(c) for c in c2d.T]).T
res = poly.polyint(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([poly.polyint(c) for c in c2d])
res = poly.polyint(c2d, axis=1)
assert_almost_equal(res, tgt)
tgt = np.vstack([poly.polyint(c, k=3) for c in c2d])
res = poly.polyint(c2d, k=3, axis=1)
assert_almost_equal(res, tgt)
class TestDerivative:
def test_polyder(self):
assert_raises(TypeError, poly.polyder, [0], .5)
assert_raises(ValueError, poly.polyder, [0], -1)
for i in range(5):
tgt = [0]*i + [1]
res = poly.polyder(tgt, m=0)
assert_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = poly.polyder(poly.polyint(tgt, m=j), m=j)
assert_almost_equal(trim(res), trim(tgt))
for i in range(5):
for j in range(2, 5):
tgt = [0]*i + [1]
res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5)
assert_almost_equal(trim(res), trim(tgt))
def test_polyder_axis(self):
c2d = np.random.random((3, 4))
tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T
res = poly.polyder(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([poly.polyder(c) for c in c2d])
res = poly.polyder(c2d, axis=1)
assert_almost_equal(res, tgt)
class TestVander:
x = np.random.random((3, 5))*2 - 1
def test_polyvander(self):
x = np.arange(3)
v = poly.polyvander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], poly.polyval(x, coef))
x = np.array([[1, 2], [3, 4], [5, 6]])
v = poly.polyvander(x, 3)
assert_(v.shape == (3, 2, 4))
for i in range(4):
coef = [0]*i + [1]
assert_almost_equal(v[..., i], poly.polyval(x, coef))
def test_polyvander2d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3))
van = poly.polyvander2d(x1, x2, [1, 2])
tgt = poly.polyval2d(x1, x2, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = poly.polyvander2d([x1], [x2], [1, 2])
assert_(van.shape == (1, 5, 6))
def test_polyvander3d(self):
x1, x2, x3 = self.x
c = np.random.random((2, 3, 4))
van = poly.polyvander3d(x1, x2, x3, [1, 2, 3])
tgt = poly.polyval3d(x1, x2, x3, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
van = poly.polyvander3d([x1], [x2], [x3], [1, 2, 3])
assert_(van.shape == (1, 5, 24))
def test_polyvandernegdeg(self):
x = np.arange(3)
assert_raises(ValueError, poly.polyvander, x, -1)
class TestCompanion:
def test_raises(self):
assert_raises(ValueError, poly.polycompanion, [])
assert_raises(ValueError, poly.polycompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0]*i + [1]
assert_(poly.polycompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(poly.polycompanion([1, 2])[0, 0] == -.5)
class TestMisc:
def test_polyfromroots(self):
res = poly.polyfromroots([])
assert_almost_equal(trim(res), [1])
for i in range(1, 5):
roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
tgt = Tlist[i]
res = poly.polyfromroots(roots)*2**(i-1)
assert_almost_equal(trim(res), trim(tgt))
def test_polyroots(self):
assert_almost_equal(poly.polyroots([1]), [])
assert_almost_equal(poly.polyroots([1, 2]), [-.5])
for i in range(2, 5):
tgt = np.linspace(-1, 1, i)
res = poly.polyroots(poly.polyfromroots(tgt))
assert_almost_equal(trim(res), trim(tgt))
def f(x):
return x*(x - 1)*(x - 2)
def f2(x):
return x**4 + x**2 + 1
assert_raises(ValueError, poly.polyfit, [1], [1], -1)
assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
assert_raises(TypeError, poly.polyfit, [], [1], 0)
assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])
assert_raises(ValueError, poly.polyfit, [1], [1], [-1,])
assert_raises(ValueError, poly.polyfit, [1], [1], [2, -1, 6])
assert_raises(TypeError, poly.polyfit, [1], [1], [])
x = np.linspace(0, 2)
y = f(x)
coef3 = poly.polyfit(x, y, 3)
assert_equal(len(coef3), 4)
assert_almost_equal(poly.polyval(x, coef3), y)
coef3 = poly.polyfit(x, y, [0, 1, 2, 3])
assert_equal(len(coef3), 4)
assert_almost_equal(poly.polyval(x, coef3), y)
coef4 = poly.polyfit(x, y, 4)
assert_equal(len(coef4), 5)
assert_almost_equal(poly.polyval(x, coef4), y)
coef4 = poly.polyfit(x, y, [0, 1, 2, 3, 4])
assert_equal(len(coef4), 5)
assert_almost_equal(poly.polyval(x, coef4), y)
coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
coef2d = poly.polyfit(x, np.array([y, y]).T, [0, 1, 2, 3])
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
w = np.zeros_like(x)
yw = y.copy()
w[1::2] = 1
yw[0::2] = 0
wcoef3 = poly.polyfit(x, yw, 3, w=w)
assert_almost_equal(wcoef3, coef3)
wcoef3 = poly.polyfit(x, yw, [0, 1, 2, 3], w=w)
assert_almost_equal(wcoef3, coef3)
wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
x = [1, 1j, -1, -1j]
assert_almost_equal(poly.polyfit(x, x, 1), [0, 1])
assert_almost_equal(poly.polyfit(x, x, [0, 1]), [0, 1])
x = np.linspace(-1, 1)
y = f2(x)
coef1 = poly.polyfit(x, y, 4)
assert_almost_equal(poly.polyval(x, coef1), y)
coef2 = poly.polyfit(x, y, [0, 2, 4])
assert_almost_equal(poly.polyval(x, coef2), y)
assert_almost_equal(coef1, coef2)
def test_polytrim(self):
coef = [2, -1, 1, 0]
assert_raises(ValueError, poly.polytrim, coef, -1)
assert_equal(poly.polytrim(coef), coef[:-1])
assert_equal(poly.polytrim(coef, 1), coef[:-3])
assert_equal(poly.polytrim(coef, 2), [0])
def test_polyline(self):
assert_equal(poly.polyline(3, 4), [3, 4])
def test_polyline_zero(self):
assert_equal(poly.polyline(3, 0), [3])
.\numpy\numpy\polynomial\tests\test_polyutils.py
"""Tests for polyutils module.
"""
import numpy as np
import numpy.polynomial.polyutils as pu
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_,
)
class TestMisc:
def test_trimseq(self):
tgt = [1]
for num_trailing_zeros in range(5):
res = pu.trimseq([1] + [0] * num_trailing_zeros)
assert_equal(res, tgt)
def test_trimseq_empty_input(self):
for empty_seq in [[], np.array([], dtype=np.int32)]:
assert_equal(pu.trimseq(empty_seq), empty_seq)
def test_as_series(self):
assert_raises(ValueError, pu.as_series, [[]])
assert_raises(ValueError, pu.as_series, [[[1, 2]]])
assert_raises(ValueError, pu.as_series, [[1], ['a']])
types = ['i', 'd', 'O']
for i in range(len(types)):
for j in range(i):
ci = np.ones(1, types[i])
cj = np.ones(1, types[j])
[resi, resj] = pu.as_series([ci, cj])
assert_(resi.dtype.char == resj.dtype.char)
assert_(resj.dtype.char == types[i])
def test_trimcoef(self):
coef = [2, -1, 1, 0]
assert_raises(ValueError, pu.trimcoef, coef, -1)
assert_equal(pu.trimcoef(coef), coef[:-1])
assert_equal(pu.trimcoef(coef, 1), coef[:-3])
assert_equal(pu.trimcoef(coef, 2), [0])
def test_vander_nd_exception(self):
assert_raises(ValueError, pu._vander_nd, (), (1, 2, 3), [90])
assert_raises(ValueError, pu._vander_nd, (), (), [90.65])
assert_raises(ValueError, pu._vander_nd, (), (), [])
def test_div_zerodiv(self):
assert_raises(ZeroDivisionError, pu._div, pu._div, (1, 2, 3), [0])
def test_pow_too_large(self):
assert_raises(ValueError, pu._pow, (), [1, 2, 3], 5, 4)
class TestDomain:
def test_getdomain(self):
x = [1, 10, 3, -1]
tgt = [-1, 10]
res = pu.getdomain(x)
assert_almost_equal(res, tgt)
x = [1 + 1j, 1 - 1j, 0, 2]
tgt = [-1j, 2 + 1j]
res = pu.getdomain(x)
assert_almost_equal(res, tgt)
def test_mapdomain(self):
dom1 = [0, 4]
dom2 = [1, 3]
tgt = dom2
res = pu.mapdomain(dom1, dom1, dom2)
assert_almost_equal(res, tgt)
dom1 = [0 - 1j, 2 + 1j]
dom2 = [-2, 2]
tgt = dom2
x = dom1
res = pu.mapdomain(x, dom1, dom2)
assert_almost_equal(res, tgt)
dom1 = [0, 4]
dom2 = [1, 3]
tgt = np.array([dom2, dom2])
x = np.array([dom1, dom1])
res = pu.mapdomain(x, dom1, dom2)
assert_almost_equal(res, tgt)
class MyNDArray(np.ndarray):
pass
dom1 = [0, 4]
dom2 = [1, 3]
x = np.array([dom1, dom1]).view(MyNDArray)
res = pu.mapdomain(x, dom1, dom2)
assert_(isinstance(res, MyNDArray))
def test_mapparms(self):
dom1 = [0, 4]
dom2 = [1, 3]
tgt = [1, .5]
res = pu.mapparms(dom1, dom2)
assert_almost_equal(res, tgt)
dom1 = [0 - 1j, 2 + 1j]
dom2 = [-2, 2]
tgt = [-1 + 1j, 1 - 1j]
res = pu.mapparms(dom1, dom2)
assert_almost_equal(res, tgt)
.\numpy\numpy\polynomial\tests\test_printing.py
from math import nan, inf
import pytest
from numpy._core import array, arange, printoptions
import numpy.polynomial as poly
from numpy.testing import assert_equal, assert_
from fractions import Fraction
from decimal import Decimal
class TestStrUnicodeSuperSubscripts:
@pytest.fixture(scope='class', autouse=True)
def use_unicode(self):
poly.set_default_printstyle('unicode')
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"),
([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"),
(arange(12), ("0.0 + 1.0·x + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "
"6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "
"11.0·x¹¹")),
))
def test_polynomial_str(self, inp, tgt):
p = poly.Polynomial(inp)
res = str(p)
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"),
(arange(12), ("0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + "
"5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + "
"9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)")),
))
def test_chebyshev_str(self, inp, tgt):
res = str(poly.Chebyshev(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"),
(arange(12), ("0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + "
"5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + "
"9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)")),
))
def test_legendre_str(self, inp, tgt):
res = str(poly.Legendre(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"),
(arange(12), ("0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + "
"5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + "
"9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)")),
))
def test_hermite_str(self, inp, tgt):
res = str(poly.Hermite(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"),
(arange(12), ("0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + "
"4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + "
"8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n"
"11.0·He₁₁(x)")),
))
def test_hermiteE_str(self, inp, tgt):
res = str(poly.HermiteE(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"),
(arange(12), ("0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + "
"5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + "
"9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)")),
))
def test_laguerre_str(self, inp, tgt):
res = str(poly.Laguerre(inp))
assert_equal(res, tgt)
def test_polynomial_str_domains(self):
res = str(poly.Polynomial([0, 1]))
tgt = '0.0 + 1.0·x'
assert_equal(res, tgt)
res = str(poly.Polynomial([0, 1], domain=[1, 2]))
tgt = '0.0 + 1.0·(-3.0 + 2.0x)'
assert_equal(res, tgt)
class TestStrAscii:
@pytest.fixture(scope='class', autouse=True)
def use_ascii(self):
poly.set_default_printstyle('ascii')
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 x + 3.0 x**2"),
([-1, 0, 3, -1], "-1.0 + 0.0 x + 3.0 x**2 - 1.0 x**3"),
(arange(12), ("0.0 + 1.0 x + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + "
"5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + "
"9.0 x**9 + 10.0 x**10 + 11.0 x**11")),
))
def test_polynomial_str(self, inp, tgt):
res = str(poly.Polynomial(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"),
(arange(12), ("0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + "
"4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + "
"8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n"
"11.0 T_11(x)")),
))
def test_chebyshev_str(self, inp, tgt):
res = str(poly.Chebyshev(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"),
(arange(12), ("0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + "
"4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + "
"8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n"
"11.0 P_11(x)")),
))
def test_legendre_str(self, inp, tgt):
res = str(poly.Legendre(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"),
(arange(12), ("0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + "
"4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + "
"8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n"
"11.0 H_11(x)")),
))
def test_hermite_str(self, inp, tgt):
res = str(poly.Hermite(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"),
(arange(12), ("0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + "
"4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + "
"7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n"
"10.0 He_10(x) + 11.0 He_11(x)")),
))
def test_hermiteE_str(self, inp, tgt):
res = str(poly.HermiteE(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"),
(arange(12), ("0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + "
"4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + "
"8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n"
"11.0 L_11(x)")),
))
def test_laguerre_str(self, inp, tgt):
res = str(poly.Laguerre(inp))
assert_equal(res, tgt)
def test_polynomial_str_domains(self):
res = str(poly.Polynomial([0, 1]))
tgt = '0.0 + 1.0 x'
assert_equal(res, tgt)
res = str(poly.Polynomial([0, 1], domain=[1, 2]))
tgt = '0.0 + 1.0 (-3.0 + 2.0x)'
assert_equal(res, tgt)
class TestLinebreaking:
@pytest.fixture(scope='class', autouse=True)
def use_ascii(self):
poly.set_default_printstyle('ascii')
def test_single_line_one_less(self):
p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 123])
assert_equal(len(str(p)), 74)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.0 x**3 + 123.0 x**4'
))
def test_num_chars_is_linewidth(self):
p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 1234])
assert_equal(len(str(p)), 75)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.0 x**3 +\n1234.0 x**4'
))
def test_first_linebreak_multiline_one_less_than_linewidth(self):
p = poly.Polynomial(
[12345678, 12345678, 12345678, 12345678, 1, 12345678]
)
assert_equal(len(str(p).split('\n')[0]), 74)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.0 x**3 + 1.0 x**4 +\n12345678.0 x**5'
))
def test_first_linebreak_multiline_on_linewidth(self):
p = poly.Polynomial(
[12345678, 12345678, 12345678, 12345678.12, 1, 12345678]
)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.12 x**3 +\n1.0 x**4 + 12345678.0 x**5'
))
@pytest.mark.parametrize(('lw', 'tgt'), (
(75, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
'500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
'900.0 x**9')),
(45, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 +\n40000.0 x**4 + '
'500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 +\n'
'900.0 x**9')),
(132, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
'500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
'900.0 x**9')),
))
def test_linewidth_printoption(self, lw, tgt):
p = poly.Polynomial(
[0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900]
)
with printoptions(linewidth=lw):
assert_equal(str(p), tgt)
for line in str(p).split('\n'):
assert_(len(line) < lw)
def test_set_default_printoptions():
p = poly.Polynomial([1, 2, 3])
c = poly.Chebyshev([1, 2, 3])
poly.set_default_printstyle('ascii')
assert_equal(str(p), "1.0 + 2.0 x + 3.0 x**2")
assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")
poly.set_default_printstyle('unicode')
assert_equal(str(p), "1.0 + 2.0·x + 3.0·x²")
assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")
with pytest.raises(ValueError):
poly.set_default_printstyle('invalid_input')
def test_complex_coefficients():
"""Test both numpy and built-in complex."""
coefs = [0+1j, 1+1j, -2+2j, 3+0j]
p1 = poly.Polynomial(coefs)
p2 = poly.Polynomial(array(coefs, dtype=object))
poly.set_default_printstyle('unicode')
assert_equal(str(p1), "1j + (1+1j)·x - (2-2j)·x² + (3+0j)·x³")
assert_equal(str(p2), "1j + (1+1j)·x + (-2+2j)·x² + (3+0j)·x³")
poly.set_default_printstyle('ascii')
assert_equal(str(p1), "1j + (1+1j) x - (2-2j) x**2 + (3+0j) x**3")
assert_equal(str(p2), "1j + (1+1j) x + (-2+2j) x**2 + (3+0j) x**3")
@pytest.mark.parametrize(('coefs', 'tgt'), (
(array([Fraction(1, 2), Fraction(3, 4)], dtype=object), (
"1/2 + 3/4·x"
)),
(array([1, 2, Fraction(5, 7)], dtype=object), (
"1 + 2·x + 5/7·x²"
)),
(array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object), (
"1.00 + 2.2·x + 3·x²"
)),
))
def test_numeric_object_coefficients(coefs, tgt):
p = poly.Polynomial(coefs)
poly.set_default_printstyle('unicode')
assert_equal(str(p), tgt)
@pytest.mark.parametrize(('coefs', 'tgt'), (
(array([1, 2, 'f'], dtype=object), '1 + 2·x + f·x²'),
(array([1, 2, [3, 4]], dtype=object), '1 + 2·x + [3, 4]·x²'),
))
def test_nonnumeric_object_coefficients(coefs, tgt):
"""
Test coef fallback for object arrays of non-numeric coefficients.
"""
p = poly.Polynomial(coefs)
poly.set_default_printstyle('unicode')
assert_equal(str(p), tgt)
class TestFormat:
def test_format_unicode(self):
poly.set_default_printstyle('ascii')
p = poly.Polynomial([1, 2, 0, -1])
assert_equal(format(p, 'unicode'), "1.0 + 2.0·x + 0.0·x² - 1.0·x³")
def test_format_ascii(self):
poly.set_default_printstyle('unicode')
p = poly.Polynomial([1, 2, 0, -1])
assert_equal(
format(p, 'ascii'), "1.0 + 2.0 x + 0.0 x**2 - 1.0 x**3"
)
def test_empty_formatstr(self):
poly.set_default_printstyle('ascii')
p = poly.Polynomial([1, 2, 3])
assert_equal(format(p), "1.0 + 2.0 x + 3.0 x**2")
assert_equal(f"{p}", "1.0 + 2.0 x + 3.0 x**2")
def test_bad_formatstr(self):
p = poly.Polynomial([1, 2, 0, -1])
with pytest.raises(ValueError):
format(p, '.2f')
@pytest.mark.parametrize(('poly', 'tgt'), (
(poly.Polynomial, '1.0 + 2.0·z + 3.0·z²'),
(poly.Chebyshev, '1.0 + 2.0·T₁(z) + 3.0·T₂(z)'),
(poly.Hermite, '1.0 + 2.0·H₁(z) + 3.0·H₂(z)'),
(poly.HermiteE, '1.0 + 2.0·He₁(z) + 3.0·He₂(z)'),
(poly.Laguerre, '1.0 + 2.0·L₁(z) + 3.0·L₂(z)'),
(poly.Legendre, '1.0 + 2.0·P₁(z) + 3.0·P₂(z)'),
))
def test_symbol(poly, tgt):
p = poly([1, 2, 3], symbol='z')
assert_equal(f"{p:unicode}", tgt)
class TestRepr:
def test_polynomial_repr(self):
res = repr(poly.Polynomial([0, 1]))
tgt = (
"Polynomial([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_chebyshev_repr(self):
res = repr(poly.Chebyshev([0, 1]))
tgt = (
"Chebyshev([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_legendre_repr(self):
res = repr(poly.Legendre([0, 1]))
tgt = (
"Legendre([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_hermite_repr(self):
res = repr(poly.Hermite([0, 1]))
tgt = (
"Hermite([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_hermiteE_repr(self):
res = repr(poly.HermiteE([0, 1]))
tgt = (
"HermiteE([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_laguerre_repr(self):
res = repr(poly.Laguerre([0, 1]))
tgt = (
"Laguerre([0., 1.], domain=[0., 1.], window=[0., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
class TestLatexRepr:
"""Test the latex repr used by Jupyter"""
@staticmethod
def as_latex(obj):
obj._repr_latex_scalar = lambda x, parens=False: str(x)
try:
return obj._repr_latex_()
finally:
del obj._repr_latex_scalar
def test_simple_polynomial(self):
p = poly.Polynomial([1, 2, 3])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,x + 3.0\,x^{2}$')
p = poly.Polynomial([1, 2, 3], domain=[-2, 0])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,\left(1.0 + x\right) + 3.0\,\left(1.0 + x\right)^{2}$')
p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,\left(2.0x\right) + 3.0\,\left(2.0x\right)^{2}$')
p = poly.Polynomial([1, 2, 3], domain=[-1, 0])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,\left(1.0 + 2.0x\right) + 3.0\,\left(1.0 + 2.0x\right)^{2}$')
def test_basis_func(self):
p = poly.Chebyshev([1, 2, 3])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0\,{T}_{0}(x) + 2.0\,{T}_{1}(x) + 3.0\,{T}_{2}(x)$')
p = poly.Chebyshev([1, 2, 3], domain=[-1, 0])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0\,{T}_{0}(1.0 + 2.0x) + 2.0\,{T}_{1}(1.0 + 2.0x) + 3.0\,{T}_{2}(1.0 + 2.0x)$')
def test_multichar_basis_func(self):
p = poly.HermiteE([1, 2, 3])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0\,{He}_{0}(x) + 2.0\,{He}_{1}(x) + 3.0\,{He}_{2}(x)$')
def test_symbol_basic(self):
p = poly.Polynomial([1, 2, 3], symbol='z')
assert_equal(self.as_latex(p),
r'$z \mapsto 1.0 + 2.0\,z + 3.0\,z^{2}$')
p = poly.Polynomial([1, 2, 3], domain=[-2, 0], symbol='z')
assert_equal(
self.as_latex(p),
(
r'$z \mapsto 1.0 + 2.0\,\left(1.0 + z\right) + 3.0\,'
r'\left(1.0 + z\right)^{2}$'
),
)
p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5], symbol='z')
assert_equal(
self.as_latex(p),
(
r'$z \mapsto 1.0 + 2.0\,\left(2.0z\right) + 3.0\,'
r'\left(2.0z\right)^{2}$'
),
)
p = poly.Polynomial([1, 2, 3], domain=[-1, 0], symbol='z')
assert_equal(
self.as_latex(p),
(
r'$z \mapsto 1.0 + 2.0\,\left(1.0 + 2.0z\right) + 3.0\,'
r'\left(1.0 + 2.0z\right)^{2}$'
),
)
def test_numeric_object_coefficients(self):
coefs = array([Fraction(1, 2), Fraction(1)])
p = poly.Polynomial(coefs)
assert_equal(self.as_latex(p), '$x \\mapsto 1/2 + 1\\,x$')
SWITCH_TO_EXP = (
'1.0 + (1.0e-01) x + (1.0e-02) x**2',
'1.2 + (1.2e-01) x + (1.2e-02) x**2',
'1.23 + 0.12 x + (1.23e-02) x**2 + (1.23e-03) x**3',
'1.235 + 0.123 x + (1.235e-02) x**2 + (1.235e-03) x**3',
'1.2346 + 0.1235 x + 0.0123 x**2 + (1.2346e-03) x**3 + (1.2346e-04) x**4',
'1.23457 + 0.12346 x + 0.01235 x**2 + (1.23457e-03) x**3 + (1.23457e-04) x**4',
'1.234568 + 0.123457 x + 0.012346 x**2 + 0.001235 x**3 + (1.234568e-04) x**4 + (1.234568e-05) x**5',
'1.2345679 + 0.1234568 x + 0.0123457 x**2 + 0.0012346 x**3 + (1.2345679e-04) x**4 + (1.2345679e-05) x**5'
)
class TestPrintOptions:
"""
测试通过printoptions正确配置输出选项。
当值过小或过大时,自动启用指数表示法。
"""
@pytest.fixture(scope='class', autouse=True)
def use_ascii(self):
poly.set_default_printstyle('ascii')
def test_str(self):
p = poly.Polynomial([1/2, 1/7, 1/7*10**8, 1/7*10**9])
assert_equal(str(p), '0.5 + 0.14285714 x + 14285714.28571429 x**2 '
'+ (1.42857143e+08) x**3')
with printoptions(precision=3):
assert_equal(str(p), '0.5 + 0.143 x + 14285714.286 x**2 '
'+ (1.429e+08) x**3')
def test_latex(self):
p = poly.Polynomial([1/2, 1/7, 1/7*10**8, 1/7*10**9])
assert_equal(p._repr_latex_(),
r'$x \mapsto \text{0.5} + \text{0.14285714}\,x + '
r'\text{14285714.28571429}\,x^{2} + '
r'\text{(1.42857143e+08)}\,x^{3}$')
with printoptions(precision=3):
assert_equal(p._repr_latex_(),
r'$x \mapsto \text{0.5} + \text{0.143}\,x + '
r'\text{14285714.286}\,x^{2} + \text{(1.429e+08)}\,x^{3}$')
def test_fixed(self):
p = poly.Polynomial([1/2])
assert_equal(str(p), '0.5')
with printoptions(floatmode='fixed'):
assert_equal(str(p), '0.50000000')
with printoptions(floatmode='fixed', precision=4):
assert_equal(str(p), '0.5000')
def test_switch_to_exp(self):
for i, s in enumerate(SWITCH_TO_EXP):
with printoptions(precision=i):
p = poly.Polynomial([1.23456789*10**-i
for i in range(i//2+3)])
assert str(p).replace('\n', ' ') == s
def test_non_finite(self):
p = poly.Polynomial([nan, inf])
assert str(p) == 'nan + inf x'
assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$'
with printoptions(nanstr='NAN', infstr='INF'):
assert str(p) == 'NAN + INF x'
assert p._repr_latex_() == \
r'$x \mapsto \text{NAN} + \text{INF}\,x$'
.\numpy\numpy\polynomial\tests\test_symbol.py
"""
Tests related to the ``symbol`` attribute of the ABCPolyBase class.
"""
import pytest
import numpy.polynomial as poly
from numpy._core import array
from numpy.testing import assert_equal, assert_raises, assert_
class TestInit:
"""
Test polynomial creation with symbol kwarg.
"""
c = [1, 2, 3]
def test_default_symbol(self):
p = poly.Polynomial(self.c)
assert_equal(p.symbol, 'x')
@pytest.mark.parametrize(('bad_input', 'exception'), (
('', ValueError),
('3', ValueError),
(None, TypeError),
(1, TypeError),
))
def test_symbol_bad_input(self, bad_input, exception):
with pytest.raises(exception):
p = poly.Polynomial(self.c, symbol=bad_input)
@pytest.mark.parametrize('symbol', (
'x',
'x_1',
'A',
'xyz',
'β',
))
def test_valid_symbols(self, symbol):
"""
Values for symbol that should pass input validation.
"""
p = poly.Polynomial(self.c, symbol=symbol)
assert_equal(p.symbol, symbol)
def test_property(self):
"""
'symbol' attribute is read only.
"""
p = poly.Polynomial(self.c, symbol='x')
with pytest.raises(AttributeError):
p.symbol = 'z'
def test_change_symbol(self):
p = poly.Polynomial(self.c, symbol='y')
pt = poly.Polynomial(p.coef, symbol='t')
assert_equal(pt.symbol, 't')
class TestUnaryOperators:
p = poly.Polynomial([1, 2, 3], symbol='z')
def test_neg(self):
n = -self.p
assert_equal(n.symbol, 'z')
def test_scalarmul(self):
out = self.p * 10
assert_equal(out.symbol, 'z')
def test_rscalarmul(self):
out = 10 * self.p
assert_equal(out.symbol, 'z')
def test_pow(self):
out = self.p ** 3
assert_equal(out.symbol, 'z')
@pytest.mark.parametrize(
'rhs',
(
poly.Polynomial([4, 5, 6], symbol='z'),
array([4, 5, 6]),
),
)
class TestBinaryOperatorsSameSymbol:
"""
Ensure symbol is preserved for numeric operations on polynomials with
the same symbol
"""
p = poly.Polynomial([1, 2, 3], symbol='z')
def test_add(self, rhs):
out = self.p + rhs
assert_equal(out.symbol, 'z')
def test_sub(self, rhs):
out = self.p - rhs
assert_equal(out.symbol, 'z')
def test_polymul(self, rhs):
out = self.p * rhs
assert_equal(out.symbol, 'z')
def test_divmod(self, rhs):
for out in divmod(self.p, rhs):
assert_equal(out.symbol, 'z')
def test_radd(self, rhs):
out = rhs + self.p
assert_equal(out.symbol, 'z')
def test_rsub(self, rhs):
out = rhs - self.p
assert_equal(out.symbol, 'z')
def test_rmul(self, rhs):
out = rhs * self.p
assert_equal(out.symbol, 'z')
def test_rdivmod(self, rhs):
for out in divmod(rhs, self.p):
assert_equal(out.symbol, 'z')
class TestBinaryOperatorsDifferentSymbol:
p = poly.Polynomial([1, 2, 3], symbol='x')
other = poly.Polynomial([4, 5, 6], symbol='y')
ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__)
@pytest.mark.parametrize('f', ops)
def test_binops_fails(self, f):
assert_raises(ValueError, f, self.other)
class TestEquality:
p = poly.Polynomial([1, 2, 3], symbol='x')
def test_eq(self):
other = poly.Polynomial([1, 2, 3], symbol='x')
assert_(self.p == other)
def test_neq(self):
other = poly.Polynomial([1, 2, 3], symbol='y')
assert_(not self.p == other)
class TestExtraMethods:
"""
Test other methods for manipulating/creating polynomial objects.
"""
p = poly.Polynomial([1, 2, 3, 0], symbol='z')
def test_copy(self):
other = self.p.copy()
assert_equal(other.symbol, 'z')
def test_trim(self):
other = self.p.trim()
assert_equal(other.symbol, 'z')
def test_truncate(self):
other = self.p.truncate(2)
assert_equal(other.symbol, 'z')
@pytest.mark.parametrize('kwarg', (
{'domain': [-10, 10]},
{'window': [-10, 10]},
{'kind': poly.Chebyshev},
))
def test_convert(self, kwarg):
other = self.p.convert(**kwarg)
assert_equal(other.symbol, 'z')
def test_integ(self):
other = self.p.integ()
assert_equal(other.symbol, 'z')
def test_deriv(self):
other = self.p.deriv()
assert_equal(other.symbol, 'z')
def test_composition():
p = poly.Polynomial([3, 2, 1], symbol="t")
q = poly.Polynomial([5, 1, 0, -1], symbol="λ_1")
r = p(q)
assert r.symbol == "λ_1"
def test_fit():
x, y = (range(10),)*2
p = poly.Polynomial.fit(x, y, deg=1, symbol='z')
assert_equal(p.symbol, 'z')
def test_froomroots():
roots = [-2, 2]
p = poly.Polynomial.fromroots(roots, symbol='z')
assert_equal(p.symbol, 'z')
def test_identity():
p = poly.Polynomial.identity(domain=[-1, 1], window=[5, 20], symbol='z')
assert_equal(p.symbol, 'z')
def test_basis():
p = poly.Polynomial.basis(3, symbol='z')
assert_equal(p.symbol, 'z')
.\numpy\numpy\polynomial\tests\__init__.py
import json
def process_data(data):
json_data = json.dumps(data)
parsed_data = json.loads(json_data)
return parsed_data
.\numpy\numpy\polynomial\_polybase.py
"""
Abstract base class for the various polynomial Classes.
The ABCPolyBase class provides the methods needed to implement the common API
for the various polynomial classes. It operates as a mixin, but uses the
abc module from the stdlib, hence it is only available for Python >= 2.6.
"""
import os
import abc
import numbers
from typing import Callable
import numpy as np
from . import polyutils as pu
__all__ = ['ABCPolyBase']
class ABCPolyBase(abc.ABC):
"""An abstract base class for immutable series classes.
ABCPolyBase provides the standard Python numerical methods
'+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the
methods listed below.
.. versionadded:: 1.9.0
Parameters
----------
coef : array_like
Series coefficients in order of increasing degree, i.e.,
``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where
``P_i`` is the basis polynomials of degree ``i``.
domain : (2,) array_like, optional
Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
to the interval ``[window[0], window[1]]`` by shifting and scaling.
The default value is the derived class domain.
window : (2,) array_like, optional
Window, see domain for its use. The default value is the
derived class window.
symbol : str, optional
Symbol used to represent the independent variable in string
representations of the polynomial expression, e.g. for printing.
The symbol must be a valid Python identifier. Default value is 'x'.
.. versionadded:: 1.24
Attributes
----------
coef : (N,) ndarray
Series coefficients in order of increasing degree.
domain : (2,) ndarray
Domain that is mapped to window.
window : (2,) ndarray
Window that domain is mapped to.
symbol : str
Symbol representing the independent variable.
Class Attributes
----------------
maxpower : int
Maximum power allowed, i.e., the largest number ``n`` such that
``p(x)**n`` is allowed. This is to limit runaway polynomial size.
domain : (2,) ndarray
Default domain of the class.
window : (2,) ndarray
Default window of the class.
"""
__hash__ = None
__array_ufunc__ = None
maxpower = 100
_superscript_mapping = str.maketrans({
"0": "⁰",
"1": "¹",
"2": "²",
"3": "³",
"4": "⁴",
"5": "⁵",
"6": "⁶",
"7": "⁷",
"8": "⁸",
"9": "⁹"
})
_subscript_mapping = str.maketrans({
"0": "₀",
"1": "₁",
"2": "₂",
"3": "₃",
"4": "₄",
"5": "₅",
"6": "₆",
"7": "₇",
"8": "₈",
"9": "₉"
})
_use_unicode = not os.name == 'nt'
@property
def symbol(self):
return self._symbol
@property
@abc.abstractmethod
def domain(self):
@property
@abc.abstractmethod
def window(self):
@property
@abc.abstractmethod
def basis_name(self):
@staticmethod
@abc.abstractmethod
def _add(c1, c2):
@staticmethod
@abc.abstractmethod
def _sub(c1, c2):
@staticmethod
@abc.abstractmethod
def _mul(c1, c2):
@staticmethod
@abc.abstractmethod
def _div(c1, c2):
@staticmethod
@abc.abstractmethod
def _pow(c, pow, maxpower=None):
@staticmethod
@abc.abstractmethod
def _val(x, c):
@staticmethod
@abc.abstractmethod
def _int(c, m, k, lbnd, scl):
@staticmethod
@abc.abstractmethod
def _der(c, m, scl):
@staticmethod
@abc.abstractmethod
def _fit(x, y, deg, rcond, full):
@staticmethod
@abc.abstractmethod
def _line(off, scl):
@staticmethod
@abc.abstractmethod
def _roots(c):
@staticmethod
@abc.abstractmethod
def _fromroots(r):
def has_samecoef(self, other):
"""Check if coefficients match.
.. versionadded:: 1.6.0
Parameters
----------
other : class instance
The other class must have the ``coef`` attribute.
Returns
-------
bool : boolean
True if the coefficients are the same, False otherwise.
"""
if len(self.coef) != len(other.coef):
return False
elif not np.all(self.coef == other.coef):
return False
else:
return True
def has_samedomain(self, other):
"""Check if domains match.
.. versionadded:: 1.6.0
Parameters
----------
other : class instance
The other class must have the ``domain`` attribute.
Returns
-------
bool : boolean
True if the domains are the same, False otherwise.
"""
return np.all(self.domain == other.domain)
def has_samewindow(self, other):
"""Check if windows match.
.. versionadded:: 1.6.0
Parameters
----------
other : class instance
The other class must have the ``window`` attribute.
Returns
-------
bool : boolean
True if the windows are the same, False otherwise.
"""
return np.all(self.window == other.window)
def has_sametype(self, other):
"""
Check if types match.
.. versionadded:: 1.7.0
Parameters
----------
other : object
Class instance.
Returns
-------
bool : boolean
True if `other` is of the same class as `self`.
"""
return isinstance(other, self.__class__)
def _get_coefficients(self, other):
"""
Interpret `other` as polynomial coefficients.
The `other` argument is checked to see if it is of the same
class as `self` with identical domain and window. If so,
return its coefficients, otherwise return `other`.
.. versionadded:: 1.9.0
Parameters
----------
other : anything
Object to be checked.
Returns
-------
coef
The coefficients of `other` if it is a compatible instance
of ABCPolyBase, otherwise `other`.
Raises
------
TypeError
When `other` is an incompatible instance of ABCPolyBase.
"""
if isinstance(other, ABCPolyBase):
if not isinstance(other, self.__class__):
raise TypeError("Polynomial types differ")
elif not np.all(self.domain == other.domain):
raise TypeError("Domains differ")
elif not np.all(self.window == other.window):
raise TypeError("Windows differ")
elif self.symbol != other.symbol:
raise ValueError("Polynomial symbols differ")
return other.coef
return other
def __init__(self, coef, domain=None, window=None, symbol='x'):
"""
Initialize a polynomial object with coefficients, domain, window, and symbol.
Parameters
----------
coef : array_like
Coefficients of the polynomial.
domain : array_like or None, optional
Domain of the polynomial.
window : array_like or None, optional
Window of the polynomial.
symbol : str, optional
Symbol representing the polynomial variable.
Raises
------
ValueError
If domain or window has incorrect number of elements,
or if symbol is not a valid Python identifier.
TypeError
If symbol is not a string.
"""
[coef] = pu.as_series([coef], trim=False)
self.coef = coef
if domain is not None:
[domain] = pu.as_series([domain], trim=False)
if len(domain) != 2:
raise ValueError("Domain has wrong number of elements.")
self.domain = domain
if window is not None:
[window] = pu.as_series([window], trim=False)
if len(window) != 2:
raise ValueError("Window has wrong number of elements.")
self.window = window
try:
if not symbol.isidentifier():
raise ValueError(
"Symbol string must be a valid Python identifier"
)
except AttributeError:
raise TypeError("Symbol must be a non-empty string")
self._symbol = symbol
def __repr__(self):
coef = repr(self.coef)[6:-1]
domain = repr(self.domain)[6:-1]
window = repr(self.window)[6:-1]
name = self.__class__.__name__
return (f"{name}({coef}, domain={domain}, window={window}, "
f"symbol='{self.symbol}')")
def __format__(self, fmt_str):
if fmt_str == '':
return self.__str__()
if fmt_str not in ('ascii', 'unicode'):
raise ValueError(
f"Unsupported format string '{fmt_str}' passed to "
f"{self.__class__}.__format__. Valid options are "
f"'ascii' and 'unicode'"
)
if fmt_str == 'ascii':
return self._generate_string(self._str_term_ascii)
return self._generate_string(self._str_term_unicode)
def __str__(self):
if self._use_unicode:
return self._generate_string(self._str_term_unicode)
return self._generate_string(self._str_term_ascii)
def _generate_string(self, term_method):
"""
Generate the full string representation of the polynomial, using
``term_method`` to generate each polynomial term.
"""
linewidth = np.get_printoptions().get('linewidth', 75)
if linewidth < 1:
linewidth = 1
out = pu.format_float(self.coef[0])
off, scale = self.mapparms()
scaled_symbol, needs_parens = self._format_term(pu.format_float,
off, scale)
if needs_parens:
scaled_symbol = '(' + scaled_symbol + ')'
for i, coef in enumerate(self.coef[1:]):
out += " "
power = str(i + 1)
try:
if coef >= 0:
next_term = "+ " + pu.format_float(coef, parens=True)
else:
next_term = "- " + pu.format_float(-coef, parens=True)
except TypeError:
next_term = f"+ {coef}"
next_term += term_method(power, scaled_symbol)
line_len = len(out.split('\n')[-1]) + len(next_term)
if i < len(self.coef[1:]) - 1:
line_len += 2
if line_len >= linewidth:
next_term = next_term.replace(" ", "\n", 1)
out += next_term
return out
def _str_term_unicode(cls, i, arg_str):
"""
使用 Unicode 字符表示单个多项式项的字符串形式,包括上标和下标。
"""
if cls.basis_name is None:
raise NotImplementedError(
"Subclasses must define either a basis_name, or override "
"_str_term_unicode(cls, i, arg_str)"
)
返回格式化的多项式项字符串,包括基函数名称和下标的 Unicode 表示
return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"
f"({arg_str})")
@classmethod
def _str_term_ascii(cls, i, arg_str):
"""
使用 ** 和 _ 表示上标和下标,生成单个多项式项的 ASCII 字符串表示。
"""
if cls.basis_name is None:
raise NotImplementedError(
"Subclasses must define either a basis_name, or override "
"_str_term_ascii(cls, i, arg_str)"
)
返回格式化的多项式项字符串,包括基函数名称和下标的 ASCII 表示
return f" {cls.basis_name}_{i}({arg_str})"
@classmethod
def _repr_latex_term(cls, i, arg_str, needs_parens):
"""
生成单个多项式项的 LaTeX 字符串表示。
"""
if cls.basis_name is None:
raise NotImplementedError(
"Subclasses must define either a basis name, or override "
"_repr_latex_term(i, arg_str, needs_parens)")
return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})"
@staticmethod
def _repr_latex_scalar(x, parens=False):
"""
生成 LaTeX 表示的标量值。
TODO: 在这个函数处理指数之前,我们禁用数学格式化。
"""
return r'\text{{{}}}'.format(pu.format_float(x, parens=parens))
def _format_term(self, scalar_format: Callable, off: float, scale: float):
"""
格式化展开中的单个项。
"""
if off == 0 and scale == 1:
term = self.symbol
needs_parens = False
elif scale == 1:
term = f"{scalar_format(off)} + {self.symbol}"
needs_parens = True
elif off == 0:
term = f"{scalar_format(scale)}{self.symbol}"
needs_parens = True
else:
term = (
f"{scalar_format(off)} + "
f"{scalar_format(scale)}{self.symbol}"
)
needs_parens = True
return term, needs_parens
def _repr_latex_(self):
off, scale = self.mapparms()
term, needs_parens = self._format_term(self._repr_latex_scalar,
off, scale)
mute = r"\color{{LightGray}}{{{}}}".format
parts = []
for i, c in enumerate(self.coef):
if i == 0:
coef_str = f"{self._repr_latex_scalar(c)}"
elif not isinstance(c, numbers.Real):
coef_str = f" + ({self._repr_latex_scalar(c)})"
elif c >= 0:
coef_str = f" + {self._repr_latex_scalar(c, parens=True)}"
else:
coef_str = f" - {self._repr_latex_scalar(-c, parens=True)}"
term_str = self._repr_latex_term(i, term, needs_parens)
if term_str == '1':
part = coef_str
else:
part = rf"{coef_str}\,{term_str}"
if c == 0:
part = mute(part)
parts.append(part)
if parts:
body = ''.join(parts)
else:
body = '0'
return rf"${self.symbol} \mapsto {body}$"
def __getstate__(self):
ret = self.__dict__.copy()
ret['coef'] = self.coef.copy()
ret['domain'] = self.domain.copy()
ret['window'] = self.window.copy()
ret['symbol'] = self.symbol
return ret
def __setstate__(self, dict):
self.__dict__ = dict
def __call__(self, arg):
arg = pu.mapdomain(arg, self.domain, self.window)
return self._val(arg, self.coef)
def __iter__(self):
return iter(self.coef)
def __len__(self):
return len(self.coef)
def __neg__(self):
return self.__class__(
-self.coef, self.domain, self.window, self.symbol
)
def __pos__(self):
return self
def __add__(self, other):
othercoef = self._get_coefficients(other)
try:
coef = self._add(self.coef, othercoef)
except Exception:
return NotImplemented
return self.__class__(coef, self.domain, self.window, self.symbol)
def __sub__(self, other):
othercoef = self._get_coefficients(other)
try:
coef = self._sub(self.coef, othercoef)
except Exception:
return NotImplemented
return self.__class__(coef, self.domain, self.window, self.symbol)
def __mul__(self, other):
othercoef = self._get_coefficients(other)
try:
coef = self._mul(self.coef, othercoef)
except Exception:
return NotImplemented
return self.__class__(coef, self.domain, self.window, self.symbol)
def __truediv__(self, other):
if not isinstance(other, numbers.Number) or isinstance(other, bool):
raise TypeError(
f"unsupported types for true division: "
f"'{type(self)}', '{type(other)}'"
)
return self.__floordiv__(other)
def __floordiv__(self, other):
res = self.__divmod__(other)
if res is NotImplemented:
return res
return res[0]
def __mod__(self, other):
res = self.__divmod__(other)
if res is NotImplemented:
return res
return res[1]
def __divmod__(self, other):
othercoef = self._get_coefficients(other)
try:
quo, rem = self._div(self.coef, othercoef)
except ZeroDivisionError:
raise
except Exception:
return NotImplemented
quo = self.__class__(quo, self.domain, self.window, self.symbol)
rem = self.__class__(rem, self.domain, self.window, self.symbol)
return quo, rem
def __pow__(self, other):
coef = self._pow(self.coef, other, maxpower=self.maxpower)
res = self.__class__(coef, self.domain, self.window, self.symbol)
return res
def __radd__(self, other):
try:
coef = self._add(other, self.coef)
except Exception:
return NotImplemented
return self.__class__(coef, self.domain, self.window, self.symbol)
def __rsub__(self, other):
try:
coef = self._sub(other, self.coef)
except Exception:
return NotImplemented
return self.__class__(coef, self.domain, self.window, self.symbol)
def __rmul__(self, other):
try:
coef = self._mul(other, self.coef)
except Exception:
return NotImplemented
return self.__class__(coef, self.domain, self.window, self.symbol)
def __rdiv__(self, other):
return self.__rfloordiv__(other)
def __rtruediv__(self, other):
return NotImplemented
def __rfloordiv__(self, other):
res = self.__rdivmod__(other)
if res is NotImplemented:
return res
return res[0]
def __rmod__(self, other):
res = self.__rdivmod__(other)
if res is NotImplemented:
return res
return res[1]
def __rdivmod__(self, other):
try:
quo, rem = self._div(other, self.coef)
except ZeroDivisionError:
raise
except Exception:
return NotImplemented
quo = self.__class__(quo, self.domain, self.window, self.symbol)
rem = self.__class__(rem, self.domain, self.window, self.symbol)
return quo, rem
def __eq__(self, other):
res = (isinstance(other, self.__class__) and
np.all(self.domain == other.domain) and
np.all(self.window == other.window) and
(self.coef.shape == other.coef.shape) and
np.all(self.coef == other.coef) and
(self.symbol == other.symbol))
return res
def __ne__(self, other):
return not self.__eq__(other)
def copy(self):
"""Return a copy.
Returns
-------
new_series : series
Copy of self.
"""
return self.__class__(self.coef, self.domain, self.window, self.symbol)
def degree(self):
"""The degree of the series.
.. versionadded:: 1.5.0
Returns
-------
degree : int
Degree of the series, one less than the number of coefficients.
Examples
--------
Create a polynomial object for ``1 + 7*x + 4*x**2``:
>>> poly = np.polynomial.Polynomial([1, 7, 4])
>>> print(poly)
1.0 + 7.0·x + 4.0·x²
>>> poly.degree()
2
Note that this method does not check for non-zero coefficients.
You must trim the polynomial to remove any trailing zeroes:
>>> poly = np.polynomial.Polynomial([1, 7, 0])
>>> print(poly)
1.0 + 7.0·x + 0.0·x²
>>> poly.degree()
2
>>> poly.trim().degree()
1
"""
return len(self) - 1
def cutdeg(self, deg):
"""Truncate series to the given degree.
Reduce the degree of the series to `deg` by discarding the
high order terms. If `deg` is greater than the current degree a
copy of the current series is returned. This can be useful in least
squares where the coefficients of the high degree terms may be very
small.
.. versionadded:: 1.5.0
Parameters
----------
deg : non-negative int
The series is reduced to degree `deg` by discarding the high
order terms. The value of `deg` must be a non-negative integer.
Returns
-------
new_series : series
New instance of series with reduced degree.
"""
return self.truncate(deg + 1)
def trim(self, tol=0):
"""Remove trailing coefficients
Remove trailing coefficients until a coefficient is reached whose
absolute value greater than `tol` or the beginning of the series is
reached. If all the coefficients would be removed the series is set
to ``[0]``. A new series instance is returned with the new
coefficients. The current instance remains unchanged.
Parameters
----------
tol : non-negative number.
All trailing coefficients less than `tol` will be removed.
Returns
-------
new_series : series
New instance of series with trimmed coefficients.
"""
coef = pu.trimcoef(self.coef, tol)
return self.__class__(coef, self.domain, self.window, self.symbol)
def truncate(self, size):
"""Truncate series to length `size`.
Reduce the series to length `size` by discarding the high
degree terms. The value of `size` must be a positive integer. This
can be useful in least squares where the coefficients of the
high degree terms may be very small.
Parameters
----------
size : positive int
The series is reduced to length `size` by discarding the high
degree terms. The value of `size` must be a positive integer.
Returns
-------
new_series : series
New instance of series with truncated coefficients.
"""
isize = int(size)
if isize != size or isize < 1:
raise ValueError("size must be a positive integer")
if isize >= len(self.coef):
coef = self.coef
else:
coef = self.coef[:isize]
return self.__class__(coef, self.domain, self.window, self.symbol)
def convert(self, domain=None, kind=None, window=None):
if kind is None:
kind = self.__class__
if domain is None:
domain = kind.domain
if window is None:
window = kind.window
return self(kind.identity(domain, window=window, symbol=self.symbol))
def mapparms(self):
return pu.mapparms(self.domain, self.window)
def integ(self, m=1, k=[], lbnd=None):
"""
Integrate.
Return a series instance that is the definite integral of the
current series.
Parameters
----------
m : non-negative int
The number of integrations to perform.
k : array_like
Integration constants. The first constant is applied to the
first integration, the second to the second, and so on. The
list of values must less than or equal to `m` in length and any
missing values are set to zero.
lbnd : Scalar
The lower bound of the definite integral.
Returns
-------
new_series : series
A new series representing the integral. The domain is the same
as the domain of the integrated series.
"""
off, scl = self.mapparms()
if lbnd is None:
lbnd = 0
else:
lbnd = off + scl * lbnd
coef = self._int(self.coef, m, k, lbnd, 1. / scl)
return self.__class__(coef, self.domain, self.window, self.symbol)
def deriv(self, m=1):
"""
Differentiate.
Return a series instance that is the derivative of the current
series.
Parameters
----------
m : non-negative int
Find the derivative of order `m`.
Returns
-------
new_series : series
A new series representing the derivative. The domain is the same
as the domain of the differentiated series.
"""
off, scl = self.mapparms()
coef = self._der(self.coef, m, scl)
return self.__class__(coef, self.domain, self.window, self.symbol)
def roots(self):
"""
Return the roots of the series polynomial.
Compute the roots for the series. Note that the accuracy of the
roots decreases the further outside the `domain` they lie.
Returns
-------
roots : ndarray
Array containing the roots of the series.
"""
roots = self._roots(self.coef)
return pu.mapdomain(roots, self.window, self.domain)
def linspace(self, n=100, domain=None):
"""Return x, y values at equally spaced points in domain.
Returns the x, y values at `n` linearly spaced points across the
domain. Here y is the value of the polynomial at the points x. By
default the domain is the same as that of the series instance.
This method is intended mostly as a plotting aid.
.. versionadded:: 1.5.0
Parameters
----------
n : int, optional
Number of point pairs to return. The default value is 100.
domain : {None, array_like}, optional
If not None, the specified domain is used instead of that of
the calling instance. It should be of the form ``[beg,end]``.
The default is None which case the class domain is used.
Returns
-------
x, y : ndarray
x is equal to linspace(self.domain[0], self.domain[1], n) and
y is the series evaluated at element of x.
"""
if domain is None:
domain = self.domain
x = np.linspace(domain[0], domain[1], n)
y = self(x)
return x, y
@classmethod
@classmethod
def fromroots(cls, roots, domain=[], window=None, symbol='x'):
"""Return series instance that has the specified roots.
Returns a series representing the product
``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
list of roots.
Parameters
----------
roots : array_like
List of roots.
domain : {[], None, array_like}, optional
Domain for the resulting series. If None the domain is the
interval from the smallest root to the largest. If [] the
domain is the class domain. The default is [].
window : {None, array_like}, optional
Window for the returned series. If None the class window is
used. The default is None.
symbol : str, optional
Symbol representing the independent variable. Default is 'x'.
Returns
-------
new_series : series
Series with the specified roots.
"""
[roots] = pu.as_series([roots], trim=False)
if domain is None:
domain = pu.getdomain(roots)
elif type(domain) is list and len(domain) == 0:
domain = cls.domain
if window is None:
window = cls.window
deg = len(roots)
off, scl = pu.mapparms(domain, window)
rnew = off + scl * roots
coef = cls._fromroots(rnew) / scl**deg
return cls(coef, domain=domain, window=window, symbol=symbol)
@classmethod
def identity(cls, domain=None, window=None, symbol='x'):
"""Identity function.
If ``p`` is the returned series, then ``p(x) == x`` for all
values of x.
Parameters
----------
domain : {None, array_like}, optional
If given, the array must be of the form ``[beg, end]``, where
``beg`` and ``end`` are the endpoints of the domain. If None is
given then the class domain is used. The default is None.
window : {None, array_like}, optional
If given, the resulting array must be if the form
``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
the window. If None is given then the class window is used. The
default is None.
symbol : str, optional
Symbol representing the independent variable. Default is 'x'.
Returns
-------
new_series : series
Series of representing the identity.
"""
if domain is None:
domain = cls.domain
if window is None:
window = cls.window
off, scl = pu.mapparms(window, domain)
coef = cls._line(off, scl)
return cls(coef, domain, window, symbol)
@classmethod
def basis(cls, deg, domain=None, window=None, symbol='x'):
"""Series basis polynomial of degree `deg`.
Returns the series representing the basis polynomial of degree `deg`.
.. versionadded:: 1.7.0
Parameters
----------
deg : int
Degree of the basis polynomial for the series. Must be >= 0.
domain : {None, array_like}, optional
If given, the array must be of the form ``[beg, end]``, where
``beg`` and ``end`` are the endpoints of the domain. If None is
given then the class domain is used. The default is None.
window : {None, array_like}, optional
If given, the resulting array must be if the form
``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
the window. If None is given then the class window is used. The
default is None.
symbol : str, optional
Symbol representing the independent variable. Default is 'x'.
Returns
-------
new_series : series
A series with the coefficient of the `deg` term set to one and
all others zero.
"""
if domain is None:
domain = cls.domain
if window is None:
window = cls.window
ideg = int(deg)
if ideg != deg or ideg < 0:
raise ValueError("deg must be non-negative integer")
return cls([0]*ideg + [1], domain, window, symbol)
def cast(cls, series, domain=None, window=None):
"""Convert series to series of this class.
The `series` is expected to be an instance of some polynomial
series of one of the types supported by by the numpy.polynomial
module, but could be some other class that supports the convert
method.
.. versionadded:: 1.7.0
Parameters
----------
series : series
The series instance to be converted.
domain : {None, array_like}, optional
If given, the array must be of the form ``[beg, end]``, where
``beg`` and ``end`` are the endpoints of the domain. If None is
given then the class domain is used. The default is None.
window : {None, array_like}, optional
If given, the resulting array must be if the form
``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
the window. If None is given then the class window is used. The
default is None.
Returns
-------
new_series : series
A series of the same kind as the calling class and equal to
`series` when evaluated.
See Also
--------
convert : similar instance method
"""
if domain is None:
domain = cls.domain
if window is None:
window = cls.window
return series.convert(domain, cls, window)
.\numpy\numpy\polynomial\_polybase.pyi
import abc
from typing import Any, ClassVar
__all__: list[str]
class ABCPolyBase(abc.ABC):
__hash__: ClassVar[None]
__array_ufunc__: ClassVar[None]
maxpower: ClassVar[int]
coef: Any
@property
def symbol(self) -> str: ...
@property
@abc.abstractmethod
def domain(self): ...
@property
@abc.abstractmethod
def window(self): ...
@property
@abc.abstractmethod
def basis_name(self): ...
def has_samecoef(self, other): ...
def has_samedomain(self, other): ...
def has_samewindow(self, other): ...
def has_sametype(self, other): ...
def __init__(self, coef, domain=..., window=..., symbol: str = ...) -> None: ...
def __format__(self, fmt_str): ...
def __call__(self, arg): ...
def __iter__(self): ...
def __len__(self): ...
def __neg__(self): ...
def __pos__(self): ...
def __add__(self, other): ...
def __sub__(self, other): ...
def __mul__(self, other): ...
def __truediv__(self, other): ...
def __floordiv__(self, other): ...
def __mod__(self, other): ...
def __divmod__(self, other): ...
def __pow__(self, other): ...
def __radd__(self, other): ...
def __rsub__(self, other): ...
def __rmul__(self, other): ...
def __rdiv__(self, other): ...
def __rtruediv__(self, other): ...
def __rfloordiv__(self, other): ...
def __rmod__(self, other): ...
def __rdivmod__(self, other): ...
def __eq__(self, other): ...
def __ne__(self, other): ...
def copy(self): ...
def degree(self): ...
def cutdeg(self, deg): ...
def trim(self, tol=...): ...
def truncate(self, size): ...
def convert(self, domain=..., kind=..., window=...): ...
def mapparms(self): ...
def integ(self, m=..., k = ..., lbnd=...): ...
def deriv(self, m=...): ...
def roots(self): ...
def linspace(self, n=..., domain=...): ...
@classmethod
def fit(cls, x, y, deg, domain=..., rcond=..., full=..., w=..., window=...): ...
@classmethod
def fromroots(cls, roots, domain = ..., window=...): ...
@classmethod
def identity(cls, domain=..., window=...): ...
@classmethod
def basis(cls, deg, domain=..., window=...): ...
@classmethod
def cast(cls, series, domain=..., window=...): ...