def prob4():
    """For n = 2^2, 2^3, ..., 2^8, calculate the error of intepolating Runge's
    function on [-1,1] with n points using SciPy's BarycentricInterpolator
    class, once with equally spaced points and once with the Chebyshev
    extremal points. Plot the absolute error of the interpolation with each
    method on a log-log plot.
    """
    domain = np.linspace(-1, 1, 400)
    n_array = [2**i for i in range(2,9)]
    f = lambda x: 1 / (1 + 25*x**2)
    plt.ion()
    poly_error = []
    cheby_error = []
    for n in n_array:
        x = np.linspace(-1, 1, n)
        poly = BarycentricInterpolator(x)
        poly.set_yi(f(x))
        poly_error.append(la.norm(f(domain) - poly(domain), ord=np.inf))
        y = np.array([(1/2)*(2*np.cos(j*np.pi/n)) for j in range(n+1)])
        cheby = BarycentricInterpolator(y)
        cheby.set_yi(f(y))
        cheby_error.append(la.norm(f(domain) - cheby(domain), ord=np.inf))
    plt.loglog(n_array, poly_error, label="equally spaced points", basex=2)
    plt.loglog(n_array, cheby_error, label="Chebyshev extremal points", basex=2)
    plt.legend()
    plt.show()
Exemplo n.º 2
0
 def interpolator(self, x, values):
     """Returns a polynomial with vector coefficients which interpolates the
     values at the Chebyshev points x."""
     # hacking the barycentric interpolator by computing the weights in advance
     p = Bary([0.])
     N = len(values)
     weights = np.ones(N)
     weights[0] = .5
     weights[1::2] = -1
     weights[-1] *= .5
     p.wi = weights
     p.xi = x
     p.set_yi(values)
     return p
Exemplo n.º 3
0
def estimate_function_for_air_data(n):
    """Interpolate the air quality data found in airdata.npy using
    Barycentric Lagrange interpolation. Plots the original data and the
    interpolating polynomial.

    Parameters:
        n (int): Number of interpolating points to use.
    """
    #dataset of air quality
    data = np.load('airdata.npy')

    #chevy extrizers
    fx = lambda a, b, n: .5 * (a + b +
                               (b - a) * np.cos(np.arange(n + 1) * np.pi / n))
    #scaled intervals to apx chevy extremizers
    a, b = 0, 366 - 1 / 24
    #scaled domain
    domain = np.linspace(0, b, 8784)
    #apx chevy extrema with regars to actual data (non continuous data....)
    points = fx(a, b, n)
    #mask for extrema aprx
    temp = np.abs(points - domain.reshape(8784, 1))
    temp2 = np.argmin(temp, axis=0)
    #interpolating poylynomial
    poly = BarycentricInterpolator(domain[temp2])
    poly.set_yi(data[temp2])

    #plot the data
    #set up plot settings
    plt.subplot(211)
    plt.title("PM_2.5 hourly concentration data 2016")
    plt.xlabel("Hours from Jan 1")
    plt.ylabel("PM_2.5 level")
    plt.plot(data)

    #domain for graph
    # x = np.linspace(0, 8784, 8784 * 10)
    x = np.linspace(0, b, len(domain))
    #plot the data
    #set up plot settings
    plt.subplot(212)
    plt.xlabel("Days from Jan 1")
    plt.ylabel("PM_2.5 level")
    plt.title("Aproximating Polynomial")

    #show graph
    plt.plot(x, poly(x))
    plt.tight_layout()
    plt.show()
Exemplo n.º 4
0
def test_barcentric_against_runges_function():
    """For n = 2^2, 2^3, ..., 2^8, calculate the error of intepolating Runge's
    function on [-1,1] with n points using SciPy's BarycentricInterpolator
    class, once with equally spaced points and once with the Chebyshev
    extremal points. Plot the absolute error of the interpolation with each
    method on a log-log plot.
    """
    #domain for graph
    d = np.linspace(-1, 1, 400)
    #iterations for testing B interp. point effect
    N = [2**2, 2**3, 2**4, 2**5, 2**6, 2**7, 2**8]
    #function to approximate
    f = np.vectorize(lambda x: 1 / (1 + 25 * x**2))
    #to chevy, extrema
    ch_ext = lambda a, b, n: .5 * (a + b + (b - a) * np.cos(
        (np.arange(0, n) * np.pi) / n))
    #evenly spaced error margins
    e1 = []
    #cheby extram interp error margins
    e2 = []
    for n in N:

        #points to interpolate
        pts = np.linspace(-1, 1, n)
        #interpolate
        poly = BarycentricInterpolator(pts)
        poly.set_yi(f(pts))
        #get errror in terms of infinity norm
        e1.append(la.norm(f(d) - poly(d), ord=np.inf))

        #points to interpolate
        pts = ch_ext(-1, 1, n + 1)
        #interpolate
        poly = BarycentricInterpolator(pts)
        poly.set_yi(f(pts))
        #get errror in terms of infinity norm
        e2.append(la.norm(f(d) - poly(d), ord=np.inf))

    #graph everything n terms of log base 10
    plt.xscale('log', basex=10)
    plt.yscale('log', basey=10)
    plt.plot(N, e1, label="uniform points")
    plt.plot(N, e2, label="chev. extrema")
    #set graph labels
    plt.xlabel("# of interp. points")
    plt.ylabel("Error")
    plt.title("Uniform vs Cheby interp. error")
    plt.legend()
    plt.show()
Exemplo n.º 5
0
 def interpolator(self, x, values):
     """
     Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x
     """
     # hacking the barycentric interpolator by computing the weights in advance
     p = Bary([0.])
     N = len(values)
     weights = np.ones(N)
     weights[0] = .5
     weights[1::2] = -1
     weights[-1] *= .5
     p.wi = weights
     p.xi = x
     p.set_yi(values)
     return p
Exemplo n.º 6
0
def generalized_gauss(collocation_points, verbose=False):
    p, result1, result2 = args.degree, [], []
    interp = BarycentricInterpolator(collocation_points)
    for n in range(p//2):
        filename = 'weights{}.txt'.format(n+1)
        with open(filename) as f:
            header = f.readline()
            x = float(header.split()[-1])
            # check if quadrature is for the given collacation point
            assert math.isclose(x, collocation_points[n], rel_tol=fixed.exact_tol)
        y, w = np.loadtxt(filename, unpack=True)
        check_generalized(lambda f: np.sum(w*f(y)), x, verbose)
        I, b1, b2 = np.eye(collocation_points.size), [], []
        for i in range(collocation_points.size):
            interp.set_yi(I[i])
            b1.append(interp(y))
            b2.append(interp(1-y[::-1]))
        result1.append(( y, w, np.array(b1) ))
        result2.append(( 1-y[::-1], w[::-1], np.array(b2) ))
    return result1 + result2[::-1]
Exemplo n.º 7
0
 def test_delayed(self):
     P = BarycentricInterpolator(self.xs)
     P.set_yi(self.ys)
     assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs))
Exemplo n.º 8
0
 def test_delayed(self):
     P = BarycentricInterpolator(self.xs)
     P.set_yi(self.ys)
     assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs))
Exemplo n.º 9
0
image_step = 200

for i in np.arange(n_images * image_step):
    if i % image_step == 0:
        fig = plt.figure(figsize=(20, 16))
        gs = gridspec.GridSpec(3, 3)
        ax0 = fig.add_subplot(gs[1:, 1:])
        axh = fig.add_subplot(gs[1, 0])
        axh.set_title('h')
        axQ_minus = fig.add_subplot(gs[0, 1])
        axQ_minus.set_title('Q_minus')
        axT_minuse = fig.add_subplot(gs[0, 2])
        axT_minuse.set_title('T_minus')
        axshear = fig.add_subplot(gs[2, 0])
        axshear.set_title('shear')
        interpolator.set_yi(active_space_a)
        ac_space_a_plot = np.array(map(interpolator, rng))
        HB_int = np.argmin(
            np.abs(ac_space_a_plot - 0.5 *
                   (np.max(ac_space_a_plot) - np.min(ac_space_a_plot))))
        print HB_int
        ax0.plot(rng,
                 np.array(map(interpolator, rng)) / 10. +
                 np.max(active_const_a) / 10.,
                 label='active_a')
        interpolator.set_yi(active_space_i)
        ax0.plot(rng,
                 np.array(map(interpolator, rng)) / 10. +
                 np.max(active_const_i) / 10.,
                 label='active_i')
        interpolator.set_yi(v_x)
image_step= 200

for i in np.arange(n_images*image_step):
    if i%image_step == 0:
        fig= plt.figure(figsize=(20,16))
        gs= gridspec.GridSpec(3,3)
        ax0= fig.add_subplot(gs[1:,1:])
        axh= fig.add_subplot(gs[1,0])
        axh.set_title('h')
        axQ_minus= fig.add_subplot(gs[0,1])
        axQ_minus.set_title('Q_minus')
        axT_minuse=fig.add_subplot(gs[0,2])
        axT_minuse.set_title('T_minus')
        axshear= fig.add_subplot(gs[2,0])
        axshear.set_title('shear')
        interpolator.set_yi(active_space_a)
        ac_space_a_plot= np.array(map(interpolator, rng))
        HB_int= np.argmin(np.abs(ac_space_a_plot- 0.5*(np.max(ac_space_a_plot)-np.min(ac_space_a_plot))))
        print HB_int
        ax0.plot(rng, np.array(map(interpolator, rng))/10.+ np.max(active_const_a)/10.,label= 'active_a')
        interpolator.set_yi(active_space_i)
        ax0.plot(rng, np.array(map(interpolator, rng))/10.+ np.max(active_const_i)/10.,label= 'active_i')
        interpolator.set_yi(v_x)
        ax0.plot(rng, np.array(map(interpolator,rng))*3., label= 'vx')
        interpolator.set_yi(h)
        h_plot=np.array(map(interpolator,rng))
        avg_h_blade.append(np.sum(h_plot[HB_int:])*x_step/(rng[-1]-rng[HB_int]))
        axh.plot(range(len(avg_h_blade)),avg_h_blade)
        axh.set_xlim([0,n_images])
        ax0.plot(rng, np.array(map(interpolator,rng))/5., label='h')
        interpolator.set_yi(Q_minus)