diff options
Diffstat (limited to 'numpy/polynomial')
-rw-r--r-- | numpy/polynomial/__init__.py | 2 | ||||
-rw-r--r-- | numpy/polynomial/_polybase.py | 48 | ||||
-rw-r--r-- | numpy/polynomial/chebyshev.py | 108 | ||||
-rw-r--r-- | numpy/polynomial/hermite.py | 94 | ||||
-rw-r--r-- | numpy/polynomial/hermite_e.py | 94 | ||||
-rw-r--r-- | numpy/polynomial/laguerre.py | 94 | ||||
-rw-r--r-- | numpy/polynomial/legendre.py | 91 | ||||
-rw-r--r-- | numpy/polynomial/polynomial.py | 92 | ||||
-rw-r--r-- | numpy/polynomial/polyutils.py | 126 | ||||
-rw-r--r-- | numpy/polynomial/setup.py | 2 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_chebyshev.py | 38 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_classes.py | 11 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_hermite.py | 34 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_hermite_e.py | 34 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_laguerre.py | 34 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_legendre.py | 34 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_polynomial.py | 36 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_polyutils.py | 6 | ||||
-rw-r--r-- | numpy/polynomial/tests/test_printing.py | 6 |
19 files changed, 529 insertions, 455 deletions
diff --git a/numpy/polynomial/__init__.py b/numpy/polynomial/__init__.py index 85cee9ce6..4ff2df57e 100644 --- a/numpy/polynomial/__init__.py +++ b/numpy/polynomial/__init__.py @@ -13,8 +13,6 @@ implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ -from __future__ import division, absolute_import, print_function - from .polynomial import Polynomial from .chebyshev import Chebyshev from .legendre import Legendre diff --git a/numpy/polynomial/_polybase.py b/numpy/polynomial/_polybase.py index bfa030714..53efbb90f 100644 --- a/numpy/polynomial/_polybase.py +++ b/numpy/polynomial/_polybase.py @@ -6,8 +6,6 @@ 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. """ -from __future__ import division, absolute_import, print_function - import abc import numbers @@ -279,18 +277,16 @@ class ABCPolyBase(abc.ABC): self.window = window def __repr__(self): - format = "%s(%s, domain=%s, window=%s)" coef = repr(self.coef)[6:-1] domain = repr(self.domain)[6:-1] window = repr(self.window)[6:-1] name = self.__class__.__name__ - return format % (name, coef, domain, window) + return f"{name}({coef}, domain={domain}, window={window})" def __str__(self): - format = "%s(%s)" coef = str(self.coef) name = self.nickname - return format % (name, coef) + return f"{name}({coef})" @classmethod def _repr_latex_term(cls, i, arg_str, needs_parens): @@ -299,9 +295,7 @@ class ABCPolyBase(abc.ABC): "Subclasses must define either a basis name, or override " "_repr_latex_term(i, arg_str, needs_parens)") # since we always add parens, we don't care if the expression needs them - return "{{{basis}}}_{{{i}}}({arg_str})".format( - basis=cls.basis_name, i=i, arg_str=arg_str - ) + return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})" @staticmethod def _repr_latex_scalar(x): @@ -316,19 +310,15 @@ class ABCPolyBase(abc.ABC): term = 'x' needs_parens = False elif scale == 1: - term = '{} + x'.format( - self._repr_latex_scalar(off) - ) + term = f"{self._repr_latex_scalar(off)} + x" needs_parens = True elif off == 0: - term = '{}x'.format( - self._repr_latex_scalar(scale) - ) + term = f"{self._repr_latex_scalar(scale)}x" needs_parens = True else: - term = '{} + {}x'.format( - self._repr_latex_scalar(off), - self._repr_latex_scalar(scale) + term = ( + f"{self._repr_latex_scalar(off)} + " + f"{self._repr_latex_scalar(scale)}x" ) needs_parens = True @@ -338,20 +328,20 @@ class ABCPolyBase(abc.ABC): for i, c in enumerate(self.coef): # prevent duplication of + and - signs if i == 0: - coef_str = '{}'.format(self._repr_latex_scalar(c)) + coef_str = f"{self._repr_latex_scalar(c)}" elif not isinstance(c, numbers.Real): - coef_str = ' + ({})'.format(self._repr_latex_scalar(c)) + coef_str = f" + ({self._repr_latex_scalar(c)})" elif not np.signbit(c): - coef_str = ' + {}'.format(self._repr_latex_scalar(c)) + coef_str = f" + {self._repr_latex_scalar(c)}" else: - coef_str = ' - {}'.format(self._repr_latex_scalar(-c)) + coef_str = f" - {self._repr_latex_scalar(-c)}" # produce the string for the term term_str = self._repr_latex_term(i, term, needs_parens) if term_str == '1': part = coef_str else: - part = r'{}\,{}'.format(coef_str, term_str) + part = rf"{coef_str}\,{term_str}" if c == 0: part = mute(part) @@ -364,7 +354,7 @@ class ABCPolyBase(abc.ABC): # in case somehow there are no coefficients at all body = '0' - return r'$x \mapsto {}$'.format(body) + return rf"$x \mapsto {body}$" @@ -425,17 +415,15 @@ class ABCPolyBase(abc.ABC): return NotImplemented return self.__class__(coef, self.domain, self.window) - def __div__(self, other): - # this can be removed when python 2 support is dropped. - return self.__floordiv__(other) - def __truediv__(self, other): # there is no true divide if the rhs is not a Number, although it # could return the first n elements of an infinite series. # It is hard to see where n would come from, though. if not isinstance(other, numbers.Number) or isinstance(other, bool): - form = "unsupported types for true division: '%s', '%s'" - raise TypeError(form % (type(self), type(other))) + raise TypeError( + f"unsupported types for true division: " + f"'{type(self)}', '{type(other)}'" + ) return self.__floordiv__(other) def __floordiv__(self, other): diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index 093eb0048..1329ba07d 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -1,5 +1,7 @@ """ -Objects for dealing with Chebyshev series. +==================================================== +Chebyshev Series (:mod:`numpy.polynomial.chebyshev`) +==================================================== This module provides a number of objects (mostly functions) useful for dealing with Chebyshev series, including a `Chebyshev` class that @@ -7,57 +9,75 @@ encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). +Classes +------- + +.. autosummary:: + :toctree: generated/ + + Chebyshev + + Constants --------- -- `chebdomain` -- Chebyshev series default domain, [-1,1]. -- `chebzero` -- (Coefficients of the) Chebyshev series that evaluates - identically to 0. -- `chebone` -- (Coefficients of the) Chebyshev series that evaluates - identically to 1. -- `chebx` -- (Coefficients of the) Chebyshev series for the identity map, - ``f(x) = x``. + +.. autosummary:: + :toctree: generated/ + + chebdomain + chebzero + chebone + chebx Arithmetic ---------- -- `chebadd` -- add two Chebyshev series. -- `chebsub` -- subtract one Chebyshev series from another. -- `chebmulx` -- multiply a Chebyshev series in ``P_i(x)`` by ``x``. -- `chebmul` -- multiply two Chebyshev series. -- `chebdiv` -- divide one Chebyshev series by another. -- `chebpow` -- raise a Chebyshev series to a positive integer power. -- `chebval` -- evaluate a Chebyshev series at given points. -- `chebval2d` -- evaluate a 2D Chebyshev series at given points. -- `chebval3d` -- evaluate a 3D Chebyshev series at given points. -- `chebgrid2d` -- evaluate a 2D Chebyshev series on a Cartesian product. -- `chebgrid3d` -- evaluate a 3D Chebyshev series on a Cartesian product. + +.. autosummary:: + :toctree: generated/ + + chebadd + chebsub + chebmulx + chebmul + chebdiv + chebpow + chebval + chebval2d + chebval3d + chebgrid2d + chebgrid3d Calculus -------- -- `chebder` -- differentiate a Chebyshev series. -- `chebint` -- integrate a Chebyshev series. + +.. autosummary:: + :toctree: generated/ + + chebder + chebint Misc Functions -------------- -- `chebfromroots` -- create a Chebyshev series with specified roots. -- `chebroots` -- find the roots of a Chebyshev series. -- `chebvander` -- Vandermonde-like matrix for Chebyshev polynomials. -- `chebvander2d` -- Vandermonde-like matrix for 2D power series. -- `chebvander3d` -- Vandermonde-like matrix for 3D power series. -- `chebgauss` -- Gauss-Chebyshev quadrature, points and weights. -- `chebweight` -- Chebyshev weight function. -- `chebcompanion` -- symmetrized companion matrix in Chebyshev form. -- `chebfit` -- least-squares fit returning a Chebyshev series. -- `chebpts1` -- Chebyshev points of the first kind. -- `chebpts2` -- Chebyshev points of the second kind. -- `chebtrim` -- trim leading coefficients from a Chebyshev series. -- `chebline` -- Chebyshev series representing given straight line. -- `cheb2poly` -- convert a Chebyshev series to a polynomial. -- `poly2cheb` -- convert a polynomial to a Chebyshev series. -- `chebinterpolate` -- interpolate a function at the Chebyshev points. -Classes -------- -- `Chebyshev` -- A Chebyshev series class. +.. autosummary:: + :toctree: generated/ + + chebfromroots + chebroots + chebvander + chebvander2d + chebvander3d + chebgauss + chebweight + chebcompanion + chebfit + chebpts1 + chebpts2 + chebtrim + chebline + cheb2poly + poly2cheb + chebinterpolate See also -------- @@ -87,9 +107,6 @@ References (preprint: https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) """ -from __future__ import division, absolute_import, print_function - -import warnings import numpy as np import numpy.linalg as la from numpy.core.multiarray import normalize_axis_index @@ -1060,7 +1077,6 @@ def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): if n > 1: tmp[2] = c[1]/4 for j in range(2, n): - t = c[j]/(2*j + 1) # FIXME: t never used tmp[j + 1] = c[j]/(2*(j + 1)) tmp[j - 1] -= c[j]/(2*(j - 1)) tmp[0] += k[i] - chebval(lbnd, tmp) @@ -1468,7 +1484,7 @@ def chebvander2d(x, y, deg): .. versionadded:: 1.7.0 """ - return pu._vander2d(chebvander, x, y, deg) + return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg) def chebvander3d(x, y, z, deg): @@ -1522,7 +1538,7 @@ def chebvander3d(x, y, z, deg): .. versionadded:: 1.7.0 """ - return pu._vander3d(chebvander, x, y, z, deg) + return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg) def chebfit(x, y, deg, rcond=None, full=False, w=None): diff --git a/numpy/polynomial/hermite.py b/numpy/polynomial/hermite.py index 0011fa3b7..44b26f5ee 100644 --- a/numpy/polynomial/hermite.py +++ b/numpy/polynomial/hermite.py @@ -1,5 +1,7 @@ """ -Objects for dealing with Hermite series. +============================================================== +Hermite Series, "Physicists" (:mod:`numpy.polynomial.hermite`) +============================================================== This module provides a number of objects (mostly functions) useful for dealing with Hermite series, including a `Hermite` class that @@ -7,60 +9,72 @@ encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). +Classes +------- +.. autosummary:: + :toctree: generated/ + + Hermite + Constants --------- -- `hermdomain` -- Hermite series default domain, [-1,1]. -- `hermzero` -- Hermite series that evaluates identically to 0. -- `hermone` -- Hermite series that evaluates identically to 1. -- `hermx` -- Hermite series for the identity map, ``f(x) = x``. +.. autosummary:: + :toctree: generated/ + + hermdomain + hermzero + hermone + hermx Arithmetic ---------- -- `hermadd` -- add two Hermite series. -- `hermsub` -- subtract one Hermite series from another. -- `hermmulx` -- multiply a Hermite series in ``P_i(x)`` by ``x``. -- `hermmul` -- multiply two Hermite series. -- `hermdiv` -- divide one Hermite series by another. -- `hermpow` -- raise a Hermite series to a positive integer power. -- `hermval` -- evaluate a Hermite series at given points. -- `hermval2d` -- evaluate a 2D Hermite series at given points. -- `hermval3d` -- evaluate a 3D Hermite series at given points. -- `hermgrid2d` -- evaluate a 2D Hermite series on a Cartesian product. -- `hermgrid3d` -- evaluate a 3D Hermite series on a Cartesian product. +.. autosummary:: + :toctree: generated/ + + hermadd + hermsub + hermmulx + hermmul + hermdiv + hermpow + hermval + hermval2d + hermval3d + hermgrid2d + hermgrid3d Calculus -------- -- `hermder` -- differentiate a Hermite series. -- `hermint` -- integrate a Hermite series. +.. autosummary:: + :toctree: generated/ + + hermder + hermint Misc Functions -------------- -- `hermfromroots` -- create a Hermite series with specified roots. -- `hermroots` -- find the roots of a Hermite series. -- `hermvander` -- Vandermonde-like matrix for Hermite polynomials. -- `hermvander2d` -- Vandermonde-like matrix for 2D power series. -- `hermvander3d` -- Vandermonde-like matrix for 3D power series. -- `hermgauss` -- Gauss-Hermite quadrature, points and weights. -- `hermweight` -- Hermite weight function. -- `hermcompanion` -- symmetrized companion matrix in Hermite form. -- `hermfit` -- least-squares fit returning a Hermite series. -- `hermtrim` -- trim leading coefficients from a Hermite series. -- `hermline` -- Hermite series of given straight line. -- `herm2poly` -- convert a Hermite series to a polynomial. -- `poly2herm` -- convert a polynomial to a Hermite series. - -Classes -------- -- `Hermite` -- A Hermite series class. +.. autosummary:: + :toctree: generated/ + + hermfromroots + hermroots + hermvander + hermvander2d + hermvander3d + hermgauss + hermweight + hermcompanion + hermfit + hermtrim + hermline + herm2poly + poly2herm See also -------- `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - -import warnings import numpy as np import numpy.linalg as la from numpy.core.multiarray import normalize_axis_index @@ -1193,7 +1207,7 @@ def hermvander2d(x, y, deg): .. versionadded:: 1.7.0 """ - return pu._vander2d(hermvander, x, y, deg) + return pu._vander_nd_flat((hermvander, hermvander), (x, y), deg) def hermvander3d(x, y, z, deg): @@ -1247,7 +1261,7 @@ def hermvander3d(x, y, z, deg): .. versionadded:: 1.7.0 """ - return pu._vander3d(hermvander, x, y, z, deg) + return pu._vander_nd_flat((hermvander, hermvander, hermvander), (x, y, z), deg) def hermfit(x, y, deg, rcond=None, full=False, w=None): diff --git a/numpy/polynomial/hermite_e.py b/numpy/polynomial/hermite_e.py index b1cc2d3ab..1a18843ec 100644 --- a/numpy/polynomial/hermite_e.py +++ b/numpy/polynomial/hermite_e.py @@ -1,5 +1,7 @@ """ -Objects for dealing with Hermite_e series. +=================================================================== +HermiteE Series, "Probabilists" (:mod:`numpy.polynomial.hermite_e`) +=================================================================== This module provides a number of objects (mostly functions) useful for dealing with Hermite_e series, including a `HermiteE` class that @@ -7,60 +9,72 @@ encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). +Classes +------- +.. autosummary:: + :toctree: generated/ + + HermiteE + Constants --------- -- `hermedomain` -- Hermite_e series default domain, [-1,1]. -- `hermezero` -- Hermite_e series that evaluates identically to 0. -- `hermeone` -- Hermite_e series that evaluates identically to 1. -- `hermex` -- Hermite_e series for the identity map, ``f(x) = x``. +.. autosummary:: + :toctree: generated/ + + hermedomain + hermezero + hermeone + hermex Arithmetic ---------- -- `hermeadd` -- add two Hermite_e series. -- `hermesub` -- subtract one Hermite_e series from another. -- `hermemulx` -- multiply a Hermite_e series in ``P_i(x)`` by ``x``. -- `hermemul` -- multiply two Hermite_e series. -- `hermediv` -- divide one Hermite_e series by another. -- `hermepow` -- raise a Hermite_e series to a positive integer power. -- `hermeval` -- evaluate a Hermite_e series at given points. -- `hermeval2d` -- evaluate a 2D Hermite_e series at given points. -- `hermeval3d` -- evaluate a 3D Hermite_e series at given points. -- `hermegrid2d` -- evaluate a 2D Hermite_e series on a Cartesian product. -- `hermegrid3d` -- evaluate a 3D Hermite_e series on a Cartesian product. +.. autosummary:: + :toctree: generated/ + + hermeadd + hermesub + hermemulx + hermemul + hermediv + hermepow + hermeval + hermeval2d + hermeval3d + hermegrid2d + hermegrid3d Calculus -------- -- `hermeder` -- differentiate a Hermite_e series. -- `hermeint` -- integrate a Hermite_e series. +.. autosummary:: + :toctree: generated/ + + hermeder + hermeint Misc Functions -------------- -- `hermefromroots` -- create a Hermite_e series with specified roots. -- `hermeroots` -- find the roots of a Hermite_e series. -- `hermevander` -- Vandermonde-like matrix for Hermite_e polynomials. -- `hermevander2d` -- Vandermonde-like matrix for 2D power series. -- `hermevander3d` -- Vandermonde-like matrix for 3D power series. -- `hermegauss` -- Gauss-Hermite_e quadrature, points and weights. -- `hermeweight` -- Hermite_e weight function. -- `hermecompanion` -- symmetrized companion matrix in Hermite_e form. -- `hermefit` -- least-squares fit returning a Hermite_e series. -- `hermetrim` -- trim leading coefficients from a Hermite_e series. -- `hermeline` -- Hermite_e series of given straight line. -- `herme2poly` -- convert a Hermite_e series to a polynomial. -- `poly2herme` -- convert a polynomial to a Hermite_e series. - -Classes -------- -- `HermiteE` -- A Hermite_e series class. +.. autosummary:: + :toctree: generated/ + + hermefromroots + hermeroots + hermevander + hermevander2d + hermevander3d + hermegauss + hermeweight + hermecompanion + hermefit + hermetrim + hermeline + herme2poly + poly2herme See also -------- `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - -import warnings import numpy as np import numpy.linalg as la from numpy.core.multiarray import normalize_axis_index @@ -1186,7 +1200,7 @@ def hermevander2d(x, y, deg): .. versionadded:: 1.7.0 """ - return pu._vander2d(hermevander, x, y, deg) + return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg) def hermevander3d(x, y, z, deg): @@ -1240,7 +1254,7 @@ def hermevander3d(x, y, z, deg): .. versionadded:: 1.7.0 """ - return pu._vander3d(hermevander, x, y, z, deg) + return pu._vander_nd_flat((hermevander, hermevander, hermevander), (x, y, z), deg) def hermefit(x, y, deg, rcond=None, full=False, w=None): diff --git a/numpy/polynomial/laguerre.py b/numpy/polynomial/laguerre.py index 7e7e45ca1..89bb8e168 100644 --- a/numpy/polynomial/laguerre.py +++ b/numpy/polynomial/laguerre.py @@ -1,5 +1,7 @@ """ -Objects for dealing with Laguerre series. +================================================== +Laguerre Series (:mod:`numpy.polynomial.laguerre`) +================================================== This module provides a number of objects (mostly functions) useful for dealing with Laguerre series, including a `Laguerre` class that @@ -7,60 +9,72 @@ encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). +Classes +------- +.. autosummary:: + :toctree: generated/ + + Laguerre + Constants --------- -- `lagdomain` -- Laguerre series default domain, [-1,1]. -- `lagzero` -- Laguerre series that evaluates identically to 0. -- `lagone` -- Laguerre series that evaluates identically to 1. -- `lagx` -- Laguerre series for the identity map, ``f(x) = x``. +.. autosummary:: + :toctree: generated/ + + lagdomain + lagzero + lagone + lagx Arithmetic ---------- -- `lagadd` -- add two Laguerre series. -- `lagsub` -- subtract one Laguerre series from another. -- `lagmulx` -- multiply a Laguerre series in ``P_i(x)`` by ``x``. -- `lagmul` -- multiply two Laguerre series. -- `lagdiv` -- divide one Laguerre series by another. -- `lagpow` -- raise a Laguerre series to a positive integer power. -- `lagval` -- evaluate a Laguerre series at given points. -- `lagval2d` -- evaluate a 2D Laguerre series at given points. -- `lagval3d` -- evaluate a 3D Laguerre series at given points. -- `laggrid2d` -- evaluate a 2D Laguerre series on a Cartesian product. -- `laggrid3d` -- evaluate a 3D Laguerre series on a Cartesian product. +.. autosummary:: + :toctree: generated/ + + lagadd + lagsub + lagmulx + lagmul + lagdiv + lagpow + lagval + lagval2d + lagval3d + laggrid2d + laggrid3d Calculus -------- -- `lagder` -- differentiate a Laguerre series. -- `lagint` -- integrate a Laguerre series. +.. autosummary:: + :toctree: generated/ + + lagder + lagint Misc Functions -------------- -- `lagfromroots` -- create a Laguerre series with specified roots. -- `lagroots` -- find the roots of a Laguerre series. -- `lagvander` -- Vandermonde-like matrix for Laguerre polynomials. -- `lagvander2d` -- Vandermonde-like matrix for 2D power series. -- `lagvander3d` -- Vandermonde-like matrix for 3D power series. -- `laggauss` -- Gauss-Laguerre quadrature, points and weights. -- `lagweight` -- Laguerre weight function. -- `lagcompanion` -- symmetrized companion matrix in Laguerre form. -- `lagfit` -- least-squares fit returning a Laguerre series. -- `lagtrim` -- trim leading coefficients from a Laguerre series. -- `lagline` -- Laguerre series of given straight line. -- `lag2poly` -- convert a Laguerre series to a polynomial. -- `poly2lag` -- convert a polynomial to a Laguerre series. - -Classes -------- -- `Laguerre` -- A Laguerre series class. +.. autosummary:: + :toctree: generated/ + + lagfromroots + lagroots + lagvander + lagvander2d + lagvander3d + laggauss + lagweight + lagcompanion + lagfit + lagtrim + lagline + lag2poly + poly2lag See also -------- `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - -import warnings import numpy as np import numpy.linalg as la from numpy.core.multiarray import normalize_axis_index @@ -1193,7 +1207,7 @@ def lagvander2d(x, y, deg): .. versionadded:: 1.7.0 """ - return pu._vander2d(lagvander, x, y, deg) + return pu._vander_nd_flat((lagvander, lagvander), (x, y), deg) def lagvander3d(x, y, z, deg): @@ -1247,7 +1261,7 @@ def lagvander3d(x, y, z, deg): .. versionadded:: 1.7.0 """ - return pu._vander3d(lagvander, x, y, z, deg) + return pu._vander_nd_flat((lagvander, lagvander, lagvander), (x, y, z), deg) def lagfit(x, y, deg, rcond=None, full=False, w=None): diff --git a/numpy/polynomial/legendre.py b/numpy/polynomial/legendre.py index 281982d0b..85fd5b18b 100644 --- a/numpy/polynomial/legendre.py +++ b/numpy/polynomial/legendre.py @@ -1,8 +1,7 @@ """ -Legendre Series (:mod: `numpy.polynomial.legendre`) -=================================================== - -.. currentmodule:: numpy.polynomial.polynomial +================================================== +Legendre Series (:mod:`numpy.polynomial.legendre`) +================================================== This module provides a number of objects (mostly functions) useful for dealing with Legendre series, including a `Legendre` class that @@ -10,16 +9,23 @@ encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). +Classes +------- +.. autosummary:: + :toctree: generated/ + + Legendre + Constants --------- .. autosummary:: :toctree: generated/ - legdomain Legendre series default domain, [-1,1]. - legzero Legendre series that evaluates identically to 0. - legone Legendre series that evaluates identically to 1. - legx Legendre series for the identity map, ``f(x) = x``. + legdomain + legzero + legone + legx Arithmetic ---------- @@ -27,17 +33,17 @@ Arithmetic .. autosummary:: :toctree: generated/ - legadd add two Legendre series. - legsub subtract one Legendre series from another. - legmulx multiply a Legendre series in ``P_i(x)`` by ``x``. - legmul multiply two Legendre series. - legdiv divide one Legendre series by another. - legpow raise a Legendre series to a positive integer power. - legval evaluate a Legendre series at given points. - legval2d evaluate a 2D Legendre series at given points. - legval3d evaluate a 3D Legendre series at given points. - leggrid2d evaluate a 2D Legendre series on a Cartesian product. - leggrid3d evaluate a 3D Legendre series on a Cartesian product. + legadd + legsub + legmulx + legmul + legdiv + legpow + legval + legval2d + legval3d + leggrid2d + leggrid3d Calculus -------- @@ -45,8 +51,8 @@ Calculus .. autosummary:: :toctree: generated/ - legder differentiate a Legendre series. - legint integrate a Legendre series. + legder + legint Misc Functions -------------- @@ -54,36 +60,25 @@ Misc Functions .. autosummary:: :toctree: generated/ - legfromroots create a Legendre series with specified roots. - legroots find the roots of a Legendre series. - legvander Vandermonde-like matrix for Legendre polynomials. - legvander2d Vandermonde-like matrix for 2D power series. - legvander3d Vandermonde-like matrix for 3D power series. - leggauss Gauss-Legendre quadrature, points and weights. - legweight Legendre weight function. - legcompanion symmetrized companion matrix in Legendre form. - legfit least-squares fit returning a Legendre series. - legtrim trim leading coefficients from a Legendre series. - legline Legendre series representing given straight line. - leg2poly convert a Legendre series to a polynomial. - poly2leg convert a polynomial to a Legendre series. - -Classes -------- - Legendre A Legendre series class. + legfromroots + legroots + legvander + legvander2d + legvander3d + leggauss + legweight + legcompanion + legfit + legtrim + legline + leg2poly + poly2leg See also -------- -numpy.polynomial.polynomial -numpy.polynomial.chebyshev -numpy.polynomial.laguerre -numpy.polynomial.hermite -numpy.polynomial.hermite_e +numpy.polynomial """ -from __future__ import division, absolute_import, print_function - -import warnings import numpy as np import numpy.linalg as la from numpy.core.multiarray import normalize_axis_index @@ -1229,7 +1224,7 @@ def legvander2d(x, y, deg): .. versionadded:: 1.7.0 """ - return pu._vander2d(legvander, x, y, deg) + return pu._vander_nd_flat((legvander, legvander), (x, y), deg) def legvander3d(x, y, z, deg): @@ -1283,7 +1278,7 @@ def legvander3d(x, y, z, deg): .. versionadded:: 1.7.0 """ - return pu._vander3d(legvander, x, y, z, deg) + return pu._vander_nd_flat((legvander, legvander, legvander), (x, y, z), deg) def legfit(x, y, deg, rcond=None, full=False, w=None): diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 3f0a902cf..2fb032db3 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -1,5 +1,7 @@ """ -Objects for dealing with polynomials. +================================================= +Power Series (:mod:`numpy.polynomial.polynomial`) +================================================= This module provides a number of objects (mostly functions) useful for dealing with polynomials, including a `Polynomial` class that @@ -7,56 +9,69 @@ encapsulates the usual arithmetic operations. (General information on how this module represents and works with polynomial objects is in the docstring for its "parent" sub-package, `numpy.polynomial`). +Classes +------- +.. autosummary:: + :toctree: generated/ + + Polynomial + Constants --------- -- `polydomain` -- Polynomial default domain, [-1,1]. -- `polyzero` -- (Coefficients of the) "zero polynomial." -- `polyone` -- (Coefficients of the) constant polynomial 1. -- `polyx` -- (Coefficients of the) identity map polynomial, ``f(x) = x``. +.. autosummary:: + :toctree: generated/ + + polydomain + polyzero + polyone + polyx Arithmetic ---------- -- `polyadd` -- add two polynomials. -- `polysub` -- subtract one polynomial from another. -- `polymulx` -- multiply a polynomial in ``P_i(x)`` by ``x``. -- `polymul` -- multiply two polynomials. -- `polydiv` -- divide one polynomial by another. -- `polypow` -- raise a polynomial to a positive integer power. -- `polyval` -- evaluate a polynomial at given points. -- `polyval2d` -- evaluate a 2D polynomial at given points. -- `polyval3d` -- evaluate a 3D polynomial at given points. -- `polygrid2d` -- evaluate a 2D polynomial on a Cartesian product. -- `polygrid3d` -- evaluate a 3D polynomial on a Cartesian product. +.. autosummary:: + :toctree: generated/ + + polyadd + polysub + polymulx + polymul + polydiv + polypow + polyval + polyval2d + polyval3d + polygrid2d + polygrid3d Calculus -------- -- `polyder` -- differentiate a polynomial. -- `polyint` -- integrate a polynomial. +.. autosummary:: + :toctree: generated/ + + polyder + polyint Misc Functions -------------- -- `polyfromroots` -- create a polynomial with specified roots. -- `polyroots` -- find the roots of a polynomial. -- `polyvalfromroots` -- evaluate a polynomial at given points from roots. -- `polyvander` -- Vandermonde-like matrix for powers. -- `polyvander2d` -- Vandermonde-like matrix for 2D power series. -- `polyvander3d` -- Vandermonde-like matrix for 3D power series. -- `polycompanion` -- companion matrix in power series form. -- `polyfit` -- least-squares fit returning a polynomial. -- `polytrim` -- trim leading coefficients from a polynomial. -- `polyline` -- polynomial representing given straight line. - -Classes -------- -- `Polynomial` -- polynomial class. +.. autosummary:: + :toctree: generated/ + + polyfromroots + polyroots + polyvalfromroots + polyvander + polyvander2d + polyvander3d + polycompanion + polyfit + polytrim + polyline See Also -------- `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - __all__ = [ 'polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval', @@ -64,7 +79,6 @@ __all__ = [ 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d', 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d'] -import warnings import numpy as np import numpy.linalg as la from numpy.core.multiarray import normalize_axis_index @@ -1133,7 +1147,7 @@ def polyvander2d(x, y, deg): polyvander, polyvander3d, polyval2d, polyval3d """ - return pu._vander2d(polyvander, x, y, deg) + return pu._vander_nd_flat((polyvander, polyvander), (x, y), deg) def polyvander3d(x, y, z, deg): @@ -1187,7 +1201,7 @@ def polyvander3d(x, y, z, deg): .. versionadded:: 1.7.0 """ - return pu._vander3d(polyvander, x, y, z, deg) + return pu._vander_nd_flat((polyvander, polyvander, polyvander), (x, y, z), deg) def polyfit(x, y, deg, rcond=None, full=False, w=None): @@ -1484,10 +1498,10 @@ class Polynomial(ABCPolyBase): @staticmethod def _repr_latex_term(i, arg_str, needs_parens): if needs_parens: - arg_str = r'\left({}\right)'.format(arg_str) + arg_str = rf"\left({arg_str}\right)" if i == 0: return '1' elif i == 1: return arg_str else: - return '{}^{{{}}}'.format(arg_str, i) + return f"{arg_str}^{{{i}}}" diff --git a/numpy/polynomial/polyutils.py b/numpy/polynomial/polyutils.py index 35b24d1ab..ec7ba6f1d 100644 --- a/numpy/polynomial/polyutils.py +++ b/numpy/polynomial/polyutils.py @@ -43,9 +43,8 @@ Functions mapparms parameters of the linear map between domains. """ -from __future__ import division, absolute_import, print_function - import operator +import functools import warnings import numpy as np @@ -79,7 +78,7 @@ class PolyDomainError(PolyError): # Base class for all polynomial types # -class PolyBase(object): +class PolyBase: """ Base class for all polynomial types. @@ -415,45 +414,89 @@ def mapdomain(x, old, new): return off + scl*x -def _vander2d(vander_f, x, y, deg): - """ - Helper function used to implement the ``<type>vander2d`` functions. +def _nth_slice(i, ndim): + sl = [np.newaxis] * ndim + sl[i] = slice(None) + return tuple(sl) + + +def _vander_nd(vander_fs, points, degrees): + r""" + A generalization of the Vandermonde matrix for N dimensions + + The result is built by combining the results of 1d Vandermonde matrices, + + .. math:: + W[i_0, \ldots, i_M, j_0, \ldots, j_N] = \prod_{k=0}^N{V_k(x_k)[i_0, \ldots, i_M, j_k]} + + where + + .. math:: + N &= \texttt{len(points)} = \texttt{len(degrees)} = \texttt{len(vander\_fs)} \\ + M &= \texttt{points[k].ndim} \\ + V_k &= \texttt{vander\_fs[k]} \\ + x_k &= \texttt{points[k]} \\ + 0 \le j_k &\le \texttt{degrees[k]} + + Expanding the one-dimensional :math:`V_k` functions gives: + + .. math:: + W[i_0, \ldots, i_M, j_0, \ldots, j_N] = \prod_{k=0}^N{B_{k, j_k}(x_k[i_0, \ldots, i_M])} + + where :math:`B_{k,m}` is the m'th basis of the polynomial construction used along + dimension :math:`k`. For a regular polynomial, :math:`B_{k, m}(x) = P_m(x) = x^m`. Parameters ---------- - vander_f : function(array_like, int) -> ndarray - The 1d vander function, such as ``polyvander`` - x, y, deg : - See the ``<type>vander2d`` functions for more detail + vander_fs : Sequence[function(array_like, int) -> ndarray] + The 1d vander function to use for each axis, such as ``polyvander`` + points : Sequence[array_like] + Arrays of point coordinates, all of the same shape. The dtypes + will be converted to either float64 or complex128 depending on + whether any of the elements are complex. Scalars are converted to + 1-D arrays. + This must be the same length as `vander_fs`. + degrees : Sequence[int] + The maximum degree (inclusive) to use for each axis. + This must be the same length as `vander_fs`. + + Returns + ------- + vander_nd : ndarray + An array of shape ``points[0].shape + tuple(d + 1 for d in degrees)``. """ - degx, degy = deg - x, y = np.array((x, y), copy=False) + 0.0 + n_dims = len(vander_fs) + if n_dims != len(points): + raise ValueError( + f"Expected {n_dims} dimensions of sample points, got {len(points)}") + if n_dims != len(degrees): + raise ValueError( + f"Expected {n_dims} dimensions of degrees, got {len(degrees)}") + if n_dims == 0: + raise ValueError("Unable to guess a dtype or shape when no points are given") - vx = vander_f(x, degx) - vy = vander_f(y, degy) - v = vx[..., None]*vy[..., None,:] - return v.reshape(v.shape[:-2] + (-1,)) + # convert to the same shape and type + points = tuple(np.array(tuple(points), copy=False) + 0.0) + # produce the vandermonde matrix for each dimension, placing the last + # axis of each in an independent trailing axis of the output + vander_arrays = ( + vander_fs[i](points[i], degrees[i])[(...,) + _nth_slice(i, n_dims)] + for i in range(n_dims) + ) -def _vander3d(vander_f, x, y, z, deg): - """ - Helper function used to implement the ``<type>vander3d`` functions. + # we checked this wasn't empty already, so no `initial` needed + return functools.reduce(operator.mul, vander_arrays) - Parameters - ---------- - vander_f : function(array_like, int) -> ndarray - The 1d vander function, such as ``polyvander`` - x, y, z, deg : - See the ``<type>vander3d`` functions for more detail + +def _vander_nd_flat(vander_fs, points, degrees): """ - degx, degy, degz = deg - x, y, z = np.array((x, y, z), copy=False) + 0.0 + Like `_vander_nd`, but flattens the last ``len(degrees)`` axes into a single axis - vx = vander_f(x, degx) - vy = vander_f(y, degy) - vz = vander_f(z, degz) - v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] - return v.reshape(v.shape[:-3] + (-1,)) + Used to implement the public ``<type>vander<n>d`` functions. + """ + v = _vander_nd(vander_fs, points, degrees) + return v.reshape(v.shape[:-len(degrees)] + (-1,)) def _fromroots(line_f, mul_f, roots): @@ -497,17 +540,15 @@ def _valnd(val_f, c, *args): c, args : See the ``<type>val<n>d`` functions for more detail """ - try: - args = tuple(np.array(args, copy=False)) - except Exception: - # preserve the old error message - if len(args) == 2: + args = [np.asanyarray(a) for a in args] + shape0 = args[0].shape + if not all((a.shape == shape0 for a in args[1:])): + if len(args) == 3: raise ValueError('x, y, z are incompatible') - elif len(args) == 3: + elif len(args) == 2: raise ValueError('x, y are incompatible') else: raise ValueError('ordinates are incompatible') - it = iter(args) x0 = next(it) @@ -745,12 +786,11 @@ def _deprecate_as_int(x, desc): else: if ix == x: warnings.warn( - "In future, this will raise TypeError, as {} will need to " - "be an integer not just an integral float." - .format(desc), + f"In future, this will raise TypeError, as {desc} will " + "need to be an integer not just an integral float.", DeprecationWarning, stacklevel=3 ) return ix - raise TypeError("{} must be an integer".format(desc)) + raise TypeError(f"{desc} must be an integer") diff --git a/numpy/polynomial/setup.py b/numpy/polynomial/setup.py index cb59ee1e5..8fc82cba1 100644 --- a/numpy/polynomial/setup.py +++ b/numpy/polynomial/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('polynomial', parent_package, top_path) diff --git a/numpy/polynomial/tests/test_chebyshev.py b/numpy/polynomial/tests/test_chebyshev.py index c8d2d6dba..2f54bebfd 100644 --- a/numpy/polynomial/tests/test_chebyshev.py +++ b/numpy/polynomial/tests/test_chebyshev.py @@ -1,8 +1,6 @@ """Tests for chebyshev module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256] Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9] -class TestPrivate(object): +class TestPrivate: def test__cseries_to_zseries(self): for i in range(5): @@ -47,7 +45,7 @@ class TestPrivate(object): assert_equal(res, tgt) -class TestConstants(object): +class TestConstants: def test_chebdomain(self): assert_equal(cheb.chebdomain, [-1, 1]) @@ -62,12 +60,12 @@ class TestConstants(object): assert_equal(cheb.chebx, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: def test_chebadd(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 @@ -77,7 +75,7 @@ class TestArithmetic(object): def test_chebsub(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 @@ -95,7 +93,7 @@ class TestArithmetic(object): def test_chebmul(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(i + j + 1) tgt[i + j] += .5 tgt[abs(i - j)] += .5 @@ -105,7 +103,7 @@ class TestArithmetic(object): def test_chebdiv(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" ci = [0]*i + [1] cj = [0]*j + [1] tgt = cheb.chebadd(ci, cj) @@ -116,14 +114,14 @@ class TestArithmetic(object): def test_chebpow(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" c = np.arange(i + 1) tgt = reduce(cheb.chebmul, [c]*j, np.array([1])) res = cheb.chebpow(c, j) assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2.5, 2., 1.5]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -141,7 +139,7 @@ class TestEvaluation(object): x = np.linspace(-1, 1) y = [polyval(x, c) for c in Tlist] for i in range(10): - msg = "At i=%d" % i + msg = f"At i={i}" tgt = y[i] res = cheb.chebval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) @@ -217,7 +215,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_chebint(self): # check exceptions @@ -319,7 +317,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_chebder(self): # check exceptions @@ -359,7 +357,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -407,7 +405,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_chebfit(self): def f(x): @@ -484,7 +482,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestInterpolate(object): +class TestInterpolate: def f(self, x): return x * (x - 1) * (x - 2) @@ -509,7 +507,7 @@ class TestInterpolate(object): assert_almost_equal(cheb.chebval(x, c), powx(x, p), decimal=12) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, cheb.chebcompanion, []) @@ -524,7 +522,7 @@ class TestCompanion(object): assert_(cheb.chebcompanion([1, 2])[0, 0] == -.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = cheb.chebgauss(100) @@ -543,7 +541,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_chebfromroots(self): res = cheb.chebfromroots([]) diff --git a/numpy/polynomial/tests/test_classes.py b/numpy/polynomial/tests/test_classes.py index 2261f960b..e9f256cf8 100644 --- a/numpy/polynomial/tests/test_classes.py +++ b/numpy/polynomial/tests/test_classes.py @@ -3,8 +3,6 @@ This tests the convert and cast methods of all the polynomial classes. """ -from __future__ import division, absolute_import, print_function - import operator as op from numbers import Number @@ -15,7 +13,6 @@ from numpy.polynomial import ( from numpy.testing import ( assert_almost_equal, assert_raises, assert_equal, assert_, ) -from numpy.compat import long from numpy.polynomial.polyutils import RankWarning # @@ -44,7 +41,7 @@ def assert_poly_almost_equal(p1, p2, msg=""): assert_(np.all(p1.window == p2.window)) assert_almost_equal(p1.coef, p2.coef) except AssertionError: - msg = "Result: %s\nTarget: %s", (p1, p2) + msg = f"Result: {p1}\nTarget: {p2}" raise AssertionError(msg) @@ -317,7 +314,7 @@ def test_truediv(Poly): s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) - for stype in (int, long, float): + for stype in (int, float): s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) @@ -574,7 +571,7 @@ def test_ufunc_override(Poly): -class TestLatexRepr(object): +class TestLatexRepr: """Test the latex repr used by ipython """ def as_latex(self, obj): @@ -628,7 +625,7 @@ class TestLatexRepr(object): # -class TestInterpolate(object): +class TestInterpolate: def f(self, x): return x * (x - 1) * (x - 2) diff --git a/numpy/polynomial/tests/test_hermite.py b/numpy/polynomial/tests/test_hermite.py index 271c1964b..53ee0844e 100644 --- a/numpy/polynomial/tests/test_hermite.py +++ b/numpy/polynomial/tests/test_hermite.py @@ -1,8 +1,6 @@ """Tests for hermite module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ def trim(x): return herm.hermtrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_hermdomain(self): assert_equal(herm.hermdomain, [-1, 1]) @@ -45,13 +43,13 @@ class TestConstants(object): assert_equal(herm.hermx, [0, .5]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-3, 3, 100) def test_hermadd(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 @@ -61,7 +59,7 @@ class TestArithmetic(object): def test_hermsub(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 @@ -82,7 +80,7 @@ class TestArithmetic(object): pol1 = [0]*i + [1] val1 = herm.hermval(self.x, pol1) for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" pol2 = [0]*j + [1] val2 = herm.hermval(self.x, pol2) pol3 = herm.hermmul(pol1, pol2) @@ -93,7 +91,7 @@ class TestArithmetic(object): def test_hermdiv(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" ci = [0]*i + [1] cj = [0]*j + [1] tgt = herm.hermadd(ci, cj) @@ -104,14 +102,14 @@ class TestArithmetic(object): def test_hermpow(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + 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(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2.5, 1., .75]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -129,7 +127,7 @@ class TestEvaluation(object): x = np.linspace(-1, 1) y = [polyval(x, c) for c in Hlist] for i in range(10): - msg = "At i=%d" % i + msg = f"At i={i}" tgt = y[i] res = herm.hermval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) @@ -205,7 +203,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_hermint(self): # check exceptions @@ -307,7 +305,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_hermder(self): # check exceptions @@ -347,7 +345,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -395,7 +393,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_hermfit(self): def f(x): @@ -472,7 +470,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, herm.hermcompanion, []) @@ -487,7 +485,7 @@ class TestCompanion(object): assert_(herm.hermcompanion([1, 2])[0, 0] == -.25) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = herm.hermgauss(100) @@ -506,7 +504,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_hermfromroots(self): res = herm.hermfromroots([]) diff --git a/numpy/polynomial/tests/test_hermite_e.py b/numpy/polynomial/tests/test_hermite_e.py index 434b30e7b..2d262a330 100644 --- a/numpy/polynomial/tests/test_hermite_e.py +++ b/numpy/polynomial/tests/test_hermite_e.py @@ -1,8 +1,6 @@ """Tests for hermite_e module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ def trim(x): return herme.hermetrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_hermedomain(self): assert_equal(herme.hermedomain, [-1, 1]) @@ -45,13 +43,13 @@ class TestConstants(object): assert_equal(herme.hermex, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-3, 3, 100) def test_hermeadd(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 @@ -61,7 +59,7 @@ class TestArithmetic(object): def test_hermesub(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 @@ -82,7 +80,7 @@ class TestArithmetic(object): pol1 = [0]*i + [1] val1 = herme.hermeval(self.x, pol1) for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" pol2 = [0]*j + [1] val2 = herme.hermeval(self.x, pol2) pol3 = herme.hermemul(pol1, pol2) @@ -93,7 +91,7 @@ class TestArithmetic(object): def test_hermediv(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" ci = [0]*i + [1] cj = [0]*j + [1] tgt = herme.hermeadd(ci, cj) @@ -104,14 +102,14 @@ class TestArithmetic(object): def test_hermepow(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + 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(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([4., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -129,7 +127,7 @@ class TestEvaluation(object): x = np.linspace(-1, 1) y = [polyval(x, c) for c in Helist] for i in range(10): - msg = "At i=%d" % i + msg = f"At i={i}" tgt = y[i] res = herme.hermeval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) @@ -205,7 +203,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_hermeint(self): # check exceptions @@ -307,7 +305,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_hermeder(self): # check exceptions @@ -348,7 +346,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -396,7 +394,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_hermefit(self): def f(x): @@ -473,7 +471,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, herme.hermecompanion, []) @@ -488,7 +486,7 @@ class TestCompanion(object): assert_(herme.hermecompanion([1, 2])[0, 0] == -.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = herme.hermegauss(100) @@ -507,7 +505,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_hermefromroots(self): res = herme.hermefromroots([]) diff --git a/numpy/polynomial/tests/test_laguerre.py b/numpy/polynomial/tests/test_laguerre.py index 4b9b28637..227ef3c55 100644 --- a/numpy/polynomial/tests/test_laguerre.py +++ b/numpy/polynomial/tests/test_laguerre.py @@ -1,8 +1,6 @@ """Tests for laguerre module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -27,7 +25,7 @@ def trim(x): return lag.lagtrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_lagdomain(self): assert_equal(lag.lagdomain, [0, 1]) @@ -42,13 +40,13 @@ class TestConstants(object): assert_equal(lag.lagx, [1, -1]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-3, 3, 100) def test_lagadd(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 @@ -58,7 +56,7 @@ class TestArithmetic(object): def test_lagsub(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 @@ -79,7 +77,7 @@ class TestArithmetic(object): pol1 = [0]*i + [1] val1 = lag.lagval(self.x, pol1) for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" pol2 = [0]*j + [1] val2 = lag.lagval(self.x, pol2) pol3 = lag.lagmul(pol1, pol2) @@ -90,7 +88,7 @@ class TestArithmetic(object): def test_lagdiv(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" ci = [0]*i + [1] cj = [0]*j + [1] tgt = lag.lagadd(ci, cj) @@ -101,14 +99,14 @@ class TestArithmetic(object): def test_lagpow(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + 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(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([9., -14., 6.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -126,7 +124,7 @@ class TestEvaluation(object): x = np.linspace(-1, 1) y = [polyval(x, c) for c in Llist] for i in range(7): - msg = "At i=%d" % i + msg = f"At i={i}" tgt = y[i] res = lag.lagval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) @@ -202,7 +200,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_lagint(self): # check exceptions @@ -304,7 +302,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_lagder(self): # check exceptions @@ -344,7 +342,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -392,7 +390,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_lagfit(self): def f(x): @@ -454,7 +452,7 @@ class TestFitting(object): assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1]) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, lag.lagcompanion, []) @@ -469,7 +467,7 @@ class TestCompanion(object): assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = lag.laggauss(100) @@ -488,7 +486,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_lagfromroots(self): res = lag.lagfromroots([]) diff --git a/numpy/polynomial/tests/test_legendre.py b/numpy/polynomial/tests/test_legendre.py index 917a7e03a..a2a212c24 100644 --- a/numpy/polynomial/tests/test_legendre.py +++ b/numpy/polynomial/tests/test_legendre.py @@ -1,8 +1,6 @@ """Tests for legendre module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ def trim(x): return leg.legtrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_legdomain(self): assert_equal(leg.legdomain, [-1, 1]) @@ -45,13 +43,13 @@ class TestConstants(object): assert_equal(leg.legx, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-1, 1, 100) def test_legadd(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 @@ -61,7 +59,7 @@ class TestArithmetic(object): def test_legsub(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 @@ -83,7 +81,7 @@ class TestArithmetic(object): pol1 = [0]*i + [1] val1 = leg.legval(self.x, pol1) for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" pol2 = [0]*j + [1] val2 = leg.legval(self.x, pol2) pol3 = leg.legmul(pol1, pol2) @@ -94,7 +92,7 @@ class TestArithmetic(object): def test_legdiv(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" ci = [0]*i + [1] cj = [0]*j + [1] tgt = leg.legadd(ci, cj) @@ -105,14 +103,14 @@ class TestArithmetic(object): def test_legpow(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + 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(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2., 2., 2.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -130,7 +128,7 @@ class TestEvaluation(object): x = np.linspace(-1, 1) y = [polyval(x, c) for c in Llist] for i in range(10): - msg = "At i=%d" % i + msg = f"At i={i}" tgt = y[i] res = leg.legval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) @@ -206,7 +204,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_legint(self): # check exceptions @@ -308,7 +306,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_legder(self): # check exceptions @@ -348,7 +346,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -396,7 +394,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_legfit(self): def f(x): @@ -473,7 +471,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, leg.legcompanion, []) @@ -488,7 +486,7 @@ class TestCompanion(object): assert_(leg.legcompanion([1, 2])[0, 0] == -.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = leg.leggauss(100) @@ -507,7 +505,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_legfromroots(self): res = leg.legfromroots([]) diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py index 1436963c6..5fd1a82a2 100644 --- a/numpy/polynomial/tests/test_polynomial.py +++ b/numpy/polynomial/tests/test_polynomial.py @@ -1,15 +1,13 @@ """Tests for polynomial module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np import numpy.polynomial.polynomial as poly from numpy.testing import ( assert_almost_equal, assert_raises, assert_equal, assert_, - assert_warns, assert_array_equal) + assert_warns, assert_array_equal, assert_raises_regex) def trim(x): @@ -29,7 +27,7 @@ T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256] Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9] -class TestConstants(object): +class TestConstants: def test_polydomain(self): assert_equal(poly.polydomain, [-1, 1]) @@ -44,12 +42,12 @@ class TestConstants(object): assert_equal(poly.polyx, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: def test_polyadd(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 @@ -59,7 +57,7 @@ class TestArithmetic(object): def test_polysub(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 @@ -77,7 +75,7 @@ class TestArithmetic(object): def test_polymul(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" tgt = np.zeros(i + j + 1) tgt[i + j] += 1 res = poly.polymul([0]*i + [1], [0]*j + [1]) @@ -96,7 +94,7 @@ class TestArithmetic(object): # check rest. for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + msg = f"At i={i}, j={j}" ci = [0]*i + [1, 2] cj = [0]*j + [1, 2] tgt = poly.polyadd(ci, cj) @@ -107,14 +105,14 @@ class TestArithmetic(object): def test_polypow(self): for i in range(5): for j in range(5): - msg = "At i=%d, j=%d" % (i, j) + 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 TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([1., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -229,7 +227,8 @@ class TestEvaluation(object): y1, y2, y3 = self.y #test exceptions - assert_raises(ValueError, poly.polyval2d, x1, x2[:2], self.c2d) + assert_raises_regex(ValueError, 'incompatible', + poly.polyval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 @@ -246,7 +245,8 @@ class TestEvaluation(object): y1, y2, y3 = self.y #test exceptions - assert_raises(ValueError, poly.polyval3d, x1, x2, x3[:2], self.c3d) + assert_raises_regex(ValueError, 'incompatible', + poly.polyval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 @@ -287,7 +287,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_polyint(self): # check exceptions @@ -386,7 +386,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_polyder(self): # check exceptions @@ -426,7 +426,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -474,7 +474,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, poly.polycompanion, []) @@ -489,7 +489,7 @@ class TestCompanion(object): assert_(poly.polycompanion([1, 2])[0, 0] == -.5) -class TestMisc(object): +class TestMisc: def test_polyfromroots(self): res = poly.polyfromroots([]) diff --git a/numpy/polynomial/tests/test_polyutils.py b/numpy/polynomial/tests/test_polyutils.py index 801c558cc..1b27f53b5 100644 --- a/numpy/polynomial/tests/test_polyutils.py +++ b/numpy/polynomial/tests/test_polyutils.py @@ -1,8 +1,6 @@ """Tests for polyutils module. """ -from __future__ import division, absolute_import, print_function - import numpy as np import numpy.polynomial.polyutils as pu from numpy.testing import ( @@ -10,7 +8,7 @@ from numpy.testing import ( ) -class TestMisc(object): +class TestMisc: def test_trimseq(self): for i in range(5): @@ -43,7 +41,7 @@ class TestMisc(object): assert_equal(pu.trimcoef(coef, 2), [0]) -class TestDomain(object): +class TestDomain: def test_getdomain(self): # test for real values diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py index 3f1236402..049d3af2f 100644 --- a/numpy/polynomial/tests/test_printing.py +++ b/numpy/polynomial/tests/test_printing.py @@ -1,10 +1,8 @@ -from __future__ import division, absolute_import, print_function - import numpy.polynomial as poly from numpy.testing import assert_equal -class TestStr(object): +class TestStr: def test_polynomial_str(self): res = str(poly.Polynomial([0, 1])) tgt = 'poly([0. 1.])' @@ -36,7 +34,7 @@ class TestStr(object): assert_equal(res, tgt) -class TestRepr(object): +class TestRepr: def test_polynomial_str(self): res = repr(poly.Polynomial([0, 1])) tgt = 'Polynomial([0., 1.], domain=[-1, 1], window=[-1, 1])' |