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)
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
def __init__(self, mesh_resolution, polynomial_degree, adjust, L, h, c): self.h = h self.L = L self.c = c P1 = Point(0., 0.) P2 = Point(L + c, h) domain1 = mshr.Rectangle(P1, P2) P3 = Point(L, -h) P4 = Point(L + L, h + h) domain2 = mshr.Rectangle(P3, P4) domain = domain1 + domain2 self.insides = TShapedOverlap(self.L, self.h, self.c) self.outsides = OnBoundary() self.left_dirichlet = TShapedLeftDirichlet(self.L) self.left_robin = TShapedLeftRobin(self.L, self.c) self.right_dirichlet = TShapedRightDirichlet(self.L, self.h) self.right_robin = TShapedRightRobin(self.L, self.h) boundaries = list([ self.insides, self.outsides, self.left_dirichlet, self.left_robin, self.right_dirichlet, self.right_robin ]) Membrane.__init__(self, domain, domain1, domain2, mesh_resolution, boundaries, polynomial_degree, adjust)
def __init__(self, mesh_resolution, polynomial_degree, adjust, h, L, o): self.h = h self.L = L self.o = o self.b = L * (1 - o) / 2 b = self.b domain = mshr.Rectangle(Point(0., 0.), Point(L, h)) domain1 = mshr.Rectangle(Point( 0., 0., ), Point(b + L * o, h)) domain2 = mshr.Rectangle(Point(b, 0.), Point(L, h)) self.insides = Overlap(b, o, L) self.outsides = OnBoundary() self.left_dirichlet = LeftDirichlet(h) self.left_robin = LeftRobin(b, o, L) self.right_dirichlet = RightDirichlet(h, L) self.right_robin = RightRobin(b) boundaries = list([ self.insides, self.outsides, self.left_dirichlet, self.left_robin, self.right_dirichlet, self.right_robin ]) Membrane.__init__(self, domain, domain1, domain2, mesh_resolution, boundaries, polynomial_degree, adjust)
def Domain(n): # defining the L-shaped domain domain = mshr.Rectangle(Point(-1., -1.), Point(1., 1.)) - mshr.Rectangle( Point(0., -1.), Point(1., 0.)) mesh = mshr.generate_mesh(domain, n) # Creating classes that define the boundary of the domain class Left(SubDomain): def inside(self, x, on_boundary): return near(x[0], -1.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], -1.0) class Top(SubDomain): def inside(self, x, on_boundary): return near(x[1], 1.0) class CornerTop(SubDomain): def inside(self, x, on_boundary): return near(x[1], 0.0) and between(x[0], (0.0, 1.0)) class CornerLeft(SubDomain): def inside(self, x, on_boundary): return near(x[0], 0.0) and between(x[1], (-1.0, 0.0)) left = Left() top = Top() right = Right() bottom = Bottom() cleft = CornerLeft() ctop = CornerTop() # Initialize mesh function for the domain domains = CellFunction("size_t", mesh) domains.set_all(0) # Initialize mesh function for boundary domains boundaries = FacetFunction("size_t", mesh) boundaries.set_all(0) left.mark(boundaries, 1) top.mark(boundaries, 1) bottom.mark(boundaries, 1) right.mark(boundaries, 1) cleft.mark(boundaries, 2) ctop.mark(boundaries, 2) return mesh, boundaries, domains
def add_rectangle_obstacle(self, p1, p2, mirror=False): self._map -= mshr.Rectangle( self.__correct_point(Point(p1[0], p1[1]), inverse=-1), self.__correct_point(Point(p2[0], p2[1]))) # Replicate the data the other side of the map. if mirror: p1bis = Point( self.dimension[0] + self.robot_radius - p1[0] + self.robot_radius, p1[1] - self.robot_radius) p2bis = Point( self.dimension[0] + self.robot_radius - p2[0] - self.robot_radius, p2[1] + self.robot_radius) self._map -= mshr.Rectangle(p2bis, p1bis)
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()
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)
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 square(self, length, origin=None): if origin is None: x, y = 0, 0 else: x, y = origin[0], origin[1] return mshr.Rectangle(FEN.Point(0 + x, 0 + y), FEN.Point(length + x, length + y))
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
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()
def make_cell(i, j, L0, base_pore_points): pore = build_pore_polygon(base_pore_points, offset=(L0 * (i + 0.5), L0 * (j + 0.5))) cell = mshr.Rectangle(fa.Point(L0 * i, L0 * j), fa.Point(L0 * (i + 1), L0 * (j + 1))) material_in_cell = cell - pore return material_in_cell
def __init__(self, pointa, pointb, *, eps = csg_eps): eps *= numpy.linalg.norm(numpy.array(pointb)-numpy.array(pointa)) super().__init__(mshr.Rectangle(dolfin.Point(*pointa), dolfin.Point(*pointb)), csg_boundaries = [ dolfin.CompiledSubDomain('on_boundary && near(x[0], xx, eps)', xx = pointa[0], eps = eps), dolfin.CompiledSubDomain('on_boundary && near(x[0], xx, eps)', xx = pointb[0], eps = eps), dolfin.CompiledSubDomain('on_boundary && near(x[1], xx, eps)', xx = pointa[1], eps = eps), dolfin.CompiledSubDomain('on_boundary && near(x[1], xx, eps)', xx = pointb[1], eps = eps) ])
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) ]) notch = mshr.Polygon([ fe.Point(0, self.height / 2 + 1e-10), fe.Point(0, self.height / 2 - 1e-10), fe.Point(self.length / 2, self.height / 2) ]) # notch = mshr.Polygon([fe.Point(self.length / 4, self.height / 2), fe.Point(self.length / 2, self.height / 2 - 1e-10), \ # fe.Point(self.length * 3 / 4, self.height / 2), fe.Point(self.length / 2, self.height / 2 + 1e-10)]) self.mesh = mshr.generate_mesh(plate - notch, 50) # self.mesh = da.RectangleMesh(fe.Point(0, 0), fe.Point(self.length, self.height), 40, 40, diagonal="crossed") 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) 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 Notch(fe.SubDomain): def inside(self, x, on_boundary): return fe.near(x[1], height / 2) and x[0] < length / 20 self.lower = Lower() self.upper = Upper() self.corner = Corner() self.left = Left() self.right = Right() self.notch = Notch()
def mfem(): files = glob.glob('data/pvd/mfem/*') for f in files: try: os.remove(f) except Exception as e: print('Failed to delete {}, reason: {}' % (f, e)) plate = mshr.Rectangle(fe.Point(0, 0), fe.Point(100, 100)) mesh = mshr.generate_mesh(plate, 50) # mesh = fe.RectangleMesh(fe.Point(-2, -2), fe.Point(2, 2), 50, 50) x_hat = fe.SpatialCoordinate(mesh) U = fe.VectorFunctionSpace(mesh, 'CG', 2) V = fe.FunctionSpace(mesh, "CG", 1) W = fe.FunctionSpace(mesh, "DG", 0) # n = 21 # control_points = np.stack((np.linspace(0, 1, n), np.linspace(0, 1, n)), axis=1) # impact_radii = np.linspace(0., 0.5, n) rho_default = 25. / np.sqrt(5) * 2 control_points = np.array([[50., 50.], [62.5, 25.]]) impact_radii = np.array([rho_default, rho_default]) mid_point = np.array([75., 0.]) mid_point1 = np.array([100., 0.]) mid_point2 = np.array([50., 0.]) points = [mid_point, mid_point1, mid_point2] direct_vec = np.array([1., -2]) rotated_vec = np.array([2., 1.]) direct_vec /= np.linalg.norm(direct_vec) rotated_vec /= np.linalg.norm(rotated_vec) directions = [direct_vec, rotated_vec] boundary_info = [points, directions, rho_default] # df, xi = distance_function_segments_ufl(x_hat, control_points, impact_radii) # d = fe.project(df, V) delta_x = map_function_ufl(x_hat, control_points, impact_radii, boundary_info) - x_hat u = fe.project(delta_x, U) # e = fe.Function(U) # int_exp = InterpolateExpression(u, control_points, impact_radii) # e = fe.interpolate(int_exp, U) # int_exp = InterpolateExpression(e, control_points, impact_radii) # e = fe.project(int_exp, U) vtkfile_u = fe.File('data/pvd/mfem/u.pvd') u.rename("u", "u") vtkfile_u << u
def __init__(self, dimension, robot_radius): self.robot_radius = robot_radius # Correct the map size by the robot_radius self.dimension = list(map(lambda x: x - robot_radius, dimension)) self._cache_path = '/tmp/mesh.xml' # Define the base rectangle. self._map = mshr.Rectangle(Point(robot_radius, robot_radius), Point(self.dimension[0], self.dimension[1])) self._mesh2d = None
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
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()
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
def __init__(self, mesh_resolution, polynomial_degree, adjust, L1, L2, h1, h2, b): self.L1 = L1 self.L2 = L2 self.h1 = h1 self.h2 = h2 self.b = b p1 = Point(0., 0.) p2 = Point(L1, h1) p3 = Point(L1 + b, h1) p4 = Point(L1, 0.) domain1 = mshr.Rectangle(p1, p2) + mshr.Polygon([p4, p3, p2]) p5 = Point(L1, -(h2 - h1)) p6 = Point(L1 + L2, h1) domain2 = mshr.Rectangle(p5, p6) domain = domain1 + domain2 self.insides = LShapedOverlap(self.L1, self.h1, self.b) self.outsides = OnBoundary() self.left_dirichlet = LShapedLeftDirichlet(self.h1) self.left_robin = LShapedLeftRobin(self.L1, self.h1, self.b) self.right_dirichlet = LShapedRightDirichlet(self.L1, self.L2, self.h1, self.h2) self.right_robin = LShapedRightRobin(self.L1, self.h1, self.b) boundaries = list([ self.insides, self.outsides, self.left_dirichlet, self.left_robin, self.right_dirichlet, self.right_robin ]) Membrane.__init__(self, domain, domain1, domain2, mesh_resolution, boundaries, polynomial_degree, adjust)
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()
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
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 build_mesh(self): self.length = 1. self.height = 1. plate = mshr.Rectangle(fe.Point(0, 0), fe.Point(self.length, self.height)) notch = mshr.Polygon([ fe.Point(0, self.height / 2 + 1e-10), fe.Point(0, self.height / 2 - 1e-10), fe.Point(self.length / 2, self.height / 2) ]) resolution = 50 * np.power(2, self.local_refinement_iteration) self.mesh = mshr.generate_mesh(plate - notch, resolution) 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 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.lower = Lower() self.upper = Upper() self.corner = Corner() self.left = Left() self.right = Right()
def method(res=10, height=1, length=5, use_mshr=False, show=False, **kwargs): ''' Function that generates a mesh for a straight capillary, default meshing method is Dolfin's RectangleMesh, but there is an option for mshr. Note: The generated mesh is stored in "BERNAISE/meshes/". ''' if use_mshr: # use mshr for the generation info("Generating mesh using the mshr tool") # Define coners of Rectangle a = df.Point(0, 0) b = df.Point(height, length) domain = mshr.Rectangle(a, b) mesh = mshr.generate_mesh(domain, res) meshpath = os.path.join( MESHES_DIR, "straight_capillary_mshr_h{}_l{}_res{}".format( height, length, res)) info("Done.") else: # use the Dolfin built-in function info("Generating mesh using the Dolfin built-in function.") # Define coners of rectangle/capilar a = df.Point(0, 0) b = df.Point(height, length) # Setting the reselution if height <= length: num_points_height = res num_points_length = res * int(length / height) else: num_points_height = res * int(height / length) num_points_length = res mesh = df.RectangleMesh(a, b, num_points_height, num_points_length) meshpath = os.path.join( MESHES_DIR, "straight_capillary_dolfin_h{}_l{}_res{}".format( height, length, res)) store_mesh_HDF5(mesh, meshpath) if show: df.plot(mesh) plt.show()
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 method(res=10, height=1, length=5, use_mshr=False, **kwargs): ''' Function that generates a mesh for a straight capilar, default meshing method is dolfin's "RectangleMesh" but has an option for mshr. Note: The generated mesh is stored in "BERNAISE/meshes/". ''' if use_mshr: # use mshr for the generation info("Generating mesh using the mshr tool") # Define coners of Rectangle a = df.Point(0, 0) b = df.Point(height, length) domain = mshr.Rectangle(a, b) mesh = mshr.generate_mesh(domain, res) meshpath = os.path.join( MESHES_DIR, "StraightCapilarMshr_h" + str(height) + "_l" + str(length) + "_res" + str(res)) info("Done.") else: # use the Dolfin built-in function info("Generating mesh using the Dolfin built-in function.") # Define coners of rectangle/capilar a = df.Point(0, 0) b = df.Point(height, length) # Setting the reselution if height <= length: num_points_height = res num_points_length = res * int(length / height) else: num_points_height = res * int(height / length) num_points_length = res mesh = df.RectangleMesh(a, b, num_points_height, num_points_length) meshpath = os.path.join( MESHES_DIR, "StraightCapilarDolfin_h" + str(height) + "_l" + str(length) + "_res" + str(res)) store_mesh_HDF5(mesh, meshpath)
def __init__(self, mesh_resolution, polynomial_degree, adjust, a, b, L, h, foot): self.center = Point(0., 0.) self.a = a self.b = b self.L = L if (L < foot + a - a * np.sqrt((1 - (h**2) / (4 * (b**2))))): print('ERROR: Selected L is too small.') elif (L > foot + a + a * np.sqrt((1 - (h**2) / (4 * (b**2))))): print('ERROR: Select L is too big.') self.h = h self.f = foot self.fx = -a * np.sqrt((1 - (h**2) / (4 * (b**2)))) self.fy = h / 2 P1 = Point(-a - foot, -h / 2) P2 = Point(-a - foot + L, h / 2) domain1 = mshr.Rectangle(P1, P2) center = Point(0., 0.) domain2 = mshr.Ellipse(center, a, b) domain = domain1 + domain2 self.insides = FinOverlap(self.L, self.h, self.a, self.b, self.f, self.fx) self.outsides = OnBoundary() self.left_dirichlet = FinShapedLeftDirichlet(self.fx) self.left_robin = FinShapedLeftRobin(self.fx) self.right_dirichlet = FinShapedRightDirichlet(self.fx) self.right_robin = FinShapedRightRobin(self.fx) boundaries = list([ self.insides, self.outsides, self.left_dirichlet, self.left_robin, self.right_dirichlet, self.right_robin ]) Membrane.__init__(self, domain, domain1, domain2, mesh_resolution, boundaries, polynomial_degree, adjust)
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()