Python numpy.polynomial.polynomial.polyfit() Examples

The following are 5 code examples of numpy.polynomial.polynomial.polyfit(). 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 also want to check out all available functions/classes of the module numpy.polynomial.polynomial , or try the search function .
Example #1
Source File: computer.py    From allesfitter with MIT License 6 votes vote down vote up
def baseline_hybrid_poly(*args):
    x, y, yerr_w, xx, params, inst, key = args
    polyorder = int(config.BASEMENT.settings['baseline_'+key+'_'+inst][-1])
    xx = (xx - x[0])/x[-1] #polyfit needs the xx-axis scaled to [0,1], otherwise it goes nuts
    x = (x - x[0])/x[-1] #polyfit needs the x-axis scaled to [0,1], otherwise it goes nuts
    if polyorder>=0:
        yerr_weights = yerr_w/np.nanmean(yerr_w)
        weights = 1./yerr_weights
        ind = np.isfinite(y) #polyfit can't handle NaN
        params_poly = poly.polyfit(x[ind],y[ind],polyorder,w=weights[ind]) #WARNING: returns params in reverse order than np.polyfit!!!
        baseline = poly.polyval(xx, params_poly) #evaluate on xx (!)
    else:
        raise ValueError("'polyorder' has to be > 0.")
    return baseline    



#==============================================================================
#::: calculate baseline: hybrid_spline (like Gillon+2012, but with a cubic spline)
#============================================================================== 
Example #2
Source File: FitDisp.py    From altanalyze with Apache License 2.0 6 votes vote down vote up
def disp(hgvfile):
    lab={}
    me=[]
    std=[]
    for line in open(hgvfile,'rU').xreadlines():
        data = line.rstrip()
        t = string.split(data,'\t')
        me.append(float(t[2]))
        std.append(float(t[1]))
        
    me=np.asarray(me)
    std=np.asarray(std)
    coefs = poly.polyfit(me, std, 2)
    ffit = poly.Polynomial(coefs)
    print len(ffit(me))
    np.savetxt("fitted.txt",ffit(me),delimiter="\t")
    fig1 = plt.figure()                                                                                           
    ax1 = fig1.add_subplot(111)                                                                                   
    ax1.scatter(me, std, facecolors='None')                                                                     
    ax1.plot(me, ffit(me))                                                                     
    plt.show() 
Example #3
Source File: rplot.py    From Computable with 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 #4
Source File: test_polynomial.py    From Computable with 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 #5
Source File: test_polynomial.py    From ImageFusion with 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])