numpy.poly1d

Here are the examples of the python api numpy.poly1d taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

120 Examples 7

3 Source : blur_pool.py
with Apache License 2.0
from 1chimaruGin

    def __init__(self, channels, filt_size=3, stride=2) -> None:
        super(BlurPool2d, self).__init__()
        assert filt_size > 1
        self.channels = channels
        self.filt_size = filt_size
        self.stride = stride
        pad_size = [get_padding(filt_size, stride, dilation=1)] * 4
        self.padding = nn.ReflectionPad2d(pad_size)
        self._coeffs = torch.tensor((np.poly1d((0.5, 0.5)) ** (self.filt_size - 1)).coeffs)  # for torchscript compat
        self.filt = {}  # lazy init by device for DataParallel compat

    def _create_filter(self, like: torch.Tensor):

3 Source : test_polynomial.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_str_leading_zeros(self):
        p = np.poly1d([4, 3, 2, 1])
        p[3] = 0
        assert_equal(str(p),
                     "   2\n"
                     "3 x + 2 x + 1")

        p = np.poly1d([1, 2])
        p[0] = 0
        p[1] = 0
        assert_equal(str(p), " \n0")

    def test_polyfit(self):

3 Source : test_polynomial.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_objects(self):
        from decimal import Decimal
        p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
        p2 = p * Decimal('1.333333333333333')
        assert_(p2[1] == Decimal("3.9999999999999990"))
        p2 = p.deriv()
        assert_(p2[1] == Decimal('8.0'))
        p2 = p.integ()
        assert_(p2[3] == Decimal("1.333333333333333333333333333"))
        assert_(p2[2] == Decimal('1.5'))
        assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
        p = np.poly([Decimal(1), Decimal(2)])
        assert_equal(np.poly([Decimal(1), Decimal(2)]),
                     [1, Decimal(-3), Decimal(2)])

    def test_complex(self):

3 Source : test_polynomial.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_complex(self):
        p = np.poly1d([3j, 2j, 1j])
        p2 = p.integ()
        assert_((p2.coeffs == [1j, 1j, 1j, 0]).all())
        p2 = p.deriv()
        assert_((p2.coeffs == [6j, 2j]).all())

    def test_integ_coeffs(self):

3 Source : test_polynomial.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_integ_coeffs(self):
        p = np.poly1d([3, 2, 1])
        p2 = p.integ(3, k=[9, 7, 6])
        assert_(
            (p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all())

    def test_zero_dims(self):

3 Source : test_polynomial.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_poly_eq(self):
        p = np.poly1d([1, 2, 3])
        p2 = np.poly1d([1, 2, 4])
        assert_equal(p == None, False)
        assert_equal(p != None, True)
        assert_equal(p == p, True)
        assert_equal(p == p2, False)
        assert_equal(p != p2, True)

    def test_poly_coeffs_immutable(self):

3 Source : test_polynomial.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_poly_coeffs_immutable(self):
        """ Coefficients should not be modifiable """
        p = np.poly1d([1, 2, 3])

        try:
            # despite throwing an exception, this used to change state
            p.coeffs += 1
        except Exception:
            pass
        assert_equal(p.coeffs, [1, 2, 3])

        p.coeffs[2] += 10
        assert_equal(p.coeffs, [1, 2, 3])


if __name__ == "__main__":

3 Source : test_regression.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_poly1d(self):
        # Ticket #28
        assert_equal(np.poly1d([1]) - np.poly1d([1, 0]),
                     np.poly1d([-1, 1]))

    def test_cov_parameters(self):

3 Source : test_regression.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_poly_div(self):
        # Ticket #553
        u = np.poly1d([1, 2, 3])
        v = np.poly1d([1, 2, 3, 4, 5])
        q, r = np.polydiv(u, v)
        assert_equal(q*v + r, u)

    def test_poly_eq(self):

3 Source : test_regression.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_poly_eq(self):
        # Ticket #554
        x = np.poly1d([1, 2, 3])
        y = np.poly1d([3, 4])
        assert_(x != y)
        assert_(x == x)

    def test_polyfit_build(self):

3 Source : test_regression.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_polyder_return_type(self):
        # Ticket #1249
        assert_(isinstance(np.polyder(np.poly1d([1]), 0), np.poly1d))
        assert_(isinstance(np.polyder([1], 0), np.ndarray))
        assert_(isinstance(np.polyder(np.poly1d([1]), 1), np.poly1d))
        assert_(isinstance(np.polyder([1], 1), np.ndarray))

    def test_append_fields_dtype_list(self):

3 Source : test_interpolate.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_lagrange(self):
        p = poly1d([5,2,1,4,3])
        xs = np.arange(len(p.coeffs))
        ys = p(xs)
        pl = lagrange(xs,ys)
        assert_array_almost_equal(p.coeffs,pl.coeffs)


class TestAkima1DInterpolator(object):

3 Source : test_polyint.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def setup_method(self):
        self.true_poly = np.poly1d([-2,3,1,5,-4])
        self.test_xs = np.linspace(-1,1,100)
        self.xs = np.linspace(-1,1,5)
        self.ys = self.true_poly(self.xs)

    def test_lagrange(self):

3 Source : test_waveforms.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_sweep_poly_quad1(self):
        p = np.poly1d([1.0, 0.0, 1.0])
        t = np.linspace(0, 3.0, 10000)
        phase = waveforms._sweep_poly_phase(t, p)
        tf, f = compute_frequency(t, phase)
        expected = p(tf)
        abserr = np.max(np.abs(f - expected))
        assert_(abserr   <   1e-6)

    def test_sweep_poly_const(self):

3 Source : test_waveforms.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_sweep_poly_const(self):
        p = np.poly1d(2.0)
        t = np.linspace(0, 3.0, 10000)
        phase = waveforms._sweep_poly_phase(t, p)
        tf, f = compute_frequency(t, phase)
        expected = p(tf)
        abserr = np.max(np.abs(f - expected))
        assert_(abserr   <   1e-6)

    def test_sweep_poly_linear(self):

3 Source : test_waveforms.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_sweep_poly_linear(self):
        p = np.poly1d([-1.0, 10.0])
        t = np.linspace(0, 3.0, 10000)
        phase = waveforms._sweep_poly_phase(t, p)
        tf, f = compute_frequency(t, phase)
        expected = p(tf)
        abserr = np.max(np.abs(f - expected))
        assert_(abserr   <   1e-6)

    def test_sweep_poly_quad2(self):

3 Source : test_waveforms.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_sweep_poly_quad2(self):
        p = np.poly1d([1.0, 0.0, -2.0])
        t = np.linspace(0, 3.0, 10000)
        phase = waveforms._sweep_poly_phase(t, p)
        tf, f = compute_frequency(t, phase)
        expected = p(tf)
        abserr = np.max(np.abs(f - expected))
        assert_(abserr   <   1e-6)

    def test_sweep_poly_cubic(self):

3 Source : test_waveforms.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_sweep_poly_cubic(self):
        p = np.poly1d([2.0, 1.0, 0.0, -2.0])
        t = np.linspace(0, 2.0, 10000)
        phase = waveforms._sweep_poly_phase(t, p)
        tf, f = compute_frequency(t, phase)
        expected = p(tf)
        abserr = np.max(np.abs(f - expected))
        assert_(abserr   <   1e-6)

    def test_sweep_poly_cubic2(self):

3 Source : orthogonal.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def __call__(self, v):
        if self._eval_func and not isinstance(v, np.poly1d):
            return self._eval_func(v)
        else:
            return np.poly1d.__call__(self, v)

    def _scale(self, p):

3 Source : test_orthogonal.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_regression(self):
        assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.)
        assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.)
        assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2]))
        assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1, -2]))


def verify_gauss_quad(root_func, eval_func, weight_func, a, b, N,

3 Source : test_polynomial.py
with MIT License
from alvarobartt

    def test_poly_eq(self):
        p = np.poly1d([1, 2, 3])
        p2 = np.poly1d([1, 2, 4])
        assert_equal(p == None, False)
        assert_equal(p != None, True)
        assert_equal(p == p, True)
        assert_equal(p == p2, False)
        assert_equal(p != p2, True)

    def test_polydiv(self):

3 Source : test_polynomial.py
with MIT License
from alvarobartt

    def test_polydiv(self):
        b = np.poly1d([2, 6, 6, 1])
        a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
        q, r = np.polydiv(b, a)
        assert_equal(q.coeffs.dtype, np.complex128)
        assert_equal(r.coeffs.dtype, np.complex128)
        assert_equal(q*a + r, b)

    def test_poly_coeffs_immutable(self):

3 Source : test_polynomial.py
with MIT License
from alvarobartt

    def test_poly_coeffs_immutable(self):
        """ Coefficients should not be modifiable """
        p = np.poly1d([1, 2, 3])

        try:
            # despite throwing an exception, this used to change state
            p.coeffs += 1
        except Exception:
            pass
        assert_equal(p.coeffs, [1, 2, 3])

        p.coeffs[2] += 10
        assert_equal(p.coeffs, [1, 2, 3])

3 Source : blur_pool.py
with Apache License 2.0
from Ascend

    def __init__(self, channels, filt_size=3, stride=2) -> None:
        super(BlurPool2d, self).__init__()
        assert filt_size > 1
        self.channels = channels
        self.filt_size = filt_size
        self.stride = stride
        self.padding = [get_padding(filt_size, stride, dilation=1)] * 4
        coeffs = torch.tensor((np.poly1d((0.5, 0.5)) ** (self.filt_size - 1)).coeffs.astype(np.float32))
        blur_filter = (coeffs[:, None] * coeffs[None, :])[None, None, :, :].repeat(self.channels, 1, 1, 1)
        self.register_buffer('filt', blur_filter, persistent=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:

3 Source : test_polynomial.py
with Apache License 2.0
from aws-samples

    def test_poly1d_resolution(self):
        p = np.poly1d([1., 2, 3])
        q = np.poly1d([3., 2, 1])
        assert_equal(p(0), 3.0)
        assert_equal(p(5), 38.0)
        assert_equal(q(0), 1.0)
        assert_equal(q(5), 86.0)

    def test_poly1d_math(self):

3 Source : test_polynomial.py
with Apache License 2.0
from aws-samples

    def test_poly1d_misc(self):
        p = np.poly1d([1., 2, 3])
        assert_equal(np.asarray(p), np.array([1., 2., 3.]))
        assert_equal(len(p), 2)
        assert_equal((p[0], p[1], p[2], p[3]), (3.0, 2.0, 1.0, 0))

    def test_poly1d_variable_arg(self):

3 Source : test_polynomial.py
with Apache License 2.0
from aws-samples

    def test_poly1d_variable_arg(self):
        q = np.poly1d([1., 2, 3], variable='y')
        assert_equal(str(q),
                     '   2\n'
                     '1 y + 2 y + 3')
        q = np.poly1d([1., 2, 3], variable='lambda')
        assert_equal(str(q),
                     '        2\n'
                     '1 lambda + 2 lambda + 3')

    def test_poly(self):

3 Source : test_polynomial.py
with Apache License 2.0
from awslabs

    def test_polydiv(self):
        b = np.poly1d([2, 6, 6, 1])
        a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
        q, r = np.polydiv(b, a)
        assert_equal(q.coeffs.dtype, np.complex128)
        assert_equal(r.coeffs.dtype, np.complex128)
        assert_equal(q*a + r, b)

    def test_poly_coeffs_mutable(self):

3 Source : test_polynomial.py
with Apache License 2.0
from awslabs

    def test_poly_coeffs_mutable(self):
        """ Coefficients should be modifiable """
        p = np.poly1d([1, 2, 3])

        p.coeffs += 1
        assert_equal(p.coeffs, [2, 3, 4])

        p.coeffs[2] += 10
        assert_equal(p.coeffs, [2, 3, 14])

        # this never used to be allowed - let's not add features to deprecated
        # APIs
        assert_raises(AttributeError, setattr, p, 'coeffs', np.array(1))

3 Source : extras.py
with MIT License
from birforce

def _hermnorm(N):
    # return the negatively normalized hermite polynomials up to order N-1
    #  (inclusive)
    #  using the recursive relationship
    #  p_n+1 = p_n(x)' - x*p_n(x)
    #   and p_0(x) = 1
    plist = [None]*N
    plist[0] = poly1d(1)
    for n in range(1,N):
        plist[n] = plist[n-1].deriv() - poly1d([1,0])*plist[n-1]
    return plist

def pdf_moments_st(cnt):

3 Source : test_polyint.py
with MIT License
from buds-lab

    def setup_method(self):
        self.true_poly = np.poly1d([-2, 3, 1, 5, -4])
        self.test_xs = np.linspace(-1, 1, 100)
        self.xs = np.linspace(-1, 1, 5)
        self.ys = self.true_poly(self.xs)

    def test_lagrange(self):

3 Source : video_face_dlib.py
with MIT License
from clolsonus

def gen_func( coeffs, min, max, steps ):
    if abs(max-min)   <   0.0001:
        max = min + 0.1
    xvals = []
    yvals = []
    step = (max - min) / steps
    func = np.poly1d(coeffs)
    for x in np.arange(min, max+step, step):
        y = func(x)
        xvals.append(x)
        yvals.append(y)
    return xvals, yvals

class FaceDetect():

3 Source : test_polynomial.py
with GNU General Public License v3.0
from dnn-security

    def test_polydiv(self):
        b = np.poly1d([2, 6, 6, 1])
        a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
        q, r = np.polydiv(b, a)
        assert_equal(q.coeffs.dtype, np.complex128)
        assert_equal(r.coeffs.dtype, np.complex128)
        assert_equal(q*a + r, b)
        
        c = [1, 2, 3]
        d = np.poly1d([1, 2, 3])
        s, t = np.polydiv(c, d)
        assert isinstance(s, np.poly1d)
        assert isinstance(t, np.poly1d)
        u, v = np.polydiv(d, c)
        assert isinstance(u, np.poly1d)
        assert isinstance(v, np.poly1d)

    def test_poly_coeffs_mutable(self):

3 Source : downsample.py
with Apache License 2.0
from frgfm

    def __init__(self, channels: int, kernel_size: int = 3, stride: int = 2) -> None:
        super().__init__()
        self.channels = channels
        if kernel_size   <  = 1:
            raise AssertionError
        self.kernel_size = kernel_size
        self.stride = stride
        pad_size = [get_padding(kernel_size, stride, dilation=1)] * 4
        self.padding = nn.ReflectionPad2d(pad_size)  # type: ignore[arg-type]
        self._coeffs = torch.tensor((np.poly1d((0.5, 0.5)) ** (self.kernel_size - 1)).coeffs)  # for torchscript compat
        self.kernel: Dict[str, Tensor] = {}  # lazy init by device for DataParallel compat

    def _create_filter(self, like: Tensor) -> Tensor:

3 Source : coreg.py
with MIT License
from GlacioHack

    def _apply_func(self, dem: np.ndarray, transform: rio.transform.Affine, **kwargs) -> np.ndarray:
        """Apply the scaling model to a DEM."""
        model = np.poly1d(self._meta["coefficients"])

        return dem + model(dem)

    def _apply_pts_func(self, coords: np.ndarray) -> np.ndarray:

3 Source : coreg.py
with MIT License
from GlacioHack

    def _apply_pts_func(self, coords: np.ndarray) -> np.ndarray:
        """Apply the scaling model to a set of points."""
        model = np.poly1d(self._meta["coefficients"])

        new_coords = coords.copy()
        new_coords[:, 2] += model(new_coords[:, 2])
        return new_coords

    def _to_matrix_func(self) -> np.ndarray:

3 Source : beta_ensemble_polynomial_potential_core.py
with MIT License
from guilgautier

def shift_pol(P, x0):
    """ Return polynomial P(x-x0) as poly1d object
    """

    X_x0 = np.poly1d([1, -x0])

    return sum(X_x0**n * c_n for n, c_n in enumerate(P.coeffs[::-1]))


def log_pdf_convex_quartic(x, P):

3 Source : beta_ensemble_polynomial_potential_core.py
with MIT License
from guilgautier

def find_mode_convex_gen_gamma(shape, P):
    """ Compute mode of :math:`\\pi \\propto x^{a-1} \\exp^{-P(x)}`,
    with :math:`a>1` and :math:`P` convex polynomial.

    .. math::

        \\pi'(x) = 0
        \\Longleftrightarrow
            X P'(X) - (a-1) = 0
    """

    roots = (np.poly1d([1, 0]) * P.deriv(m=1) - (shape - 1)).roots
    real_roots = roots[np.isreal(roots)].real

    return real_roots[real_roots > 0][0]


def find_a_b_convex_gen_gamma(shape, P, mode):

3 Source : test_polynomial.py
with MIT License
from ktraunmueller

    def test_str_leading_zeros(self):
        p = np.poly1d([4, 3, 2, 1])
        p[3] = 0
        assert_equal(str(p),
                     "   2\n"
                     "3 x + 2 x + 1")

        p = np.poly1d([1, 2])
        p[0] = 0
        p[1] = 0
        assert_equal(str(p), " \n0")

    def test_polyfit(self) :

3 Source : test_polynomial.py
with MIT License
from ktraunmueller

    def test_objects(self):
        from decimal import Decimal
        p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
        p2 = p * Decimal('1.333333333333333')
        assert_(p2[1] == Decimal("3.9999999999999990"))
        p2 = p.deriv()
        assert_(p2[1] == Decimal('8.0'))
        p2 = p.integ()
        assert_(p2[3] == Decimal("1.333333333333333333333333333"))
        assert_(p2[2] == Decimal('1.5'))
        assert_(np.issubdtype(p2.coeffs.dtype, np.object_))

    def test_complex(self):

3 Source : test_polynomial.py
with MIT License
from ktraunmueller

    def test_integ_coeffs(self):
        p = np.poly1d([3, 2, 1])
        p2 = p.integ(3, k=[9, 7, 6])
        assert_((p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all())

    def test_zero_dims(self):

3 Source : test_regression.py
with MIT License
from ktraunmueller

    def test_poly1d(self,level=rlevel):
        """Ticket #28"""
        assert_equal(np.poly1d([1]) - np.poly1d([1, 0]),
                     np.poly1d([-1, 1]))

    def test_cov_parameters(self,level=rlevel):

3 Source : test_regression.py
with MIT License
from ktraunmueller

    def test_poly_div(self, level=rlevel):
        """Ticket #553"""
        u = np.poly1d([1, 2, 3])
        v = np.poly1d([1, 2, 3, 4, 5])
        q, r = np.polydiv(u, v)
        assert_equal(q*v + r, u)

    def test_poly_eq(self, level=rlevel):

3 Source : test_regression.py
with MIT License
from ktraunmueller

    def test_poly_eq(self, level=rlevel):
        """Ticket #554"""
        x = np.poly1d([1, 2, 3])
        y = np.poly1d([3, 4])
        assert_(x != y)
        assert_(x == x)

    def test_mem_insert(self, level=rlevel):

3 Source : test_regression.py
with MIT License
from ktraunmueller

    def test_polyder_return_type(self):
        """Ticket #1249"""
        assert_(isinstance(np.polyder(np.poly1d([1]), 0), np.poly1d))
        assert_(isinstance(np.polyder([1], 0), np.ndarray))
        assert_(isinstance(np.polyder(np.poly1d([1]), 1), np.poly1d))
        assert_(isinstance(np.polyder([1], 1), np.ndarray))

    def test_append_fields_dtype_list(self):

3 Source : test_interpolate.py
with MIT License
from ktraunmueller

    def test_lagrange(self):
        p = poly1d([5,2,1,4,3])
        xs = np.arange(len(p.coeffs))
        ys = p(xs)
        pl = lagrange(xs,ys)
        assert_array_almost_equal(p.coeffs,pl.coeffs)

if __name__ == "__main__":

3 Source : morestats.py
with MIT License
from ktraunmueller

def _hermnorm(N):
    # return the negatively normalized hermite polynomials up to order N-1
    #  (inclusive)
    #  using the recursive relationship
    #  p_n+1 = p_n(x)' - x*p_n(x)
    #   and p_0(x) = 1
    plist = [None]*N
    plist[0] = poly1d(1)
    for n in range(1,N):
        plist[n] = plist[n-1].deriv() - poly1d([1,0])*plist[n-1]
    return plist


def pdf_fromgamma(g1,g2,g3=0.0,g4=None):

3 Source : common_layers.py
with MIT License
from leondgarse

def __anti_alias_downsample_initializer__(weight_shape, dtype="float32"):
    import numpy as np

    kernel_size, channel = weight_shape[0], weight_shape[2]
    ww = tf.cast(np.poly1d((0.5, 0.5)) ** (kernel_size - 1), dtype)
    ww = tf.expand_dims(ww, 0) * tf.expand_dims(ww, 1)
    ww = tf.repeat(ww[:, :, tf.newaxis, tf.newaxis], channel, axis=-2)
    return ww


def anti_alias_downsample(inputs, kernel_size=3, strides=2, padding="SAME", trainable=False, name=None):

3 Source : run_benchmark.py
with Apache License 2.0
from megvii-research

    def __init__(self, K_coeff: Tuple[float, float], B_coeff: Tuple[float, float, float], anchor: float, V: float = 959.0):
        self.K = np.poly1d(K_coeff)
        self.Sigma = np.poly1d(B_coeff)
        self.anchor = anchor
        self.V = V

    def __call__(self, img_01, iso: float, inverse=False):

3 Source : morestats.py
with GNU Affero General Public License v3.0
from nccgroup

def _hermnorm(N):
    # return the negatively normalized hermite polynomials up to order N-1
    #  (inclusive)
    #  using the recursive relationship
    #  p_n+1 = p_n(x)' - x*p_n(x)
    #   and p_0(x) = 1
    plist = [None] * N
    plist[0] = poly1d(1)
    for n in range(1, N):
        plist[n] = plist[n-1].deriv() - poly1d([1, 0]) * plist[n-1]

    return plist


# Note: when removing pdf_fromgamma, also remove the _hermnorm support function
@np.deprecate(message="scipy.stats.pdf_fromgamma is deprecated in scipy 0.16.0 "

See More Examples