def __init__(self, degX, xMin, xMax, degY, yMin, yMax): self.degX = degX self.xMin = xMin self.xMax = xMax self.xRange = xMax - xMin self.degY = degY self.yMin = yMin self.yMax = yMax self.yRange = yMax - yMin self.Xp = sps.chebyt(self.degX) self.Yp = sps.chebyt(self.degY)
def fchebyshev(x, m): """Compute the first `m` Chebyshev polynomials. Parameters ---------- x : array-like Compute the Chebyshev polynomials at these abscissa values. m : :class:`int` The number of Chebyshev polynomials to compute. For example, if :math:`m = 3`, :math:`T_0 (x)`, :math:`T_1 (x)` and :math:`T_2 (x)` will be computed. Returns ------- :class:`numpy.ndarray` """ if isinstance(x, np.ndarray): n = x.size else: n = 1 if m < 1: raise ValueError('Order of Chebyshev polynomial must be at least 1.') try: dt = x.dtype except AttributeError: dt = np.float64 leg = np.ones((m, n), dtype=dt) if m >= 2: leg[1, :] = x if m >= 3: for k in range(2, m): leg[k, :] = np.polyval(chebyt(k), x) return leg
def fchebyshev(x, m): """Compute the first `m` Chebyshev polynomials. Parameters ---------- x : array-like Compute the Chebyshev polynomials at these abscissa values. m : :class:`int` The number of Chebyshev polynomials to compute. For example, if :math:`m = 3`, :math:`T_0 (x)`, :math:`T_1 (x)` and :math:`T_2 (x)` will be computed. Returns ------- :class:`numpy.ndarray` """ from scipy.special import chebyt if isinstance(x, np.ndarray): n = x.size else: n = 1 if m < 1: raise ValueError('Order of Chebyshev polynomial must be at least 1.') try: dt = x.dtype except AttributeError: dt = np.float64 leg = np.ones((m, n), dtype=dt) if m >= 2: leg[1, :] = x if m >= 3: for k in range(2, m): leg[k, :] = np.polyval(chebyt(k), x) return leg
def __init__(self, order): self.order = order from scipy.special import chebyt self.poly = chebyt(order) self.domain = (-1, 1) self.intdomain = (-1+1e-6, 1-1e-6) #not sure if I need this, in integration nans are possible on the boundary self.offsetfactor = 0.01 #required for integration
def get_mode_cheb_coeffs(self, mode_index, cheb_order): """ Cheb coeffs of a mode. The projection process is performed on [0,1]^dim. """ import scipy.special as sps cheby_nodes, _, cheby_weights = \ sps.chebyt(cheb_order).weights.T # pylint: disable=E1136,E0633 window = [0, 1] cheby_nodes = cheby_nodes * (window[1] - window[0]) / 2 + np.mean(window) cheby_weights = cheby_weights * (window[1] - window[0]) / 2 mode = self.get_template_mode(mode_index) grid = np.meshgrid(*[cheby_nodes for d in range(self.dim)], indexing='ij') mvals = mode(*grid) from numpy.polynomial.chebyshev import Chebyshev coef_scale = 2 * np.ones(cheb_order) / cheb_order coef_scale[0] /= 2 basis_1d = np.array([ Chebyshev(coef=_orthonormal(cheb_order, i), domain=window)(cheby_nodes) for i in range(cheb_order) ]) from itertools import product if self.dim == 1: basis_set = basis_1d elif self.dim == 2: basis_set = np.array([ b1.reshape([cheb_order, 1]) * b2.reshape([1, cheb_order]) for b1, b2 in product(*[basis_1d for d in range(self.dim)]) ]) elif self.dim == 3: basis_set = np.array([ b1.reshape([cheb_order, 1, 1]) * b2.reshape([1, cheb_order, 1]) * b3.reshape([1, 1, cheb_order]) for b1, b2, b3 in product(*[basis_1d for d in range(self.dim)]) ]) mode_cheb_coeffs = np.array([ np.sum(mvals * basis) for basis in basis_set ]) * _self_tp(coef_scale, self.dim).reshape(-1) # purge small coeffs whose magnitude are less than 8 times machine epsilon mode_cheb_coeffs[np.abs(mode_cheb_coeffs) < 8 * np.finfo(mode_cheb_coeffs.dtype).eps] = 0 return mode_cheb_coeffs
def axes8(epsoutfile): """Plot of Chebychev polynomials""" g = pyxgraph(key=pyx.graph.key.key(pos="mr",hinside=0), ylimits=(-1.1, 1.1), xlabel="$x$", ylabel="$T_j(x)$") x = arange(-1.0,1.01,0.01) for i in xrange(5): g.pyxplot((x, special.chebyt(i)(x)), title="$T_%d(x)$" % i, style="l", dl=2, color=0) g.pyxsave(epsoutfile)
doplot = 1 if doplot: plt.figure() plt.hist(obs_dist, bins=50, normed=True, color='red') plt.plot(grid, xf, lw=2, color='black') plt.plot(grid, mpdf, lw=2, color='green') plt.title('using Hermite polynomials') plt.show() #check orthonormality: print(np.max(np.abs(inner_cont(dop.polys[:5], 0, 1)[0] -np.eye(5)))) #check orthonormality hpolys = [HPoly(i) for i in range(5)] inn = inner_cont(hpolys, -6, 6)[0] print(np.max(np.abs(inn - np.eye(5)))) print((inn*100000).astype(int)) from scipy.special import hermite, chebyt htpolys = [hermite(i) for i in range(5)] innt = inner_cont(htpolys, -10, 10)[0] print((innt*100000).astype(int)) polysc = [chebyt(i) for i in range(4)] r, e = inner_cont(polysc, -1, 1, weight=lambda x: (1-x*x)**(-1/2.)) print(np.max(np.abs(r - np.diag(np.diag(r)))))
# page 98 import numpy as np import matplotlib.pyplot as plt import scipy.special as spec def Plot(x, y, label, figure, line) : plt.figure(figure) plt.plot(x, y, line, label=label) plt.title('this function', fontsize='large', va='bottom', ha='right') plt.xlabel('x') plt.ylabel('$f(x)$') plt.legend(loc='lower left') plt.grid(True) x = np.linspace(-1., 1., 100) y1 = spec.chebyt(1)(x) Plot(x, y1, '$T_1(x)$', 1,'-') y2 = spec.chebyt(2)(x) Plot(x, y2, '$T_2(x)$', 1,'--') y3 = spec.chebyt(3)(x) Plot(x, y3, '$T_3(x)$', 1,'-.') y4 = spec.chebyt(4)(x) Plot(x, y4, '$T_4(x)$', 1,':') plt.show()
kwargs=mix_kwds) doplot = 1 if doplot: plt.figure() plt.hist(obs_dist, bins=50, normed=True, color='red') plt.plot(grid, xf, lw=2, color='black') plt.plot(grid, mpdf, lw=2, color='green') plt.title('using Hermite polynomials') plt.show() #check orthonormality: print(np.max(np.abs(inner_cont(dop.polys[:5], 0, 1)[0] -np.eye(5)))) #check orthonormality hpolys = [HPoly(i) for i in range(5)] inn = inner_cont(hpolys, -6, 6)[0] print(np.max(np.abs(inn - np.eye(5)))) print((inn*100000).astype(int)) from scipy.special import hermite, chebyt htpolys = [hermite(i) for i in range(5)] innt = inner_cont(htpolys, -10, 10)[0] print((innt*100000).astype(int)) polysc = [chebyt(i) for i in range(4)] r, e = inner_cont(polysc, -1, 1, weight=lambda x: (1-x*x)**(-1/2.)) print(np.max(np.abs(r - np.diag(np.diag(r)))))
import numpy as np import matplotlib.pyplot as plt from scipy.special import chebyt, hermitenorm x = np.linspace(-1, 1, 100) xx = np.linspace(-5, 5, 100) t1 = np.polyval(chebyt(1), x) t2 = np.polyval(chebyt(2), x) t3 = np.polyval(chebyt(3), x) t4 = np.polyval(chebyt(4), x) h1 = np.polyval(hermitenorm(1), x) h2 = np.polyval(hermitenorm(2), x) h3 = np.polyval(hermitenorm(3), x) h4 = np.polyval(hermitenorm(4), x) plt.rc('mathtext', fontset='stix') fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(9, 6)) ax1.plot(x, t1, label=r'$T_{1}(x)$') ax1.plot(x, t2, label=r'$T_{2}(x)$') ax1.plot(x, t3, label=r'$T_{3}(x)$') ax1.plot(x, t4, label=r'$T_{4}(x)$') ax1.legend(loc='best') ax1.set_xlabel(r'$x$') ax1.set_title('First four Chebyshev polynomials of the first kind') ax1.grid() ax2.plot(xx, h1, label=r'$H_{1}(x)$') ax2.plot(xx, h2, label=r'$H_{2}(x)$') ax2.plot(xx, h3, label=r'$H_{3}(x)$')
def P(x): sum = 0 for i in range(n): sum += c[i] * chebyt(i)(x) return sum
def func(k, x): return chebyt(k)(x) * f(x) / math.sqrt(1 - x**2)
return 1. / math.pi else: return 2. / math.pi # Найдем коэффициенты с_k for i in range(n): c[i] = coef(i) * quad(lambda x: func(i, x), a, b)[0] # Функция, которая считает значение искомого многочлена в точке x def P(x): sum = 0 for i in range(n): sum += c[i] * chebyt(i)(x) return sum # Построим на графике sin(x) и многочлен P(x) на отрезке [-1,1] X = np.linspace(a, b, 100) pylab.plot(X, f(X), 'r', lw=2) pylab.plot(X, P(X), 'b', lw=2) # Построим график ошибки на отрезке [-1,1] pylab.plot(X, f(X) - np.array([c[i] * chebyt(i)(X) for i in range(n)]).sum(axis=0), 'g', lw=3) pylab.show()
import bionet.ted.bpa_python as bpa_python if 'linux' in sys.platform: import bionet.ted.bpa_cython_linux2 as bpa_cython elif sys.platform == 'darwin': import bionet.ted.bpa_cython_darwin as bpa_cython else: raise RuntimeError('cannot import binary BPA module') # Try to find the coefficients of a Chebyshev polynomial by solving # a Vandermonde system. This test case should exhibit good accuracy for # N less than about 13: N = 12 i = arange(N) a = 1.0/(i+2) T = chebyt(N-1) f = T(a) V = fliplr(vander(a)) c = array(T)[::-1] start = time() c_solve = bpa_python.bpa(V, f) end = time() print 'Python implementation results:' print 'original c = ', c print 'solved c = ', c_solve print 'error = ', abs(c-c_solve) print 'time = ', end-start start = time()
def test_gh_6721(): # Regresssion test for gh_6721. This should not raise. sc.chebyt(65)(0.2)
import bionet.ted.bpa_python as bpa_python if 'linux' in sys.platform: import bionet.ted.bpa_cython_linux2 as bpa_cython elif sys.platform == 'darwin': import bionet.ted.bpa_cython_darwin as bpa_cython else: raise RuntimeError('cannot import binary BPA module') # Try to find the coefficients of a Chebyshev polynomial by solving # a Vandermonde system. This test case should exhibit good accuracy for # N less than about 13: N = 12 i = arange(N) a = 1.0 / (i + 2) T = chebyt(N - 1) f = T(a) V = fliplr(vander(a)) c = array(T)[::-1] start = time() c_solve = bpa_python.bpa(V, f) end = time() print 'Python implementation results:' print 'original c = ', c print 'solved c = ', c_solve print 'error = ', abs(c - c_solve) print 'time = ', end - start start = time()
def max_rE_gamma_2d(sh_l): max_rE = max_rE_2d(np.max(sh_l)) return np.array([np.polyval(spec.chebyt(deg), max_rE) for deg in sh_l])
def Afunc_pp(n, p, q, sgn): return PseudoPolynomial(p=p * np.array(chebyt(n).coef)[::-1], q=-sgn * q * np.array(chebyu(n-1).coef)[::-1] \ if n > 0 else np.array([0]), r=0)
# page 98 import numpy as np import matplotlib.pyplot as plt import scipy.special as spec def Plot(x, y, label, figure, line): plt.figure(figure) plt.plot(x, y, line, label=label) plt.title('this function', fontsize='large', va='bottom', ha='right') plt.xlabel('x') plt.ylabel('$f(x)$') plt.legend(loc='lower left') plt.grid(True) x = np.linspace(-1., 1., 100) y1 = spec.chebyt(1)(x) Plot(x, y1, '$T_1(x)$', 1, '-') y2 = spec.chebyt(2)(x) Plot(x, y2, '$T_2(x)$', 1, '--') y3 = spec.chebyt(3)(x) Plot(x, y3, '$T_3(x)$', 1, '-.') y4 = spec.chebyt(4)(x) Plot(x, y4, '$T_4(x)$', 1, ':') plt.show()