Beispiel #1
0
def test_sharp_cutoff():
    """Tests that the sharp cutoff function does what it should."""

    k = 10.0

    mesh = fd.UnitSquareMesh(10,10)

    V = fd.FunctionSpace(mesh,"CG",1)
    
    prob = hh.HelmholtzProblem(k,V,n=2.0)

    prob.sharp_cutoff(np.array([0.5,0.5]),0.5)

    V_DG = fd.FunctionSpace(mesh,"DG",0)
    
    n_fn = fd.Function(V_DG)

    n_fn.interpolate(prob._n)


    # This is a rudimentary test that it's 1 on the boundary and 2 elsewhere
    # Yes, I kind of made this pass by changing the value to check until it did.
    # But I've confirmed that it's doing (roughly) the right thing visually, so I'm content
    
    assert n_fn.dat.data_ro[97] == 1.0

    assert n_fn.dat.data_ro[95] == 2.0
Beispiel #2
0
    def __init__(self, *args, meshcell_size, **kwargs):

        n = int(round(1 / meshcell_size))

        kwargs["mesh"] = fe.UnitSquareMesh(n, n)

        super().__init__(*args, **kwargs)
def test__verify__second_order_temporal_convergence__via_mms(
        sim_constructor_kwargs={
            "quadrature_degree": 4,
            "element_degree": 1,
            "time_stencil_size": 3
        },
        parameters={
            "grashof_number": 2.,
            "prandtl_number": 5.,
            "stefan_number": 0.2,
            "heat_capacity_solid_to_liquid_ratio": 0.500,
            "thermal_conductivity_solid_to_liquid_ratio": 2.14 / 0.561,
            "smoothing": 1. / 16.
        },
        meshsize=24,
        timestep_sizes=(1. / 3., 1. / 9., 1. / 27.),
        tolerance=0.3):

    rx = sim_constructor_kwargs["element_degree"] + 1

    mesh = fe.UnitSquareMesh(meshsize, meshsize)

    h = mesh.cell_sizes((0., ) * mesh.geometric_dimension())

    sapphire.mms.verify_temporal_order_of_accuracy(
        sim_module=sim_module,
        manufactured_solution=manufactured_solution,
        sim_constructor_kwargs=sim_constructor_kwargs,
        mesh=mesh,
        parameters=parameters,
        expected_order=2,
        tolerance=tolerance,
        timestep_sizes=timestep_sizes,
        endtime=0.5)
def test_kl_like_coeff_reorder():
    """Tests the KL-like coefficient reordering works correctly."""

    mesh = fd.UnitSquareMesh(10,10)

    J = 2

    delta = 2.0

    lambda_mult = 0.1

    j_scaling = 1.0

    n_0 = 1.0

    stochastic_points_2 = np.array([[1.0,1.0],[2.0,2.0]])

    kl_like = UniformKLLikeCoeff(mesh,J,delta,lambda_mult,j_scaling,n_0,
                                 stochastic_points_2)

    kl_like.reorder([1,0],include_current_point=True)

    assert (kl_like.current_and_unsampled_points() == np.array([[2.0,2.0],[1.0,1.0]])).all()

    stochastic_points_3 = np.array([[1.0,1.0],[2.0,2.0],[3.0,3.0]])

    kl_like = UniformKLLikeCoeff(mesh,J,delta,lambda_mult,j_scaling,n_0,
                                 stochastic_points_3)

    kl_like.reorder([1,0],include_current_point=False)
    assert (kl_like.unsampled_points() == np.array([[3.0,3.0],[2.0,2.0]])).all()
def test_coeff_size():
    """Tests that the p/w/ const coeffs are the correct size."""

    mesh = fd.UnitSquareMesh(100,100)
    V = fd.FunctionSpace(mesh, "CG", 1)

    num_pieces = 1
    noise_level = 0.1
    num_repeats = 100
    
    A_pre = fd.as_matrix(np.array([[1.0,0.0],[0.0,1.0]]))
    A_stoch = PiecewiseConstantCoeffGenerator(mesh,num_pieces,
                                                   noise_level,A_pre,[2,2])

    n_pre = 1.0
    n_stoch = PiecewiseConstantCoeffGenerator(mesh,num_pieces,
                                                   noise_level,n_pre,[1])
    for ii in range(num_repeats):
        A_stoch.sample()
        n_stoch.sample()
        fl = A_stoch._constant_array.flat
        for jj in fl:
            coords = hh_utils.flatiter_hack(A_stoch._constant_array,fl.coords)
            assert A_stoch._constant_array[coords].evaluate(None,None,(),None).shape\
                == (2,2)
            assert n_stoch._constant_array[coords].evaluate(None,None,(),None).shape\
                == ()
def test_kl_like_coeff_change_all_points():
    """Tests the KL-like coefficient changes points correctly (and
    accesses points correctly too)."""

    mesh = fd.UnitSquareMesh(10,10)

    J = 10

    delta = 2.0

    lambda_mult = 0.1

    j_scaling = 1.0

    n_0 = 1.0

    stochastic_points = np.random.rand(3,J) - 0.5

    kl_like = UniformKLLikeCoeff(mesh,J,delta,lambda_mult,j_scaling,n_0,
                                 stochastic_points)

    new_points = np.random.rand(7,J) - 0.5
    
    kl_like.change_all_points(new_points)

    assert (kl_like.current_and_unsampled_points() == new_points).all()
def test_noise_level():
    """Tests p/w const coeffs have correct noise_level.

    Only works for the case coeff_pre = 1.0."""

    mesh = fd.UnitSquareMesh(100,100)

    num_pieces = 12
    noise_level = 0.1
    num_repeats = 100
    
    n_pre = 1.0
    n_stoch = PiecewiseConstantCoeffGenerator(mesh,num_pieces,
                                                   noise_level,n_pre,[1])

    V = fd.FunctionSpace(mesh, "CG", 1)
    n_func = fd.Function(V)
    
    for ii in range(num_repeats):
        n_stoch.sample()

        fl = n_stoch._constant_array.flat
        for jj in fl:
            coords = hh_utils.flatiter_hack(n_stoch._constant_array,fl.coords)

            assert abs(n_stoch._constant_array[coords]\
                       .evaluate(None,None,(),None)) <= noise_level

        n_func.interpolate(n_stoch.coeff)

        assert (np.abs(n_func.dat.data_ro-n_pre) <= noise_level).all()
def test_coeff_being_updated():
    """Test that the p/w/ const random coefficients are updated."""

    k = 20.0
    mesh = fd.UnitSquareMesh(100,100)
    V = fd.FunctionSpace(mesh, "CG", 1)

    num_pieces = 12
    noise_level = 0.1
    num_repeats = 10
    
    A_pre = fd.as_matrix(np.array([[1.0,0.0],[0.0,1.0]]))
    A_stoch = PiecewiseConstantCoeffGenerator(mesh,num_pieces,
                                                   noise_level,A_pre,[2,2])

    n_pre = 1.0
    n_stoch = PiecewiseConstantCoeffGenerator(mesh,num_pieces,
                                                   noise_level,n_pre,[1])

    A_copy = copy.deepcopy(A_stoch._constant_array[0,0].values())

    n_copy = copy.deepcopy(n_stoch._constant_array[0,0].values())

    A_stoch.sample()

    n_stoch.sample()

    A_diff = A_copy - A_stoch._constant_array[0,0].values()

    assert all(A_copy != 0.0)

    assert n_copy != n_stoch._constant_array[0,0].values()    
def test__verify__third_order_spatial_convergence__via_mms(
        sim_constructor_kwargs={
            "quadrature_degree": 2,
            "element_degree": 2,
            "time_stencil_size": 4
        },
        parameters={
            "grashof_number": 2.,
            "prandtl_number": 5.,
            "stefan_number": 0.2,
            "heat_capacity_solid_to_liquid_ratio": 0.500,
            "thermal_conductivity_solid_to_liquid_ratio": 2.14 / 0.561,
            "smoothing": 1. / 16.
        },
        mesh_sizes=(3, 6, 12, 24),
        timestep_size=1. / 64.,
        tolerance=0.32):

    rt = sim_constructor_kwargs["time_stencil_size"] - 1

    sapphire.mms.verify_spatial_order_of_accuracy(
        sim_module=sim_module,
        manufactured_solution=manufactured_solution,
        sim_constructor_kwargs=sim_constructor_kwargs,
        meshes=[fe.UnitSquareMesh(n, n) for n in mesh_sizes],
        parameters=parameters,
        expected_order=3,
        tolerance=tolerance,
        timestep_size=timestep_size,
        endtime=0.32)
Beispiel #10
0
def test_sharp_cutoff_ufl():
    """Tests that the sharp cutoff function does what it should when the
coefficient is given by a ufl expression."""

    k = 10.0

    mesh = fd.UnitSquareMesh(10,10)

    V = fd.FunctionSpace(mesh,"CG",1)

    x = fd.SpatialCoordinate(mesh)

    n = 1.0 + fd.sin(30*x[0])
    
    prob = hh.HelmholtzProblem(k,V,n=n)
    
    prob.sharp_cutoff(np.array([0.5,0.5]),0.5)

    V_DG = fd.FunctionSpace(mesh,"DG",0)
    
    n_fn = fd.Function(V_DG)

    n_fn.interpolate(prob._n)


    # This is a rudimentary test that it's 1 on the boundary
    # Yes, I kind of made this pass by changing the value to check until it did.
    # But I've confirmed that it's doing (roughly) the right thing visually, so I'm content
    
    assert n_fn.dat.data_ro[97] == 1.0
Beispiel #11
0
def test__steady_state_lid_driven_cavity_benchmark():
    """ Verify against steady state lid-driven cavity benchmark.
    
    Comparing to data published in 
    
        @article{ghia1982high-re,
            author = {Ghia, Urmila and Ghia, K.N and Shin, C.T},
            year = {1982},
            month = {12},
            pages = {387-411},
            title = {High-Re solutions for incompressible flow using the Navier-Stokes equations and a multigrid method1},
            volume = {48},
            journal = {Journal of Computational Physics},
            doi = {10.1016/0021-9991(82)90058-4}
        }
    """
    endtime = 1.e12

    sim = LidDrivenCavitySimulation(reynolds_number=100.,
                                    mesh=fe.UnitSquareMesh(50, 50),
                                    element_degrees=(2, 1),
                                    timestep_size=endtime)

    sim.states = sim.run(endtime=endtime)

    tests.validation.helpers.check_scalar_solution_component(
        solution=sim.solution,
        component=0,
        subcomponent=0,
        coordinates=[(0.5, y) for y in (0.9766, 0.1016, 0.0547, 0.0000)],
        expected_values=(0.8412, -0.0643, -0.0372, 0.0000),
        absolute_tolerances=(0.0025, 0.0015, 0.001, 1.e-16))
Beispiel #12
0
def run_L2tracking_optimization(write_output=False):
    """ Test template for fsz.LevelsetFunctional."""

    # tool for developing new tests, allows storing shape iterates
    if write_output:
        out = fd.File("domain.pvd")

        def cb(*args):
            out.write(Q.mesh_m.coordinates)

        cb()
    else:
        cb = None

    # setup problem
    mesh = fd.UnitSquareMesh(30, 30)
    Q = fs.FeControlSpace(mesh)
    inner = fs.ElasticityInnerProduct(Q)
    q = fs.ControlVector(Q, inner)

    # setup PDE constraint
    mesh_m = Q.mesh_m
    e = PoissonSolver(mesh_m)

    # create PDEconstrained objective functional
    J_ = L2trackingObjective(e, Q, cb=cb)
    J = fs.ReducedObjective(J_, e)

    # ROL parameters
    params_dict = {
        'General': {
            'Secant': {
                'Type': 'Limited-Memory BFGS',
                'Maximum Storage': 10
            }
        },
        'Step': {
            'Type': 'Line Search',
            'Line Search': {
                'Descent Method': {
                    'Type': 'Quasi-Newton Step'
                }
            },
        },
        'Status Test': {
            'Gradient Tolerance': 1e-4,
            'Step Tolerance': 1e-5,
            'Iteration Limit': 15
        }
    }

    # assemble and solve ROL optimization problem
    params = ROL.ParameterList(params_dict, "Parameters")
    problem = ROL.OptimizationProblem(J, q)
    solver = ROL.OptimizationSolver(problem, params)
    solver.solve()

    # verify that the norm of the gradient at optimum is small enough
    state = solver.getAlgorithmState()
    assert (state.gnorm < 1e-4)
def test_coeff_definition_no_error():
    """Test that a coeff with just too few many pieces is not caught."""
    k = 20.0
    mesh = fd.UnitSquareMesh(100, 100)
    V = fd.FunctionSpace(mesh, "CG", 1)

    num_pieces = 12
    noise_level = 0.1
    num_repeats = 10

    A_pre = fd.as_matrix(np.array([[1.0, 0.0], [0.0, 1.0]]))
    A_stoch = PiecewiseConstantCoeffGenerator(mesh, num_pieces, noise_level,
                                              A_pre, [2, 2])

    n_pre = 1.0
    n_stoch = PiecewiseConstantCoeffGenerator(mesh, num_pieces, noise_level,
                                              n_pre, [1])

    f = 1.0
    g = 1.0

    GMRES_its = nbex.nearby_preconditioning_experiment(V, k, A_pre, A_stoch,
                                                       n_pre, n_stoch, f, g,
                                                       num_repeats)

    # The code should not error.

    assert GMRES_its.shape != (0, )
Beispiel #14
0
def test_plot_field():
    mesh = firedrake.UnitSquareMesh(32, 32)
    Q = firedrake.FunctionSpace(mesh, "CG", 1)
    x, y = firedrake.SpatialCoordinate(mesh)
    u = interpolate(x * y, Q)

    fig, axes = icepack.plot.subplots(nrows=2,
                                      ncols=2,
                                      sharex=True,
                                      sharey=True)

    filled_contours = icepack.plot.tricontourf(u, axes=axes[0, 0])
    assert filled_contours is not None
    colorbar = plt.colorbar(filled_contours, ax=axes[0, 0])
    assert colorbar is not None

    contours = icepack.plot.tricontour(u, axes=axes[0, 1])
    assert contours is not None

    colors_flat = icepack.plot.tripcolor(u, shading="flat", axes=axes[1, 0])
    assert colors_flat is not None

    colors_gouraud = icepack.plot.tripcolor(u,
                                            shading="gouraud",
                                            axes=axes[1, 1])
    assert colors_flat.get_array().shape != colors_gouraud.get_array().shape
Beispiel #15
0
 def __init__(self, *args,
         mesh_dimensions = (20, 20),
         hotwall_temperature = 0.5,
         coldwall_temperature = -0.5,
         reynolds_number = 1.,
         rayleigh_number = 1.e6,
         prandtl_number = 0.71,
         **kwargs):
     
     if "solution" not in kwargs:
         
         kwargs["mesh"] = fe.UnitSquareMesh(*mesh_dimensions)
         
     self.hotwall_id = 1
     
     self.coldwall_id = 2
     
     self.hotwall_temperature = fe.Constant(hotwall_temperature)
 
     self.coldwall_temperature = fe.Constant(coldwall_temperature)
     
     super().__init__(
         *args,
         reynolds_number = reynolds_number,
         rayleigh_number = rayleigh_number,
         prandtl_number = prandtl_number,
         **kwargs)
def test_coeff_definition_error():
    """Test that a coeff with too many pieces is caught."""
    k = 20.0
    mesh = fd.UnitSquareMesh(100, 100)
    V = fd.FunctionSpace(mesh, "CG", 1)

    num_pieces = 13
    noise_level = 0.1
    num_repeats = 10

    A_pre = fd.as_matrix(np.array([[1.0, 0.0], [0.0, 1.0]]))
    A_stoch = PiecewiseConstantCoeffGenerator(mesh, num_pieces, noise_level,
                                              A_pre, [2, 2])

    n_pre = 1.0
    n_stoch = PiecewiseConstantCoeffGenerator(mesh, num_pieces, noise_level,
                                              n_pre, [1])

    f = 1.0
    g = 1.0

    GMRES_its = nbex.nearby_preconditioning_experiment(V, k, A_pre, A_stoch,
                                                       n_pre, n_stoch, f, g,
                                                       num_repeats)

    # The code should catch the error and print a warning message, and
    # exit, not recording any GMRES iterations.

    assert GMRES_its.shape == (0, )
Beispiel #17
0
    def __init__(self,
                 *args,
                 mesh_dimensions=(24, 24),
                 hotwall_temperature=1.,
                 initial_temperature=-0.01,
                 reynolds_number=1.,
                 rayleigh_number=3.27e5,
                 prandtl_number=56.2,
                 stefan_number=0.045,
                 liquidus_temperature=0.,
                 **kwargs):

        if "solution" not in kwargs:

            kwargs["mesh"] = fe.UnitSquareMesh(*mesh_dimensions)

        self.hotwall_temperature = fe.Constant(hotwall_temperature)

        self.initial_temperature = fe.Constant(initial_temperature)

        super().__init__(*args,
                         liquidus_temperature=liquidus_temperature,
                         reynolds_number=reynolds_number,
                         rayleigh_number=rayleigh_number,
                         prandtl_number=prandtl_number,
                         stefan_number=stefan_number,
                         **kwargs)
Beispiel #18
0
def test_scalar_field():
    Nx, Ny = 16, 16
    mesh2d = firedrake.UnitSquareMesh(Nx, Ny)
    mesh3d = firedrake.ExtrudedMesh(mesh2d, layers=1)
    x, y, z = firedrake.SpatialCoordinate(mesh3d)

    Q3D = firedrake.FunctionSpace(mesh3d,
                                  family='CG',
                                  degree=2,
                                  vfamily='GL',
                                  vdegree=5)
    q3d = firedrake.interpolate((x**2 + y**2) * (1 - z**4), Q3D)
    q_avg = depth_average(q3d)

    p3d = firedrake.interpolate(x**2 + y**2, Q3D)
    p_avg = depth_average(p3d, weight=1 - z**4)

    Q2D = firedrake.FunctionSpace(mesh2d, family='CG', degree=2)
    x, y = firedrake.SpatialCoordinate(mesh2d)
    q2d = firedrake.interpolate(4 * (x**2 + y**2) / 5, Q2D)

    assert q_avg.ufl_domain() is mesh2d
    assert norm(q_avg - q2d) / norm(q2d) < 1 / (Nx * Ny)**2
    assert norm(p_avg - q2d) / norm(q2d) < 1 / (Nx * Ny)**2

    Q0 = firedrake.FunctionSpace(mesh3d,
                                 family='CG',
                                 degree=2,
                                 vfamily='GL',
                                 vdegree=0)
    q_lift = lift3d(q_avg, Q0)
    assert norm(depth_average(q_lift) - q2d) / norm(q2d) < 1 / (Nx * Ny)**2
Beispiel #19
0
def test_n_min_ufl():
    """Tests that the sharp cutoff function does what it should when n is given by a ufl expression."""

    k = 10.0

    mesh = fd.UnitSquareMesh(10,10)

    V = fd.FunctionSpace(mesh,"CG",1)

    x = fd.SpatialCoordinate(mesh)
    
    n = 1.0 + fd.sin(30*x[0])
    
    prob = hh.HelmholtzProblem(k,V,n=n)

    n_min_val = 2.0
    
    prob.n_min(n_min_val)

    V_DG = fd.FunctionSpace(mesh,"DG",0)
    
    n_fn = fd.Function(V_DG)

    n_fn.interpolate(prob._n)
    
    assert (n_fn.dat.data_ro >= n_min_val).all()
Beispiel #20
0
def test_n_min_pre_ufl():
    """Tests that the sharp cutoff function does what it should when n_pre is given by a UFL expression."""

    k = 10.0

    mesh = fd.UnitSquareMesh(10,10)

    V = fd.FunctionSpace(mesh,"CG",1)

    x = fd.SpatialCoordinate(mesh)
    
    n_pre = 1.0 + fd.sin(30*x[0])
    
    prob = hh.HelmholtzProblem(k,V,n_pre=n_pre,A_pre = fd.as_matrix([[1.0,0.0],[0.0,1.0]]))

    n_min_val = 2.0
    
    prob.n_min(n_min_val,True)

    V_DG = fd.FunctionSpace(mesh,"DG",0)
    
    n_fn = fd.Function(V_DG)

    n_fn.interpolate(prob._n_pre)
    
    assert (n_fn.dat.data_ro >= n_min_val).all()
Beispiel #21
0
    def __init__(self, *args, meshsize, **kwargs):

        self.hot_wall_temperature = fe.Constant(1.)

        self.cold_wall_temperature = fe.Constant(-0.01)

        self.topwall_heatflux = fe.Constant(0.)

        super().__init__(
            *args,
            mesh=fe.UnitSquareMesh(meshsize, meshsize),
            initial_values=initial_values,
            dirichlet_boundary_conditions=dirichlet_boundary_conditions,
            **kwargs)

        q = self.topwall_heatflux

        _, _, psi_T = fe.TestFunctions(self.function_space)

        ds = fe.ds(domain=self.mesh, subdomain_id=4)

        self.variational_form_residual += psi_T * q * ds

        Ra = 3.27e5

        Pr = 56.2

        self.grashof_number = self.grashof_number.assign(Ra / Pr)

        self.prandtl_number = self.prandtl_number.assign(Pr)

        self.stefan_number = self.stefan_number.assign(0.045)

        self.liquidus_temperature = self.liquidus_temperature.assign(0.)
Beispiel #22
0
def test_sharp_cutoff_pre_ufl():
    """Tests that the sharp cutoff function does what it should when the
    preconditioning coefficient is given by ufl."""

    k = 10.0

    mesh = fd.UnitSquareMesh(10,10)

    V = fd.FunctionSpace(mesh,"CG",1)

    x = fd.SpatialCoordinate(mesh)

    n_pre = 1.0 + fd.sin(30*x[0])

    prob = hh.HelmholtzProblem(k,V,n_pre=n_pre,A_pre = fd.as_matrix([[1.0,0.0],[0.0,1.0]]))

    prob.sharp_cutoff(np.array([0.5,0.5]),0.5,True)

    V_DG = fd.FunctionSpace(mesh,"DG",0)

    n_fn = fd.Function(V_DG)

    n_fn.interpolate(prob._n_pre)

    # As above
    assert n_fn.dat.data_ro[97] == 1.0
Beispiel #23
0
def test_interpolating_function():
    nx, ny = 32, 32
    mesh = firedrake.UnitSquareMesh(nx, ny)
    x = firedrake.SpatialCoordinate(mesh)
    Q = firedrake.FunctionSpace(mesh, "CG", 2)
    q = icepack.interpolate(x[0] ** 2 - x[1] ** 2, Q)
    assert abs(firedrake.assemble(q * dx)) < 1e-6
Beispiel #24
0
def test_vector_field():
    Nx, Ny = 16, 16
    mesh2d = firedrake.UnitSquareMesh(Nx, Ny)
    mesh3d = firedrake.ExtrudedMesh(mesh2d, layers=1)
    x, y, z = firedrake.SpatialCoordinate(mesh3d)

    V3D = firedrake.VectorFunctionSpace(mesh3d,
                                        "CG",
                                        2,
                                        vfamily="GL",
                                        vdegree=5,
                                        dim=2)
    u3d = firedrake.interpolate(firedrake.as_vector((1 - z**4, 0)), V3D)
    u_avg = depth_average(u3d)

    V2D = firedrake.VectorFunctionSpace(mesh2d, "CG", 2)
    x, y = firedrake.SpatialCoordinate(mesh2d)
    u2d = firedrake.interpolate(firedrake.as_vector((4 / 5, 0)), V2D)

    assert norm(u_avg - u2d) / norm(u2d) < 1 / (Nx * Ny)**2

    V0 = firedrake.VectorFunctionSpace(mesh3d,
                                       "CG",
                                       2,
                                       vfamily="GL",
                                       vdegree=0,
                                       dim=2)
    u_lift = lift3d(u_avg, V0)
    assert norm(depth_average(u_lift) - u2d) / norm(u2d) < 1 / (Nx * Ny)**2
def create_form(form_string, family, degree, dimension, operation):
    from firedrake import dx, inner, grad
    import firedrake as f

    f.parameters['coffee']['optlevel'] = 'O3'
    f.parameters['pyop2_options']['opt_level'] = 'O3'
    f.parameters['pyop2_options']['simd_isa'] = 'avx'
    f.parameters["pyop2_options"]["lazy_evaluation"] = False

    m = f.UnitSquareMesh(2, 2, quadrilateral=True)
    if dimension == 3:
        m = f.ExtrudedMesh(m, 2)

    fs = f.FunctionSpace(m, family, degree)
    v = f.TestFunction(fs)
    if operation == "matrix":
        u = f.TrialFunction(fs)
    elif operation == "action":
        u = f.Function(fs)
    else:
        raise ValueError("Unknown operation: %s" % operation)

    if form_string == "u * v * dx":
        return u * v * dx
    elif form_string == "inner(grad(u), grad(v)) * dx":
        return inner(grad(u), grad(v)) * dx
Beispiel #26
0
def test_checkpointing(controlspace_t):
    mesh = fd.UnitSquareMesh(5, 5)

    if controlspace_t == fs.BsplineControlSpace:
        bbox = [(-1, 2), (-1, 2)]
        orders = [2, 2]
        levels = [4, 4]
        Q = fs.BsplineControlSpace(mesh, bbox, orders, levels)
    elif controlspace_t == fs.FeMultiGridControlSpace:
        Q = fs.FeMultiGridControlSpace(mesh, refinements=1, order=2)
    else:
        Q = controlspace_t(mesh)

    inner = fs.H1InnerProduct(Q)

    q = fs.ControlVector(Q, inner)
    p = fs.ControlVector(Q, inner)

    from firedrake.petsc import PETSc
    rand = PETSc.Random().create(mesh.comm)
    rand.setInterval((1, 2))
    q.vec_wo().setRandom(rand)

    Q.store(q)

    Q.load(p)

    assert q.norm() > 0
    assert abs(q.norm()-p.norm()) < 1e-14
    p.axpy(-1, q)
    assert p.norm() < 1e-14
Beispiel #27
0
def test_ilu():
    """Tests that ILU functionality gives correct solution."""

    k = 10.0

    num_cells = utils.h_to_num_cells(k**-1.5,2)

    mesh = fd.UnitSquareMesh(num_cells,num_cells)

    V = fd.FunctionSpace(mesh,"CG",1)
    
    prob = hh.HelmholtzProblem(k,V)

    angle = 2.0 * np.pi/7.0

    d = [np.cos(angle),np.sin(angle)]
    
    prob.f_g_plane_wave(d)

    for fill_in in range(40):
    
        prob.use_ilu_gmres(fill_in)

        prob.solve()

        x = fd.SpatialCoordinate(mesh)

        # This error was found out by eye
        assert np.abs(fd.norms.errornorm(fd.exp(1j * k * fd.dot(fd.as_vector(d),x)),uh=prob.u_h,norm_type='H1')) < 0.5
Beispiel #28
0
def make_domain(nx, ny, xmin, ymin, width, height):
    mesh = firedrake.UnitSquareMesh(nx, ny, diagonal="crossed")
    x, y = firedrake.SpatialCoordinate(mesh)
    Vc = mesh.coordinates.function_space()
    expr = firedrake.as_vector((width * x + xmin, height * y + ymin))
    f = firedrake.interpolate(expr, Vc)
    mesh.coordinates.assign(f)
    return mesh
Beispiel #29
0
def test_plot_field():
    mesh = firedrake.UnitSquareMesh(32, 32)
    Q = firedrake.FunctionSpace(mesh, 'CG', 1)
    x, y = firedrake.SpatialCoordinate(mesh)
    u = firedrake.interpolate(x * y, Q)
    contours = icepack.plot.tricontourf(u)
    assert contours is not None
    colorbar = plt.colorbar(contours)
    assert colorbar is not None
Beispiel #30
0
def test_StochasticHelmholtzProblem_sample():
    """Test that sample routine works correctly."""

    class DeterministicCoeff(object):
        """Generates 'random' coefficients in a known way.

        Coefficients are of the type required in
        StochasticHelmholtzProblem, but matrix-valued coefficients take
        the values [[1.0,0.0],[0.0,1.0/n]] and scalar-valued
        coefficients take the value 1.0 = 1.0/n, where n >= 1 is the
        number of times the coefficient has been sampled.
        """

        def __init__(self,type):
            """Initialises testing class."""
            self._counter = 1

            self._changes = fd.Constant(1.0)

            self._type = type

            if type == "matrix":
                self.coeff = fd.as_matrix([[1.0,0.0],[0.0,1.0/self._changes]])

            if type == "scalar":
                self.coeff = 1 + 1.0/self._changes

        def sample(self):
            """Update coefficient."""

            self._counter += 1
            
            self._changes.assign(float(self._counter))

    A_test = DeterministicCoeff("matrix")

    n_test = DeterministicCoeff("scalar")

    k = 20.0
    
    mesh = fd.UnitSquareMesh(100,100)

    V = fd.FunctionSpace(mesh, "CG", 1)

    prob = hh.StochasticHelmholtzProblem(k,V,A_test,n_test)

    num_samples = 999
    
    for ii in range(num_samples):
        prob.sample()

    # The following test isn't perfect, but it shows that the `sample'
    # method for StochasticHelmholtzProblem is calling the `sample'
    # method of the coefficients correctly. (It doesn't show if the
    # embedding in the form is correct.)
    assert n_test._changes.values() == float(num_samples + 1)
    assert A_test._changes.values() == float(num_samples + 1)