def test_divmod(self) : tquo = ch.Chebyshev([1]) trem = ch.Chebyshev([2]) quo, rem = divmod(self.p5, self.p1) assert_(quo == tquo and rem == trem) quo, rem = divmod(self.p5, [1,2,3]) assert_(quo == tquo and rem == trem) quo, rem = divmod([3,2,3], self.p1) assert_(quo == tquo and rem == trem)
def remezToPoly(remez): cheby = C.Chebyshev(remez.weights) p = cheby.convert(kind=P.Polynomial) p = p(rebase) # (x0, x1) = remez.domain # p = p(P.Polynomial([-x0 / (x1 - x0), 1.0 / (x1 - x0)])) return p
def cheby_newton_root(z, f, z0=None, degree=512): import numpy.polynomial.chebyshev as npcheb import scipy.optimize as scpop Lz = np.max(z) - np.min(z) if z0 is None: z0 = Lz / 2 def to_x(z, Lz): # convert back to [-1,1] return (2 / Lz) * z - 1 def to_z(x, Lz): # convert back from [-1,1] return (x + 1) * Lz / 2 logger.info("searching for roots starting from z={}".format(z0)) x = to_x(z, Lz) x0 = to_x(z0, Lz) cheb_coeffs = npcheb.chebfit(x, f, degree) cheb_interp = npcheb.Chebyshev(cheb_coeffs) cheb_der = npcheb.chebder(cheb_coeffs) def newton_func(x_newton): return npcheb.chebval(x_newton, cheb_coeffs) def newton_derivative_func(x_newton): return npcheb.chebval(x_newton, cheb_der) try: x_root = scpop.newton(newton_func, x0, fprime=newton_derivative_func, tol=1e-10) z_root = to_z(x_root, Lz) except: logger.info("error in root find") x_root = np.nan z_root = np.nan logger.info("newton: found root z={} (x0:{} -> {})".format( z_root, x0, x_root)) for x0 in x: print(x0, newton_func(x0)) a = Lz / 4 b = Lz * 3 / 4 logger.info("bisecting between z=[{},{}] (x=[{},{}])".format( a, b, to_x(a, Lz), to_x(b, Lz))) logger.info("f(a) = {} and f(b) = {}".format(newton_func(to_x(a, Lz)), newton_func(to_x(b, Lz)))) x_root_2 = scpop.bisect(newton_func, to_x(a, Lz), to_x(b, Lz)) z_root_2 = to_z(x_root_2, Lz) logger.info("bisect: found root z={} (x={})".format(z_root_2, x_root_2)) return z_root_2
def convert_to_poly(p): if p[0].lower().startswith("poly"): return P.Polynomial(p[1]) elif p[0].lower().startswith("cheb"): v = cheb.Chebyshev(p[1], domain=p[2], window=p[3]) return v return None
def test_collocation_points_chebyshev_gauss_lobatto(self): for num_coll_points in range(2, 13): coefs = np.zeros(num_coll_points) coefs[-1] = 1. coll_points_numpy = np.concatenate( ([-1.], chebyshev.Chebyshev(coefs).deriv().roots(), [1.])) mesh = Mesh1D(num_coll_points, Basis.Chebyshev, Quadrature.GaussLobatto) coll_points_spectre = collocation_points(mesh) np.testing.assert_allclose(coll_points_numpy, coll_points_spectre, 1e-12, 1e-12)
def get_orthpoly(n_deg, f_weighting, n_extra_point=10, return_coef=True, representation='chebyshev', integral_method='legendre'): """ Get orthogonal polynomials with respect to the weighting (f_weighting). The polynomials are represented by coefficients of Chebyshev polynomials. Evaluate it as: np.dot(cheb.chebvander(set_of_x, n_deg), repr_coef) See weighted_orthpoly1.py for validation of this algorithm. """ n_sampling = n_deg + 1 + n_extra_point # Do the intergration by discrete sampling at good points. if integral_method == 'chebyshev': # Here we use (first kind) Chebyshev points. x_sampling = chebyshev_roots(n_sampling) # Put together the weighting and the weighting of the Gauss-Chebyshev quadrature. diag_weight = np.array( [f_weighting(x) / cheb.chebweight(x) for x in x_sampling]) * (pi / n_sampling) elif integral_method == 'legendre': # Use Gauss-Legendre quadrature. x_sampling, int_weight = lege.leggauss(n_sampling) diag_weight = np.array( [f_weighting(x) * w for x, w in zip(x_sampling, int_weight)]) if representation == 'chebyshev': V = cheb.chebvander(x_sampling, n_deg) else: V = lege.legvander(x_sampling, n_deg) # Get basis from chol of the Gramian matrix. # inner_prod_matrix = dot(V.T, diag_weight[:, np.newaxis] * V) # repr_coef = inv(cholesky(inner_prod_matrix).T) # QR decomposition should give more accurate result. repr_coef = inv(qr(sqrt(diag_weight[:, np.newaxis]) * V, mode='r')) repr_coef = repr_coef * sign(sum(repr_coef, axis=0)) if return_coef: return repr_coef else: if representation == 'chebyshev': polys = [cheb.Chebyshev(repr_coef[:, i]) for i in range(n_deg + 1)] else: polys = [lege.Legendre(repr_coef[:, i]) for i in range(n_deg + 1)] return polys
def __init__(self, fitparams): # handed a list or tuple of firparams (which includes flags # for type of fit) sets up the irafcurve instance. # should be an int but it i'nt sometimes typecode = int(fitparams[0] + 0.001) if typecode == 1: self.curvetype = 'chebyshev' elif typecode == 2: self.curvetype = 'legendre' elif typecode == 3: self.curvetype = 'spline3' else: print("Unknown fit type: ", fitparams[0]) # the 'iraforder' is not the conventional order; it's # the number of coefficients for a polynomial, so a # a straight line has iraforder = 2. For a spline3 it is # the number of spline segments. self.iraforder = int(fitparams[1] + 0.001) self.xrange = (fitparams[2], fitparams[3]) self.span = self.xrange[1] - self.xrange[0] self.sumrange = self.xrange[0] + self.xrange[1] self.fitcoeffs = np.array(fitparams[4:]) # Numpy provides built-in legendre and chebyshev apparatuses that make # this trivial. The numpy spline3 is apparently oriented toward interpolation, # and wasn't as easy to adapt, though I'm probably missing something. My own # spline3 stuff works correctly though it's more awkward. if self.curvetype == 'legendre': self.lpoly = leg.Legendre(self.fitcoeffs, domain = [self.xrange[0], self.xrange[1]]) if self.curvetype == 'chebyshev': self.chpoly = cheb.Chebyshev(self.fitcoeffs, domain = [self.xrange[0], self.xrange[1]])
def test_pow(self) : tgt = ch.Chebyshev([1]) for i in range(5) : res = self.p1**i assert_(res == tgt) tgt *= self.p1
def T(idx=0): coefs = np.zeros(idx + 1) coefs[idx] = 1 return cheb.Chebyshev(coefs)
def test_mod(self) : tgt = ch.Chebyshev([1]) assert_((self.p4 % self.p1) == tgt) assert_((self.p4 % [1,2,3]) == tgt) assert_(([2,2,3] % self.p1) == tgt)
def test_floordiv(self) : tgt = ch.Chebyshev([1]) assert_(self.p4 // self.p1 == tgt) assert_(self.p4 // [1,2,3] == tgt) assert_([2,2,3] // self.p1 == tgt)
def test_mul(self) : tgt = ch.Chebyshev([7.5, 10., 8., 6., 4.5]) assert_(self.p1 * self.p1 == tgt) assert_(self.p1 * [1,2,3] == tgt) assert_([1,2,3] * self.p1 == tgt)
def read_cheby(cb_group_name): c = f[cb_group_name]['c'][...] x_a = f[cb_group_name].attrs['x_a'] x_b = f[cb_group_name].attrs['x_b'] c[0] *= 0.5 return cheby.Chebyshev(c, domain=[x_a, x_b])
def chebfit(xs, ys, deg): coeffs = cheb.chebfit(xs, ys, deg) p = cheb.Chebyshev(coeffs) return mkseries(xs, ys, p)
y = lag_pol(x) plt.plot(x, y, label='Interpolacion') plt.plot(xp, fp, 'o', label='Muestras') plt.plot(x, runge(x), label='Real') plt.legend(loc='upper center') plt.show() from numpy.polynomial import chebyshev # Importar polinomio de Chebyshev N = 11 # Nodos de interpolacion coeffs_cheb = [0] * N + [1] # Tomar el elemento 11 de la serie print(coeffs_cheb) T11 = chebyshev.Chebyshev(coeffs_cheb, [-5, 5]) xp_ch = T11.roots() xp_ch fp = runge(xp_ch) x = np.linspace(-5, 5, 200) lag_pol = interpolate.lagrange(xp_ch, fp) y = lag_pol(x) plt.plot(x, y, label='Interpolacion') plt.plot(xp_ch, fp, 'o', label='Muestras') plt.plot(x, runge(x), label='Real')
from numpy.polynomial import chebyshev import numpy as np from scipy.interpolate import barycentric_interpolate def runge(x): """FunciĆ³n de Runge.""" return 1 / (1 + 25 * x**2) N = 3 # Nodos de interpolaciĆ³n xp = array([3, 8, 20]) fp = runge(xp) x = np.linspace(0, 20) y = barycentric_interpolate(xp, fp, x) #------- from numpy.polynomial import chebyshev coeffs_cheb = [0] * 3 + [1] T3 = chebyshev.Chebyshev(coeffs_cheb, [0, 20]) xp_ch = T3.roots()
def __init__(self, f, interval=[-1, 1], degs=[3, 3], coeffs=None): """ Find the rational approximation of a given function. Parameters ---------- f : 1-D function Function to be approximated. Should be real-valued and accept real inputs. interval : array-like, optional (not quite working yet--best to leave as [-1,1]) Left and right endpoints of interval over which to approximate f. f is approximated over interval[0] <= x <= interval[1]. Modifies the interval variable of the Rational_approximation object to match interval degs : array-like, optional Degrees of the polynomials in the numerator and denominator. deg(numerator) = degs[0], deg(denominator) = degs[1] coeffs : array-like, optional Array-like object with two entries. The first should contain the Chebyshev cofficients of the numerator and the second the Chebyshev coefficients of the denominator of the rational approximation. coeffs may also be a dict with keys num and denom with corresponding values the Chebyshev coefficients of the numerator and denominator. Note: passing in coefficients will cause the function f to be ignored Example ---------- import matplotlib.pyplot as plt f = lambda x: np.exp(-x) r = Rational(f, degs=[3,3]) x = np.linspace(-1,3) plt.plot(x,f(x),'b-',x,r.eval(x),'r--') plt.legend(["True function","Rational approximation"]) plt.show() """ # Map the interval to [-1,1] assert len(interval) == 2, "interval must consist of two points" assert interval[0] < interval[ 1], "interval[0] must be less than interval[1]" self.interval = interval a, b = interval[0], interval[1] # f_norm = lambda x: f((2. * x - a - b) / (b - a)) f_norm = lambda x: f((x * (b - a) + a + b) / 2.) # Get the coefficients, if given if coeffs is None: self.coeffs = {'num': C.Chebyshev(0), 'denom': C.Chebyshev(0)} else: if isinstance(coeffs, dict): self.coeffs = coeffs else: assert len(coeffs) == 2, "coeffs must have exactly two entries" self.coeffs = { 'num': C.Chebyshev(coeffs[0], domain=interval), 'denom': C.Chebyshev(coeffs[1], domain=interval) } return # Find Chebyshev representation of f_norm * q assert len(degs) == 2, "degs must consist of two numbers" assert type(degs[0]) == int and type( degs[1]) == int, "entries of degs must be integers" assert degs[0] > -1 and degs[ 1] > -1, "entries of degs must be nonnegative" n, m = degs[0], degs[1] N = n + m # Total degree of p and q f_cheb_coeffs = np.zeros(N + m + 1) # (Could be made more efficient by using fixed points and precomputing f_norm(cos(theta))) f_cheb_coeffs[0] = (2 / np.pi) * quad( lambda theta: f_norm(np.cos(theta)), 0, np.pi)[0] for k in range(1, N + m + 1): f_cheb_coeffs[k] = (2 / np.pi) * quad( lambda theta: f_norm(np.cos(theta)) * np.cos(k * theta), 0, np.pi)[0] # Form linear system to be solved for Chebyshev coefficients of p and q A = np.zeros((N + 1, N + 2)) for i in range(N + 1): if i <= n: A[i, i] = 1 for j in range(n + 1, N + 1): if i > 0: A[i, j] = -(f_cheb_coeffs[i + j - n] + f_cheb_coeffs[np.abs(i - j + n)]) / 2. else: # Can vectorize this A[i, j] = -f_cheb_coeffs[j - n] / 2. A[:, N + 1] = f_cheb_coeffs[:N + 1] A[0, N + 1] /= 2 # Solve linear system and interpret coefficients as Chebyshev polynomials x = np.linalg.solve(A[:, :-1], A[:, -1]) self.coeffs['num'] = C.Chebyshev(x[:n + 1], domain=interval) self.coeffs['denom'] = C.Chebyshev(np.concatenate(([1], x[n + 1:]), axis=None), domain=interval)
def trace_aperture_chebyshev_old(xy_list, domain=None): """ a list of (x_array, y_array). y_array must be a masked array """ import numpy.polynomial.chebyshev as cheb #for x, y in r["cent_bottom_list"]: # xy_list = r["cent_up_list"] # domain = [0, 2047] if domain is None: xmax = max(x.max() for x, y in xy_list) xmin = min(x.min() for x, y in xy_list) domain = [xmin, xmax] #xx = np.arange(domain[0], domain[1]+1) # fit with chebyshev polynomical with domain 0..2047 f_list = [] for x, y in xy_list: msk = ~y.mask & np.isfinite(y.data) x1, y1 = x[msk], y.data[msk] f = cheb.Chebyshev.fit(x1, y1, 4, domain=domain) f_list.append(f) # fit 3rd and 2nd order term to remove erroneous value o = np.arange(len(f_list)) # fitting poly order = 1, sigma = 3 y3_ = [f_.coef[3] for f_ in f_list] p3_ = polyfitr(o, y3_, 1, 3) p3 = np.polyval(p3_, o) # fitting poly order = 2, sigma = 3 y2_ = [f_.coef[2] for f_ in f_list] p2_ = polyfitr(o, y2_, 2, 3) p2 = np.polyval(p2_, o) # now subtract the fitted 3rd and 2nd term from the original data, # and then refit with 1st order poly. f2_list = [] for i, (x, y) in enumerate(xy_list): f = f_list[i] y_3 = p3[i]*f.basis(3, domain=domain)(x) y_2 = p2[i]*f.basis(2, domain=domain)(x) y = y - (y_2+y_3) msk = ~y.mask & np.isfinite(y.data) x1, y1 = x[msk], y.data[msk] # fit with 1st poly. f_ = cheb.Chebyshev.fit(x1, y1, 1, domain=domain) # now, regenerate 3d poly. f = cheb.Chebyshev(np.concatenate([f_.coef, [p2[i], p3[i]]]), domain=domain) f2_list.append(f) return f2_list
def test_trim(self) : coef = [1, 1e-6, 1e-12, 0] p = ch.Chebyshev(coef) assert_equal(p.trim().coef, coef[:3]) assert_equal(p.trim(1e-10).coef, coef[:2]) assert_equal(p.trim(1e-5).coef, coef[:1])
def test_add(self) : tgt = ch.Chebyshev([2,4,6]) assert_(self.p1 + self.p1 == tgt) assert_(self.p1 + [1,2,3] == tgt) assert_([1,2,3] + self.p1 == tgt)
def test_roots(self) : p = ch.Chebyshev(ch.poly2cheb([0, -1, 0, 1]), [0, 1]) res = p.roots() tgt = [0, .5, 1] assert_almost_equal(res, tgt)
def test_sub(self) : tgt = ch.Chebyshev([1]) assert_(self.p4 - self.p1 == tgt) assert_(self.p4 - [1,2,3] == tgt) assert_([2,2,3] - self.p1 == tgt)
class TestChebyshevClass(TestCase) : p1 = ch.Chebyshev([1,2,3]) p2 = ch.Chebyshev([1,2,3], [0,1]) p3 = ch.Chebyshev([1,2]) p4 = ch.Chebyshev([2,2,3]) p5 = ch.Chebyshev([3,2,3]) def test_equal(self) : assert_(self.p1 == self.p1) assert_(self.p2 == self.p2) assert_(not self.p1 == self.p2) assert_(not self.p1 == self.p3) assert_(not self.p1 == [1,2,3]) def test_not_equal(self) : assert_(not self.p1 != self.p1) assert_(not self.p2 != self.p2) assert_(self.p1 != self.p2) assert_(self.p1 != self.p3) assert_(self.p1 != [1,2,3]) def test_add(self) : tgt = ch.Chebyshev([2,4,6]) assert_(self.p1 + self.p1 == tgt) assert_(self.p1 + [1,2,3] == tgt) assert_([1,2,3] + self.p1 == tgt) def test_sub(self) : tgt = ch.Chebyshev([1]) assert_(self.p4 - self.p1 == tgt) assert_(self.p4 - [1,2,3] == tgt) assert_([2,2,3] - self.p1 == tgt) def test_mul(self) : tgt = ch.Chebyshev([7.5, 10., 8., 6., 4.5]) assert_(self.p1 * self.p1 == tgt) assert_(self.p1 * [1,2,3] == tgt) assert_([1,2,3] * self.p1 == tgt) def test_floordiv(self) : tgt = ch.Chebyshev([1]) assert_(self.p4 // self.p1 == tgt) assert_(self.p4 // [1,2,3] == tgt) assert_([2,2,3] // self.p1 == tgt) def test_mod(self) : tgt = ch.Chebyshev([1]) assert_((self.p4 % self.p1) == tgt) assert_((self.p4 % [1,2,3]) == tgt) assert_(([2,2,3] % self.p1) == tgt) def test_divmod(self) : tquo = ch.Chebyshev([1]) trem = ch.Chebyshev([2]) quo, rem = divmod(self.p5, self.p1) assert_(quo == tquo and rem == trem) quo, rem = divmod(self.p5, [1,2,3]) assert_(quo == tquo and rem == trem) quo, rem = divmod([3,2,3], self.p1) assert_(quo == tquo and rem == trem) def test_pow(self) : tgt = ch.Chebyshev([1]) for i in range(5) : res = self.p1**i assert_(res == tgt) tgt *= self.p1 def test_call(self) : # domain = [-1, 1] x = np.linspace(-1, 1) tgt = 3*(2*x**2 - 1) + 2*x + 1 assert_almost_equal(self.p1(x), tgt) # domain = [0, 1] x = np.linspace(0, 1) xx = 2*x - 1 assert_almost_equal(self.p2(x), self.p1(xx)) def test_degree(self) : assert_equal(self.p1.degree(), 2) def test_cutdeg(self) : assert_raises(ValueError, self.p1.cutdeg, .5) assert_raises(ValueError, self.p1.cutdeg, -1) assert_equal(len(self.p1.cutdeg(3)), 3) assert_equal(len(self.p1.cutdeg(2)), 3) assert_equal(len(self.p1.cutdeg(1)), 2) assert_equal(len(self.p1.cutdeg(0)), 1) def test_convert(self) : x = np.linspace(-1,1) p = self.p1.convert(domain=[0,1]) assert_almost_equal(p(x), self.p1(x)) def test_mapparms(self) : parms = self.p2.mapparms() assert_almost_equal(parms, [-1, 2]) def test_trim(self) : coef = [1, 1e-6, 1e-12, 0] p = ch.Chebyshev(coef) assert_equal(p.trim().coef, coef[:3]) assert_equal(p.trim(1e-10).coef, coef[:2]) assert_equal(p.trim(1e-5).coef, coef[:1]) def test_truncate(self) : assert_raises(ValueError, self.p1.truncate, .5) assert_raises(ValueError, self.p1.truncate, 0) assert_equal(len(self.p1.truncate(4)), 3) assert_equal(len(self.p1.truncate(3)), 3) assert_equal(len(self.p1.truncate(2)), 2) assert_equal(len(self.p1.truncate(1)), 1) def test_copy(self) : p = self.p1.copy() assert_(self.p1 == p) def test_integ(self) : p = self.p2.integ() assert_almost_equal(p.coef, ch.chebint([1,2,3], 1, 0, scl=.5)) p = self.p2.integ(lbnd=0) assert_almost_equal(p(0), 0) p = self.p2.integ(1, 1) assert_almost_equal(p.coef, ch.chebint([1,2,3], 1, 1, scl=.5)) p = self.p2.integ(2, [1, 2]) assert_almost_equal(p.coef, ch.chebint([1,2,3], 2, [1,2], scl=.5)) def test_deriv(self) : p = self.p2.integ(2, [1, 2]) assert_almost_equal(p.deriv(1).coef, self.p2.integ(1, [1]).coef) assert_almost_equal(p.deriv(2).coef, self.p2.coef) def test_roots(self) : p = ch.Chebyshev(ch.poly2cheb([0, -1, 0, 1]), [0, 1]) res = p.roots() tgt = [0, .5, 1] assert_almost_equal(res, tgt) def test_fromroots(self) : roots = [0, .5, 1] p = ch.Chebyshev.fromroots(roots, domain=[0, 1]) res = p.coef tgt = ch.poly2cheb([0, -1, 0, 1]) assert_almost_equal(res, tgt) def test_fit(self) : def f(x) : return x*(x - 1)*(x - 2) x = np.linspace(0,3) y = f(x) # test default value of domain p = ch.Chebyshev.fit(x, y, 3) assert_almost_equal(p.domain, [0,3]) # test that fit works in given domains p = ch.Chebyshev.fit(x, y, 3, None) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, [0,3]) p = ch.Chebyshev.fit(x, y, 3, []) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, [-1, 1]) def test_identity(self) : x = np.linspace(0,3) p = ch.Chebyshev.identity() assert_almost_equal(p(x), x) p = ch.Chebyshev.identity([1,3]) assert_almost_equal(p(x), x)
from numpy.polynomial import chebyshev import matplotlib.pyplot as plt from scipy.interpolate import lagrange import numpy as np from scipy import interpolate coeffs_cheb = [0] * 11 + [1] # Solo queremos el elemento 11 de la serie T10 = chebyshev.Chebyshev(coeffs_cheb, [-3, 3]) xp_ch_10 = T10.roots() print(xp_ch_10) coeffs_cheb = [0] * 21 + [1] # Solo queremos el elemento 11 de la serie T21 = chebyshev.Chebyshev(coeffs_cheb, [-3, 3]) xp_ch_21 = T21.roots() print(xp_ch_21) def orginalfunction(xi:float): return ((1+xi**2)**-1) listO10=[orginalfunction(elem) for elem in xp_ch_10] listO20=[orginalfunction(elem) for elem in xp_ch_21] p10_r = np.poly1d(np.polyfit(xp_ch_10, listO10, 10)) p20_r = np.poly1d(np.polyfit(xp_ch_21, listO20, 20)) t= np.linspace(-3,3,50)