예제 #1
0
    def test_integrate_polyn_good_degree(self):
        """
        Check quadrature errors for polynomials of max. degree N+1
        which should be zero. The integral values on the given domain are of
        magnitue 1e90 for n=13, so if this relative error is machine precision, it
        must be exact.
        """
        for number in self.orders:
            cc = clenshawcurtis.ClenshawCurtis(number, self.ndim, self.ilbds)
            random_poly = np.random.randint(1, 11, (number + 1, number + 1))
            integrated_poly = npoly.polyint(npoly.polyint(random_poly).T).T

            # pylint: disable=cell-var-from-loop
            def testpoly(val):
                return npoly.polyval2d(val[:, 0], val[:, 1], c=random_poly)

            truesol = (
                npoly.polyval2d(
                    self.ilbds[0, 1], self.ilbds[1, 1], c=integrated_poly) -
                npoly.polyval2d(
                    self.ilbds[0, 1], self.ilbds[1, 0], c=integrated_poly) -
                npoly.polyval2d(
                    self.ilbds[0, 0], self.ilbds[1, 1], c=integrated_poly) +
                npoly.polyval2d(
                    self.ilbds[0, 0], self.ilbds[1, 0], c=integrated_poly))

            abserror = np.abs(
                cc.integrate(testpoly, isvectorized=True) - truesol)
            relerror = abserror / np.abs(truesol)
            self.assertLess(relerror, 1e-14)
예제 #2
0
def plot():
    """Plot raw data and polynomial approximation"""
    plt.figure()
    Cm1s, Uts, npshrs = _points()

    # Plot fit
    for Ut in sorted(list(set(Uts))):
        fitted_Cm1 = np.linspace(5, 50)
        fitted_Ut = [Ut] * len(fitted_Cm1)
        fitted_npshr = polynomial.polyval2d(fitted_Cm1, fitted_Ut,
                                            get_coeffs())
        plt.plot(fitted_Cm1, fitted_npshr, 'g-')
        annotate_x = 34
        annotate_y = polynomial.polyval2d(annotate_x, Ut, get_coeffs())
        plt.annotate("Ut=" + str(Ut), xy=(annotate_x, annotate_y))
    plt.plot(Cm1s, npshrs, 'r.')

    # Plot data
    plt.gca().set_title(__doc__)
    plt.gca().set_xticks(np.arange(0, 50 + 5, 5))
    plt.gca().set_yticks(np.arange(0, 80 + 5, 5))
    plt.gca().set_xlim(0, 50)
    plt.gca().set_ylim(0, 80)
    plt.minorticks_on()
    plt.grid()
    plt.xlabel('Cm1 - Suction Eye Velocity [ft/s]')
    plt.ylabel('Required NPSH water [ft]')
    plt.draw()
예제 #3
0
파일: Maps.py 프로젝트: LongyanU/simpeg
    def _transform(self, m):
        # Set model parameters
        alpha = self.slope
        sig1,sig2 = m[0],m[1]
        c = m[2:]
        if self.logSigma:
            sig1, sig2 = np.exp(sig1), np.exp(sig2)
        #2D
        if self.mesh.dim == 2:
            X = self.mesh.gridCC[:,0]
            Y = self.mesh.gridCC[:,1]
            if self.normal =='X':
                f = polynomial.polyval(Y, c) - X
            elif self.normal =='Y':
                f = polynomial.polyval(X, c) - Y
            else:
                raise(Exception("Input for normal = X or Y or Z"))
        #3D
        elif self.mesh.dim == 3: 
            X = self.mesh.gridCC[:,0]
            Y = self.mesh.gridCC[:,1]            
            Z = self.mesh.gridCC[:,2]            
            if self.normal =='X':
                f = polynomial.polyval2d(Y, Z, c.reshape((self.order[0]+1,self.order[1]+1))) - X
            elif self.normal =='Y':
                f = polynomial.polyval2d(X, Z, c.reshape((self.order[0]+1,self.order[1]+1))) - Y
            elif self.normal =='Z':
                f = polynomial.polyval2d(X, Y, c.reshape((self.order[0]+1,self.order[1]+1))) - Z
            else:
                raise(Exception("Input for normal = X or Y or Z"))
        else:
            raise(Exception("Only supports 2D"))
                    

        return sig1+(sig2-sig1)*(np.arctan(alpha*f)/np.pi+0.5)
예제 #4
0
파일: psf.py 프로젝트: ameisner/crowdsource
 def __call__(self, x, y, stampsz=59, deriv=False):
     from numpy.polynomial.polynomial import polyval2d
     shiftx, shifty = (q - numpy.round(q) for q in (x, y))
     x = x / 1000.
     y = y / 1000.
     fwhm = polyval2d(x, y, self.fwhm)
     beta = polyval2d(x, y, self.beta)
     xy = polyval2d(x, y, self.xy)
     yy = polyval2d(x, y, self.yy)
     tstampsz = max(stampsz, self.normalize)
     psf = moffat_psf(fwhm,
                      beta=beta,
                      xy=xy,
                      yy=yy,
                      stampsz=tstampsz,
                      deriv=deriv,
                      shift=(shiftx, shifty))
     if not deriv:
         psf = [psf]
     if self.normalize > 0:
         norms = numpy.sum(central_stamp(psf[0], censize=self.normalize),
                           axis=(-1, -2)).reshape(-1, 1, 1)
     else:
         norms = 1
     psf = [central_stamp(p, censize=stampsz) / norms for p in psf]
     if not deriv:
         psf = psf[0]
     return psf
예제 #5
0
    def fun2_xy(xx, ct, bt, ax, ay, a, dist):
        x_n, y_n, a_k = xx[:NN], xx[NN:2 * NN], xx[2 * NN:]

        a[mask] = xx[2 * NN:]

        ax = poly_utils.polyder2d(a, ax, 0)
        ay = poly_utils.polyder2d(a, ay, 1)

        # cost:
        # (features[k] = n, xi, yi, m, xj, yj)
        # x_m - x_n + x_i - x_j + ux(x_i, y_i) - ux(x_j, y_j) = 0
        # y_m - y_n + y_i - y_j + uy(x_i, y_i) - uy(x_j, y_j) = 0

        temp1 = x_n[pos_inv[fes[:, 3].astype(np.int)]] - x_n[pos_inv[fes[:, 0].astype(np.int)]]  \
             + fes[:, 1] - fes[:, 4] \
             + polyval2d((fes[:, 1]+xmin)/float(xmax), (fes[:, 2]+ymin)/float(ymax), ax) \
             - polyval2d((fes[:, 4]+xmin)/float(xmax), (fes[:, 5]+ymin)/float(ymax), ax)

        temp2 = y_n[pos_inv[fes[:, 3].astype(np.int)]] - y_n[pos_inv[fes[:, 0].astype(np.int)]]  \
             + fes[:, 2] - fes[:, 5] \
             + polyval2d((fes[:, 1]+xmin)/float(xmax), (fes[:, 2]+ymin)/float(ymax), ay) \
             - polyval2d((fes[:, 4]+xmin)/float(xmax), (fes[:, 5]+ymin)/float(ymax), ay)

        cost = np.sum((temp1**2 + temp2**2) * reg)

        # integrate:
        ct = poly_utils.polymul2d(a, a, ct)
        cost += str_sm * poly_utils.polyint2d(ct, bt, -1., 1., -1., 1.)
        return cost
예제 #6
0
    def fun2_xy(xx, ct, bt):
        x_n, y_n, a_k, b_k = xx[:NN], xx[NN:2 * NN], xx[2 * NN:2 * NN + K**2 -
                                                        2], xx[2 * NN + K**2 -
                                                               2:]

        a_k = np.concatenate(([
            0,
        ], a_k[:K - 1], [
            0,
        ], a_k[K - 1:])).reshape((K, K))
        b_k = np.concatenate(([0, 0], b_k)).reshape((K, K))

        # cost:
        # (features[k] = n, xi, yi, m, xj, yj)
        # x_m - x_n + x_i - x_j + ux(x_i, y_i) - ux(x_j, y_j) = 0
        # y_m - y_n + y_i - y_j + uy(x_i, y_i) - uy(x_j, y_j) = 0

        temp1 = x_n[pos_inv[fes[:, 3].astype(np.int)]] - x_n[pos_inv[fes[:, 0].astype(np.int)]]  \
             + fes[:, 1] - fes[:, 4] \
             + polyval2d((fes[:, 1]+xmin)/float(xmax-xmin), (fes[:, 2]+ymin)/float(ymax-ymin), a_k) \
             - polyval2d((fes[:, 4]+xmin)/float(xmax-xmin), (fes[:, 5]+ymin)/float(ymax-ymin), a_k)

        temp2 = y_n[pos_inv[fes[:, 3].astype(np.int)]] - y_n[pos_inv[fes[:, 0].astype(np.int)]]  \
             + fes[:, 2] - fes[:, 5] \
             + polyval2d((fes[:, 1]+xmin)/float(xmax-xmin), (fes[:, 2]+ymin)/float(ymax-ymin), b_k) \
             - polyval2d((fes[:, 4]+xmin)/float(xmax-xmin), (fes[:, 5]+ymin)/float(ymax-ymin), b_k)

        cost = np.sum(temp1**2 + temp2**2)

        # integrate:
        ct = poly_utils.polymul2d(a_k, a_k, ct)
        cost += str_sm * poly_utils.polyint2d(ct, bt, -1., 1., -1., 1.)
        ct = poly_utils.polymul2d(b_k, b_k, ct)
        cost += str_sm * poly_utils.polyint2d(ct, bt, -1., 1., -1., 1.)
        return cost
예제 #7
0
파일: wcs.py 프로젝트: wkerzendorf/xtool
 def evaluate(self, x, y, wave_transform_coef, slit_transform_coef):
     x = np.squeeze(x)
     y = np.squeeze(x)
     wave_transform_coef = np.squeeze(wave_transform_coef)
     slit_transform_coef = np.squeeze(slit_transform_coef)
     return (polynomial.polyval2d(x, y, wave_transform_coef),
             polynomial.polyval2d(x, y, slit_transform_coef))
예제 #8
0
    def err_xy(xx, ct, bt):
        x_n, y_n, a_k, b_k = xx[:NN], xx[NN:2 * NN], xx[2 * NN:2 * NN + K**2 -
                                                        2], xx[2 * NN + K**2 -
                                                               2:]

        a_k = np.concatenate(([
            0,
        ], a_k[:K - 1], [
            0,
        ], a_k[K - 1:])).reshape((K, K))
        b_k = np.concatenate(([0, 0], b_k)).reshape((K, K))

        # cost:
        # (features[k] = n, xi, yi, m, xj, yj)
        # x_m - x_n + x_i - x_j + ux(x_i, y_i) - ux(x_j, y_j) = 0
        # y_m - y_n + y_i - y_j + uy(x_i, y_i) - uy(x_j, y_j) = 0

        temp1 = x_n[pos_inv[fes[:, 3].astype(np.int)]] - x_n[pos_inv[fes[:, 0].astype(np.int)]]  \
             + fes[:, 1] - fes[:, 4] \
             + polyval2d((fes[:, 1]+xmin)/float(xmax-xmin), (fes[:, 2]+ymin)/float(ymax-ymin), a_k) \
             - polyval2d((fes[:, 4]+xmin)/float(xmax-xmin), (fes[:, 5]+ymin)/float(ymax-ymin), a_k)

        temp2 = y_n[pos_inv[fes[:, 3].astype(np.int)]] - y_n[pos_inv[fes[:, 0].astype(np.int)]]  \
             + fes[:, 2] - fes[:, 5] \
             + polyval2d((fes[:, 1]+xmin)/float(xmax-xmin), (fes[:, 2]+ymin)/float(ymax-ymin), b_k) \
             - polyval2d((fes[:, 4]+xmin)/float(xmax-xmin), (fes[:, 5]+ymin)/float(ymax-ymin), b_k)

        return temp1**2 + temp2**2
예제 #9
0
def plot():
    """Plot raw data and polynomial approximation"""
    plt.figure()

    # Plot data
    for curve in _data():
        vanes = curve['vanes']
        x, y = np.transpose(curve['points']).tolist()
        plt.plot(x, y, 'r--')
        label = str(curve['vanes']) + ' vanes, ' + str(
            curve['discharge_angle']) + ' deg' + (', droop'
                                                  if curve['droop'] else '')
        plt.annotate(label, xy=(x[-1], y[-1]))

    # Plot fitted curves
    for vanes in range(get_vane_limits()[0], get_vane_limits()[1] + 1):
        endpoint = np.polyval(get_Ns_limit_coeffs(), vanes)
        x = np.linspace(0, endpoint)
        y = polynomial.polyval2d(np.ones(len(x)) * vanes, x, get_coeffs())
        plt.plot(x, y, 'g-')

    # plot limit of data
    vanespace = np.linspace(*get_vane_limits())
    limit_Ns = np.polyval(get_Ns_limit_coeffs(), vanespace)
    limit_phr = polynomial.polyval2d(vanespace, limit_Ns, get_coeffs())
    plt.plot(limit_Ns, limit_phr)

    plt.gca().set_title(__doc__)
    plt.gca().set_xticks(np.arange(0, endpoint + 1, 400))
    plt.gca().set_yticks(np.arange(0, 65, 5))
    plt.xlabel('Ns - Specific Speed')
    plt.ylabel('Percent Head Rise from B.E.P. to shutoff')
    plt.grid()
    plt.draw()
예제 #10
0
def plot():
    """Plot raw data and polynomial approximation"""
    plt.figure()

    # Plot data
    for curve in _data():
        vanes = curve['vanes']
        Ns, Km2 = np.transpose(curve['points']).tolist()
        plt.plot(Ns, Km2, 'r--')

    # Plot fitted curves
    for vanes in np.arange(get_vane_limits()[0],
                           get_vane_limits()[1] + 0.5,
                           step=0.5):
        startpoint, endpoint_coeffs = get_Ns_limits_coeffs()
        endpoint = np.polyval(endpoint_coeffs, vanes)
        x = np.linspace(startpoint, endpoint)
        y = polynomial.polyval2d(np.ones(len(x)) * vanes, x, get_Km2_coeffs())
        plt.plot(x, y, 'g-')
        plt.annotate(str(vanes), xy=(x[-1], y[-1]))

    # plot limit of data
    vanespace = np.linspace(*get_vane_limits())
    limit_x = np.polyval(get_Ns_limits_coeffs()[1], vanespace)
    limit_y = polynomial.polyval2d(vanespace, limit_x, get_Km2_coeffs())
    plt.plot(limit_x, limit_y)

    plt.gca().set_title(__doc__)
    plt.gca().set_xticks(np.arange(0, 3600 + 1, 400))
    plt.gca().set_yticks(np.arange(0, 0.28, 0.02))
    plt.xlabel('Ns - Specific Speed')
    plt.ylabel('Km2 - Capacity Constant')
    plt.grid()
    plt.draw()
예제 #11
0
    def poly2dlL(self,functionroot,kwds):
        '''
        poly2d of l=bxlumi, L=totallumi
        c00 + c10*x + c01*y (n=1)
        c00 + c10*x + c01*y + c20*x**2 + c02*y**2 + c11*x*y (n=2)
        if l is scalar, scale l to y/NBX, then the final result is NBX*singleresult
        otherwise, make l,L  the same shape
        '''        
        l = functionroot.root[0]  #per bunch lumi or totallumi
        L = functionroot.root[1] #total lumi
        ncollidingbx = functionroot.root[2] 
        totlumi = 0
        bxlumi = 0

        if isinstance(l,collections.Iterable):
            bxlumi = np.array(l)
            totlumi = np.full_like(bxlumi, L)
        else:
            if l!=L:
                raise ValueError('l and L are of different value ')
            with np.errstate(divide='ignore',invalid='ignore'):
                bxlumi = np.true_divide(L,ncollidingbx)
                if bxlumi == np.inf:
                    bxlumi = 0
                bxlumi = np.nan_to_num(bxlumi)                    
            totlumi = L

       
        coefsStr = kwds['coefs']

        coefs = np.array(ast.literal_eval(coefsStr), dtype=np.float)
        if isinstance(l,collections.Iterable):
            return P.polyval2d(bxlumi,totlumi,coefs)
        else:
            return ncollidingbx*P.polyval2d(bxlumi,totlumi,coefs)
예제 #12
0
파일: wcs.py 프로젝트: eso/xtool
 def evaluate(self, x, y, wave_transform_coef, slit_transform_coef):
     x = np.squeeze(x)
     y = np.squeeze(x)
     wave_transform_coef = np.squeeze(wave_transform_coef)
     slit_transform_coef = np.squeeze(slit_transform_coef)
     return (polynomial.polyval2d(x, y, wave_transform_coef),
             polynomial.polyval2d(x, y, slit_transform_coef))
예제 #13
0
파일: Maps.py 프로젝트: sdevriese/simpeg
    def deriv(self, m, v=None):
        alpha = self.slope
        sig1, sig2, c = m[0], m[1], m[2:]
        if self.logSigma:
            sig1, sig2 = np.exp(sig1), np.exp(sig2)

        # 2D
        if self.mesh.dim == 2:
            X = self.mesh.gridCC[self.actInd, 0]
            Y = self.mesh.gridCC[self.actInd, 1]

            if self.normal == 'X':
                f = polynomial.polyval(Y, c) - X
                V = polynomial.polyvander(Y, len(c) - 1)
            elif self.normal == 'Y':
                f = polynomial.polyval(X, c) - Y
                V = polynomial.polyvander(X, len(c) - 1)
            else:
                raise (Exception("Input for normal = X or Y or Z"))

        # 3D
        elif self.mesh.dim == 3:
            X = self.mesh.gridCC[self.actInd, 0]
            Y = self.mesh.gridCC[self.actInd, 1]
            Z = self.mesh.gridCC[self.actInd, 2]

            if self.normal == 'X':
                f = (polynomial.polyval2d(
                    Y, Z, c.reshape(
                        (self.order[0] + 1, self.order[1] + 1))) - X)
                V = polynomial.polyvander2d(Y, Z, self.order)
            elif self.normal == 'Y':
                f = (polynomial.polyval2d(
                    X, Z, c.reshape(
                        (self.order[0] + 1, self.order[1] + 1))) - Y)
                V = polynomial.polyvander2d(X, Z, self.order)
            elif self.normal == 'Z':
                f = (polynomial.polyval2d(
                    X, Y, c.reshape(
                        (self.order[0] + 1, self.order[1] + 1))) - Z)
                V = polynomial.polyvander2d(X, Y, self.order)
            else:
                raise (Exception("Input for normal = X or Y or Z"))

        if self.logSigma:
            g1 = -(np.arctan(alpha * f) / np.pi + 0.5) * sig1 + sig1
            g2 = (np.arctan(alpha * f) / np.pi + 0.5) * sig2
        else:
            g1 = -(np.arctan(alpha * f) / np.pi + 0.5) + 1.0
            g2 = (np.arctan(alpha * f) / np.pi + 0.5)

        g3 = Utils.sdiag(alpha * (sig2 - sig1) / (1. +
                                                  (alpha * f)**2) / np.pi) * V

        if v is not None:
            return sp.csr_matrix(np.c_[g1, g2, g3]) * v
        return sp.csr_matrix(np.c_[g1, g2, g3])
예제 #14
0
파일: psf.py 프로젝트: ctslater/crowdsource
 def render_model(self, x, y, stampsz=59, deriv=False):
     from numpy.polynomial.polynomial import polyval2d
     x = x / 1000.
     y = y / 1000.
     fwhm = polyval2d(x, y, self.fwhm)
     beta = polyval2d(x, y, self.beta)
     xy = polyval2d(x, y, self.xy)
     yy = polyval2d(x, y, self.yy)
     return moffat_psf(fwhm, beta=beta, xy=xy,
                       yy=yy, stampsz=stampsz, deriv=deriv)
예제 #15
0
파일: psf.py 프로젝트: ameisner/crowdsource
 def centroid(self, x, y):
     from numpy.polynomial.polynomial import polyval2d
     x, y = (x / 1000., y / 1000.)
     if self.normalize < 0:
         norm = 1
     else:
         norm = self.norm(x, y)
     xc = polyval2d(x, y, self.xstamp)
     yc = polyval2d(x, y, self.ystamp)
     return xc / norm, yc / norm
예제 #16
0
 def eval(self, peaks, order, coef_tilt, coef_shear):
     if self.mode == "1D":
         tilt = np.zeros(peaks.shape)
         shear = np.zeros(peaks.shape)
         for i in np.unique(order):
             idx = order == i
             tilt[idx] = np.polyval(coef_tilt[i], peaks[idx])
             shear[idx] = np.polyval(coef_shear[i], peaks[idx])
     elif self.mode == "2D":
         tilt = polyval2d(peaks, order, coef_tilt)
         shear = polyval2d(peaks, order, coef_shear)
     return tilt, shear
예제 #17
0
    def deriv(self, m, v=None):
        alpha = self.slope
        sig1, sig2, c = m[0], m[1], m[2:]
        if self.logSigma:
            sig1, sig2 = np.exp(sig1), np.exp(sig2)

        # 2D
        if self.mesh.dim == 2:
            X = self.mesh.gridCC[self.actInd, 0]
            Y = self.mesh.gridCC[self.actInd, 1]

            if self.normal == 'X':
                f = polynomial.polyval(Y, c) - X
                V = polynomial.polyvander(Y, len(c)-1)
            elif self.normal == 'Y':
                f = polynomial.polyval(X, c) - Y
                V = polynomial.polyvander(X, len(c)-1)
            else:
                raise(Exception("Input for normal = X or Y or Z"))

        # 3D
        elif self.mesh.dim == 3:
            X = self.mesh.gridCC[self.actInd, 0]
            Y = self.mesh.gridCC[self.actInd, 1]
            Z = self.mesh.gridCC[self.actInd, 2]

            if self.normal == 'X':
                f = (polynomial.polyval2d(Y, Z, c.reshape((self.order[0]+1,
                     self.order[1]+1))) - X)
                V = polynomial.polyvander2d(Y, Z, self.order)
            elif self.normal == 'Y':
                f = (polynomial.polyval2d(X, Z, c.reshape((self.order[0]+1,
                     self.order[1]+1))) - Y)
                V = polynomial.polyvander2d(X, Z, self.order)
            elif self.normal == 'Z':
                f = (polynomial.polyval2d(X, Y, c.reshape((self.order[0]+1,
                     self.order[1]+1))) - Z)
                V = polynomial.polyvander2d(X, Y, self.order)
            else:
                raise(Exception("Input for normal = X or Y or Z"))

        if self.logSigma:
            g1 = -(np.arctan(alpha*f)/np.pi + 0.5)*sig1 + sig1
            g2 = (np.arctan(alpha*f)/np.pi + 0.5)*sig2
        else:
            g1 = -(np.arctan(alpha*f)/np.pi + 0.5) + 1.0
            g2 = (np.arctan(alpha*f)/np.pi + 0.5)

        g3 = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*V

        if v is not None:
            return sp.csr_matrix(np.c_[g1, g2, g3]) * v
        return sp.csr_matrix(np.c_[g1, g2, g3])
예제 #18
0
def getMVPolyNormal(p, x, y):
    '''
      calculate the normal vector for a 3d polynomial at x and y
    '''
    dx = polyder2d(p)                             # get derivative with respect to x
    gx = polyval2d(x,y,np.fliplr(np.flipud(dx)))  # evaluate for gradient wrt x - why, oh why, is polynomial package backwards from polyval and poly1d?
    #gx = np.array((1,0,gx))                       # translate them to vectors
    dy = polyder2d(p,1)                           # get derivative with respect to y
    gy = polyval2d(x,y,np.fliplr(np.flipud(dy)))  # evaluate for gradient wrt y - why, oh why, is polynomial package backwards from polyval and poly1d?
    #gy = np.array((0,1,gy))                       # translate them to vectors
    #c = np.cross(gx,gy)                           # get cross product
    c = np.array((gx,gy,-1))                      # axis aligned orthoganal - no need for cross product
    return c/norm(c)
예제 #19
0
파일: psf.py 프로젝트: ameisner/crowdsource
 def render_model(self, x, y, stampsz=59, deriv=False):
     from numpy.polynomial.polynomial import polyval2d
     x = x / 1000.
     y = y / 1000.
     tstamps = polyval2d(x, y, central_stamp(self.stamp, stampsz))
     if len(tstamps.shape) == 3:
         tstamps = tstamps.transpose(2, 0, 1)
     if deriv:
         dpsfdx = polyval2d(x, y, central_stamp(self.deriv[0], stampsz))
         dpsfdy = polyval2d(x, y, central_stamp(self.deriv[1], stampsz))
         if len(tstamps.shape) == 3:
             dpsfdx = dpsfdx.transpose(2, 0, 1)
             dpsfdy = dpsfdy.transpose(2, 0, 1)
         tstamps = (tstamps, dpsfdx, dpsfdy)
     return tstamps
예제 #20
0
 def dV(x, y):
     # -1.0 for convenience, because we eventually care about the electric field
     # Factors of 10 are to get to V/cm (poly interp data is in mm)
     return -1.0 * (10.)**(xord + yord) * np.dot(
         ev_array,
         polyval2d(np.array(x).ravel(),
                   np.array(y).ravel(), valarr))
예제 #21
0
def polyval2d(x, y, c):
    """Evaluate a 2-D polynomial at points (x, y).

    This function returns the value

    .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points (x, y), where x
        and y must have the same shape. If x or y is a list or tuple, it is
        first converted to an ndarray, otherwise it is left unchanged and, if it
        is not an ndarray, it is treated as a scalar.
    c : array_like
        Array of coefficients ordered so that the coefficient of the term of
        multi-degree i,j is contained in `c[i,j]`.

    Returnes
    --------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points formed with pairs
        of corresponding values from x and y.

    See Also
    --------
    polygrid2d, polyfit2d
    numpy.polynomial.polynomial.polyval2d
    """
    from numpy.polynomial.polynomial import polyval2d

    c = np.asarray(c)
    if c.ndim != 2 or c.shape[0] != c.shape[1]:
        raise ValueError("c must be a squared 2-dim array.")
    return polyval2d(x, y, c)
예제 #22
0
    def test_polyval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        #test exceptions
        assert_raises(ValueError, poly.polyval2d, x1, x2[:2], self.c2d)

        #test values
        tgt = y1*y2
        res = poly.polyval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        #test shape
        z = np.ones((2,3))
        res = poly.polyval2d(z, z, self.c2d)
        assert_(res.shape == (2,3))
예제 #23
0
def estimate_gradient(im):
    # simple estimation of 2d linear gradient surface ~12ms

    def _polyfit2d(x, y, f, deg):
        deg = np.asarray(deg)
        vander = polynomial.polyvander2d(x, y, deg)
        vander = vander.reshape((-1, vander.shape[-1]))
        f = f.reshape((vander.shape[0], ))
        c = np.linalg.lstsq(vander, f, rcond=None)[0]
        return c.reshape(deg + 1)

    try:
        # fit at random pixels
        npts = 500
        r, c = im.shape

        x = np.random.random_integers(0, high=c - 1, size=(npts))
        y = np.random.random_integers(0, high=r - 1, size=(npts))
        z = np.array([im[j, i] for i, j in zip(x, y)])

        zlo, zhi = np.percentile(z, 20), np.percentile(z, 80)
        inds = [i for i, j in enumerate(z) if (j >= zlo) and (j <= zhi)]

        # perform fit
        return polynomial.polyval2d(
            *np.meshgrid(np.arange(c), np.arange(r)),
            _polyfit2d(x[inds], y[inds], z[inds], deg=[2, 1]))

    except Exception as e:
        logger.warning(
            'gradient estimation failed; returning zeros ({:})'.format(e))
        return np.zeros(im.shape)
예제 #24
0
def deskewmem(input_data,
              DeltaKCOAPoly,
              dim0_coords_m,
              dim1_coords_m,
              dim,
              fft_sgn=-1):
    """Performs deskew (centering of the spectrum on zero frequency) on a complex dataset.

    INPUTS:
       input_data:  Complex FFT Data
       DeltaKCOAPoly:  Polynomial that describes center of frequency support of data.
       dim0_coords_m:  Coordinate of each "row" in dimension 0
       dim1_coords_m:  Coordinate of each "column" in dimension 1
       dim:  Dimension over which to perform deskew
       fft_sgn:  FFT sign required to transform data to spatial frequency domain
    OUTPUTS:
       output_data:  Deskewed data
       new_DeltaKCOAPoly:  Frequency support shift in the non-deskew dimension
          caused by the deskew.
    """

    # Integrate DeltaKCOA polynomial (in meters) to form new polynomial DeltaKCOAPoly_int
    DeltaKCOAPoly_int = polynomial.polyint(DeltaKCOAPoly, axis=dim)
    # New DeltaKCOAPoly in other dimension will be negative of the derivative of
    # DeltaKCOAPoly_int in other dimension (assuming it was zero before).
    new_DeltaKCOAPoly = -polynomial.polyder(DeltaKCOAPoly_int, axis=dim - 1)
    # Apply phase adjustment from polynomial
    [dim1_coords_m_2d, dim0_coords_m_2d] = np.meshgrid(dim1_coords_m,
                                                       dim0_coords_m)
    output_data = np.multiply(
        input_data,
        np.exp(1j * fft_sgn * 2 * np.pi * polynomial.polyval2d(
            dim0_coords_m_2d, dim1_coords_m_2d, DeltaKCOAPoly_int)))
    return output_data, new_DeltaKCOAPoly
예제 #25
0
def deskewmem(input_data, DeltaKCOAPoly, dim0_coords_m, dim1_coords_m, dim, fft_sgn=-1):
    """
    Performs deskew (centering of the spectrum on zero frequency) on a complex dataset.

    Parameters
    ----------
    input_data : numpy.ndarray
        Complex FFT Data
    DeltaKCOAPoly : numpy.ndarray
        Polynomial that describes center of frequency support of data.
    dim0_coords_m : numpy.ndarray
    dim1_coords_m : numpy.ndarray
    dim : int
    fft_sgn : int|float

    Returns
    -------
    Tuple[numpy.ndarray, numpy.ndarray]
        * `output_data` - Deskewed data
        * `new_DeltaKCOAPoly` - Frequency support shift in the non-deskew dimension caused by the deskew.
    """

    # Integrate DeltaKCOA polynomial (in meters) to form new polynomial DeltaKCOAPoly_int
    DeltaKCOAPoly_int = polynomial.polyint(DeltaKCOAPoly, axis=dim)
    # New DeltaKCOAPoly in other dimension will be negative of the derivative of
    # DeltaKCOAPoly_int in other dimension (assuming it was zero before).
    new_DeltaKCOAPoly = - polynomial.polyder(DeltaKCOAPoly_int, axis=dim-1)
    # Apply phase adjustment from polynomial
    dim1_coords_m_2d, dim0_coords_m_2d = np.meshgrid(dim1_coords_m, dim0_coords_m)
    output_data = np.multiply(input_data, np.exp(1j * fft_sgn * 2 * np.pi *
                                                 polynomial.polyval2d(
                                                     dim0_coords_m_2d,
                                                     dim1_coords_m_2d,
                                                     DeltaKCOAPoly_int)))
    return output_data, new_DeltaKCOAPoly
예제 #26
0
def mls_height_apprx(pointcloud,
                     point,
                     support_radius=1.,
                     degree=(1, 1)) -> float:
    """
    аппроксимация высоты точки по облаку с помощью moving least squares

    :param pointcloud: карта высот
    :param point: точка для аппроксимации
    :param kwargs:
        support_radius - радиус в пределах которого учитывать точки (default - 1.)
        degree - порядок полинома для аппроксимации в формате (xm, ym) (default - (1,1))
    :return:
    """
    data = pointcloud[~np.isnan(pointcloud).any(axis=-1)].reshape(-1, 3)
    cond = np.sum(np.power(data[:, :2] - point[:2], 2),
                  axis=-1) <= support_radius**2
    data = data[cond] - (point[X], point[Y], 0)
    if data.size >= ((degree[0] + 1) * (degree[1] + 1)):
        c = mls3d(data, (0, 0), support_radius, degree).reshape(
            (degree[0] + 1, degree[1] + 1))
        z = polyval2d(0, 0, c)
        return z
    elif data.size > 0:
        return np.mean(data)
    else:
        return 0
예제 #27
0
    def test_polyval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # test exceptions
        assert_raises(ValueError, poly.polyval2d, x1, x2[:2], self.c2d)

        # test values
        tgt = y1 * y2
        res = poly.polyval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # test shape
        z = np.ones((2, 3))
        res = poly.polyval2d(z, z, self.c2d)
        assert_(res.shape == (2, 3))
예제 #28
0
 def eval(self, peaks, order, coef_tilt, coef_shear):
     if self.mode == "1D":
         tilt = np.zeros(peaks.shape)
         shear = np.zeros(peaks.shape)
         for i in np.unique(order):
             idx = order == i
             tilt[idx] = np.polyval(coef_tilt[i], peaks[idx])
             shear[idx] = np.polyval(coef_shear[i], peaks[idx])
     elif self.mode == "2D":
         tilt = polyval2d(peaks, order, coef_tilt)
         shear = polyval2d(peaks, order, coef_shear)
     else:
         raise ValueError(
             f"Value for 'mode' not understood. Expected one of ['1D', '2D'] but got {self.mode}"
         )
     return tilt, shear
예제 #29
0
def polyval2d(x, y, c):
    """Evaluate a 2-D polynomial at points (x, y).

    This function returns the value

    .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points (x, y), where x
        and y must have the same shape. If x or y is a list or tuple, it is
        first converted to an ndarray, otherwise it is left unchanged and, if it
        is not an ndarray, it is treated as a scalar.
    c : array_like
        Array of coefficients ordered so that the coefficient of the term of
        multi-degree i,j is contained in `c[i,j]`.

    Returnes
    --------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points formed with pairs
        of corresponding values from x and y.

    See Also
    --------
    polygrid2d, polyfit2d
    numpy.polynomial.polynomial.polyval2d
    """
    from numpy.polynomial.polynomial import polyval2d

    c = np.asarray(c)
    if c.ndim != 2 or c.shape[0] != c.shape[1]:
        raise ValueError("c must be a squared 2-dim array.")
    return polyval2d(x, y, c)
def ex_function(xy):
    x = np.array(xy[0])
    y = np.array(xy[1])
    #S_xy = 2.*x**2. + (3./2.)*y**2. +x*y - x - 2.*y + 6.
    coeffs = get_Sxy_coeff()
    S_xy = polyval2d(x, y, coeffs)
    return S_xy
예제 #31
0
def reflectRayMVPolynomial(p, rd, rp):
    '''
      reflect the ray definded by point rp and vector rd on the surface of polynomial p
    '''
    if rd[0] == 0:
        x = rp[0]
        if rd[1] == 0:
            y = rp[1]
        else:
            m,b = calcLineFromRay(rd,rp,2,1)
            lineZy = np.poly1d([m,b])
            polyZy = partialEvalMVPolynomial(p, x, axis=0) 
            polyZy -= lineZy
            y = chooseRoot(polyZy.r)
        z = polyval2d(x,y,np.fliplr(np.flipud(p)))
    else:
        #print('\nray point: %s'%rp)
        m,b = calcLineFromRay(rd,rp,1,0)
        lineYx = np.poly1d([m,b])            # calc poly1ds for y of ray
        m,b = calcLineFromRay(rd,rp,2,0)
        lineZx = np.poly1d([m,b])            # calc poly1ds for y of ray
        x,y,z = intersectMVLinePolynomial(p, lineYx, lineZx) # intersect line and poly
    if x is None:
        return np.array([float('nan')]*3), np.array([float('nan')]*3)
    n = getMVPolyNormal(p,x,y)          # find normal at intersection
    fd = rd - 2*n*(np.dot(rd,n))        # from http://paulbourke.net/geometry/reflected/
    fd = fd/norm(fd)
    # check reflection direction - ensure it is opposite incomming ray direction
    n = n if np.dot(n,rd) < 0 else -n
    fd = -fd if np.dot(fd,n) < 0 else fd
    fp = np.array([x,y,z])
    return fd, fp
예제 #32
0
    def zernikepoly(self, n, m):
        r"""Build Cartesian coefficient matrix for :math:`Z_n^m`.

        :math:`m,n>=0` and :math:`m<=n`.

        Returns
        -------
        function(x, y) -> 1D float array
            Function that takes x and y coordinates and calculates result for
            given :math:`Z_n^m`.
            (Wrapped `numpy.polynomials.polynomial.polyval2d()`)
        """
        coeff = np.zeros(shape=(n + 1, n + 1))
        h = n - 2 * m
        if h <= 0:
            p = 0
            q = -h // 2 if n % 2 == 0 else (-h - 1) // 2
        else:
            p = 1
            q = h // 2 - 1 if n % 2 == 0 else (h - 1) // 2
        h = abs(h)
        m = (n - h) // 2
        for i in range(q + 1):
            for j in range(m + 1):
                for k in range(m - j + 1):
                    factor = 1 if (i + j) % 2 == 0 else -1
                    factor *= binom(h, 2 * i + p)
                    factor *= binom(m - j, k)
                    factor *= factorial(n - j) / (
                        factorial(j) * factorial(m - j) * factorial(n - m - j))
                    ypow = 2 * (i + k) + p
                    xpow = n - 2 * (i + j + k) - p
                    coeff[xpow, ypow] += factor
        return lambda x, y: polyval2d(x, y, coeff)
예제 #33
0
def calc(Cm1, Ut):
    """Calculate NPSHR"""
    startpoint_Cm1, endpoint_npshr, (startpoint_Ut, endpoint_Ut) = get_limits()
    assert startpoint_Ut <= Ut <= endpoint_Ut
    assert startpoint_Cm1 <= Cm1
    npshr = polynomial.polyval2d(Cm1, Ut, get_coeffs())
    assert npshr <= endpoint_npshr
    return npshr
예제 #34
0
 def sag_xy(x, y):
     cx = -1/452.62713
     cy = -1/443.43539
     kx = ky = 0.0
     x2 = x*x
     y2 = y*y
     z = (cx*x2 + cy*y2)/(1 + np.sqrt(1-((1+kx)*cx*cx)*x2 - ((1+ky)*cy*cy)*y2))
     return z + polyval2d(x, y, sag_xy.coeff)
예제 #35
0
    def __vanderfit(self, order):
        """
        Calculates the surface on a 3D meshgrid
        :param order: ordertuple of the surface
        :return: x y and z values and coefficient matrix
        """

        c = self.__polyfit2dvander(order)

        nx, ny = self.grid
        xx, yy = np.meshgrid(np.linspace(self.x.min(), self.x.max(), nx),
                             np.linspace(self.y.min(), self.y.max(), ny))

        # store the fit result for error calculation, zz is used to plot the surface
        self.fit_result = polynomial.polyval2d(self.x, self.y, c)
        zz = polynomial.polyval2d(xx, yy, c)

        return xx, yy, zz, c
예제 #36
0
    def test_polyvander2d(self) :
        # also tests polyval2d for non-square coefficient array
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = poly.polyvander2d(x1, x2, [1, 2])
        tgt = poly.polyval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # check shape
        van = poly.polyvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))
        def _fit_lin_surface(zz, pixelsize):

            from numpy.polynomial import polynomial

            xx, yy = wpu.grid_coord(zz, pixelsize)

            f = zz.flatten()
            deg = np.array([1, 1])
            vander = polynomial.polyvander2d(xx.flatten(), yy.flatten(), deg)
            vander = vander.reshape((-1, vander.shape[-1]))
            f = f.reshape((vander.shape[0],))
            c = np.linalg.lstsq(vander, f)[0]

            print(c)

            return polynomial.polyval2d(xx, yy, c.reshape(deg+1))
예제 #38
0
    # Plot predicted
    pred = prob_core.fields(mrec)
    
    PF.Magnetics.plot_obs_2D(rxLoc,pred,'Predicted Data', vmin = np.min(survey.dobs), vmax = np.max(survey.dobs))
    
    PF.Magnetics.plot_obs_2D(rxLoc,survey.dobs-pred,'Residual Data')
    
    #PF.Magnetics.writeUBCobs(home_dir + dsep + 'Pred_Final.pre',B,M,rxLoc,pred,np.ones(len(d)))
    
    
    print "Final misfit:" + str(np.sum( ((d-pred)/uncert)**2. ) )
    
    #%% Write parametric surface
    yz = Utils.ndgrid(np.r_[-ncy/2*dx,0,ncy/2*dx],np.r_[mesh.vectorCCz[-1],mesh.vectorCCz[0]])
    
    xout = polynomial.polyval2d(yz[:,0],yz[:,1],np.reshape(mrec[2:],(2,2)))
    
    
    xyz = np.c_[xout,yz]

    # Rotate back to global coordinates
    # Create rotation matrix
    Rz = np.array([[np.cos(-azm), -np.sin(-azm)],
                   [np.sin(-azm), np.cos(-azm)]])
    
    
    temp = Rz.dot( np.vstack([xyz[:,0].T, xyz[:,1].T]) )
    
    if ii == 0:
    # Rotate
        ROTxyz = np.c_[temp[0,:].T + midx, temp[1,:].T + midy, xyz[:,2]]