예제 #1
0
def odRegress(x, y, weights=[], linreg=None):
    # Produce Orthogonal Data Reduction (fit) for the passed x,y pairings.
    # Returns: [fit parameters] , [parm. errors], [[covariance matrix]],
    #           [estimated error in x vars], [estimated error in y vars]
    # Code modified from: Robin Wilson, see the site for copyright notice:
    # http://blog.rtwilson.com/orthogonal-distance-regression-in-python/
    #
    # x,y both arrays of same length
    assert len(x) == len(y)

    if linreg is None:
        linreg = stats.linregress(x, y)

    # Linear function defined above
    model = odr.Model(Linear)
    if len(weights) != len(x):
        data = odr.Data(x, y=y)
    else:
        data = odr.Data(x, y=y, we=weights)

    # Bad variable naming, I know...so caps to avoid(?) confusion. :P
    ODR = odr.ODR(data, model, beta0=linreg[0:2])

    out = ODR.run()
    return out.beta, out.sd_beta, out.cov_beta, out.delta, out.eps
예제 #2
0
    def __init__(self, list_of_points, pointcloud):
        self.points = list_of_points 
        model = odr.Model(odr_linear_definition)

        #extract coordinates from list of points
        x = [pointcloud.points[p][0] for p in list_of_points]
        y = [pointcloud.points[p][1] for p in list_of_points]

        #calculate standard errors along dimensions or something
        wd = 1/(np.std(x)**2) #FIXME: I have no idea what this is 
        we = 1/(np.std(y)**2) #or if I did it right

        #fit ODR
        data = odr.Data(x, y, wd=wd, we=we)
        self.odr = odr.ODR(data, model, beta0=[1., 1.])
        self.odr.run()

        params = self.odr.output.beta 

        #apply bounds for start and end point
        bounds = []
        for index in [-1, 0]:
            m, b = params 
            p_x, p_y = pointcloud.points[self.points[index]]
            bounds.append(self._find_closest_input_val(m, b, p_x, p_y))
        bounds.sort()

        #save the params in nice formats
        params = {"m": params[0], "b": params[1], "low": bounds[0], "high": bounds[1]}
        self.params = params
        self.start_point = [params["low"], params["low"] * params["m"] + params["b"]]
        self.end_point = [params["high"], params["high"] * params["m"] + params["b"]]
예제 #3
0
def fitLine(data):
    start = 0
    end = 0
    rest = 0
    listOfSpeeds = []
    errors = []
    frameNo = []
    metEnd = False
    for i in xrange(len(data) - 1):
        rest += 1
        frameNo.append(i)
        if data[i + 1] < data[i] and metEnd == False:
            start = i + 9
            metEnd = True
        if data[i + 1] > data[i] and rest > 10:
            metEnd = False
            rest = 0
            end = i
            x = frameNo[start:end]
            y = data[start:end]
            myodr = odr.ODR(odr.Data(frameNo[start:end], data[start:end]),
                            odr.Model(str8Line),
                            beta0=[-0.5, 70])
            result = myodr.run()
            fitLine = result.beta[0] * frameNo[start:end] + result.beta[1]
            listOfSpeeds.append(result.beta[0])
            errors.append(result.sd_beta[0])
    return np.mean(listOfSpeeds), np.mean(errors)
예제 #4
0
파일: calibration.py 프로젝트: lspgl/csat
    def optimize_odr(self, data):
        """
        Calculate the orthogonal distance regression for a dataset fitted to a circle

        Parameters
        ----------
        data: 2D array
            x-y coordinates of all datapoints in all images

        Returns
        -------
        calibration: float array
            array of midpoint coordinates and respective radii
        """
        self.grid = data[0][1]
        self.grid_stack = np.array(list(self.grid) * len(data))
        x = np.array(data)[:, 0, :].flatten()
        lsc_data = odr.Data(x, y=1)
        lsc_model = odr.Model(fcn=self.f_odr_multivariate,
                              implicit=True,
                              estimate=self.calc_estimate_odr_multivariate)
        lsc_odr = odr.ODR(lsc_data, lsc_model)
        lsc_out = lsc_odr.run()
        lsc_out.pprint()
        opt = lsc_out.beta

        calibration = []
        for i in range(len(data)):
            xc = opt[i * 2]
            yc = opt[i * 2 + 1]
            r = opt[-1]
            package = [xc, yc, r]
            calibration.append(package)
        return calibration
def autoCorrelation(xData,maxRange):                                    
    """
    A function to calculate the auto correlation time of a data set.
    :xData: the data for which the time is found.
    :maxRange: the range over which an exponential decay is fitted(=100).
    """
    maxTp = maxRange                                                    # the maximum distance between values in a list, eg List[0] and List[100]
    xMean = np.average(xData)                                           # finds the mean of all values
    C = np.zeros(maxTp)                                                 # numpy arrays to hold Correlation
    tPr = np.zeros(maxTp)                                               # different Correlation times, t', No of elements between values
    for i in xrange(maxTp):
        xLen = xData.shape[0]
        runTot = 0
        for j in xrange(xLen-i):
            runTot+=xData[j]*xData[j+i]                                 # checks how correlated each bit is
        C[i]=(float(runTot)/float(xLen-i))
        tPr[i]=(i)
    C = C - xMean**2.
    
    lnC = np.log(C)
    myodr = odr.ODR(odr.Data(tPr,lnC), odr.Model(str8Line), beta0=[-1.0, -1.0])
    result = myodr.run()
    fitLine = result.beta[0]*tPr + result.beta[1]
    
    #pl.plot(tPr,lnC)
    #pl.plot(tPr,fitLine)
    #pl.show()
    
    correlationTime = -1.0/result.beta[0]
    if np.isnan(correlationTime):return 700
    return correlationTime
예제 #6
0
def autoCorrelation(xData):
    maxTp = 400

    xMean = np.average(xData)
    C = np.zeros(maxTp)
    tPr = np.zeros(maxTp)
    for i in xrange(maxTp):
        xLen = xData.shape[0]
        runTot = 0
        for j in xrange(xLen - i):
            runTot += xData[j] * xData[j + i]
        C[i] = (float(runTot) / float(xLen - i))
        tPr[i] = (i)
    C = C - xMean**2.

    lnC = np.log(C)
    myodr = odr.ODR(odr.Data(tPr, lnC),
                    odr.Model(str8Line),
                    beta0=[-0.00558, -1.0])
    result = myodr.run()
    fitLine = result.beta[0] * tPr + result.beta[1]

    pl.plot(tPr, lnC)
    pl.plot(tPr, fitLine)
    pl.show()

    correlationTime = -1.0 / result.beta[0]

    print correlationTime
    return correlationTime
예제 #7
0
    def fit_ellipse(self,
                    beta_i,
                    num_fitting_pts=5000,
                    ring_width=40,
                    num_high_pix=20):
        '''
        Fit an ellipse to a ring image
        ============================== 
        beta_i          - float tuple , ( x_center, y_center, x_radius, y_radius )
        num_fitting_pts - int, number of pixels to include in fit 
        ring_width      - int, width ring-like region on image that contains ring of interest (pixels units)
        num_high_pix    - int, remove this many pixels before running fit (removes artificial high pixels that might bias the fit)
        '''

        r = sqrt((self.x - beta_i[0])**2 + (self.y - beta_i[1])**2)
        self.img[r > beta_i[2] + ring_width / 2] = 0
        self.img[r < beta_i[2] - ring_width / 2] = 0

        img1 = self.img.ravel()
        self._remove_highest(img1, num_high_pix)

        num_pts = where(img1 > 0)[0].shape[0]
        if num_fitting_pts >= num_pts:
            num_fitting_pts = num_pts / 2

        inds = argsort(img1)[::-1][:num_fitting_pts]

        pts = row_stack([self.x1[inds], self.y1[inds]])
        lsc_data = odr.Data(pts, y=1)
        lsc_odr = odr.ODR(lsc_data, self.ellipse_model, beta_i)
        lsc_out = lsc_odr.run()
        return lsc_out.beta
def perform_odr(x, y, sx, sy):
    linear = odr.Model(f)
    mydata = odr.Data(x, y, wd=1./np.power(sx,2), we=1./np.power(sy,2))
    myodr = odr.ODR(mydata, linear, beta0=linreg[0:2])
    output = myodr.run()
    output.pprint()
    return output
예제 #9
0
    def odr(self, i, plot=False, eps=2):
        """Orthogonal distance regression for temporally concurrent points of overlapping time series. Uses :mod:`scipy.odr`.

        :param i: the 'join' index (``0`` is the index of the join between series ``0`` and ``1`` etc.)
        :param plot: whether or not to plot the given join
        :param eps: the ``eps`` param to be handed down to the :meth:`.dbscan` method for outlier detection
        :returns: dictionary with computed statistics, including the additive offset (key ``offs``)
        :rtype: :obj:`dict`

        """
        c = self.var.iloc[:, i:i + 2].dropna(0, 'any')

        # outliers are detected from the differenc between the two series
        diff = c.diff(1, 1).values[:, 1]
        k, labels = self.dbscan(diff, True, True, eps=eps)

        x, y = c.iloc[k].values.T
        o = odr.ODR(odr.Data(x, y), odr.models.unilinear, beta0=[1, 0]).run()
        diff = diff[k]
        offs = np.nanmean(diff)
        m = np.argmin(abs(diff - offs)) + np.where(k)[0].min()
        self.starts[i + 1] += m
        self.ends[i] = self.starts[i + 1] - 1

        if plot:
            fig, axs = plt.subplots(1, 2, figsize=(12, 5))
            t = c.index.values.astype('datetime64[s]').astype(float).reshape(
                (-1, 1))
            x, y = c.values.T
            for h in labels:
                pl = axs[0].plot(t[h], x[h], 'x')[0]
                axs[0].plot(t[h], y[h], '*', color=pl.get_color())
                axs[1].plot(x[h], y[h], 'x')
                axs[1].plot(o.xplus, o.y, 'r-')
            axs[1].plot(x, y, 'mo', mfc='none')
            axs[1].yaxis.tick_right()
            plt.show()
        else:
            idx = c.index.symmetric_difference(c.index[k])
            j = np.where(np.diff(idx) != self.delta)[0]
            if len(j) > 1:
                print('Complex outlier structure deteced at knot {}'.format(i))
            elif len(
                    j
            ) == 1:  # means there are outliers on either end of the overlap
                self.out.loc[idx[:j[0] + 1], 'outliers'] = i + 1
                self.out.loc[idx[j[0] + 1:], 'outliers'] = i
            elif len(
                    idx
            ) > 0:  # means there are outliers only in one of the two series
                self.out.loc[idx, 'outliers'] = i + int(idx[0] == c.index[0])
            return {
                'offs': offs,
                'kind': 'mean',
                'stdev': diff.std() / np.sqrt(len(diff)),
                'odr_slope': o.beta[0],
                'odr_offs': o.beta[1],
                'RSS1': np.mean(o.delta**2),
                'RSS2': np.mean(o.eps**2),
            }
예제 #10
0
def fit_circle(points):
    """
    fits a circle to the given points. The method has been adapted from
        http://wiki.scipy.org/Cookbook/Least_Squares_Circle
    The function returns an instance of Circle
    """
    def calc_dist(xc, yc):
        """ calculate the distance of each point from the center (xc, yc) """
        return np.linalg.norm(points - np.array([[xc, yc]]), axis=0)
    
    def circle_implicit(beta, x):
        """ implicit definition of the circle """
        return (x[0] - beta[0])**2 + (x[1] - beta[1])**2 - beta[2]**2

    # coordinates of the bary center
    x_m, y_m = np.mean(points, axis=0)

    # initial guess for parameters
    R_m = calc_dist(x_m, y_m).mean()
    beta0 = [x_m, y_m, R_m]    
    
    # for implicit function :
    #       data.x contains both coordinates of the points (data.x = [x, y])
    #       data.y is the dimensionality of the response
    lsc_data  = odr.Data(points.T, y=1)
    lsc_model = odr.Model(circle_implicit, implicit=True)
    lsc_odr   = odr.ODR(lsc_data, lsc_model, beta0)
    lsc_out   = lsc_odr.run()
    
    # collect result
    xc, yc, R = lsc_out.beta
    return shapes.Circle(xc, yc, R)
def fiting_test():
    a = 2.
    b = 3.
    N = 10
    x = np.linspace(-a, a, N)
    y = b * np.sqrt(1. - (x / a)**2)

    x += (2. * np.random.random(N) - 1.) * 0.1
    y += (2. * np.random.random(N) - 1.) * 0.1

    xx = np.array([x, y])

    mdr = odr.Model(f, implicit=True)
    mydata = odr.Data(xx, y=1)

    myodr = odr.ODR(mydata, mdr, beta0=[1., 2.])
    myoutput = myodr.run()
    myoutput.pprint()

    ax = plt.subplot(111, aspect='equal')
    plt.scatter(x, y)  # raw data with randomness

    ell = Ellipse(xy=(0., 0.),
                  width=2. * myoutput.beta[0],
                  height=2. * myoutput.beta[1],
                  angle=0.0)
    ell.set_facecolor('none')
    ax.add_artist(ell)  # fitted curve

    plt.show()
def fit_circle(x, y):

    x_m = np.mean(x)
    y_m = np.mean(y)

    def calc_R(xc, yc):
        """ calculate the distance of each 2D points from the center (xc, yc) """
        return np.sqrt((x - xc)**2 + (y - yc)**2)

    def f_3(beta, x):
        """ implicit definition of the circle """
        return (x[0] - beta[0])**2 + (x[1] - beta[1])**2 - beta[2]**2

    # initial guess for parameters
    R_m = calc_R(x_m, y_m).mean()
    beta0 = [x_m, y_m, R_m]

    # for implicit function :
    #       data.x contains both coordinates of the points (data.x = [x, y])
    #       data.y is the dimensionality of the response
    lsc_data = odr.Data(np.row_stack([x, y]), y=1)
    lsc_model = odr.Model(f_3, implicit=True)
    lsc_odr = odr.ODR(lsc_data, lsc_model, beta0)
    lsc_out = lsc_odr.run()

    xc_3, yc_3, R_3 = lsc_out.beta
    Ri_3 = calc_R(xc_3, yc_3)
    residu_3 = sum((Ri_3 - R_3)**2)
    return xc_3, yc_3, R_3, residu_3
예제 #13
0
 def fit_odr(data, correlant, odr_function, poly_order, weights):
     if weights == 'relative':
         std = 0.1
         mydata = _odr.RealData(
             data, correlant, sx=data * std, sy=correlant *
             std)  # , wd=1. / self.sx ** 2, we=1. / self.sy ** 2)
     elif weights == 'absolute':
         sx, sy = (1, 1)
         mydata = _odr.Data(data,
                            correlant,
                            wd=1. / sx**2,
                            we=1. / sy**2)
     else:
         raise ValueError('weights has to be scalar or absolute')
     if odr_function != 'linear':
         raise (
             'only "linear" allowed at this point, programming required!'
         )
     model = _odr.polynomial(poly_order)
     myodr = _odr.ODR(mydata, model)
     myoutput = myodr.run()
     odr_res = {
         'model': myodr,
         'output': myoutput,
         'function': _np.polynomial.Polynomial(myoutput.beta)
     }
     return odr_res
def perform_odr(x, y, xerr, yerr):
    quadr = odr.Model(odr_line)
    mydata = odr.Data(x, y, wd=1. / xerr, we=1. / yerr)
    #mydata = odr.Data(x, y)
    myodr = odr.ODR(mydata, quadr, beta0=[0., 0.])
    output = myodr.run()
    return output
예제 #15
0
    def _fit_a_model(self, model, param_guess):
#       use odr module to fit data to model
        self.pts = np.row_stack( [self.x1D[ self.fit_indices], 
                            self.y1D[ self.fit_indices]])
        lsc_data = odr.Data( self.pts , y=1)
        lsc_odr = odr.ODR( lsc_data, model, param_guess)
        lsc_out = lsc_odr.run()
        self.beta_fit = lsc_out.beta
def getOutput(xa, ya):
    def f(B, x):
        return B[0]*x+B[1]
    linear = odr.Model(f)
    mydata = odr.Data(xa, ya)
    myodr = odr.ODR(mydata, linear, beta0=[1., 10.])
    myoutput = myodr.run()
    return myoutput
예제 #17
0
 def lin_fit(self, C):
     ''' Perform orthogonal linear regression on this Cluster.
         The slope and intercept are stored as a tuple in the field <linear>'''
     linear_fit = odr.Model(lin_func)
     data = odr.Data(C * self.t_co, self.v_co)  # y-axis is frequency
     odr_inst = odr.ODR(data, linear_fit, beta0=[0.0, self.v_mean])
     output = odr_inst.run()
     (slope, intercept) = output.beta[0], output.beta[1]
     self.linear = (C * slope, intercept)
예제 #18
0
def gap_filler(x, y, R, center, fill_density=0.1):
    """
    Returns N points to fill in a gap

    Parameters
    ----------
    x: sequence
        x = (x_left, x_right)
    y: sequence
        y = (y_left, y_right)
    R: float
        initial guess at average radius
    center: `np.ndarray`
        initial guess at the center of the ellipse
    N: int
        The number of points to return, defaults to 15

    Returns: `np.ndarray`
        A 2xN `np.ndarray` [x_vals, y_vals]
    """
    xl, xr = x
    yl, yr = y

    R2 = R * R

    a = c = 1 / R2
    b = 0
    d = -center[0] / R2
    f = -center[1] / R2

    p0 = (a, b, c, d, f)
    data = sodr.Data((np.hstack(x), np.hstack(y)), 1)
    model = sodr.Model(_e_funx, implicit=1)
    worker = sodr.ODR(data, model, p0)
    out = worker.run()
    #out = worker.restart()

    ap, bp, t0, x0, y0 = gen_to_parm(out.beta)

    if np.any(np.isnan([ap, bp, t0, x0, y0])):
        #        print out.beta
        #        print ap, bp, t0, x0, y0
        raise EllipseException('parameters contain NaN')
    theta_start = np.mod(np.arctan2(yl[-1] - y0, xl[-1] - x0), 2 * np.pi)
    theta_end = np.mod(np.arctan2(yr[0] - y0, xr[0] - x0), 2 * np.pi)
    if theta_end < theta_start:
        theta_end += 2 * np.pi

    N = int((theta_end - theta_start) * fill_density * (ap + bp) / 2)
    #    print theta_start, theta_end, (ap + bp) / 2, N
    if N < 1:
        print('gap_filler: under fill')
        N = 1

    theta_list = np.linspace(theta_start, theta_end, N + 2)[1:-1]

    return gen_ellipse(ap, bp, t0, x0, y0, theta_list)
예제 #19
0
def autoCorrelation(xData, maxRange, plot, col):
    """
    A function to calculate the auto correlation time of a data set.
    :xData: the data for which the time is found.
    :maxRange: the range over which an exponential decay is fitted(=100).
    """
    maxTp = maxRange  # the maximum distance between values in a list, eg List[0] and List[100]
    xMean = np.average(xData)  # finds the mean of all values
    C = np.zeros(maxTp)  # numpy arrays to hold Correlation
    tPr = np.zeros(
        maxTp
    )  # different Correlation times, t', No of elements between values
    for i in xrange(maxTp):
        xLen = xData.shape[0]
        runTot = 0
        for j in xrange(xLen - i):
            runTot += xData[j] * xData[j +
                                       i]  # checks how correlated each bit is
        C[i] = (float(runTot) / float(xLen - i))
        tPr[i] = (i)
    C = C - xMean**2.

    lnC = np.log(np.absolute(C))

    myodr = odr.ODR(odr.Data(tPr, lnC),
                    odr.Model(str8Line),
                    beta0=[-0.00558, -1.0])
    print myodr.beta0

    result = myodr.run()
    print result.beta
    print result.sd_beta

    print result.sd_beta / (result.beta**2.0)

    chisq = result.res_var
    print chisq

    if chisq < 0.001: chisq = 1.09

    fitLine = result.beta[0] * tPr + result.beta[1]
    correlationTime = -1.0 / result.beta[0]

    axarr[plot].plot(tPr,
                     lnC,
                     color=col,
                     label="t*={:.1f}".format(correlationTime))
    axarr[plot].plot(tPr,
                     fitLine,
                     "k--",
                     label=("$\chi^{2}$=" + "{:.2f}".format(chisq)),
                     linewidth=3)
    axarr[plot].legend(loc="best")

    return correlationTime
예제 #20
0
    def fit_odr(self, p0):
        from scipy import odr
        model = odr.Model(self.func)
        data = odr.Data(self._xdata, self._ydata)
        fit = odr.ODR(data, model, p0, maxit=100)
        fit.set_job(fit_type=0)  #0 = LSQ, 1 = EXPlicit
        out = fit.run()

        self._fit_params = out.beta
        self._fit_err = out.sd_beta
        return self._fit_params
예제 #21
0
    def _fit_a_model_fast(self, model, param_guess):
#       use odr module to fit data to model
        self.pts = np.row_stack( [self.x1D[ self.fit_indices], 
                            self.y1D[ self.fit_indices]])
        
        lsc_data = odr.Data( self.pts , y=1)
        lsc_odr   = odr.ODR(lsc_data, model)#  param_guess)
        lsc_odr.set_job(deriv=3) 
        lsc_odr.set_iprint(iter=1, iter_step=1)
        lsc_out = lsc_odr.run()
        self.beta_fit = lsc_out.beta
예제 #22
0
def linear_fit(x, y, xerr=None, yerr=None):
    from scipy import odr
    linear = odr.Model(f)
    if xerr == None: xerr = np.ones(len(x))
    if yerr == None: yerr = np.ones(len(y))
    for i, e in enumerate(yerr):
        if e == 0: yerr[i] = 1
    mydata = odr.Data(x, y, wd=1 / xerr, we=1 / yerr)
    myodr = odr.ODR(mydata, linear, beta0=[-1., 0.])
    myoutput = myodr.run()
    return (myoutput.beta[0], myoutput.beta[1], myoutput.sd_beta[0],
            myoutput.sd_beta[1])
예제 #23
0
 def DM_fit(self, tstart, v_max_index):
     ''' Perform orthogonal DM (inverse square) regression on this Cluster.
         The fitted DM value is stored in the field <DM>.'''
     # Note: frequency axis is flipped, because high freqs correspond to low array indices
     t_co = (self.t_co * tsamp * dt) + tstart
     v_co = ((v_max_index - self.v_co) * vsamp * dv) + vlow
     #print(DM_func([560.0*kDM], v_co, t_co[0], v_co[0]))
     data = odr.Data(v_co, t_co)  # y-axis is time
     DM_mod = odr.Model(DM_func, extra_args=(t_co[0], v_co[0]))
     # Note: beta0 is initial estimate of DM*kDM
     odr_inst = odr.ODR(data, DM_mod, beta0=[560.0 * kDM])
     output = odr_inst.run()
     self.DM = output.beta[0] / kDM
예제 #24
0
  def OrthReg(self, Deg=1):
    """
    Orthogonal regressiong of a polynomial of
    arbitrary degree.
    """

    B0 = np.ones(Deg+1)

    PF = odr.Model(PolyFun)

    if (self.Xw.all() == 0) and (self.Yw.all() == 0):
      Data = odr.Data(self.X, self.Y)
    else:
      Wx = 1./np.power(self.Xw,2)
      Wy = 1./np.power(self.Yw,2)
      Data = odr.Data(self.X, self.Y, Wx, Wy)

    Out = odr.ODR(Data, PF, beta0=B0)
    Out.run()

    self.B = Out.output.beta
    self.E = Out.output.sd_beta
예제 #25
0
def faceON(table):

    index, = np.where(table['flag']>0)
    table0 = trim(table, index)

    index, = np.where(table0['flag']<3)
    table0 = trim(table0, index)
    
    #### for test not face-on
    ###index, = np.where(table['Sqlt']>3)
    ###table0 = trim(table, index)

    ###index, = np.where(table0['Wqlt']>3)
    ###table0 = trim(table0, index)

    ###index, = np.where(table0['flag']==0)
    ###table0 = trim(table0, index)

    ###index, = np.where(table0['inc']>80)
    ###table0 = trim(table0, index)

    ###index, = np.where(table0['inc']<90)
    ###table0 = trim(table0, index)
    #### end test
    
    logWimx = table0['logWimx']
    r_w1 = table0['r_w1']
    c21w = table0['c21w'] 
    Ec21w = table0['Ec21w']

    AB, cov  = np.polyfit(logWimx,r_w1, 1, cov=True, full = False)
    a0, b0 = AB[0],AB[1]
    a = 1./a0
    b = -1.*b0/a0
    print "AB: ", a0, b0
    print "Covariance AB: ", cov

    delta = r_w1-(a0*logWimx+b0)
   
    a, b, c  = np.polyfit(c21w,delta, 2)
    x = c21w
    y = delta
    mydata = odr.Data(x, y, wd=Ec21w, we=delta*0.+0.1)
    F = odr.Model(Fdelta)
    myodr = odr.ODR(mydata, F, beta0=[a,b,c])
    myoutput = myodr.run()
    print "Delta: ", myoutput.beta
    print"Std Error Delta: ", myoutput.sd_beta
    
    return [a0,b0], myoutput.beta, table0, cov, myoutput.sd_beta
예제 #26
0
def TLS_regresssion(stock_1, stock_2):
    def f(B, x):
        '''Linear function y = m*x + b'''
        # B is a vector of the parameters.
        # x is an array of the current x values.
        # x is in the same format as the x passed to Data or RealData.
        # Return an array in the same format as y passed to Data or RealData.
        return B[0] * x + B[1]

    linear_model = odr.Model(f)
    used_data = odr.Data(stock_1, stock_2)
    TLS_regression_model = odr.ODR(used_data, linear_model, beta0=[1., 2.])
    result = TLS_regression_model.run()
    return result
예제 #27
0
def reldist_odr(x, y):
    import scipy.odr as odr

    def f(B, xx):
        return B[0] * xx + B[1]

    linear = odr.Model(f)
    data = odr.Data(x, y, wd=1, we=1)
    res = odr.ODR(data, linear, beta0=[.4, .0])
    res = res.run()
    b = res.beta[0]
    b = np.array([b, 1 / b])[np.argmin(np.abs([b, 1 / b]))]
    # print reldist_type2(x,y),b
    return b
예제 #28
0
    def fit_circle(arc_contour):
        """
        Fit the circle with feeding points

        Algorithm from scipy-cookbook: http://scipy-cookbook.readthedocs.io/items/Least_Squares_Circle.html
        :param arc_contour:
        :return: (x, y, r)
        """
        from scipy import odr

        x = np.array([i[0][0] for i in arc_contour])
        y = np.array([i[0][1] for i in arc_contour])

        def calc_R(c):
            """ calculate the distance of each 2D points from the center c=(xc, yc) """
            return np.sqrt((x - c[0])**2 + (y - c[1])**2)

        def circlemodel(beta, x):
            """ implicit function of the circle """
            xc, yc, r = beta
            return (x[0] - xc)**2 + (x[1] - yc)**2 - r**2

        def calc_estimate(data):
            """ Return a first estimation on the parameter from the data  """
            xc0, yc0 = data.x.mean(axis=1)
            r0 = np.sqrt((data.x[0] - xc0)**2 + (data.x[1] - yc0)**2).mean()
            return xc0, yc0, r0

        # for implicit function :
        #       data.x contains both coordinates of the points
        #       data.y is the dimensionality of the response
        lsc_data = odr.Data(np.row_stack([x, y]), y=1)
        lsc_model = odr.Model(circlemodel,
                              implicit=True,
                              estimate=calc_estimate)
        lsc_odr = odr.ODR(lsc_data, lsc_model)
        lsc_out = lsc_odr.run()

        xc_3, yc_3, R_3 = lsc_out.beta
        print('lsc_out.sum_square = ', lsc_out.sum_square)

        # Ri_3 = calc_R([xc_3, yc_3])
        # residu_3 = sum((Ri_3 - R_3) ** 2)
        # residu2_3 = sum((Ri_3 ** 2 - R_3 ** 2) ** 2)
        # print('residu_3  :', residu_3 )
        # print('residu2_3 :', residu2_3)

        return xc_3, yc_3, R_3
예제 #29
0
    def __init__(self, x, y, xerr=None, yerr=None):
        
        self.n = len(x)
        self.data = odr.Data(x, y, wd=xerr, we=yerr) 
        self.odr = odr.ODR(self.data, odr.unilinear).run()
        
        self.beta = self.odr.beta
        self.cov_beta = self.odr.cov_beta
        self.stderr_beta = self.odr.sd_beta

        self.xhat = np.sort(x)
        self.yhat = self.predict(self.xhat)
        
        self.r2 = self._calc_r2()
        self.rmse = self._calc_rmse()
        self.pval = self._calc_pval()
def findCurvatureR(x, y):
    # for implicit function :
    #       data.x contains both coordinates of the points
    #       data.y is the dimensionality of the response
    lsc_data = odr.Data(np.row_stack([x, y]), y=1)
    lsc_model = odr.Model(f_3, implicit=True, estimate=calc_estimate)
    lsc_odr = odr.ODR(lsc_data, lsc_model)
    lsc_out = lsc_odr.run()

    xc_3, yc_3, R_3 = lsc_out.beta
    Ri_3 = calc_R([xc_3, yc_3], x, y)
    residu_3 = sum((Ri_3 - R_3)**2)
    residu2_3 = sum((Ri_3**2 - R_3**2)**2)
    #ncalls_3   = f_3.ncalls

    #print ('lsc_out.sum_square = ',lsc_out.sum_square)
    return ([xc_3, yc_3, R_3])