Python numpy.poly1d() Examples

The following are 30 code examples for showing how to use numpy.poly1d(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: MPContribs   Author: materialsproject   File: xas_process.py    License: MIT License 6 votes vote down vote up
def remove_linear_BG_XAS_preedge(
    xmcd_data, scanparams, process_parameters=None, process_number=-1
):
    """Should remove a linear bg based on the preedge average"""
    preedge_spectrum = get_preedge_spectrum(process_parameters, xmcd_data)

    preedge_poly = np.poly1d(
        np.polyfit(preedge_spectrum["Energy"], preedge_spectrum["XAS"], 1)
    )

    xas_bg = preedge_poly(xmcd_data["Energy"])

    for xas in ["XAS+", "XAS-", "XAS"]:
        xmcd_data[xas] -= xas_bg

    return (xmcd_data, {"xas_bg_poly_coeffs": " ".join(map(str, preedge_poly.coeffs))}) 
Example 2
Project: python-control   Author: python-control   File: rlocus.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _break_points(num, den):
    """Extract break points over real axis and gains given these locations"""
    # type: (np.poly1d, np.poly1d) -> (np.array, np.array)
    dnum = num.deriv(m=1)
    dden = den.deriv(m=1)
    polynom = den * dnum - num * dden
    real_break_pts = polynom.r
    # don't care about infinite break points
    real_break_pts = real_break_pts[num(real_break_pts) != 0]
    k_break = -den(real_break_pts) / num(real_break_pts)
    idx = k_break >= 0   # only positives gains
    k_break = k_break[idx]
    real_break_pts = real_break_pts[idx]
    if len(k_break) == 0:
        k_break = [0]
        real_break_pts = den.roots
    return k_break, real_break_pts 
Example 3
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 6 votes vote down vote up
def test_poly1d_str_and_repr(self):
        p = np.poly1d([1., 2, 3])
        assert_equal(repr(p), 'poly1d([1., 2., 3.])')
        assert_equal(str(p),
                     '   2\n'
                     '1 x + 2 x + 3')

        q = np.poly1d([3., 2, 1])
        assert_equal(repr(q), 'poly1d([3., 2., 1.])')
        assert_equal(str(q),
                     '   2\n'
                     '3 x + 2 x + 1')

        r = np.poly1d([1.89999 + 2j, -3j, -5.12345678, 2 + 1j])
        assert_equal(str(r),
                     '            3      2\n'
                     '(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)')

        assert_equal(str(np.poly1d([-3, -2, -1])),
                     '    2\n'
                     '-3 x - 2 x - 1') 
Example 4
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 6 votes vote down vote up
def test_poly1d_math(self):
        # here we use some simple coeffs to make calculations easier
        p = np.poly1d([1., 2, 4])
        q = np.poly1d([4., 2, 1])
        assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75])))
        assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.]))
        assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.]))

        p = np.poly1d([1., 2, 3])
        q = np.poly1d([3., 2, 1])
        assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.]))
        assert_equal(p + q, np.poly1d([4., 4., 4.]))
        assert_equal(p - q, np.poly1d([-2., 0., 2.]))
        assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.]))
        assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.]))
        assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.]))
        assert_equal(p.deriv(), np.poly1d([2., 2.]))
        assert_equal(p.deriv(2), np.poly1d([2.]))
        assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])),
                     (np.poly1d([1., -1.]), np.poly1d([0.]))) 
Example 5
Project: ocelot   Author: ocelot-collab   File: k_analysis.py    License: GNU General Public License v3.0 6 votes vote down vote up
def data_analysis(e_ph, flux, method="least"):

    if method == "least":
        coeffs = np.polyfit(x=e_ph, y=flux, deg=11)
        polynom = np.poly1d(coeffs)


        x = np.linspace(e_ph[0], e_ph[-1], num=100)
        pd = np.polyder(polynom, m=1)
        indx = np.argmax(np.abs(pd(x)))
        eph_c = x[indx]

        pd2 = np.polyder(polynom, m=2)
        p2_roots = np.roots(pd2)
        p2_roots = p2_roots[p2_roots[:].imag == 0]
        p2_roots = np.real(p2_roots)
        Eph_fin = find_nearest(p2_roots,eph_c)
        return Eph_fin, polynom

    elif method == "new method":
        pass

        #plt.plot(Etotal, total, "ro")
        #plt.plot(x, polynom(x)) 
Example 6
Project: Computable   Author: ktraunmueller   File: orthogonal.py    License: MIT License 6 votes vote down vote up
def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None, limits=None, monic=0,eval_func=None):
        np.poly1d.__init__(self, roots, r=1)
        equiv_weights = [weights[k] / wfunc(roots[k]) for k in range(len(roots))]
        self.__dict__['weights'] = np.array(list(zip(roots,weights,equiv_weights)))
        self.__dict__['weight_func'] = wfunc
        self.__dict__['limits'] = limits
        mu = sqrt(hn)
        if monic:
            evf = eval_func
            if evf:
                eval_func = lambda x: evf(x)/kn
            mu = mu / abs(kn)
            kn = 1.0
        self.__dict__['normcoef'] = mu
        self.__dict__['coeffs'] *= kn

        # Note: eval_func will be discarded on arithmetic
        self.__dict__['_eval_func'] = eval_func 
Example 7
Project: ICDAR-2019-SROIE   Author: zzzDavid   File: text_proposal_connector.py    License: MIT License 5 votes vote down vote up
def fit_y(self, X, Y, x1, x2):
        len(X) != 0
        # if X only include one point, the function will get line y=Y[0]
        if np.sum(X == X[0]) == len(X):
            return Y[0], Y[0]
        p = np.poly1d(np.polyfit(X, Y, 1))
        return p(x1), p(x2) 
Example 8
Project: ICDAR-2019-SROIE   Author: zzzDavid   File: text_proposal_connector_oriented.py    License: MIT License 5 votes vote down vote up
def fit_y(self, X, Y, x1, x2):
        len(X) != 0
        # if X only include one point, the function will get line y=Y[0]
        if np.sum(X == X[0]) == len(X):
            return Y[0], Y[0]
        p = np.poly1d(np.polyfit(X, Y, 1))
        return p(x1), p(x2) 
Example 9
Project: python-control   Author: python-control   File: rlocus.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _systopoly1d(sys):
    """Extract numerator and denominator polynomails for a system"""
    # Allow inputs from the signal processing toolbox
    if (isinstance(sys, scipy.signal.lti)):
        nump = sys.num
        denp = sys.den

    else:
        # Convert to a transfer function, if needed
        sys = _convert_to_transfer_function(sys)

        # Make sure we have a SISO system
        if (sys.inputs > 1 or sys.outputs > 1):
            raise ControlMIMONotImplemented()

        # Start by extracting the numerator and denominator from system object
        nump = sys.num[0][0]
        denp = sys.den[0][0]

    # Check to see if num, den are already polynomials; otherwise convert
    if (not isinstance(nump, poly1d)):
        nump = poly1d(nump)

    if (not isinstance(denp, poly1d)):
        denp = poly1d(denp)

    return (nump, denp) 
Example 10
Project: ProMo   Author: timmahrt   File: interpolation.py    License: MIT License 5 votes vote down vote up
def quadraticInterpolation(valueList2d, numDegrees, n,
                           startTime=None, endTime=None):
    '''
    Generates a series of points on a smooth curve that cross the given points
    
    numDegrees - the degrees of the fitted polynomial
               - the curve gets weird if this value is too high for the input
    n - number of points to output
    startTime/endTime/n - n points will be generated at evenly spaced
                          intervals between startTime and endTime
    '''
    _numpyCheck()
    
    x, y = zip(*valueList2d)
    
    if startTime is None:
        startTime = x[0]
    if endTime is None:
        endTime = x[-1]
    
    polyFunc = np.poly1d(np.polyfit(x, y, numDegrees))
    
    newX = np.linspace(startTime, endTime, n)
    
    retList = [(n, polyFunc(n)) for n in newX]
    
    return retList 
Example 11
Project: Advanced_Lane_Lines   Author: ChengZhongShen   File: lane_detection.py    License: MIT License 5 votes vote down vote up
def fit_polynomial(leftx, lefty, rightx, righty, out_img):
	"""
	fit left and right lane polynomi
	"""
	# check if there is search failure
	if leftx.size == 0 or lefty.size == 0:
		cv2.putText(out_img,"Search failure", (50,60), cv2.FONT_HERSHEY_SIMPLEX,2,(255,0,255),3)
		return out_img 

	# line fit use np.ployfit, second order, note lefty is x, leftx is y, later use ploty to get plotx
	left_fit = np.polyfit(lefty, leftx, 2)
	right_fit = np.polyfit(righty, rightx, 2)
	# print(left_fit)
	# print(right_fit)

	left_lane_fun = np.poly1d(left_fit)
	right_lane_fun = np.poly1d(right_fit)

	# Generate x and y values for plotting
	ploty = np.linspace(0, out_img.shape[0]-1, out_img.shape[0])
	left_plotx = left_lane_fun(ploty)
	right_plotx = right_lane_fun(ploty)

	# Visualization
	# Colors in the left and right lane regions
	out_img[lefty, leftx] = [255, 0, 0]
	out_img[righty, rightx] = [0 ,0 , 255]

	# draw fit line(sue 9 stright line)
	for i in range(0, 9):
		cv2.line(out_img, (int(left_plotx[i*79]), int(ploty[i*79])), (int(left_plotx[(i+1)*79]), int(ploty[(i+1)*79])), (255,255,0),2)
		cv2.line(out_img, (int(right_plotx[i*79]), int(ploty[i*79])), (int(right_plotx[(i+1)*79]), int(ploty[(i+1)*79])), (255,255,0),2)

	# Plots the left and right polynomials on the lane lines
	# plt.plot(left_plotx, ploty, color='yellow')
	# plt.plot(right_plotx, ploty, color='yellow')

	# print(len(leftx))
	# print(len(ploty))
	return out_img 
Example 12
Project: Advanced_Lane_Lines   Author: ChengZhongShen   File: lane_detection.py    License: MIT License 5 votes vote down vote up
def get_polynomial(leftx, lefty, rightx, righty, img_size):


	left_fit = np.polyfit(lefty, leftx, 2)
	right_fit = np.polyfit(righty, rightx, 2)

	left_lane_fun = np.poly1d(left_fit)
	right_lane_fun = np.poly1d(right_fit)

	ploty = ploty = np.linspace(0, img_size[0]-1, img_size[0])
	left_fitx = left_lane_fun(ploty)
	right_fitx = right_lane_fun(ploty)

	return left_fitx, right_fitx, ploty 
Example 13
Project: Advanced_Lane_Lines   Author: ChengZhongShen   File: cal_curv.py    License: MIT License 5 votes vote down vote up
def measure_offset(leftx, lefty, rightx, righty, ym_per_pix=30/720, xm_per_pix=3.7/700):
	'''
	calculate the the offest from lane center
	'''
	# HYPOTHESIS : the camera is mounted at the center of the car
	# the offset of the lane center from the center of the image is 
	# distance from the center of lane
	
	# Transform pixel to meters
	leftx = leftx * xm_per_pix
	lefty = lefty * ym_per_pix
	rightx = rightx * xm_per_pix
	righty = righty * ym_per_pix

	# fit the polynomial
	left_fit_cr = np.polyfit(lefty, leftx, 2)
	right_fit_cr = np.polyfit(righty, rightx, 2)

	# Define y-value where we want radius of curvature
	# choose the maximum y-value
	y_eval = Y_MAX * ym_per_pix

	left_point = np.poly1d(left_fit_cr)(y_eval)
	right_point = np.poly1d(right_fit_cr)(y_eval)

	lane_center = (left_point + right_point) / 2
	image_center = X_MAX * xm_per_pix / 2

	offset = lane_center - image_center

	return offset 
Example 14
Project: keras-ctpn   Author: yizt   File: text_proposal_connector.py    License: Apache License 2.0 5 votes vote down vote up
def fit_y(self, X, Y, x1, x2):
        """
        一元线性函数拟合X,Y,并返回x1,x2的的函数值
        """
        len(X) != 0
        # 只有一个点返回 y=Y[0]
        if np.sum(X == X[0]) == len(X):
            return Y[0], Y[0]
        p = np.poly1d(np.polyfit(X, Y, 1))
        return p(x1), p(x2) 
Example 15
Project: keras-ctpn   Author: yizt   File: gt_utils.py    License: Apache License 2.0 5 votes vote down vote up
def linear_fit_y(xs, ys, x_list):
    """
    线性函数拟合两点(x1,y1),(x2,y2);并求得x_list在的取值
    :param xs:  [x1,x2]
    :param ys:  [y1,y2]
    :param x_list: x轴坐标点,numpy数组 [n]
    :return:
    """
    if xs[0] == xs[1]:  # 垂直线
        return np.ones_like(x_list) * np.mean(ys)
    elif ys[0] == ys[1]:  # 水平线
        return np.ones_like(x_list) * ys[0]
    else:
        fn = np.poly1d(np.polyfit(xs, ys, 1))  # 一元线性函数
        return fn(x_list) 
Example 16
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 17
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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)) 
Example 18
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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') 
Example 19
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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)]) 
Example 20
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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()) 
Example 21
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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()) 
Example 22
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 23
Project: recruit   Author: Frank-qlu   File: test_polynomial.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 24
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_poly1d(self):
        # Ticket #28
        assert_equal(np.poly1d([1]) - np.poly1d([1, 0]),
                     np.poly1d([-1, 1])) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_poly1d_nan_roots(self):
        # Ticket #396
        p = np.poly1d([np.nan, np.nan, 1], r=0)
        assert_raises(np.linalg.LinAlgError, getattr, p, "r") 
Example 26
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_poly_eq(self):
        # Ticket #554
        x = np.poly1d([1, 2, 3])
        y = np.poly1d([3, 4])
        assert_(x != y)
        assert_(x == x) 
Example 28
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
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)) 
Example 29
Project: lambda-packs   Author: ryfeus   File: waveforms.py    License: MIT License 5 votes vote down vote up
def _sweep_poly_phase(t, poly):
    """
    Calculate the phase used by sweep_poly to generate its output.

    See `sweep_poly` for a description of the arguments.

    """
    # polyint handles lists, ndarrays and instances of poly1d automatically.
    intpoly = polyint(poly)
    phase = 2 * pi * polyval(intpoly, t)
    return phase 
Example 30
Project: lambda-packs   Author: ryfeus   File: orthogonal.py    License: MIT License 5 votes vote down vote up
def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None,
                 limits=None, monic=False, eval_func=None):
        equiv_weights = [weights[k] / wfunc(roots[k]) for
                         k in range(len(roots))]
        mu = sqrt(hn)
        if monic:
            evf = eval_func
            if evf:
                knn = kn
                eval_func = lambda x: evf(x) / knn
            mu = mu / abs(kn)
            kn = 1.0
            
        # compute coefficients from roots, then scale
        poly = np.poly1d(roots, r=True)
        np.poly1d.__init__(self, poly.coeffs * float(kn))
        
        # TODO: In numpy 1.13, there is no need to use __dict__ to access attributes
        self.__dict__['weights'] = np.array(list(zip(roots,
                                                     weights, equiv_weights)))
        self.__dict__['weight_func'] = wfunc
        self.__dict__['limits'] = limits
        self.__dict__['normcoef'] = mu

        # Note: eval_func will be discarded on arithmetic
        self.__dict__['_eval_func'] = eval_func