def __init__(self, *args, meshcell_size, **kwargs): n = int(round(1 / meshcell_size)) kwargs["mesh"] = fe.UnitIntervalMesh(n) super().__init__(*args, **kwargs)
def test_firedrake_to_numpy_function(): # Functions in DG0 have nodes at centers of finite element cells mesh = firedrake.UnitIntervalMesh(10) V = firedrake.FunctionSpace(mesh, "DG", 0) x = firedrake.SpatialCoordinate(mesh) test_input = firedrake.interpolate(x[0], V) expected = numpy.linspace(0.05, 0.95, num=10) assert numpy.allclose(to_numpy(test_input), expected)
def test_from_jax_function(test_input, expected_expr): mesh = firedrake.UnitIntervalMesh(10) V = firedrake.FunctionSpace(mesh, "DG", 0) template = firedrake.Function(V) fenics_test_input = from_jax(test_input, template) expected = firedrake.interpolate(expected_expr(mesh), V) assert numpy.allclose( fenics_test_input.vector().get_local(), expected.vector().get_local() )
def test_numpy_to_firedrake_function(): test_input = numpy.linspace(0.05, 0.95, num=10) mesh = firedrake.UnitIntervalMesh(10) V = firedrake.FunctionSpace(mesh, "DG", 0) template = firedrake.Function(V) firedrake_test_input = from_numpy(test_input, template) x = firedrake.SpatialCoordinate(mesh) expected = firedrake.interpolate(x[0], V) assert numpy.allclose(firedrake_test_input.vector().get_local(), expected.vector().get_local())
def test__verify_convergence_order_via_mms(): sapphire.mms.verify_spatial_order_of_accuracy( sim_module = sim_module, manufactured_solution = manufactured_solution, meshes = [fe.UnitIntervalMesh(n) for n in (8, 16, 32)], norms = ("L2",), expected_orders = (2,), decimal_places = 1)
def test__verify_convergence_order_via_mms( mesh_sizes = (8, 16, 32), tolerance = 0.1): sapphire.mms.verify_spatial_order_of_accuracy( sim_module = sim_module, sim_constructor_kwargs = {"quadrature_degree": 2, "element_degree": 1}, manufactured_solution = manufactured_solution, meshes = [fe.UnitIntervalMesh(n) for n in mesh_sizes], expected_order = 2, tolerance = tolerance)
def test_firedrake_to_numpy_mixed_function(): # Functions in DG0 have nodes at centers of finite element cells mesh = firedrake.UnitIntervalMesh(10) vec_dim = 4 V = firedrake.VectorFunctionSpace(mesh, "DG", 0, dim=vec_dim) x = firedrake.SpatialCoordinate(mesh) test_input = firedrake.interpolate(firedrake.as_vector(vec_dim * (x[0], )), V) expected = numpy.linspace(0.05, 0.95, num=10) expected = numpy.reshape(numpy.tile(expected, (4, 1)).T, V.dim()) assert numpy.allclose(to_numpy(test_input), expected)
def test__verify_spatial_convergence__first_order__via_mms(): sapphire.mms.verify_spatial_order_of_accuracy( sim_module=sim_module, sim_kwargs={"timestep_size": 1. / 64.}, manufactured_solution=manufactured_solution, meshes=[fe.UnitIntervalMesh(n) for n in (4, 8, 16, 32)], norms=("H1", ), expected_orders=(1, ), decimal_places=1, endtime=1.)
def test__verify_temporal_convergence__first_order__via_mms(): sapphire.mms.verify_temporal_order_of_accuracy( sim_module=sim_module, sim_kwargs={"mesh": fe.UnitIntervalMesh(256)}, manufactured_solution=manufactured_solution, norms=("L2", ), expected_orders=(1, ), endtime=1., timestep_sizes=(1. / 4., 1. / 8., 1. / 16., 1. / 32.), decimal_places=1)
def test__verify_spatial_convergence__second_order__via_mms( mesh_sizes=(4, 8, 16, 32), timestep_size=1. / 64., tolerance=0.1): sapphire.mms.verify_spatial_order_of_accuracy( sim_module=sim_module, manufactured_solution=manufactured_solution, meshes=[fe.UnitIntervalMesh(n) for n in mesh_sizes], sim_constructor_kwargs={ "element_degree": 1, "time_stencil_size": 2 }, expected_order=2, tolerance=tolerance, timestep_size=timestep_size, endtime=1.)
def test__verify_temporal_convergence__first_order__via_mms(): sapphire.mms.verify_temporal_order_of_accuracy( sim_module=sim_module, sim_kwargs={ "stefan_number": 0.1, "liquidus_smoothing_factor": 1. / 32., "mesh": fe.UnitIntervalMesh(512), }, manufactured_solution=manufactured_solution, norms=("L2", ), expected_orders=(1, ), endtime=1., timestep_sizes=(1. / 16., 1. / 32., 1. / 64., 1. / 128.), decimal_places=1)
def test__verify_spatial_convergence__first_order__via_mms(): sapphire.mms.verify_spatial_order_of_accuracy( sim_module=sim_module, sim_kwargs={ "stefan_number": 0.1, "liquidus_smoothing_factor": 1. / 32., "timestep_size": 1. / 256., }, manufactured_solution=manufactured_solution, meshes=[fe.UnitIntervalMesh(size) for size in (4, 8, 16, 32)], norms=("H1", ), expected_orders=(1, ), endtime=1., decimal_places=1)
def test__verify_temporal_convergence__second_order__via_mms(): sapphire.mms.verify_temporal_order_of_accuracy( sim_module=sim_module, sim_kwargs={ "mesh": fe.UnitIntervalMesh(128), "element_degree": 2, "time_stencil_size": 3, }, manufactured_solution=manufactured_solution, norms=("L2", ), expected_orders=(2, ), endtime=1., timestep_sizes=(1. / 16., 1. / 32., 1. / 64., 1. / 128.), decimal_places=1)
def test__verify_temporal_convergence__third_order__via_mms( meshsize=128, timestep_sizes=(1. / 4., 1. / 8., 1. / 16., 1. / 32.), tolerance=0.1): sapphire.mms.verify_temporal_order_of_accuracy( sim_module=sim_module, manufactured_solution=manufactured_solution, mesh=fe.UnitIntervalMesh(meshsize), sim_constructor_kwargs={ "element_degree": 2, "time_stencil_size": 4 }, expected_order=3, endtime=1., timestep_sizes=timestep_sizes, tolerance=tolerance)
def compute_space_accuracy_via_mms( grid_sizes, element_degree, quadrature_degree, smoothing): dx = fe.dx(degree = quadrature_degree) parameters["smoothing"].assign(smoothing) h, e, order = [], [], [] for gridsize in grid_sizes: mesh = fe.UnitIntervalMesh(gridsize) element = fe.FiniteElement("P", mesh.ufl_cell(), element_degree) V = fe.FunctionSpace(mesh, element) u_m = manufactured_solution(mesh) bc = fe.DirichletBC(V, u_m, "on_boundary") u = fe.TrialFunction(V) v = fe.TestFunction(V) u_h = fe.Function(V) fe.solve(F(u, v)*dx == v*R(u_m)*dx, u_h, bcs = bc) e.append(math.sqrt(fe.assemble(fe.inner(u_h - u_m, u_h - u_m)*dx))) h.append(1./float(gridsize)) if len(e) > 1: r = h[-2]/h[-1] log = math.log order = log(e[-2]/e[-1])/log(r) print("{0: <4}, {1: .3f}, {2: .5f}, {3: .3f}, {4: .3f}".format( str(quadrature_degree), smoothing, h[-1], e[-1], order))
def test__verify_temporal_convergence__first_order__via_mms( meshsize = 256, timestep_sizes = (1./16., 1./32., 1./64., 1./128.), tolerance = 0.1): sapphire.mms.verify_temporal_order_of_accuracy( sim_module = sim_module, manufactured_solution = manufactured_solution, mesh = fe.UnitIntervalMesh(meshsize), sim_constructor_kwargs = { "quadrature_degree": 4, "element_degree": 1, "time_stencil_size": 2}, parameters = { "stefan_number": 0.1, "smoothing": 1./32.}, expected_order = 1, endtime = 1., timestep_sizes = timestep_sizes, tolerance = tolerance)
def test__verify_spatial_convergence__second_order__via_mms( mesh_sizes = (4, 8, 16, 32), timestep_size = 1./256., tolerance = 0.1): sapphire.mms.verify_spatial_order_of_accuracy( sim_module = sim_module, manufactured_solution = manufactured_solution, meshes = [fe.UnitIntervalMesh(size) for size in mesh_sizes], sim_constructor_kwargs = { "quadrature_degree": 4, "element_degree": 1, "time_stencil_size": 2}, parameters = { "stefan_number": 0.1, "smoothing": 1./32.}, expected_order = 2, timestep_size = timestep_size, endtime = 1., tolerance = tolerance)
def compute_space_accuracy_via_mms(grid_sizes, element_degree): print("h, L2_norm_error") h, e = [], [] for gridsize in grid_sizes: mesh = fe.UnitIntervalMesh(gridsize) element = fe.FiniteElement("P", mesh.ufl_cell(), element_degree) V = fe.FunctionSpace(mesh, element) u_m = manufactured_solution(mesh) bc = fe.DirichletBC(V, u_m, "on_boundary") u = fe.TrialFunction(V) v = fe.TestFunction(V) u_h = fe.Function(V) fe.solve(F(u, v) == v*R(u_m)*dx, u_h, bcs = bc) e.append(math.sqrt(fe.assemble(fe.inner(u_h - u_m, u_h - u_m)*dx))) h.append(1./float(gridsize)) print(str(h[-1]) + ", " + str(e[-1])) r = h[-2]/h[-1] log = math.log order = log(e[-2]/e[-1])/log(r) return order
def plot(u_h, sample_size=1000, axes=None, color="k", **kwargs): """ fe.plot ignores color argument """ mesh = u_h.function_space().mesh() if (type(mesh) == type(fe.UnitIntervalMesh(1))): sample_points = [ x / float(sample_size) for x in range(sample_size + 1) ] if axes is None: fig = plt.figure() axes = plt.axes() plt.plot(sample_points, [u_h((p, )) for p in sample_points], axes=axes, color=color) else: fe.plot(u_h, axes=axes, color=color, **kwargs)
from matplotlib import pyplot as plt import numpy as np import sys # This isn't in a formal pytest framework because the 'at' functionality # isn't working yet in complex Firedrake. selection = int(sys.argv[1]) if selection == 0: """Tests that the f function works correctly.""" # I can't tell if this isn't working correctly, or if we just see # rounding error. I think it's just rounding error. num_cells = 1000 mesh = fd.UnitIntervalMesh(num_cells) V = fd.FunctionSpace(mesh, "CG", 1) v = fd.Function(V) x = fd.SpatialCoordinate(mesh) # for eps in [1.0,0.5,0.1,0.05]: v.interpolate(utils.f(x[0])) fd.plot(v) print("Any NaNs?") print(np.any(np.isnan(v.dat.data_ro))) #print(v.dat.data_ro) plt.show()
filenames = ['interpolation-left','interpolation-right'] for ii_k in range(2): k = k_list[ii_k] h = (k**-1.0) * (np.pi/5.0) h_coarse = (k_list[0]**-1.0) * (np.pi/5.0) num_cells_coarse = h_to_num_cells(h_coarse,d) num_cells = h_to_num_cells(h,d) mesh_interpolate = fd.UnitIntervalMesh(num_cells_coarse) mesh_fine = fd.UnitIntervalMesh(10*num_cells) V_interpolate = fd.FunctionSpace(mesh_interpolate,"CG",1) u_interpolate = fd.Function(V_interpolate) x_interpolate = fd.SpatialCoordinate(mesh_interpolate) u_interpolate.interpolate(fd.sin(k*x_interpolate[0])) coord_interpolate = fd.Function(V_interpolate) coord_interpolate.interpolate(x_interpolate[0])
from matplotlib import pyplot as plt import numpy as np from matplotlib import rc rc('text', usetex=True ) # Found out about this from https://stackoverflow.com/q/54827147 k = 1000.0 h = (k**-1.0) * (np.pi / 5.0) d = 1 num_cells = h_to_num_cells(h, d) mesh = fd.UnitIntervalMesh(num_cells) mesh_fine = fd.UnitIntervalMesh(20 * num_cells) V = fd.FunctionSpace(mesh, "CG", 1) V_fine = fd.FunctionSpace(mesh_fine, "CG", 1) u = fd.TrialFunction(V) v = fd.TestFunction(V) a = (fd.inner(fd.grad(u), fd.grad(v))\ - k**2 * fd.inner(u,v)) * fd.dx#\ # - (1j* k * fd.inner(u,v)) * fd.ds(2)
def compute_time_accuracy_via_mms( gridsize, element_degree, timestep_sizes, endtime): mesh = fe.UnitIntervalMesh(gridsize) element = fe.FiniteElement("P", mesh.ufl_cell(), element_degree) V = fe.FunctionSpace(mesh, element) u_h = fe.Function(V) v = fe.TestFunction(V) un = fe.Function(V) u_m = manufactured_solution(mesh) bc = fe.DirichletBC(V, u_m, "on_boundary") _F = F(u_h, v, un) problem = fe.NonlinearVariationalProblem( _F - v*R(u_m)*dx, u_h, bc, fe.derivative(_F, u_h)) solver = fe.NonlinearVariationalSolver(problem) t.assign(0.) initial_values = fe.interpolate(u_m, V) L2_norm_errors = [] print("Delta_t, L2_norm_error") for timestep_size in timestep_sizes: Delta_t.assign(timestep_size) un.assign(initial_values) time = 0. t.assign(time) while time < (endtime - TIME_EPSILON): time += timestep_size t.assign(time) solver.solve() un.assign(u_h) L2_norm_errors.append( math.sqrt(fe.assemble(fe.inner(u_h - u_m, u_h - u_m)*dx))) print(str(timestep_size) + ", " + str(L2_norm_errors[-1])) r = timestep_sizes[-2]/timestep_sizes[-1] e = L2_norm_errors log = math.log order = log(e[-2]/e[-1])/log(r) return order
import firedrake as fe mesh = fe.UnitIntervalMesh(2) x = fe.SpatialCoordinate(mesh)[0] sin, pi, exp, diff = fe.sin, fe.pi, fe.exp, fe.diff for t in (fe.Constant(0.), fe.variable(0.)): u = sin(pi * x) * exp(-t) print(diff(u, t))