Пример #1
0
 def _cooks(cls, **kwargs):
     mesh = UnitSquareMesh(10, 5)
     def cooks_domain(x, y):
         return [48 * x, 44 * (x + y) - 18 * x * y]
     mesh.coordinates()[:] = np.array(cooks_domain(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1])).transpose()
 #    plot(mesh, interactive=True, axes=True) 
     maxx, minx, maxy, miny = 48, 0, 60, 0
     # setup boundary parts
     llc, lrc, tlc, trc = compile_subdomains(['near(x[0], 0.) && near(x[1], 0.)',
                                                      'near(x[0], 48.) && near(x[1], 0.)',
                                                      'near(x[0], 0.) && near(x[1], 60.)',
                                                      'near(x[0], 48.) && near(x[1], 60.)'])
     top, bottom, left, right = compile_subdomains([  'x[0] >= 0. && x[0] <= 48. && x[1] >= 44. && on_boundary',
                                                      'x[0] >= 0. && x[0] <= 48. && x[1] <= 44. && on_boundary',
                                                      'near(x[0], 0.) && on_boundary',
                                                      'near(x[0], 48.) && on_boundary'])
     # the corners
     llc.minx = minx
     llc.miny = miny
     lrc.maxx = maxx
     lrc.miny = miny
     tlc.minx = minx
     tlc.maxy = maxy
     trc.maxx = maxx
     trc.maxy = maxy
     # the edges
     top.minx = minx
     top.maxx = maxx
     bottom.minx = minx
     bottom.maxx = maxx
     left.minx = minx
     right.maxx = maxx
     return mesh, {'top':top, 'bottom':bottom, 'left':left, 'right':right, 'llc':llc, 'lrc':lrc, 'tlc':tlc, 'trc':trc, 'all': DomainBoundary()}, 2
Пример #2
0
    def test_compute_entity_collisions_tree_2d(self):

        references = [[[20, 21, 22, 23, 28, 29, 30, 31],
                      [0, 1, 2, 3, 8, 9, 10, 11]],
                      [[6],
                       [25]]]

        points = [Point(0.52, 0.51), Point(0.9, -0.9)]

        for i, point in enumerate(points):

            mesh_A = UnitSquareMesh(4, 4)
            mesh_B = UnitSquareMesh(4, 4)

            mesh_B.translate(point)

            tree_A = BoundingBoxTree()
            tree_A.build(mesh_A)

            tree_B = BoundingBoxTree()
            tree_B.build(mesh_B)

            entities_A, entities_B = tree_A.compute_entity_collisions(tree_B)

            if MPI.num_processes() == 1:
                self.assertEqual(sorted(entities_A), references[i][0])
                self.assertEqual(sorted(entities_B), references[i][1])
Пример #3
0
    def test_compute_collisions_tree_2d(self):

        references = [[set([20, 21, 22, 23, 28, 29, 30, 31]),
                       set([0, 1, 2, 3, 8, 9, 10, 11])],
                      [set([6, 7]),
                       set([24, 25])]]

        points = [Point(0.52, 0.51), Point(0.9, -0.9)]

        for i, point in enumerate(points):

            mesh_A = UnitSquareMesh(4, 4)
            mesh_B = UnitSquareMesh(4, 4)

            mesh_B.translate(point)

            tree_A = BoundingBoxTree()
            tree_A.build(mesh_A)

            tree_B = BoundingBoxTree()
            tree_B.build(mesh_B)

            entities_A, entities_B = tree_A.compute_collisions(tree_B)

            if MPI.size(mesh_A.mpi_comm()) == 1:
                self.assertEqual(set(entities_A), references[i][0])
                self.assertEqual(set(entities_B), references[i][1])
Пример #4
0
def test_HarmonicSmoothing():

    # Create some mesh and its boundary
    mesh = UnitSquareMesh(10, 10)
    boundary = BoundaryMesh(mesh, 'exterior')

    # Move boundary
    disp = Expression(("0.3*x[0]*x[1]", "0.5*(1.0-x[1])"))
    ALE.move(boundary, disp)

    # Move mesh according to given boundary
    ALE.move(mesh, boundary)

    # Check that new boundary topology corresponds to given one
    boundary_new = BoundaryMesh(mesh, 'exterior')
    assert boundary.topology().hash() == boundary_new.topology().hash()

    # Check that coordinates are almost equal
    err = sum(sum(abs(boundary.coordinates() \
                    - boundary_new.coordinates()))) / mesh.num_vertices()
    print("Current CG solver produced error in boundary coordinates", err)
    assert round(err - 0.0, 5) == 0

    # Check mesh quality
    magic_number = 0.35
    rmin = MeshQuality.radius_ratio_min_max(mesh)[0]
    assert rmin > magic_number
Пример #5
0
def test_compute_entity_collisions_tree_2d():

    references = [[set([20, 21, 22, 23, 28, 29, 30, 31]),
                    set([0, 1, 2, 3, 8, 9, 10, 11])],
                  [set([6]),
                    set([25])]]

    points = [Point(0.52, 0.51), Point(0.9, -0.9)]

    for i, point in enumerate(points):

        mesh_A = UnitSquareMesh(4, 4)
        mesh_B = UnitSquareMesh(4, 4)

        mesh_B.translate(point)

        tree_A = BoundingBoxTree()
        tree_A.build(mesh_A)

        tree_B = BoundingBoxTree()
        tree_B.build(mesh_B)

        entities_A, entities_B = tree_A.compute_entity_collisions(tree_B)

        assert set(entities_A) == references[i][0]
        assert set(entities_B) == references[i][1]
Пример #6
0
    def test_HarmonicSmoothing(self):

        print ""
        print "Testing HarmonicSmoothing::move(Mesh& mesh, " \
              "const BoundaryMesh& new_boundary)"

        # Create some mesh and its boundary
        mesh = UnitSquareMesh(10, 10)
        boundary = BoundaryMesh(mesh, 'exterior')

        # Move boundary
        disp = Expression(("0.3*x[0]*x[1]", "0.5*(1.0-x[1])"))
        boundary.move(disp)

        # Move mesh according to given boundary
        mesh.move(boundary)

        # Check that new boundary topology corresponds to given one
        boundary_new = BoundaryMesh(mesh, 'exterior')
        self.assertEqual(boundary.topology().hash(),
                         boundary_new.topology().hash())

        # Check that coordinates are almost equal
        err = sum(sum(abs(boundary.coordinates() \
                        - boundary_new.coordinates()))) / mesh.num_vertices()
        print "Current CG solver produced error in boundary coordinates", err
        self.assertAlmostEqual(err, 0.0, places=5)

        # Check mesh quality
        magic_number = 0.35
        self.assertTrue(mesh.radius_ratio_min()>magic_number)
Пример #7
0
def neumann_elasticity_data():
    '''
    Return:
        a  bilinear form in the neumann elasticity problem
        L  linear form in therein
        V  function space, where a, L are defined
        bc homog. dirichlet conditions for case where we want pos. def problem
        z  list of orthonormal vectors in the nullspace of A that form basis
           of ker(A)
    '''
    mesh = UnitSquareMesh(40, 40)

    V = VectorFunctionSpace(mesh, 'CG', 1)
    u = TrialFunction(V)
    v = TestFunction(V)

    f = Expression(('sin(pi*x[0])', 'cos(pi*x[1])'))

    epsilon = lambda u: sym(grad(u))

    # Material properties
    E, nu = 10.0, 0.3
    mu, lmbda = Constant(E/(2*(1 + nu))), Constant(E*nu/((1 + nu)*(1 - 2*nu)))

    sigma = lambda u: 2*mu*epsilon(u) + lmbda*tr(epsilon(u))*Identity(2)

    a = inner(sigma(u), epsilon(v))*dx
    L = inner(f, v)*dx  # Zero stress

    bc = DirichletBC(V, Constant((0, 0)), DomainBoundary())

    z0 = interpolate(Constant((1, 0)), V).vector()
    normalize(z0, 'l2')

    z1 = interpolate(Constant((0, 1)), V).vector()
    normalize(z1, 'l2')

    X = mesh.coordinates().reshape((-1, 2))
    c0, c1 = np.sum(X, axis=0)/len(X)
    z2 = interpolate(Expression(('x[1]-c1',
                                 '-(x[0]-c0)'), c0=c0, c1=c1), V).vector()
    normalize(z2, 'l2')

    z = [z0, z1, z2]

    # Check that this is orthonormal basis
    I = np.zeros((3, 3))
    for i, zi in enumerate(z):
        for j, zj in enumerate(z):
            I[i, j] = zi.inner(zj)

    print I
    print la.norm(I-np.eye(3))
    assert la.norm(I-np.eye(3)) < 1E-13

    return a, L, V, bc, z
Пример #8
0
    def test_mesh_point_2d(self):
        "Test mesh-point intersection in 2D"

        point = Point(0.1, 0.2)
        mesh = UnitSquareMesh(16, 16)

        intersection = intersect(mesh, point)

        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(intersection.intersected_cells(), [98])
Пример #9
0
    def test_compute_collisions_point_2d(self):

        reference = {1: set([226]),
                     2: set([136, 137])}

        p = Point(0.3, 0.3)
        mesh = UnitSquareMesh(16, 16)
        for dim in range(1, 3):
            tree = BoundingBoxTree()
            tree.build(mesh, dim)
            entities = tree.compute_collisions(p)
            if MPI.size(mesh.mpi_comm()) == 1:
                self.assertEqual(set(entities), reference[dim])
Пример #10
0
def test_compute_first_entity_collision_2d():

    reference = [136, 137]

    p = Point(0.3, 0.3)
    mesh = UnitSquareMesh(16, 16)
    tree = BoundingBoxTree()
    tree.build(mesh)
    first = tree.compute_first_entity_collision(p)
    assert first in reference

    tree = mesh.bounding_box_tree()
    first = tree.compute_first_entity_collision(p)
    assert first in reference
Пример #11
0
def square_with_obstacle():
    # Create classes for defining parts of the boundaries and the interior
    # of the domain
    class Left(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], 0.0)

    class Right(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], 1.0)

    class Bottom(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], 0.0)

    class Top(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], 1.0)

    class Obstacle(SubDomain):
        def inside(self, x, on_boundary):
            return between(x[1], (0.5, 0.7)) and between(x[0], (0.2, 1.0))

    # Initialize sub-domain instances
    left = Left()
    top = Top()
    right = Right()
    bottom = Bottom()
    obstacle = Obstacle()

    # Define mesh
    mesh = UnitSquareMesh(100, 100, "crossed")

    # Initialize mesh function for interior domains
    domains = CellFunction("size_t", mesh)
    domains.set_all(0)
    obstacle.mark(domains, 1)

    # Initialize mesh function for boundary domains
    boundaries = MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
    boundaries.set_all(0)
    left.mark(boundaries, 1)
    top.mark(boundaries, 2)
    right.mark(boundaries, 3)
    bottom.mark(boundaries, 4)

    boundary_indices = {"left": 1, "top": 2, "right": 3, "bottom": 4}
    f = Constant(0.0)
    theta0 = Constant(293.0)
    return mesh, f, boundaries, boundary_indices, theta0
Пример #12
0
def test_compute_entity_collisions_2d():

    reference = set([136, 137])

    p = Point(0.3, 0.3)
    mesh = UnitSquareMesh(16, 16)

    tree = BoundingBoxTree()
    tree.build(mesh)
    entities = tree.compute_entity_collisions(p)
    assert set(entities) == reference

    tree = mesh.bounding_box_tree()
    entities = tree.compute_entity_collisions(p)
    assert set(entities) == reference
Пример #13
0
def test_compute_first_collision_2d():

    reference = {1: [226],
                  2: [136, 137]}

    p = Point(0.3, 0.3)
    mesh = UnitSquareMesh(16, 16)
    for dim in range(1, 3):
        tree = BoundingBoxTree()
        tree.build(mesh, dim)
        first = tree.compute_first_collision(p)
        assert first in reference[dim]

    tree = mesh.bounding_box_tree()
    first = tree.compute_first_collision(p)
    assert first in reference[mesh.topology().dim()]
Пример #14
0
    def test_compute_entity_collisions_2d(self):

        reference = [136, 137]

        p = Point(0.3, 0.3)
        mesh = UnitSquareMesh(16, 16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        entities = tree.compute_entity_collisions(p, mesh)
        if MPI.num_processes() == 1:
            self.assertEqual(sorted(entities), reference)

        tree = mesh.bounding_box_tree()
        entities = tree.compute_entity_collisions(p, mesh)
        
        if MPI.num_processes() == 1:
            self.assertEqual(sorted(entities), reference)
Пример #15
0
    def test_compute_first_entity_collision_2d(self):

        reference = [136, 137]

        p = Point(0.3, 0.3)
        mesh = UnitSquareMesh(16, 16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        first = tree.compute_first_entity_collision(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertIn(first, reference)


        tree = mesh.bounding_box_tree()
        first = tree.compute_first_entity_collision(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertIn(first, reference)
Пример #16
0
def test_compute_closest_entity_2d():

    reference = (1, 1.0)

    p = Point(-1.0, 0.01)
    mesh = UnitSquareMesh(16, 16)
    tree = BoundingBoxTree()
    tree.build(mesh)
    entity, distance = tree.compute_closest_entity(p)

    assert entity == reference[0]
    assert round(distance - reference[1], 7) == 0

    tree = mesh.bounding_box_tree()
    entity, distance = tree.compute_closest_entity(p)
    assert entity == reference[0]
    assert round(distance - reference[1], 7) == 0
Пример #17
0
    def test_compute_entity_collisions_2d(self):

        reference = set([136, 137])

        p = Point(0.3, 0.3)
        mesh = UnitSquareMesh(16, 16)

        tree = BoundingBoxTree()
        tree.build(mesh)
        entities = tree.compute_entity_collisions(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(set(entities), reference)

        tree = mesh.bounding_box_tree()
        entities = tree.compute_entity_collisions(p)

        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(set(entities), reference)
Пример #18
0
    def test_compute_first_collision_2d(self):

        reference = {1: [226],
                     2: [136, 137]}

        p = Point(0.3, 0.3)
        mesh = UnitSquareMesh(16, 16)
        for dim in range(1, 3):
            tree = BoundingBoxTree()
            tree.build(mesh, dim)
            first = tree.compute_first_collision(p)
            if MPI.size(mesh.mpi_comm()) == 1:
                self.assertIn(first, reference[dim])

        tree = mesh.bounding_box_tree()
        first = tree.compute_first_collision(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertIn(first, reference[mesh.topology().dim()])
Пример #19
0
def test_mesh_point_2d_quadrilateral():
    "Test mesh-point intersection in 2D for quadrilateral mesh"

    point = Point(0.1, 0.2)
    mesh = UnitSquareMesh.create(16, 16, CellType.Type.quadrilateral)

    intersection = intersect(mesh, point)

    assert intersection.intersected_cells() == [49]
Пример #20
0
    def test_compute_collisions_2d(self):

        reference = {1: [226],
                     2: [136, 137]}

        p = Point(0.3, 0.3)
        mesh = UnitSquareMesh(16, 16)
        for dim in range(1, 3):
            tree = BoundingBoxTree()
            tree.build(mesh, dim)
            entities = tree.compute_collisions(p)
            if MPI.num_processes() == 1:
                self.assertEqual(sorted(entities), reference[dim])

        tree = mesh.bounding_box_tree()
        entities = tree.compute_collisions(p)
        if MPI.num_processes() == 1:
            self.assertEqual(sorted(entities), reference[mesh.topology().dim()])
Пример #21
0
    def test_compute_closest_entity_2d(self):

        reference = (1, 1.0)

        p = Point(-1.0, 0.01)
        mesh = UnitSquareMesh(16, 16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        entity, distance = tree.compute_closest_entity(p)

        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(entity, reference[0])
            self.assertAlmostEqual(distance, reference[1])

        tree = mesh.bounding_box_tree()
        entity, distance = tree.compute_closest_entity(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(entity, reference[0])
            self.assertAlmostEqual(distance, reference[1])
Пример #22
0
    def test_compute_closest_entity_2d(self):

        reference = (0, numpy.sqrt(2.0))

        p = Point(-1.0, -1.0)
        mesh = UnitSquareMesh(16, 16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        entity, distance = tree.compute_closest_entity(p, mesh)

        if MPI.num_processes() == 1:
            self.assertEqual(entity, reference[0])
            self.assertAlmostEqual(distance, reference[1])

        tree = mesh.bounding_box_tree()
        entity, distance = tree.compute_closest_entity(p, mesh)
        if MPI.num_processes() == 1:
            self.assertEqual(entity, reference[0])
            self.assertAlmostEqual(distance, reference[1])
Пример #23
0
        def test_ale(self):

            print ""
            print "Testing ALE::move(Mesh& mesh0, const Mesh& mesh1)"

            # Create some mesh
            mesh = UnitSquareMesh(4, 5)

            # Make some cell function
            # FIXME: Initialization by array indexing is probably
            #        not a good way for parallel test
            cellfunc = CellFunction('size_t', mesh)
            cellfunc.array()[0:4] = 0
            cellfunc.array()[4:]  = 1

            # Create submeshes - this does not work in parallel
            submesh0 = SubMesh(mesh, cellfunc, 0)
            submesh1 = SubMesh(mesh, cellfunc, 1)

            # Move submesh0
            disp = Constant(("0.1", "-0.1"))
            submesh0.move(disp)

            # Move and smooth submesh1 accordignly
            submesh1.move(submesh0)

            # Move mesh accordingly
            parent_vertex_indices_0 = \
                     submesh0.data().array('parent_vertex_indices', 0)
            parent_vertex_indices_1 = \
                     submesh1.data().array('parent_vertex_indices', 0)
            mesh.coordinates()[parent_vertex_indices_0[:]] = \
                     submesh0.coordinates()[:]
            mesh.coordinates()[parent_vertex_indices_1[:]] = \
                     submesh1.coordinates()[:]

            # If test passes here then it is probably working
            # Check for cell quality for sure
            magic_number = 0.28
            rmin = MeshQuality.radius_ratio_min_max(mesh)[0]
            self.assertTrue(rmin > magic_number)
Пример #24
0
def test_compute_first_collision_2d():

    # FIXME: This test should not use facet indices as there are no guarantees
    # on how DOLFIN numbers facets
    reference = {1: [226],
                  2: [136, 137]}

    p = Point(0.3, 0.3)
    mesh = UnitSquareMesh(16, 16)
    for dim in range(1, 3):
        tree = BoundingBoxTree()
        tree.build(mesh, dim)
        first = tree.compute_first_collision(p)

        # FIXME: Facet test is excluded because it mistakingly relies in the
        # facet indices
        if dim != mesh.topology().dim() - 1:
            assert first in reference[dim]

    tree = mesh.bounding_box_tree()
    first = tree.compute_first_collision(p)
    assert first in reference[mesh.topology().dim()]
Пример #25
0
def test_lu_cholesky():
    """Test that PETScLUSolver selects LU or Cholesky solver based on
    symmetry of matrix operator.

    """

    from petsc4py import PETSc

    mesh = UnitSquareMesh(MPI.comm_world, 12, 12)
    V = FunctionSpace(mesh, "Lagrange", 1)
    u, v = TrialFunction(V), TestFunction(V)
    A = PETScMatrix(mesh.mpi_comm())
    assemble(Constant(1.0)*u*v*dx, tensor=A)

    # Check that solver type is LU
    solver = PETScLUSolver(mesh.mpi_comm(), A, "petsc")
    pc_type = solver.ksp().getPC().getType()
    assert pc_type == "lu"

    # Set symmetry flag
    A.mat().setOption(PETSc.Mat.Option.SYMMETRIC, True)

    # Check symmetry flags
    symm = A.mat().isSymmetricKnown()
    assert symm[0] == True
    assert symm[1] == True

    # Check that solver type is Cholesky since matrix has now been
    # marked as symmetric
    solver = PETScLUSolver(mesh.mpi_comm(), A, "petsc")
    pc_type = solver.ksp().getPC().getType()
    assert pc_type == "cholesky"

    # Re-assemble, which resets symmetry flag
    assemble(Constant(1.0)*u*v*dx, tensor=A)
    solver = PETScLUSolver(mesh.mpi_comm(), A, "petsc")
    pc_type = solver.ksp().getPC().getType()
    assert pc_type == "lu"
Пример #26
0
def mesh():
    return UnitSquareMesh(MPI.comm_world, 4, 4, CellType.Type.triangle)
Пример #27
0
    def __init__(self, VV, parameters=[]):
        self.parameters = {}
        self.parameters['eps'] = 1e-4
        self.parameters['correctcost'] = True
        self.parameters.update(parameters)
        eps = Constant(self.parameters['eps'])

        self.ab = Function(VV)
        self.a, self.b = self.ab.split(deepcopy=True)
        normgrada = sqrt(inner(nabla_grad(self.a), nabla_grad(self.a)) + eps)
        ngrada = nabla_grad(self.a) / normgrada
        normgradb = sqrt(inner(nabla_grad(self.b), nabla_grad(self.b)) + eps)
        ngradb = nabla_grad(self.b) / normgradb

        # cost
        if self.parameters['correctcost']:
            meshtmp = UnitSquareMesh(VV.mesh().mpi_comm(), 10, 10)
            Vtmp = FunctionSpace(meshtmp, 'CG', 1)
            x = SpatialCoordinate(meshtmp)
            correctioncost = 1. / assemble(sqrt(4.0 * x[0] * x[0]) * dx)
            print '[NCG] Correction cost with factor={}'.format(correctioncost)
        else:
            correctioncost = 1.0
        self.cost = 0.5 * correctioncost * (
            1.0 - inner(ngrada, ngradb) * inner(ngrada, ngradb)) * dx
        # gradient
        testa, testb = TestFunction(VV)
        grada = - inner(ngrada, ngradb)* \
        (inner(ngradb/normgrada, nabla_grad(testa)) -
        inner(ngrada, ngradb)* \
        inner(ngrada/normgrada, nabla_grad(testa)))*dx
        gradb = - inner(ngrada, ngradb)* \
        (inner(ngrada/normgradb, nabla_grad(testb)) -
        inner(ngrada, ngradb)* \
        inner(ngradb/normgradb, nabla_grad(testb)))*dx
        self.grad = grada + gradb
        # Hessian
        self.ahat, self.bhat = self.ab.split(deepcopy=True)
        self.abhat = Function(VV)
        triala, trialb = TrialFunction(VV)
        wkform11 = -((inner(ngradb / normgrada, nabla_grad(testa)) - inner(
            ngrada, ngradb) * inner(ngrada / normgrada, nabla_grad(testa))) *
                     (inner(ngradb / normgrada, nabla_grad(triala)) -
                      inner(ngrada, ngradb) *
                      inner(ngrada / normgrada, nabla_grad(triala))) +
                     inner(ngrada, ngradb) *
                     (-inner(ngradb / normgrada, nabla_grad(testa)) *
                      inner(ngrada / normgrada, nabla_grad(triala)) -
                      inner(ngradb / normgrada, nabla_grad(triala)) *
                      inner(ngrada / normgrada, nabla_grad(testa)) -
                      inner(ngrada / normgrada, ngradb / normgrada) *
                      inner(nabla_grad(testa), nabla_grad(triala)) +
                      3 * inner(ngrada, ngradb) *
                      inner(ngrada / normgrada, nabla_grad(testa)) *
                      inner(ngrada / normgrada, nabla_grad(triala)))) * dx
        #
        wkform12 = -(
            (inner(ngradb / normgrada, nabla_grad(testa)) -
             inner(ngrada, ngradb) *
             inner(ngrada / normgrada, nabla_grad(testa))) *
            (inner(ngrada / normgradb, nabla_grad(trialb)) - inner(
                ngrada, ngradb) * inner(ngradb / normgradb, nabla_grad(trialb))
             ) + inner(ngrada, ngradb) *
            (inner(
                nabla_grad(testa) / normgrada,
                nabla_grad(trialb) / normgradb) -
             inner(ngradb / normgrada, nabla_grad(testa)) *
             inner(ngradb / normgradb, nabla_grad(trialb)) -
             inner(ngrada / normgrada, nabla_grad(testa)) *
             (inner(ngrada / normgradb, nabla_grad(trialb)) -
              inner(ngrada, ngradb) *
              inner(ngradb / normgradb, nabla_grad(trialb))))) * dx
        #
        wkform22 = -((inner(ngrada / normgradb, nabla_grad(testb)) - inner(
            ngrada, ngradb) * inner(ngradb / normgradb, nabla_grad(testb))) *
                     (inner(ngrada / normgradb, nabla_grad(trialb)) -
                      inner(ngrada, ngradb) *
                      inner(ngradb / normgradb, nabla_grad(trialb))) +
                     inner(ngrada, ngradb) *
                     (-inner(ngrada / normgradb, nabla_grad(testb)) *
                      inner(ngradb / normgradb, nabla_grad(trialb)) -
                      inner(ngrada / normgradb, nabla_grad(trialb)) *
                      inner(ngradb / normgradb, nabla_grad(testb)) -
                      inner(ngrada / normgradb, ngradb / normgradb) *
                      inner(nabla_grad(testb), nabla_grad(trialb)) +
                      3 * inner(ngrada, ngradb) *
                      inner(ngradb / normgradb, nabla_grad(testb)) *
                      inner(ngradb / normgradb, nabla_grad(trialb)))) * dx
        #
        wkform21 = -(
            (inner(ngrada / normgradb, nabla_grad(testb)) -
             inner(ngrada, ngradb) *
             inner(ngradb / normgradb, nabla_grad(testb))) *
            (inner(ngradb / normgrada, nabla_grad(triala)) - inner(
                ngrada, ngradb) * inner(ngrada / normgrada, nabla_grad(triala))
             ) + inner(ngrada, ngradb) *
            (inner(
                nabla_grad(testb) / normgradb,
                nabla_grad(triala) / normgrada) -
             inner(ngrada / normgradb, nabla_grad(testb)) *
             inner(ngrada / normgrada, nabla_grad(triala)) -
             inner(ngradb / normgradb, nabla_grad(testb)) *
             (inner(ngradb / normgrada, nabla_grad(triala)) -
              inner(ngrada, ngradb) *
              inner(ngrada / normgrada, nabla_grad(triala))))) * dx
        #
        self.hessian = wkform11 + wkform22 + wkform12 + wkform21
        self.precond = wkform11 + wkform22  #+ wkform12 + wkform21
Пример #28
0
#
# Next, various model parameters are defined::


# Model parameters
lmbda = 1.0e-02  # surface parameter
dt = 5.0e-06  # time step
theta = 0.5      # time stepping family, e.g. theta=1 -> backward Euler, theta=0.5 -> Crank-Nicolson

# A unit square mesh with 97 (= 96 + 1) vertices in each direction is
# created, and on this mesh a
# :py:class:`FunctionSpace<dolfin.functions.functionspace.FunctionSpace>`
# ``ME`` is built using a pair of linear Lagrangian elements. ::

# Create mesh and build function space
mesh = UnitSquareMesh(MPI.comm_world, 96, 96, CellType.Type.triangle)
P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
ME = FunctionSpace(mesh, P1 * P1)

# Trial and test functions of the space ``ME`` are now defined::

# Define trial and test functions
du = TrialFunction(ME)
q, v = TestFunctions(ME)

# .. index:: split functions
#
# For the test functions,
# :py:func:`TestFunctions<dolfin.functions.function.TestFunctions>` (note
# the 's' at the end) is used to define the scalar test functions ``q``
# and ``v``. The
Пример #29
0
def meshes_p1():
    return UnitIntervalMesh(10), UnitSquareMesh(3, 3), UnitCubeMesh(2, 2, 2)
Пример #30
0
 def get(self):
     """Built in mesh."""
     x = self.pad(self.values)
     return UnitSquareMesh(x[0], x[1], self.diag[x[2]])
Пример #31
0
def test_krylov_reuse_pc():
    "Test preconditioner re-use with PETScKrylovSolver"

    # Define problem
    mesh = UnitSquareMesh(MPI.comm_world, 8, 8)
    V = FunctionSpace(mesh, 'Lagrange', 1)
    bc = DirichletBC(V, Constant(0.0), lambda x, on_boundary: on_boundary)
    u = TrialFunction(V)
    v = TestFunction(V)

    # Forms
    a, L = inner(grad(u), grad(v)) * dx, dot(Constant(1.0), v) * dx

    A, P = PETScMatrix(), PETScMatrix()
    b = PETScVector()

    # Assemble linear algebra objects
    assemble(a, tensor=A)  # noqa
    assemble(a, tensor=P)  # noqa
    assemble(L, tensor=b)  # noqa

    # Apply boundary conditions
    bc.apply(A)
    bc.apply(P)
    bc.apply(b)

    # Create Krysolv solver and set operators
    solver = PETScKrylovSolver("gmres", "bjacobi")
    solver.set_operators(A, P)

    # Solve
    x = PETScVector()
    num_iter_ref = solver.solve(x, b)

    # Change preconditioner matrix (bad matrix) and solve (PC will be
    # updated)
    a_p = u * v * dx
    assemble(a_p, tensor=P)  # noqa
    bc.apply(P)
    x = PETScVector()
    num_iter_mod = solver.solve(x, b)
    assert num_iter_mod > num_iter_ref

    # Change preconditioner matrix (good matrix) and solve (PC will be
    # updated)
    a_p = a
    assemble(a_p, tensor=P)  # noqa
    bc.apply(P)
    x = PETScVector()
    num_iter = solver.solve(x, b)
    assert num_iter == num_iter_ref

    # Change preconditioner matrix (bad matrix) and solve (PC will not
    # be updated)
    solver.set_reuse_preconditioner(True)
    a_p = u * v * dx
    assemble(a_p, tensor=P)  # noqa
    bc.apply(P)
    x = PETScVector()
    num_iter = solver.solve(x, b)
    assert num_iter == num_iter_ref

    # Update preconditioner (bad PC, will increase iteration count)
    solver.set_reuse_preconditioner(False)
    x = PETScVector()
    num_iter = solver.solve(x, b)
    assert num_iter == num_iter_mod
Пример #32
0
def structured_mesh_2d():
    return UnitSquareMesh(3, 3)
Пример #33
0
def test_UnitQuadMesh():
    mesh = UnitSquareMesh(MPI.comm_world, 5, 7, CellType.Type.quadrilateral)
    assert mesh.num_entities_global(0) == 48
    assert mesh.num_entities_global(2) == 35
    assert mesh.geometry.dim == 2
Пример #34
0
def test_RefineUnitSquareMesh():
    """Refine mesh of unit square."""
    mesh = UnitSquareMesh(MPI.comm_world, 5, 7)
    mesh = refine(mesh, False)
    assert mesh.num_entities_global(0) == 165
    assert mesh.num_entities_global(2) == 280
Пример #35
0
def test_UnitSquareMeshDistributed():
    """Create mesh of unit square."""
    mesh = UnitSquareMesh(MPI.comm_world, 5, 7)
    assert mesh.num_entities_global(0) == 48
    assert mesh.num_entities_global(2) == 70
    assert mesh.geometry.dim == 2
Пример #36
0
def test_UnitSquareMeshLocal():
    """Create mesh of unit square."""
    mesh = UnitSquareMesh(MPI.comm_self, 5, 7)
    assert mesh.num_entities(0) == 48
    assert mesh.num_cells() == 70
    assert mesh.geometry.dim == 2
Пример #37
0
def mesh():
    return UnitSquareMesh(MPI.comm_world, 3, 3)
Пример #38
0
 def __init__(self, Th):
     mesh = UnitSquareMesh(Th, Th)
     self.V = FunctionSpace(mesh, "Lagrange", 1)
     u = TrialFunction(self.V)
     v = TestFunction(self.V)
     self.a = lambda k: k * inner(grad(u), grad(v)) * dx
Пример #39
0
        # Build translational null space basis
        V.sub(0).dofmap().set(basis[0], 1.0)
        V.sub(1).dofmap().set(basis[1], 1.0)

        # Build rotational null space basis
        V.sub(0).set_x(basis[2], -1.0, 1)
        V.sub(1).set_x(basis[2], 1.0, 0)

        # Add vector that is not in nullspace
        V.sub(1).set_x(basis[3], 1.0, 1)

    return la.VectorSpaceBasis(nullspace_basis)


@pytest.mark.parametrize("mesh", [
    UnitSquareMesh(MPI.comm_world, 12, 13),
    UnitCubeMesh(MPI.comm_world, 12, 18, 15)
])
@pytest.mark.parametrize("degree", [1, 2])
def test_nullspace_orthogonal(mesh, degree):
    """Test that null spaces orthogonalisation"""
    V = VectorFunctionSpace(mesh, ('Lagrange', degree))
    null_space = build_elastic_nullspace(V)
    assert not null_space.is_orthogonal()
    assert not null_space.is_orthonormal()

    null_space.orthonormalize()
    assert null_space.is_orthogonal()
    assert null_space.is_orthonormal()

Пример #40
0
    def __init__(self):
        n = 40
        self.mesh = UnitSquareMesh(n, n, "crossed")

        # Define mesh and boundaries.
        class LeftBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[0] < DOLFIN_EPS

        class RightBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[0] > 1.0 - DOLFIN_EPS

        class LowerBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[1] < DOLFIN_EPS

        class UpperBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[1] > 1.0 - DOLFIN_EPS

        class RestrictedUpperBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return (
                    on_boundary
                    and x[1] > 1.0 - DOLFIN_EPS
                    and DOLFIN_EPS < x[0]
                    and x[0] < 0.5 - DOLFIN_EPS
                )

        left = LeftBoundary()
        right = RightBoundary()
        lower = LowerBoundary()
        upper = UpperBoundary()
        # restricted_upper = RestrictedUpperBoundary()

        # Be particularly careful with the boundary conditions.
        # The main problem here is that the PPE system is consistent if and
        # only if
        #
        #     \int_\Omega div(u) = \int_\Gamma n.u = 0.
        #
        # This is exactly and even pointwise fulfilled for the continuous
        # problem.  In the discrete case, we can have to make sure that n.u is
        # 0 all along the boundary.
        # In the lid-driven cavity problem, of particular interest are the
        # corner points at the lid. One has to assert that the z-component of u
        # is 0 all across the lid, and the x-component of u is 0 everywhere but
        # the lid.  Since u is L2-"continuous", the lid condition on u_x must
        # not be enforced in the corner points. The u_y component must be
        # enforced all over the lid, including the end points.
        V_element = FiniteElement("CG", self.mesh.ufl_cell(), 2)
        self.W = FunctionSpace(self.mesh, V_element * V_element)

        self.u_bcs = [
            DirichletBC(self.W, (0.0, 0.0), left),
            DirichletBC(self.W, (0.0, 0.0), right),
            # DirichletBC(self.W.sub(0), Expression('x[0]'), restricted_upper),
            DirichletBC(self.W, (0.0, 0.0), lower),
            DirichletBC(self.W.sub(0), Constant("1.0"), upper),
            DirichletBC(self.W.sub(1), 0.0, upper),
            # DirichletBC(self.W.sub(0), Constant('-1.0'), lower),
            # DirichletBC(self.W.sub(1), 0.0, lower),
            # DirichletBC(self.W.sub(1), Constant('1.0'), left),
            # DirichletBC(self.W.sub(0), 0.0, left),
            # DirichletBC(self.W.sub(1), Constant('-1.0'), right),
            # DirichletBC(self.W.sub(0), 0.0, right),
        ]
        self.P = FunctionSpace(self.mesh, "CG", 1)
        self.p_bcs = []
        return
Пример #41
0
def mesh(Nx=50, Ny=50, **params):
    m = UnitSquareMesh(Nx, Ny)
    x = m.coordinates()
    # x[:] = (x - 0.5) * 2
    # x[:] = 0.5*(cos(pi*(x-1.) / 2.) + 1.)
    return m
Пример #42
0
def mesh(Nx=160, Ny=160, **params):
    m = UnitSquareMesh(Nx, Ny)
    x = m.coordinates()
    #x[:] = (x - 0.5) * 2
    #x[:] = 0.5*(cos(pi*(x-1.) / 2.) + 1.)
    return m
Пример #43
0
"Finite Element Analysis of Acoustic Scattering" p138-139 '''

# Copyright (C) 2018 Samuel Groth
#
# This file is part of DOLFIN (https://www.fenicsproject.org)
#
# SPDX-License-Identifier:    LGPL-3.0-or-later

# Wavenumber
k0 = 20
# approximation space polynomial degree
deg = 1
# number of elements in each direction of mesh
n_elem = 128

mesh = UnitSquareMesh(MPI.comm_world, n_elem, n_elem)
n = FacetNormal(mesh)

# Incident plane wave
theta = np.pi / 8
ui = Expression('exp(j*k0*(cos(theta)*x[0] + sin(theta)*x[1]))',
                k0=k0,
                theta=theta,
                degree=deg + 3,
                domain=mesh.ufl_domain())

# Test and trial function space
V = FunctionSpace(mesh, "Lagrange", deg)

# Define variational problem
u = TrialFunction(V)
Пример #44
0
 def init_matrix(A):
     mesh = UnitSquareMesh(12, 12)
     V = FunctionSpace(mesh, "Lagrange", 1)
     u, v = TrialFunction(V), TestFunction(V)
     assemble(u * v * dx, tensor=A)
Пример #45
0
def square():
    return UnitSquareMesh(MPI.comm_world, 5, 5)
Пример #46
0
 def __init__(self, Th, Q):
     self.Q = Q
     mesh = UnitSquareMesh(Th, Th)
     self.V = FunctionSpace(mesh, "Lagrange", 1)
     v = TestFunction(self.V)
     self.f = lambda g: g*v*dx
Пример #47
0
rho = 1.0
c = np.sqrt(lam / rho)
tf = 0.2 / c  # Final time
exact_expr = Expression(\
'(pow(t,2)-(pow(x[0]-0.5,2)+pow(x[1]-0.5,2)))*(sqrt(pow(x[0]-0.5,2)+pow(x[1]-0.5,2))<=t)', \
t=tf)


def source(tt):
    return Expression('6*(sqrt(pow(x[0]-0.5,2)+pow(x[1]-0.5,2))<=t)', t=tt)


for Nxy in NN:
    h = 1. / Nxy
    print '\n\th = {}'.format(h)
    mesh = UnitSquareMesh(Nxy, Nxy, "crossed")
    q = 1  # Polynomial order
    V = FunctionSpace(mesh, 'Lagrange', q)
    Dt = h / (q * 5. * c)

    Wave = AcousticWave({'V': V, 'Vl': V, 'Vr': V})
    Wave.timestepper = 'backward'
    Wave.lump = True
    #Wave.verbose = True
    Wave.exact = interpolate(exact_expr, V)
    Wave.update({'lambda':lam, 'rho':rho, 't0':0.0, 'tf':tf, 'Dt':Dt,\
    'u0init':Function(V), 'utinit':Function(V)})
    test = TestFunction(V)

    def srcterm(tt):
        src_expr = source(tt)
Пример #48
0
 def __init__(self, Th, N):
     self.N = N
     mesh = UnitSquareMesh(Th, Th)
     self.V = FunctionSpace(mesh, "Lagrange", 1)
Пример #49
0
def cmscr1dnewton(img: np.array, alpha0: float, alpha1: float, alpha2: float,
                  alpha3: float, beta: float) \
                  -> (np.array, np.array, float, float, bool):
    """Same as cmscr1d but doesn't use FEniCS Newton method.

    Args:
        img (np.array): A 1D image sequence of shape (m, n), where m is the
                        number of time steps and n is the number of pixels.
        alpha0 (float): The spatial regularisation parameter for v.
        alpha1 (float): The temporal regularisation parameter for v.
        alpha2 (float): The spatial regularisation parameter for k.
        alpha3 (float): The temporal regularisation parameter for k.
        beta (float): The parameter for convective regularisation.

    Returns:
        v: A velocity array of shape (m, n).
        k: A source array of shape (m, n).
        res (float): The residual.
        fun (float): The function value.
        converged (bool): True if Newton's method converged.

    """
    # Create mesh.
    [m, n] = img.shape
    mesh = UnitSquareMesh(m - 1, n - 1)

    # Define function space and functions.
    W = VectorFunctionSpace(mesh, 'CG', 1, dim=2)
    w = Function(W)
    v, k = split(w)
    w1, w2 = TestFunctions(W)

    # Convert image to function.
    V = FunctionSpace(mesh, 'CG', 1)
    f = Function(V)
    f.vector()[:] = dh.img2funvec(img)

    # Define derivatives of data.
    ft = Function(V)
    ftv = np.diff(img, axis=0) * (m - 1)
    ftv = np.concatenate((ftv, ftv[-1, :].reshape(1, n)), axis=0)
    ft.vector()[:] = dh.img2funvec(ftv)

    fx = Function(V)
    fxv = np.gradient(img, 1 / (n - 1), axis=1)
    fx.vector()[:] = dh.img2funvec(fxv)

    # Define weak formulation.
    F = - (ft + fx*v + f*v.dx(1) - k) * (fx*w1 + f*w1.dx(1))*dx \
        - alpha0*v.dx(1)*w1.dx(1)*dx - alpha1*v.dx(0)*w1.dx(0)*dx \
        - beta*k.dx(1)*(k.dx(0) + k.dx(1)*v)*w1*dx \
        + (ft + fx*v + f*v.dx(1) - k)*w2*dx \
        - alpha2*k.dx(1)*w2.dx(1)*dx - alpha3*k.dx(0)*w2.dx(0)*dx \
        - beta*(k.dx(0)*w2.dx(0) + k.dx(1)*v*w2.dx(0)
                + k.dx(0)*v*w2.dx(1) + k.dx(1)*v*v*w2.dx(1))*dx

    # Define derivative.
    dv, dk = TrialFunctions(W)
    J = - (fx*dv + f*dv.dx(1) - dk)*(fx*w1 + f*w1.dx(1))*dx \
        - alpha0*dv.dx(1)*w1.dx(1)*dx - alpha1*dv.dx(0)*w1.dx(0)*dx \
        - beta*(k.dx(1)*(dk.dx(0) + dk.dx(1)*v) + k.dx(1)**2*dv
                + dk.dx(1)*(k.dx(0) + k.dx(1)*v))*w1*dx \
        + (fx*dv + f*dv.dx(1) - dk)*w2*dx \
        - alpha2*dk.dx(1)*w2.dx(1)*dx - alpha3*dk.dx(0)*w2.dx(0)*dx \
        - beta*(dv*k.dx(1) + dk.dx(0) + v*dk.dx(1))*w2.dx(0)*dx \
        - beta*(dv*k.dx(0) + 2*v*dv*k.dx(1) + v*dk.dx(0)
                + v*v*dk.dx(1))*w2.dx(1)*dx

    # Alternatively, use automatic differentiation.
    # J = derivative(F, w)

    # Define algorithm parameters.
    tol = 1e-10
    maxiter = 100

    # Define increment.
    dw = Function(W)

    # Run Newton iteration.
    niter = 0
    eps = 1
    res = 1
    while res > tol and niter < maxiter:
        niter += 1

        # Solve for increment.
        solve(J == -F, dw)

        # Update solution.
        w.assign(w + dw)

        # Compute norm of increment.
        eps = dw.vector().norm('l2')

        # Compute norm of residual.
        a = assemble(F)
        res = a.norm('l2')

        # Print statistics.
        print("Iteration {0} eps={1} res={2}".format(niter, eps, res))

    # Split solution.
    v, k = w.split(deepcopy=True)

    # Evaluate and print residual and functional value.
    res = abs(ft + fx * v + f * v.dx(1) - k)
    fun = 0.5 * (res**2 + alpha0 * v.dx(1)**2 + alpha1 * v.dx(0)**2 +
                 alpha2 * k.dx(1)**2 + alpha3 * k.dx(0)**2 + beta *
                 (k.dx(0) + k.dx(1) * v)**2)
    print('Res={0}, Func={1}'.format(assemble(res * dx), assemble(fun * dx)))

    # Convert back to array.
    vel = dh.funvec2img(v.vector().get_local(), m, n)
    k = dh.funvec2img(k.vector().get_local(), m, n)
    return vel, k, assemble(res * dx), assemble(fun * dx), res > tol
Пример #50
0
    def __init__(self, Vm, parameters=[]):
        """ Vm = FunctionSpace for the parameters m1, and m2 """
        self.parameters = {}
        self.parameters['k'] = 1.0
        self.parameters['eps'] = 1e-2
        self.parameters['correctcost'] = True
        self.parameters.update(parameters)
        k = self.parameters['k']
        eps = self.parameters['eps']

        self.m1 = Function(Vm)
        self.m2 = Function(Vm)
        self.m1h = Function(Vm)
        self.m2h = Function(Vm)
        VmVm = createMixedFS(Vm, Vm)
        self.m12h = Function(VmVm)
        testm = TestFunction(VmVm)
        testm1, testm2 = testm
        trialm = TrialFunction(VmVm)
        trialm1, trialm2 = trialm

        # cost function
        normm1 = inner(nabla_grad(self.m1), nabla_grad(self.m1))
        normm2 = inner(nabla_grad(self.m2), nabla_grad(self.m2))
        TVnormsq = normm1 + normm2 + Constant(eps)
        TVnorm = sqrt(TVnormsq)
        if self.parameters['correctcost']:
            meshtmp = UnitSquareMesh(Vm.mesh().mpi_comm(), 10, 10)
            Vtmp = FunctionSpace(meshtmp, 'CG', 1)
            x = SpatialCoordinate(meshtmp)
            correctioncost = 1. / assemble(sqrt(4.0 * x[0] * x[0]) * dx)
            print '[VTV] correction cost with factor={}'.format(correctioncost)
        else:
            correctioncost = 1.0
        self.wkformcost = Constant(k * correctioncost) * TVnorm * dx

        # gradient
        gradm1 = Constant(k) / TVnorm * inner(nabla_grad(self.m1),
                                              nabla_grad(testm1)) * dx
        gradm2 = Constant(k) / TVnorm * inner(nabla_grad(self.m2),
                                              nabla_grad(testm2)) * dx
        self.gradm = gradm1 + gradm2

        # Hessian
        H11 = Constant(k)/TVnorm*(inner(nabla_grad(trialm1), nabla_grad(testm1)) - \
        inner(nabla_grad(testm1),nabla_grad(self.m1))* \
        inner(nabla_grad(self.m1), nabla_grad(trialm1))/TVnormsq)*dx
        H12 = -Constant(k)/(TVnorm*TVnormsq)*(inner(nabla_grad(testm1),nabla_grad(self.m1))* \
        inner(nabla_grad(self.m2), nabla_grad(trialm2)))*dx
        H21 = -Constant(k)/(TVnorm*TVnormsq)*(inner(nabla_grad(testm2),nabla_grad(self.m2))* \
        inner(nabla_grad(self.m1), nabla_grad(trialm1)))*dx
        H22 = Constant(k)/TVnorm*(inner(nabla_grad(trialm2), nabla_grad(testm2)) - \
        inner(nabla_grad(testm2),nabla_grad(self.m2))* \
        inner(nabla_grad(self.m2), nabla_grad(trialm2))/TVnormsq)*dx
        self.hessian = H11 + H12 + H21 + H22

        # for preconditioning
        self.amgprecond = amg_solver()
        M = assemble(inner(testm, trialm) * dx)
        factM = 1e-2 * k
        self.sMass = M * factM
Пример #51
0
def cmscr1d_img(img: np.array,
                alpha0: float, alpha1: float,
                alpha2: float, alpha3: float,
                beta: float, deriv, mesh=None, bc='natural') \
                -> (np.array, np.array, float, float, bool):
    """Computes the L2-H1 mass conserving flow with source for a 1D image
    sequence with spatio-temporal and convective regularisation.

    Allows to specify how to approximate partial derivatives of f numerically.

    Args:
        img (np.array): 1D image sequence of shape (m, n), where m is the
                        number of time steps and n is the number of pixels.
        alpha0 (float): The spatial regularisation parameter for v.
        alpha1 (float): The temporal regularisation parameter for v.
        alpha2 (float): The spatial regularisation parameter for k.
        alpha3 (float): The temporal regularisation parameter for k.
        beta (float): The convective regularisation parameter.
        deriv (str): Specifies how to approximate pertial derivatives.
                     When set to 'mesh' it uses FEniCS built in function.
                     When set to 'fd' it uses finite differences.
        mesh: A custom mesh (optional). Must have (m - 1, n - 1) cells.
        bc (str): One of {'natural', 'zero', 'zerospace'} for boundary
                    conditions for the velocity v (optional).

    Returns:
        v (np.array): A velocity array of shape (m, n).
        k (np.array): A source array of shape (m, n).
        res (float): The residual.
        fun (float): The function value.
        converged (bool): True if Newton's method converged.

    """
    # Check for valid arguments.
    valid = {'mesh', 'fd'}
    if deriv not in valid:
        raise ValueError("Argument 'deriv' must be one of %r." % valid)

    # Create mesh.
    m, n = img.shape
    if mesh is None:
        mesh = UnitSquareMesh(m - 1, n - 1)

    # Define function spaces.
    V = dh.create_function_space(mesh, 'default')
    W = dh.create_vector_function_space(mesh, 'default')

    # Convert array to function.
    f = Function(V)
    f.vector()[:] = dh.img2funvec(img)

    # Compute partial derivatives.
    if deriv is 'mesh':
        ft, fx = f.dx(0), f.dx(1)
    if deriv is 'fd':
        imgt, imgx = nh.partial_derivatives(img)
        ft, fx = Function(V), Function(V)
        ft.vector()[:] = dh.img2funvec(imgt)
        fx.vector()[:] = dh.img2funvec(imgx)

    # Check for valid arguments.
    valid = {'natural', 'zero', 'zerospace'}
    if bc not in valid:
        raise ValueError("Argument 'bc' must be one of %r." % valid)

    # Define boundary conditions for velocity.
    if bc is 'natural':
        bc = []
    if bc is 'zero':
        bc = DirichletBC(W.sub(0), Constant(0), dh.DirichletBoundary())
    if bc is 'zerospace':
        bc = DirichletBC(W.sub(0), Constant(0), dh.DirichletBoundarySpace())

    # Compute velocity.
    v, k, res, fun, converged = cmscr1d_weak_solution(W,
                                                      f,
                                                      ft,
                                                      fx,
                                                      alpha0,
                                                      alpha1,
                                                      alpha2,
                                                      alpha3,
                                                      beta,
                                                      bcs=bc)

    # Convert back to array and return.
    v = dh.funvec2img(v.vector().get_local(), m, n)
    k = dh.funvec2img(k.vector().get_local(), m, n)
    return v, k, res, fun, converged
Пример #52
0
def test_hash():
    h1 = UnitSquareMesh(MPI.comm_world, 4, 4).hash()
    h2 = UnitSquareMesh(MPI.comm_world, 4, 5).hash()
    h3 = UnitSquareMesh(MPI.comm_world, 4, 4).hash()
    assert h1 == h3
    assert h1 != h2
Пример #53
0
                    TrialFunction, UnitSquareMesh, has_petsc_complex,
                    interpolate, solve)
from dolfin.fem.assemble import assemble_scalar
from dolfin.io import XDMFFile
from ufl import dx, grad, inner

# wavenumber
k0 = 4 * np.pi

# approximation space polynomial degree
deg = 1

# number of elements in each direction of mesh
n_elem = 128

mesh = UnitSquareMesh(MPI.comm_world, n_elem, n_elem)
n = FacetNormal(mesh)

# Source amplitude
if has_petsc_complex:
    A = 1 + 1j
else:
    A = 1


def source(values, x):
    values[:, 0] = A * k0**2 * np.cos(k0 * x[:, 0]) * np.cos(k0 * x[:, 1])


# Test and trial function space
V = FunctionSpace(mesh, ("Lagrange", deg))
Пример #54
0
def test_GetCoordinates():
    """Get coordinates of vertices"""
    mesh = UnitSquareMesh(MPI.comm_world, 5, 5)
    assert len(mesh.geometry.points) == 36
Пример #55
0
def test_GetCells():
    """Get cells of mesh"""
    mesh = UnitSquareMesh(MPI.comm_world, 5, 5)
    assert MPI.sum(mesh.mpi_comm(), len(mesh.cells())) == 50
def mesh():
    return UnitSquareMesh(4, 4)
Пример #57
0
def mesh():
    return UnitSquareMesh(10, 10)