Esempio n. 1
0
def test_build_mesh():
    """
    Create a few meshes, extract the vertices and cells from them and pass them
    to build_mesh() to rebuild the mesh. Then check that the result is the same
    as the original.
    """
    def assert_mesh_builds_correctly(mesh):
        coords = mesh.coordinates()
        cells = mesh.cells()
        mesh_new = build_mesh(coords, cells)
        assert np.allclose(coords, mesh_new.coordinates())
        assert np.allclose(cells, mesh_new.cells())

    mesh1 = df.RectangleMesh(df.Point(0, 0), df.Point(20, 10), 12, 8)
    assert_mesh_builds_correctly(mesh1)

    mesh2_temp = mshr.Circle(df.Point(2.0, -3.0), 10)
    mesh2 = mshr.generate_mesh(mesh2_temp, 10)
    assert_mesh_builds_correctly(mesh2)

    mesh3 = df.BoxMesh(df.Point(0, 0, 0), df.Point(20, 10, 5), 12, 8, 3)
    assert_mesh_builds_correctly(mesh3)

    mesh4_temp = mshr.Sphere(df.Point(2.0, 3.0, -4.0), 10)
    mesh4 = mshr.generate_mesh(mesh4_temp, 10)
    assert_mesh_builds_correctly(mesh4)
Esempio n. 2
0
        def test_mesh_diameter(self):

            mesh = UnitSquareMesh(10, 7)
            d = mesh_diameter(mesh)
            self.assertAlmostEqual(d, 2.0**0.5)

            mesh = UnitCubeMesh(3, 4, 5)
            d = mesh_diameter(mesh)
            self.assertAlmostEqual(d, 3.0**0.5)

            try:
                import mshr
            except ImportError:
                warning("mshr not available; skipping some tests of "
                        "'mesh_diameter'...")
            else:

                b0 = mshr.Rectangle(Point(0.0, 0.0), Point(0.5, 1.0))
                b1 = mshr.Rectangle(Point(0.0, 0.0), Point(1.0, 0.5))
                lshape = b0 + b1
                mesh = mshr.generate_mesh(lshape, 10)
                d = mesh_diameter(mesh)
                self.assertAlmostEqual(d, 2.0**0.5)

                s = mshr.Sphere(Point(100.0, -666666.6, 1e10), 4.0, 5)
                mesh = mshr.generate_mesh(s, 5)
                d = mesh_diameter(mesh)
                self.assertAlmostEqual(d, 8.0, 0)
Esempio n. 3
0
    def __init__(self, domain, domain1, domain2, mesh_resolution, boundaries,
                 polynomial_degree, adjust):
        self.domain = domain
        self.domain1 = domain1
        self.domain2 = domain2
        self.left = domain1 - domain2
        self.right = domain2 - domain1
        self.overlap_domain = domain - (self.left + self.right)
        self.mesh_resolution = mesh_resolution
        self.mesh = mshr.generate_mesh(domain, mesh_resolution)
        self.mesh1 = mshr.generate_mesh(domain1, mesh_resolution / 2)
        self.mesh2 = mshr.generate_mesh(domain2, mesh_resolution / 2)
        self.overlap_mesh = mshr.generate_mesh(self.overlap_domain,
                                               mesh_resolution)

        self.insides = boundaries[0]
        self.left_robin = boundaries[1]
        self.right_robin = boundaries[2]

        self.adjustment = adjust
        self.p = polynomial_degree
        self.VO = FunctionSpace(self.overlap_mesh, "Lagrange", self.p)

        self.K, self.M, self.V = self.assemble_matrices(self.mesh)
        self.K1, self.M1, self.V1 = self.assemble_matrices(self.mesh1)
        self.K2, self.M2, self.V2 = self.assemble_matrices(self.mesh2)
Esempio n. 4
0
def get_geometry(domain_part):
    nx = 5
    ny = 10
    low_resolution = 5
    high_resolution = 5
    n_vertices = 20

    if domain_part is DomainPart.LEFT:
        nx = nx * 3
    elif domain_part is DomainPart.RIGHT:
        ny = ny * 2
    elif domain_part is DomainPart.CIRCULAR:
        n_vertices = n_vertices
    elif domain_part is DomainPart.RECTANGLE:
        n_vertices = n_vertices
    else:
        raise Exception("invalid domain_part: {}".format(domain_part))

    if domain_part is DomainPart.LEFT or domain_part is DomainPart.RIGHT:
        if domain_part is DomainPart.LEFT:
            p0 = Point(x_left, y_bottom)
            p1 = Point(x_coupling, y_top)
        elif domain_part is DomainPart.RIGHT:
            p0 = Point(x_coupling, y_bottom)
            p1 = Point(x_right, y_top)
        else:
            raise Exception("invalid control flow!")
        mesh = RectangleMesh(p0, p1, nx, ny)
        coupling_boundary = StraightBoundary()
        remaining_boundary = ExcludeStraightBoundary()

    elif domain_part is DomainPart.CIRCULAR or domain_part is DomainPart.RECTANGLE:
        p0 = Point(x_left, y_bottom)
        p1 = Point(x_right, y_top)
        whole_domain = mshr.Rectangle(p0, p1)
        if domain_part is DomainPart.CIRCULAR:
            circular_domain = mshr.Circle(midpoint, radius, n_vertices)
            mesh = mshr.generate_mesh(circular_domain, high_resolution, "cgal")
        elif domain_part is DomainPart.RECTANGLE:
            circular_domain = mshr.Circle(midpoint, radius, n_vertices)
            mesh = mshr.generate_mesh(whole_domain - circular_domain,
                                      low_resolution, "cgal")
        else:
            raise Exception("invalid control flow!")
        coupling_boundary = CircleBoundary()
        remaining_boundary = ExcludeCircleBoundary()

    else:
        raise Exception("invalid control flow!")

    return mesh, coupling_boundary, remaining_boundary
Esempio n. 5
0
 def shape(self, mesh, size=50):
     """Build mesh."""
     vf = np.vectorize(self.f)
     x = mesh.coordinates()[:, 0]
     y = mesh.coordinates()[:, 1]
     a = np.arctan2(y, x)
     x, y = [x * vf(a), y * vf(a)]
     mesh.coordinates()[:] = np.array([x, y]).transpose()
     boundary = BoundaryMesh(mesh, 'exterior')
     boundary.init()
     lst = [0]
     vs = list(vertices(boundary))
     while True:
         v = vs[lst[-1]]
         neighbors = set()
         for e in edges(v):
             neighbors.update(e.entities(0))
         neighbors.remove(v.index())
         neighbors = list(neighbors)
         k = 0
         if len(lst) > 1:
             if neighbors[0] == lst[-2]:
                 k = 1
         lst.append(neighbors[k])
         if lst[-1] == lst[0]:
             break
     lst = lst[:-1]
     points = boundary.coordinates()[lst]
     points = [Point(*p) for p in points]
     try:
         polygon = Polygon(points)
     except:
         polygon = Polygon(points[::-1])
     return generate_mesh(polygon, size)
Esempio n. 6
0
def test_CarstensenKlose(p, N):
    from dolfintape.demo_problems.exact_solutions import pLaplace_CarstensenKlose
    from dolfintape.mesh_fixup import mesh_fixup
    import mshr

    label = 'CarstensenKlose_%s_%02d' % (p, N)

    # Build mesh on L-shaped domain (-1, 1)^2 \ (0, 1)*(-1, 0)
    b0 = mshr.Rectangle(Point(-1.0, -1.0), Point(1.0, 1.0))
    b1 = mshr.Rectangle(Point(0.0, -1.0), Point(1.0, 0.0))
    mesh = mshr.generate_mesh(b0 - b1, N)
    mesh = mesh_fixup(mesh)
    print("num cells %s" % mesh.num_cells())
    plot_cutoff_distribution(p, mesh, label)

    # Fetch exact solution and rhs of p-Laplacian
    u, f = pLaplace_CarstensenKlose(p=p, eps=0.0, delta=7.0/8,
                                    domain=mesh, degree=4)
    # There are some problems with quadrature element,
    # see https://bitbucket.org/fenics-project/ffc/issues/84,
    # so precompute (f, vh) for vh from P1
    f = project(f, FunctionSpace(mesh, 'Lagrange', 1),
                form_compiler_parameters=
                    {'quadrature_degree': f.ufl_element().degree()})
    f.set_allow_extrapolation(True)

    # Now the heavy lifting
    result = compute_liftings(label, p, mesh, f, u)
    uh, glob, loc, ee, fe = result[0:5]

    # Report
    format_result('Carstensen--Klose', p, mesh.num_cells(), *result[5:])
    plot_liftings(glob, loc, ee, fe, label)
    save_functions(uh, glob, loc, ee, fe, label)
    list_timings(TimingClear_clear, [TimingType_wall])
Esempio n. 7
0
def box_mesh_with_hole(point1=Point(0, 0, 0),
                       point2=Point(2, 1, 1),
                       cyl_cent1=Point(1, -10, 0.5),
                       cyl_cent2=Point(1, 10, 0.5),
                       cyl_rad=0.25,
                       numpts=15):
    """
    generates a 3D box mesh with tetrahedral elements with a cylindrical hole in it

    input
    ------
        point1: Point coordinates in 3D corner_min of box
        point2: Point coordinates in 3D corner_max of box
        cyl_cent1: Point coordinates in 3D of center1 of Cylinder
        cyl_cent2: Point coordinates in 3D of center1 of Cylinder
        cyl_rad:   Radius of cylinder
        npts: Number of discretization points
    output:
    ------
        mesh: 3D FEniCS mesh with a cylindrical hole

    """
    Router = mshr.Box(point1, point2)
    Rinner = mshr.Cylinder(cyl_cent1, cyl_cent2, cyl_rad, cyl_rad)
    domain = Router - Rinner

    mesh = mshr.generate_mesh(domain, numpts)
    print_mesh_stats(mesh)

    return mesh
Esempio n. 8
0
def rectangle_mesh_with_hole(point1=Point(0, 0),
                             point2=Point(3, 1),
                             hole_cent=Point(1.5, 0.5),
                             hole_rad=0.25,
                             npts=15):
    """
    generates a triangulated Rectangular domain with a circular hole

    input
    ------
        point1: Point coordinates in 3D corner_min of box
        point2: Point coordinates in 3D corner_max of box
        cyl_cent1: Point coordinates in 3D of center1 of Cylinder
        cyl_cent2: Point coordinates in 3D of center1 of Cylinder
        cyl_rad:   Radius of cylinder
        npts:      number of discretization points
    output:
    ------
        mesh: 2D FEniCS mesh with circular hole

    """

    Router = mshr.Rectangle(point1, point2)
    Rinner = mshr.Circle(hole_cent, hole_rad)
    domain = Router - Rinner

    mesh = mshr.generate_mesh(domain, npts)
    print_mesh_stats(mesh)

    return mesh
def method(res=50, diameter=1., length=5., **kwargs):
    '''
    Function That Generates a mesh for a barbell capilar,
    Meshing method is mshr.

    Note: The generarted mesh is stored in "BERNAISE/meshes/".
    '''
    info("Generating mesh using the mshr tool.")

    inletdiameter = diameter * 5.
    inletlength = diameter * 4.

    # Define coners of "capilar"
    a = df.Point(-diameter / 2., -length / 2 - inletlength / 2.)
    b = df.Point(diameter / 2., length / 2 + inletlength / 2.)
    capilar = mshr.Rectangle(a, b)
    # Define coners of "leftbell
    c = df.Point(-inletdiameter / 2., -length / 2 - inletlength)
    d = df.Point(inletdiameter / 2., -length / 2)
    leftbell = mshr.Rectangle(c, d)
    # Define coners of "rightbell"
    e = df.Point(-inletdiameter / 2., length / 2)
    f = df.Point(inletdiameter / 2., length / 2 + inletlength)
    rightbell = mshr.Rectangle(e, f)

    domain = capilar + leftbell + rightbell
    mesh = mshr.generate_mesh(domain, res)
    meshpath = os.path.join(
        MESHES_DIR, "BarbellCapilarDolfin_d" + str(diameter) + "_l" +
        str(length) + "_res" + str(res))
    store_mesh_HDF5(mesh, meshpath)
Esempio n. 10
0
def generate_mesh():
    # Define domain
    x_min = 0
    x_max = 5
    y_min = 0
    y_max = 1.5

    xc = 0.7
    yc = 0.5 * (y_min + y_max)
    r = 0.2

    circle = mshr.Circle(Point(xc, yc), r)
    domain = mshr.Rectangle(Point(x_min, y_min), Point(x_max, y_max)) - circle

    # Create resolution
    mesh_res = 64

    # Create mesh
    mesh = mshr.generate_mesh(domain, mesh_res)

    # Save mesh
    File(os.path.join(DATA_DIR, 'mesh.xml.gz')) << mesh

    # Save dof coordinates
    V = FunctionSpace(mesh, 'P', 1)
    dof_coordinates = V.tabulate_dof_coordinates()
    np.save(os.path.join(DATA_DIR, 'coordinates.npy'), dof_coordinates)

    # Save dof triangles
    vertex2dof = vertex_to_dof_map(V)
    vertex2dof_vec = np.vectorize(lambda v: vertex2dof[v])
    dof_triangles = vertex2dof_vec(mesh.cells())
    np.save(os.path.join(DATA_DIR, 'triangles.npy'), dof_triangles)
Esempio n. 11
0
    def run(self):
        domain = self._create_domain()
        mesh = generate_mesh(domain, MESH_PTS)
        
        # fe.plot(mesh)
        # plt.show()

        self._create_boundary_expression()
        
        Omega = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
        R = fe.FiniteElement("Real", mesh.ufl_cell(), 0)
        W = fe.FunctionSpace(mesh, Omega*R)
        Theta, c = fe.TrialFunction(W)
        v, d = fe.TestFunctions(W)
        sigma = self.conductivity
        
        LHS = (sigma * fe.inner(fe.grad(Theta), fe.grad(v)) + c*v + Theta*d) * fe.dx
        RHS = self.boundary_exp * v * fe.ds

        w = fe.Function(W)
        fe.solve(LHS == RHS, w)
        Theta, c = w.split()
        print(c(0, 0))

        # fe.plot(Theta, "solution", mode='color', vmin=-3, vmax=3)
        # plt.show()

        plot(fe.interpolate(Theta, fe.FunctionSpace(mesh, Omega)), mode='color')
        plt.show()
Esempio n. 12
0
def mesh_Square(n=10, method='regular'):
    if method == 'mshr':
        dom = mshr.Rectangle(Point(-1., -1.), Point(1., 1.))
        mesh = mshr.generate_mesh(dom, n, "cgal")
    elif method == 'regular':
        mesh = RectangleMesh(Point(-1., -1.), Point(1., 1.), n, n)
    return mesh
Esempio n. 13
0
def solve_poisson_equation(u_e, alpha, title_name):
    domain = Circle(Point(0, 0), 1)
    mesh = generate_mesh(domain, 30)
    V = FunctionSpace(mesh, 'P', 2)

    u_d = Expression(ccode(u_e), degree=2)
    bc = DirichletBC(V, u_d, check_boundary)
    u = TrialFunction(V)
    v = TestFunction(V)

    f = -calculate_laplacian(u_e) + alpha * u_e
    f = Expression(ccode(f), degree=2)
    g = calculate_normal_derivative(u_e)
    g = Expression(ccode(g), degree=2)

    a = dot(grad(u), grad(v)) * dx + alpha * u * v * dx
    L = f * v * dx + g * v * ds
    u = Function(V)
    solve(a == L, u, bc)

    u_e = u_d
    error_L2 = errornorm(u_e, u, 'L2')
    vertex_values_u = u.compute_vertex_values(mesh)
    vertex_values_u_e = u_e.compute_vertex_values(mesh)
    error_max = np.max(np.abs(vertex_values_u_e - vertex_values_u))
    print('Max error = %.3g, L2 error = %.3g' % (error_max, error_L2))
    image = plot_solutions(u_e, u, mesh)
    imageio.imsave(f'poisson_{title_name}.png', image)
Esempio n. 14
0
def generate_mesh(name, par=40, refinement=False):
    info("Generating mesh {} ...".format(name))

    # construct mesh
    geometry = mshr.Rectangle(Point(0.0, 0.0), Point(gL, gW)) \
           - mshr.Circle(Point(gX, gY), g_radius, 20) \
           - mshr.Rectangle(Point(gX, gY - 0.5*gEH), Point(gX + g_radius + gEL, gY + 0.5*gEH))
    mesh = mshr.generate_mesh(geometry, par)

    if refinement:
        parameters["refinement_algorithm"] = "plaza_with_parent_facets"
        for k in range(2):  # 2
            cf = MeshFunction('bool', mesh, 2)
            cf.set_all(False)
            z = 0.2  #0.15 # 0.08
            for c in cells(mesh):
                if c.midpoint().distance(Point(gX, gY)) < (0.05 + k * z):
                    cf[c] = True
                elif (c.midpoint()[0] <= gX + g_radius + gEL + k*z and c.midpoint()[0] >= gX - k*z\
                 and c.midpoint()[1] <= gY + 0.5*gEH + k*z and c.midpoint()[1] >= gY - 0.5*gEH - k*z):
                    cf[c] = True
            mesh = refine(mesh, cf)

    mesh.init()

    # Save mesh
    if __version__[:4] == '2018':
        hdf5 = HDF5File(MPI.comm_world, name, 'w')
    else:
        hdf5 = HDF5File(mpi_comm_world(), name, 'w')
    hdf5.write(mesh, "/mesh")

    return mesh
Esempio n. 15
0
def main():
    "Generates the mesh"

    import mshr as m
    import dolfin as d
    import matplotlib.pyplot as plt

    d.set_log_level(13)  # PROGRESS

    r_1 = 0.5  # inner
    r_2 = 2.0  # outer
    res = 10  # resolution

    circle_inner = m.Circle(d.Point(0.0, 0.0), r_1)
    circle_outer = m.Circle(d.Point(0.0, 0.0), r_2)

    domain = circle_outer - circle_inner

    domain.set_subdomain(1, circle_inner)
    domain.set_subdomain(2, circle_outer)

    mesh = m.generate_mesh(domain, res)

    print("max edge length:", mesh.hmax())

    mesh_file_pvd = d.File("mesh.pvd")
    mesh_file_pvd.write(mesh)

    plt.figure()
    d.plot(mesh, title="Mesh")
    plt.show()
def make_metamaterial_mesh(
    L0,
    c1,
    c2,
    pore_radial_resolution,
    min_feature_size,
    resolution,
    n_cells,
    porosity,
):

    material_domain = None
    base_pore_points = None
    for i in range(n_cells):
        for j in range(n_cells):
            c1_ = c1[i, j] if isinstance(c1, np.ndarray) else c1
            c2_ = c2[i, j] if isinstance(c2, np.ndarray) else c2

            if isinstance(c1, np.ndarray) or base_pore_points is None:
                base_pore_points, radii, thetas = build_base_pore(
                    L0, c1_, c2_, pore_radial_resolution, porosity)

                verify_params(base_pore_points, radii, L0, min_feature_size)

            cell = make_cell(i, j, L0, base_pore_points)
            material_domain = (cell if material_domain is None else cell +
                               material_domain)

    return fa.Mesh(mshr.generate_mesh(material_domain, resolution * n_cells))
Esempio n. 17
0
def create_simple_mesh(Rint, Rout, resolution):
    # Create circles as Circle(Center, Radius)
    outer_circle = mshr.Circle(df.Point(0, 0), Rout)
    inner_circle = mshr.Circle(df.Point(0, 0), Rint)
    domain = outer_circle - inner_circle
    mesh = mshr.generate_mesh(domain, resolution)
    return mesh
Esempio n. 18
0
    def build_mesh(self, resolution=20):
        from mshr import Rectangle, Circle, generate_mesh

        domain = Rectangle(Point(0.0, 0.0), Point(self.L, self.L)) - Circle(
            Point(0.0, 0.0), self.radius
        )
        return generate_mesh(domain, resolution)
Esempio n. 19
0
 def shape(self, mesh, size=50):
     """Build mesh."""
     vf = np.vectorize(self.f)
     x = mesh.coordinates()[:, 0]
     y = mesh.coordinates()[:, 1]
     a = np.arctan2(y, x)
     x, y = [x * vf(a), y * vf(a)]
     mesh.coordinates()[:] = np.array([x, y]).transpose()
     boundary = BoundaryMesh(mesh, 'exterior')
     boundary.init()
     lst = [0]
     vs = list(vertices(boundary))
     while True:
         v = vs[lst[-1]]
         neighbors = set()
         for e in edges(v):
             neighbors.update(e.entities(0))
         neighbors.remove(v.index())
         neighbors = list(neighbors)
         k = 0
         if len(lst) > 1:
             if neighbors[0] == lst[-2]:
                 k = 1
         lst.append(neighbors[k])
         if lst[-1] == lst[0]:
             break
     lst = lst[:-1]
     points = boundary.coordinates()[lst]
     points = [Point(*p) for p in points]
     try:
         polygon = Polygon(points)
     except:
         polygon = Polygon(points[::-1])
     return generate_mesh(polygon, size)
Esempio n. 20
0
    def build_mesh(self):
        self.length = 100
        self.height = 100

        plate = mshr.Rectangle(fe.Point(0, 0),
                               fe.Point(self.length, self.height))
        notch = mshr.Polygon([
            fe.Point(0, self.height / 2 + 1),
            fe.Point(0, self.height / 2 - 1),
            fe.Point(6, self.height / 2)
        ])
        self.mesh = mshr.generate_mesh(plate - notch, 30)

        length = self.length
        height = self.height

        class Lower(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[1], 0)

        class Upper(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[1], height)

        class Corner(fe.SubDomain):
            def inside(self, x, on_boundary):
                return fe.near(x[0], 0) and fe.near(x[1], 0)

        self.lower = Lower()
        self.upper = Upper()
        self.corner = Corner()
Esempio n. 21
0
    def create_coronal_section_mesh(self, model_z_n=0):

        brain_slice = self.image_manipulation_obj.\
                get_brain_slice_from_model_z_n(model_z_n)

        x_size = 65
        self.boundary_points = brain_slice.\
                generate_boundary_points_ccw(x_size)
        domain_vertices = []

        for x, y in zip(self.boundary_points[0], self.boundary_points[1]):
            domain_vertices.append(fe.Point(x, y))

        self.geometry = mesher.Polygon(domain_vertices)
        self.mesh = mesher.generate_mesh(self.geometry, 16)

        self.compute_mesh_volume()
        self.original_volume = self.mesh_volume
        print('Original volume', self.original_volume)
        self.generate_holes()
        #self.compute_hole_fractional_volume()
        self.puncture_mesh()
        self.compute_mesh_volume()
        domain_volume = self.mesh_volume
        print('New volume', domain_volume)
        self.hole_fractional_volume = 1 - domain_volume / self.original_volume
        print('Hole fractional volume:', self.hole_fractional_volume)
        print('# holes:', self.n_holes)
        print('Estimated hole fractional volume:',\
                self.compute_hole_fractional_volume())
def generate_rectangle_mesh(mesh_resolution):
    # Generate domain and mesh
    xmin, xmax = -2, 2
    ymin, ymax = -2, 2
    mesh = generate_mesh(Rectangle(Point(xmin, ymin), Point(xmax, ymax)),
                         mesh_resolution)
    return mesh
Esempio n. 23
0
    def build_mesh(self):
        length = 60
        height = 30
        radius = 5
        plate = mshr.Rectangle(fe.Point(0, 0), fe.Point(length, height))
        circle1 = mshr.Circle(fe.Point(length/3, height/3), radius)
        circle2 = mshr.Circle(fe.Point(length*2/3, height*2/3), radius)
        material_domain = plate - circle1 - circle2
        self.mesh = mshr.generate_mesh(material_domain, 50)

        # Add dolfin-adjoint dependency
        self.mesh  = create_overloaded_object(self.mesh)

        class Left(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[0], 0)

        class Right(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[0], length)

        class Corner(fe.SubDomain):
            def inside(self, x, on_boundary):                    
                return fe.near(x[0], 0) and fe.near(x[1], 0)

        self.left = Left()
        self.right = Right()
        self.corner = Corner()
Esempio n. 24
0
def mesh_Triangle(n=10):
    dom = mshr.Polygon(
        [Point(0., -1.),
         Point(sqrt(3) / 2, 1. / 2),
         Point(-sqrt(3) / 2, 1. / 2)])
    mesh = mshr.generate_mesh(dom, n, "cgal")
    return mesh
Esempio n. 25
0
    def create_cocontinuous_mesh(self):

        if self.use_previously_stored_mesh:

            self.mesh = fe.Mesh(self.mesh_fname)
            print('Mesh has been loaded from file')
            return

        p = self.L * np.ones(3)
        geo     = mesher.Box(fe.Point(0,0,0), fe.Point(p))
        net     = self.extrude_base_net()
        columns = self.create_cylindrical_columns()
        net    += columns

        if self.keep_only_network: 
            geo  = net
        else:
            geo -= net

        print('Finished creating the geometry')
        self.mesh = mesher.generate_mesh(geo, self.mesh_density);

        print('Writing mesh to file')
        mesh_file = fe.File(self.mesh_fname)
        mesh_file << self.mesh
        print('Finished writing mesh to file')
Esempio n. 26
0
 def generate_mesh(self, typ, order, resolution):
     self._mesh = mshr.generate_mesh(self._domain, resolution)
     self.input['mesh'] = self._mesh
     self._V = FEN.FunctionSpace(self._mesh, typ, order)
     self.input['V'] = self._V
     self._u = FEN.TrialFunction(self._V)
     self._v = FEN.TestFunction(self._V)
Esempio n. 27
0
	def __init__(self, x0, y0, z0, R, n):
		class SphereSurface(SubDomain):
			def inside(self, x, on_boundary):
				return on_boundary
		class X_Symmetric(SubDomain):
			def inside(self, x, on_boundary):
				return near(x[0], x0)
		class Y_Symmetric(SubDomain):
			def inside(self, x, on_boundary):
				return near(x[1], y0)
		class Z_Symmetric(SubDomain):
			def inside(self, x, on_boundary):
				return near(x[2], z0)
		self.geometry = Sphere(Point(x0, y0, z0), R, segments=n) - Box(Point(x0 + R, y0, z0 - R), Point(x0 - R, y0 - R, z0 + R)) - Box(Point(x0 - R, y0 + R, z0), Point(x0 + R, y0, z0 - R)) - Box(Point(x0, y0, z0), Point(x0 - R, y0 + R, z0 + R))
		self.mesh = generate_mesh(self.geometry, n)
		self.domains = MeshFunction("size_t", self.mesh, self.mesh.topology().dim())
		self.domains.set_all(0)
		self.dx = Measure('dx', domain=self.mesh, subdomain_data=self.domains)
		self.boundaries = MeshFunction("size_t", self.mesh, self.mesh.topology().dim()-1)
		self.boundaries.set_all(0)
		self.sphereSurface = SphereSurface()
		self.sphereSurface.mark(self.boundaries, 1)
		self.x_symmetric = X_Symmetric()
		self.x_symmetric.mark(self.boundaries, 2)
		self.y_symmetric = Y_Symmetric()
		self.y_symmetric.mark(self.boundaries, 3)
		self.z_symmetric = Z_Symmetric()
		self.z_symmetric.mark(self.boundaries, 4)
		self.ds = Measure('ds', domain=self.mesh, subdomain_data=self.boundaries)
		self.dS = Measure('dS', domain=self.mesh, subdomain_data=self.boundaries)
Esempio n. 28
0
def initialise(dem, bounds, res):
    """
    Function to initialise the model space

    :param dem: 0 = no input DEM; 1 = input DEM
    :param bounds: west, south, east, north - if no DEM [0, 0, lx, ly]; if DEM [west, south, east, north]
    :param res: model resolution along the y-axis.
    :return model_space, u_n, mesh, V, bc:
    """

    if dem == 0:
        lx = bounds[1]
        ly = bounds[3]

        # Create mesh and define function space
        domain = Rectangle(Point(0, 0), Point(lx / ly, ly / ly))
        mesh = generate_mesh(domain, res)

        V = FunctionSpace(mesh, 'P', 1)

        # Define initial value
        u_D = Constant(0)
        eps = 10 / ly
        u_n = interpolate(u_D, V)
        u_n.vector().set_local(u_n.vector().get_local() +
                               eps * np.random.random(u_n.vector().size()))

    if dem == 1:
        u_n, lx, ly, mesh, V = read_dem(bounds, res)

    # boundary conditions

    class East(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], lx / ly)

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

    class North(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], ly / ly)

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

    # Should make this into an option!

    bc = [DirichletBC(V, u_n, West()), DirichletBC(V, u_n, East())]

    # def boundary(x, on_boundary):
    #   return on_boundary
    # bc = DirichletBC(V, u_n, boundary)

    model_space = [lx, ly, res]

    return model_space, u_n, mesh, V, bc
def spherical_shell(dim, radii, n_refinements=0):
    """
    Creates the mesh of a spherical shell using the mshr module.
    """
    assert isinstance(dim, int)
    assert dim == 2 or dim == 3

    assert isinstance(radii, (list, tuple)) and len(radii) == 2
    ri, ro = radii
    assert isinstance(ri, float) and ri > 0.
    assert isinstance(ro, float) and ro > 0.
    assert ri < ro

    assert isinstance(n_refinements, int) and n_refinements >= 0

    # mesh generation
    if dim == 2:
        center = dlfn.Point(0., 0.)
    elif dim == 3:
        center = dlfn.Point(0., 0., 0.)

    if dim == 2:
        domain = Circle(center, ro)\
            - Circle(center, ri)
        mesh = generate_mesh(domain, 75)
    elif dim == 3:
        domain = Sphere(center, ro) \
            - Sphere(center, ri)
        mesh = generate_mesh(domain, 15)

    # mesh refinement
    for i in range(n_refinements):
        mesh = dlfn.refine(mesh)

    # MeshFunction for boundaries ids
    facet_marker = dlfn.MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
    facet_marker.set_all(0)

    # mark boundaries
    BoundaryMarkers = SphericalAnnulusBoundaryMarkers
    gamma_inner = CircularBoundary(mesh=mesh, radius=ri)
    gamma_inner.mark(facet_marker, BoundaryMarkers.interior_boundary.value)
    gamma_outer = CircularBoundary(mesh=mesh, radius=ro)
    gamma_outer.mark(facet_marker, BoundaryMarkers.exterior_boundary.value)

    return mesh, facet_marker
Esempio n. 30
0
def create_mesh_with_holes(Rint, Rout, Rhole, resolution):
    # Create circles as Circle(Center, Radius)
    outer_circle = mshr.Circle(df.Point(0,0), Rout)
    inner_circle = mshr.Circle(df.Point(0,0), Rint)
    hole = mshr.Circle(df.Point(0, 0.5*(Rint+Rout)), Rhole)
    domain = outer_circle - inner_circle - hole
    mesh = mshr.generate_mesh(domain, resolution)
    return mesh 
Esempio n. 31
0
    def puncture_mesh(self):

        for p in self.hole_coordinates:
            circle = mesher.Circle(fe.Point(p), self.hole_radius)
            self.geometry -= circle

        self.mesh = mesher.generate_mesh(self.geometry, self.mesh_density)
        print('Done with the mesh generation')
Esempio n. 32
0
def get_mesh(k):
    h = 0.5**k
    # cell_size = 2 * pi / num_boundary_points
    c = mshr.Circle(dolfin.Point(0., 0., 0.), 1, int(2*pi / h))
    # cell_size = 2 * bounding_box_radius / res
    m = mshr.generate_mesh(c, 2.0 / h)
    coords = m.coordinates()
    coords = numpy.c_[coords, numpy.zeros(len(coords))]
    return pyfvm.meshTri.meshTri(coords, m.cells())
Esempio n. 33
0
def get_mesh(k):
    h = 0.5**(k+2)
    c = mshr.Sphere(dolfin.Point(0., 0., 0.), 1.0, int(2*pi / h))
    m = mshr.generate_mesh(c, 2.0 / h)
    return pyfvm.meshTetra.meshTetra(
            m.coordinates(),
            m.cells(),
            mode='geometric'
            )
Esempio n. 34
0
def make_spherical_mesh(size, resolution):

    #Defining the domain for the mesh using the Sphere function from mshr
    domain = mshr.Sphere(origin, size)

    #Meshing the sphere generated with resolution 10 (cells per dimension)
    initial_mesh = mshr.generate_mesh(domain, resolution)

    return initial_mesh
Esempio n. 35
0
    def build_mesh(self):
        self.length = 8.
        self.height = 2.
        self.notch_length = 0.2
        self.notch_height = 0.4

        domain = mshr.Polygon([fe.Point(0., 0.), 
                  fe.Point(self.length/2. - self.notch_length/2., 0.),
                  fe.Point(self.length/2., self.notch_height),
                  fe.Point(self.length/2. + self.notch_length/2., 0.),
                  fe.Point(self.length, 0.),
                  fe.Point(self.length, self.height),
                  fe.Point(self.length/2. + self.notch_length/2., self.height),
                  fe.Point(self.length/2., self.height),
                  fe.Point(self.length/2. - self.notch_length/2., self.height),
                  fe.Point(0., self.height)])

        # resolution = 100 if self.local_refinement_iteration == 0 else 200
        # self.mesh = mshr.generate_mesh(domain, resolution)

        self.mesh = mshr.generate_mesh(domain, 100)
        for i in range(self.local_refinement_iteration):
            cell_markers = fe.MeshFunction('bool', self.mesh, self.mesh.topology().dim())
            cell_markers.set_all(False)
            for cell in fe.cells(self.mesh):
                p = cell.midpoint()
                if  p[0] > 14./32.*self.length and p[0] < 18./32.*self.length and p[1] < self.height - self.notch_height:
                    cell_markers[cell] = True
            self.mesh = fe.refine(self.mesh, cell_markers)

        length = self.length
        height = self.height
        notch_length = self.notch_length

        class Upper(fe.SubDomain):
            def inside(self, x, on_boundary):
                # return on_boundary
                return on_boundary and fe.near(x[1], height) 


        class LeftCorner(fe.SubDomain):
            def inside(self, x, on_boundary):
                return fe.near(x[0], 0.) and fe.near(x[1], 0.)

        class RightCorner(fe.SubDomain):
            def inside(self, x, on_boundary):
                return fe.near(x[0], length) and fe.near(x[1], 0.)

        class MiddlePoint(fe.SubDomain):
            def inside(self, x, on_boundary):                    
                # return fe.near(x[0], length/2.) and fe.near(x[1], height)
                return x[0] > length/2. - notch_length/2.  and  x[0] < length/2. + notch_length/2. and fe.near(x[1], height)

        self.upper = Upper()
        self.left = LeftCorner()
        self.right = RightCorner()
        self.middle = MiddlePoint()
Esempio n. 36
0
def create_cylinder():
    """ Geometry of a cylinder """
    R = 1.0     # Inner radius
    H = 0.3     # Thickness
    L = 10.0    # Length

    geometry = mshr.Cylinder(Point(0.0,0.0,0.0),Point(0.0,0.0,L),R+H,R+H,30) - \
    mshr.Cylinder(Point(0.0,0.0,0.0),Point(0.0,0.0,L),R,R,30)
    mesh = mshr.generate_mesh(geometry, 30)

    return mesh
Esempio n. 37
0
    def get(self):
        """ Generate polygon from top and bottom curves. """
        radius, N = self.pad(self.values)
        radius = evaluate(radius)[0]

        points = [Point(*(radius(theta)*np.array([cos(theta), sin(theta)])))
                  for theta in np.linspace(0, 2*np.pi, N+2)]
        if abs(radius(0)-radius(2*np.pi)) < 1E-4:
            points.pop()
        try:
            # may fail if not counterclockwise vertices
            poly = Polygon(points)
        except:
            poly = Polygon(points[::-1])
        return generate_mesh(poly, 1)
Esempio n. 38
0
 def get(self):
     """Built-in polygonal mesh."""
     params = self.pad(self.values)
     if params[1]:
         vertices = convex_hull(params[0])
     else:
         vertices = params[0]
     vertices = [Point(*p) for p in vertices]
     size = params[2]
     try:
         # may fail if not counterclockwise vertices
         poly = Polygon(vertices)
     except:
         poly = Polygon(vertices[::-1])
     return generate_mesh(poly, size)
Esempio n. 39
0
def test(n):
    domain = Rectangle(Point(0, 0), Point(2, 3))
    mesh = generate_mesh(domain, n)

    # Cell-cell connectivity will be defined over facet
    tdim = mesh.topology().dim()
    mesh.init(tdim, tdim-1)
    mesh.init(tdim-1, tdim)

    c2f = mesh.topology()(tdim, tdim-1)
    f2c = mesh.topology()(tdim-1, tdim)

    c2c = lambda c: set(np.hstack([f2c(f) for f in c2f(c)]))

    def cells_in_radius(c0, mesh, cell_connectivity, radius):
        x0 = c0.midpoint()
        c0 = c0.index()
        N = set([c0])              # cells in the patch
        C = cell_connectivity(c0)  # where to look elements of the patch
        C.remove(c0)

        while C:
            c = C.pop()
            x = Cell(mesh, c).midpoint()
            if x.distance(x0) < radius:
                N.add(c)
                new = cell_connectivity(c) - N
                C.update(new)
        return N
     
    f = CellFunction('size_t', mesh, 0)

    # c0 = Cell(mesh, choice(range(mesh.num_cells())))
    # for c in  cells_in_radius(c0, mesh, c2c, 0.4):
    #     f[int(c)] = 1
    # f[c0] = 2
    # plot(f, interactive=True)

    t = Timer('dt')
    c0 = choice(range(mesh.num_cells()))
    c0 = Cell(mesh, c0)
    t.start()
    print '\tPatch size', len(cells_in_radius(c0, mesh, c2c, 0.4))
    dt = t.stop()
    
    return mesh.num_cells(), dt
Esempio n. 40
0
    def __init__(self, model_name="cylinder_demo3d"):
        pyurdme.URDMEModel.__init__(self, model_name)

        # System constants
        D_const = 0.1
        
        # Define Species
        A = pyurdme.Species(name="A", diffusion_constant=D_const)
        B = pyurdme.Species(name="B", diffusion_constant=D_const)
        self.add_species([A, B])
        
        # Define Geometry
        pt1 = dolfin.Point(MAX_X_DIM, 0, 0)
        pt2 = dolfin.Point(MIN_X_DIM, 0, 0)
        cylinder = mshr.Cylinder(pt1, pt2, 1.0, 1.0)
        self.mesh = pyurdme.URDMEMesh(mesh=mshr.generate_mesh(cylinder, 32))
        
        # Define Subdomains
        self.add_subdomain(Edge1(), 2)
        self.add_subdomain(Edge2(), 3)

        data = self.get_solver_datastructure()
        vol = data['vol']
        sd = data['sd']
        left = numpy.sum(vol[sd == 2])
        right = numpy.sum(vol[sd == 3])
    
        k_react = pyurdme.Parameter(name="k_react", expression=1.0)
        
        k_creat1 = pyurdme.Parameter(name="k_creat1", expression=100/left)
        k_creat2 = pyurdme.Parameter(name="k_creat2", expression=100/right)
        
        self.add_parameter([k_react, k_creat1,k_creat2])

        
        # Define Reactions
        R1 = pyurdme.Reaction(name="R1", reactants=None, products={A:1}, rate=k_creat1, restrict_to=2)
        R2 = pyurdme.Reaction(name="R2", reactants=None, products={B:1}, rate=k_creat2, restrict_to=3)
        R3 = pyurdme.Reaction(name="R3", reactants={A:1, B:1}, products=None, rate=k_react)
        self.add_reaction([R1, R2, R3])

        # Define simulation timespan
        self.timespan(range(200))
Esempio n. 41
0
def create_toy_mesh():

    box = mshr.Box(dolfin.Point(-3, -1, -0.5), dolfin.Point(3, 1, 0.5))

    c1 = mshr.Cylinder(dolfin.Point(0, 0, -2), dolfin.Point(0, 0, 2), 0.6, 0.6)
    b1 = mshr.Box(dolfin.Point(-2.5, -0.5, -2), dolfin.Point(-1.5, 0.5, 2))

    # "triangle"
    t1 = mshr.Polygon(
        [
            dolfin.Point(2.5, -0.5, 0),
            dolfin.Point(2.5, 0.5, 0),
            dolfin.Point(1.5, -0.5, 0),
        ]
    )
    g3d = mshr.Extrude2D(t1, -2)
    g3d = mshr.CSGTranslation(g3d, dolfin.Point(0, 0, 1))

    m = mshr.generate_mesh(box - c1 - b1 - g3d, 40, "cgal")

    return m.coordinates(), m.cells()
Esempio n. 42
0
 def get(self):
     """ Generate polygon from top and bottom curves. """
     m, M, top, bottom, var, N = self.pad(self.values)
     top = evaluate(top)[0]
     bottom = evaluate(bottom)[0]
     if var == 'x':
         points = [Point(x, top(x)) for x in np.linspace(m, M, N+2)]
     else:
         points = [Point(top(x), x) for x in np.linspace(m, M, N+2)]
     if abs(top(M)-bottom(M)) < 1E-4:
         points.pop()
     if var == 'x':
         points += [Point(x, bottom(x)) for x in np.linspace(M, m, N+2)]
     else:
         points += [Point(bottom(x), x) for x in np.linspace(M, m, N+2)]
     if abs(top(m)-bottom(m)) < 1E-4:
         points.pop()
     try:
         # may fail if not counterclockwise vertices
         poly = Polygon(points)
     except:
         poly = Polygon(points[::-1])
     return generate_mesh(poly, 1)
Esempio n. 43
0
def kernel_collision(mesh, filter_radius):
    """ 
    Calculate the kernel support using the dolfin collision function
    More inefficient than the current DFS
    """
    # Build circle or kernel support
    domain = mshr.Circle(Point(0.,0.), filter_radius)
    circle_mesh = mshr.generate_mesh(domain, 60, "cgal")

    # Build bounding box trees for background mesh
    tree_A = BoundingBoxTree()
    tree_A.build(mesh)

    # Bounding box for the circle
    tree_circle = BoundingBoxTree()

    for c in cells(mesh):
        cell_centroid = c.midpoint()
        circle_mesh.translate(cell_centroid)

        # Rebuild the tree
        tree_circle.build(circle_mesh)
        entities_AB, entities_B = tree_A.compute_collisions(tree_circle)
Esempio n. 44
0
import mshr
from dolfin import *

# issue 37
g = mshr.Rectangle(Point(0.0, 0.0), Point(2.2, .41)) - mshr.Circle(Point(.2, .2), .05, 40)
m = mshr.generate_mesh(g, 50)

# issue 41 (failed only in parallel)
c = mshr.Extrude2D(mshr.Circle(Point(0, 0, 0), 1), 1)
m = mshr.generate_mesh(c, 10)
Esempio n. 45
0
 def get(self):
     """Use mshr Cylinder, though centers seem to not work."""
     h, b, t, n, k = self.pad(self.values)
     from mshr import Cylinder
     c = Cylinder(Point(0, 0, 0), Point(0, 0, h), b, t, n)
     return generate_mesh(c, k)
Esempio n. 46
0
#         25, 25, 25
#         )
# mesh = pyfvm.meshTetra.meshTetra(vertices, cells)
# vertices, cells = meshzoo.rectangle.create_mesh(
#         0.0, 2.0,
#         0.0, 1.0,
#         401, 201,
#         zigzag=True
#         )
# mesh = pyfvm.meshTri.meshTri(vertices, cells)

import mshr
import dolfin
h = 2.5e-2
# cell_size = 2 * pi / num_boundary_points
c = mshr.Circle(dolfin.Point(0., 0., 0.), 1, int(2*pi / h))
# cell_size = 2 * bounding_box_radius / res
m = mshr.generate_mesh(c, 2.0 / h)
coords = m.coordinates()
coords = numpy.c_[coords, numpy.zeros(len(coords))]
mesh = pyfvm.meshTri.meshTri(coords, m.cells())

linear_system = pyfvm.discretize(Poisson(), mesh)

ml = pyamg.ruge_stuben_solver(linear_system.matrix)
x = ml.solve(linear_system.rhs, tol=1e-10)
# from scipy.sparse import linalg
# x = linalg.spsolve(linear_system.matrix, linear_system.rhs)

mesh.write('out.vtu', point_data={'x': x})
Esempio n. 47
0
from block import block_mat, block_vec, block_bc
from dolfin import *
from xii import *

import mshr

N = 10
EPS = 1E-3
R = 0.25
box_domain = mshr.Box(dolfin.Point(0, 0, 0), dolfin.Point(1, 1, 1))
_mesh = mshr.generate_mesh(box_domain, N)

stokes_subdomain = dolfin.CompiledSubDomain(
    "sqrt((x[0]-0.5) * (x[0]-0.5) + (x[1]-0.5) * (x[1]-0.5)) < R", R=R
)

subdomains = MeshFunction('size_t', _mesh, _mesh.topology().dim(), 0)

# Awkward marking
for cell in cells(_mesh):
    x = cell.midpoint().array()
    if stokes_subdomain.inside(x, False):
        subdomains[cell] = 1
    else:
        subdomains[cell] = 0

submeshes, interface, _ = mortar_meshes(subdomains, range(2), strict=True, tol=EPS)


stokes_domain = submeshes[0]
porous_domain = submeshes[1]
Esempio n. 48
0
from dolfin import *
import mshr

# The ellipse is completely contained in the circle and will not be
# visible in the resulting mesh, but it is so small that with
# mesh_resolution = 10 that when converting it to a polygon the number
# of segments in the polygon will be 0 (ie. the polygon is degenerate)
# if not handled correctly.
c = mshr.Circle(Point(0, 0), 1.5)
e = mshr.Ellipse(Point(.05, 0), .01, .05)

mesh = mshr.generate_mesh(c+e, 10)

Esempio n. 49
0
# Copyright (C) 2015 Benjamin Kehlet
#
# This file is part of mshr.
#
# mshr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# mshr is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with mshr.  If not, see <http://www.gnu.org/licenses/>.

# This demo illustrates how a 2D geometry can be extruded to 3D.

from dolfin import *
import mshr

g2d = mshr.Circle(Point(0,0), 1.2) + mshr.Circle(Point(0, 1.2), 1.2)

# Any simple 2D geometry can be extruded to 3D
g3d = mshr.Extrude2D(g2d, 
                     .2) # The z "thickness"

m = mshr.generate_mesh(g3d, 15)
plot(m, interactive=True)
Esempio n. 50
0
def Regular(n, size=50):
    """Build mesh for a regular polygon with n sides."""
    points = [(np.cos(2*np.pi*i/n), np.sin(2*np.pi*i/n)) for i in range(n)]
    polygon = Polygon([Point(*p) for p in points])
    return generate_mesh(polygon, size)
Esempio n. 51
0
import numpy as np
import pylab
from dolfin import *

####  Rotating cylinders  ####

# physical values
u0 = Constant(0)
u1 = Constant(1)

# Create mesh
c1 = mshh.Circle(Point(0, 0, 0),  1.0)
c2 = mshh.Circle(Point(0, 0, 0),  3.0)

geometry = c2-c1
mesh = mshh.generate_mesh(geometry, 8)

# function spaces and functions
V = FunctionSpace(mesh, "Lagrange", 1)
u = TrialFunction(V)
v = TestFunction(V)

class Inner(SubDomain):
	def inside(self, x, on_boundry):
		return on_boundry

class Outer(SubDomain):
	def inside(self, x, on_boundry):
		return (sqrt(x[0]*x[0] + x[1]*x[1]) > 1.5) and on_boundry

out_circ = Outer()
Esempio n. 52
0
def generate_tower_mesh(quality=20):
    otri = mshr.Polygon([Point(0, 0), Point(1, 0), Point(0.5, 1)])
    itri = mshr.Polygon([Point(0.2, 0.0), Point(0.8, 0.0), Point(0.5, 0.75)])
    domain = otri - itri
    return mshr.generate_mesh(domain, quality)
Esempio n. 53
0
def CircleMesh(p, r, s):
    """ mshr has no CircleMesh. """
    return generate_mesh(Circle(p, r, max(int(4 * pi / s), 4)), int(2 / s))
Esempio n. 54
0
# Define domain
H = 0.41
L = 2.5

zero = Point(0.0, 0.0, 0.0)
corner = Point(L, H, H)
box = mshr.Box(zero, corner)

cyl_offset = 0.5
right = Point(cyl_offset, 0.2, H)
left = Point(cyl_offset, 0.2, 0)
radius = 0.05
cylinder = mshr.Cylinder(left, right, radius, radius)
geometry = box - cylinder

# Build mesh
mesh = mshr.generate_mesh(geometry, factor)
print(mesh)
plot(mesh, title="mesh", interactive=True)
exit()

# Construct facet markers
bndry = FacetFunction("size_t", mesh)
for f in facets(mesh):
    mp = f.midpoint()
    if near(mp[0], 0.0): bndry[f] = 1  # inflow
    elif near(mp[0], L): bndry[f] = 2  # outflow
    elif near(mp[1], 0.0) or near(mp[1], W): bndry[f] = 3  # walls
    elif mp.distance(center) <= radius:      bndry[f] = 5  # cylinder
#############################################################################################################
### Test 1: Hexagon
#############################################################################################################

for N in range(4,21):
    x = empty((N,))
    y = empty((N,))
    for n in range(N):
        x[n] = cos(2.*pi*n/N)
        y[n] = sin(2.*pi*n/N)

    interior_angles = 180.*(N - 2)/N
    if interior_angles > 90:
        interior_angles = 180 - interior_angles

    mesh = generate_mesh(Polygon([Point(xx,yy) for xx,yy in zip(x,y)]), N)

    markers1 = detect_colinearity(mesh, interior_angles - 1)

    markers2 = detect_colinearity(mesh, interior_angles + 1)

    # number of tags should be equal to the number of sides of the polygon plus the interior tag
    if len(unique(markers1.array())) != N+1:
        raise RuntimeError('Test failed: number of tags assigned by colinearity_detection is wrong')

    # number of tags should be equal to the number of sides of the polygon divided by 2 plus the interior tag
    # this is because colinearity is checked with respect to the first untagged facet found
    if len(unique(markers2.array())) != int(N/2)+1:
        raise RuntimeError('Test failed: number of tags assigned by colinearity_detection is wrong')

#############################################################################################################
Esempio n. 56
0
                                "report": True,
                                "maximum_iterations": 10}}
compiler_parameters =  {"optimize": True,
                        "cpp_optimize": True,
                        "cpp_optimize_flags": "-O3 -ffast-math -march=native"}
output = File("solutions/laplace-young2/sol5.pvd")

# Mesh properties (for ellipse and rectangle)
a = 1.0;
b = 1.0;
xn = 100
yn = 100

# Ellipse (figure 1)
domain = mshr.Ellipse(Point(0.0, 0.0), a, b, xn)
mesh = mshr.generate_mesh(domain, 50, "cgal")
# Droplet
#u_0 = Expression('''0.5*sqrt(1 - x[0]*x[0]/(a*a) - x[1]*x[1]/(b*b) + 0.01 )''', a = a, b = b)
# Wrinkled disc
u_0 = Expression('''0.5*(1 - 0.5*sin(2*x[0]*x[0]/(b*b)
                        + 10*x[1]*x[1]/(a*a)) )''', a = a, b = b)

# Triangular pizza mesh (Figure 2/3/4)
# a = 1.0;
# b = 3.0;
# triangle = mshr.Polygon([Point(-a, 0.0), Point(a, 0.0), Point(0.0, b)])
# half_circle = mshr.Ellipse(Point(0.0, 0.0), a, a, xn) - \
#                 mshr.Rectangle(Point(-a, 0.0), Point(a,a))
# domain = triangle + half_circle
# mesh = mshr.generate_mesh(domain, xn, "cgal")
# u_0 = Expression('''0.3*(1 - 0.5*x[0]*x[0]
Esempio n. 57
0
Top    = 1.0 
Bottom = -1.0 

lb_corner = Point( Left, Bottom ) 
rt_corner = Point( Right, Top ) 



t2 = mshr.Polygon( points ) 

## number of elements 
N = 1

## L-shaped domain
domain = mshr.Rectangle( lb_corner, rt_corner ) - t2 
mesh = mshr.generate_mesh( domain, N )


# Global mesh refinement 
#markers = CellFunction("bool", mesh)
#markers.set_all(True) 
#mesh = refine(mesh, markers, redistribute=False) 

initRef = 0
for i in range(initRef): 
   mesh = refine( mesh )  
nelem = mesh.num_cells() 



print 'Mesh with ', nelem , 'elements was generated.'
from dolfin import *
import mshr

domain = mshr.Circle(Point(0.,0), 1.0)
circle_mesh = mshr.generate_mesh(domain, 20)
    
def boundary_projection(f, V):
    u, v = TrialFunction(V), TestFunction(V)
    #ds = Measure("ds", domain=circle_mesh)
    #dx = Measure("dx", domain=circle_mesh)
    a = inner(u,v) * ds + Constant(0)*inner(u,v)*dx # ensure existing diagonal
    L = inner(f, v) * ds

    # solve
    A, b = assemble_system(a, L)
    A.ident_zeros() #fix interior dofs
    Pf = Function(V)
    solve(A, Pf.vector(), b)

    return Pf

def nodal_normal(V):

    n_ufl =  FacetNormal(V.mesh())
    return boundary_projection(n_ufl, V)

    
def nodal_tangent(V):
    #import IPython; IPython.embed()
    n_ufl =  FacetNormal(V.mesh())
    t_ufl = cross(as_vector((0,0,1)), as_vector((n_ufl[0], n_ufl[1], 0)))
#Choose a domain
domain = 0 #Choose a domain 0 = unit circle, 1 = Unit square, 2 = Square centred at 0 width 1, 4 = curved square, 5 = non symmetric domain, 6 = oval

#Choose an initial guess, i.e. u_0
prob = 0

# Function spaces for the solution and Hessian
solution_space = "CG"
Hessian_solution_space = "CG"
e_L2 = []; e_H1 = []; e_H2 = []; e_D2 = []; ndof = []; one = [];

# Create the triangulation of the computational domain
if domain==0:
    dom = mshr.Circle(Point(0.0,0.0),1.0,60)
    mesh = mshr.generate_mesh(dom,20,"cgal")
    parameters['allow_extrapolation'] = True
    PENALTY = False #toggling boundary condition penalty parameter
    plot(mesh,interactive = True)
elif domain==1:
    mesh = UnitSquareMesh(50, 50)
    PENALTY = 1 #toggling boundary condition penalty parameter
elif domain==2:
    mesh = RectangleMesh(-0.5,-0.5,0.5,0.5,50,50,'left')
    parameters['allow_extrapolation'] = True
    PENALTY = True #toggling boundary condition penalty parameter
elif domain==3:
    mesh = RectangleMesh(0.5,0.5,1.0,1.0,4, 4,'left')
    parameters['allow_extrapolation'] = True
    PENALTY = 1 #toggling boundary condition penalty parameter
elif domain==4:
Esempio n. 60
0
from dolfin import *
import numpy as np
from math import log as ln, sinh, pi

A = 5.0  # big circle radius
B = 1.0  # small circle radius
C = 1.0  # distance between centers

# Create mesh
import mshr as mshh

big_circle = mshh.Circle(Point(0, 0, 0), A)
small_circle = mshh.Circle(Point(-1.0, 0, 0), B)
geometry = big_circle - small_circle
mesh1 = mshh.generate_mesh(geometry, 10)
mesh2 = mshh.generate_mesh(geometry, 20)
mesh3 = mshh.generate_mesh(geometry, 40)
mesh4 = mshh.generate_mesh(geometry, 80)


def solver(mesh, deg):
    # Physical parameters
    dpdx = Constant(-1)
    mu = Constant(100)

    V = FunctionSpace(mesh, "Lagrange", deg)
    u = TrialFunction(V)
    v = TestFunction(V)

    # Mark boundary subdomians
    class Sides(SubDomain):