Exemple #1
1
def comparison_plot(f, u, Omega, filename='tmp.pdf',
                    plot_title='', ymin=None, ymax=None,
                    u_legend='approximation'):
    """Compare f(x) and u(x) for x in Omega in a plot."""
    x = sm.Symbol('x')
    print 'f:', f

    f = sm.lambdify([x], f, modules="numpy")
    u = sm.lambdify([x], u, modules="numpy")
    if len(Omega) != 2:
        raise ValueError('Omega=%s must be an interval (2-list)' % str(Omega))
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    if not isinstance(Omega[0], (int,float)):
        Omega[0] = float(Omega[0].evalf())
    if not isinstance(Omega[1], (int,float)):
        Omega[1] = float(Omega[1].evalf())

    resolution = 401  # no of points in plot
    xcoor = linspace(Omega[0], Omega[1], resolution)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    exact  = f(xcoor)
    approx = u(xcoor)
    plot(xcoor, approx, '-')
    hold('on')
    plot(xcoor, exact, '-')
    legend([u_legend, 'exact'])
    title(plot_title)
    xlabel('x')
    if ymin is not None and ymax is not None:
        axis([xcoor[0], xcoor[-1], ymin, ymax])
    savefig(filename)
Exemple #2
0
def comparison_plot(f, u, Omega, plotfile='tmp'):
    """Compare f(x,y) and u(x,y) for x,y in Omega in a plot."""
    x, y = sm.symbols('x y')

    f = sm.lambdify([x,y], f, modules="numpy")
    u = sm.lambdify([x,y], u, modules="numpy")
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    for r in range(2):
        for s in range(2):
            if not isinstance(Omega[r][s], (int,float)):
                Omega[r][s] = float(Omega[r][s].evalf())

    resolution = 41  # no of points in plot
    xcoor = linspace(Omega[0][0], Omega[0][1], resolution)
    ycoor = linspace(Omega[1][0], Omega[1][1], resolution)
    xv, yv = ndgrid(xcoor, ycoor)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    exact  = f(xv, yv)
    approx = u(xv, yv)
    figure()
    surfc(xv, yv, exact, title='f(x,y)',
          colorbar=True, colormap=hot(), shading='flat')
    if plotfile:
        savefig('%s_f.pdf' % plotfile, color=True)
        savefig('%s_f.png' % plotfile)
    figure()
    surfc(xv, yv, approx, title='f(x,y)',
          colorbar=True, colormap=hot(), shading='flat')
    if plotfile:
        savefig('%s_u.pdf' % plotfile, color=True)
        savefig('%s_u.png' % plotfile)
Exemple #3
0
def solver(T, dt, v0, Cd, rho, A, m, Source=None):
    """
    This is the main solver function for the program. It takes the problem 
    specific variables as arguments, and returns two meshes containing the 
    velocity and time points respectively.
    """
    a = Cd * rho * A / (2 * m)  # Set up the constant a for compact code
    v = zeros(int(T / dt) + 1)  # Create the velocity mesh
    v[0] = v0
    g = 9.81
    #Initial velocity and the value of gravity acceleration

    # Description of the functions X(t) and Y(t) is given in the PDF file
    def X(t):
        if (Source == None):
            return -g
        else:
            return -g + Source(t + dt / 2.) / m

    def Y(t):
        return a

    #Calculate the velocity at each meshpoint
    for i in range(1, len(v)):
        v[i] = skydiving_iterate(v[i - 1], dt * (i - 1), dt, X, Y)
    return v, linspace(0, T, T / dt + 1)
Exemple #4
0
def comparison_plot(u, Omega, u_e=None, filename='tmp.eps',
                    plot_title='', ymin=None, ymax=None):
    x = sp.Symbol('x')
    u = sp.lambdify([x], u, modules="numpy")
    if len(Omega) != 2:
        raise ValueError('Omega=%s must be an interval (2-list)' % str(Omega))
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    if not isinstance(Omega[0], (int,float)):
        Omega[0] = float(Omega[0].evalf())
    if not isinstance(Omega[1], (int,float)):
        Omega[1] = float(Omega[1].evalf())

    resolution = 401  # no of points in plot
    xcoor = linspace(Omega[0], Omega[1], resolution)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    approx = u(xcoor)
    plot(xcoor, approx)
    legends = ['approximation']
    if u_e is not None:
        exact  = u_e(xcoor)
        hold('on')
        plot(xcoor, exact)
        legends = ['exact']
    legend(legends)
    title(plot_title)
    xlabel('x')
    if ymin is not None and ymax is not None:
        axis([xcoor[0], xcoor[-1], ymin, ymax])
    savefig(filename)
Exemple #5
0
def test_easyviz():
    from scitools.std import linspace, ndgrid, plot, contour, peaks, \
         quiver, surfc, backend, get_backend
    n = 21
    x = linspace(-3, 3, n)
    xx, yy = ndgrid(x, x, sparse=False)

    # a basic plot
    plot(x, x**2, 'bx:')
    wait()

    if backend in ['gnuplot', 'vtk', 'matlab', 'dx', 'visit', 'veusz']:
        # a contour plot
        contour(peaks(n), title="contour plot")
        wait()

        # a vector plot
        uu = yy
        vv = xx
        quiver(xx, yy, uu, vv)
        wait()

        # a surface plot with contours
        zz = peaks(xx, yy)
        surfc(xx, yy, zz, colorbar=True)
        wait()

    if backend == 'grace':
        g = get_backend()
        g('exit')
Exemple #6
0
def test_easyviz():
    from scitools.std import linspace, ndgrid, plot, contour, peaks, \
         quiver, surfc, backend, get_backend
    n = 21
    x = linspace(-3, 3, n)
    xx, yy = ndgrid(x, x, sparse=False)

    # a basic plot
    plot(x, x**2, 'bx:')
    wait()

    if backend in ['gnuplot', 'vtk', 'matlab', 'dx', 'visit', 'veusz']:
        # a contour plot
        contour(peaks(n), title="contour plot")
        wait()

        # a vector plot
        uu = yy
        vv = xx
        quiver(xx, yy, uu, vv)
        wait()

        # a surface plot with contours
        zz = peaks(xx, yy)
        surfc(xx, yy, zz, colorbar=True)
        wait()

    if backend == 'grace':
        g = get_backend()
        g('exit')
Exemple #7
0
def _test():
#	from InverseFunction import InverseFunction as I
	from scitools.std import log, linspace, plot
	def f(x):
		return log(x)
	x = linspace(1, 5, 101)
	f_inv = InverseFunction(f, x)
	plot(x,f(x),x, f_inv.values,legend=['log(x)', 'inv log(x)'])
	raw_input('Press Enter to quit: ')
Exemple #8
0
def _test():
    x0 = float(sys.argv[1])
    x, info = Newton(_g, x0, _dg, store=True)
    print('root: %.16g' % x)
    for i in range(len(info)):
        print('Iteration %2d: f(%g)=%g' % (i, info[i][0], info[i][1]))

    x = linspace(-7, 7, 401)
    y = _g(x)
    plot(x, y)
	def graph(self, resolution=1001):
		'''
		graphs the Lagrange polynomial over self.points	
		'''
		#from scitools.std import *
		from scitools.std import zeros, linspace, plot, array
		points = self.points
		xlist = linspace(points[0,0], points[-1,0], resolution)
		ylist = self.__call__(xlist)
		plot(xlist, ylist)
Exemple #10
0
    def graph(self, resolution=1001):
        '''
		graphs the Lagrange polynomial over self.points	
		'''
        #from scitools.std import *
        from scitools.std import zeros, linspace, plot, array
        points = self.points
        xlist = linspace(points[0, 0], points[-1, 0], resolution)
        ylist = self.__call__(xlist)
        plot(xlist, ylist)
Exemple #11
0
 def __call__(self, x):
     from scitools.std import linspace, sum, zeros,iseq
     f, a, n = self.f, self.a, self.n
     h = (x-a)/float(n)
     I = 0.5*f(a)
     ar = zeros(len(linspace(1,n-1, n-1)))
     for i in iseq(1, n-1):
         ar[i-1] = f(a + i*h)
     I = sum(ar)
     I += 0.5*f(x)
     I *= h
     return I
Exemple #12
0
 def __call__(self, x):
     from scitools.std import linspace, sum, zeros, iseq
     f, a, n = self.f, self.a, self.n
     h = (x - a) / float(n)
     I = 0.5 * f(a)
     ar = zeros(len(linspace(1, n - 1, n - 1)))
     for i in iseq(1, n - 1):
         ar[i - 1] = f(a + i * h)
     I = sum(ar)
     I += 0.5 * f(x)
     I *= h
     return I
def comparison_plot(f, u, Omega, filename='tmp.pdf'):
    x = sm.Symbol('x')
    f = sm.lambdify([x], f, modules="numpy")
    u = sm.lambdify([x], u, modules="numpy")
    resolution = 401  # no of points in plot
    xcoor  = linspace(Omega[0], Omega[1], resolution)
    exact  = f(xcoor)
    approx = u(xcoor)
    plot(xcoor, approx)
    hold('on')
    plot(xcoor, exact)
    legend(['approximation', 'exact'])
    savefig(filename)
Exemple #14
0
def _test():
    from scitools.std import sin, cos, exp, linspace, plot, pi
    import sys

    x0 = float(sys.argv[1])
    x, info = Newton(_g, x0, _dg, store=True)
    print("root: %.16g" % x)
    for i in range(len(info)):
        print("Iteration %2d: f(%g)=%g" % (i, info[i][0], info[i][1]))

    x = linspace(-7, 7, 401)
    y = _g(x)
    plot(x, y)
Exemple #15
0
def _test():
    from scitools.std import sin, cos, exp, linspace, plot, pi
    import sys

    x0 = float(sys.argv[1])
    x, info = Newton(_g, x0, _dg, store=True)
    print('root: %.16g' % x)
    for i in range(len(info)):
        print('Iteration %2d: f(%g)=%g' % \
              (i, info[i][0], info[i][1]))

    x = linspace(-7, 7, 401)
    y = _g(x)
    plot(x, y)
Exemple #16
0
def forward_leaper(I,a,b,T,dt):
	"""
	Solves u'(t) = -a(t)*u(t) + b(t), u(0) = I with a forward difference scheme.
	"""

	raise_type(a)
	raise_type(b)

	dt = float(dt)
	N = int(round(T/dt)) # Rounds off to the closest integer
	T = N*dt # Recalculate the T value based upon the new N value
	u = zeros(N+1)
	t = linspace(0,T,N+1)
		
	for n in range(0,N):
		u[n+1] = u[n] - dt*a(dt*n)*u[n] + dt*b(dt*n)
	return t,u
Exemple #17
0
def forward_leaper(I, a, b, T, dt):
    """
	Solves u'(t) = -a(t)*u(t) + b(t), u(0) = I with a forward difference scheme.
	"""

    raise_type(a)
    raise_type(b)

    dt = float(dt)
    N = int(round(T / dt))  # Rounds off to the closest integer
    T = N * dt  # Recalculate the T value based upon the new N value
    u = zeros(N + 1)
    t = linspace(0, T, N + 1)

    for n in range(0, N):
        u[n + 1] = u[n] - dt * a(dt * n) * u[n] + dt * b(dt * n)
    return t, u
def finite_difference(L, Nx, N, dt, C, P_L, P_R):
    x = linspace(0, L, Nx+1)
    dx = x[1] - x[0]
    C = 0.4*C*dt/(dx**2)
    print C	
    Q   = zeros(Nx+1)
    Q_1 = P_R**2*ones(Nx+1)

    for n in range(0, N):
        # Compute u at inner mesh points
        for i in range(1, Nx):
            Q[i] = Q_1[i] + C*(Q_1[i-1]**2.5 - 2*Q_1[i]**2.5 + Q_1[i+1]**2.5)
	# Insert boundary conditions 
	Q[0]=P_L**2; Q[Nx]=P_R**2
    	# Update u_1 before next step
    	Q_1[:]= Q
    
    return sqrt(Q), x
def finite_difference(L, Nx, N, dt, C, P_L, P_R):
    x = linspace(0, L, Nx+1)
    dx = x[1] - x[0]
    C = C*dt/(dx**2)
    print C	
    P   = zeros(Nx+1)
    P_1 = P_R*ones(Nx+1)

    for n in range(0, N):
        # Compute u at inner mesh points
        for i in range(1, Nx):
	    #print P_1
            P[i] = P_1[i] + C*(P_1[i-1]**2 - 2*P_1[i]**2 + P_1[i+1]**2)
	# Insert boundary conditions 
	P[0]=P_L; P[Nx]=P_R
    	# Update u_1 before next step
    	P_1[:]= P
    
    return P, x
Exemple #20
0
def solver(T, dt, v0, Cd, rho, A, m, Source=None):
    """
    This is the main solver function for the program. It takes the problem 
    specific variables as arguments, and returns two meshes containing the 
    velocity and time points respectively.
    """
    a = Cd*rho*A/(2*m) # Set up the constant a for compact code
    v = zeros(int(T/dt) + 1) # Create the velocity mesh
    v[0] = v0; g = 9.81;#Initial velocity and the value of gravity acceleration
    
    # Description of the functions X(t) and Y(t) is given in the PDF file
    def X(t):  
        if(Source == None):
            return -g
        else:
            return -g + Source(t+dt/2.)/m
        
    def Y(t):
        return a
    
    #Calculate the velocity at each meshpoint
    for i in range(1,len(v)):
        v[i] = skydiving_iterate(v[i-1], dt*(i-1), dt, X, Y)
    return v, linspace(0, T, T/dt +1)
Exemple #21
0
"""
Exercise 5.31: Animate a wave packet
Author: Weiyun Lu
"""

from scitools.std import exp, sin, pi, linspace, plot, movie
import time
import glob
import os

f = lambda x, t: exp(-(x - 3 * t)**2) * sin(3 * pi * (x - t))
fps = float(1 / 6)

xp = linspace(-6, 6, 1001)
tp = linspace(-1, 1, 61)
counter = 0

for name in glob.glob('pix/plot_wave*.png'):
    os.remove(name)

for t in tp:
    yp = f(xp, t)
    plot(xp, yp, '-b', axis=[xp[0], xp[-1], -1.5, 1.5], legend='t=%4.2f' % t,\
        title='Evolution of wave over time', savefig='pix/plot_wave%04d.png' \
        % counter)
    counter += 1
    time.sleep(fps)

#movie('pix/plot_wave*.png')
def solver(I, V_, f_, c, Lx, Ly, Nx, Ny, dt, T, b,
           user_action=None, version='scalar', skip_every_n_frame=10, show_cpu_time=False,display_warnings=True, plotting=False):

    order = 'C' # Store arrays in a column-major order (in memory)

    x = linspace(0, Lx, Nx+1)  # mesh points in x dir
    y = linspace(0, Ly, Ny+1)  # mesh points in y dir
    dx = x[1] - x[0]
    dy = y[1] - y[0]

    xv = x[:,newaxis]          # for vectorized function evaluations
    yv = y[newaxis,:]

    # Assuming c is a function:
    c_ = zeros((Nx+1,Ny+1), order='c')
    for i,xx in enumerate(x):
        for j,yy in enumerate(y):
            c_[i,j] = c(xx,yy)  # Loop through x and y with indices i,j at the same time
    c_max = c_.max()            # Pick out the largest value from c(x,y)
    q = c_**2

    stability_limit = (1/float(c_max))*(1/sqrt(1/dx**2 + 1/dy**2))
    if dt <= 0:                # shortcut for max time step is to use i.e. dt = -1
        safety_factor = -dt    # use negative dt as safety factor
        extra_factor  = 1      # Easy way to make dt even smaller
        dt = safety_factor*stability_limit*extra_factor
    elif dt > stability_limit and display_warnings:
        print '\nWarning: (Unless you are testing the program), be aware that'
        print 'dt: %g is currently exceeding the stability limit: %g\n' %(dt, stability_limit)
    Nt = int(round(T/float(dt)))
    t  = linspace(0, Nt*dt, Nt+1)              # mesh points in time
    dt2 = dt**2

    # Constants for simple calculation
    A = (1 + b*dt/2)**(-1)
    B = (b*dt/2 - 1)
    dtdx2 = dt**2/(2*dx**2)
    dtdy2 = dt**2/(2*dy**2)

    # Make f(x,y,t) and V(x,y) ready for computation with different schemes
    if f_ is None or f_ == 0:
        f = (lambda x, y, t: 0) if version == 'scalar' else \
            lambda x, y, t: zeros((xv.shape[0], yv.shape[1]))
    else:
        if version == 'scalar':
            f = f_
    if V_ is None or V_ == 0:
        V = (lambda x, y: 0) if version == 'scalar' else \
            lambda x, y: zeros((xv.shape[0], yv.shape[1]))
    else:
        if version == 'scalar':
            V = V_

    if version == 'vectorized': # Generate and fill matrices for first timestep
        f = zeros((Nx+1,Ny+1), order=order)
        V = zeros((Nx+1,Ny+1), order=order)
        f[:,:] = f_(xv,yv,0)
        V[:,:] = V_(xv,yv)

    u   = zeros((Nx+1,Ny+1), order=order)   # solution array
    u_1 = zeros((Nx+1,Ny+1), order=order)   # solution at t-dt
    u_2 = zeros((Nx+1,Ny+1), order=order)   # solution at t-2*dt

    Ix = range(0, u.shape[0])               # Index set notation
    Iy = range(0, u.shape[1])
    It = range(0, t.shape[0])

    import time; t0 = time.clock()          # for measuring CPU time

    # Load initial condition into u_1
    if version == 'scalar':
        for i in Ix:
            for j in Iy:
                u_1[i,j] = I(x[i], y[j])
    else: # use vectorized version
        u_1[:,:] = I(xv, yv)

    if user_action is not None:
        if plotting:
            user_action(u_1, x, xv, y, yv, t, 0, skip_every_n_frame)
        else:
            user_action(u_1, x, xv, y, yv, t, 0)

    # Special formula for first time step
    n = 0
    # First step requires a special formula, use either the scalar
    # or vectorized version (the impact of more efficient loops than
    # in advance_vectorized is small as this is only one step)
    if version == 'scalar':
        u,cpu_time = advance_scalar(u, u_1, u_2, q, f, x, y, t, n, A, B,
                            dt2, dtdx2,dtdy2, V, step1=True)
    else:
        u,cpu_time = advance_vectorized(u, u_1, u_2, q, f, t, n, A, B,
                            dt2, dtdx2,dtdy2, V, step1=True)

    if user_action is not None:
        if plotting:
            user_action(u, x, xv, y, yv, t, 1, skip_every_n_frame)
        else:
            user_action(u_1, x, xv, y, yv, t, 1)

    # Update data structures for next step
    u_2, u_1, u = u_1, u, u_2

    # Time loop for all later steps
    for n in It[1:-1]:
        if version == 'scalar':
            # use f(x,y,t) function
            u,cpu_time = advance_scalar(u, u_1, u_2, q, f, x, y, t, n, A, B, dt2, dtdx2,dtdy2)
            if show_cpu_time:
                percent = (float(n)/It[-2])*100.0
                sys.stdout.write("\rLast step took: %.3f sec with [scalar-code]. Computation is %d%% " %(cpu_time,percent))
                sys.stdout.flush()
        else: # Use vectorized code
            f[:,:] = f_(xv, yv, t[n])  # must precompute the matrix f
            u,cpu_time = advance_vectorized(u, u_1, u_2, q, f, t, n, A, B,
                                dt2, dtdx2,dtdy2)
            if show_cpu_time:
                percent = (float(n)/It[-2])*100.0
                sys.stdout.write("\rLast step took: %.5f sec with [vec-code]. Computation is %d%% " %(cpu_time,percent))
                sys.stdout.flush()

        if user_action is not None:
            if plotting:
                if user_action(u, x, xv, y, yv, t, n+1, skip_every_n_frame):
                    break
            else:
                if user_action(u, x, xv, y, yv, t, n+1):
                    break

        # Update data structures for next step
        #u_2[:] = u_1;  u_1[:] = u  # safe, but slower
        u_2, u_1, u = u_1, u, u_2

    # Important to set u = u_1 if u is to be returned!
    t1 = time.clock()
    # dt might be computed in this function so return the value
    return dt, t1 - t0
Exemple #23
0
    def graph(self, resolution=1001):
        '''
		graphs the Lagrange polynomial over self.points	
		'''
        #from scitools.std import *
        from scitools.std import zeros, linspace, plot, array
        points = self.points
        xlist = linspace(points[0, 0], points[-1, 0], resolution)
        ylist = self.__call__(xlist)
        plot(xlist, ylist)


if __name__ == '__main__':
    from scitools.std import *
    x = linspace(0, pi, 5)
    y = sin(x)
    points = array(zip(x, y))
    l = Lagrange(points)
    l.verify()

    figure()
    hold('on')
    axis([-.1, pi + .1, -.1, 1.1])
    for i in [5, 10, 20, 55, 70, 100]:
        x = linspace(0, pi, i)
        y = sin(x)
        points = array(zip(x, y))
        l = Lagrange(points)
        l.graph()
        xlabel('x')
Exemple #24
0
 def visualize(self, r_start, r_stop, n=100):
     from scitools.std import plot, linspace
     r = linspace(r_start, r_stop, n)
     g = self.force(r)
     title = 'Gravity force: m=%g, M=%g' % (self.m, self.M)
     plot(r, g, title=title)
Exemple #25
0
 def table(self, n, l, r):
     from scitools.std import linspace, array
     x = linspace(l, r, n)
     print '%10s %10s' % ('x', 'f(x)')
     for i in x:
         print '%10f %10f' % (i, value(i))
def graph(f, n, xmin, xmax, resolution=1001):
    Xp = linspace(xmin, xmax, n)
    Yp = f(Xp)
    Xr = linspace(xmin, xmax, resolution)  #array of values to plot
    Yr = array([p_L(x, Xp, Yp) for x in Xr])  #get interpolation points
    plot(Xr, Yr, '-r', Xp, Yp, 'bo', title='Lagrange Interpolation')
Exemple #27
0
    s = 0  #initialize sum
    n = len(xp) - 1
    for k in range(n + 1):
        s += yp[k] * L_k(x, k, xp, yp)
    return s


def test_p_L(xp, yp):
    n = len(xp) - 1
    eps = 10e-12
    count = 0  #count how many answers are not close enough
    for k in range(n + 1):
        if abs(p_L(xp[k], xp, yp) - yp[k]) > eps:
            count += 1
    if count == 0:
        print 'Success!  The Lagrange interpolation polynomial indeed passes',\
        'through all the points (xp,yp).'
    else:
        print 'Oh no!  There were %d points where the interpolation polynomial'\
        %(count), 'fails to pass through (xp,yp).'


if __name__ == '__main__':
    Xp = linspace(0, pi, 5)
    Yp = sin(Xp)
    test_p_L(Xp, Yp)
    x = Xp[2] - Xp[1] / 2.0
    y = sin(x)
    y_inter = p_L(x, Xp, Yp)
    print 'Take the point between Xp[1] and Xp[2].  Evaluating the sin function',\
    'directly yields %.6f, whilst the interpolated value is %.6f.' %(y, y_inter)
from scitools.std import plot, linspace, vectorize


def v_all(x, mu=1E-6, exp=math.exp):
    x = np.float128(x)
    mu = np.float128(mu)
    num = (1 - exp(float(x) / mu))
    denom = (1 - exp(1.0 / mu))
    return num, denom, num / denom


def v(x, mu=1E-6, exp=math.exp):
    return v_all(x, mu, exp)[2]


for x in linspace(0, 1, 25):
    for f in [math.exp, np.exp]:
        try:
            print v_all(x, 1E-3, f)
        except:
            print('Could not compute an instance of v(x).')

#This function is subject to overflow.
#Many more instances succeed with float128 than default float64.

x = linspace(0, 1, 10000)
v = vectorize(v)

plot(x,
     v(x, 1.0, np.exp),
     '-r',
"""
Exercise 5.7: Demonstrate array slicing
Author: Weiyun Lu
"""

from scitools.std import linspace

w = linspace(0, 3, 31)
print w

print w[:]  #should just be the whole thing
print w[:-2]  #up to but not including 2nd last, so should be up to 2.8
print w[::5]  #every fifth element starting with 0
print w[2:-2:6]  #start with 0.2 and up to 2.8; every 6th element
Exemple #30
0
if __name__ == '__main__':

	c = Calculator(10, 5)
	#d = Calculator(10, 5)
	#print c + d
	print 'Adding: ', c.add()
	print 'Subtracting: ', c.subtract()
	print 'Multiplying: ', c.multiply()
	print 'Divifing: ', c.divide()
	print 'Changeing variables...'
	c.change_variables(6, 3)
	print 'Now adding: ', c.add()
	print 'Now trying functions...'
	print 'f(x) = x^2, x = 2: ', c.function('x**2', 2)
	print 'Trying with array...'
	c.change_variables(linspace(-5, -3, 3), linspace(-1, 1, 3))
	print 'Adding linspace(-5, -3, 5), linspace(-1, 1, 5):'
	print c.add()
	print 'f(x) = x^2, x = linspace(-1, 1, 11): '
	print  c.function('x**2', linspace(-1, 1, 21))
	x = linspace(-5, 5)
	plot(x, c.function('x**2+x**4-3', x))
	raw_input()

'''
Bergem$ python Calculator.py
Adding:  15
Subtracting:  5
Multiplying:  50
Divifing:  2.0
Changeing variables...
Exemple #31
0
omega1 = 2 * pi / P1
a1 = sqrt(omega1 / (2 * k))

A2 = 7  # amplitude of yearly temperature variations (in C)
P2 = 24 * 60 * 60 * 365.  # oscillation period of 1 yr (in seconds)
# angular frequency of yearly temperature variations (in rad/s)
omega2 = 2 * pi / P2
a2 = sqrt(omega2 / (2 * k))

dt = P2 / 30  # time lag: 0.1 yr
tmax = 3 * P2  # 3 year simulation
T0 = 10  # mean surface temperature in Celsius
D = -(1 / a1) * log(0.001)  # max depth
n = 501  # no of points in the z direction

z = linspace(0, D, n)


def z_scaled(x, s):
    a = x[0]
    b = x[-1]
    return a + (b - a) * ((x - a) / (b - a))**s


zs = z_scaled(z, 3)

animate(tmax, dt, zs, T, T0 - A2 - A1, T0 + A2 + A1, 0, 'z', 'T')

movie('tmp_*.png', encoder='convert', fps=6)
import glob
import os
Exemple #32
0
# from __future__ import unicode_literals
# import matplotlib
# matplotlib.rcParams['text.usetex'] = True
# matplotlib.rcParams['text.latex.unicode'] = True


from matplotlib import rc
import matplotlib.pyplot as plt
from scitools.std import sqrt, pi, exp, linspace
import os




def f(x, m, s):
    return (1.0/(sqrt(2*pi)*s))*exp(-0.5*((x-m)/s)**2)

m=0
s_min = 0.2
s_max = 2
x = linspace(m -3*s_max, m + 3*s_max, 100)
s_values = linspace(s_max, s_min, 5)
# f is max for x=m; smaller s gives larger max value
max_f = f(m, m, s_min)

os.system("rm ./tmp*.png")
#plt.figure(1, figsize=(6, 4))
#
#
plt.ion()
Exemple #33
0
k = 1E-6            # thermal diffusivity (in m**2/s)

A1 = 15             # amplitude of the daily temperature variations (in C)
P1 = 24 * 60 * 60.      # oscillation period of 24 h (in seconds)
omega1 = 2 * pi / P1   # angular freq of daily temp variations (in rad/s)
a1 = sqrt(omega1 / (2 * k))

A2 = 7                    # amplitude of yearly temperature variations (in C)
P2 = 24 * 60 * 60 * 365.  # oscillation period of 1 yr (in seconds)
omega2 = 2 * pi / P2      # angular freq of yearly temp variations (in rad/s)
a2 = sqrt(omega2 / (2 * k))

dt = P2 / 20            # time lag: 0.1 yr
tmax = 3 * P2               # 3 year simulation
T0 = 10                 # mean surface temperature in Celsius
D = -(1 / a1) * log(0.001)  # max depth
n = 501                 # no of points in the z direction

# set T0, A, k, omega, D, n, tmax, dt
z = linspace(0, D, n)
animate(tmax, dt, z, T, T0 - A2 - A1, T0 + A2 + A1, 0, 'z', 'T')

movie('tmp_*.png', encoder='convert', fps=6, outputfile='tmp_heatwave.gif')

import glob
import os
# Remove frames
for filename in glob.glob('tmp_*.png'):
    os.remove(filename)
    return s


def test_p_L(xp, yp):
    n = len(xp) - 1
    eps = 10e-12
    count = 0  #count how many answers are not close enough
    for k in range(n + 1):
        if abs(p_L(xp[k], xp, yp) - yp[k]) > eps:
            count += 1
    if count == 0:
        print 'Success!  The Lagrange interpolation polynomial indeed passes',\
        'through all the points (xp,yp).'
    else:
        print 'Oh no!  There were %d points where the interpolation polynomial'\
        %(count), 'fails to pass through (xp,yp).'


def graph(f, n, xmin, xmax, resolution=1001):
    Xp = linspace(xmin, xmax, n)
    Yp = f(Xp)
    Xr = linspace(xmin, xmax, resolution)  #array of values to plot
    Yr = array([p_L(x, Xp, Yp) for x in Xr])  #get interpolation points
    plot(Xr, Yr, '-r', Xp, Yp, 'bo', title='Lagrange Interpolation')


if __name__ == '__main__':
    XP = linspace(0, pi, 5)
    YP = sin(XP)
    test_p_L(XP, YP)
    graph(sin, 5, 0, pi)
Exemple #35
0
plt.figure()
plt.plot(t,nsy,'r-')
plt.title('Diffusion  D = %.1f ' % D)
plt.xlabel('time [MD]')
#plt.xlabel('time [fs]')
plt.ylabel('msq/t [MD]')
#plt.ylabel('msq/t [m^2/t]')
plt.legend(('Diffusion constant'), loc='lower right')


#######################################3
print timeiterations
l_binz = len(binz)
print l_binz

radius = linspace(0,(l_binz+1)*0.1,l_binz)

#plt.figure()
#plt.plot(radius,binz)


volumeR = zeros(l_binz)

for i in range(l_binz-1):
    volumeR[i] = (4./3)*pi*(radius[i+1]**3 - radius[i]**3) # volume of shell in range [r,r+dr]

binz[1:] = binz[1:]/(timeiterations*N*rho*volumeR[i]) # mean number of particles in volume

plt.figure()
plt.plot(radius,binz,'r-*')
plt.title('Average number of particles in distance r from atom')
"""
Exercise 5.41: Plot functions from the command line
Author: Weiyun Lu
"""

import sys
from scitools.std import StringFunction, plot, linspace
from numpy import *

try:
    f = StringFunction(sys.argv[1])
    f = vectorize(f)
    min = eval(sys.argv[2])
    max = eval(sys.argv[3])
except IndexError:
    print('You must supply a function, a minimum value, and a maximum value!')
    sys.exit(1)
except ValueError or TypeError:
    print('You must supply a function (as a string), and valid min and max',
          'numerical values!')
    sys.exit(1)

if sys.argv[4] != None:
    n = eval(sys.argv[4])
else:
    n = 501

x = linspace(min, max, n)
plot(x, f(x), xlabel='x', ylabel='f(x)', title='f(x)=%s' % sys.argv[1])
"""
Exercise 5.28: Plot the viscosity of water
Author: Weiyun Lu
"""

from scitools.std import plot, linspace

A = 2.414e-5
B = 247.8
C = 140.0
mu = lambda T: A * 10**(B / (T - C))  #viscosity in terms of Kelvin
mu_celcius = lambda T: mu(T + 273)  #calculate mu in terms of celcius

x = linspace(0, 100, 100)
y = mu_celcius(x)

plot(x, y, '-b', xlabel='Temperature (C)', ylabel='Viscosity (Pa s)', \
    title='Viscocity of Water')
Exemple #38
0
	def table(self, n, l, r):
		from scitools.std import linspace, array
		x = linspace(l, r, n)
		print '%10s %10s' % ('x', 'f(x)')
		for i in x:
			print '%10f %10f' % (i, value(i))
Exemple #39
0
"""
Exercise 5.26: Plot a wave packet
Author: Weiyun Lu
"""

from scitools.std import exp, sin, pi, linspace, plot

f = lambda x, t : exp(-(x-3*t)**2) * sin(3*pi*(x-t))

xp = linspace(-4,4,100)
yp = f(xp, 0)

plot(xp, yp , '-b', title='A wave localized in space')
	def graph(self, resolution=1001):
		'''
		graphs the Lagrange polynomial over self.points	
		'''
		#from scitools.std import *
		from scitools.std import zeros, linspace, plot, array
		points = self.points
		xlist = linspace(points[0,0], points[-1,0], resolution)
		ylist = self.__call__(xlist)
		plot(xlist, ylist)

	

if __name__ == '__main__':
	from scitools.std import *
	x = linspace(0, pi, 5)
	y = sin(x)
	points = array(zip(x,y))
	l = Lagrange(points)
	l.verify()
	
	figure()
	hold('on')
	axis([-.1, pi+.1, -.1, 1.1])
	for i in [5,10,20,55,70, 100]:
		x = linspace(0, pi, i)
		y = sin(x)
		points = array(zip(x,y))
		l = Lagrange(points)	
		l.graph()
		xlabel('x')
Exemple #41
0
# plt.plot(x, B1energyVec)
# plt.xlabel('$x_1$')
# plt.ylabel('$u_3$')
# plt.title('Deflection of a cantilever beam under self weight')
# plt.show()


def f(x,m,s):
    return (1.0/(sqrt(2*pi)*s))*exp(-0.5*((x-m)/s)**2)



m=0
s_min=0.2
s_max=2
x=linspace(m-3*s_max, m+3*s_max,10)
s_values =linspace(s_max, s_min, 3)
max_f=f(m,m,s_min)


#
plt.ion()
y=f(x,m, s_max)
print len(x), "\n", len(y)
print x, \
    "\n", \
      y
plt.plot(x,y)
plt.axis([x[0], x[-1], -0.1, max_f])
# plt.xlabel('x')
# plt.ylabel('f')
Exemple #42
0
from scitools.std import sqrt, pi, exp, linspace, plot, movie
import time, glob, os, sys

# Clean up old frames
for name in glob.glob('tmp_*.pdf'):
    os.remove(name)

def f(x, m, s):
    return (1.0/(sqrt(2*pi)*s))*exp(-0.5*((x-m)/s)**2)

m = 0
s_max = 2
s_min = 0.2
x = linspace(m -3*s_max, m + 3*s_max, 1000)
s_values = linspace(s_max, s_min, 30)
# f is max for x=m; smaller s gives larger max value
max_f = f(m, m, s_min)

# Show the movie, and make hardcopies of frames simulatenously
counter = 0
for s in s_values:
    y = f(x, m, s)
    plot(x, y, '-', axis=[x[0], x[-1], -0.1, max_f],
         xlabel='x', ylabel='f', legend='s=%4.2f' % s,
         savefig='tmp_%04d.png' % counter)
    counter += 1
    #time.sleep(0.2)  # can insert a pause to control movie speed

if '--no-moviefile' in sys.argv:
    # Drop making movie files
    import sys; sys.exit(0)
Exemple #43
0
"""
Exercise 5.12: Plot exact and inexact Fahrenheit-Celcius conversion formulas
Author: Weiyun Lu
"""

from scitools.std import linspace, plot

F = linspace(-20,120,20)
C_approx = (F-30) / 2.0
C_actual = (F-32) * 5.0/9

plot(F, C_approx, '-r', F, C_actual, '-b', legend=('approx C', 'actual C'),\
        xlabel='Fahrenheit', ylabel='Celcius')
Exemple #44
0
plt.figure()
plt.plot(t, nsy, 'r-')
plt.title('Diffusion  D = %.1f ' % D)
plt.xlabel('time [MD]')
#plt.xlabel('time [fs]')
plt.ylabel('msq/t [MD]')
#plt.ylabel('msq/t [m^2/t]')
plt.legend(('Diffusion constant'), loc='lower right')

#######################################3
print timeiterations
l_binz = len(binz)
print l_binz

radius = linspace(0, (l_binz + 1) * 0.1, l_binz)

#plt.figure()
#plt.plot(radius,binz)

volumeR = zeros(l_binz)

for i in range(l_binz - 1):
    volumeR[i] = (4. / 3) * pi * (radius[i + 1]**3 - radius[i]**3
                                  )  # volume of shell in range [r,r+dr]

binz[1:] = binz[1:] / (timeiterations * N * rho * volumeR[i]
                       )  # mean number of particles in volume

plt.figure()
plt.plot(radius, binz, 'r-*')
Exemple #45
0
"""
Exercise 5.3: Fill arrays; vectorized (plot)
Author: Weiyun Lu
"""

from scitools.std import sqrt, pi, exp, linspace, plot

h = lambda x : (1/(sqrt(2*pi))) * exp(-0.5*x**2)
xlist = linspace(-4,4,41)
hlist = h(xlist)
pairs = zip(xlist,hlist)

plot(xlist, hlist, axis=[xlist[0], xlist[-1], 0, 0.5], xlabel='x', \
    ylabel='h(x)', title='Standard Gaussian')
Exemple #46
0
 def visualize(self, r_start, r_stop, n=100):
     from scitools.std import plot, linspace
     r = linspace(r_start, r_stop, n)
     g = self.force(r)
     title='Gravity force: m=%g, M=%g' % (self.m, self.M)
     plot(r, g, title=title)
 def differentiate(self):
     """Differentiate this polynomial in-place."""
     from scitools.std import linspace
     n = len(self.coeff)
     self.coeff[:-1] = linspace(1, n-1, n-1)*self.coeff[1:]
     self.coeff = self.coeff[:-1]