コード例 #1
0
ファイル: test_chebyshev.py プロジェクト: 0x60/yhack2017
    def test_chebpts2(self):
        #test exceptions
        assert_raises(ValueError, cheb.chebpts2, 1.5)
        assert_raises(ValueError, cheb.chebpts2, 1)

        #test points
        tgt = [-1, 1]
        assert_almost_equal(cheb.chebpts2(2), tgt)
        tgt = [-1, 0, 1]
        assert_almost_equal(cheb.chebpts2(3), tgt)
        tgt = [-1, -0.5, .5, 1]
        assert_almost_equal(cheb.chebpts2(4), tgt)
        tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0]
        assert_almost_equal(cheb.chebpts2(5), tgt)
コード例 #2
0
ファイル: test_chebyshev.py プロジェクト: glimmercn/numpy
    def test_chebpts2(self):
        #test exceptions
        assert_raises(ValueError, cheb.chebpts2, 1.5)
        assert_raises(ValueError, cheb.chebpts2, 1)

        #test points
        tgt = [-1, 1]
        assert_almost_equal(cheb.chebpts2(2), tgt)
        tgt = [-1, 0, 1]
        assert_almost_equal(cheb.chebpts2(3), tgt)
        tgt = [-1, -0.5, .5, 1]
        assert_almost_equal(cheb.chebpts2(4), tgt)
        tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0]
        assert_almost_equal(cheb.chebpts2(5), tgt)
コード例 #3
0
ファイル: Polynomial.py プロジェクト: skeeet/MetaLab
def cheb_fitcurve(x, y, order):
    x = cheb.chebpts2(len(x))
    order = 64
    coef = legend.legfit(x, y, order)
    assert_equal(len(coef), order + 1)
    y1 = legend.legval(x, coef)
    err_1 = np.linalg.norm(y1 - y) / np.linalg.norm(y)

    coef = cheb.chebfit(x, y, order)
    assert_equal(len(coef), order + 1)
    thrsh = abs(coef[0] / 1000)
    for i in range(len(coef)):
        if abs(coef[i]) < thrsh:
            coef = coef[0:i + 1]
            break

    y2 = cheb.chebval(x, coef)
    err_2 = np.linalg.norm(y2 - y) / np.linalg.norm(y)

    plt.plot(x, y2, '.')
    plt.plot(x, y, '-')
    plt.title("nPt={} order={} err_cheby={:.6g} err_legend={:.6g}".format(
        len(x), order, err_2, err_1))
    plt.show()
    assert_almost_equal(cheb.chebval(x, coef), y)
    #
    return coef
コード例 #4
0
ファイル: diff.py プロジェクト: WhFanatic/channel_IDM
	def __cheb_quad(n):
		''' weights for Chebyshev–Gauss quadrature,
			https://keisan.casio.com/exec/system/1282551763 '''
		W = np.zeros(n)
		a = np.pi / (n-1)
		for i,y in enumerate(cb.chebpts2(n)):
			if 0 < i < n-1:
				W[i] = a * np.sin(a*i)**2 / (1 - y**2)**.5
		return W / 2 # /2 for normalizing the integration on range [-1,1]
コード例 #5
0
ファイル: shentransform.py プロジェクト: SebsterG/spectralDNS
 def points_and_weights(self, N):
     self.N = N
     if self.quad == "GL":
         points = n_cheb.chebpts2(N)[::-1]
         weights = np.zeros((N)) + np.pi / (N - 1)
         weights[0] /= 2
         weights[-1] /= 2
     elif self.quad == "GC":
         points, weights = n_cheb.chebgauss(N)
     return points, weights
コード例 #6
0
 def points_and_weights(self, N):
     self.N = N
     if self.quad == "GC":
         points = n_cheb.chebpts2(N)[::-1]
         weights = np.zeros((N))+np.pi/(N-1)
         weights[0] /= 2
         weights[-1] /= 2
     elif self.quad == "GL":
         points, weights = n_cheb.chebgauss(N)
     return points, weights
コード例 #7
0
def simulate(Xpred):
    ' Generates y from x data '
    lambda_0 = 240
    lambda_f = 2000
    n_spct = 256

    cheb_plot = cheb.chebpts2(n_spct)
    scale = (lambda_f - lambda_0) / 2
    offset = lambda_0 + scale
    scaled_cheb = [i * scale + offset for i in cheb_plot]

    # Load refractive indices of materials at different sizes
    n_dict = N_Dict()
    n_dict.Load("Si3N4", "./Si3N4_310nm-14280nm.txt", scale=1000)
    n_dict.Load("Graphene", "./Graphene_240nm-30000nm.txt")
    n_dict.InitMap2(["Si3N4", "Graphene"], scaled_cheb)
    map2 = n_dict.map2

    Ypred = np.zeros((Xpred.shape[0], n_spct))

    for c, x in enumerate(Xpred):
        dataY = np.zeros((n_spct, 3))

        t_layers = np.array([])
        for val in x:
            # Graphene is preset to always be 0.35 thick
            t_layers = np.concatenate((t_layers, np.array([0.35, val])))
        t_layers = np.concatenate((np.array([np.nan]),t_layers, np.array([np.nan])))

        # Each y-point has different ns in each layer
        for row, lenda in enumerate(scaled_cheb):
            n_layers = np.array([])
            for i in range(len(t_layers) - 2):
                # -2 added to subtract added substrate parameters from length
                if i % 2 == 0:
                    n_layers = np.concatenate((n_layers, np.array([map2['Graphene', lenda]])))
                else:
                    n_layers = np.concatenate((n_layers, np.array([map2['Si3N4', lenda]])))
            # Sandwich by substrate
            n_layers = np.concatenate((np.array([1.46 + 0j]), n_layers, np.array([1 + 0j])))

            # TARGET PARAMETERS OF THE PROBLEM!
            xita = 0
            polar = 0

            r, t, R, T, A = jreftran_rt(lenda, t_layers, n_layers, xita, polar)

            dataY[row, 0] = R
            dataY[row, 1] = T
            dataY[row, 2] = A

        # Because graphs are of absorbance 2nd value is selected
        Ypred[c, :] = dataY[0:n_spct, 2]

    return Ypred
コード例 #8
0
    def points_and_weights(self, N):
        self.N = N
        if self.quad == "GL":
            points = (n_cheb.chebpts2(N)[::-1]).astype(float)
            weights = zeros(N)+pi/(N-1)
            weights[0] /= 2
            weights[-1] /= 2

        elif self.quad == "GC":
            points, weights = n_cheb.chebgauss(N)
            points = points.astype(float)
            weights = weights.astype(float)
            
        return points, weights
コード例 #9
0
 def assemble(self):
     k = arange(self.N).astype(float)
     Am = Amat(k)
     Bm = Bmat(k, "GC")
     Cm = Cmat(k, "GC")
     weights = zeros((self.N))+pi/(self.N-1)
     weights[0] /= 2
     weights[-1] /= 2
     A = Am.diags().toarray()
     B = Bm.diags().toarray()
     C = Cm.diags().toarray()
     points = n_cheb.chebpts2(self.N)[::-1]
     self.B = -1j*self.alfa*self.Re*(C+self.alfa**2*B)
     self.A = (A + (2*self.alfa**2+1j*self.alfa*self.Re*(1-points**2))*C + 
               (self.alfa**4+1j*self.alfa**3*self.Re*(1-points**2)-2*1j*self.alfa*self.Re)*B)
コード例 #10
0
 def assemble(self):
     k = arange(self.N).astype(float)
     Am = Amat(k)
     Bm = Bmat(k, "GC")
     Cm = Cmat(k, "GC")
     weights = zeros((self.N))+pi/(self.N-1)
     weights[0] /= 2
     weights[-1] /= 2
     A = Am.diags().toarray()
     B = Bm.diags().toarray()
     C = Cm.diags().toarray()
     points = n_cheb.chebpts2(self.N)[::-1]
     self.B = -1j*self.alfa*self.Re*(C+self.alfa**2*B)
     self.A = (A + (2*self.alfa**2+1j*self.alfa*self.Re*(1-points**2))*C + 
               (self.alfa**4+1j*self.alfa**3*self.Re*(1-points**2)-2*1j*self.alfa*self.Re)*B)
コード例 #11
0
    def points_and_weights(self, N, scaled=False):
        if self.quad == "GL":
            points = -(n_cheb.chebpts2(N)).astype(float)
            weights = np.full(N, np.pi/(N-1))
            weights[0] /= 2
            weights[-1] /= 2

        elif self.quad == "GC":
            points, weights = n_cheb.chebgauss(N)
            points = points.astype(float)
            weights = weights.astype(float)

        if scaled is True:
            points = self.map_true_domain(points)

        return points, weights
コード例 #12
0
    def points_and_weights(self, N):
        self.N = N
        if self.quad == "GL":
            points = (n_cheb.chebpts2(N)[::-1]).astype(float)
            #points = (n_cheb.chebpts2(N)).astype(float)
            weights = zeros(N) + pi / (N - 1)
            weights[0] /= 2
            weights[-1] /= 2

        elif self.quad == "GC":
            points, weights = n_cheb.chebgauss(N)
            #points = points[::-1]
            points = points.astype(float)
            weights = weights.astype(float)

        return points, weights
コード例 #13
0
    def _fit_fft(self,func,N):
        """ Get the chebyshev coefficients using fft
            inspired by: http://www.scientificpython.net/1/post/2012/4/the-fast-chebyshev-transform.html
            *Doesn't seem to work right now*
        """
        pts = cheb.chebpts2(N)
        y = func(pts)
        A = y[:,np.newaxis]
        m = np.size(y,0)
        k = m-1-np.arange(m-1)
        V = np.vstack((A[0:m-1,:],A[k,:]))
        F = ifft(V,n=None,axis=0)
        B = np.vstack((F[0,:],2*F[1:m-1,:],F[m-1,:]))

        if A.dtype != 'complex':
            return np.real(B)
        return B
コード例 #14
0
    def Init_lenda_tic(self ):
        l_0 = self.lenda_0

        self.lenda_tic=[]
        if self.tic_type=="cheb_":
            pt_1 = cheb.chebpts1(256)
            pt_2 = cheb.chebpts2(256)
            scale = (self.lenda_1-l_0)/2
            off = l_0+scale
            self.lenda_tic = [i * scale + off for i in pt_2]
            assert(self.lenda_tic[0]==l_0 and self.lenda_tic[-1]==self.lenda_1)
        else:

            if( self.lenda_0<500 ):
                self.lenda_tic = list(range(self.lenda_0,500,1))
                l_0 = 500
            self.lenda_tic.extend( list(range(l_0,self.lenda_1+self.lenda_step,self.lenda_step)) )
コード例 #15
0
def collocation_matrix(n, bcs):
    x = 0.5 * (1 + chebpts2(n))
    b = numpy.zeros((n, ))
    A = numpy.zeros((n, n))
    # Left boundary
    b[0] = bcs[0]
    A[0, 0] = 1
    # Right boundary
    b[-1] = bcs[-1]
    A[-1, :] = 1

    for nx in range(1, n - 1):
        for j in range(n):
            A[nx, j] = A[nx, j] - x[nx]**(j)
        for j in range(2, n):
            A[nx, j] = A[nx, j] + (j) * (j - 1) * x[nx]**(j - 2)

    return numpy.linalg.solve(A, b)
コード例 #16
0
ファイル: __init__.py プロジェクト: Bankq/CS6998
def chebpts2(npts):
    from numpy.polynomial.chebyshev import chebpts2
    return chebpts2(npts)
コード例 #17
0
ファイル: diff.py プロジェクト: WhFanatic/channel_IDM
		plt.legend()
		plt.show()

		plt.close()



if __name__ == '__main__':

	Ny = 201
	Ly = 1.

	# ys = Ly * np.linspace(0, 1, Ny)
	# ys = Ly * (1 - np.cos(.5*np.pi*np.linspace(0,1,Ny)))
	ys = cb.chebpts2(Ny)

	# D1, D2, I2 = Schemes.compact6(ys)
	# D1, D2, I2 = Schemes.center2(ys)
	D1, D2, I1 = Schemes.cheb(ys)

	# us = np.sin(2*np.pi*ys) * np.cos(np.pi*ys**2)
	us = (ys - ys[0]) * (ys[-1] - ys)

	print(cb.chebval(ys, cb.chebint(cb.chebfit(ys, us, len(ys)-1), lbnd=ys[0]))[-1])
	print(np.diag(I1) @ us * (ys[-1]-ys[0]))

	Schemes.check(ys, us, D1, D2)


コード例 #18
0
 def _fit_builtin(self,func,N):
     """ Return the chebyshev coefficients using the builtin chebfit """
     pts = cheb.chebpts2(N)
     y = func(pts)
     coeffs = cheb.chebfit(pts,y,N)
     return coeffs
コード例 #19
0
ファイル: __init__.py プロジェクト: 1950/sawbuck
def chebpts2(npts):
    from numpy.polynomial.chebyshev import chebpts2
    return chebpts2(npts)
コード例 #20
0
"""

# Use sympy to compute a rhs, given an analytical solution
x = Symbol("x")
u = (1 - x ** 2) ** 2 * cos(np.pi * x) * (x - 0.25) ** 2
f = u.diff(x, 2)

# Choices
banded = True
fast_transform = False

N = 20
k = np.arange(N - 2)
# Get points and weights for Chebyshev weighted integrals
points = n_cheb.chebpts2(N)[::-1]
weights = np.zeros((N)) + np.pi / (N - 1)
weights[0] /= 2
weights[-1] /= 2

# Note! N points in real space gives N-2 bases in spectral space

# Build Vandermonde matrix for Lobatto points and weights
V = n_cheb.chebvander(points, N - 3).T - n_cheb.chebvander(points, N - 1)[:, 2:].T

# Gauss-Chebyshev quadrature to compute rhs
fj = np.array([f.subs(x, j) for j in points], dtype=float)  # Get f on quad points


def fastChebScalar(fj):
    return dct(fj, 1) * np.pi / (2 * (len(fj) - 1))
コード例 #21
0
weighted L_w norm (u, v)_w = \int_{-1}^{1} u v / \sqrt(1-x^2) dx

    (\nabla^ u, \phi_k)_w = (f, \phi_k)_w 
    

"""

# Use sympy to compute a rhs, given an analytical solution
x = Symbol("x")
u = cos(np.pi * x)
f = u.diff(x, 2)

N = 50
k = np.arange(N - 2).astype(np.float)
# Get points and weights for Chebyshev weighted integrals
points = n_cheb.chebpts2(N)[::-1]
weights = np.zeros((N)) + np.pi / (N - 1)
weights[0] /= 2
weights[-1] /= 2

# Build Vandermonde matrix for Lobatto points and weights
V = n_cheb.chebvander(points, N - 3).T - (
    (k /
     (k + 2))**2)[:, np.newaxis] * n_cheb.chebvander(points, N - 1)[:, 2:].T
V = V[1:, :]  # Not using k=0


def fastShenTransNeumann(fj):
    """Fast Shen transform on cos(j*pi/N).
    """
    cj = fastShenScalarNeumann(fj)