Python numpy.polynomial.polynomial.polyfit() Examples

The following are code examples for showing how to use numpy.polynomial.polynomial.polyfit(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: xwavecal   Author: gmbrandt   File: overlap_utils.py    MIT License 6 votes vote down vote up
def _refine_fit(self, coeffs, b_lines, r_lines, pixel_tol=10, deg=2):
        """
        :param coeffs: array-like.
                       array of coefficients [a, b, c, ...] for g(x) = a + b*x + c*x^2 etc..
        :param b_lines: array-like
                        x-locations (pixel-locations) of emission lines from the blue order.
        :param r_lines: array-like
                        x-locations (pixel-locations) of emission lines from the red order.
        :param pixel_tol: tolerance for g(xr) - xb for the peaks at xr and xb to be considered
                          a matched-peak (i.e. duplicates of one-another). Where xr is the pixel
                          coordinate of the peak from the red order, and xb is the pixel coordinate
                          of the peak from the blue order.
        :param deg: polynomial degree of the mapping g(x)
        :return: ndarray
                 coefficients for g(x), [a, b, c,...] which minimize the chi^2 of (g(xr) - xb) for all
                 matched peaks (xr, xb) within the overlap.
        """
        peaks = poly.polyval(r_lines, coeffs)
        blue_peaks = interpolate.interp1d(b_lines, b_lines, kind='nearest', bounds_error=False,
                                          fill_value=(np.min(b_lines), np.max(b_lines)))(peaks)
        if np.count_nonzero(np.isclose(blue_peaks, peaks, atol=pixel_tol)) >= deg + 1:
            coeffs = poly.polyfit(r_lines[np.isclose(blue_peaks, peaks, atol=pixel_tol)],
                                  blue_peaks[np.isclose(blue_peaks, peaks, atol=pixel_tol)], deg)
        return coeffs 
Example 2
Project: iot   Author: jdupl   File: analytics.py    GNU General Public License v3.0 6 votes vote down vote up
def _get_polynomial(sensor_uuid, start, stop=dt.datetime.now()):
    """
    Get a polynomial aproximation of the soil humidity function from data.
    """
    x = []
    y = []

    records = HygroRecord.query \
        .filter(HygroRecord.sensor_uuid == sensor_uuid) \
        .filter(between(HygroRecord.timestamp, start, stop)) \
        .order_by(HygroRecord.timestamp).all()

    for r in records:
        x.append((r.timestamp - start))
        y.append(int(r.value))

    if len(x) > 0:
        return polynomial.polyfit(x, y, 1) 
Example 3
Project: RainMaker   Author: granttremblay   File: rainmaker.py    MIT License 5 votes vote down vote up
def fit_polynomial(data, ln_xray_property, deg, whatIsFit):
    """Fit a DEG-order polynomial in x, y space.

    numpy.polynomial.polinomial.polyfit() returns coefficients,
    from 0th order first to N-th order last (note that this is
    *opposite* from how np.polyfit behaves!).
    """
    radiuspackage = extrapolate_radius(data)

    r = radiuspackage[0]
    ln_r = radiuspackage[1]
    r_fine = radiuspackage[2]
    ln_r_fine = radiuspackage[4]

    print("Now fitting    |" + "  " + make_number_ordinal(deg) +
          " order polynomial to " + whatIsFit)

    coeffs = poly.polyfit(ln_r, ln_xray_property, deg)

    # polyval() is used to assemble cubic fit:
    # $p(x) = c_0 + c_1 x + c_2 x^2 + c3 x^3$
    # where c_n are the coeffs returned by polyfit()
    ln_fit = poly.polyval(ln_r, coeffs)
    fit = np.exp(ln_fit)

    # Now use these coefficients to extrapolate fit
    # across larger radius

    ln_fit_fine = poly.polyval(ln_r_fine, coeffs)
    fit_fine = np.exp(ln_fit_fine)

    fitpackage = (fit, r, fit_fine, r_fine, coeffs)

    return fitpackage 
Example 4
Project: Computable   Author: ktraunmueller   File: rplot.py    MIT License 5 votes vote down vote up
def work(self, fig=None, ax=None):
        """Draw the polynomial fit on matplotlib figure or axis

        Parameters:
        -----------
        fig: matplotlib figure
        ax: matplotlib axis

        Returns:
        --------
        a tuple with figure and axis objects
        """
        if ax is None:
            if fig is None:
                return fig, ax
            else:
                ax = fig.gca()
        from numpy.polynomial.polynomial import polyfit
        from numpy.polynomial.polynomial import polyval
        x = self.data[self.aes['x']]
        y = self.data[self.aes['y']]
        min_x = min(x)
        max_x = max(x)
        c = polyfit(x, y, self.degree)
        x_ = np.linspace(min_x, max_x, len(x))
        y_ = polyval(x_, c)
        ax.plot(x_, y_, lw=self.lw, c=self.colour)
        return fig, ax 
Example 5
Project: bezier   Author: dhermes   File: _algebraic_intersection.py    Apache License 2.0 5 votes vote down vote up
def _to_power_basis23(nodes1, nodes2):
    r"""Compute the coefficients of an **intersection polynomial**.

    Helper for :func:`to_power_basis` in the case that the first curve is
    degree two and the second is degree three. In this case, B |eacute| zout's
    `theorem`_ tells us that the **intersection polynomial** is
    degree :math:`2 \cdot 3` hence we return seven coefficients.

    .. note::

       This uses a least-squares fit to the function evaluated at the
       Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the
       coefficients may be less stable than those produced for smaller
       degrees.

    Args:
        nodes1 (numpy.ndarray): The nodes in the first curve.
        nodes2 (numpy.ndarray): The nodes in the second curve.

    Returns:
        numpy.ndarray: ``7``-array of coefficients.
    """
    evaluated = [
        eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB7
    ]
    return polynomial.polyfit(_CHEB7, evaluated, 6) 
Example 6
Project: bezier   Author: dhermes   File: _algebraic_intersection.py    Apache License 2.0 5 votes vote down vote up
def _to_power_basis_degree8(nodes1, nodes2):
    r"""Compute the coefficients of an **intersection polynomial**.

    Helper for :func:`to_power_basis` in the case that B |eacute| zout's
    `theorem`_ tells us the **intersection polynomial** is degree
    :math:`8`. This happens if the two curves have degrees one and eight
    or have degrees two and four.

    .. note::

       This uses a least-squares fit to the function evaluated at the
       Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the
       coefficients may be less stable than those produced for smaller
       degrees.

    Args:
        nodes1 (numpy.ndarray): The nodes in the first curve.
        nodes2 (numpy.ndarray): The nodes in the second curve.

    Returns:
        numpy.ndarray: ``9``-array of coefficients.
    """
    evaluated = [
        eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB9
    ]
    return polynomial.polyfit(_CHEB9, evaluated, 8) 
Example 7
Project: bezier   Author: dhermes   File: _algebraic_intersection.py    Apache License 2.0 5 votes vote down vote up
def _to_power_basis33(nodes1, nodes2):
    r"""Compute the coefficients of an **intersection polynomial**.

    Helper for :func:`to_power_basis` in the case that each curve is
    degree three. In this case, B |eacute| zout's `theorem`_ tells us
    that the **intersection polynomial** is degree :math:`3 \cdot 3`
    hence we return ten coefficients.

    .. note::

       This uses a least-squares fit to the function evaluated at the
       Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the
       coefficients may be less stable than those produced for smaller
       degrees.

    Args:
        nodes1 (numpy.ndarray): The nodes in the first curve.
        nodes2 (numpy.ndarray): The nodes in the second curve.

    Returns:
        numpy.ndarray: ``10``-array of coefficients.
    """
    evaluated = [
        eval_intersection_polynomial(nodes1, nodes2, t_val)
        for t_val in _CHEB10
    ]
    return polynomial.polyfit(_CHEB10, evaluated, 9) 
Example 8
Project: bladeBench   Author: Extent421   File: logReader.py    MIT License 5 votes vote down vote up
def getThrustFit(sample, index):
	# thrust / RPM
	x = []
	y = []
	smooth = smoother()
	#sample, index = readLog('C:\\Users\\markm\\Documents\\Drones\\PropBenchmarks\\bladeShapes\\rxTri.txt')
	for sampleIndex in index['RPM']:
		rpm = sample[sampleIndex]['RPM']
		time = sample[sampleIndex]['Time']
		thrust = sample[sampleIndex]['Thrust']
		if rpm > 45000: continue

		smooth.add( rpm )
		smoothedValue = round(smooth.get(), 3 )
		x.append(smoothedValue)
		y.append(thrust)

	xTrim = x[:int(len(x)*0.5)]
	yTrim = y[:int(len(y)*0.5)]
	#Calculate trendline
	x = numpy.linspace(0, 40000, num=len(xTrim))
	order = 2
	coeffs = poly.polyfit(xTrim,yTrim, order)
	y = poly.polyval(x, coeffs)

	return x, y 
Example 9
Project: senior-design   Author: james-tate   File: test_polynomial.py    GNU General Public License v2.0 5 votes vote down vote up
def test_polyfit(self) :
        def f(x) :
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1],    [1],     -1)
        assert_raises(TypeError,  poly.polyfit, [[1]],  [1],      0)
        assert_raises(TypeError,  poly.polyfit, [],     [1],      0)
        assert_raises(TypeError,  poly.polyfit, [1],    [[[1]]],  0)
        assert_raises(TypeError,  poly.polyfit, [1, 2], [1],      0)
        assert_raises(TypeError,  poly.polyfit, [1],    [1, 2],   0)
        assert_raises(TypeError,  poly.polyfit, [1],    [1],   0, w=[[1]])
        assert_raises(TypeError,  poly.polyfit, [1],    [1],   0, w=[1,1])

        # Test fit
        x = np.linspace(0,2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y,y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3,coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw,yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) 
Example 10
Project: kraksat-receiver   Author: KrakSat-2016   File: kundt.py    MIT License 5 votes vote down vote up
def frequency(points):
        """
        Use polynomial approximation to find resonance frequency
        :param points: peak points
        :return: resonance frequency in Hz
        """
        coefficients = polyfit(list(map(lambda x: x[0], points)),
                               list(map(lambda x: x[1], points)), 5)
        result, amplitude = 0, 0
        for i in arange(points[0][0], points[-1][0], -0.1):
            if polyval(i, coefficients) > amplitude:
                amplitude = polyval(i, coefficients)
                result = i
        return result 
Example 11
Project: cnidaria   Author: sauloal   File: rplot.py    MIT License 5 votes vote down vote up
def work(self, fig=None, ax=None):
        """Draw the polynomial fit on matplotlib figure or axis

        Parameters:
        -----------
        fig: matplotlib figure
        ax: matplotlib axis

        Returns:
        --------
        a tuple with figure and axis objects
        """
        if ax is None:
            if fig is None:
                return fig, ax
            else:
                ax = fig.gca()
        from numpy.polynomial.polynomial import polyfit
        from numpy.polynomial.polynomial import polyval
        x = self.data[self.aes['x']]
        y = self.data[self.aes['y']]
        min_x = min(x)
        max_x = max(x)
        c = polyfit(x, y, self.degree)
        x_ = np.linspace(min_x, max_x, len(x))
        y_ = polyval(x_, c)
        ax.plot(x_, y_, lw=self.lw, c=self.colour)
        return fig, ax 
Example 12
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_polynomial.py    GNU General Public License v3.0 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 13
Project: Computable   Author: ktraunmueller   File: test_polynomial.py    MIT License 4 votes vote down vote up
def test_polyfit(self) :
        def f(x) :
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1],    [1],     -1)
        assert_raises(TypeError,  poly.polyfit, [[1]],  [1],      0)
        assert_raises(TypeError,  poly.polyfit, [],     [1],      0)
        assert_raises(TypeError,  poly.polyfit, [1],    [[[1]]],  0)
        assert_raises(TypeError,  poly.polyfit, [1, 2], [1],      0)
        assert_raises(TypeError,  poly.polyfit, [1],    [1, 2],   0)
        assert_raises(TypeError,  poly.polyfit, [1],    [1],   0, w=[[1]])
        assert_raises(TypeError,  poly.polyfit, [1],    [1],   0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 14
Project: 3dprinteros-client   Author: panasevychol   File: test_polynomial.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 15
Project: 3dprinteros-client   Author: panasevychol   File: test_polynomial.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 16
Project: linear_neuron   Author: uglyboxer   File: test_polynomial.py    MIT License 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 17
Project: ImageFusion   Author: pfchai   File: test_polynomial.py    MIT License 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 18
Project: motif   Author: rabitt   File: utils.py    MIT License 4 votes vote down vote up
def _fit_poly(n_poly_degrees, signal, grid=None, norm=False):
    '''Fit a signal to a polynomial. If grid is not given, assumes a uniform
    grid between 0 and 1 of length len(signal).

    Parameters
    ----------
    n_poly_degrees : int
        Number of polynomial degrees to fit.
    signal : np.array
        Array of values to fit.
    grid : np.array or None, default=None
        Array of x-values, or None.
        If None, uses a uniform time grid between 0 and 1.
    norm : bool, default=False
        If True, scales the signal to be between 0 and 1
        If False, the signal is not altered.

    Returns
    -------
    poly_coeff : np.array
        The coefficients of the polynomial.
    poly_approx : np.array
        The polynomial approximation of the signal.
    residual : np.array
        The pointwise difference between the signal and the polynomial.

    '''
    n_points = len(signal)
    if n_points < n_poly_degrees + 1:
        raise ValueError('signal must be at least as long as n_poly_degrees')

    if norm:
        signal = signal - np.min(signal)
        max_val = np.max(signal)
        if max_val > 0:
            signal = signal / max_val

    if grid is None:
        grid = np.linspace(-1, 1, num=n_points)
    else:
        grid = grid - np.mean(grid)

    poly_coeff = Poly.polyfit(grid, signal, n_poly_degrees)
    poly_approx = Poly.polyval(grid, poly_coeff)
    residual = signal - poly_approx

    return poly_coeff, poly_approx, residual 
Example 19
Project: PYPIC   Author: max614   File: test_polynomial.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) 
Example 20
Project: neurotools   Author: michaelerule   File: regressions.py    GNU General Public License v3.0 4 votes vote down vote up
def power_law(X,Y,W):
    '''
    Fit a power law, but with error terms computed by r^2 in
    the original space.
    
    Parameters
    ----------
    X: List of distances
    Y: List of amplitudes
    W: Weights for points   
    
    Returns
    ------- 
    '''
    '''
    power law form is `np.log(y)=a*np.log(x)+b` or `y = b*x^a`

    initial best guess using linear regression.

    result = power_law(X,Y,1/X**16)
    a,b = result.x

    EPS = 1e-10
    use = (X>EPS)&(Y>EPS)
    a,b = weighted_least_squares(np.log(X)[use],np.log(Y)[use],W[use]).x
    plot(sorted(X),b*arr(sorted(X))**a)

    from numpy.polynomial.polynomial import polyfit

    X,Y = ravel(f),ravel(y[:,i])
    a,b = power_law(X,Y,1/X**2)
    plot(sorted(X),b*arr(sorted(X))**a)
    '''
    X = np.float64(X)
    Y = np.float64(Y)
    EPS = 1e-10
    use = (X>EPS)&(Y>EPS)
    a,b = polyfit(np.log(X)[use],np.log(Y)[use],1,w=W[use])
    '''
    def objective(ab):
        a,b = (a,b)
        z = np.exp(b+a*np.log(X))
        obj = np.sum((W*(Y-z)**2)[use])
        print(a,b,obj)
        return obj
    result = minimize(objective,[a,b])
    '''
    return a,np.exp(b) 
Example 21
Project: cnidaria   Author: sauloal   File: test_polynomial.py    MIT License 4 votes vote down vote up
def test_polyfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, poly.polyfit, [1], [1], -1)
        assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
        assert_raises(TypeError, poly.polyfit, [], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
        assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = poly.polyfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(poly.polyval(x, coef3), y)
        #
        coef4 = poly.polyfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(poly.polyval(x, coef4), y)
        #
        coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # test weighting
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        yw[0::2] = 0
        wcoef3 = poly.polyfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # test scaling with complex values x points whose square
        # is zero when summed.
        x = [1, 1j, -1, -1j]
        assert_almost_equal(poly.polyfit(x, x, 1), [0, 1])