Beispiel #1
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
Beispiel #2
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()
Beispiel #3
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()
Beispiel #4
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 
Beispiel #5
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
Beispiel #6
0
def mesh2d(inner, outer, *meshres, stefan=True):
    origin = dolfin.Point(0., 0.)
    if stefan:
        geometry = mshr.Circle(origin, outer, 2 * meshres[0]) - mshr.Circle(
            origin, inner, int(0.5 * meshres[0]))
        mesh = mshr.generate_mesh(geometry, meshres[0])
        mesh.init()
        # Construct of the facet markers:
        boundary = (dolfin.MeshFunction("size_t", mesh,
                                        mesh.topology().dim() - 1, 0), {})
        for f in dolfin.facets(mesh):
            if f.midpoint().distance(origin) <= inner and f.exterior():
                boundary[0][f] = 1  # inner radius
                boundary[1]['inner'] = 1
            elif f.midpoint().distance(origin) >= (inner +
                                                   outer) / 2 and f.exterior():
                boundary[0][f] = 2  # outer radius
                boundary[1]['outer'] = 2
        # Definition of measures and normal vector:
        n = dolfin.FacetNormal(mesh)
        dx = dolfin.Measure("dx", mesh)
        ds = dolfin.Measure("ds", domain=mesh, subdomain_data=boundary[0])
    else:
        width = inner
        height = outer
        mesh = dolfin.RectangleMesh(origin, Point(width, height), meshres[0],
                                    meshres[1])
        mesh.init()
        boundary = (dolfin.MeshFunction("size_t", mesh,
                                        mesh.topology().dim() - 1, 0), {})
        for f in dolfin.facets(mesh):
            if dolfin.near(f.midpoint()[1], 0.):
                boundary[0][f] = 1  # bottom
                boundary[1]['bottom'] = 1
            elif dolfin.near(f.midpoint()[1], height):
                boundary[0][f] = 2  # top
                boundary[1]['top'] = 2
            elif dolfin.near(f.midpoint()[0], 0.):
                boundary[0][f] = 3  # left
                boundary[1]['left'] = 3
            elif dolfin.near(f.midpoint()[0], width):
                boundary[0][f] = 4  # right
                boundary[1]['right'] = 4
        # Definition of measures and normal vector:
        n = dolfin.FacetNormal(mesh)
        dx = dolfin.Measure("dx", mesh)
        ds = dolfin.Measure("ds", subdomain_data=boundary[0])
    return (mesh, boundary, n, dx, ds)
Beispiel #7
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)
Beispiel #8
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)
Beispiel #9
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
Beispiel #10
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
Beispiel #11
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')
Beispiel #12
0
def irregular_channel():
    radius = 0.35
    resolution = 25
    point_A = fa.Point(0, 0)
    point_B = fa.Point(2, -1)
    point_C = fa.Point(2, 2)
    point_D = fa.Point(0, 1)
    point_E = fa.Point(0.5, 0.5)
    point_F = fa.Point(1.5, 1)
    point_G = fa.Point(1.5, 0)
    outline = mshr.Polygon([point_A, point_B, point_C, point_D])
    circle_1 = mshr.Circle(point_E, radius)
    circle_2 = mshr.Circle(point_F, radius)
    circle_3 = mshr.Circle(point_G, radius)
    mesh = mshr.generate_mesh(outline - circle_1 - circle_2 - circle_3,
                              resolution)
    return mesh
Beispiel #13
0
	def __init__(self, center, radius, *, maxh = 1., eps = csg_eps):
		segments = max(int(4*radius/maxh), 32)
		eps *= radius
		super().__init__(mshr.Circle(dolfin.Point(*center), radius, segments), csg_boundaries = [
			dolfin.CompiledSubDomain(
				'on_boundary && near((x[0]-c0)*(x[0]-c0) + (x[1]-c1)*(x[1]-c1), rr, eps)',
				c0 = center[0], c1 = center[1], rr = radius * radius, eps = eps
			)
		])
def geo_fun():
    '''
    Creates hollow circle.
    '''
    geo_params = {}
    geo_params['R_in'] = 8e-3  #m
    geo_params['R_ex'] = 16e-3  #m
    geo_params['x_0'] = 0.
    geo_params['y_0'] = 0.
    geo_params['z_0'] = 0.

    #number of faces on the side when generating a polyhedral approximation
    #CGAL meshes the polyhedral approximation; hence, it is better to keep it high
    #https://bitbucket.org/fenics-project/mshr/issues/26/creation-of-mesh-with-generate_mesh-most
    fragments1 = 1000
    fragments2 = 400

    cyl_ho = ms.Circle(
        do.Point(geo_params['x_0'], geo_params['y_0'], geo_params['z_0']),
        geo_params['R_ex'], fragments2)

    #x0_l = [-.5, 0., .5, 0.]
    #y0_l = [0., -.5, 0., .5]

    x0_l = [0.]
    y0_l = [0.]

    for itera in xrange(len(x0_l)):
        geo_params['x_0_{}'.format(itera)] = x0_l[itera]
        geo_params['y_0_{}'.format(itera)] = y0_l[itera]
        geo_params['z_0_{}'.format(itera)] = 0.

        #top, bottom, top radius, bottom radius, segments
        cyl_in = ms.Circle(
            do.Point(geo_params['x_0_{}'.format(itera)],
                     geo_params['y_0_{}'.format(itera)],
                     geo_params['z_0_{}'.format(itera)]), geo_params['R_in'],
            fragments1)

        #hollow cylinder
        cyl_ho -= cyl_in

    return cyl_ho, geo_params
Beispiel #15
0
    def add_circle_obstacle(self, p, radius, mirror=False, accuracy=10):
        points = [Point(p[0], p[1])]

        # Replicate the circle on the other edge of the map.
        if mirror:
            points.append(
                Point(self.dimension[0] + self.robot_radius - p[0], p[1]))

        for point in points:
            self._map -= mshr.Circle(point, radius + self.robot_radius,
                                     accuracy)
Beispiel #16
0
def tensile_test_bar(numpts=60, plot_=True):

    outer = mshr.Rectangle(Point(-100, -10), Point(100, 10))
    barLo = mshr.Rectangle(Point(-30, 6.25), Point(30, 10))
    barHi = mshr.Rectangle(Point(-30, -10), Point(30, -6.25))
    c1 = mshr.Circle(Point(-30, -19.5), 13.4)
    c2 = mshr.Circle(Point(30, -19.5), 13.4)
    c3 = mshr.Circle(Point(-30, 19.5), 13.4)
    c4 = mshr.Circle(Point(30, 19.5), 13.4)
    domain = outer - barLo - barHi - c1 - c2 - c3 - c4

    mm = mshr.generate_mesh(domain, numpts)

    if plot_:
        plt.figure()
        plot(mm, color='k')
        plt.xlim(-120, 120)
        plt.ylim(-20, 20)
        plt.show(block=False)
    return mm
Beispiel #17
0
def method(L=3., H=1., R=0.3, n_segments=40, res=60, show=False, **kwargs):
    """
    Generates mesh of Snausen/Snoevsen.
    """
    info("Generating mesh of Snoevsen.")

    # Define points:
    pt_A = df.Point(0., 0.)
    pt_B = df.Point(L, H)
    pt_C = df.Point(L / 2 - 2 * R, 0.)
    pt_D = df.Point(L / 2 + 2 * R, 0.)
    pt_E = df.Point(L / 2 - 2 * R, -R)
    pt_F = df.Point(L / 2 + 2 * R, -R)
    pt_G = df.Point(L / 2, -R)

    tube = mshr.Rectangle(pt_A, pt_B)
    add_rect = mshr.Rectangle(pt_E, pt_D)
    neg_circ_L = mshr.Circle(pt_E, R, segments=n_segments)
    neg_circ_R = mshr.Circle(pt_F, R, segments=n_segments)
    pos_circ = mshr.Circle(pt_G, R, segments=n_segments)

    domain = tube + add_rect - neg_circ_L - neg_circ_R + pos_circ

    mesh = mshr.generate_mesh(domain, res)

    # check that mesh is periodic along x
    boun = df.BoundaryMesh(mesh, "exterior")
    y = boun.coordinates()[:, 1]
    y = y[y < 1.]
    y = y[y > 0.]
    n_y = len(y)
    n_y_unique = len(np.unique(y))

    assert (n_y == 2 * n_y_unique)

    mesh_path = os.path.join(MESHES_DIR, "snoevsen_res" + str(res))
    store_mesh_HDF5(mesh, mesh_path)

    if show:
        df.plot(mesh, "Mesh")
        plt.show()
Beispiel #18
0
def generate_polygonal_mesh(resolution,
                            ampothem,
                            nedges,
                            radius,
                            plot_mesh=False):
    """
    Sometimes segault is thrown when mshr.generate_mesh() is 
    called. This is because resolution is to low to resolve
    smaller inner-most circle.
    """
    import mshr
    vertices = get_vertices_of_polygon(ampothem, nedges)

    domain_vertices = []
    for vertex in vertices.T:
        domain_vertices.append(dl.Point(vertex[0], vertex[1]))

    domain = mshr.Polygon(domain_vertices)

    cx1, cy1 = 0.0, 0.0
    circle1 = mshr.Circle(dl.Point(cx1, cy1), radius)
    domain.set_subdomain(1, circle1)
    cx2, cy2 = cx1 - radius / np.sqrt(8), cy1 - radius / np.sqrt(8)
    circle2 = mshr.Circle(dl.Point(cx2, cy2), radius / 2)
    domain.set_subdomain(2, circle2)
    mesh = mshr.generate_mesh(domain, resolution)

    if plot_mesh:
        subdomains = dl.MeshFunction('size_t', mesh, mesh.topology().dim(), 2)
        subdomains.set_all(0)
        subdomain1 = dl.AutoSubDomain(lambda x: np.sqrt(
            (x[0] - cx1)**2 + (x[1] - cy1)**2) < radius + 1e-8)
        subdomain1.mark(subdomains, 1)
        subdomain2 = dl.AutoSubDomain(lambda x: np.sqrt(
            (x[0] - cx2)**2 + (x[1] - cy2)**2) < radius / 2 + 1e-8)
        subdomain2.mark(subdomains, 2)
        dl.plot(mesh)
        dl.plot(subdomains)
        plt.show()

    return mesh
Beispiel #19
0
def generate_mesh_with_cicular_subdomain(resolution, radius, plot_mesh=False):
    cx1, cy1 = 0.5, 0.5
    lx, ly = 1.0, 1.0

    # Define 2D geometry
    domain = mshr.Rectangle(dl.Point(0.0, 0.0), dl.Point(lx, ly))
    domain.set_subdomain(1, mshr.Circle(dl.Point(cx1, cy1), radius))
    cx2, cy2 = cx1 - radius / np.sqrt(8), cy1 - radius / np.sqrt(8)
    domain.set_subdomain(2, mshr.Circle(dl.Point(cx2, cy2), radius / 2))

    # Generate and plot mesh
    mesh2d = mshr.generate_mesh(domain, resolution)
    if plot_mesh:
        dl.plot(mesh2d, "2D mesh")

        class Circle1(dl.SubDomain):
            def inside(self, x, on_boundary):
                return pow(x[0] - cx1, 2) + pow(x[1] - cy1, 2) <= pow(
                    radius, 2)

        class Circle2(dl.SubDomain):
            def inside(self, x, on_boundary):
                return pow(x[0] - cx2, 2) + pow(x[1] - cy2, 2) <= pow(
                    radius / 2, 2)

        # Convert subdomains to mesh function for plotting
        mf = dl.MeshFunction("size_t", mesh2d, 2)
        mf.set_all(0)
        circle1 = Circle1()
        circle2 = Circle2()

        for c in dl.cells(mesh2d):
            if circle1.inside(c.midpoint(), True):
                mf[c.index()] = 1
            if circle2.inside(c.midpoint(), True):
                mf[c.index()] = 2

        dl.plot(mf, "Subdomains")
        # show must be called here or plot gets messed up
        # plt.show()
    return mesh2d
    def make_mesh(self, KindOfMesh, nCellsX, nCellsY):
        """generates the mesh  and returns it"""

        #KindOfMesh = 0 => UnitSquareMesh
        #KindOfMesh = 1 => CircleMesh

        if (KindOfMesh == 0):
            mesh = UnitSquareMesh(nCellsX, nCellsY)
        elif (KindOfMesh == 1):
            circle = mshr.Circle(Point(0, 0), 1)
            mesh = mshr.generate_mesh(circle, nCellsX)
        else:
            print("KindOfMesh has value", KindOfMesh, "which is not valid.")
            exit(1)
        self.mesh = mesh
Beispiel #21
0
def method(Lx=4.,
           Ly=4.,
           rad=0.2,
           R=0.3,
           N=24,
           n_segments=40,
           res=80,
           do_plot=False,
           **kwargs):
    """ Porous mesh. Not really done or useful. """
    info("Generating porous mesh")

    # x = np.random.rand(N, 2)

    diam2 = 4 * R**2

    pts = np.zeros((N, 2))
    for i in range(N):
        while True:
            pt = (np.random.rand(2) - 0.5) * np.array([Lx - 2 * R, Ly - 2 * R])
            if i == 0:
                break
            dist = pts[:i, :] - np.outer(np.ones(i), pt)
            dist2 = dist[:, 0]**2 + dist[:, 1]**2
            if all(dist2 > diam2):
                break
        pts[i, :] = pt

    rect = mshr.Rectangle(df.Point(-Lx / 2, -Ly / 2), df.Point(Lx / 2, Ly / 2))
    domain = rect
    for i in range(N):
        domain -= mshr.Circle(df.Point(pts[i, 0], pts[i, 1]),
                              rad,
                              segments=n_segments)

    mesh = mshr.generate_mesh(domain, res)

    store_mesh_HDF5(
        mesh,
        os.path.join(
            MESHES_DIR,
            "porous_Lx{Lx}_Ly{Ly}_rad{rad}_R{R}_N{N}_res{res}.h5".format(
                Lx=Lx, Ly=Ly, rad=rad, R=R, N=N, res=res)))

    if do_plot:
        df.plot(mesh)
        df.interactive()
Beispiel #22
0
def build_space(N_circle, N_bulk, u_in):
    """Prepare data for DGF benchmark. Return function
    space, list of boundary conditions and surface measure
    on the cylinder."""

    # Define domain
    center = Point(0.2, 0.2)
    radius = 0.05
    L = 2.2
    W = 0.41
    geometry = mshr.Rectangle(Point(0.0, 0.0), Point(L, W)) \
             - mshr.Circle(center, radius, N_circle)

    # Build mesh
    mesh = mshr.generate_mesh(geometry, N_bulk)

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

    # Build function spaces (Taylor-Hood)
    P2 = VectorElement("P", mesh.ufl_cell(), 2)
    P1 = FiniteElement("P", mesh.ufl_cell(), 1)
    TH = MixedElement([P2, P1])
    W = FunctionSpace(mesh, TH)

    # Prepare Dirichlet boundary conditions
    bc_walls = DirichletBC(W.sub(0), (0, 0), bndry, 3)
    bc_cylinder = DirichletBC(W.sub(0), (0, 0), bndry, 5)
    bc_in = DirichletBC(W.sub(0), u_in, bndry, 1)
    bcs = [bc_cylinder, bc_walls, bc_in]

    # Prepare surface measure on cylinder
    ds_circle = Measure("ds", subdomain_data=bndry, subdomain_id=5)

    return W, bcs, ds_circle
Beispiel #23
0
def heat_equation(h, print_to_file=False):
    N = 32
    k = 401.
    u_f = 280.

    # Create mesh
    domain = mshr.Rectangle(Point(-1, -1), Point(1, 1)) - mshr.Circle(
        Point(0, 0), 0.25)
    mesh = mshr.generate_mesh(domain, N)

    # Set up function space
    V = FunctionSpace(mesh, "Lagrange", 2)

    # Set up functions
    u = TrialFunction(V)
    v = TestFunction(V)

    # Set up boundary
    [boundaries, ds] = set_boundary(mesh)
    bc = DirichletBC(V, 1000., boundaries, 1)

    # Set up boundary functions
    g_N = Expression('0', degree=1)
    g_R = h * u_f

    # Set up variational problem
    a = k * inner(grad(u), grad(v)) * dx + k * h * (u * v) * ds(3)
    L = g_N * v * k * ds(2) + g_R * k * v * ds(3)

    # Solve the system
    usol = Function(V)
    solve(a == L, usol, bc)

    # Plot solution
    plot(usol, interactive=True)
    plt.title('h = %d' % h)
    plt.show()

    # Print total heat
    print('h = %d ==> %f' % (h, assemble(usol * dx)))

    if (print_to_file):
        # Print to files readable by ParaView
        file = File('hvalue%d.pvd' % h)
        file << usol
def method(res=96, H=0.41, L=2.2, x=0.2, y=0.2, r=0.05,
           segments=100, show=False, **kwargs):
    '''
    Generates mesh for the 'Flow around cylinder' benchmark:

    http://www.featflow.de/en/benchmarks/cfdbenchmarking/flow.html

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

    rect = mshr.Rectangle(df.Point(0, 0), df.Point(L, H))
    cyl = mshr.Circle(df.Point(x, y), r, segments=segments)
    domain = rect - cyl
    mesh = mshr.generate_mesh(domain, res)
    meshpath = os.path.join(
        MESHES_DIR,
        "cylinderinchannel_H{}_L{}_x{}_y{}_r{}_res{}".format(
            H, L, x, y, r, res))
    store_mesh_HDF5(mesh, meshpath)

    if show:
        df.plot(mesh)
        plt.show()
Beispiel #25
0
def solve0(variant):
    cur_var = int(variant)
    alpha = 1
    if (cur_var == 1):
        u_D = Expression('3 + 2*x[0]*x[0] + 3*x[1]*x[1]', degree=2)
        g = Expression(
            '(4*sqrt(x[0]*x[0]+x[1]*x[1])*pow(cos(atan2(x[1],x[0])),2)+6*sqrt(x[0]*x[0] + x[1]*x[1])*pow(sin(atan2(x[1],x[0])),2))',
            degree=2)
        f = Expression('-10 + alpha*(3+2*x[0]*x[0]+3*x[1]*x[1])',
                       degree=2,
                       alpha=alpha)
    elif (cur_var == 2):
        u_D = Expression('(x[0]*x[0]+x[1]*x[1])*pow(cos(atan2(x[1],x[0])),2)',
                         degree=2)
        g = Expression(
            '2*sqrt(x[0]*x[0]+x[1]*x[1])*pow(cos(atan2(x[1],x[0])),2)',
            degree=2)
        f = Expression(
            '-(4*pow(cos(atan2(x[1],x[0])),2)-2*cos(2*atan2(x[1],x[0]))) + alpha*(x[0]*x[0]+x[1]*x[1])*pow(cos(atan2(x[1],x[0])),2)',
            degree=2,
            alpha=alpha)
    elif (cur_var == 3):
        u_D = Expression('x[0]*x[0]+x[0]*x[1]', degree=2)
        g = Expression(
            '2*sqrt(x[0]*x[0]+x[1]*x[1])*pow(cos(atan2(x[1],x[0])),2)+sqrt(x[0]*x[0]+x[1]*x[1])*sin(2*atan2(x[1],x[0]))',
            degree=2)
        f = Expression('-2+alpha*(x[0]*x[0]+x[0]*x[1])', degree=2, alpha=alpha)
    else:
        return

    domain = mshr.Circle(Point(0., 0.), 1.0, 60)
    mesh = mshr.generate_mesh(domain, 60)
    V = FunctionSpace(mesh, 'P', 1)

    def boundary1(x, on_boundary):
        if on_boundary:
            if x[1] >= 0:
                return True
            else:
                return False
        else:
            return False

    bc = DirichletBC(V, u_D, boundary1)
    u = TrialFunction(V)
    v = TestFunction(V)
    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)

    #errors

    error_L2 = errornorm(u_D, u, 'L2')
    vertex_values_u_D = u_D.compute_vertex_values(mesh)
    vertex_values_u = u.compute_vertex_values(mesh)
    error_C = np.max(np.abs(vertex_values_u - vertex_values_u_D))
    print('norm_L2 = ' + str(error_L2))
    print('error_C = ' + str(error_C))

    #graph 1
    n = mesh.num_vertices()
    d = mesh.geometry().dim()
    mesh_coordinates = mesh.coordinates().reshape((n, d))
    triangles = np.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)

    fig1 = plt.figure(1)
    zfaces = np.asarray([u(cell.midpoint()) for cell in cells(mesh)])
    plt.tripcolor(triangulation, facecolors=zfaces, edgecolors='k')
    plt.savefig(str('u' + variant + '.png'))

    #graph 2
    fig2 = plt.figure(2)
    zfaces2 = np.asarray([u_D(cell.midpoint()) for cell in cells(mesh)])
    plt.tripcolor(triangulation, facecolors=zfaces2, edgecolors='k')
    plt.savefig(str('u_D' + variant + '.png'))

    #difference
    fig3 = plt.figure(3)
    zfaces3 = abs(zfaces - zfaces2)
    plt.tripcolor(triangulation, facecolors=zfaces3, edgecolors='k')
    plt.colorbar()
    plt.savefig(str('difference' + variant + '.png'))
Beispiel #26
0
fig.tight_layout()


# ## Circular geometry

# In[98]:

r_outer = 1
r_inner = 0.25
r_middle = 0.1
x0, y0 = 0.4, 0.4


# In[99]:

domain = mshr.Circle(dolfin.Point(.0, .0), r_outer)     - mshr.Circle(dolfin.Point(.0, .0), r_inner)     - mshr.Circle(dolfin.Point( x0,  y0), r_middle)     - mshr.Circle(dolfin.Point( x0, -y0), r_middle)     - mshr.Circle(dolfin.Point(-x0,  y0), r_middle)     - mshr.Circle(dolfin.Point(-x0, -y0), r_middle)


# In[100]:

mesh = mshr.generate_mesh(domain, 10)


# In[101]:

mesh


# In[102]:

V = dolfin.FunctionSpace(mesh, 'Lagrange', 1)
Beispiel #27
0
 def Circle(self, center, rad):
     """
     create a mesh on a circular domain with a radius equal to rad
     """
     return mshr.Circle(center, rad)
Beispiel #28
0
from dolfin import *

T = 1000
num_steps = 5000
dt = T / num_steps
alpha = 0
beta = 1.2
sigma = 1000.0

# Create mesh and define function space
długość = 10.0
szerokość = 5.0
drzwi = 1.5

pomieszczenie = ms.Rectangle(Point(0.0, 0.0), Point(długość, szerokość))
przeszkoda_kolista = ms.Circle(Point(długość - szerokość / 2, szerokość / 2),
                               szerokość / 4)
mesh = ms.generate_mesh(pomieszczenie - przeszkoda_kolista, 100)

mesh2 = ms.generate_mesh(ms.Rectangle(Point(0.0, 0.0), Point(2.0, 2.0)), 200)

drzwi1 = 3.0
drzwi2 = 4.0
drzwi3 = 3.0
korytarz = 80.0

#mesh_lotnisko - hala przylotów
hala = ms.Rectangle(Point(0.0, 0.0), Point(100.0, 40.0))
stoisko1 = ms.Rectangle(Point(15.0, 18.0), Point(15.0 + 4.0, 18.0 + 5.0))
stoisko2 = ms.Rectangle(Point(80.0, 18.0), Point(80.0 + 4.0, 18.0 + 5.0))
ławka = ms.Rectangle(Point(48.0, 20.0), Point(48.0 + 4.0, 20.0 + 1.0))
mesh_lotnisko = ms.generate_mesh(hala - stoisko1 - stoisko2 - ławka, 100)
Beispiel #29
0
from finmag import Simulation as Sim
from finmag.energies import Exchange, Demag, DMI, Zeeman
from finmag.energies import UniaxialAnisotropy
from finmag.util.consts import mu0

import os, shutil
import dolfin as df

# Geometries
import mshr
from finmag.util.mesh_templates import Nanodisk

# MESH ------------------------------------------------------------------------

mesh_file = 'mesh/nanodisk.xml.gz'
mesh = mshr.Circle(df.Point(0, 0), 50)
mesh = mshr.generate_mesh(mesh, 40)
mesh = df.Mesh(mesh)

# Simulation and energies -----------------------------------------------------

# Interfacial
A = 13e-12
D = 3e-3
Ms = 0.86e6
Ku = 0.4e6

sim = Sim(mesh, Ms=Ms, unit_length=1e-9, name="nanodisk_Cnv")


def m_init(pos):
Beispiel #30
0
    def solve_cell_problems(self, method='regularized', plot=False):
        """
        Solve the cell problems for the given PDE by changing the geometry to exclude the zone in the middle
        :return:
        """
        class PeriodicBoundary(fe.SubDomain):

            # Left boundary is "target domain" G
            def inside(self, x, on_boundary):
                par = MembraneSimulator.w / MembraneSimulator.length
                tol = 1E-4
                return on_boundary and x[1] >= -tol and x[1] <= tol

            # Map right boundary (H) to left boundary (G)
            def map(self, x, y):
                y[1] = x[1] + 2 * self.eta / MembraneSimulator.length
                y[0] = x[0]

        mesh_size = 50
        # Domain

        if method == 'circle':
            self.obstacle_radius = self.eta / MembraneSimulator.length / 2
            box_begin_point = fe.Point(-self.w / MembraneSimulator.length, 0)
            box_end_point = fe.Point(self.w / MembraneSimulator.length,
                                     2 * self.eta / MembraneSimulator.length)
            box = mshr.Rectangle(box_begin_point, box_end_point)
            cell = box - mshr.Circle(
                fe.Point(0, self.eta / MembraneSimulator.length),
                self.obstacle_radius, mesh_size)
            self.cell_mesh = mshr.generate_mesh(cell, mesh_size)
            diff_coef = fe.Constant(
                ((0, 0), (0, self.D[1, 1])))  # limit for regularisation below.
        # elif method == 'diff_coef':
        #     print("Haha this is going to crash. Also it is horrible in accuracy")
        #     self.cell_mesh = fe.RectangleMesh(fe.Point(-self.w / MembraneSimulator.length, 0),
        #                                       fe.Point(self.w / MembraneSimulator.length,
        #                                                2 * self.eta / MembraneSimulator.length), mesh_size, mesh_size)
        #     diff_coef = fe.Expression(
        #         (('0', '0'), ('0', 'val * ((x[0] - c_x)*(x[0] - c_x) + (x[1] - c_y)*(x[1] - c_y) > r*r)')),
        #         val=(4 * self.ref_T * MembraneSimulator.d2 / MembraneSimulator.length ** 2), c_x=0,
        #         c_y=(self.eta / MembraneSimulator.length),
        #         r=self.obstacle_radius, degree=2, domain=self.cell_mesh)
        elif method == 'regularized':
            box_begin_point = fe.Point(-self.w / MembraneSimulator.length, 0)
            box_end_point = fe.Point(self.w / MembraneSimulator.length,
                                     2 * self.eta / MembraneSimulator.length)
            box = mshr.Rectangle(box_begin_point, box_end_point)
            obstacle_begin_point = fe.Point(
                -self.w / MembraneSimulator.length * self.obs_length,
                self.eta / MembraneSimulator.length * (1 - self.obs_height))
            obstacle_end_point = fe.Point(
                self.w / MembraneSimulator.length * self.obs_length,
                self.eta / MembraneSimulator.length * (1 + self.obs_height))
            obstacle = mshr.Rectangle(obstacle_begin_point, obstacle_end_point)
            cell = box - obstacle
            self.cell_mesh = mshr.generate_mesh(cell, mesh_size)
            diff_coef = fe.Constant(((self.obs_ratio * self.D[0, 0], 0),
                                     (0, self.D[1, 1])))  # defect matrix.
        else:
            raise ValueError("%s not a valid method to solve cell problem" %
                             method)
        self.cell_fs = fe.FunctionSpace(self.cell_mesh, 'P', 2)
        self.cell_solutions = [
            fe.Function(self.cell_fs),
            fe.Function(self.cell_fs)
        ]
        w = fe.TrialFunction(self.cell_fs)
        phi = fe.TestFunction(self.cell_fs)
        scaled_unit_vectors = [
            fe.Constant((1. / np.sqrt(self.obs_ratio), 0.)),
            fe.Constant((0., 1.))
        ]
        for i in range(2):
            weak_form = fe.dot(
                diff_coef *
                (fe.grad(w) + scaled_unit_vectors[i]), fe.grad(phi)) * fe.dx
            print("Solving cell problem")
            bc = fe.DirichletBC(self.cell_fs, fe.Constant(0),
                                MembraneSimulator.cell_boundary)
            if i == 0:
                # Periodicity is applied automatically
                bc = None
            fe.solve(
                fe.lhs(weak_form) == fe.rhs(weak_form), self.cell_solutions[i],
                bc)
            if plot:
                plt.rc('text', usetex=True)
                f = fe.plot(self.cell_solutions[i])
                plt.colorbar(f)
                plt.title(r'Solution to cell problem $w_%d$' % (i + 1))
                plt.xlabel(r'$Y_1$')
                plt.ylabel(r'$Y_2$')
                print("Cell solution")
                print(np.min(self.cell_solutions[i].vector().get_local()),
                      np.max(self.cell_solutions[i].vector().get_local()))
                plt.show()