price = [5.99, 10.25, 2.0, 40.99, 5.60, 63.49] price*2 price+0.5 for i in range(len(price)): price[i] = price[i]*2 price[i] = price[i]+0.5 print price from numpy import * sin(3*pi/2)*exp(2) import numpy as np price = np.array([5.99, 10.25, 2.0, 40.99, 5.60, 63.49]) print type(price) price = price*2+0.5 print price x = np.linspace(-1,1,5) print x y = np.arange(0,1,0.2) print y # type your solution here #%load solutions/1D_array.py np.arange? A = np.array([[1,2.4,-13],[4.1,5,0],[7.2,8,9]]) print "A = ", A print type(A) print A.shape print A.dtype A = np.array([[1,2+4j,3j],[4j,5,6-5j],[7j,8,9+3j]]) # dtype=complex print A.conjugate() print A.size np.random.uniform(0,1,size=(5,5)) # 5 x 5 matrix with elements from a uniform distribution print np.zeros((3,4)) print np.ones((2,3)) print np.eye(3) print np.diag(x,0) print np.diag([2,3,4]) print np.random.random((2,2)) A = np.arange(1,10) print "A = ", A A = A.reshape((3,3)) print A B = arange(15).reshape((3,5)) print "B = ", B print B.ravel() # flatten the array print A print A[0,0] print A[1:3,0:2] print A[1:3,[0,1]] print A print A[0,:] # row selection print A[:,0] # column selection print A[:,1:] # all rows, from 2nd column until the end print A[-1,:] # last row, all columns A[:,2] = [.3,.4,9.12] print A print A.dtype A = array(A,dtype='float') A[:,2] = [.3,.4,9.12] print A a = arange(10) print a print a[: :-1] # reverse a b = a>5 print b a[b] = 0 # All elements of 'a' higher than 5 become 0 print a print a**2 print 10*sin(np.pi/a[1:5]) # avoiding division with zero! print A*A np.dot(A,A) A = array(A,dtype='int') print A print A.sum() # sum of all elements print A.min() print A.max() print A.sum(axis=0) # sum of each column print A.min(axis=1) # min of each row print A.cumsum(axis=1) # cumulative sum along each row A = floor(10*random.random((2,2))) print A B = floor(10*random.random((2,2))) print B print np.vstack((A,B)) print np.hstack((B,A)) A = floor(10*random.random((2,12))) print A print np.hsplit(A,3) # Split A into 3 arrays print np.hsplit(A,(3,4)) # Split A after the third and the fourth column # type your solution here #%load solutions/array_operations.py import os filename = 'stockholm_temp.txt' if os.path.exists(filename): # look at the first 3 lines with open(filename,'r') as f: print '\n'.join(f.readlines()[:3]) # alternative look at the first head lines !head 'stockholm_temp.txt' data = np.loadtxt(filename) # alternative we can use genfromtxt command else: print 'Weather data does not exist, please download "stockholm_temp.txt" from Github.' dt = np.dtype([('Year', 'int16'), ('Month', 'int8'), ('Day', 'int8'), ('Temp', 'float64')]) data = np.loadtxt(filename,dtype=dt) data[:10] # first 10 entries of our data data['Temp'] years = np.unique(data['Year']) # making an array with each year appearing only once leap_years = np.zeros((1,),dtype='int16') # initializing array for leap years for i in range(len(years)): if np.fmod(years[i],4)==0 and ((np.fmod(years[i],100)==0 and np.fmod(years[i],400)==0) or np.fmod(years[i],100)!=0): leap_years = np.append(leap_years,years[i]) # adding a leap year leap_years = leap_years[1:] # removing dummy first value print leap_years # type your solution here #%load solutions/temperatures.py x = np.random.random(10) print x np.linalg.norm(x,np.inf) # maximum norm of a vector A = np.array([[0,2],[8,0]]) b = np.array([1,2]) print A print b x = np.linalg.solve(A,b) print x lamda,V = np.linalg.eig(A) print lamda print V # type your solution here #%load solutions/linear_algebra.py %pylab inline --no-import-all import matplotlib.pyplot as plt x = np.linspace(0,np.pi,1000) f = np.sin(np.exp(x)) g = np.cos(2*x) plt.plot(x,f) plt.plot(x,g) plt.figure(figsize=(10,6), dpi=100) # changing figure's shape plt.xlim(x.min()-0.1, x.max()+0.1) # adjusting horizonatal axis limits plt.ylim(f.min()-0.1, f.max()+0.1) # adjusting vertical axis limits plt.xticks([0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'],fontsize=14) # setting ticks plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'],fontsize=14) # setting ticks plt.plot(x, f, color="blue", linewidth=2.5, linestyle="-", label="$\sin(e^x)$") # changing color and thickness plt.plot(x, g, color="red", linewidth=2.5, linestyle="-", label="$\cos(2x)$") # changing color and thickness plt.legend(loc='lower left',prop={'size':16}) # placing legend on bottom left plt.xlabel('$x$',fontsize=16) # horizontal axis name plt.ylabel('test functions',fontsize=16) # vertical axis name plt.title('Sample plot',fontsize=18) # title plt.grid(True) # enabling grid #plt.savefig('trig_functions.pdf') plt.savefig('trig_functions.pdf') alpha = 0.7 phi_ext = 2*np.pi*0.5 def flux_qubit_potential(phi_m, phi_p): return 2 + alpha - 2*np.cos(phi_p)*np.cos(phi_m) - alpha*np.cos(phi_ext - 2*phi_p) phi_m = np.linspace(0, 2*np.pi, 100) phi_p = np.linspace(0, 2*np.pi, 100) X,Y = np.meshgrid(phi_p, phi_m) Z = flux_qubit_potential(X, Y).T from mpl_toolkits.mplot3d.axes3d import Axes3D # imports 3D plotting from matplotlib import cm # module for color pattern fig = plt.figure(figsize=(14,6)) # `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot ax = fig.add_subplot(1, 2, 1, projection='3d') p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0) # surface_plot with color grading and color bar ax = fig.add_subplot(1, 2, 2, projection='3d') p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) cb = fig.colorbar(p, shrink=0.5) # enables colorbar # type your solution here #%load solutions/plotting.py def solution(filename, path='woodward_colella_blast'): """ This function reads the solution stored in an ascii file written by pyclaw. """ import sys # Concatenate path and file name pathfilename = path + "/" + filename try: f = open(pathfilename,"r") except IOError as e: print("({})".format(e)) sys.exit() # Read file header # The information contained in the first two lines are not used. unused = f.readline() # grid_number unused = f.readline() # AMR_level # Read mx, my, xlow, ylow, dx and dy line = f.readline() sline = line.split() mx = int(sline[0]) line = f.readline() sline = line.split() xlower = float(sline[0]) line = f.readline() sline = line.split() dx = float(sline[0]) # Grid: xupper = xlower + mx * dx xc = np.linspace(xlower+dx/2.,xupper-dx/2.,mx) # Read solution # Define arrays of conserved variables q = np.zeros((mx,3)) line = f.readline() for j in range(mx): line = f.readline() q[j,:] = np.array(map(float, line.split())) return q, xc def time(filename, path='woodward_colella_blast'): """ This function reads the time stored in an ascii file written by pyclaw. """ from clawpack import pyclaw import sys # Concatenate path and file name pathfilename = path + "/" + filename try: f = open(pathfilename,"r") except IOError as e: print("({})".format(e)) sys.exit() # Read time line = f.readline() sline = line.split() t = float(sline[0]) return t def fplot(i): index = "%02d" % i q, xc = solution('fort.q00' + index) t = time('fort.t00' + index) line.set_data(xc, q[:,0]) ax.set_title('Density at t='+str(t)) return line def init(): line.set_data([], []) return line, ### main block ### from matplotlib import animation import matplotlib.pyplot as plt from clawpack.visclaw.JSAnimation import IPython_display _, xc = solution('fort.q0000') fig = plt.figure(figsize=[8,4]) ax = plt.axes(xlim=(xc[0], xc[-1]), ylim=(0, 10)) line, = ax.plot([], [], lw=2) animation.FuncAnimation(fig, fplot, frames=11, init_func=init, blit=True)