예제 #1
0
def main():
    np.random.seed(793817931)
    degree = 3
    mesh = UnitSquareMesh(2, 2)
    gdim = mesh.geometry().dim()
    fs = FunctionSpace(mesh, 'CG', degree)
    f = Function(fs)
    random_function(f)
    print(f.vector()[:])
예제 #2
0
    def test_multiplication(self):
        print(
            '\n== testing multiplication of system matrix for problem of weighted projection ===='
        )
        for dim, pol_order in itertools.product([2, 3], [1, 2]):
            N = 2  # no. of elements

            print('dim={0}, pol_order={1}, N={2}'.format(dim, pol_order, N))

            # creating MESH and defining MATERIAL
            if dim == 2:
                mesh = UnitSquareMesh(N, N)
                m = Expression("1+10*16*x[0]*(1-x[0])*x[1]*(1-x[1])",
                               degree=2)  # material coefficients
            elif dim == 3:
                mesh = UnitCubeMesh(N, N, N)
                m = Expression("1+10*16*x[0]*(1-x[0])*(1-x[1])*x[2]",
                               degree=2)  # material coefficients

            mesh.coordinates()[:] += 0.1 * np.random.random(
                mesh.coordinates().shape)  # mesh perturbation

            V = FunctionSpace(mesh, "CG", pol_order)  # original FEM space
            W = FunctionSpace(mesh, "CG", 2 * pol_order)  # double-grid space

            print('assembling local matrices for DoGIP...')
            Bhat = get_Bhat(
                dim, pol_order,
                problem=0)  # projection between V on W on a reference element
            AT_dogip = get_A_T(m, V, W, problem=0)

            dofmapV = V.dofmap()

            def system_multiplication_DoGIP(AT_dogip, Bhat, u_vec):
                # mutliplication with DoGIP decomposition
                Au = np.zeros_like(u_vec)
                for ii, cell in enumerate(cells(mesh)):
                    ind = dofmapV.cell_dofs(ii)  # local to global map
                    Au[ind] += Bhat.T.dot(AT_dogip[ii] * Bhat.dot(u_vec[ind]))
                return Au

            print('assembling FEM sparse matrix')
            u, v = TrialFunction(V), TestFunction(V)
            Asp = assemble(m * u * v * dx, tensor=EigenMatrix())  #
            Asp = Asp.sparray()

            print('multiplication...')
            ur = Function(V)  # creating random vector
            ur_vec = 5 * np.random.random(V.dim())
            ur.vector().set_local(ur_vec)

            Au_DoGIP = system_multiplication_DoGIP(
                AT_dogip, Bhat, ur_vec)  # DoGIP multiplication
            Auex = Asp.dot(ur_vec)  # FEM multiplication with sparse matrix

            # testing the difference between DoGIP and FEniCS
            self.assertAlmostEqual(0, np.linalg.norm(Auex - Au_DoGIP))
            print('...ok')
예제 #3
0
    def test_DoGIP_vs_FEniCS(self):
        print(
            '\n== testing DoGIP vs. FEniCS for problem of weighted projection ===='
        )

        for dim, pol_order in itertools.product([2, 3], [1, 2]):
            print('dim={}; pol_order={}'.format(dim, pol_order))
            N = 2
            # creating MESH, defining MATERIAL and SOURCE
            if dim == 2:
                mesh = UnitSquareMesh(N, N)
                m = Expression("1+10*16*x[0]*(1-x[0])*x[1]*(1-x[1])",
                               degree=3)  # material coefficients
                f = Expression("x[0]*x[0]*x[1]", degree=2)
            elif dim == 3:
                mesh = UnitCubeMesh(N, N, N)
                m = Expression("1+100*x[0]*(1-x[0])*x[1]*x[2]",
                               degree=2)  # material coefficients
                f = Expression("(1-x[0])*x[1]*x[2]", degree=2)

            mesh.coordinates()[:] += 0.1 * np.random.random(
                mesh.coordinates().shape)  # mesh perturbation

            ## standard approach with FEniCS #############################################
            V = FunctionSpace(mesh, "CG", pol_order)  # original FEM space
            u, v = TrialFunction(V), TestFunction(V)
            u_fenics = Function(V)
            solve(m * u * v * dx == m * f * v * dx, u_fenics)

            ## DoGIP - double-grid integration with interpolation-projection #############
            W = FunctionSpace(mesh, "CG", 2 * pol_order)  # double-grid space
            w = TestFunction(W)
            A_dogip = assemble(
                m * w *
                dx).get_local()  # diagonal matrix of material coefficients
            b = assemble(m * f * v * dx)  # vector of right-hand side

            # assembling interpolation-projection matrix B
            B = get_B(V, W, problem=0)

            # # linear solver on double grid, standard
            Afun = lambda x: B.T.dot(A_dogip * B.dot(x))

            Alinoper = linalg.LinearOperator((V.dim(), V.dim()),
                                             matvec=Afun,
                                             dtype=np.float)
            x, info = linalg.cg(Alinoper,
                                b.get_local(),
                                x0=np.zeros(V.dim()),
                                tol=1e-10,
                                maxiter=1e3,
                                callback=None)

            # testing the difference between DoGIP and FEniCS
            self.assertAlmostEqual(
                0, np.linalg.norm(u_fenics.vector().get_local() - x))
            print('...ok')
예제 #4
0
    def __init__(self,
                 grid_shape,
                 f,
                 init_z,
                 dirichlet,
                 degree=1,
                 polynomial_type='P',
                 reparam=True):
        """Parameters
        ----------
        grid_shape : numpy.array or list
            Defines the grid dimensions of the mesh used to solve the problem.
        f : str
            Source term of the Poisson equation in a form accepted by FEniCS (C++ style string)
        init_z : numpy.ndarray
            Placeholder value(s) for parameters of the model.
        dirichlet : str
            Dirichlet boundary conditions in string form accepted by FEniCS.
        degree : int, default 1
            Polynomial degree for the functional space.
        polynomial_type : str, default 'P'
            String encoding the type of polynomials in the functional space, according to FEniCS conventions
            (defaults to Lagrange polynomials).
        reparam: bool, default True
            Boolean indicating whether input parameters are to be reparametrized according to
            an inverse-logit transform.
        """
        def boundary(x, on_boundary):
            return on_boundary

        self.grid_shape = grid_shape
        self.mesh = UnitSquareMesh(*grid_shape)

        self.V = FunctionSpace(self.mesh, polynomial_type, degree)
        self.dirichlet = DirichletBC(self.V,
                                     Expression(dirichlet, degree=degree + 3),
                                     boundary)
        self._paramnames = ['param{}'.format(i) for i in range(len(init_z))]
        self.f = Expression(f,
                            degree=degree,
                            **dict(zip(self._paramnames, init_z)))
        u = TrialFunction(self.V)
        v = TestFunction(self.V)

        self.a = dot(grad(u), grad(v)) * dx
        self.L = self.f * v * dx
        self.u = Function(self.V)
        self.reparam = reparam
        self.solver = CountIt(solve)
예제 #5
0
def compute_error(u1, u2):
    """
    L1 error between two functions u1 and u2

    :param u1: FEniCS function
    :param u2: FEniCS function
    :return: Approximate L1 error between u1 and u2
    """
    mesh_resolution_ref = 400
    mesh_ref = UnitSquareMesh(mesh_resolution_ref, mesh_resolution_ref)
    V_ref = FunctionSpace(mesh_ref, "CG", degree=1)
    Iu1 = interpolate(u1, V_ref)
    Iu2 = interpolate(u2, V_ref)
    error = assemble(abs(Iu1 - Iu2) * dx)
    return error
예제 #6
0
def dual_error_estimates(resolution):
    mesh = UnitSquareMesh(resolution, resolution)

    def all_boundary(_, on_boundary):
        return on_boundary

    zero = Constant(0.0)

    def a(u, v):
        return inner(grad(u), grad(v)) * dx

    def L(f, v):
        return f * v * dx

    # Primal problem
    f = Expression("32.*x[0]*(1. - x[0])+32.*x[1]*(1. - x[1])",
                   domain=mesh,
                   degree=5)
    ue = Expression("16.*x[0]*(1. - x[0])*x[1]*(1. - x[1])",
                    domain=mesh,
                    degree=5)

    Qp = FunctionSpace(mesh, 'CG', 1)
    bcp = DirichletBC(Qp, zero, all_boundary)

    u = TrialFunction(Qp)
    v = TestFunction(Qp)

    U = Function(Qp)
    solve(a(u, v) == L(f, v), U, bcp)

    # Dual problem
    Qd = FunctionSpace(mesh, 'CG', 2)
    psi = Constant(1.0)
    bcd = DirichletBC(Qd, zero, all_boundary)

    w = TestFunction(Qd)
    phi = TrialFunction(Qd)
    Phi = Function(Qd)
    solve(a(w, phi) == L(psi, w), Phi, bcd)

    # Compute errors
    e1 = compute_error(ue, U)
    e2 = assemble((inner(grad(U), grad(Phi)) - f * Phi) * dx)
    print("e1 = {}".format(e1))
    print("e2 = {}".format(e2))
def test_video_loading():
    m = UnitSquareMesh(30, 30)
    V = FunctionSpace(m, "CG", 4)

    video = VideoData(element=V.ufl_element())
    video.load_video("video_data/ach12.mp4")

    print(video)

    plot(video, mesh=m)
    plt.show()

    video.set_time(10000.)
    plot(video, mesh=m)
    plt.show()

    assert True
def test():
    """Unit test."""
    from fenics import cpp, pi, UnitCubeMesh, UnitSquareMesh

    def print_slave_to_master_map(mesh, domain):
        """ Print the slave-to-master map."""
        for i in range(mesh.geometry().dim()):
            print("   In dimension {}:".format(i))
            mapping = cpp.PeriodicBoundaryComputation.compute_periodic_pairs(
                mesh, domain, i)
            for (source, (_, dest)) in mapping.items():
                print("      {} -> {}".format(source, dest))

    print("Test 1: flat 2-torus.")
    print_slave_to_master_map(UnitSquareMesh(1, 1), FlatTorus2D())
    print("")

    print("Test 2: flat 3-torus.")
    print_slave_to_master_map(UnitCubeMesh(1, 1, 1), FlatTorus3D())
    print("")
    def inside(self, x, on_boundary):
        return on_boundary and x[0] == 1


parser = argparse.ArgumentParser(description="Solving a volume coupled problem")
command_group = parser.add_mutually_exclusive_group(required=True)
command_group.add_argument("-s", "--source", help="create a source", dest="source", action="store_true")
command_group.add_argument("-d", "--drain", help="create a drain", dest="drain", action="store_true")
args = parser.parse_args()

if args.source:
    precice = Adapter(adapter_config_filename="precice-adapter-config-source.json")
elif args.drain:
    precice = Adapter(adapter_config_filename="precice-adapter-config-drain.json")

mesh = UnitSquareMesh(10, 10)
V = FunctionSpace(mesh, "P", 1)

u = TrialFunction(V)
v = TestFunction(V)
u_n = Function(V)
if args.source:
    u_ini = Expression("1", degree=1)
    bc = DirichletBC(V, u_ini, AllBoundary())
elif args.drain:
    u_ini = Expression("0", degree=1)
    bc = DirichletBC(V, u_ini, RightBoundary())


u_n = interpolate(u_ini, V)
예제 #10
0
V2 = np.loadtxt(in_dir + 'V2.txt')

# disk one velocity :
n1 = np.shape(X1)[0]
U1 = -u_mag * np.ones([n1, 2])

# disk two velocity :
n2 = np.shape(X2)[0]
U2 = u_mag * np.ones([n2, 2])

# corresponding Material objects :
disk1 = ElasticMaterial('disk1', X1, U1, E, nu, V=V1, rho=rho)
disk2 = ElasticMaterial('disk2', X2, U2, E, nu, V=V2, rho=rho)

# the finite-element mesh used :
mesh = UnitSquareMesh(n_x, n_x)

# initialize the model :
grid_model = GridModel(mesh, out_dir, verbose=False)

# create the main model to perform MPM calculations :
model = Model(out_dir, grid_model, dt, verbose=False)

# add the materials to the model :
model.add_material(disk1)
model.add_material(disk2)

# files for saving grid variables :
m_file = File(out_dir + '/m.pvd')
u_file = File(out_dir + '/u.pvd')
a_file = File(out_dir + '/a.pvd')
예제 #11
0
class TestWriteData(TestCase):
    dummy_config = "tests/precice-adapter-config.json"

    mesh = UnitSquareMesh(10, 10)
    dimension = 2

    scalar_expr = Expression("x[0]*x[0] + x[1]*x[1]", degree=2)
    scalar_V = FunctionSpace(mesh, "P", 2)
    scalar_function = interpolate(scalar_expr, scalar_V)

    vector_expr = Expression(("x[0] + x[1]*x[1]", "x[0] - x[1]*x[1]"),
                             degree=2)
    vector_V = VectorFunctionSpace(mesh, "P", 2)
    vector_function = interpolate(vector_expr, vector_V)

    def setUp(self):
        pass

    def test_write_scalar_data(self):
        from precice import Interface
        import fenicsadapter

        def dummy_set_mesh_vertices(mesh_id, positions):
            vertex_ids = np.arange(len(positions))
            return vertex_ids

        Interface.configure = MagicMock()
        Interface.write_block_scalar_data = MagicMock()
        Interface.read_block_vector_data = MagicMock()
        Interface.get_dimensions = MagicMock(return_value=2)
        Interface.set_mesh_vertices = MagicMock(
            side_effect=dummy_set_mesh_vertices)
        Interface.initialize = MagicMock()
        Interface.initialize_data = MagicMock()
        Interface.is_action_required = MagicMock(return_value=False)
        Interface.mark_action_fulfilled = MagicMock()
        Interface.is_time_window_complete = MagicMock()
        Interface.advance = MagicMock()
        Interface.get_mesh_id = MagicMock()
        Interface.get_data_id = MagicMock(return_value=15)
        Interface.is_read_data_available = MagicMock(return_value=False)
        Interface.set_mesh_edge = MagicMock()

        write_u = self.scalar_function
        read_u = self.vector_function
        u_init = self.scalar_function

        precice = fenicsadapter.Adapter(self.dummy_config)
        precice._coupling_bc_expression = MagicMock()
        precice.initialize(RightBoundary(), self.mesh, read_u, write_u, u_init)
        precice.advance(write_u, u_init, u_init, 0, 0, 0)

        expected_data_id = 15
        expected_values = np.array([
            self.scalar_expr(x_right, y)
            for y in np.linspace(y_bottom, y_top, 11)
        ])
        expected_ids = np.arange(11)

        expected_args = [expected_data_id, expected_ids, expected_values]

        for arg, expected_arg in zip(
                Interface.write_block_scalar_data.call_args[0], expected_args):
            if type(arg) is int:
                self.assertTrue(arg == expected_arg)
            elif type(arg) is np.ndarray:
                np.testing.assert_allclose(arg, expected_arg)

    def test_write_vector_data(self):
        from precice import Interface
        import fenicsadapter

        def dummy_set_mesh_vertices(mesh_id, positions):
            vertex_ids = np.arange(len(positions))
            return vertex_ids

        Interface.configure = MagicMock()
        Interface.write_block_vector_data = MagicMock()
        Interface.read_block_scalar_data = MagicMock()
        Interface.get_dimensions = MagicMock(return_value=2)
        Interface.set_mesh_vertices = MagicMock(
            side_effect=dummy_set_mesh_vertices)
        Interface.initialize = MagicMock()
        Interface.initialize_data = MagicMock()
        Interface.is_action_required = MagicMock(return_value=False)
        Interface.mark_action_fulfilled = MagicMock()
        Interface.is_time_window_complete = MagicMock()
        Interface.advance = MagicMock()
        Interface.get_mesh_id = MagicMock()
        Interface.get_data_id = MagicMock(return_value=15)
        Interface.is_read_data_available = MagicMock(return_value=False)
        Interface.set_mesh_edge = MagicMock()

        write_u = self.vector_function
        read_u = self.scalar_function
        u_init = self.vector_function

        precice = fenicsadapter.Adapter(self.dummy_config)
        precice._coupling_bc_expression = MagicMock()
        precice.initialize(RightBoundary(), self.mesh, read_u, write_u, u_init)
        precice.advance(write_u, u_init, u_init, 0, 0, 0)

        expected_data_id = 15
        expected_values_x = np.array([
            self.vector_expr(x_right, y)[0]
            for y in np.linspace(y_bottom, y_top, 11)
        ])
        expected_values_y = np.array([
            self.vector_expr(x_right, y)[1]
            for y in np.linspace(y_bottom, y_top, 11)
        ])
        expected_values = np.stack([expected_values_x, expected_values_y],
                                   axis=1)
        expected_ids = np.arange(11)

        expected_args = [expected_data_id, expected_ids, expected_values]

        for arg, expected_arg in zip(
                Interface.write_block_vector_data.call_args[0], expected_args):
            if type(arg) is int:
                self.assertTrue(arg == expected_arg)
            elif type(arg) is np.ndarray:
                np.testing.assert_almost_equal(arg, expected_arg)

    def test_read_scalar_data(self):
        from precice import Interface
        import fenicsadapter

        def return_dummy_data(data_id, value_indices):
            read_data = np.arange(len(value_indices))
            return read_data

        def dummy_set_mesh_vertices(mesh_id, positions):
            vertex_ids = np.arange(len(positions))
            return vertex_ids

        Interface.configure = MagicMock()
        Interface.write_block_vector_data = MagicMock()
        Interface.read_block_scalar_data = MagicMock(
            side_effect=return_dummy_data)
        Interface.get_dimensions = MagicMock(return_value=self.dimension)
        Interface.set_mesh_vertices = MagicMock(
            side_effect=dummy_set_mesh_vertices)
        Interface.initialize = MagicMock()
        Interface.initialize_data = MagicMock()
        Interface.is_action_required = MagicMock(return_value=False)
        Interface.mark_action_fulfilled = MagicMock()
        Interface.is_time_window_complete = MagicMock()
        Interface.advance = MagicMock()
        Interface.get_mesh_id = MagicMock()
        Interface.get_data_id = MagicMock(return_value=15)
        Interface.is_read_data_available = MagicMock(return_value=False)
        Interface.set_mesh_edge = MagicMock()

        write_u = self.vector_function
        read_u = self.scalar_function
        u_init = self.vector_function

        precice = fenicsadapter.Adapter(self.dummy_config)
        precice._coupling_bc_expression = MagicMock()
        precice.initialize(RightBoundary(), self.mesh, read_u, write_u, u_init)
        precice.advance(write_u, u_init, u_init, 0, 0, 0)

        expected_data_id = 15
        expected_ids = np.arange(11)

        expected_args = [expected_data_id, expected_ids]

        for arg, expected_arg in zip(
                Interface.read_block_scalar_data.call_args[0], expected_args):
            if type(arg) is int:
                self.assertTrue(arg == expected_arg)
            elif type(arg) is np.ndarray:
                np.testing.assert_allclose(arg, expected_arg)

    def test_read_vector_data(self):
        from precice import Interface
        import fenicsadapter

        def return_dummy_data(data_id, value_indices):
            read_data = np.arange(len(value_indices) * self.dimension).reshape(
                len(value_indices), self.dimension)
            return read_data

        def dummy_set_mesh_vertices(mesh_id, positions):
            vertex_ids = np.arange(len(positions))
            return vertex_ids

        Interface.configure = MagicMock()
        Interface.write_block_scalar_data = MagicMock()
        Interface.read_block_vector_data = MagicMock(
            side_effect=return_dummy_data)
        Interface.get_dimensions = MagicMock(return_value=self.dimension)
        Interface.set_mesh_vertices = MagicMock(
            side_effect=dummy_set_mesh_vertices)
        Interface.initialize = MagicMock()
        Interface.initialize_data = MagicMock()
        Interface.is_action_required = MagicMock(return_value=False)
        Interface.mark_action_fulfilled = MagicMock()
        Interface.is_time_window_complete = MagicMock()
        Interface.advance = MagicMock()
        Interface.get_mesh_id = MagicMock()
        Interface.get_data_id = MagicMock(return_value=15)
        Interface.is_read_data_available = MagicMock(return_value=False)
        Interface.set_mesh_edge = MagicMock()

        write_u = self.scalar_function
        read_u = self.vector_function
        u_init = self.scalar_function

        precice = fenicsadapter.Adapter(self.dummy_config)
        precice._coupling_bc_expression = MagicMock()
        precice.initialize(RightBoundary(), self.mesh, read_u, write_u, u_init)
        precice.advance(write_u, u_init, u_init, 0, 0, 0)

        expected_data_id = 15
        expected_ids = np.arange(11)

        expected_args = [expected_data_id, expected_ids]

        for arg, expected_arg in zip(
                Interface.read_block_vector_data.call_args[0], expected_args):
            if type(arg) is int:
                self.assertTrue(arg == expected_arg)
            elif type(arg) is np.ndarray:
                np.testing.assert_allclose(arg, expected_arg)
예제 #12
0
파일: FEM.py 프로젝트: vondrejc/FFTHomPy
    def inside(self, x, on_boundary):
        return (between(x[1], (0.2, 0.8)) and between(x[0], (0.2, 0.8)))


class Inclusion_3d(SubDomain):  # cube inclusion
    def inside(self, x, on_boundary):
        return (between(x[2], (0.2, 0.8)) and between(x[1], (0.2, 0.8))
                and between(x[0], (0.2, 0.8)))


E = np.zeros(dim)
E[0] = 1.  # macroscopic value
E = Constant(E)

if dim == 2:
    mesh = UnitSquareMesh(*N)  # generation of mesh
    inclusion = Inclusion_2d()
    point0 = "near(x[0], 0) && near(x[1], 0)"
elif dim == 3:
    mesh = UnitCubeMesh(*N)  # generation of mesh
    inclusion = Inclusion_3d()
    point0 = "near(x[0], 0) && near(x[1], 0) && near(x[2], 0)"

V = FunctionSpace(mesh, "CG", order, constrained_domain=PeriodicBoundary(dim))

# setting the elements that lies in inclusion and in matrix phase
domains = MeshFunction("size_t", mesh, dim)
domains.set_all(0)
inclusion.mark(domains, 1)
dx = Measure('dx', subdomain_data=domains)
import fenics

import numpy as np
import matplotlib.pyplot as plt

from fenics import UnitSquareMesh, Expression, Constant, Function
from fenics import FunctionSpace, TrialFunction, TestFunction, DirichletBC
from fenics import dot, grad, solve, plot, dx, errornorm

if __name__ == '__main__':
    fenics.set_log_level(30)  # only display warnings or errors

    # Create mesh and define function space
    grid_shape = np.array([32, 32])
    poly_degree = 1
    mesh = UnitSquareMesh(*grid_shape)
    V = FunctionSpace(mesh, 'P', poly_degree)
    # creates a grid_shape[0+1 x grid_shape[1]+1 vertices mesh with Lagrange polynomials of order order_degree

    # Define boundary condition
    u_D = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree=poly_degree + 3)

    # the expression accepts a string with commands in C++ style, that is then compiled for efficiency
    # the degree parameter specifies the polynomial degree for interpolation of the solution
    # if using the exact solution, the order should be at least a few units more than the functional space's elements


    def boundary(x, on_boundary):
        return on_boundary

    bc = DirichletBC(V, u_D, boundary)
 def load_video_mesh(self, nx = 30, ny = 30):
     self.mesh = UnitSquareMesh(nx, ny)