test_polynomial.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import numpy as np
  2. from numpy.testing import (
  3. assert_, assert_equal, assert_array_equal, assert_almost_equal,
  4. assert_array_almost_equal, assert_raises, assert_allclose
  5. )
  6. import pytest
  7. # `poly1d` has some support for `bool_` and `timedelta64`,
  8. # but it is limited and they are therefore excluded here
  9. TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["AllFloat"] + "O"
  10. class TestPolynomial:
  11. def test_poly1d_str_and_repr(self):
  12. p = np.poly1d([1., 2, 3])
  13. assert_equal(repr(p), 'poly1d([1., 2., 3.])')
  14. assert_equal(str(p),
  15. ' 2\n'
  16. '1 x + 2 x + 3')
  17. q = np.poly1d([3., 2, 1])
  18. assert_equal(repr(q), 'poly1d([3., 2., 1.])')
  19. assert_equal(str(q),
  20. ' 2\n'
  21. '3 x + 2 x + 1')
  22. r = np.poly1d([1.89999 + 2j, -3j, -5.12345678, 2 + 1j])
  23. assert_equal(str(r),
  24. ' 3 2\n'
  25. '(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)')
  26. assert_equal(str(np.poly1d([-3, -2, -1])),
  27. ' 2\n'
  28. '-3 x - 2 x - 1')
  29. def test_poly1d_resolution(self):
  30. p = np.poly1d([1., 2, 3])
  31. q = np.poly1d([3., 2, 1])
  32. assert_equal(p(0), 3.0)
  33. assert_equal(p(5), 38.0)
  34. assert_equal(q(0), 1.0)
  35. assert_equal(q(5), 86.0)
  36. def test_poly1d_math(self):
  37. # here we use some simple coeffs to make calculations easier
  38. p = np.poly1d([1., 2, 4])
  39. q = np.poly1d([4., 2, 1])
  40. assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75])))
  41. assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.]))
  42. assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.]))
  43. p = np.poly1d([1., 2, 3])
  44. q = np.poly1d([3., 2, 1])
  45. assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.]))
  46. assert_equal(p + q, np.poly1d([4., 4., 4.]))
  47. assert_equal(p - q, np.poly1d([-2., 0., 2.]))
  48. assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.]))
  49. assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.]))
  50. assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.]))
  51. assert_equal(p.deriv(), np.poly1d([2., 2.]))
  52. assert_equal(p.deriv(2), np.poly1d([2.]))
  53. assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])),
  54. (np.poly1d([1., -1.]), np.poly1d([0.])))
  55. @pytest.mark.parametrize("type_code", TYPE_CODES)
  56. def test_poly1d_misc(self, type_code: str) -> None:
  57. dtype = np.dtype(type_code)
  58. ar = np.array([1, 2, 3], dtype=dtype)
  59. p = np.poly1d(ar)
  60. # `__eq__`
  61. assert_equal(np.asarray(p), ar)
  62. assert_equal(np.asarray(p).dtype, dtype)
  63. assert_equal(len(p), 2)
  64. # `__getitem__`
  65. comparison_dct = {-1: 0, 0: 3, 1: 2, 2: 1, 3: 0}
  66. for index, ref in comparison_dct.items():
  67. scalar = p[index]
  68. assert_equal(scalar, ref)
  69. if dtype == np.object_:
  70. assert isinstance(scalar, int)
  71. else:
  72. assert_equal(scalar.dtype, dtype)
  73. def test_poly1d_variable_arg(self):
  74. q = np.poly1d([1., 2, 3], variable='y')
  75. assert_equal(str(q),
  76. ' 2\n'
  77. '1 y + 2 y + 3')
  78. q = np.poly1d([1., 2, 3], variable='lambda')
  79. assert_equal(str(q),
  80. ' 2\n'
  81. '1 lambda + 2 lambda + 3')
  82. def test_poly(self):
  83. assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
  84. [1, -3, -2, 6])
  85. # From matlab docs
  86. A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
  87. assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])
  88. # Should produce real output for perfect conjugates
  89. assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
  90. assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
  91. 1-2j, 1.+3.5j, 1-3.5j])))
  92. assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j])))
  93. assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j])))
  94. assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j])))
  95. assert_(np.isrealobj(np.poly([1j, -1j])))
  96. assert_(np.isrealobj(np.poly([1, -1])))
  97. assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))
  98. np.random.seed(42)
  99. a = np.random.randn(100) + 1j*np.random.randn(100)
  100. assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
  101. def test_roots(self):
  102. assert_array_equal(np.roots([1, 0, 0]), [0, 0])
  103. def test_str_leading_zeros(self):
  104. p = np.poly1d([4, 3, 2, 1])
  105. p[3] = 0
  106. assert_equal(str(p),
  107. " 2\n"
  108. "3 x + 2 x + 1")
  109. p = np.poly1d([1, 2])
  110. p[0] = 0
  111. p[1] = 0
  112. assert_equal(str(p), " \n0")
  113. def test_polyfit(self):
  114. c = np.array([3., 2., 1.])
  115. x = np.linspace(0, 2, 7)
  116. y = np.polyval(c, x)
  117. err = [1, -1, 1, -1, 1, -1, 1]
  118. weights = np.arange(8, 1, -1)**2/7.0
  119. # Check exception when too few points for variance estimate. Note that
  120. # the estimate requires the number of data points to exceed
  121. # degree + 1
  122. assert_raises(ValueError, np.polyfit,
  123. [1], [1], deg=0, cov=True)
  124. # check 1D case
  125. m, cov = np.polyfit(x, y+err, 2, cov=True)
  126. est = [3.8571, 0.2857, 1.619]
  127. assert_almost_equal(est, m, decimal=4)
  128. val0 = [[ 1.4694, -2.9388, 0.8163],
  129. [-2.9388, 6.3673, -2.1224],
  130. [ 0.8163, -2.1224, 1.161 ]]
  131. assert_almost_equal(val0, cov, decimal=4)
  132. m2, cov2 = np.polyfit(x, y+err, 2, w=weights, cov=True)
  133. assert_almost_equal([4.8927, -1.0177, 1.7768], m2, decimal=4)
  134. val = [[ 4.3964, -5.0052, 0.4878],
  135. [-5.0052, 6.8067, -0.9089],
  136. [ 0.4878, -0.9089, 0.3337]]
  137. assert_almost_equal(val, cov2, decimal=4)
  138. m3, cov3 = np.polyfit(x, y+err, 2, w=weights, cov="unscaled")
  139. assert_almost_equal([4.8927, -1.0177, 1.7768], m3, decimal=4)
  140. val = [[ 0.1473, -0.1677, 0.0163],
  141. [-0.1677, 0.228 , -0.0304],
  142. [ 0.0163, -0.0304, 0.0112]]
  143. assert_almost_equal(val, cov3, decimal=4)
  144. # check 2D (n,1) case
  145. y = y[:, np.newaxis]
  146. c = c[:, np.newaxis]
  147. assert_almost_equal(c, np.polyfit(x, y, 2))
  148. # check 2D (n,2) case
  149. yy = np.concatenate((y, y), axis=1)
  150. cc = np.concatenate((c, c), axis=1)
  151. assert_almost_equal(cc, np.polyfit(x, yy, 2))
  152. m, cov = np.polyfit(x, yy + np.array(err)[:, np.newaxis], 2, cov=True)
  153. assert_almost_equal(est, m[:, 0], decimal=4)
  154. assert_almost_equal(est, m[:, 1], decimal=4)
  155. assert_almost_equal(val0, cov[:, :, 0], decimal=4)
  156. assert_almost_equal(val0, cov[:, :, 1], decimal=4)
  157. # check order 1 (deg=0) case, were the analytic results are simple
  158. np.random.seed(123)
  159. y = np.random.normal(size=(4, 10000))
  160. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, deg=0, cov=True)
  161. # Should get sigma_mean = sigma/sqrt(N) = 1./sqrt(4) = 0.5.
  162. assert_allclose(mean.std(), 0.5, atol=0.01)
  163. assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)
  164. # Without scaling, since reduced chi2 is 1, the result should be the same.
  165. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=np.ones(y.shape[0]),
  166. deg=0, cov="unscaled")
  167. assert_allclose(mean.std(), 0.5, atol=0.01)
  168. assert_almost_equal(np.sqrt(cov.mean()), 0.5)
  169. # If we estimate our errors wrong, no change with scaling:
  170. w = np.full(y.shape[0], 1./0.5)
  171. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=w, deg=0, cov=True)
  172. assert_allclose(mean.std(), 0.5, atol=0.01)
  173. assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)
  174. # But if we do not scale, our estimate for the error in the mean will
  175. # differ.
  176. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=w, deg=0, cov="unscaled")
  177. assert_allclose(mean.std(), 0.5, atol=0.01)
  178. assert_almost_equal(np.sqrt(cov.mean()), 0.25)
  179. def test_objects(self):
  180. from decimal import Decimal
  181. p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
  182. p2 = p * Decimal('1.333333333333333')
  183. assert_(p2[1] == Decimal("3.9999999999999990"))
  184. p2 = p.deriv()
  185. assert_(p2[1] == Decimal('8.0'))
  186. p2 = p.integ()
  187. assert_(p2[3] == Decimal("1.333333333333333333333333333"))
  188. assert_(p2[2] == Decimal('1.5'))
  189. assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
  190. p = np.poly([Decimal(1), Decimal(2)])
  191. assert_equal(np.poly([Decimal(1), Decimal(2)]),
  192. [1, Decimal(-3), Decimal(2)])
  193. def test_complex(self):
  194. p = np.poly1d([3j, 2j, 1j])
  195. p2 = p.integ()
  196. assert_((p2.coeffs == [1j, 1j, 1j, 0]).all())
  197. p2 = p.deriv()
  198. assert_((p2.coeffs == [6j, 2j]).all())
  199. def test_integ_coeffs(self):
  200. p = np.poly1d([3, 2, 1])
  201. p2 = p.integ(3, k=[9, 7, 6])
  202. assert_(
  203. (p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all())
  204. def test_zero_dims(self):
  205. try:
  206. np.poly(np.zeros((0, 0)))
  207. except ValueError:
  208. pass
  209. def test_poly_int_overflow(self):
  210. """
  211. Regression test for gh-5096.
  212. """
  213. v = np.arange(1, 21)
  214. assert_almost_equal(np.poly(v), np.poly(np.diag(v)))
  215. def test_zero_poly_dtype(self):
  216. """
  217. Regression test for gh-16354.
  218. """
  219. z = np.array([0, 0, 0])
  220. p = np.poly1d(z.astype(np.int64))
  221. assert_equal(p.coeffs.dtype, np.int64)
  222. p = np.poly1d(z.astype(np.float32))
  223. assert_equal(p.coeffs.dtype, np.float32)
  224. p = np.poly1d(z.astype(np.complex64))
  225. assert_equal(p.coeffs.dtype, np.complex64)
  226. def test_poly_eq(self):
  227. p = np.poly1d([1, 2, 3])
  228. p2 = np.poly1d([1, 2, 4])
  229. assert_equal(p == None, False)
  230. assert_equal(p != None, True)
  231. assert_equal(p == p, True)
  232. assert_equal(p == p2, False)
  233. assert_equal(p != p2, True)
  234. def test_polydiv(self):
  235. b = np.poly1d([2, 6, 6, 1])
  236. a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
  237. q, r = np.polydiv(b, a)
  238. assert_equal(q.coeffs.dtype, np.complex128)
  239. assert_equal(r.coeffs.dtype, np.complex128)
  240. assert_equal(q*a + r, b)
  241. c = [1, 2, 3]
  242. d = np.poly1d([1, 2, 3])
  243. s, t = np.polydiv(c, d)
  244. assert isinstance(s, np.poly1d)
  245. assert isinstance(t, np.poly1d)
  246. u, v = np.polydiv(d, c)
  247. assert isinstance(u, np.poly1d)
  248. assert isinstance(v, np.poly1d)
  249. def test_poly_coeffs_mutable(self):
  250. """ Coefficients should be modifiable """
  251. p = np.poly1d([1, 2, 3])
  252. p.coeffs += 1
  253. assert_equal(p.coeffs, [2, 3, 4])
  254. p.coeffs[2] += 10
  255. assert_equal(p.coeffs, [2, 3, 14])
  256. # this never used to be allowed - let's not add features to deprecated
  257. # APIs
  258. assert_raises(AttributeError, setattr, p, 'coeffs', np.array(1))