示例#1
0
def poly_lsq(x, y, n, verbose=False, itmax=200):
    ''' Performs a polynomial least squares fit to the data,
    with errors! Uses scipy odrpack, but for least squares.

    IN:
       x,y (arrays) - data to fit
       n (int)      - polinomial order
       verbose      - can be 0,1,2 for different levels of output
                      (False or True are the same as 0 or 1)
       itmax (int)  - optional maximum number of iterations

    OUT:
       coeff -  polynomial coefficients, lowest order first
       err   - standard error (1-sigma) on the coefficients

    --Tiago, 20071114
    '''
    func = models.polynomial(n)
    mydata = odr.Data(x, y)
    myodr = odr.ODR(mydata, func, maxit=itmax)
    # Set type of fit to least-squares:
    myodr.set_job(fit_type=2)
    if verbose == 2:
        myodr.set_iprint(final=2)
    fit = myodr.run()
    # Display results:
    if verbose:
        fit.pprint()
    if fit.stopreason[0] == 'Iteration limit reached':
        print('(WWW) poly_lsq: Iteration limit reached, result not reliable!')
    # Results and errors
    coeff = fit.beta
    err = fit.sd_beta
    return coeff, err
示例#2
0
def poly_lsq(x,y,n,verbose=False,itmax=200):
    ''' Performs a polynomial least squares fit to the data,
    with errors! Uses scipy odrpack, but for least squares.
    
    IN:
       x,y (arrays) - data to fit
       n (int)      - polinomial order
       verbose      - can be 0,1,2 for different levels of output
                      (False or True are the same as 0 or 1)
       itmax (int)  - optional maximum number of iterations
       
    OUT:
       coeff -  polynomial coefficients, lowest order first
       err   - standard error (1-sigma) on the coefficients

    --Tiago, 20071114
    '''

    # http://www.scipy.org/doc/api_docs/SciPy.odr.odrpack.html
    # see models.py and use ready made models!!!!
    
    func   = models.polynomial(n)
    mydata = odr.Data(x, y)
    myodr  = odr.ODR(mydata, func,maxit=itmax)

    # Set type of fit to least-squares:
    myodr.set_job(fit_type=2)
    if verbose == 2: myodr.set_iprint(final=2)
          
    fit = myodr.run()

    # Display results:
    if verbose: fit.pprint()

    if fit.stopreason[0] == 'Iteration limit reached':
        print '(WWW) poly_lsq: Iteration limit reached, result not reliable!'

    # Results and errors
    coeff = fit.beta[::-1]
    err   = fit.sd_beta[::-1]

    return coeff, err
示例#3
0
文件: fitting.py 项目: vlslv/helita
def poly_lsq(x, y, n, verbose=False, itmax=200):
    """
    Performs a polynomial least squares fit to the data,
    with errors! Uses scipy odrpack, but for least squares.

    Parameters
    ----------
    x, y : 1-D arrays
        Data to fit.
    n : int
        Polynomial order
    verbose : bool or int, optional
        Can be 0,1,2 for different levels of output (False or True
        are the same as 0 or 1)
    itmax : int, optional
        Maximum number of iterations.

    Returns
    -------
    coeff :  1-D array
        Polynomial coefficients, lowest order first.
    err :  1-D array
        Standard error (1-sigma) on the coefficients.
    """
    func = models.polynomial(n)
    mydata = odr.Data(x, y)
    myodr = odr.ODR(mydata, func, maxit=itmax)
    # Set type of fit to least-squares:
    myodr.set_job(fit_type=2)
    if verbose == 2:
        myodr.set_iprint(final=2)
    fit = myodr.run()
    # Display results:
    if verbose:
        fit.pprint()
    if fit.stopreason[0] == 'Iteration limit reached':
        print('(WWW) poly_lsq: Iteration limit reached, result not reliable!')
    # Results and errors
    coeff = fit.beta
    err = fit.sd_beta
    return coeff, err
lwc = float(lines[1].strip())
lwhmag = float(lines[2].strip())
'''
################################################################################
'''


# def funtion
def linear_reg_fix_slope(c, x):
    from numpy import log10, zeros_like
    grd = grad  # set gradient
    ans = c[0] + x * grd
    return ans


linreg = models.polynomial(1)

im = [7.5, 8.0]
isi = [0.2, 0.1]
'''
################################################################################
'''
# set data
ftypes = ['Intraslab', 'Outer Rise', 'Strike-Slip']
grads = [lengrd1, widgrd1, areagrd1, mxsgrd, avsgrd, lwgrd]
fmag = [intra_fmag, outer_fmag, trans_fmag]
flen = [intra_flen, outer_flen, trans_flen]
fwid = [intra_fwid, outer_fwid, trans_fwid]
farea = [intra_farea, outer_farea, trans_farea]
fmxs = [intra_fmxs, outer_fmxs, trans_fmxs]
favs = [intra_favs, outer_favs, trans_favs]
示例#5
0
文件: Analysis.py 项目: robios/PyTES
def fit_offset(pha, offset, sigma=1, prange=None, orange=None, method='ols', flip=False):
    """
    Fit a pha and an offset (DC level)
    
    Parameters (and their default values):
        pha:    pha data (array-like)
        offset: offset data (array-like)
        sigma:  sigmas allowed for median filter (Default: 1)
        prange: a tuple of range for pha to fit if not None (Default: None)
        orange: a tuple of range for offset to fit if not None (Default: None)
        method: fitting method from ols (ordinal least squares)
                or odr (orthogonal distance regression) (Default: ols)
        flip:   flip pha and offset when fitting if True (Default: False)
    
    Return ((a, b), coef):
        a, b:   fitting results to pha = a*(1+b*offset)
        coef:   correlation coefficient
    """

    # Sanity check
    if len(pha) != len(offset):
        raise ValueError("data length of pha and offset does not match")
    
    pha = np.asarray(pha)
    offset = np.asarray(offset)
    
    # Reduction
    if prange is not None:
        pmask = (pha >= prange[0]) & (pha <= prange[1])
    else:
        pmask = median_filter(pha, sigma=sigma)
    
    if orange is not None:
        omask = (offset >= orange[0]) & (offset <= orange[1])
    else:
        omask = median_filter(offset, sigma=sigma)
    
    mask = pmask & omask
    
    # Correlation coefficient
    coef = np.corrcoef(pha[mask], offset[mask])[0,1]
    
    # Fitting to a*x+b
    if method.lower() == 'ols':
        if flip:
            _a, _b = np.polyfit(pha[mask], offset[mask], 1)
        else:
            _a, _b = np.polyfit(offset[mask], pha[mask], 1)
    elif method.lower() == 'odr':
        f = models.polynomial(1)
        if flip:
            data = odrpack.Data(pha[mask], offset[mask])
        else:
            data = odrpack.Data(offset[mask], pha[mask])
        odr = odrpack.ODR(data, f, maxit=100)
        fit = odr.run()
        _a, _b = fit.beta[::-1]
    else:
        raise ValueError('Unknown method: %s' % method)
    
    if flip:
        a = -_b/_a
        b = -1/_b
    else:
        a = _b
        b = _a/_b
    
    return (a, b), coef
示例#6
0
coeftxt = 'Function,a,b,SEa,SEb,sig,Condition\n'

# make uncertainty arrays for weighting for ODR
reg_logMo = (mw2m0(array(reg_fmag)))

#sx = ones(len(reg_fmag))*0.1 # uniform uncertainty of 0.2 mu
#sx = ones(len(reg_fmag))*0.2
im = [7.5, 8.0]
isi = [0.2, 0.1]
sx = interp(reg_fmag, im, isi)
#idx = reg_fmag >= 8.0
#sx[idx] = 0.1
sy = sx

# do ODR on raw data
func = models.polynomial(1)
#data = Data(array(inter_fmag),log10(array(inter_flen)))
data = odrpack.RealData(array(reg_fmag), log10(array(reg_flen)), sx=sx, sy=sy)

# set data
mrng = arange(7., 9.61, 0.01)
'''
########################################################################################
test linear vs ODR linear vs ODR bi-linear
'''

# regress M vs L - ODR
beta0 = [-2.7, 0.62]
odr = ODR(data, func, beta0)
odr.set_job(fit_type=0)  #if set fit_type=2, returns the same as leastsq
out = odr.run()