Esempio n. 1
0
def gaussian(C=1, Nx=50, animate=True, T=2, loc=0):
    """Gaussian bell as initial condition."""
    L = 1.
    c = 1

    def I(x):
        return exp(-0.5 * ((x - loc) / 0.05)**2)

    bc_left = 'dudx=0' if loc == 0 else 'open'
    dt = (L / Nx) / c  # choose the stability limit with given Nx
    cpu = viz(I,
              None,
              None,
              c,
              L,
              dt,
              C,
              T,
              umin=-0.2,
              umax=1,
              animate=animate,
              bc_left=bc_left)


if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([plug, gaussian], sys.argv)
    eval(cmd)
Esempio n. 2
0
	#print sp.latex(b, mode='plain')
	if symbolic:
		c = A.LUsolve(b)
	else:
		c = np.linalg.solve(A, b)
	print 'c:\n', c
	print 'Plain interpolation/collocation:'
	x = sp.Symbol('x')
	f = sp.lambdify([x], f, modules='numpy')
	try:
		f_at_nodes = [f(xc) for xc in nodes]
	except NameError as e:
		raise NameError('numpy does not support special function:\n%s' % e)
	print f_at_nodes
	if not symbolic and filename is not None:
		xf = np.linspace(Omega[0], Omega[1], 10001)
		U = np.asarray(c)
		xu, u = u_glob(U, elements, nodes)
		plt.plot(xu, u, '-',
		xf, f(xf), '--')
		plt.legend(['u', 'f'])
		plt.savefig(filename + '.pdf')
		plt.savefig(filename + '.png')


if __name__ == '__main__':
	import sys
	from scitools.misc import function_UI
	cmd = function_UI([phi_r, u_glob, element_matrix, element_vector, exemplify_element_matrix_vector, assemble, approximate], sys.argv)
	x = sp.Symbol('x') # needed in eval when expression f contains x
	eval(cmd)
Esempio n. 3
0
            return 0
        else:
            return 1

    cpu = viz(I, None, None, c, L, Nx, C, T,
              umin=-1.1, umax=1.1, animate=animate)


def test_plug():
    """Check that an initial plug is correct back after one period."""
    L = 1
    I = lambda x: 0 if abs(x-L/2.0) > 0.1 else 1

    u_s, x, t, cpu = solver(
        I=I, V=None, f=None, c=0.5, L=L,
        Nx=50, C=1, T=4, user_action=None)
    u_v, x, t, cpu = solver(
        I=I, V=None, f=None, c=0.5, L=L,
        Nx=50, C=1, T=4, user_action=None)
    diff = abs(u_s - u_v).max()
    nt.assert_almost_equal(diff, 0, places=13)
    u_0 = array([I(x_) for x_ in x])
    diff = abs(u_s - u_0).max()
    nt.assert_almost_equal(diff, 0, places=13)

if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([test_plug, plug], sys.argv)
    eval(cmd)
Esempio n. 4
0
            return cos(pi*(x-xc)/a) \
                   if xc - 0.5*a <= x <= xc + 0.5*a else 0
    else:
        raise ValueError('Wrong pulse_tp="%s"' % pulse_tp)

    def c(x):
        return c_0/slowness_factor \
               if medium[0] <= x <= medium[1] else c_0

    umin=-0.5; umax=1.5*I(xc)
    casename = '%s_Nx%s_sf%s' % \
               (pulse_tp, Nx, slowness_factor)
    action = PlotMediumAndSolution(
        medium, casename=casename, umin=umin, umax=umax,
        every_frame=every_frame, screen_movie=animate)

    solver(I=I, V=None, f=None, c=c, U_0=None, U_L=None,
           L=L, Nx=Nx, C=C, T=T,
           user_action=action, version=version,
           dt_safety_factor=1)



if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([test_quadratic, test_plug, pulse,
                       moving_end,], sys.argv)
    eval(cmd)
    raw_input()
def test_mms():
    domain = UnitDomain([10])
    alpha = lambda u: 1.0 + pow(u, 2.0)
    #f = Constant(0.0)
    I = Expression("cos(pi*x[0])")
    p = 1
    rho = 1.0
    dt = 0.05
    T = 0.5
    f = Expression(
        "-rho*pow(x[0],3)/3 + rho*pow(x[0],2)/2 + 8*pow(t,3)*pow(x[0],7)/9 - 28*pow(t,3)*pow(x[0],6)/9+7*pow(t,3)*pow(x[0],5)/2 - 5*pow(t,3)*pow(x[0],4)/4 + 2*t*x[0] - t",
        t=0.0,
        rho=rho)

    def u_e(x, t):
        return (x**2.0) * (0.5 - x / 3.0) * t

    def action(t, u):
        for x in range(10):
            assert_almost_equal(u_e(x, t), u.vector().array()[x])

    solver(dt, T, domain, p, rho, alpha, f, I, action)


if __name__ == "__main__":
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([solver, test_convergance_rate, test_mms], sys.argv)
    eval(cmd)
Esempio n. 6
0
		elif plot_method == 3:
			print 'Experimental 3D matplotlib...under development...'
			#plt.clf()
			ax = fig.add_subplot(111, projection='3d')
			u_surf = ax.plot_surface(xv, yv, u, alpha=0.3)
			#ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm)
			#ax.set_zlim(-1, 1)
			# Remove old surface before drawing
			if u_surf is not None:
				ax.collections.remove(u_surf)
			plt.draw()
			time.sleep(1)
		if plot_method > 0:
			time.sleep(0) # pause between frames
			if save_plot:
				filename = 'tmp_%04d.png' % n
				savefig(filename)  # time consuming!

	Nx = 20; Ny = 20; T = 30
	dt, cpu = solver(I, None, None, b, q, Lx, Ly, Nx, Ny, -1, T,
		             user_action=plot_u, version=version)


if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([run_efficiency_tests,
                       run_Gaussian, 
                       run_physical_problem, ], sys.argv)
    eval(cmd)
Esempio n. 7
0
            time.sleep(0)  # pause between frames
            filename = 'tmp_%04d.png' % n
            #savefig(filename)  # time consuming - dropped

    Nx = 40
    Ny = 40
    T = 20
    dt = solver(I,
                None,
                None,
                c,
                Lx,
                Ly,
                Nx,
                Ny,
                0,
                T,
                user_action=plot_u,
                version=version)


if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([
        test_quadratic,
        run_efficiency_tests,
        run_Gaussian,
    ], sys.argv)
    eval(cmd)
Esempio n. 8
0
    E2 = []
    h = []
    for _N in N:
        psi, points = Lagrange_polynomials_01(x, _N)
        u = interpolation(f, psi, points)
        un = sm.lambdify([x], u, modules='numpy')
        ucoor = un(xcoor)
        e = fcoor - ucoor
        Einf.append(e.max())
        E2.append(np.sqrt(np.sum(e*e/e.size)))
        h.append(1./_N)
    print Einf
    print E2
    print h
    print N
    # Assumption: error = CN**(-N)
    print 'convergence rates:'
    for i in range(len(E2)):
        C1 = E2[i]/(N[i]**(-N[i]/2))
        C2 = Einf[i]/(N[i]**(-N[i]/2))
        print N[i], C1, C2
    # Does not work properly...


if __name__ == '__main__':
    functions = \
        [eval(fname) for fname in dir() if fname.startswith('run_')]
    from scitools.misc import function_UI
    cmd = function_UI(functions, sys.argv)
    eval(cmd)
Esempio n. 9
0
    """Plug profile as initial condition."""
    L = 1.
    c = 1

    I = lambda x: 1 if abs(x-loc) < 0.1 else 0

    bc_left = 'dudx=0' if loc == 0 else 'open'
    dt = (L/Nx)/c  # choose the stability limit with given Nx
    cpu = viz(I, None, None, c, L, dt, C, T,
              umin=-0.3, umax=1.1, animate=animate,
              bc_left=bc_left)

def gaussian(C=1, Nx=50, animate=True, T=2, loc=0):
    """Gaussian bell as initial condition."""
    L = 1.
    c = 1

    def I(x):
        return exp(-0.5*((x-loc)/0.05)**2)

    bc_left = 'dudx=0' if loc == 0 else 'open'
    dt = (L/Nx)/c  # choose the stability limit with given Nx
    cpu = viz(I, None, None, c, L, dt, C, T,
              umin=-0.2, umax=1, animate=animate, bc_left=bc_left)

if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([plug, gaussian], sys.argv)
    eval(cmd)
Esempio n. 10
0
    else:
        raise ValueError('Wrong pulse_tp="%s"' % pulse_tp)

    def c(x):
        return c_0/slowness_factor \
               if medium[0] <= x <= medium[1] else c_0

    umin=-0.5; umax=1.5*I(xc)
    casename = '%s_Nx%s_sf%s' % \
               (pulse_tp, Nx, slowness_factor)
    action = PlotMediumAndSolution(
        medium, casename=casename, umin=umin, umax=umax,
        every_frame=every_frame, screen_movie=animate)

    solver(I=I, V=None, f=None, c=c, U_0=None, U_L=None,
           L=L, Nx=Nx, C=C, T=T,
           user_action=action, version=version,
           dt_safety_factor=1)



if __name__ == '__main__':
    import sys
    # Enable running the various functions from the command line
    from scitools.misc import function_UI
    cmd = function_UI([test_quadratic, test_plug, pulse,
                       demo_BC_plug, demo_BC_gaussian, moving_end,],
                      sys.argv)
    eval(cmd)
    raw_input()
Esempio n. 11
0
        """Gaussian peak at (Lx/2, Ly/2)."""
        return exp(-0.5*(x-Lx/2.0)**2 - 0.5*(y-Ly/2.0)**2)

    def plot_u(u, x, xv, y, yv, t, n):
        if t[n] == 0:
            time.sleep(2)
        if plot_method == 1:
            mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                 caxis=[-1,1])
        elif plot_method == 2:
            surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                  colorbar=True, colormap=hot(), caxis=[-1,1],
                  shading='flat')
        if plot_method > 0:
            time.sleep(0) # pause between frames
            filename = 'tmp_%04d.png' % n
            #savefig(filename)  # time consuming - dropped

    Nx = 40; Ny = 40; T = 20
    dt = solver(I, None, None, c, Lx, Ly, Nx, Ny, 0, T,
                user_action=plot_u, version=version)



if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([test_quadratic, run_efficiency_tests,
                       run_Gaussian, ], sys.argv)
    eval(cmd)
Esempio n. 12
0
    u_s, x, t, cpu = solver(I=I,
                            V=None,
                            f=None,
                            c=0.5,
                            L=L,
                            Nx=50,
                            C=1,
                            T=4,
                            user_action=None)
    u_v, x, t, cpu = solver(I=I,
                            V=None,
                            f=None,
                            c=0.5,
                            L=L,
                            Nx=50,
                            C=1,
                            T=4,
                            user_action=None)
    diff = abs(u_s - u_v).max()
    nt.assert_almost_equal(diff, 0, places=13)
    u_0 = array([I(x_) for x_ in x])
    diff = abs(u_s - u_0).max()
    nt.assert_almost_equal(diff, 0, places=13)


if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([test_plug, plug], sys.argv)
    eval(cmd)
Esempio n. 13
0
    Nx = 80
    cpu = viz(I, None, None, c, U_0, U_L, L, Nx, C, T,
              umin=-1.1, umax=1.1, version='scalar', animate=True)

    # Convergence study
    def action(u, x, t, n):
        e = abs(u - exact(x, t[n])).max()
        errors_in_time.append(e)

    E = []
    dt = []
    Nx_values = [10, 20, 40, 80, 160]
    for Nx in Nx_values:
        errors_in_time = []
        solver(I, None, None, c, U_0, U_L, L, Nx, C, T,
               user_action=action, version='scalar')
        E.append(max(errors_in_time))
        _dx = L/Nx
        _dt = C*_dx/c
        dt.append(_dt)
        print dt[-1], E[-1]
    return dt, E

if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([test_quadratic, test_plug, plug,
                       gaussian, sincos, guitar,
                       moving_end,], sys.argv)
    eval(cmd)
Esempio n. 14
0

def sines(x, y, Nx, Ny):
    return [sym.sin(sym.pi*(i+1)*x)*sym.sin(sym.pi*(j+1)*y)
            for i in range(Nx+1) for j in range(Ny+1)]

def taylor(x, y, Nx, Ny):
    return [x**i*y**j for i in range(Nx+1) for j in range(Ny+1)]


# ----------------------------------------------------------------------

def run_linear():
    f = (1+x**2)*(1+2*y**2)
    psi = taylor(x, y, 1, 1)
    print psi
    Omega = [[0, 2], [0, 2]]
    u = least_squares(f, psi, Omega)
    comparison_plot(f, u, Omega, plotfile='approx2D_bilinear')
    print '\n\n**** Include second order terms:'
    psi = taylor(x, y, 2, 2)
    u = least_squares(f, psi, Omega)


if __name__ == '__main__':
    functions = \
        [eval(fname) for fname in dir() if fname.startswith('run_')]
    from scitools.misc import function_UI
    cmd = function_UI(functions, sys.argv)
    eval(cmd)
	E = sqrt(sum(e**2)/u.vector().array().size)
	assert_almost_equal(E, pow(dt,p))
	
def test_mms():
	domain = UnitDomain([10])
	alpha = lambda u: 1.0 + pow(u,2.0)
	#f = Constant(0.0)
	I = Expression("cos(pi*x[0])")
	p = 1
	rho = 1.0
	dt = 0.05
	T = 0.5
	f = Expression("-rho*pow(x[0],3)/3 + rho*pow(x[0],2)/2 + 8*pow(t,3)*pow(x[0],7)/9 - 28*pow(t,3)*pow(x[0],6)/9+7*pow(t,3)*pow(x[0],5)/2 - 5*pow(t,3)*pow(x[0],4)/4 + 2*t*x[0] - t",t=0.0,rho=rho)
	
	def u_e(x,t):
		return (x**2.0)*(0.5 - x/3.0)*t
	
	def action(t, u):
		for x in range(10):
			assert_almost_equal(u_e(x,t),u.vector().array()[x])
	
	solver(dt, T, domain, p, rho, alpha, f, I, action)	

if __name__ == "__main__":
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([solver,
                       test_convergance_rate, 
                       test_mms], sys.argv)
    eval(cmd)
Esempio n. 16
0
    if isinstance(X, np.ndarray):
        z = np.zeros(len(X))
    if d == 0:
        return 0 + z
    elif d == 1:
        if r == 0:
            return -0.5 + z
        elif r == 1:
            return 0.5 + z
    elif d == 2:
        if r == 0:
            return X - 0.5
        elif r == 1:
            return -2*X
        elif r == 2:
            return X + 0.5
    else:
        print 'dphi_r only supports d=0,1,2, not %d' % d
        return None


if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI(
        [phi_r, u_glob, element_matrix, element_vector,
         exemplify_element_matrix_vector, assemble, approximate],
        sys.argv)
    x = sym.Symbol('x')  # needed in eval when expression f contains x
    eval(cmd)
Esempio n. 17
0
    solver(I=I,
           V=None,
           f=None,
           c=c,
           U_0=None,
           U_L=None,
           L=L,
           Nx=Nx,
           C=C,
           T=T,
           user_action=action,
           version=version,
           dt_safety_factor=1)


if __name__ == '__main__':
    import sys
    # Enable running the various functions from the command line
    from scitools.misc import function_UI
    cmd = function_UI([
        test_quadratic,
        test_plug,
        pulse,
        demo_BC_plug,
        demo_BC_gaussian,
        moving_end,
    ], sys.argv)
    eval(cmd)
    raw_input()
Esempio n. 18
0
    Nx = 80
    cpu = viz(I, None, None, c, U_0, U_L, L, Nx, C, T,
              umin=-1.1, umax=1.1, version='scalar', animate=True)

    # Convergence study
    def action(u, x, t, n):
        e = abs(u - exact(x, t[n])).max()
        errors_in_time.append(e)

    E = []
    dt = []
    Nx_values = [10, 20, 40, 80, 160]
    for Nx in Nx_values:
        errors_in_time = []
        solver(I, None, None, c, U_0, U_L, L, Nx, C, T,
               user_action=action, version='scalar')
        E.append(max(errors_in_time))
        _dx = L/Nx
        _dt = C*_dx/c
        dt.append(_dt)
        print dt[-1], E[-1]
    return dt, E

if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([test_quadratic, test_plug, plug,
                       gaussian, sincos, guitar,
                       moving_end,], sys.argv)
    eval(cmd)
Esempio n. 19
0
                                   umax=umax,
                                   every_frame=every_frame,
                                   screen_movie=animate)

    solver(I=I,
           V=None,
           f=None,
           c=c,
           U_0=None,
           U_L=None,
           L=L,
           Nx=Nx,
           C=C,
           T=T,
           user_action=action,
           version=version,
           dt_safety_factor=1)


if __name__ == '__main__':
    import sys
    from scitools.misc import function_UI
    cmd = function_UI([
        test_quadratic,
        test_plug,
        pulse,
        moving_end,
    ], sys.argv)
    eval(cmd)
    raw_input()