def extra(): l_bc, r_bc = 0., 1. lmbda = 12 N = 50 D, x = cheb_vectorized(N) M = np.dot(D, D) guess = (.5*(x+1))#**lmbda N2 = 500 def pseudospectral_ode(y): out = np.zeros(y.shape) ypp = M.dot(y) out = 4*ypp - lmbda*np.sinh(lmbda*y) out[0], out[-1] = y[0] - r_bc, y[-1] - l_bc return out u = root(pseudospectral_ode,guess,method='lm',tol=1e-9) print u.success num_sol = BarycentricInterpolator(x,u.x) xx = np.linspace(-1, 1, N2) uu = num_sol.__call__(xx) plt.plot(x,guess,'*b') plt.plot(xx, uu, '-r') # Numerical solution via # the pseudospectral method plt.axis([-1.,1.,0-.1,1.1]) plt.show() plt.clf()
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. """ #initialize the domain and function domain = np.linspace(-1, 1, 400) f = lambda x: 1 / (1 + 25 * x**2) err1 = [] err2 = [] #test for different n value for n in 2**np.arange(2, 9): #test the err between build_in function and original function poly = BarycentricInterpolator(np.linspace(-1, 1, n), f(np.linspace(-1, 1, n))) err1.append(la.norm(f(domain) - poly(domain), ord=np.inf)) #test the err between build_in function with chebshev points and original function points = np.array([np.cos(i * np.pi / n) for i in range(n + 1)]) cheb = BarycentricInterpolator(points, f(points)) err2.append(la.norm(f(domain) - cheb(domain), ord=np.inf)) plt.loglog(2**np.arange(2, 9), err1, "-o", basex=2, label="equally spaced points") plt.loglog(2**np.arange(2, 9), err2, "-o", basex=2, label="Chebyshev extremal points") plt.legend() plt.title("Errors") plt.show()
def extra(): l_bc, r_bc = 0., 1. lmbda = 12 N = 50 D, x = cheb_vectorized(N) M = np.dot(D, D) guess = (.5 * (x + 1)) #**lmbda N2 = 500 def pseudospectral_ode(y): out = np.zeros(y.shape) ypp = M.dot(y) out = 4 * ypp - lmbda * np.sinh(lmbda * y) out[0], out[-1] = y[0] - r_bc, y[-1] - l_bc return out u = root(pseudospectral_ode, guess, method='lm', tol=1e-9) print u.success num_sol = BarycentricInterpolator(x, u.x) xx = np.linspace(-1, 1, N2) uu = num_sol.__call__(xx) plt.plot(x, guess, '*b') plt.plot(xx, uu, '-r') # Numerical solution via # the pseudospectral method plt.axis([-1., 1., 0 - .1, 1.1]) plt.show() plt.clf()
def test_vector(self): xs = [0, 1, 2] ys = np.array([[0,1],[1,0],[2,1]]) P = BarycentricInterpolator(xs,ys) Pi = [BarycentricInterpolator(xs,ys[:,i]) for i in xrange(ys.shape[1])] test_xs = np.linspace(-1,3,100) assert_almost_equal(P(test_xs), np.rollaxis(np.asarray([p(test_xs) for p in Pi]),-1))
def interpolation_matrix_1d(fine_grid, coarse_grid, k=2, periodic=False, pad=1): """ Function to contruct the restriction matrix in 1d using barycentric interpolation Args: fine_grid (np.ndarray): a one dimensional 1d array containing the nodes of the fine grid coarse_grid (np.ndarray): a one dimensional 1d array containing the nodes of the coarse grid k (int): order of the restriction periodic (bool): flag to indicate periodicity pad (int): padding parameter for boundaries Returns: sprs.csc_matrix: interpolation matrix """ n_f = fine_grid.size if periodic: M = np.zeros((fine_grid.size, coarse_grid.size)) for i, p in zip(range(n_f), fine_grid): nn = next_neighbors_periodic(p, coarse_grid, k) circulating_one = np.asarray([1.0] + [0.0] * (k - 1)) cont_arr = continue_periodic_array(coarse_grid, nn) if p > np.mean(fine_grid) and not (cont_arr[0] <= p <= cont_arr[-1]): cont_arr += 1 bary_pol = [] for l in range(k): bary_pol.append( BarycentricInterpolator(cont_arr, np.roll(circulating_one, l))) M[i, nn] = np.asarray(list(map(lambda x: x(p), bary_pol))) else: M = np.zeros((fine_grid.size, coarse_grid.size + 2 * pad)) for i, p in zip(range(n_f), fine_grid): padded_c_grid = border_padding(coarse_grid, pad, pad) nn = next_neighbors(p, padded_c_grid, k) # construct the lagrange polynomials for the k neighbors circulating_one = np.asarray([1.0] + [0.0] * (k - 1)) bary_pol = [] for l in range(k): bary_pol.append( BarycentricInterpolator(padded_c_grid[nn], np.roll(circulating_one, l))) M[i, nn] = np.asarray(list(map(lambda x: x(p), bary_pol))) if pad > 0: M = M[:, pad:-pad] return sprs.csc_matrix(M)
def interp_ephem(ts_quasi_mjd, ts_quasi_mjd_cpf, positions_cpf): ''' Interpolate the CPF ephemeris using the 10-point(degree 9) Lagrange polynomial interpolation method. Usage: positions = interp_ephem(ts_quasi_mjd,ts_quasi_mjd_cpf,positions_cpf) Inputs: Here, the quasi MJD is defined as int(MJD) + (SoD + Leap Second)/86400, which is different from the conventional MJD defination. For example, MJD and SoD for '2016-12-31 23:59:60' are 57753.99998842606 and 86400, but the corresponding quasi MJD is 57754.0 with leap second of 0. As a comparison, MJD and SoD for '2017-01-01 00:00:00' are 57754.0 and 0, but the corresponding quasi MJD is 57754.00001157408 with leap second of 1. The day of '2016-12-31' has 86401 seconds, and for conventional MJD calculation, one second is compressed to a 86400/86401 second. Hence, the quasi MJD is defined for convenience of interpolation. ts_quasi_mjd -> [float array] quasi MJD for interpolated prediction ts_quasi_mjd_cpf -> [float array] quasi MJD for CPF ephemeris positions_cpf -> [2d float array] target positions in cartesian coordinates in meters w.r.t. ITRF for CPF ephemeris. Outputs: positions -> [2d float array] target positions in cartesian coordinates in meters w.r.t. ITRF for interpolated prediction. ''' positions = [] m = len(ts_quasi_mjd) n = len(ts_quasi_mjd_cpf) if m > n: for i in range(n - 1): flags = (ts_quasi_mjd >= ts_quasi_mjd_cpf[i]) & ( ts_quasi_mjd < ts_quasi_mjd_cpf[i + 1]) if flags.any(): positions.append( BarycentricInterpolator(ts_quasi_mjd_cpf[i - 4:i + 6], positions_cpf[i - 4:i + 6])( ts_quasi_mjd[flags])) positions = np.concatenate(positions) else: for j in range(m): boundary = np.diff( ts_quasi_mjd[j] >= ts_quasi_mjd_cpf).nonzero()[0][0] if ts_quasi_mjd[j] in ts_quasi_mjd_cpf: positions.append(positions_cpf[boundary]) else: positions.append( BarycentricInterpolator( ts_quasi_mjd_cpf[boundary - 4:boundary + 6], positions_cpf[boundary - 4:boundary + 6])( ts_quasi_mjd[j])) positions = np.array(positions) return positions
def trajectory(): N = 200 D, x = cheb(N) eps = 0. def L_yp(x,yp_): a_ = a(x) return a_**3.*yp_*(1 + a_**2.*yp_**2.)**(-1./2) - a_**2.*r(x) def g(z): out = D.dot(L_yp( x,D.dot(z) )) out[0], out[-1] = z[0] - z1, z[-1] - 0 return out # Use the straight line trajectory as an initial guess. # Another option would be to use the shortest-time trajectory found # in heuristic_tractory() as an initial guess. eps, time = time_functional() sol = root(g,y(x,eps)) # sol = root(g,z1/2.*(x-(-1.))) # print sol.success z = sol.x poly = BarycentricInterpolator(x,D.dot(z)) num_func = lambda inpt: poly.__call__(inpt) def L(x): a_, yp_ = a(x), num_func(x) return a_*(1 + a_**2.*yp_**2.)**(1./2) - a_**2.*r(x)*yp_ print "The shortest time is approximately " print integrate.quad(L,-1,1,epsabs=1e-10,epsrel=1e-10)[0] # x0 = np.linspace(-1,1,200) # y0 = y(x0,eps) # plt.plot(x0,y0,'-g',linewidth=2.,label='Initial guess') # plt.plot(x,z,'-b',linewidth=2.,label="Numerical solution") # ax = np.linspace(0-.05,z1+.05,200) # plt.plot(-np.ones(ax.shape),ax,'-k',linewidth=2.5) # plt.plot(np.ones(ax.shape),ax,'-k',linewidth=2.5) # plt.plot(-1,0,'*b',markersize=10.) # plt.plot(1,z1,'*b',markersize=10.) # plt.xlabel('$x$',fontsize=18) # plt.ylabel('$y$',fontsize=18) # plt.legend(loc='best') # plt.axis([-1.1,1.1,0. -.05,z1 +.05]) # # plt.savefig("minimum_time_rivercrossing.pdf") # plt.show() # plt.clf() return x, z, N
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
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()
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()
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
def interp_fnc(f, in_xhat, out_xhat): permutation = np.random.permutation(in_xhat.shape[0]) permuted_in_xhat = in_xhat[permutation] C = (np.max(permuted_in_xhat) - np.min(permuted_in_xhat)) / 4.0 Cinv = 1.0 / C I = BarycentricInterpolator(Cinv * permuted_in_xhat, f[permutation]) return I(Cinv * out_xhat)
def prob6(n): """Interpolate the air quality data found in airdata.npy using Barycentric Lagrange interpolation. Plot the original data and the interpolating polynomial. Parameters: n (int): Number of interpolating points to use. """ #load the data data = np.load("airdata.npy") #initialize the function and domain fx = lambda a, b, n: .5 * (a + b + (b - a) * np.cos(np.arange(n + 1) * np.pi / n)) a, b = 0, 366 - 1 / 24 domain = np.linspace(0, b, 8784) points = fx(a, b, n) temp = np.abs(points - domain.reshape(8784, 1)) temp2 = np.argmin(temp, axis=0) #plot the origin data and interpolated data poly = BarycentricInterpolator(domain[temp2], data[temp2]) plt.subplot(211) plt.plot(data) plt.title("Original") plt.subplot(212) plt.plot(poly(domain)) plt.title("Interpolation") plt.show()
def _getWeights(self, a, b): """ Computes weights using barycentric interpolation Args: a (float): left interval boundary b (float): right interval boundary Returns: numpy.ndarray: weights of the collocation formula given by the nodes """ if self.nodes is None: raise CollocationError( "Need nodes before computing weights, got %s" % self.nodes) circ_one = np.zeros(self.num_nodes) circ_one[0] = 1.0 tcks = [] for i in range(self.num_nodes): tcks.append( BarycentricInterpolator(self.nodes, np.roll(circ_one, i))) weights = np.zeros(self.num_nodes) for i in range(self.num_nodes): weights[i] = quad(tcks[i], a, b, epsabs=1e-14)[0] return weights
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]
def _gauss6(f, t, y, h): """ One step Gauss6 for the autonomous system y'=f(y). This is implemented as an Runge-Kutta method. See Hairer, Lubich, Wanner, Geometric Numerical Integration, page 30. Input f the right-hand side t the initial time y can either be a number for the initial value or a function whose value at t serves as the inital value and can be used for extrapolating initial guesses for the nonliear solver h step size Output yn the solution function on [t, t + h] """ # Step 0: initialize (a, b, c) = _WEIGHTS # get coefficients # Step 1: generate initial guess for stage values if hasattr(y, '__call__'): # y is a function => rename it to l and take y0=y(t) l = y y0 = y(t) else: # y is a single number => use the linear interpolant for initial guess l = BarycentricInterpolator([t, t + h], [y, y + h * f(y)]) y0 = y # compute initial guess for stage values z = array([l(t + ci * h) - y0 for ci in c]) # Step 2: solve for stage values # the nonlinear system associate with the stage values def eq(w): return h * a.dot(array([f(y0 + wi) for wi in w])) # solve using fixed point interation z = fixed_point(eq, z, xtol=DOLFIN_SQRT_EPS, maxiter=500000) # Step 3: construct the solution as the interpolant pts = array([t + ci * h for ci in c]) return BarycentricInterpolator(pts, y0 + z)
def interpolate(f,n): #First we the interpolating polynomial x = cheb_points(n) #y contains our function's values at the chebyshev points y = f(x) #Below we get an interpolating polynomial that runs through points in y p = BarycentricInterpolator(x, y) xnew = np.linspace(-1,1,1000) ynew = p(xnew) #Below we plotted on (-2,2) using values from our interpolating polynomial plt.plot(xnew,ynew) return y
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()
def interpolate(alpha, n, ts, collocation_scheme=None): # By default, interpolation over the Chebyshev nodes of the second kind is used if collocation_scheme is None: collocation_scheme = pyritz.interpolation.collocation.chebyshev2 cts, _ = collocation_scheme(n, []) dim = int(len(alpha) / (n + 1)) alpha_reshaped = alpha.reshape((dim, n + 1)) xs = np.zeros((dim, len(ts))) for i in range(dim): xs[i, :] = BarycentricInterpolator(cts, alpha_reshaped[i, :])(ts) return xs
def update_interpolator(self, t): i = 0 for line in range(1, len(self.predictions)): if t < self.predictions[i][0] and t > self.predictions[i-1][0]: break i += 1 if i < 5: raise ValueError("Cannot interpolate: Timestamp too close to start. Try the previous day's CPF file.") if i > len(self.predictions)-5: raise ValueError("Cannot interpolate: Timestamp too close to end. Try the next day's CPF file.") points = self.predictions[i-5 : i+5] X = [p[0] for p in points] Y = np.array([p[1] for p in points]) self.interp_start = X[4] self.interp_end = X[5] self.Interpolator = BarycentricInterpolator(X, Y)
def polynomial(desired_point, model_points, degree): idx_points_for_poly_interp = _argsort_height_diffs( desired_point, model_points)[:(degree + 1)] points_for_poly_interp = \ [model_points[idx] for idx in idx_points_for_poly_interp] heights = [point.height for point in points_for_poly_interp] ts_df = pd.concat([ point._time_series[0]._timeseries for point in points_for_poly_interp ], axis=1) results = ts_df.T.apply(lambda x: BarycentricInterpolator( heights, x.values)(desired_point.height).reshape(1)[0]) return results
def lagrangeInterpolation(): sample_rate, sample = wavfile.read('songs/hakuna_matata.wav') sample = sample[5000000:5000100] sample_rateBAD, sampleBAD = wavfile.read( 'songs/bad_songs/not_good_song.wav') sampleBAD = sampleBAD[5000000:5000100] BadSample = sample.copy() dz.theEvilMethod(BadSample, 0.7) matches = recognize.cheat(sample, BadSample) x, y = utils.tovalidxy(BadSample, matches) f = BarycentricInterpolator(x, y) utils.repair(BadSample, matches, f) IwannaSee(sample, BadSample, sampleBAD)
def _explicit_euler(f, t, y, h): """ One step of explicit Euler for the autonomous system y'=f(y). Input f the right-hand side t the initial time y can either be a number for the initial value or a function whose value at t serves as the inital value h step size Output yn the solution function on [t, t + h] """ if hasattr(y, '__call__'): # y is a function y0 = y(t) else: # y is a single number y0 = y return BarycentricInterpolator([t, t + h], [y0, y0 + h * f(y0)])
def main(): mpl.rcParams['font.sans-serif'] = [u'Times New Roman'] mpl.rcParams['axes.unicode_minus'] = False x = np.random.poisson(lam=5, size=1000) pillar = 15 # 第一个返回值:每个bins点对应的频率值 # 第二个返回值:每个bin的区间范围 # 第三个返回值:每个bin里面包含的数据,是一个list a = plt.hist(x, bins=pillar, density=True, range=[0, pillar], color='g', edgecolor='k', alpha=0.8) plt.title(r'$y = \frac{\Lambda^k}{k!}e^{-\Lambda}$') plt.grid() plt.show() print(a) rv = poisson(5) x1 = a[1] y1 = rv.pmf(x1) itp = BarycentricInterpolator(x1, y1) # 重心插值 x2 = np.linspace(x.min(), x.max(), 50) y2 = itp(x2) cs = CubicSpline(x1, y1) # 三次样条插值 plt.plot(x2, cs(x2), 'm--', linewidth=5, label='CubicSpine') # 三次样条插值 plt.plot(x2, y2, 'g-', linewidth=3, label='BarycentricInterpolator') # 重心插值 plt.plot(x1, y1, 'r-', linewidth=1, label='Actural Value') # 原始值 plt.legend(loc='upper right') plt.grid() plt.show()
def test_large_chebyshev(self): # The weights for Chebyshev points of the second kind have analytically # solvable weights. Naive calculation of barycentric weights will fail # for large N because of numerical underflow and overflow. We test # correctness for large N against analytical Chebyshev weights. # Without capacity scaling or permutation, n=800 fails, # With just capacity scaling, n=1097 fails # With both capacity scaling and random permutation, n=30000 succeeds n = 800 j = np.arange(n + 1).astype(np.float64) x = np.cos(j * np.pi / n) # See page 506 of Berrut and Trefethen 2004 for this formula w = (-1) ** j w[0] *= 0.5 w[-1] *= 0.5 P = BarycentricInterpolator(x) # It's okay to have a constant scaling factor in the weights because it # cancels out in the evaluation of the polynomial. factor = P.wi[0] assert_almost_equal(P.wi / (2 * factor), w)
def test_wrapper(self): P = BarycentricInterpolator(self.xs, self.ys) values = barycentric_interpolate(self.xs, self.ys, self.test_xs) assert_almost_equal(P(self.test_xs), values)
def test_shapes_1d_vectorvalue(self): P = BarycentricInterpolator(self.xs, np.outer(self.ys, [1])) assert_array_equal(np.shape(P(0)), (1, )) assert_array_equal(np.shape(P([0])), (1, 1)) assert_array_equal(np.shape(P([0, 1])), (2, 1))
def test_shapes_vectorvalue(self): P = BarycentricInterpolator(self.xs, np.outer(self.ys, np.arange(3))) assert_array_equal(np.shape(P(0)), (3, )) assert_array_equal(np.shape(P([0])), (1, 3)) assert_array_equal(np.shape(P([0, 1])), (2, 3))
def test_shapes_scalarvalue(self): P = BarycentricInterpolator(self.xs, self.ys) assert_array_equal(np.shape(P(0)), ()) assert_array_equal(np.shape(P(np.array(0))), ()) assert_array_equal(np.shape(P([0])), (1, )) assert_array_equal(np.shape(P([0, 1])), (2, ))
def test_append(self): P = BarycentricInterpolator(self.xs[:3], self.ys[:3]) P.add_xi(self.xs[3:], self.ys[3:]) assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs))
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))
def test_scalar(self): P = BarycentricInterpolator(self.xs, self.ys) assert_almost_equal(self.true_poly(7), P(7)) assert_almost_equal(self.true_poly(np.array(7)), P(np.array(7)))
t0_a= 10.8 sigma_t_a= 0.2 sigma= 0.04 active_space_a= np.array(map(lambda x: 1./(1+np.exp((x-L)/sigma)),x))*1./(1+np.exp(t0_a/sigma_t_a)) active_const_a= np.array(map(lambda x: 1.,x))*1./(1+np.exp(t0_a/sigma_t_a)) t0_i= 12.2 sigma_t_i= .8 sigma= 0.04 active_space_i= np.array(map(lambda x: 1./(1+np.exp((x-L)/sigma)),x))*1./(1+np.exp(t0_i/sigma_t_i)) active_const_i= np.array(map(lambda x: 1.,x))*1./(1+np.exp(t0_i/sigma_t_i)) rng= np.linspace(-1,1,1000) x_step= 2./1000 interpolator= BI(x) avg_h_blade= [] avg_Q_minus_blade= [] avg_T_minus_blade= [] avg_shear_blade= [] zeta= zeta_h*active_space_a + zeta_b*active_const_a zetabar= zetabar_h*active_space_i + zetabar_b*active_const_i lambda2= lambda2_h*active_space_a + lambda2_b*active_const_a #xi = xi_h*active_space_a + xi_b*active_const_a n_images= 150 image_step= 200 for i in np.arange(n_images*image_step): if i%image_step == 0:
npts = 7 noiseAmp = 0.03 xdata = np.linspace(0.2, 10., npts) + 0.3*np.random.randn(npts) xdata = np.sort(xdata) ydata = f(xdata) * (1.0 + noiseAmp * np.random.randn(npts)) np.savetxt('logCurveData9.txt', zip(xdata, ydata), fmt='%10.2f') # Create x array spanning data set plus 5% xmin, xmax = frangeAdd(xdata, 0.05) x = np.linspace(xmin, xmax, 200) # Plot data and "fit" plt.plot(xdata, ydata, 'or', label='data') plt.plot(x, f(x), 'k-', label='fitting function') # Create y array from cubic spline f_cubic = interp1d(xdata, ydata, kind='cubic', bounds_error=False) plt.plot(x, f_cubic(x), 'k-', label='cubic spline') # Create y array from univariate spline f_univar = UnivariateSpline(xdata, ydata, w=None, bbox=[xmin, xmax], k=3) plt.plot(x, f_univar(x), label='univariate spline') # Create y array from barycentric interpolation f_bary = BarycentricInterpolator(xdata, ydata) plt.plot(x, f_bary.__call__(x), label='barycentric interp') plt.legend(loc='best') plt.show()
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))
def test_append(self): P = BarycentricInterpolator(self.xs[:3],self.ys[:3]) P.add_xi(self.xs[3:],self.ys[3:]) assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs))
def nonlinear_minimal_area_surface_of_revolution(): l_bc, r_bc = 1., 7. N = 80 D, x = cheb_vectorized(N) M = np.dot(D, D) guess = 1. + (x--1.)*((r_bc - l_bc)/2.) N2 = 50 def pseudospectral_ode(y): out = np.zeros(y.shape) yp, ypp = D.dot(y), M.dot(y) out = y*ypp - 1. - yp**2. out[0], out[-1] = y[0] - r_bc, y[-1] - l_bc return out u = root(pseudospectral_ode,guess,method='lm',tol=1e-9) num_sol = BarycentricInterpolator(x,u.x) # Up to this point we have found the numerical solution # using the pseudospectral method. In the code that follows # we check that solution with the analytic solution, # and graph the results def f(x): return np.array([ x[1]*np.cosh((-1.+x[0])/x[1])-l_bc, x[1]*np.cosh((1.+x[0])/x[1])-r_bc]) parameters = root(f,np.array([1.,1.]),method='lm',tol=1e-9) A, B = parameters.x[0], parameters.x[1] def analytic_solution(x): out = B*np.cosh((x + A)/B) return out xx = np.linspace(-1, 1, N2) uu = num_sol.__call__(xx) # print "Max error is ", np.max(np.abs(uu - analytic_solution(xx))) plt.plot(x,guess,'-b') plt.plot(xx, uu, '-r') # Numerical solution via # the pseudospectral method plt.plot(xx, analytic_solution(xx), '*k') # Analytic solution plt.axis([-1.,1.,l_bc-1.,r_bc +1.]) # plt.show() plt.clf() theta = np.linspace(0,2*np.pi,N2) X,Theta = np.meshgrid(xx,theta,indexing='ij') print "\nxx = \n", xx print "\nuu = \n", uu F = uu[:,np.newaxis] +np.zeros(uu.shape) print "\nX = \n", X print "\nTheta = \n", Theta print "\nF = \n", F Y = F*np.cos(Theta) Z = F*np.sin(Theta) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # X, Y, Z = axes3d.get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1) print ax.azim, ax.elev ax.azim=-65; ax.elev = 0 # ax.view_init(elev=-60, azim=30) # plt.savefig('minimal_surface.pdf') plt.show()