Ejemplo n.º 1
0
 def domain(self, domaintype='meshpy'):
     if domaintype == 'meshpy':
         from meshpy.triangle import MeshInfo
         domain = MeshInfo()
         points = np.array([(0, 0), (48, 44), (48, 60), (0, 44)],
                           dtype=np.float)
         facets = np.array([(0, 1), (1, 2), (2, 3), (3, 0)], dtype=np.int)
         domain.set_points(points)
         domain.set_facets(facets)
         return domain
     if domaintype == 'halfedge':
         return None
Ejemplo n.º 2
0
def triangle_polygon_domain(points, facets, h, meshtype='tri'):
    from meshpy.triangle import MeshInfo, build
    mesh_info = MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(facets)
    mesh = build(mesh_info, max_volume=h**2)
    node = np.array(mesh.points, dtype=np.float)
    cell = np.array(mesh.elements, dtype=np.int)
    if meshtype is 'tri':
        return TriangleMesh(node, cell)
    elif meshtype is 'polygon':
        mesh = TriangleMeshWithInfinityNode(TriangleMesh(node, cell))
        pnode, pcell, pcellLocation = mesh.to_polygonmesh()
        return PolygonMesh(pnode, pcell, pcellLocation)
Ejemplo n.º 3
0
def triangle(box, h, meshtype='tri'):
    from meshpy.triangle import MeshInfo, build
    mesh_info = MeshInfo()
    mesh_info.set_points([(box[0], box[2]), (box[1], box[2]), (box[1], box[3]), (box[0], box[3])])
    mesh_info.set_facets([[0,1], [1,2], [2,3], [3,0]])  
    mesh = build(mesh_info, max_volume=h**2)
    node = np.array(mesh.points, dtype=np.float)
    cell = np.array(mesh.elements, dtype=np.int)
    if meshtype is 'tri':
        return TriangleMesh(node, cell)
    elif meshtype is 'polygon':
        mesh = TriangleMeshWithInfinityNode(TriangleMesh(node, cell))
        pnode, pcell, pcellLocation = mesh.to_polygonmesh()
        return PolygonMesh(pnode, pcell, pcellLocation) 
Ejemplo n.º 4
0
def get_mesh_example():
	area = rect((0.,0.),(1.,1.))
	init = rect((0.1,0.1),(0.2,0.2))
	goal1 = rect((0.8,0.8),(0.9,0.9))
	goal2 = rect((0.2,0.8),(0.3,0.9))

	env = area + goal1 + goal2 + init

	info = MeshInfo()
	info.set_points(env)
	info.set_facets(loop(0,4) + loop(4,8) + loop(8,12) + loop(12,16), facet_markers = [0]*4 + [1]*4 + [2]*4 + [3]*4) # Create 8 facets and apply markers 1-8 on them
	info.regions.resize(4)
	s = 0.05
	info.regions[0] = [0.15, 0.15, 0, s] # Replace 0.1 by a smaller value to produce a finer mesh
	info.regions[1] = [0.25, 0.85, 1, s] # Fourth item specifies maximum area of triangles as a region attribute
	info.regions[2] = [0.85, 0.85, 2, s] # Replace 0.1 by a smaller value to produce a finer mesh
	info.regions[3] = [0.5, 0.5, 3, s] # Fourth item specifies maximum area of triangles as a region attribute

	mesh = build(info, volume_constraints=True, attributes=True,
	generate_faces=True, min_angle=20, mesh_order=1)
	return mesh
Ejemplo n.º 5
0
    def make_mesh_triangle_meshpy(self, **params):
        """make_mesh_meshpy_triangle
        
        create mesh using meshpy.triangle.MeshInfo
        """
        c = params['c']
        mesh_info = MeshInfo()

        # generate vertices and facets
        if params['obj'] == 'line':
            points, facets, faces = make_vertex_facets_line(params)
        elif params['obj'] == 'hexagon':
            points, facets, faces = make_vertex_facets_hexagon(params)
        elif params['obj'] == 'rect':
            points, facets = make_vertex_facets_rect(params)

        print('points = {0}\nfacets = {1}'.format(pformat(points),
                                                  pformat(facets)))
        # print('mesh_info.unit = {0}'.format(mesh_info.unit))

        # copy points data into mesh
        mesh_info.set_points(points)

        # copy facets data into mesh
        mesh_info.set_facets(facets)

        # build the mesh
        mesh = build(mesh_info)

        # writing objects
        # mesh.write_vtk("trigrid.vtk")
        # f = open('trigrid.pkl', 'wb')
        # pickle.dump(mesh, f)
        # f.close()
        # joblib.dump(mesh, 'trigrid.pkl')
        # sys.exit()
        return mesh
Ejemplo n.º 6
0
def uniform_refine_triangles(points, elements, factor=2):
    new_points = points[:]
    new_elements = []
    old_face_to_new_faces = {}
    face_point_dict = {}

    points_per_edge = factor+1

    def get_refined_face(a, b):
        if a > b:
            a, b = b, a
            flipped = True
        else:
            flipped = False

        try:
            face_points = face_point_dict[a, b]
        except KeyError:
            a_pt, b_pt = [points[idx] for idx in [a, b]]
            dx = (b_pt - a_pt)/factor

            # build subdivided facet
            face_points = [a]

            for i in range(1, points_per_edge-1):
                face_points.append(len(new_points))
                new_points.append(a_pt + dx*i)

            face_points.append(b)

            face_point_dict[a, b] = face_points

            # build old_face_to_new_faces
            old_face_to_new_faces[frozenset([a, b])] = [
                    (face_points[i], face_points[i+1])
                    for i in range(factor)]

        if flipped:
            return face_points[::-1]
        else:
            return face_points

    for a, b, c in elements:
        a_pt, b_pt, c_pt = [points[idx] for idx in [a, b, c]]
        dr = (b_pt - a_pt)/factor
        ds = (c_pt - a_pt)/factor

        ab_refined, bc_refined, ac_refined = [
                get_refined_face(*pt_indices)
                for pt_indices in [(a, b), (b, c), (a, c)]]

        el_point_dict = {}

        # fill out edges of el_point_dict
        for i in range(points_per_edge):
            el_point_dict[i, 0] = ab_refined[i]
            el_point_dict[0, i] = ac_refined[i]
            el_point_dict[points_per_edge-1-i, i] = bc_refined[i]

        # fill out interior of el_point_dict
        for i in range(1, points_per_edge-1):
            for j in range(1, points_per_edge-1-i):
                el_point_dict[i, j] = len(new_points)
                new_points.append(a_pt + dr*i + ds*j)

        # generate elements
        for i in range(0, points_per_edge-1):
            for j in range(0, points_per_edge-1-i):
                new_elements.append((
                    el_point_dict[i, j],
                    el_point_dict[i+1, j],
                    el_point_dict[i, j+1],
                    ))
                if i+1+j+1 <= factor:
                    new_elements.append((
                        el_point_dict[i+1, j+1],
                        el_point_dict[i+1, j],
                        el_point_dict[i, j+1],
                        ))

    from meshpy.triangle import MeshInfo
    mi = MeshInfo()
    mi.set_points(new_points)
    mi.elements.resize(len(new_elements))
    for i, el in enumerate(new_elements):
        mi.elements[i] = el
    from meshpy.triangle import write_gnuplot_mesh
    write_gnuplot_mesh("mesh.dat", mi)

    return new_points, new_elements, old_face_to_new_faces
Ejemplo n.º 7
0
from fealpy.functionspace.mixed_fem_space import RaviartThomasFiniteElementSpace2d
from fealpy.functionspace.mixed_fem_space import BDMFiniteElementSpace2d
from fealpy.functionspace.mixed_fem_space import FirstNedelecFiniteElement2d


def mesh_2dpy(mesh_info, h):
    mesh = build(mesh_info, max_volume=(h)**2)
    point = np.array(mesh.points, dtype=np.float)
    cell = np.array(mesh.elements, dtype=np.int)
    tmesh = TriangleMesh(point, cell)
    return tmesh


mesh_info = MeshInfo()

mesh_info.set_points([(0, 0), (1, 0), (1, 1), (0, 1)])
mesh_info.set_facets([[0, 1], [1, 2], [2, 3], [3, 0]])
h = 0.5
tmesh = mesh_2dpy(mesh_info, h)

#point = np.array([
#    (0, 0),
#    (1, 0),
#    (1, 1),
#    (0, 1)], dtype=np.float)
#cell = np.array([
#    (1, 2, 0),
#    (3, 0, 2)], dtype=np.int)
#tmesh = TriangleMesh(point, cell)

space = RaviartThomasFiniteElementSpace2d(tmesh)
Ejemplo n.º 8
0
import numpy as np
import matplotlib.pyplot as plt
from meshpy.triangle import MeshInfo, build

# Utility function to create lists of the form [(1,2), (2,3), (3,4),
# (4,1)], given two numbers 1 and 4
from itertools import islice, cycle


def loop(a, b):
    return list(
        zip(list(range(a, b)), islice(cycle(list(range(a, b))), 1, None)))


info = MeshInfo()
info.set_points([(0, 0), (1, 0), (1, 1), (0, 1), (2, 0), (3, 0), (3, 1),
                 (2, 1)])
info.set_facets(loop(0, 4) + loop(4, 8), list(range(
    1, 9)))  # Create 8 facets and apply markers 1-8 on them
info.regions.resize(2)
info.regions[0] = [
    0.5,
    0.5,
    1,
    0.1,
]  # Fourth item specifies maximum area of triangles as a region attribute
info.regions[1] = [
    2.5,
    0.5,
    2,
    0.1,
]  # Replace 0.1 by a smaller value to produce a finer mesh
Ejemplo n.º 9
0
# Quadratic element demo, by Aravind Alwan

from numpy import *
from matplotlib.pyplot import *
from meshpy.triangle import MeshInfo, build

# Utility function to create lists of the form [(1,2), (2,3), (3,4),
# (4,1)], given two numbers 1 and 4
from itertools import islice, cycle
from six.moves import range
from six.moves import zip

loop = lambda a, b: list(zip(list(range(a, b)), islice(cycle(list(range(a, b))), 1, None)))

info = MeshInfo()
info.set_points([(0, 0), (1, 0), (1, 1), (0, 1), (2, 0), (3, 0), (3, 1), (2, 1)])
info.set_facets(loop(0, 4) + loop(4, 8), list(range(1, 9)))  # Create 8 facets and apply markers 1-8 on them
info.regions.resize(2)
info.regions[0] = [0.5, 0.5, 1, 0.1]  # Fourth item specifies maximum area of triangles as a region attribute
info.regions[1] = [2.5, 0.5, 2, 0.1]  # Replace 0.1 by a smaller value to produce a finer mesh

mesh = build(info, volume_constraints=True, attributes=True, generate_faces=True, min_angle=33, mesh_order=2)

pts = vstack(mesh.points)  # (npoints, 2)-array of points
elements = vstack(mesh.elements)  # (ntriangles, 6)-array specifying element connectivity

# Matplotlib's Triangulation module uses only linear elements, so use only first 3 columns when plotting
triplot(pts[:, 0], pts[:, 1], elements[:, :3])

plot(pts[:, 0], pts[:, 1], "ko")  # Manually plot all points including the ones at the midpoints of triangle faces
Ejemplo n.º 10
0
def uniform_refine_triangles(points, elements, factor=2):
    new_points = points[:]
    new_elements = []
    old_face_to_new_faces = {}
    face_point_dict = {}

    points_per_edge = factor + 1

    def get_refined_face(a, b):
        if a > b:
            a, b = b, a
            flipped = True
        else:
            flipped = False

        try:
            face_points = face_point_dict[a, b]
        except KeyError:
            a_pt, b_pt = [points[idx] for idx in [a, b]]
            dx = (b_pt - a_pt) / factor

            # build subdivided facet
            face_points = [a]

            for i in range(1, points_per_edge - 1):
                face_points.append(len(new_points))
                new_points.append(a_pt + dx * i)

            face_points.append(b)

            face_point_dict[a, b] = face_points

            # build old_face_to_new_faces
            old_face_to_new_faces[frozenset([a, b])] = [
                (face_points[i], face_points[i + 1]) for i in range(factor)
            ]

        if flipped:
            return face_points[::-1]
        else:
            return face_points

    for a, b, c in elements:
        a_pt, b_pt, c_pt = [points[idx] for idx in [a, b, c]]
        dr = (b_pt - a_pt) / factor
        ds = (c_pt - a_pt) / factor

        ab_refined, bc_refined, ac_refined = [
            get_refined_face(*pt_indices)
            for pt_indices in [(a, b), (b, c), (a, c)]
        ]

        el_point_dict = {}

        # fill out edges of el_point_dict
        for i in range(points_per_edge):
            el_point_dict[i, 0] = ab_refined[i]
            el_point_dict[0, i] = ac_refined[i]
            el_point_dict[points_per_edge - 1 - i, i] = bc_refined[i]

        # fill out interior of el_point_dict
        for i in range(1, points_per_edge - 1):
            for j in range(1, points_per_edge - 1 - i):
                el_point_dict[i, j] = len(new_points)
                new_points.append(a_pt + dr * i + ds * j)

        # generate elements
        for i in range(0, points_per_edge - 1):
            for j in range(0, points_per_edge - 1 - i):
                new_elements.append((
                    el_point_dict[i, j],
                    el_point_dict[i + 1, j],
                    el_point_dict[i, j + 1],
                ))
                if i + 1 + j + 1 <= factor:
                    new_elements.append((
                        el_point_dict[i + 1, j + 1],
                        el_point_dict[i + 1, j],
                        el_point_dict[i, j + 1],
                    ))

    from meshpy.triangle import MeshInfo
    mi = MeshInfo()
    mi.set_points(new_points)
    mi.elements.resize(len(new_elements))
    for i, el in enumerate(new_elements):
        mi.elements[i] = el
    from meshpy.triangle import write_gnuplot_mesh
    write_gnuplot_mesh("mesh.dat", mi)

    return new_points, new_elements, old_face_to_new_faces
Ejemplo n.º 11
0
from meshpy.triangle import MeshInfo, build, refine
import numpy as np

mesh_info = MeshInfo()
mesh_info.set_points([
    (0,0),
    (0,1),
    (1,1),
    (1,0)
    ])
mesh_info.set_facets([
    [0,1],
    [1,2],
    [2,3],
    [3,0]



    ])

def refinement_func(tri_points, area):
    max_area=0.001
    return bool(area>max_area);

mesh = build(mesh_info, refinement_func = refinement_func)

'''
print "Mesh Points:"
for i, p in enumerate(mesh.points):
    print i, p
print "Point numbers in tetrahedra:"
Ejemplo n.º 12
0
    nodes_remove_ID = np.unique(elements.simplices[coarsenIds][0])

    #redraw the delaunay triangles

    return findDelaunayTriangles(nodepts)


if __name__ == '__main__':
    #Create the intial mesh node pts
    nodepts = createInitialTriGridPts(4, 4)
    #Define the element triangles that link the nodes
    elements = defineElementConnectivity(nodepts)

    mesh_info = MeshInfo()
    print(nodepts)
    mesh_info.set_points(nodepts)
    print(elements.simplices)
    mesh_info.set_facets(elements.simplices)
    mesh = build(mesh_info)
    #mesh.triangle.
    write_gnuplot_mesh("test.vtk", mesh_info.points, facets=False)

    #triangle=showMesh(nodepts,elements.simplices)
    print(elements)
    print(elements.simplices)
    print(elements.points)

    nodepts, elements = refineMesh(nodepts, elements, 7)
    nodepts, elements = refineMesh(nodepts, elements, 20)
    #nodepts,elements = refineMesh(nodepts,elements,100)
    #nodepts,elements = refineMesh(nodepts,elements,50)
Ejemplo n.º 13
0
from  meshpy.triangle import MeshInfo, build
import numpy as np
import matplotlib.pyplot as plt
from fealpy.mesh import TriangleMesh
domain = MeshInfo()
domain.set_points([(0,0),(1,0),(1,1),(0,1)])
domain.set_facets([(0,1),(1,2),(2,3),(3,0)], facet_markers=[1, 2, 3, 4])
mesh = build(domain, max_volume = 0.1**2, attributes=True)
node = np.array(mesh.points, dtype = np.float)
cell = np.array(mesh.elements, dtype = np.int)
tmesh = TriangleMesh(node, cell)

fig = plt.figure()
axes =  fig.gca()
tmesh.add_plot(axes)

cell = tmesh.entity('cell')
node = tmesh.entity('node')
NN = tmesh.number_of_nodes()
isBdNode = tmesh.ds.boundary_node_flag()

newNode = np.zeros((NN, 2), dtype=np.float)
degree = np.zeros(NN, dtype=np.int)
np.add.at(degree, cell, 1)
for i in range(10):
    #bc = tmesh.entity_barycenter('cell')
    bc, R = tmesh.circumcenter()
    np.add.at(newNode, (cell, np.s_[:]), bc[:, np.newaxis, :])
    newNode /= degree[:, np.newaxis]
    node[~isBdNode] = newNode[~isBdNode]
    newNode[:] = 0
Ejemplo n.º 14
0
def discretise_faces(vertices, faces, target, min_angle=15, factor=3):
    """ Make discretised triangles from input coarse triangles data.

    Parameters
    ----------
    vertices : list
        Co-ordinates of coarse vertices.
    faces : list
        Vertex indices of each face of the coarse triangles.
    target : float
        Target edge length of each triangle.
    min_angle : float
        Minimum internal angle of triangles.
    factor : float
        Factor on the maximum area of each triangle.

    Returns
    -------
    list
        Vertices of the discretised trianlges.
    list
        Vertex numbers of the discretised trianlges.

    Notes
    -----
    - An experimental script.

    """

    points_all = []
    faces_all = []

    Amax = factor * 0.5 * target**2

    for count, face in enumerate(faces):

        # Seed

        face.append(face[0])

        points = []
        facets = []

        for u, v in zip(face[:-1], face[1:]):
            sp = vertices[u]
            ep = vertices[v]
            vec = subtract_vectors(ep, sp)
            l = length_vector(vec)
            div = l / target
            n = max([1, int(div)])
            for j in range(n):
                points.append(add_vectors(sp, scale_vector(vec, j / n)))
        facets = [[i, i + 1] for i in range(len(points) - 1)]
        facets.append([len(points) - 1, 0])

        # Starting orientation

        cent = centroid_points(points)
        vec1 = subtract_vectors(points[1], points[0])
        vec2 = subtract_vectors(cent, points[0])
        vecn = cross_vectors(vec1, vec2)

        # Rotate about x

        points = array(points).transpose()
        phi = -arctan2(vecn[2], vecn[1]) + 0.5 * pi
        Rx = array([[1, 0, 0], [0, cos(phi), -sin(phi)],
                    [0, sin(phi), cos(phi)]])
        vecn_x = dot(Rx, array(vecn)[:, newaxis])
        points_x = dot(Rx, points)
        Rx_inv = inv(Rx)

        # Rotate about y

        psi = +arctan2(vecn_x[2, 0], vecn_x[0, 0]) - 0.5 * pi
        Ry = array([[cos(psi), 0, sin(psi)], [0, 1, 0],
                    [-sin(psi), 0, cos(psi)]])
        points_y = dot(Ry, points_x)
        Ry_inv = inv(Ry)

        V = points_y.transpose()

        try:

            new_points = [list(i) for i in list(V[:, :2])]

            info = MeshInfo_tri()
            info.set_points(new_points)
            info.set_facets(facets)

            tris = build_tri(info,
                             allow_boundary_steiner=False,
                             min_angle=min_angle,
                             max_volume=Amax)
            new_points = [list(j) + [V[0, 2]] for j in tris.points]
            new_tris = [list(j) for j in tris.elements]

            V = array(new_points)
            points = dot(Ry_inv, V.transpose())
            points_all.append(
                [list(i) for i in list(dot(Rx_inv, points).transpose())])
            faces_all.append(new_tris)

        except:

            print('***** ERROR discretising face {0} *****'.format(count))

    return points_all, faces_all
Ejemplo n.º 15
0
            newParent[:, 0] = np.repeat(idx, 4)
            newParent[:, 1] = ranges(4 * np.ones(NCC, dtype=np.int))
            child[idx, :] = np.arange(NC, NC + 4 * NCC).reshape(NCC, 4)

            cell = np.concatenate((cell, newCell), axis=0)
            self.node = np.concatenate((node, edgeCenter, cellCenter), axis=0)
            self.parent = np.concatenate((parent, newParent), axis=0)
            self.child = np.concatenate((child, newChild), axis=0)
            self.ds.reinit(N + NEC + NCC, cell)
            return True
        else:
            return False


mesh_info = MeshInfo()
mesh_info.set_points([(-1, -1), (0, -1), (0, 0), (1, 0), (1, 1), (0, 1),
                      (1, 1), (-1, 0)])
mesh_info.set_facets([[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7],
                      [7, 0]])

h = 0.05
mesh = build(mesh_info, max_volume=h**2)
node = np.array(mesh.points, dtype=np.float)
cell = np.array(mesh.elements, dtype=np.int)
ttree = Tritree(node, cell)
mesh = ttree.to_mesh()

pde = LShapeRSinData()
integrator = mesh.integrator(3)
fem = PoissonFEMModel(pde, mesh, 1, integrator)
fem.solve()
eta = fem.recover_estimate()