def test_distance_triangle(): mesh = UnitSquareMesh(MPI.comm_self, 1, 1) cell = Cell(mesh, 1) assert round( cell.distance(Point(-1.0, -1.0)._cpp_object) - numpy.sqrt(2), 7) == 0 assert round(cell.distance(Point(-1.0, 0.5)._cpp_object) - 1, 7) == 0 assert round(cell.distance(Point(0.5, 0.5)._cpp_object) - 0.0, 7) == 0
def test_open_boundary(advection_scheme): xmin, xmax = 0., 1. ymin, ymax = 0., 1. pres = 3 mesh = RectangleMesh(Point(xmin, ymin), Point(xmax, ymax), 10, 10) # Particle x = RandomRectangle(Point(0.955, 0.45), Point(1., 0.55)).generate([pres, pres]) x = comm.bcast(x, root=0) # Given velocity field: vexpr = Constant((1., 1.)) # Given time do_step: dt = 0.05 p = particles(x, [x, x], mesh) V = VectorFunctionSpace(mesh, "CG", 1) v = Function(V) v.assign(vexpr) # Different boundary parts bound_left = UnitSquareLeft() bound_right = UnitSquareRight() bound_top = UnitSquareTop() bound_bottom = UnitSquareBottom() # Mark all facets facet_marker = MeshFunction('size_t', mesh, mesh.topology().dim() - 1) facet_marker.set_all(0) # Mark as open bound_right.mark(facet_marker, 2) # Mark other boundaries as closed bound_left.mark(facet_marker, 1) bound_top.mark(facet_marker, 1) bound_bottom.mark(facet_marker, 1) if advection_scheme == 'euler': ap = advect_particles(p, V, v, facet_marker) elif advection_scheme == 'rk2': ap = advect_rk2(p, V, v, facet_marker) elif advection_scheme == 'rk3': ap = advect_rk3(p, V, v, facet_marker) else: assert False # Do one timestep, particle must bounce from wall of ap.do_step(dt) num_particles = p.number_of_particles() # Check if all particles left domain if comm.rank == 0: assert(num_particles == 0)
def mesh_Cube(n=10): dom = mshr.Box(Point(0., 0., 0.), Point(1., 1., 1.)) gen = mshr.CSGCGALMeshGenerator3D() #gen.parameters["facet_angle"] = 30.0 #gen.parameters["facet_size"] = 0.5 #gen.parameters["edge_size"] = 0.5 gen.parameters["mesh_resolution"] = 0.01 gen.parameters["odt_optimize"] = True mesh = gen.generate(mshr.CSGCGALDomain3D(dom)) return mesh
def test_distance_tetrahedron(): mesh = UnitCubeMesh(MPI.comm_self, 1, 1, 1) cell = Cell(mesh, 5) assert round( cell.distance(Point(-1.0, -1.0, -1.0)._cpp_object) - numpy.sqrt(3), 7) == 0 assert round(cell.distance(Point(-1.0, 0.5, 0.5)._cpp_object) - 1, 7) == 0 assert round(cell.distance(Point(0.5, 0.5, 0.5)._cpp_object) - 0.0, 7) == 0
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 test_advect_periodic_facet_marker(advection_scheme): xmin, xmax = 0.0, 1.0 ymin, ymax = 0.0, 1.0 mesh = RectangleMesh(Point(xmin, ymin), Point(xmax, ymax), 10, 10) facet_marker = MeshFunction("size_t", mesh, mesh.topology().dim() - 1) facet_marker.set_all(0) boundaries = Boundaries() boundaries.mark(facet_marker, 3) lims = np.array([ [xmin, xmin, ymin, ymax], [xmax, xmax, ymin, ymax], [xmin, xmax, ymin, ymin], [xmin, xmax, ymax, ymax], ]) vexpr = Constant((1.0, 1.0)) V = VectorFunctionSpace(mesh, "CG", 1) x = RandomRectangle(Point(0.05, 0.05), Point(0.15, 0.15)).generate([3, 3]) x = comm.bcast(x, root=0) dt = 0.05 v = Function(V) v.assign(vexpr) p = particles(x, [x * 0, x**2], mesh) if advection_scheme == "euler": ap = advect_particles(p, V, v, facet_marker, lims.flatten()) elif advection_scheme == "rk2": ap = advect_rk2(p, V, v, facet_marker, lims.flatten()) elif advection_scheme == "rk3": ap = advect_rk3(p, V, v, facet_marker, lims.flatten()) else: assert False xp0 = p.positions() t = 0.0 while t < 1.0 - 1e-12: ap.do_step(dt) t += dt xpE = p.positions() # Check if position correct xp0_root = comm.gather(xp0, root=0) xpE_root = comm.gather(xpE, root=0) if comm.Get_rank() == 0: xp0_root = np.float32(np.vstack(xp0_root)) xpE_root = np.float32(np.vstack(xpE_root)) error = np.linalg.norm(xp0_root - xpE_root) assert error < 1e-10
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)
def UnstructuredRectangle(xa, ya, xb, yb, h): mesh = Mesh() domain_vertices = [ Point(xa, ya), Point(xa, yb), Point(xb, yb), Point(xb, ya), Point(xa, ya) ] PolygonalMeshGenerator.generate(mesh, domain_vertices, h) return mesh
def test_bounded_domain_boundary(xlims, ylims, advection_scheme): xmin, xmax = xlims ymin, ymax = ylims pres = 1 mesh = RectangleMesh(Point(xmin, ymin), Point(xmax, ymax), 10, 10) ymin += 0.0025 lims = np.array([xmin, xmax, ymin, ymax]) v_arr = np.array([-1.0, -1.0]) vexpr = Constant(v_arr) V = VectorFunctionSpace(mesh, "CG", 1) x = RandomRectangle(Point(0.05, 0.05), Point(0.15, 0.15)).generate([pres, pres]) dt = 0.005 v = Function(V) v.assign(vexpr) p = particles(x, [x], mesh) if advection_scheme == 'euler': ap = advect_particles(p, V, v, 'bounded', lims.flatten()) elif advection_scheme == 'rk2': ap = advect_rk2(p, V, v, 'bounded', lims.flatten()) elif advection_scheme == 'rk3': ap = advect_rk3(p, V, v, 'bounded', lims.flatten()) else: assert False original_num_particles = p.number_of_particles() t = 0. while t < 3.0 - 1e-12: ap.do_step(dt) t += dt assert p.number_of_particles() == original_num_particles xpn = np.array(p.get_property(0)).reshape((-1, 2)) x0 = np.array(p.get_property(1)).reshape((-1, 2)) analytical_position = x0 + t * v_arr analytical_position[:, 0] = np.maximum( np.minimum(xmax, analytical_position[:, 0]), xmin) analytical_position[:, 1] = np.maximum( np.minimum(ymax, analytical_position[:, 1]), ymin) error = np.abs(xpn - analytical_position) assert np.all(np.abs(error) < 1e-12)
def setup_geometry(): # Generate mesh xmin, xmax = -10.0, 10.0 ymin, ymax = -0.5, 0.5 geometry = Rectangle(Point(xmin, ymin), Point(xmax, ymax)) mesh_resolution = 50 mesh = generate_mesh(geometry, mesh_resolution) # Define boundary def boundary(x, on_boundary): return on_boundary return mesh, boundary
def test_near_evaluations(R, mesh): # Test that we allow point evaluation that are slightly outside u0 = Function(R) u0.vector()[:] = 1.0 a = Vertex(mesh, 0).point().array() offset = 0.99 * DOLFIN_EPS a_shift_x = Point(a[0] - offset, a[1], a[2]).array() assert round(u0(a)[0] - u0(a_shift_x)[0], 7) == 0 a_shift_xyz = Point(a[0] - offset / sqrt(3), a[1] - offset / sqrt(3), a[2] - offset / sqrt(3)).array() assert round(u0(a)[0] - u0(a_shift_xyz)[0], 7) == 0
def test_advect_open(advection_scheme): pres = 3 mesh = UnitCubeMesh(10, 10, 10) # Particle x = RandomBox(Point(0.955, 0.45, 0.5), Point(0.99, 0.55, 0.6)).generate([pres, pres, pres]) x = comm.bcast(x, root=0) # Given velocity field: vexpr = Constant((1.0, 1.0, 1.0)) # Given time do_step: dt = 0.05 p = particles(x, [x, x], mesh) V = VectorFunctionSpace(mesh, "CG", 1) v = Function(V) v.assign(vexpr) # Different boundary parts bounds = Boundaries() bound_right = UnitCubeRight() # Mark all facets facet_marker = MeshFunction("size_t", mesh, mesh.topology().dim() - 1) facet_marker.set_all(0) bounds.mark(facet_marker, 1) bound_right.mark(facet_marker, 2) # Mark as open bound_right.mark(facet_marker, 2) if advection_scheme == "euler": ap = advect_particles(p, V, v, facet_marker) elif advection_scheme == "rk2": ap = advect_rk2(p, V, v, facet_marker) elif advection_scheme == "rk3": ap = advect_rk3(p, V, v, facet_marker) else: assert False # Do one timestep, particle must bounce from wall of ap.do_step(dt) num_particles = p.number_of_particles() # Check if all particles left domain if comm.rank == 0: assert num_particles == 0
def test_near_evaluations(R, mesh): # Test that we allow point evaluation that are slightly outside bb_tree = cpp.geometry.BoundingBoxTree(mesh, mesh.geometry.dim) u0 = Function(R) u0.vector().set(1.0) a = Vertex(mesh, 0).point().array() offset = 0.99 * np.finfo(float).eps a_shift_x = Point(a[0] - offset, a[1], a[2]).array() assert round(u0(a, bb_tree)[0] - u0(a_shift_x, bb_tree)[0], 7) == 0 a_shift_xyz = Point(a[0] - offset / math.sqrt(3), a[1] - offset / math.sqrt(3), a[2] - offset / math.sqrt(3)).array() assert round(u0(a, bb_tree)[0] - u0(a_shift_xyz, bb_tree)[0], 7) == 0
def gen_mesh(n_gridpoints, dim): if dim == 2: #if(dolfin.__version__[2] <= 4): # mesh = RectangleMesh(0,0,1,1,n_gridpoints,n_gridpoints,"left"); #else: p0 = Point(0, 0) p1 = Point(1, 1) mesh = RectangleMesh(p0, p1, n_gridpoints, n_gridpoints, "left") else: p0 = Point(0, 0, 0) p1 = Point(1, 1, 0) mesh = BoxMesh(p0, p1, n_gridpoints, n_gridpoints, n_gridpoints) return mesh
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 EvaluateReference(self, VectorComponent=None, TensorComponent=None): y = zeros(self._points.shape[0]) if VectorComponent is None and TensorComponent is None: for i, row in enumerate(self._points): y[i] = self._f(Point(row)) elif VectorComponent is not None: for i, row in enumerate(self._points): y[i] = self._f(Point(row))[VectorComponent] elif TensorComponent is not None: for i, row in enumerate(self._points): y[i] = self._f(Point(row))[TensorComponent] return y
def test_compute_first_entity_collision_2d(): reference = [136, 137] p = Point(0.3, 0.3) mesh = UnitSquareMesh(MPI.comm_world, 16, 16) tree = BoundingBoxTree(mesh, mesh.topology.dim) first = tree.compute_first_entity_collision(p, mesh) assert first in reference
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)
def _locate_event(self, event): 'Find cells(indices) where the key press was initiated.' # Locate all the cells that intersect event point. If locating is done # by compute_first_collision the cells are difficult to mark. bb_tree = self.mesh.bounding_box_tree() try: # Get coordinates of the event point x_string = self.axes.format_coord(event.xdata, event.ydata) split_on = ',' if x_string.find(',') > -1 else ' ' try: x = map( float, [w.split('=')[1] for w in x_string.split(split_on) if w]) cell_indices = bb_tree.compute_entity_collisions(Point(*x)) # Click outside figure? except ValueError: message = 'Are you clicking outside the active figure?' self.printer(message, 'pink') cell_indices = [] # Click outside figure? except TypeError: message = 'Are you clicking outside the active figure?' self.printer(message, 'pink') cell_indices = [] return cell_indices
def _build_eval_matrix(V, points): """Build the sparse m-by-n matrix that maps a coefficient set for a function in V to the values of that function at m given points.""" # See <https://www.allanswered.com/post/lkbkm/#zxqgk> mesh = V.mesh() bbt = BoundingBoxTree() bbt.build(mesh) dofmap = V.dofmap() el = V.element() sdim = el.space_dimension() rows = [] cols = [] data = [] for i, x in enumerate(points): cell_id = bbt.compute_first_entity_collision(Point(*x)) cell = Cell(mesh, cell_id) coordinate_dofs = cell.get_vertex_coordinates() rows.append(np.full(sdim, i)) cols.append(dofmap.cell_dofs(cell_id)) v = el.evaluate_basis_all(x, coordinate_dofs, cell_id) data.append(v) rows = np.concatenate(rows) cols = np.concatenate(cols) data = np.concatenate(data) m = len(points) n = V.dim() matrix = sparse.csr_matrix((data, (rows, cols)), shape=(m, n)) return matrix
def test_point_array(): p = Point(1, 2, 3) assert np.all(p.array() == (1, 2, 3)) # Point.array() is a copy, no in-place modification p.array()[:] += 1000.0 assert np.all(p.array() == (1, 2, 3))
def test_point_setitem(): p = Point() p[0] = 6.0 assert p[0] == 6.0 p[1] = 16.0 p[1] += 600.0 assert np.isclose(p[1], 616.0) p[2] = 111.0 p[2] *= 12.0 p[2] /= 2 assert np.isclose(p[2], 666.0) with pytest.raises(IndexError): p[3] = 6666.0 p[:] = (0, 0, 0) assert np.all(p[:] == 0) p[:] = (1, 2, 3) assert np.all(p[:] == (1, 2, 3)) p[:] += np.array((1, 2, 3)) assert np.all(p[:] == (2, 4, 6)) p[:] /= 2 assert np.all(p[:] == (1, 2, 3)) p[:] *= np.array((2., 2., 2.)) assert np.all(p[:] == (2, 4, 6))
def test_cmscr1d_img_custom_mesh(self): print("Running test 'test_cmscr1d_img_custom_mesh'") # Create zero image. img = np.zeros((10, 25)) # Create custom mesh. m, n = img.shape mesh = RectangleMesh(Point(0, 0), Point(0.1, 1), m - 1, n - 1) v, k, res, fun, converged = cmscr1d_img(img, 1.0, 1.0, 1.0, 1.0, 1.0, 'mesh', mesh=mesh) np.testing.assert_allclose(v.shape, img.shape) np.testing.assert_allclose(v, np.zeros_like(v)) np.testing.assert_allclose(k.shape, img.shape) np.testing.assert_allclose(k, np.zeros_like(k))
def test_compute_first_collision_3d(): # FIXME: This test should not use facet indices as there are no guarantees # on how DOLFIN numbers facets reference = { 1: [1364], 2: [1967, 1968, 1970, 1972, 1974, 1976], 3: [876, 877, 878, 879, 880, 881] } p = Point(0.3, 0.3, 0.3) mesh = UnitCubeMesh(MPI.comm_world, 8, 8, 8) for dim in range(1, 4): tree = BoundingBoxTree(mesh.geometry.dim) tree.build_mesh(mesh, dim) first = tree.compute_first_collision(p) # FIXME: Face and test is excluded because it mistakingly # relies in the facet indices tdim = mesh.topology.dim if dim != tdim - 1 and dim != tdim - 2: assert first in reference[dim] # FIXME: remove after Mesh is wrapped in Python tree_cpp = mesh.bounding_box_tree() tree = BoundingBoxTree() tree._cpp_object = tree_cpp first = tree.compute_first_collision(p) assert first in reference[mesh.topology.dim]
def test_compute_first_collision_2d(): # FIXME: This test should not use facet indices as there are no guarantees # on how DOLFIN numbers facets reference = {1: [226], 2: [136, 137]} p = Point(0.3, 0.3) mesh = UnitSquareMesh(MPI.comm_world, 16, 16) for dim in range(1, 3): tree = BoundingBoxTree(mesh.geometry.dim) tree.build_mesh(mesh, dim) first = tree.compute_first_collision(p) # FIXME: Facet test is excluded because it mistakingly relies in the # facet indices if dim != mesh.topology.dim - 1: assert first in reference[dim] # FIXME: remove after Mesh is wrapped in Python tree_cpp = mesh.bounding_box_tree() tree = BoundingBoxTree() tree._cpp_object = tree_cpp first = tree.compute_first_collision(p) assert first in reference[mesh.topology.dim]
def test_compute_first_collision_3d(): # FIXME: This test should not use facet indices as there are no guarantees # on how DOLFIN numbers facets reference = { 1: [1364], 2: [1967, 1968, 1970, 1972, 1974, 1976], 3: [876, 877, 878, 879, 880, 881] } p = Point(0.3, 0.3, 0.3) mesh = UnitCubeMesh(8, 8, 8) for dim in range(1, 4): tree = BoundingBoxTree() tree.build(mesh, dim) first = tree.compute_first_collision(p) # FIXME: Face and test is excluded because it mistakingly # relies in the facet indices tdim = mesh.topology().dim() if dim != tdim - 1 and dim != tdim - 2: assert first in reference[dim] tree = mesh.bounding_box_tree() first = tree.compute_first_collision(p) assert first in reference[mesh.topology().dim()]
def test_manifold_point_search(): # Simple two-triangle surface in 3d vertices = [(0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)] cells = [(0, 1, 2), (0, 1, 3)] mesh = Mesh(MPI.comm_world, CellType.Type.triangle, numpy.array(vertices, dtype=numpy.float64), numpy.array(cells, dtype=numpy.int32), [], cpp.mesh.GhostMode.none) bb = mesh.bounding_box_tree() p = Point(0.5, 0.25, 0.75) assert bb.compute_first_entity_collision(p, mesh) == 0 p = Point(0.25, 0.5, 0.75) assert bb.compute_first_entity_collision(p, mesh) == 1
def test_mixed_parallel(): mesh = UnitSquareMesh(MPI.comm_world, 5, 8) V = VectorElement("Lagrange", triangle, 4) Q = FiniteElement("Lagrange", triangle, 5) W = FunctionSpace(mesh, Q * V) F = Function(W) @function.expression.numba_eval def expr_eval(values, x, cell_idx): values[:, 0] = x[:, 0] values[:, 1] = x[:, 1] values[:, 2] = numpy.sin(x[:, 0] + x[:, 1]) F.interpolate(Expression(expr_eval, shape=(3, ))) # Generate random points in this mesh partition (one per cell) x = numpy.zeros(3) for c in Cells(mesh): x[0] = random() x[1] = random() * (1 - x[0]) x[2] = (1 - x[0] - x[1]) p = Point(0.0, 0.0) for i, v in enumerate(VertexRange(c)): p += v.point() * x[i] p = p.array()[:2] val = F(p) assert numpy.allclose(val[0], p[0]) assert numpy.isclose(val[1], p[1]) assert numpy.isclose(val[2], numpy.sin(p[0] + p[1]))
def test_mesh_generator_2d(): """Basic functionality test.""" mesh = RectangleMesh(Point(0.0, 0.0), Point(1.0, 1.0), 5, 5) for x in mesh.coordinates(): x[0] += 0.5 * x[1] w = RandomCell(mesh) pts = w.generate(3) assert len(pts) == mesh.num_cells() * 3 interpolate_expression = Expression("x[0] + x[1]", degree=1) s = assign_particle_values(pts, interpolate_expression, on_root=False) p = particles(pts, [s], mesh) assert np.linalg.norm(np.sum(pts, axis=1) - s) <= 1e-15 assert np.linalg.norm(pts - p.positions()) <= 1e-15
def test_compute_first_entity_collision_3d(): reference = [876, 877, 878, 879, 880, 881] p = Point(0.3, 0.3, 0.3) mesh = UnitCubeMesh(MPI.comm_world, 8, 8, 8) tree = BoundingBoxTree(mesh, mesh.topology.dim) first = tree.compute_first_entity_collision(p, mesh) assert first in reference