def p1_1(part=None): """ Complete solution to problem 1.1 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ print 'Starting part a' x_edge, h = make_grid(0, np.pi, 100, 'cell_edge') f = lambda x: np.sin(x) * np.sinh(x) plt.figure() plt.plot(x_edge, f(x_edge)) plt.title('Part a') plt.draw() print 'Finished part a \n', '----' * 5, '\nStarting part b' x_center, h2 = make_grid(0, 2, 5000, 'cell_center') f2 = lambda x: np.cos(x) plt.figure() plt.plot(x_center, f2(x_center)) plt.title('Part b') plt.draw() int_estimate = np.sum(f2(x_center)) * h2 int_real = quad(f2, 0, 2)[0] abs_int_error = abs(int_real - int_estimate) print 'Absolute error in integral is %.6e' % (abs_int_error) print 'Finished part b \n', '----' * 5, '\nStarting part c' x_c_ghost, h3 = make_grid(0, np.pi / 2, 500, 'cell_center_ghost') f3 = lambda x: np.sin(x) y3 = f3(x_c_ghost) pass # Return nothing
def ilc_map(map_dic, opbeam, map_params, experiment, components='all', cov_from_sims=True): # collecting multifrequency maps freq_arr = sorted(map_dic.keys()) map_arr = [] for freq in freq_arr: curr_map = map_dic[freq] map_arr.append(curr_map) # obtaining weights res_weights = residuals_and_weights(map_dic, map_params, components, experiment, cov_from_sims) l, cl_residual, res_ilc_dic, weights_arr = res_weights # rebeaming l, bl_dic = exp.beam_power_spectrum_dic(experiment, opbeam) bl_rebeam_arr = exp.rebeam(bl_dic) # computing 2D versions grid, _ = tools.make_grid(map_params, harmonic=True) weights_arr_2D = [] for currW in weights_arr: l = np.arange(len(currW)) currW_2D = tools.convert_to_2d(grid, l, currW) weights_arr_2D.append(currW_2D) weights_arr_2D = np.asarray(weights_arr_2D) rebeam_arr_2D = [] for currB in bl_rebeam_arr: l = np.arange(len(currB)) currB_2D = tools.convert_to_2d(grid, l, currB) rebeam_arr_2D.append(np.sqrt(currB_2D)) rebeam_arr_2D = np.asarray(rebeam_arr_2D) # modify weights to include rebeam rebeamed_weights_arr = rebeam_arr_2D * weights_arr_2D # compute ilc map weighted_maps_arr = [] for mm in range(len(map_arr)): curr_map = map_arr[mm] rebeamed_weights_arr[mm][np.isnan(rebeamed_weights_arr[mm])] = 0. rebeamed_weights_arr[mm][np.isinf(rebeamed_weights_arr[mm])] = 0. map_weighted = np.fft.fft2(curr_map) * rebeamed_weights_arr[mm] weighted_maps_arr.append(map_weighted) ilc_map_fft = np.sum(weighted_maps_arr, axis=0) ilc_map = np.fft.ifft2(ilc_map_fft).real return ilc_map, res_weights
def deflection_from_convergence(mapparams, kappa_map): # defining underlying grid in harmonic space grid, _ = tools.make_grid(mapparams, harmonic=True) lX, lY = grid l2d = np.hypot(lX, lY) # computing deflection angle from convergence map kappa_map_fft = np.fft.fft2(kappa_map) alphaX_fft = 1j * lX * 2. * kappa_map_fft / l2d**2 alphaY_fft = 1j * lY * 2. * kappa_map_fft / l2d**2 alphaX_fft[np.isnan(alphaX_fft)] = 0 alphaY_fft[np.isnan(alphaY_fft)] = 0 alphaX = np.degrees(np.fft.ifft2(alphaX_fft).real) * 60 alphaY = np.degrees(np.fft.ifft2(alphaY_fft).real) * 60 alpha_vec = [alphaX, alphaY] return alpha_vec # in arcmin
def p1_7(part=None): """ Complete solution to problem 1.7. Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ x, h = make_grid(0, 5, 1000, 'cell_edge') # cell-edge data f = np.cos(x) y = np.cos(x) + .001 * np.random.rand(x.size) yp = np.zeros(y.shape) # Pre-allocate memory for yp and ypp ypp = np.zeros(y.shape) # Get centered estimate for yp(p) yp = centered_difference(y, 1, h, 'linear') ypp = centered_difference(y, 2, h, 'linear') # Get real derivatives fp = -np.sin(x) fpp = -np.cos(x) # Plot f, y, fp, yp plt.figure() plt.subplot(211) plt.plot(x, f, 'b', x, y, 'g') plt.legend(('Real', 'Noisy'), loc=0) plt.title('f(x)') plt.subplot(212) plt.plot(x, fp, 'k', x, yp, 'r') plt.legend(('Real', 'Estimated'), loc=0) plt.title('fp(x)') plt.draw() pass # return nothing
def lens_map(map_params, unlensed_map, alpha_vec): # creating undeflected field grid, _ = tools.make_grid(map_params) betaX, betaY = grid # cromputing deflected field alphaX, alphaY = alpha_vec thetaX = betaX + alphaX thetaY = betaY + alphaY # computing lensed map through interpolation interpolate = sp.interpolate.RectBivariateSpline(betaY[:, 0], betaX[0, :], unlensed_map, kx=5, ky=5) lensed_map = interpolate.ev(thetaY.flatten(), thetaX.flatten()).reshape( [len(betaY), len(betaX)]) return lensed_map
def convergence_map(self, map_params, centroid_shift=None): # getting kappa_profile nx, dx, _, _ = map_params theta = np.linspace(0, nx * dx / 2, nx) kappa_profile = self.convergence_profile(theta) # creating map grid grid, _ = tools.make_grid(map_params) # adding Gaussian positional uncertainties gridX, gridY = grid if centroid_shift is not None: x_shift, y_shift = centroid_shift gridX += x_shift gridY += y_shift grid = gridX, gridY # computing convergence map from convergence profile kappa_map = tools.convert_to_2d(grid, theta, kappa_profile) return kappa_map
def lens_map(unlensed_map, alpha_vec, map_params): """Returns the lensed version of the underlying map based on the given deflection angle. Args: unlensed_map (numpy.ndarray): Input map. alpha_vec (list): Array containing the X and Y components of the deflection angle: alphaX (array_like): X field of the deflection angle in arcmin. alphaY (array_like): Y field of the deflection angle in arcmin. map_params (list): List containing the map parameters: nx (int): Number of pixels in horizontal direction. dx (float) Pixel resolution in horizontal direction in arcmin. ny (int): Number of pixels in vertical direction. dy (float): Pixel resolution in vertical direction in arcmin. Returns: lensed_map (numpy.ndarray): Lensed version of the input map. """ # Create undeflected field. grid, _ = tools.make_grid(map_params) betaX, betaY = grid # Compute deflected field. alphaX, alphaY = alpha_vec thetaX = betaX + alphaX thetaY = betaY + alphaY # Compute lensed map through interpolation using bivariate spline approximation. interpolate = sp.interpolate.RectBivariateSpline(betaY[:, 0], betaX[0, :], unlensed_map, kx=5, ky=5) lensed_map = interpolate.ev(thetaY.flatten(), thetaX.flatten()).reshape( [len(betaY), len(betaX)]) return lensed_map
def deflection_from_convergence(kappa_map, map_params): """Returns the deflection angle based on a given convergence map. Args: kappa_map (numpy.ndarray): Convergence map. map_params (list): List containing the map parameters: nx (int): Number of pixels in horizontal direction. dx (float) Pixel resolution in horizontal direction in arcmin. ny (int): Number of pixels in vertical direction. dy (float): Pixel resolution in vertical direction in arcmin. Returns: alpha_vec (list): List containing the X and Y components of the deflection angle: alphaX (array_like): X field of the deflection angle in arcmin. alphaY (array_like): Y field of the deflection angle in arcmin. """ # Create map grid in Fourier space. grid, _ = tools.make_grid(map_params, Fourier=True) lX, lY = grid l2d = np.hypot(lX, lY) # Compute deflection angle from convergence map in Fourier space. kappa_map_fft = np.fft.fft2(kappa_map) alphaX_fft = 1j * lX * 2. * kappa_map_fft / l2d**2 alphaY_fft = 1j * lY * 2. * kappa_map_fft / l2d**2 alphaX_fft[np.isnan(alphaX_fft)] = 0 alphaY_fft[np.isnan(alphaY_fft)] = 0 # Compute real space deflection angle. alphaX = np.degrees(np.fft.ifft2(alphaX_fft).real) * 60 alphaY = np.degrees(np.fft.ifft2(alphaY_fft).real) * 60 alpha_vec = [alphaX, alphaY] return alpha_vec
def cmb_mock_data(map_params, l, cl, cluster=None, centroid_shift_value=0, nber_ch=1, cluster_corr_cutouts=None, cl_extragal=None, bl=None, nl=None, nber_obs=1): nx, dx, ny, dy = map_params sims = [] for i in range(nber_obs): sim = tools.make_gaussian_realization(l, cl, map_params) if cluster is not None: M, c, z = cluster x_shift, y_shift = np.random.normal( loc=0.0, scale=centroid_shift_value / (2**0.5)), np.random.normal( loc=0.0, scale=centroid_shift_value / (2**0.5)) centroid_shift = [x_shift, y_shift] grid, _ = tools.make_grid(map_params, grid_shift=centroid_shift) theta = np.hypot(grid[0], grid[1]) kappa_map = lensing.NFW_convergence(M, c, z, 1100, theta, dim=2) alpha_vec = lensing.deflection_from_convergence( kappa_map, map_params) sim = lensing.lens_map(sim, alpha_vec, map_params) sims_ch_arr = [np.copy(sim) for k in range(nber_ch)] if cluster_corr_cutouts is not None: if np.asarray(cluster_corr_cutouts).ndim == 3: cluster_corr_cutouts = [cluster_corr_cutouts] cluster_corr_cutout = cluster_corr_cutouts[0][0] nx_cutout, ny_cutout = cluster_corr_cutout.shape[ 0], cluster_corr_cutout.shape[1] s, e = int((nx - nx_cutout) / 2), int((ny + ny_cutout) / 2) rand_sel = random.randint(0, len(cluster_corr_cutouts[0]) - 1) rand_ang = random.randint(-180, 180) for j in range(nber_ch): cluster_corr_cutout = scipy.ndimage.rotate( np.nan_to_num(cluster_corr_cutouts[j][rand_sel]), np.nan_to_num(rand_ang), reshape=False, mode='reflect') sims_ch_arr[j][s:e, s:e] = sims_ch_arr[j][s:e, s:e] + cluster_corr_cutout if cl_extragal is not None: if isinstance(cl_extragal, list) is False: cl_extragal = [cl_extragal] for j in range(nber_ch): extragal_noise_map = tools.make_gaussian_realization( l, cl_extragal[j], map_params, random_seed=0) sims_ch_arr[j] += extragal_noise_map if bl is not None: if isinstance(bl, list) is False: bl = [bl] for j in range(nber_ch): sims_ch_arr[j] = tools.convolve(sims_ch_arr[j], l, np.sqrt(bl[j]), mapparams=map_params) if nl is not None: if isinstance(nl, list) is False: nl = [nl] for j in range(nber_ch): noise_map = tools.make_gaussian_realization( l, nl[j], map_params) sims_ch_arr[j] += noise_map sims.append(sims_ch_arr) if nber_ch == 1 and nber_obs == 1: return sims[0][0] if nber_ch == 1: sims_one_freq = [] for i in range(len(sims)): sims_one_freq.append(sims[i][0]) return sims_one_freq if nber_obs == 1: return sims[0] sims_freq_sorted = [] for i in range(nber_ch): maps_at_freq_i = [] for j in range(nber_obs): maps_at_freq_i.append(sims[j][i]) sims_freq_sorted.append(maps_at_freq_i) return sims_freq_sorted
def p5_3(part=None): """ Complete solution to problem 5_3 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ if not part: part = 'a' # Initialize the animation writer FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='P430 5.3' + part, artist='Spencer Lyon') writer = FFMpegWriter(fps=15, metadata=metadata) # Set the values for parameters c = 2 # wave speed # build a cell-centered grid with N=200 cells # on the interval x=0 to x=L, with L=1 L = 1 # Left boundary n = 200 # Number of cells x, h = make_grid(0, L, n, grid_type='cell_center_ghost') j = np.arange(1, n + 1) # define the initial displacement and velocity vs. x y = np.exp(- (x - L / 2) ** 2 * 160 / L ** 2) - \ np.exp(- (0 - L / 2) ** 2 * 160 / L ** 2) vy = np.zeros_like(x) if part == 'c': y = np.zeros_like(x) vy = np.exp(- (x - L / 2) ** 2 * 160 / L ** 2) - \ np.exp(- (0 - L / 2) ** 2 * 160 / L ** 2) # Choose a time step (Suggest that it is no larger than taulim) taulim = h / c print 'Courant time step limit %f \n' % (taulim) tau = float(raw_input('Enter the time step: ')) # Get the initial value of y_old from the initial y and vy y_old = np.zeros_like(y) y_old[j] = y[j] - tau * vy[j] + c ** 2 * tau ** 2 / (2 * h ** 2) * \ (y[j + 1] - 2 * y[j] + y[j - 1]) # Apply the boundary conditions for y_old(1) and y_old(N+2) y_old[0] = 0 y_old[-1] = 0 # plot the initial conditions and pause to look at them plt.ion() plt.figure() plt.subplot(211) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y(x,0)') plt.title('Initial Displacement') plt.subplot(212) plt.plot(x, vy) plt.xlabel('x') plt.ylabel('v_y(x,0)') plt.title('Initial Velocity') plt.draw() plt.ioff() # Choose how long to run and when to plot tfinal = float(raw_input(' Enter tfinal (2 seconds is plenty): ')) skip = float(raw_input(' Enter # of steps to skip between plots' + \ '(1-5 is good):')) nsteps = int(tfinal / tau) # here is the loop that steps the solution along fig = plt.figure() l, = plt.plot([], [], 'b-') if part != 'c': plt.axis([x.min(), x.max(), -2, 2]) else: plt.axis([x.min(), x.max(), -0.04, 0.04]) with writer.saving(fig, "p5_3" + part + ".mp4", 200): for n in range(nsteps): time = n * tau # compute the time # Use leapfrog and the boundary conditions to load y_new with y # at the next time step using y and y_old, i.e., y_new(2:N+1)=... # Be sure to use colon commands so it will run fast. ynew = np.zeros_like(y) ynew[j] = 2 * y[j] - y_old[j] + c ** 2 * tau ** 2 / (h ** 2) * \ (y[j + 1] - 2 * y[j] + y[j - 1]) if part == 'b': ynew[0] = ynew[1] ynew[-1] = ynew[-2] #update y_old and y y_old = y y = ynew # make plots every skip time steps if n % skip == 0: print 'On step %i of %i' % (n, nsteps) l.set_data(x, y) plt.title('Staggered Leapfrog Wave: time %.2e' % time) writer.grab_frame()
def p4_5(part=None): """ Complete solution to problem 4.5 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ # Define parameters and create grid L = 2 xmin = -5 xmax = 5 n = 500 x, h = make_grid(xmin, xmax, n, 'cell_center_ghost') # Get number of elements in x (number of rows in A and B) n_rows = x.size # Create A matrix A = np.zeros((n_rows, n_rows)) A[0, 0] = 1 # Boundary conditions are that xsi(-inf) = xsi(inf) = 0 A[-1, -1] = 1 # Boundary conditions are that xsi(-inf) = xsi(inf) = 0 for i in xrange(1, n_rows - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2) * (-1 / 2.), - 2 / (h ** 2) * (-1 / 2.) + x[i] ** 4, 1 / (h ** 2) * (-1 / 2.)] # Create B matrix B = np.eye(n_rows) B[-1, -1] = 0 # Equation 4.8 B[0, 0] = 0 # Equation 4.10 B[0, 1] = 0 # Equation 4.10 # Solve genearalized eigenvalue problem (eigen.m for python) lamb, v1 = la.eig(A, B) epsi_raw = lamb # epsilon is equal to the eigenvalues epsi, k = [np.sort(epsi_raw), np.argsort(epsi_raw)] # sort and get indices print "First 5 epsilon_n's" print epsi[:5].real # Plot Solutions contin = 1 for i in range(n): if contin == 1: t = r'$\epsilon_{%s}$ = %.6f' % (i, epsi[i]) gn = v1[:, k[i]] A = 1 / np.abs(trapz(np.abs(gn ** 2), x)) plt.figure() plt.plot(x, np.abs(gn ** 2) * A, 'r.') plt.title(t) plt.xlabel(r'$g_{%s}(x)$' % (i + 1)) plt.ylabel('x') plt.draw() ans = raw_input('Continue? Enter 0 if no, leave blank if yes ') try: contin = int(ans) plt.close('all') except ValueError: contin = 1 else: plt.close('all') break
def show_usps(data): plt.imshow(data.reshape((16, 16)), interpolation="nearest", cmap="gray") ### Donnees artificielles plt.ion() xgentrain, ygentrain = gen_arti(data_type=0, sigma=0.5, nbex=1000, epsilon=0.1) xgentest, ygentest = gen_arti(data_type=0, sigma=0.5, nbex=1000, epsilon=0.1) plt.figure() plot_data(xgentrain, ygentrain) ### Donnees reelles plt.figure() xuspstrain, yuspstrain = load_usps("USPS/USPS_train.txt") xuspstest, yuspstest = load_usps("USPS/USPS_test.txt") x06train, y06train = get_usps([0, 6], xuspstrain, yuspstrain) x06test, y06test = get_usps([0, 6], xuspstest, yuspstest) show_usps(x06train[0]) def f(X): return np.linalg.norm(X, axis=1) #### Pour la visualisation des couts #### En 2D, f etant une fonction de R^2 -> R grid, xx, yy = make_grid(xmin=-1, xmax=3, ymin=-1, ymax=3, step=50) plt.figure() plt.contourf(xx, yy, f(grid).reshape(xx.shape), 256)
def p3_1(part=None, no_plot=False): """ Complete solution to problem 3.1 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ def f_x(x): """ implement the piecewise function in equation 3.4 """ x = np.ascontiguousarray(x) ret = np.zeros(x.size) for i in range(x.size): if 0.8 <= x[i] and x[i] < 1: ret[i] = 0.73 return ret # Define parameters mu = 0.003 T = 127 L = 1.2 omega = 400 # Build grid n = 100 xmin = 0 xmax = L x, h = make_grid(xmin, xmax, n, 'cell_edge') # Get data for function y = f_x(x) # Create the matrix representing A in the matrix equation for the BVP A = np.zeros((n, n)) # Preallocate memory for A A[0, 0] = 1 # Set first row of A A[-1, -1] = 1 # Set last row of A for i in xrange(1, n - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [T / (h ** 2), - 2 * T / (h ** 2) + mu * omega ** 2, T / (h ** 2)] # Create the vector representing x in the matrix equation for the BVP x_approx = np.zeros(n) # Preallocate memory for x_approx x_approx[0] = 0 # Set first row of x_approx x_approx[-1] = 0 # Set last row of x_approx x_approx[1:-1] = -f_x(x[1:-1]) # Fill in all other rows of x_approx # Approximate y y_approx = la.solve(A, x_approx) if no_plot == False: plt.figure() plt.plot(x, y_approx, 'b--') plt.title('Solution to part a with n = 100') plt.draw() # ------------------------------- Part b ------------------------------- # omega_arr = np.linspace(400, 1200, 100) iteration_data = pd.DataFrame(index=range(1, 101)) maxes = np.zeros(100) iteration_data.index.name = 'x' for i in range(100): w = omega_arr[i] A2 = np.zeros((n, n)) # Preallocate memory for A2 A2[0, 0] = 1 # Set first row of A2 A2[-1, -1] = 1 # Set last row of A2 for i in xrange(1, n - 1): # Fill in all other rows of A2 A2[i, i - 1: i + 2] = [T / (h ** 2), - 2 * T / (h ** 2) + mu * w ** 2, T / (h ** 2)] y_approx2 = la.solve(A2, x_approx) iteration_data[w] = y_approx2 if no_plot == False: plt.figure() iteration_data.max(0).plot() plt.title('Solution to part b') plt.draw() iteration_data.columns.name = 'Omega' return iteration_data
def p2_2(part=None): """ Complete solution to problem 2.2 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet Notes ----- Part a: Solve equation 2.6 using the linear algebra approach Part b: Solve equation 2.7 using the linear algebra approach """ # ------------------------------- Part a ------------------------------- # n = 30 xmin = 0 xmax = 5 x, h = make_grid(xmin, xmax, n, 'cell_edge') # Create matrix A A = np.zeros((n, n)) # Preallocate memory for A A[0, 0] = 1 # Set first row of A A[-1, -1] = 1 # Set last row of A for i in xrange(1, n - 1): # For readability I compute each element on a separate line and combine jx = x[i] el1 = 1 / (h ** 2) - 1 / (2 * jx * h) # for y_{j - 1} el2 = - 2 / (h ** 2) + 1 - 1 / (jx ** 2) # for y_{j} el3 = 1 / (h ** 2) + 1 / (2 * jx * h) # for y_{j + 1} A[i, i - 1: i + 2] = [el1, el2, el3] # Create vector to represent x in the matrix equation x_approx = np.zeros(n) # Preallocate memory for A x_approx[0] = 0 # Set first row of x_approx x_approx[-1] = 1 # Set last row of x_approx x_approx[1:-1] = x[1:-1] # Fill in all other rows of x_approx # Solve the matrix equation y_approx = la.solve(A, x_approx) # Compute Exact solution y = - 4 / jn(1, 5) * jn(1, x) + x # Plot solution plt.figure() plt.plot(x, y_approx, 'r.', x, y, 'b') plt.title('Plot for part a') plt.draw() # ------------------------------- Part b ------------------------------- # n2 = 600 xmin2 = 0 xmax2 = 5 x2, h2 = make_grid(xmin2, xmax2, n2, 'cell_edge') A2 = np.zeros((n2, n2)) # Preallocate memory for A2 A2[0, 0] = 1 # Set first row of A2 A2[-1, -1] = 1 # Set last row of A2 for i in xrange(1, n2 - 1): # For readability I compute each element on a separate line and combine xi = x2[i] el1 = 1 / (h2 ** 2) - np.sin(xi) / (2 * h2) # for y_{j - 1} el2 = - 2 / (h2 ** 2) + np.exp(xi) # for y_{j} el3 = 1 / (h2 ** 2) + np.sin(xi) / (2 * h2) # for y_{j + 1} A2[i, i - 1: i + 2] = [el1, el2, el3] # Create vector to represent x in the matrix equation x_approx2 = np.zeros(n2) # Preallocate memory for A2 x_approx2[0] = 0 # Set first row of x_approx2 x_approx2[-1] = 3 # Set last row of x_approx2 x_approx2[1:-1] = x2[1:-1] # Fill in all other rows of x_approx2 # Solve the matrix equation y_approx2 = la.solve(A2, x_approx2) plt.figure() plt.plot(x2, y_approx2) plt.title('Plot for part b') plt.draw() ind1 = np.where(x2 > 4.5)[0][0] close_ones = np.array([ind1 - 1, ind1]) print 'From Mathematica y(4.5) = 8.72062' py_data = pd.DataFrame(np.column_stack((x2[close_ones], y_approx2[close_ones])), columns=['x', 'y']) print 'Data around x = 4.5 from python: ' print py_data
def p5_5(part=None): """ Complete solution to problem 5.5 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='P430 5.5', artist='Spencer Lyon') writer = FFMpegWriter(fps=15, metadata=metadata) # Set the values for parameters T = 127 mu = 0.003 L = 1.2 c = np.sqrt(T / mu) # wave speed omega = 400 gamma = 0.2 # build a cell-centered grid with N=200 cells # on the interval x=0 to x=L, with L=1 n = 200 # Number of cells x, h = make_grid(0, L, n, grid_type='cell_center_ghost') f = np.zeros_like(x) f[x >= 0.8] = 0.73 f[x <= 1] = 0 j = np.arange(1, n + 1) # define the initial displacement and velocity vs. x y = np.zeros_like(x) vy = np.exp(- (x - L / 2) ** 2 * 160 / L ** 2) - \ np.exp(- (0 - L / 2) ** 2 * 160 / L ** 2) # Choose a time step (Suggest that it is no larger than taulim) taulim = h / c print 'Courant time step limit %f \n' % (taulim) tau = float(raw_input('Enter the time step: ')) # Get the initial value of yold from the initial y and vy y_old = np.zeros_like(y) # plot the initial conditions and pause to look at them plt.ion() plt.figure() plt.subplot(211) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y(x,0)') plt.title('Initial Displacement') plt.subplot(212) plt.plot(x, vy) plt.xlabel('x') plt.ylabel('v_y(x,0)') plt.title('Initial Velocity') plt.draw() plt.ioff() # Choose how long to run and when to plot tfinal = float(raw_input(' Enter tfinal:')) skip = float(raw_input(' Enter # of steps to skip between plots (faster):')) nsteps = int(tfinal // tau) # here is the loop that steps the solution along max_y = np.zeros(nsteps) times = np.linspace(0, tfinal, nsteps) # Get plot environment ready fig = plt.figure() # TODO: use plt.animate here l, = plt.plot([], [], 'b-') plt.axis([x.min(), x.max(), -0.001, 0.001]) with writer.saving(fig, "p5_5_omega" + str(omega) + ".mp4", 200): for n in xrange(nsteps): time = times[n] # compute the time # Use leapfrog and the boundary conditions to load y_new with y # at the next time step using y and y_old, i.e., y_new(2:N+1)=... # Be sure to use colon commands so it will run fast. ynew = np.zeros_like(y) # ynew[j] = (4 * y[j] - 2 * y_old[j]) / (2 + gamma * tau) + \ # gamma * tau * y_old[j] / (2 + gamma * tau) + \ # 2 * c ** 2 * tau ** 2 / h ** 2 / (2 + gamma * tau) * \ # (y[j + 1] - 2 * y[j] + y[j - 1]) + f[j] * tau ** 2 / mu / \ # (1 + gamma * tau / 2) * np.cos(omega * time) ynew[j] = (1 / (h ** 2 * mu * (gamma * tau + 2))) * ( mu * (2 * (c * tau) ** 2 * (y[j - 1] - 2 * y[j] + y[j + 1]) + h ** 2 * (4 * y[j] + gamma * tau * y_old[j] - 2 * y_old[j])) + 2 * f[j] * (h * tau) ** 2 * np.cos(time * omega)) ynew[0] = -ynew[1] ynew[-1] = -ynew[-2] #update y_old and y y_old = y y = ynew max_y[n] = np.abs(y).max() # make plots every skip time steps if n % skip == 0: l.set_data(x, y) plt.title('Staggered Leapfrog Wave: time %.2e' % time) writer.grab_frame() # plt.plot(x, y, 'b-') # plt.xlabel('x') # plt.ylabel('y') # plt.title('Staggered Leapfrog Wave: time %.2e' % time) # plt.axis([x.min(), x.max(), -0.4, 0.4]) # plt.draw() # raw_input('Press any key to continue') # pause(.1) # TODO: figure out how to use this if n % (10 * skip) == 0: print 'On step %i of %i' % (n, nsteps) plt.figure() plt.plot(times, max_y, 'b-') plt.plot(times, 0.035 * np.exp(-gamma * times / 2), 'r-') plt.title('Max Amplitude vs. time')
def p2_1(part=None): """ Complete solution to problem 2.1 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet Notes ----- Part a: Create a cell edge grid witn n = 30 points from x = 0 to x = 2. Part b: Solve boundary value problem in mathematica, use ToMatlab to get the solution in Python, then plot the solution using a blue curve. Part c: Solve the boundary value problem using the linear algebra technique summarized in equation 2.5 then plot the solution using red dots. Then repeat the process with N = 100 instead of N = 30 """ # ------------------------------- Part a ------------------------------- # n = 30 xmin = 0 xmax = 2 x, h = make_grid(xmin, xmax, n, 'cell_edge') cot = lambda x: 1 / np.tan(x) csc = lambda x: 1 / np.sin(x) # ------------------------------- Part b ------------------------------- # fy = lambda x: \ (1 / 24) * ((-2) * cos(3 * x) * sin(2 * x) + (-4) * cos(2) ** 2 * \ sin(3 * x) + cos(8) * sin(3 * x) + 4 * cos(x) ** 2 * sin(3 * x) + \ (-1) * cos(4 * x) * sin(3 * x) + 24 * csc(6) * sin(3 * x) + 2 * \ cot(6) * sin(4) * sin(3 * x) + (-1) * cot(6) * sin(8) * sin(3 * x) + \ cos(3 * x) * sin(4 * x)) y = fy(x) # ------------------------------- Part c ------------------------------- # # Create the matrix representing A in the matrix equation 2.5 A = np.zeros((n, n)) # Preallocate memory for A A[0, 0] = 1 # Set first row of A A[-1, -1] = 1 # Set last row of A for i in xrange(1, n - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2) + 9, 1 / (h ** 2)] # Create the vector representing x in the matrix equation 2.5 x_approx = np.zeros(n) # Preallocate memory for x_approx x_approx[0] = 0 # Set first row of x_approx x_approx[-1] = 1 # Set last row of x_approx x_approx[1:-1] = sin(x[1:-1]) # Fill in all other rows of x_approx # Approximate y y_approx = la.solve(A, x_approx) plt.figure() plt.plot(x, y, 'b', x, y_approx, 'r.') plt.title('Exact and approximate with n = 30') plt.draw() n2 = 100 h2 = (xmax - xmin) / (n2 - 1) x2 = np.linspace(xmin, xmax, n2) y2 = fy(x2) # Create the matrix representing A in the matrix equation 2.5 A2 = np.zeros((n2, n2)) # Preallocate memory for A2 A2[0, 0] = 1 # Set first row of A2 A2[-1, -1] = 1 # Set last row of A2 for i in xrange(1, n2 - 1): # Fill in all other rows of A2 A2[i, i - 1: i + 2] = [1 / (h2 ** 2), - 2 / (h2 ** 2) + 9, 1 / (h2 ** 2)] # Create the vector representing x in the matrix equation 2.5 x_approx2 = np.zeros(n2) # Preallocate memory for x_approx2 x_approx2[0] = 0 # Set first row of x_approx2 x_approx2[-1] = 1 # Set last row of x_approx2 x_approx2[1:-1] = sin(x2[1:-1]) # Fill in all other rows of x_approx2 # Approximate y y_approx2 = la.solve(A2, x_approx2) plt.figure() plt.plot(x2, y2, 'b', x2, y_approx2, 'r.') plt.title('Exact and approximate with n = 100') plt.draw()
def p3_2(part=None): """ Complete solution to problem 3.2 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ # ------------------------------- Part a ------------------------------- # mu = 0.003 T = 127 L = 1.2 omega = 400 # Build grid n = 100 xmin = 0 xmax = L x, h = make_grid(xmin, xmax, n, 'cell_edge') # Create A matrix A = np.zeros((n, n)) A[0, 0] = 1 A[-1, -1] = 1 for i in xrange(1, n - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2), 1 / (h ** 2)] # Create B matrix B = np.eye(n) B[0, 0] = 0 B[-1, -1] = 0 # Solve genearalized eigenvalue problem (eigen.m for python) lamb, v1 = la.eig(A, B) w2raw = - (T / mu) * lamb # convert lambda to w ** 2 w2, k = [np.sort(w2raw), np.argsort(w2raw)] # sort and get indices contin = 1 for i in range(n): if contin == 1: t = r'$\omega^2$ = %.3f, $\omega$ = %.3f' \ % (w2[i], np.sqrt(np.abs(w2[i]))) gn = v1[:, k[i]] # w = (i + 1) * np.pi / L plt.figure() plt.plot(x, gn, 'r.') plt.title(t) plt.xlabel('x') plt.ylabel('g(n, x)') plt.draw() ans = raw_input('Continue? Enter 0 if no, leave blank if yes ') try: contin = int(ans) plt.close('all') except ValueError: contin = 1 else: plt.close('all') break # ------------------------------- Part b ------------------------------- # # Get the first two frequencies first_w = np.sqrt(w2[0]).real second_w = np.sqrt(w2[1]).real # Use the iteration_data object created in 3.1.b iteration_data = p3_1(no_plot=True) maxes = iteration_data.max(0) where_1 = np.where(maxes.index > first_w)[0][0] where_2 = np.where(maxes.index > second_w)[0][0] plt.figure(figsize=(14, 5)) plt.subplot(121) plt.plot(maxes.index[where_1 - 5: where_1 + 5], maxes.ix[where_1 - 5: where_1 + 5]) plt.title(r'Around $\omega$ = %.3f' % first_w) plt.xlabel(r'$\omega$') plt.ylabel('Max Amplitude') plt.subplot(122) plt.plot(maxes.index[where_2 - 5: where_2 + 5], maxes.ix[where_2 - 5: where_2 + 5]) plt.title(r'Around $\omega$ = %.3f' % second_w) plt.xlabel(r'$\omega$') plt.ylabel('Max Amplitude') plt.show()
def p2_3(part=None): """ Complete solution to problem 2.3 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know- Notes ----- Part a: Solve equation 2.8 with forward difference for derivative B.C. Part b: Solve equation 2.8 with quadratic extrapolation for derivative B.C. """ def p2_2_sym(): a, b, c, x, xN, xNm1, xNm2 = symbols('a, b, c, x, xN, xNm1, xNm2') h, yN, yNm1, yNm2 = symbols('h, yN, yNm1, yNm2') xNm1 = xN - h xNm2 = xN - 2 * h eqns = (Eq(yN, a + b * xN + c * xN ** 2), Eq(yNm1, a + b * xNm1 + c * xNm1 ** 2), Eq(yNm2, a + b * xNm2 + c * xNm2 ** 2)) soln = solve(eqns, a, b, c) x = symbols('x') y = a + b * x + c * x ** 2 yprime = diff(y, x) soln[x] = xN ans = expand(yprime.subs(soln)) print 'Solution to symbolic part: ' pprint(ans) return # ------------------------------- Part a ------------------------------- # n = 30 xmin = 0 xmax = 2 x, h = make_grid(xmin, xmax, n, 'cell_edge') # Create the matrix representing A in the matrix equation 2.5 A = np.zeros((n, n)) # Preallocate memory for A A[0, 0] = 1 # Set first row of A A[-1, -2:] = [-1 / h, 1 / h] # Set last row of A for i in xrange(1, n - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2) + 9, 1 / (h ** 2)] # Create the vector representing x in the matrix equation 2.5 x_approx = np.zeros(n) # Preallocate memory for x_approx x_approx[0] = 0 # Set first row of x_approx x_approx[-1] = 0 # Set last row of x_approx x_approx[1:-1] = x[1:-1] # Fill in all other rows of x_approx # Approximate y y_approx = la.solve(A, x_approx) y = x / 9 - np.sin(3 * x) / (27 * np.cos(6)) plt.figure() plt.plot(x, y_approx, 'r.', x, y, 'b-') plt.title('Problem 2.3 part a') plt.draw() rms_err_a = np.sqrt(np.mean(np.power(y - y_approx, 2))) # ------------------------------- Part b ------------------------------- # # Call symbolic function: p2_2_sym() # Create A matrix A2 = np.zeros((n, n)) # Preallocate memory for A2 A2[0, 0] = 1 # Set first row of A2 A2[-1, -3:] = [1 / (2 * h), -2 / h, 3 / (2 * h)] # Set last row of A2 for i in xrange(1, n - 1): # Fill in all other rows of A2 A2[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2) + 9, 1 / (h ** 2)] # Approximate y y_approx2 = la.solve(A2, x_approx) plt.figure() plt.plot(x, y_approx2, 'r.', x, y, 'b-') plt.title('Problem 2.3 part b') rms_err_b = np.sqrt(np.mean(np.power(y - y_approx2, 2))) err = pd.DataFrame(np.array([rms_err_a, rms_err_b]), index=['Forward Difference', 'Quadratic Extrapolation'], columns=['RMS errors']) print err
def p3_3(part=None): """ Complete solution to problem 3.3 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ # ------------------------------- Part a ------------------------------- # mu = 0.003 T = 127 L = 1.2 omega = 400 # Build grid n = 100 xmin = 0 xmax = L x, h = make_grid(xmin, xmax, n, 'cell_edge') # Create A matrix A = np.zeros((n, n)) A[0, 0] = 1 A[-1, -3:] = [1 / (2 * h), -2 / h, 3 / (2 * h)] for i in xrange(1, n - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2), 1 / (h ** 2)] # Create B matrix B = np.eye(n) B[0, 0] = 0 B[-1, -1] = 0 # Solve genearalized eigenvalue problem (eigen.m for python) lamb, v1 = la.eig(A, B) w2raw = - (T / mu) * lamb # convert lambda to w ** 2 w2, k = [np.sort(w2raw), np.argsort(w2raw)] # sort and get indices contin = 1 for i in range(n): if contin == 1: t = r'$\omega^2$ = %.3f, $\omega$ = %.3f' \ % (w2[i], np.sqrt(np.abs(w2[i]))) gn = v1[:, k[i]] plt.figure() plt.axis([0, L, -1, 1]) plt.plot(x, gn, 'r.') plt.title(t) plt.xlabel('x') plt.ylabel('g(n, x)') plt.draw() ans = raw_input('Continue? Enter 0 if no, leave blank if yes ') try: contin = int(ans) plt.close('all') except ValueError: contin = 1 else: plt.close('all') break # ------------------------------- Part b ------------------------------- # # Create A matrix A2 = np.zeros((n, n)) A2[0, 0] = 1 A2[-1, -3:] = [1 / (2 * h), -2 / h, 3 / (2 * h) - 2] for i in xrange(1, n - 1): # Fill in all other rows of A2 A2[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2), 1 / (h ** 2)] # Create B matrix B = np.eye(n) B[0, 0] = 0 B[-1, -1] = 0 # Solve genearalized eigenvalue problem (eigen.m for python) lamb2, v12 = la.eig(A2, B) w2raw2 = - (T / mu) * lamb2 # convert lambda to w ** 2 w22, k2 = [np.sort(w2raw2), np.argsort(w2raw2)] # sort and get indices contin = 1 for i in range(n): if contin == 1: t = r'$\omega^2$ = %.3f, $\omega$ = %.3f' \ % (w22[i], np.sqrt(np.abs(w22[i]))) gn = v12[:, k2[i]] plt.figure() plt.axis([0, L, -1, 1]) plt.plot(x, gn, 'r.') plt.title(t) plt.xlabel('x') plt.ylabel('g(n, x)') plt.draw() ans = raw_input('Continue? Enter 0 if no, leave blank if yes ') try: contin = int(ans) plt.close('all') except ValueError: contin = 1 else: plt.close('all') break
def p2_4(part=None): """ Complete solution to problem 2.4 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet Notes ----- Part a: We can't turn this into a linear algebra problem because of the fact that y(x) is embedded inside the sin() function. Part b: Solve equation 2.13 with linear algebra methods inside an iterative loop. """ # ------------------------------- Part b ------------------------------- # n = 50 xmin = 0 xmax = 3 x, h = make_grid(xmin, xmax, n, 'cell_edge') # Create the matrix representing A in the matrix equation 2.5 A = np.zeros((n, n)) # Preallocate memory for A A[0, 0] = 1 # Set first row of A A[-1, -1] = 1 # Set last row of A for i in xrange(1, n - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2), - 2 / (h ** 2), 1 / (h ** 2)] # Setup iteration variables toler = 1e-8 # convergence criterion max_iter = 500 # Max number of iterations its = 0 # iteration number counter dist = 500 # starting norm # define initial y(x) y_old = np.zeros(n) while its < max_iter and dist > toler: b = 1 - np.sin(y_old) # Create b using y_old b[0] = 0 b[-1] = 0 y = la.solve(A, b) # Solve linear problem for y # Create y'' and check the norm dist = np.linalg.norm(A.dot(y) - 1 + np.sin(y)) # Set y_old equal to the y created on this iteration and update its y_old = y its += 1 plt.figure() plt.plot(x, y) plt.title('Solution to 2.4 part b') plt.show()
def models(nber_fit, map_params, l, cl, mass_int, z, centroid_shift_value=0, bl=None, cl_noise=None, cutout_size_am=10, use_magnitude_weights=True, use_noise_weights=False, apply_noise=True, average=1): nx, dx, ny, dy = map_params if cl_noise is None: cl_noise = np.zeros(max(l) + 1) mass_int = np.copy(mass_int) * 1e14 models = [] for k in range(average): cutouts_clus_arr = [] magnitude_weights_clus_arr = [] profile_models_arr = [] for i in range(nber_fit): sim = sims.cmb_mock_data(map_params, l, cl) x_shift, y_shift = np.random.normal( loc=0.0, scale=centroid_shift_value / (2**0.5)), np.random.normal( loc=0.0, scale=centroid_shift_value / (2**0.5)) centroid_shift = [x_shift, y_shift] grid, _ = tools.make_grid(map_params, grid_shift=centroid_shift) theta = np.hypot(grid[0], grid[1]) total_noise_map = tools.make_gaussian_realization( l, cl_noise, map_params) for j in range(len(mass_int)): c200c = cosmo.concentration_parameter(mass_int[j], z, 0.674) kappa_map = lensing.NFW_convergence(mass_int[j], c200c, z, 1100, theta, dim=2) alpha_vec = lensing.deflection_from_convergence( kappa_map, map_params) sim_lensed = lensing.lens_map(sim, alpha_vec, map_params) sim_lensed_noise = np.copy(sim_lensed) sim_lensed_noise += total_noise_map if bl is not None: sim_lensed = tools.convolve(sim_lensed, l, np.sqrt(bl), map_params=map_params) sim_lensed_noise = tools.convolve(sim_lensed_noise, l, np.sqrt(bl), map_params=map_params) if apply_noise is False: sim_lensed_noise = np.copy(sim_lensed) cutout_aligned, magnitude_weight = get_aligned_cutout( map_params, sim_lensed_noise, image_noiseless=sim_lensed, cutout_size_am=cutout_size_am, l=l, cl=cl, cl_noise=cl_noise) if use_magnitude_weights is False: magnitude_weight = 1 cutouts_clus_arr.append(cutout_aligned * magnitude_weight) magnitude_weights_clus_arr.append(magnitude_weight) stack_bg = np.sum(cutouts_clus_arr[0::len(mass_int)], axis=0) / np.sum( magnitude_weights_clus_arr[0::len(mass_int)]) for i in range(len(mass_int)): stack_clus = np.sum( cutouts_clus_arr[i::len(mass_int)], axis=0) / np.sum( magnitude_weights_clus_arr[i::len(mass_int)]) stack_dipole = stack_clus - stack_bg profile_model = np.mean(stack_dipole, axis=0) profile_models_arr.append(profile_model) models.append(profile_models_arr) return np.mean(models, axis=0)
def p1_4(part=None): """ Complete solution to problem 1.4 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet TODO: Call centered difference formula for derivatives. """ x, h = make_grid(0, 5, 100) f = lambda x: jn(0, x) # define function y = f(x) # Evaluate function on grid # Get numerical derivatives using routine from tools.py yplin = centered_difference(y, 1, h, 'linear') ypplin = centered_difference(y, 2, h, 'linear') ypquad = centered_difference(y, 1, h, 'quadratic') yppquad = centered_difference(y, 2, h, 'quadratic') # Calculate real derivatives fp = - jn(1, x) fpp = 1 / 2 * (- jn(0, x) + jn(2, x)) abs_err_linp = np.mean(np.abs(yplin - fp)) # linear 1st der. error abs_err_linpp = np.mean(np.abs(ypplin - fpp)) # linear 2nd der. error abs_err_quadp = np.mean(np.abs(ypquad - fp)) # quad 1st der. error abs_err_quadpp = np.mean(np.abs(yppquad - fpp)) # quad 2nd der. error print 'Linear first derivative error: %.8e' % (abs_err_linp) print 'Linear second derivative error: %.8e' % (abs_err_linpp) print 'Quadratic first derivative error: %.8e' % (abs_err_quadp) print 'Quadratic second derivative error: %.8e' % (abs_err_quadpp) plt.figure() plt.subplot(211) plt.plot(x, fp, x, yplin, x, ypquad) plt.title('First derivatives') plt.legend(('Real Derivative', 'Linear Extrapolation', 'quadratic Extrapolation'), loc=0) plt.subplot(212) plt.plot(x, fpp, x, ypplin, x, yppquad) plt.title('Second derivatives') plt.legend(('Real Derivative', 'Linear Extrapolation', 'quadratic Extrapolation'), loc=0) plt.draw() pass # return nothing
def p4_2(part=None): """ Complete solution to problem 4.2 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ # Define parameters and create grid L = 2 xmin = 0 xmax = L n = 200 x, h = make_grid(xmin, xmax, n, 'cell_center_ghost') # Get number of elements in x (number of rows in A and B) n_rows = x.size # Create A matrix A = np.zeros((n_rows, n_rows)) A[-1, -2] = 1. / 2 # Equation 4.8 A[-1, -1] = 1. / 2 # Equation 4.8 A[0, 0] = -1. / h # Equation 4.10 A[0, 1] = 1. / h # Equation 4.10 for i in xrange(1, n_rows - 1): # Fill in all other rows of A A[i, i - 1: i + 2] = [1 / (h ** 2) * x[i] - 1 / (2 * h), - 2 / (h ** 2) * x[i], 1 / (h ** 2) * x[i] + 1 / (2 * h)] # Create B matrix B = np.eye(n_rows) B[-1, -1] = 0 # Equation 4.8 B[0, 0] = 1. / 2 # Equation 4.10 B[0, 1] = 1. / 2 # Equation 4.10 # Solve genearalized eigenvalue problem (eigen.m for python) lamb, v1 = la.eig(A, B) w2raw = - 9.8 * lamb # convert lambda to w ** 2. g = 9.8 w2, k = [np.sort(w2raw), np.argsort(w2raw)] # sort and get indices contin = 1 for i in range(n): if contin == 1: t = r'$\omega_{%s}^2$ = %.3f, $\omega_{%s}$ = %.3f' \ % (i + 1, w2[i], i + 1, np.sqrt(np.abs(w2[i]))) gn = v1[:, k[i]] plt.figure() plt.plot(gn, x, 'r.') plt.title(t) plt.xlabel(r'$g_{%s}(x)$' % (i + 1)) plt.ylabel('x') plt.draw() ans = raw_input('Continue? Enter 0 if no, leave blank if yes ') try: contin = int(ans) plt.close('all') except ValueError: contin = 1 else: plt.close('all') break
def p5_4(part=None): """ Complete solution to problem 5.4 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ # Initialize the animation writer FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='P430 5.4', artist='Spencer Lyon') writer = FFMpegWriter(fps=15, metadata=metadata) # Set the values for parameters c = 2 # wave speed gamma = 0.2 # build a cell-centered grid with N=200 cells # on the interval x=0 to x=L, with L=1 L = 1 # Left boundary n = 200 # Number of cells x, h = make_grid(0, L, n, grid_type='cell_center_ghost') j = np.arange(1, n + 1) # define the initial displacement and velocity vs. x y = np.zeros_like(x) vy = np.exp(- (x - L / 2) ** 2 * 160 / L ** 2) - \ np.exp(- (0 - L / 2) ** 2 * 160 / L ** 2) # Choose a time step (Suggest that it is no larger than taulim) taulim = h / c print 'Courant time step limit %f \n' % (taulim) tau = float(raw_input('Enter the time step: ')) # Get the initial value of yold from the initial y and vy y_old = np.zeros_like(y) y_old[j] = (1 / (2 * h ** 2)) * ( (c * tau) ** 2 * (y[j - 1] - 2 * y[j] + y[j + 1]) + h ** 2 * (2 * y[j] - tau * vy[j] * (gamma * tau + 2))) # Apply the boundary conditions for yold(1) and yold(N+2) y_old[0] = 0 y_old[-1] = 0 # plot the initial conditions and pause to look at them plt.ion() plt.figure() plt.subplot(211) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y(x,0)') plt.title('Initial Displacement') plt.subplot(212) plt.plot(x, vy) plt.xlabel('x') plt.ylabel('v_y(x,0)') plt.title('Initial Velocity') plt.show() plt.draw() plt.ioff() # Choose how long to run and when to plot tfinal = float(raw_input(' Enter tfinal:')) skip = float(raw_input(' Enter # of steps to skip between plots (faster):')) nsteps = int(tfinal / tau) # here is the loop that steps the solution along fig = plt.figure() l, = plt.plot([], [], 'b-') plt.axis([x.min(), x.max(), -0.04, 0.04]) max_y = np.zeros(nsteps) times = np.linspace(0, 25, nsteps) with writer.saving(fig, "p5_4c.mp4", 200): for n in range(nsteps): time = times[n] # compute the time # Use leapfrog and the boundary conditions to load y_new with y # at the next time step using y and y_old, i.e., y_new(2:N+1)=... # Be sure to use colon commands so it will run fast. ynew = np.zeros_like(y) ynew[j] = (1 / (2 + gamma * tau)) * ( 4 * y[j] - 2 * y_old[j] + gamma * tau * y_old[j] + (2 * (c * tau) ** 2 / (h ** 2)) * (y[j + 1] - 2 * y[j] + y[j - 1])) #update y_old and y y_old = y y = ynew max_y[n] = y.max() # make plots every skip time steps if n % skip == 0: print 'On step %i of %i' % (n, nsteps) l.set_data(x, y) plt.title('Staggered Leapfrog Wave: time %.2e' % time) writer.grab_frame() # plt.plot(x, y, 'b-') # plt.xlabel('x') # plt.ylabel('y') # plt.title('Staggered Leapfrog Wave: time %.2e' % time) # plt.axis([x.min(), x.max(), -2, 2]) # if part == 'c': # plt.axis([x.min(), x.max(), -0.04, 0.04]) # plt.draw() # raw_input('Press any key to continue') # pause(.1) # TODO: figure out how to use this plt.figure() plt.plot(times, max_y, 'b-') plt.plot(times, 0.035 * np.exp(-gamma * times / 2), 'r-') plt.title('Max Amplitude vs. time')