Esempio n. 1
0
def test_tetgen():
    from meshpy.tet import MeshInfo, build
    mesh_info = MeshInfo()

    mesh_info.set_points([
        (0, 0, 0),
        (2, 0, 0),
        (2, 2, 0),
        (0, 2, 0),
        (0, 0, 12),
        (2, 0, 12),
        (2, 2, 12),
        (0, 2, 12),
        ])

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

    build(mesh_info)
Esempio n. 2
0
def main():
    #Test1: mesh testing
    MeshPoints = []
    MeshFacets = []
    with open('MeshFacets', 'rb') as input:
        MeshFacets = pickle.load(input)
    with open('MeshPoints', 'rb') as input:
        MeshPoints = pickle.load(input)

    mesh_info = MeshInfo()

    mesh_info.regions.resize(1)
    mesh_info.regions[0] = [
                            MeshPoints[0][0], MeshPoints[0][1], MeshPoints[0][2], # point in volume -> first box
                            0, # region tag (user-defined number)
                            1, # max tet volume in region
                            ]
    print "Building mesh from {} facets and {} points".format(len(MeshFacets), len(MeshPoints))
    try:
        mesh = build(mesh_info, options=Options(switches="pqT", epsilon=0.01), volume_constraints=True)
    except:
        pass
    try:
        mesh = build(mesh_info, options=Options(switches="pqT", epsilon=0.0001), volume_constraints=True)
    except:
        pass
    print "Created mesh with {} points, {} faces and {} elements.".format(len(mesh.points), len(mesh.faces), len(mesh.elements))
Esempio n. 3
0
def test_tetgen():
    from meshpy.tet import MeshInfo, build
    mesh_info = MeshInfo()

    mesh_info.set_points([
        (0, 0, 0),
        (2, 0, 0),
        (2, 2, 0),
        (0, 2, 0),
        (0, 0, 12),
        (2, 0, 12),
        (2, 2, 12),
        (0, 2, 12),
    ])

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

    build(mesh_info)
Esempio n. 4
0
def main():
    #Test1: mesh testing


    MeshPoints = []
    MeshFacets = []
    with open('MeshFacets', 'rb') as input:
        MeshFacets = pickle.load(input)
    with open('MeshPoints', 'rb') as input:
        MeshPoints = pickle.load(input)

    mesh_info = MeshInfo()

    mesh_info.regions.resize(1)
    mesh_info.regions[0] = [
                            MeshPoints[0][0], MeshPoints[0][1], MeshPoints[0][2], # point in volume -> first box
                            0, # region tag (user-defined number)
                            1, # max tet volume in region
                            ]
    print "Building mesh from {} facets and {} points".format(len(MeshFacets), len(MeshPoints))
    try:
        mesh = build(mesh_info, options=Options(switches="pqT", epsilon=0.01), volume_constraints=True)
    except:
        pass
    try:
        mesh = build(mesh_info, options=Options(switches="pqT", epsilon=0.0001), volume_constraints=True)
    except:
        pass
    print "Created mesh with {} points, {} faces and {} elements.".format(len(mesh.points), len(mesh.faces), len(mesh.elements))
Esempio n. 5
0
def tets_from_vertices_faces(vertices, faces, volume=None):
    """ Generate tetrahedron points and elements with MeshPy (TetGen).

    Parameters
    ----------
    vertices : list
        List of lists of vertex co-ordinates for the input surface mesh.
    faces : list
        List of lists of face indices for the input surface mesh.
    volume : float
        Volume constraint for each tetrahedron element.

    Returns
    -------
    list
        Points of the tetrahedrons.
    list
        Indices of points for each tetrahedron element.

    """

    try:
        info = MeshInfo()
        info.set_points(vertices)
        info.set_facets(faces)

        tets = build(info, max_volume=volume)
        points = [list(i) for i in list(tets.points)]
        elements = [list(i) for i in list(tets.elements)]

        return points, elements

    except:

        print('***** MeshPy failed *****')
Esempio n. 6
0
def create_beam(vol):
    # build using MeshPy
    from meshpy.tet import MeshInfo, build

    mesh_info = MeshInfo()

    mesh_info.set_points([
        (0, 0, 0),
        (0, 1, 0),
        (0, 1, 1),
        (0, 0, 1),
        (5, 0, 0),
        (5, 1, 0),
        (5, 1, 1),
        (5, 0, 1),
    ])

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

    mesh = build(mesh_info, max_volume=vol)

    return fmsh.MeshPyTet(mesh)
Esempio n. 7
0
def generateCubeMesh():
    mesh_info = MeshInfo()
    mesh_info.set_points([
        (0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0),
        (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1),
    ])
    mesh_info.set_facets([
        [0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 4, 5, 1],
        [1, 5, 6, 2],
        [2, 6, 7, 3],
        [3, 7, 4, 0],
    ])
    mesh = build(mesh_info)

    cellList = []
    vertexList = []
    mupifMesh = Mesh.UnstructuredMesh()

    print("Mesh Points:")
    for i, p in enumerate(mesh.points):
        print(i, p)
        vertexList.extend([Vertex.Vertex(i, i, p)])

    print("Point numbers in tetrahedra:")
    for i, t in enumerate(mesh.elements):
        print(i, t)
        cellList.extend([Cell.Tetrahedron_3d_lin(mupifMesh, i, i, t)])

    mupifMesh.setup(vertexList, cellList)

    return(mupifMesh)
Esempio n. 8
0
 def mesh(self):
     mesh_info = MeshInfo()
     mesh_info.set_points(transpose([self.flat_x,self.flat_y,self.flat_z]))
     mesh = build(mesh_info)
     print 'yo'
     for i, t in enumerate(mesh.elements):
         print i, t
Esempio n. 9
0
def main():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import \
            generate_surface_of_revolution, EXT_OPEN, \
            GeometryBuilder

    r = 3

    points = 10
    dphi = pi/points

    def truncate(r):
        if abs(r) < 1e-10:
            return 0
        else:
            return r

    rz = [(truncate(r*sin(i*dphi)), r*cos(i*dphi)) for i in range(points+1)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(rz,
            closure=EXT_OPEN, radial_subdiv=10))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh = build(mesh_info)
    mesh.write_vtk("ball.vtk")
Esempio n. 10
0
def create_ball_mesh(num_longi_points=10):

    radius = 5.0

    radial_subdiv = 2 * num_longi_points

    dphi = np.pi / num_longi_points

    # Make sure the nodes meet at the poles of the ball.
    def truncate(r):
        if abs(r) < 1e-10:
            return 0
        else:
            return r

    # Compute the volume of a canonical tetrahedron
    # with edgelength radius*dphi.
    a = radius * dphi
    canonical_tet_volume = np.sqrt(2.0) / 12 * a**3

    # Build outline for surface of revolution.
    rz = [(truncate(radius * np.sin(i * dphi)), radius * np.cos(i * dphi))
          for i in range(num_longi_points + 1)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(
        rz, closure=EXT_OPEN, radial_subdiv=radial_subdiv))
    mesh_info = MeshInfo()
    geob.set(mesh_info)
    meshpy_mesh = build(mesh_info, max_volume=canonical_tet_volume)

    return np.array(meshpy_mesh.points), np.array(meshpy_mesh.elements)
Esempio n. 11
0
def make_cylinder_mesh(radius=0.5, height=1, radial_subdivisions=10,
        height_subdivisions=1, max_volume=None, periodic=False,
        boundary_tagger=(lambda fvi, el, fn, all_v: [])):
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import make_cylinder

    points, facets, facet_holestarts, facet_markers = \
            make_cylinder(radius, height, radial_subdivisions,
                    height_subdivisions)

    assert len(facets) == len(facet_markers)

    if periodic:
        return _make_z_periodic_mesh(
                points, facets, facet_holestarts, facet_markers,
                height=height,
                max_volume=max_volume,
                boundary_tagger=boundary_tagger)
    else:
        mesh_info = MeshInfo()
        mesh_info.set_points(points)
        mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers)

        generated_mesh = build(mesh_info, max_volume=max_volume)

        from hedge.mesh import make_conformal_mesh_ext
        from hedge.mesh.element import Tetrahedron

        vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C")
        return make_conformal_mesh_ext(
                vertices,
                [Tetrahedron(i, el_idx, vertices)
                    for i, el_idx in enumerate(generated_mesh.elements)],
                boundary_tagger)
Esempio n. 12
0
def main():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import (
        generate_surface_of_revolution,
        EXT_CLOSED_IN_RZ,
        GeometryBuilder,
    )

    big_r = 3
    little_r = 2.9

    points = 50
    dphi = 2 * pi / points

    rz = [(big_r + little_r * cos(i * dphi), little_r * sin(i * dphi))
          for i in range(points)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(
        rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh_info.save_nodes("torus")
    mesh_info.save_poly("torus")
    mesh = build(mesh_info)
    mesh.write_vtk("torus.vtk")
    mesh.save_elements("torus_mesh")
    mesh.save_nodes("torus_mesh")

    mesh.write_neu(open("torus.neu", "w"), {1: ("pec", 0)})
Esempio n. 13
0
def main():
    mesh_info = MeshInfo()

    mesh_info.set_points([
        (0, 0, 0),
        (2, 0, 0),
        (2, 2, 0),
        (0, 2, 0),
        (0, 0, 12),
        (2, 0, 12),
        (2, 2, 12),
        (0, 2, 12),
        ])

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

    mesh_info.save_nodes("bar")
    mesh_info.save_poly("bar")

    mesh = build(mesh_info)

    mesh.save_nodes("barout")
    mesh.save_elements("barout")
    mesh.save_faces("barout")

    mesh.write_vtk("test.vtk")
Esempio n. 14
0
def main():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import \
            generate_surface_of_revolution, EXT_OPEN, \
            GeometryBuilder

    r = 1
    l = 1

    rz = [(0,0), (r,0), (r,l), (0,l)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(rz,
            radial_subdiv=20, ring_markers=[1,2,3]))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh = build(mesh_info, max_volume=0.01)
    mesh.write_vtk("cylinder.vtk")
    mesh.write_neu(open("cylinder.neu", "w"), {
        1: ("minus_z", 1),
        2: ("outer", 2),
        3: ("plus_z", 3),
        })
Esempio n. 15
0
def PlotTets():

    # Get the mesh
    from meshpy.tet import MeshInfo, build

    mesh_info = MeshInfo()
    mesh_info.set_points([(-1, -1, -1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1)])
    mesh_info.set_facets([[0, 2, 1], [0, 1, 3], [0, 3, 2], [2, 1, 3]])
    mesh = build(mesh_info, max_volume=0.0002)
    points = np.asarray(mesh.points)
    elements = np.asarray(mesh.elements)
    faces = np.asarray(mesh.faces)

    # mesh.save_faces('/home/roman/Desktop/test.dat')

    C = 2
    nsize = int((C + 2) * (C + 3) * (C + 4) / 6.)

    Bases = np.zeros((points.shape[0], nsize))
    for i in range(0, points.shape[0]):
        Bases[i, :] = Tet.hpBases(C, points[i, 0], points[i, 1], points[i,
                                                                        2])[0]

    mydict = {
        'points': points,
        'elements': elements,
        'faces': faces,
        'Bases': Bases
    }
    io.savemat(
        '/home/roman/Desktop/orthopoly/bases_tet_p' + str(C + 1) + '.mat',
        mydict)
Esempio n. 16
0
def main():
    mesh_info = MeshInfo()

    mesh_info.set_points([
        (0,0,0),
        (2,0,0),
        (2,2,0),
        (0,2,0),
        (0,0,12),
        (2,0,12),
        (2,2,12),
        (0,2,12),
        ])

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

    mesh_info.save_nodes("bar")
    mesh_info.save_poly("bar")

    mesh = build(mesh_info)

    mesh.save_nodes("barout")
    mesh.save_elements("barout")
    mesh.save_faces("barout")

    mesh.write_vtk("test.vtk")
Esempio n. 17
0
def main():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import \
            generate_surface_of_revolution, EXT_OPEN, \
            GeometryBuilder

    r = 1
    l = 1

    rz = [(0, 0), (r, 0), (r, l), (0, l)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(
        rz, radial_subdiv=20, ring_markers=[1, 2, 3]))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh = build(mesh_info, max_volume=0.01)
    mesh.write_vtk("cylinder.vtk")
    mesh.write_neu(file("cylinder.neu", "w"), {
        1: ("minus_z", 1),
        2: ("outer", 2),
        3: ("plus_z", 3),
    })
Esempio n. 18
0
def create_mesh(big_r=1.0, small_r=0.5, num_points=10):
    dphi = 2 * np.pi / num_points

    # Compute the volume of a canonical tetrahedron
    # with edgelength radius2*dphi.
    a = small_r * dphi
    canonical_tet_volume = np.sqrt(2.0) / 12 * a ** 3

    radial_subdiv = int(2 * np.pi * big_r / a)

    rz = [
        (big_r + small_r * np.cos(i * dphi), 0.5 * small_r * np.sin(i * dphi))
        for i in range(num_points)
    ]

    geob = GeometryBuilder()
    geob.add_geometry(
        *generate_surface_of_revolution(
            rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=radial_subdiv
        )
    )
    mesh_info = MeshInfo()
    geob.set(mesh_info)
    meshpy_mesh = build(mesh_info, max_volume=canonical_tet_volume)

    return np.array(meshpy_mesh.points), np.array(meshpy_mesh.elements)
Esempio n. 19
0
def create_beam(vol):
    # build using MeshPy
    from meshpy.tet import MeshInfo,build

    mesh_info = MeshInfo()

    mesh_info.set_points([
        (0,0,0),
        (0,1,0),
        (0,1,1),
        (0,0,1),
        (5,0,0),
        (5,1,0),
        (5,1,1),
        (5,0,1),
        ])

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


    mesh = build(mesh_info,max_volume=vol)

    return fmsh.MeshPyTet(mesh)
Esempio n. 20
0
def ball(h):
    from meshpy.geometry import (
        EXT_OPEN,
        GeometryBuilder,
        generate_surface_of_revolution,
    )
    from meshpy.tet import MeshInfo, build

    r = 3

    polar_subdivision = int(math.pi / h)
    dphi = math.pi / polar_subdivision

    def truncate(val):
        return 0 if abs(val) < 1e-10 else val

    rz = [
        [truncate(r * math.sin(i * dphi)), r * math.cos(i * dphi)]
        for i in range(polar_subdivision + 1)
    ]

    geob = GeometryBuilder()
    radial_subdivision = int(2 * math.pi / h)
    geob.add_geometry(
        *generate_surface_of_revolution(
            rz, closure=EXT_OPEN, radial_subdiv=radial_subdivision
        )
    )

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh = build(mesh_info)
    return numpy.array(mesh.points), numpy.array(mesh.elements)
Esempio n. 21
0
def main():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import generate_surface_of_revolution,\
            EXT_CLOSED_IN_RZ, GeometryBuilder

    big_r = 3
    little_r = 2.9

    points = 50
    dphi = 2*pi/points

    rz = [(big_r+little_r*cos(i*dphi), little_r*sin(i*dphi))
            for i in range(points)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(rz,
            closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh_info.save_nodes("torus")
    mesh_info.save_poly("torus")
    mesh = build(mesh_info)
    mesh.write_vtk("torus.vtk")
    mesh.save_elements("torus_mesh")
    mesh.save_nodes("torus_mesh")

    mesh.write_neu(file("torus.neu", "w"),
            {1: ("pec", 0)})
Esempio n. 22
0
def main():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import (
        generate_surface_of_revolution,
        EXT_OPEN,
        GeometryBuilder,
    )

    r = 3

    points = 10
    dphi = pi / points

    def truncate(r):
        if abs(r) < 1e-10:
            return 0
        else:
            return r

    rz = [(truncate(r * sin(i * dphi)), r * cos(i * dphi))
          for i in range(points + 1)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(
        rz, closure=EXT_OPEN, radial_subdiv=10))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh = build(mesh_info)
    mesh.write_vtk("ball.vtk")
Esempio n. 23
0
def generateCubeMesh():
    mesh_info = MeshInfo()
    mesh_info.set_points([
        (0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0),
        (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1),
    ])
    mesh_info.set_facets([
        [0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 4, 5, 1],
        [1, 5, 6, 2],
        [2, 6, 7, 3],
        [3, 7, 4, 0],
    ])
    mesh = build(mesh_info)

    cellList = []
    vertexList = []
    mupifMesh = Mesh.UnstructuredMesh()

    print("Mesh Points:")
    for i, p in enumerate(mesh.points):
        print(i, p)
        vertexList.extend([Vertex.Vertex(i, i, p)])

    print("Point numbers in tetrahedra:")
    for i, t in enumerate(mesh.elements):
        print(i, t)
        cellList.extend([Cell.Tetrahedron_3d_lin(mupifMesh, i, i, t)])

    mupifMesh.setup(vertexList, cellList)

    return(mupifMesh)
Esempio n. 24
0
def test_tet_mesh(visualize=False):
    pytest.importorskip("meshpy")

    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import \
            GeometryBuilder, generate_surface_of_revolution, EXT_CLOSED_IN_RZ

    pytest.importorskip("meshpy")

    big_r = 3
    little_r = 1.5

    points = 50
    dphi = 2 * pi / points

    rz = np.array(
        [[big_r + little_r * cos(i * dphi), little_r * sin(i * dphi)]
         for i in range(points)])

    geo = GeometryBuilder()
    geo.add_geometry(*generate_surface_of_revolution(
        rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geo.set(mesh_info)

    mesh = build(mesh_info)

    def tet_face_vertices(vertices):
        return [
            (vertices[0], vertices[1], vertices[2]),
            (vertices[0], vertices[1], vertices[3]),
            (vertices[0], vertices[2], vertices[3]),
            (vertices[1], vertices[2], vertices[3]),
        ]

    face_map = {}
    for el_id, el in enumerate(mesh.elements):
        for fid, face_vertices in enumerate(tet_face_vertices(el)):
            face_map.setdefault(frozenset(face_vertices), []).append(
                (el_id, fid))

    adjacency = {}
    for face_vertices, els_faces in face_map.items():
        if len(els_faces) == 2:
            (e1, f1), (e2, f2) = els_faces
            adjacency.setdefault(e1, []).append(e2)
            adjacency.setdefault(e2, []).append(e1)

    cuts, part_vert = pymetis.part_graph(17, adjacency)

    if visualize:
        import pyvtk

        vtkelements = pyvtk.VtkData(
            pyvtk.UnstructuredGrid(mesh.points, tetra=mesh.elements), "Mesh",
            pyvtk.CellData(pyvtk.Scalars(part_vert, name="partition")))
        vtkelements.tofile('split.vtk')
Esempio n. 25
0
def main():
    import numpy as np
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import \
            GeometryBuilder, generate_surface_of_revolution, EXT_CLOSED_IN_RZ

    big_r = 3
    little_r = 1.5

    points = 50
    dphi = 2*pi/points

    rz = np.array([[big_r+little_r*cos(i*dphi), little_r*sin(i*dphi)]
            for i in range(points)])

    geo = GeometryBuilder()
    geo.add_geometry(
            *generate_surface_of_revolution(rz,
                closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geo.set(mesh_info)

    mesh = build(mesh_info)

    def tet_face_vertices(vertices):
        return [(vertices[0], vertices[1], vertices[2]),
                (vertices[0], vertices[1], vertices[3]),
                (vertices[0], vertices[2], vertices[3]),
                (vertices[1], vertices[2], vertices[3]),
                ]

    face_map = {}
    for el_id, el in enumerate(mesh.elements):
        for fid, face_vertices in enumerate(tet_face_vertices(el)):
            face_map.setdefault(frozenset(face_vertices), []).append((el_id, fid))

    adjacency = {}
    for face_vertices, els_faces in face_map.items():
        if len(els_faces) == 2:
            (e1, f1), (e2, f2) = els_faces
            adjacency.setdefault(e1, []).append(e2)
            adjacency.setdefault(e2, []).append(e1)

    from pymetis import part_graph

    cuts, part_vert = part_graph(17, adjacency)

    try:
        import pyvtk
    except ImportError:
        print("Test succeeded, but could not import pyvtk to visualize result")
    else:
        vtkelements = pyvtk.VtkData(
            pyvtk.UnstructuredGrid(mesh.points, tetra=mesh.elements),
            "Mesh",
            pyvtk.CellData(pyvtk.Scalars(part_vert, name="partition")))
        vtkelements.tofile('split.vtk')
Esempio n. 26
0
def main():
    import numpy
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import GeometryBuilder, Marker, \
            generate_extrusion, make_box

    from meshpy.naca import generate_naca

    geob = GeometryBuilder()

    box_marker = Marker.FIRST_USER_MARKER

    wing_length = 2
    wing_subdiv = 5

    rz_points = [
        (0, -wing_length * 1.05),
        (0.7, -wing_length * 1.05),
    ] + [(r, x) for x, r in zip(
        numpy.linspace(-wing_length, 0, wing_subdiv, endpoint=False),
        numpy.linspace(0.8, 1, wing_subdiv, endpoint=False))] + [(1, 0)] + [
            (r, x) for x, r in zip(
                numpy.linspace(wing_length, 0, wing_subdiv, endpoint=False),
                numpy.linspace(0.8, 1, wing_subdiv, endpoint=False))
        ][::-1] + [(0.7, wing_length * 1.05), (0, wing_length * 1.05)]

    geob.add_geometry(*generate_extrusion(
        rz_points=rz_points,
        base_shape=generate_naca("0012", verbose=False, number_of_points=20),
        ring_markers=(wing_subdiv * 2 + 4) * [box_marker]))

    from meshpy.tools import make_swizzle_matrix
    swizzle_matrix = make_swizzle_matrix("z:x,y:y,x:z")
    geob.apply_transform(lambda p: numpy.dot(swizzle_matrix, p))

    def deform_wing(p):
        x, y, z = p
        return numpy.array([
            x, y + 0.1 * abs(x / wing_length)**2,
            z + 0.8 * abs(x / wing_length)**1.2
        ])

    geob.apply_transform(deform_wing)

    points, facets, _, facet_markers = make_box(
        numpy.array([-wing_length - 1, -1, -1.5]),
        numpy.array([wing_length + 1, 1, 3]))

    geob.add_geometry(points, facets, facet_markers=facet_markers)

    mesh_info = MeshInfo()
    geob.set(mesh_info)
    mesh_info.set_holes([(0, 0, 0.5)])

    mesh = build(mesh_info)
    print "%d elements" % len(mesh.elements)
    mesh.write_vtk("airfoil3d.vtk")
Esempio n. 27
0
def test_tet_mesh(visualize=False):
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import GeometryBuilder, generate_surface_of_revolution, EXT_CLOSED_IN_RZ

    pytest.importorskip("meshpy")

    big_r = 3
    little_r = 1.5

    points = 50
    dphi = 2*pi/points

    rz = np.array([[big_r+little_r*cos(i*dphi), little_r*sin(i*dphi)]
            for i in range(points)])

    geo = GeometryBuilder()
    geo.add_geometry(
            *generate_surface_of_revolution(rz,
                closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geo.set(mesh_info)

    mesh = build(mesh_info)

    def tet_face_vertices(vertices):
        return [(vertices[0], vertices[1], vertices[2]),
                (vertices[0], vertices[1], vertices[3]),
                (vertices[0], vertices[2], vertices[3]),
                (vertices[1], vertices[2], vertices[3]),
                ]

    face_map = {}
    for el_id, el in enumerate(mesh.elements):
        for fid, face_vertices in enumerate(tet_face_vertices(el)):
            face_map.setdefault(frozenset(face_vertices), []).append((el_id, fid))

    adjacency = {}
    for face_vertices, els_faces in face_map.items():
        if len(els_faces) == 2:
            (e1, f1), (e2, f2) = els_faces
            adjacency.setdefault(e1, []).append(e2)
            adjacency.setdefault(e2, []).append(e1)

    import ipdb; ipdb.set_trace()
    cuts, part_vert = pymetis.part_graph(17, adjacency)

    if visualize:
        import pyvtk

        vtkelements = pyvtk.VtkData(
            pyvtk.UnstructuredGrid(mesh.points, tetra=mesh.elements),
            "Mesh",
            pyvtk.CellData(pyvtk.Scalars(part_vert, name="partition")))
        vtkelements.tofile('split.vtk')
Esempio n. 28
0
def brep2lar(larBrep):
    V,FV = larBrep    
    mesh_info = MeshInfo()
    mesh_info.set_points(V)
    mesh_info.set_facets(FV)
    mesh = build(mesh_info)
    W = [v for h,v in enumerate(mesh.points)]
    CW = [tet for k,tet in enumerate(mesh.elements)]
    FW = sorted(set(AA(tuple)(CAT(AA(faces)(CW)))))
    EW = sorted(set(AA(tuple)(CAT(AA(edges)(FW)))))
    return W,CW,FW,EW
Esempio n. 29
0
def brep2lar(larBrep):
    V, FV = larBrep
    mesh_info = MeshInfo()
    mesh_info.set_points(V)
    mesh_info.set_facets(FV)
    mesh = build(mesh_info)
    W = [v for h, v in enumerate(mesh.points)]
    CW = [tet for k, tet in enumerate(mesh.elements)]
    FW = sorted(set(AA(tuple)(CAT(AA(faces)(CW)))))
    EW = sorted(set(AA(tuple)(CAT(AA(edges)(FW)))))
    return W, CW, FW, EW
Esempio n. 30
0
def test_tetgen_points():
    from meshpy.tet import MeshInfo, build, Options

    import numpy as np
    points = np.random.randn(10000, 3)

    mesh_info = MeshInfo()
    mesh_info.set_points(points)
    options = Options("")
    mesh = build(mesh_info, options=options)

    print(len(mesh.points))
    print(len(mesh.elements))
Esempio n. 31
0
def test_tetgen_points():
    from meshpy.tet import MeshInfo, build, Options

    import numpy as np
    points = np.random.randn(10000, 3)

    mesh_info = MeshInfo()
    mesh_info.set_points(points)
    options = Options("")
    mesh = build(mesh_info, options=options)

    print(len(mesh.points))
    print(len(mesh.elements))
Esempio n. 32
0
def test_torus():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import generate_surface_of_revolution, \
            EXT_CLOSED_IN_RZ, GeometryBuilder

    big_r = 3
    little_r = 2.9

    points = 50
    dphi = 2*pi/points

    rz = [(big_r+little_r*cos(i*dphi), little_r*sin(i*dphi))
            for i in range(points)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(rz,
            closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    build(mesh_info)
Esempio n. 33
0
def test_torus():
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import generate_surface_of_revolution, \
            EXT_CLOSED_IN_RZ, GeometryBuilder

    big_r = 3
    little_r = 2.9

    points = 50
    dphi = 2 * pi / points

    rz = [(big_r + little_r * cos(i * dphi), little_r * sin(i * dphi))
          for i in range(points)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(
        rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    build(mesh_info)
Esempio n. 34
0
def _make_z_periodic_mesh(points, facets, facet_holestarts, facet_markers, height,
        max_volume, boundary_tagger):
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import Marker

    mesh_info = MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers)

    mesh_info.pbc_groups.resize(1)
    pbcg = mesh_info.pbc_groups[0]

    pbcg.facet_marker_1 = Marker.MINUS_Z
    pbcg.facet_marker_2 = Marker.PLUS_Z

    pbcg.set_transform(translation=[0, 0, height])

    def zper_boundary_tagger(fvi, el, fn, all_v):
        # we only ask about *boundaries*
        # we should not try to have the user tag
        # the (periodicity-induced) interior faces

        face_marker = fvi2fm[frozenset(fvi)]

        if face_marker == Marker.MINUS_Z:
            return ["minus_z"]
        if face_marker == Marker.PLUS_Z:
            return ["plus_z"]

        result = boundary_tagger(fvi, el, fn, all_v)
        if face_marker == Marker.SHELL:
            result.append("shell")
        return result

    generated_mesh = build(mesh_info, max_volume=max_volume)
    fvi2fm = generated_mesh.face_vertex_indices_to_face_marker

    from hedge.mesh import make_conformal_mesh_ext
    from hedge.mesh.element import Tetrahedron

    vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C")
    return make_conformal_mesh_ext(
            vertices,
            [Tetrahedron(i, el_idx, vertices)
                for i, el_idx in enumerate(generated_mesh.elements)],
            zper_boundary_tagger,
            periodicity=[None, None, ("minus_z", "plus_z")])
Esempio n. 35
0
def main():
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import generate_surface_of_revolution, GeometryBuilder

    simple_rz = [(0, 0), (1, 1), (1, 2), (0, 3)]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(simple_rz))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    # mesh_info.save_nodes("test")
    # mesh_info.save_poly("test")
    # mesh_info.load_poly("test")
    mesh = build(mesh_info)
    mesh.write_vtk("my_mesh.vtk")
Esempio n. 36
0
def main():
    from optparse import OptionParser

    description = "generate a vtk mesh from a superfish input file"
    parser = OptionParser(description=description)
    parser.add_option(
	    "--point-dist", dest="point_dist", default=0.3, type="float",
	    help="Spacing of intermediate points in circular arcs")
    parser.add_option(
	    "--inverse", dest="generate_inverse", action="store_true",
	    help="Whether to mesh the inverse of the gun (useless, but fun)")
    parser.add_option(
	    "--radial-subdiv", dest="radial_subdiv", action="store", type="int",
            default=16, help="How many radial subdivisions")
    parser.add_option(
	    "--tube-radius", dest="tube_radius", action="store", type="float",
            default=0.1, help="Radius of the interior tube")

    options, args = parser.parse_args()

    from superfish import parse_superfish_format
    rz = parse_superfish_format(args[0], options.point_dist)

    build_kwargs = {}

    if options.generate_inverse:
        from rzmesh import inverse_mesh_info_from_rz
        mesh_info = inverse_mesh_info_from_rz(rz, options.radial_subdiv)
    elif options.tube_radius:
        from rzmesh import make_mesh_info_with_inner_tube
        mesh_info = make_mesh_info_with_inner_tube(rz, 
                options.tube_radius, options.radial_subdiv)

        build_kwargs["volume_constraints"] = True
    else:
        from rzmesh import make_mesh_info
        mesh_info = make_mesh_info_with_inner_tube(rz, options.radial_subdiv)

    #mesh_info.save_poly("gun")
    #mesh_info.save_nodes("gun")

    from meshpy.tet import build
    mesh = build(mesh_info, verbose=True, **build_kwargs)
    print "%d elements" % len(mesh.elements)
    mesh.write_vtk("gun.vtk")
Esempio n. 37
0
def main():
    from ply import parse_ply
    import sys
    data = parse_ply(sys.argv[1])

    from meshpy.geometry import GeometryBuilder

    builder = GeometryBuilder()
    builder.add_geometry(points=[pt[:3] for pt in data["vertex"].data],
                         facets=[fd[0] for fd in data["face"].data])
    builder.wrap_in_box(1)

    from meshpy.tet import MeshInfo, build
    mi = MeshInfo()
    builder.set(mi)
    mi.set_holes([builder.center()])
    mesh = build(mi)
    print("%d elements" % len(mesh.elements))
    mesh.write_vtk("out.vtk")
Esempio n. 38
0
def main():
    from ply import parse_ply
    import sys
    data = parse_ply(sys.argv[1])

    from meshpy.geometry import GeometryBuilder

    builder = GeometryBuilder()
    builder.add_geometry(
            points=[pt[:3] for pt in data["vertex"].data],
            facets=[fd[0] for fd in data["face"].data])
    builder.wrap_in_box(1)

    from meshpy.tet import MeshInfo, build
    mi = MeshInfo()
    builder.set(mi)
    mi.set_holes([builder.center()])
    mesh = build(mi)
    print("%d elements" % len(mesh.elements))
    mesh.write_vtk("out.vtk")
Esempio n. 39
0
def main():
    import numpy
    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import GeometryBuilder, Marker, make_box

    geob = GeometryBuilder()

    box_marker = Marker.FIRST_USER_MARKER
    extent_small = 0.1*numpy.ones(3, dtype=numpy.float64)
    points, facets, _, _ = \
            make_box(-extent_small, extent_small)

    geob.add_geometry(points, facets, facet_markers=box_marker)

    # make small "separator box" for region attribute
    geob.wrap_in_box(0.3)

    points, facets, _, facet_markers = \
            make_box(numpy.array([-1,-1,-1]), numpy.array([1,1,5]))

    geob.add_geometry(points, facets, facet_markers=facet_markers)

    mesh_info = MeshInfo()
    geob.set(mesh_info)
    mesh_info.set_holes([(0,0,0)])

    # region attributes
    mesh_info.regions.resize(1)
    mesh_info.regions[0] = (
            # point in region
            list(extent_small*2) + [
            # region number
            1,
            # max volume in region
            0.0001])

    mesh = build(mesh_info, max_volume=0.02, volume_constraints=True, attributes=True)
    print ("%d elements" % len(mesh.elements))
    mesh.write_vtk("box-in-box.vtk")
Esempio n. 40
0
def brep2lar(model,cycles,holes):
    V,FV,EV = model    
    FE = crossRelation(V,FV,EV)
    mesh_info = MeshInfo()
    mesh_info.set_points(V)
    mesh_info.set_facets_ex(cycles)
    #mesh_info.set_holes(holes)
    mesh = build(mesh_info,options=Options("pqYY"))
    W = [v for h,v in enumerate(mesh.points)]
    CW = [tet for k,tet in enumerate(mesh.elements)]
    
    def simplify(fun):
        def simplify0(simplices):
	    cellDict = defaultdict(tuple)
	    for cell in CAT(AA(fun)(simplices)):
	        cellDict[tuple(sorted(cell))] = tuple(cell)
	    return cellDict.values()
	return simplify0
    
    FW = sorted(simplify(faces)(CW))
    EW = sorted(simplify(edges)(FW))
    return W,CW,FW,EW
Esempio n. 41
0
def main():
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import generate_surface_of_revolution, GeometryBuilder

    simple_rz = [
        (0, 0),
        (1, 1),
        (1, 2),
        (0, 3),
    ]

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(simple_rz))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    # mesh_info.save_nodes("test")
    # mesh_info.save_poly("test")
    # mesh_info.load_poly("test")
    mesh = build(mesh_info)
    mesh.write_vtk("my_mesh.vtk")
Esempio n. 42
0
def build_tetmesh(domain, sphere_pieces, boundaries, config):
    """Handles calling TetGen to construct the tetrahedral mesh.
    :param domain Domain: spatial domain for mesh.
    :param sphere_pieces list: list of SpherePiece objects.
    :param boundaries list: list of boundaryPLC objects.
    :param config Config: configuration for mesh build.
    :return mesh: tetrahedral mesh.
    :rtype: MeshInfo.
    """
    logger.info('Building tetrahedral mesh')

    boundaries = duplicate_lower_boundaries(domain, boundaries)

    points = build_point_list(domain, sphere_pieces, boundaries)

    # Fix boundary points to exactly zero
    for i in range(3):
        points[(np.isclose(points[:, i], 0.), i)] = 0.

    facets, markers = build_facet_list(sphere_pieces, boundaries)
    holes = build_hole_list(sphere_pieces)

    rad_edge = config.tetgen_rad_edge_ratio
    min_angle = config.tetgen_min_angle
    max_volume = config.tetgen_max_volume

    options = tet.Options('pq{}/{}nzfennYCV'.format(rad_edge, min_angle))
    options.quiet = False

    mesh = tet.MeshInfo()
    mesh.set_points(points)
    mesh.set_facets(facets.tolist(), markers=markers.tolist())
    mesh.set_holes(holes)

    with redirect_tetgen_output():
        return tet.build(mesh,
                         options=options,
                         verbose=True,
                         max_volume=max_volume)
Esempio n. 43
0
def createSphere(center, R, m, n, mv=1):
    """
    The function computes the panelisation of a sphere using the predefined
    tools available in the Python module meshpy.
    
    INPUTS:
    - R:    radius of the sphere (m)
    - m:    number of radial subdivisions of the mesh (integer)
    - n:    number of circumferential subdivisions of the mesh (integer)
    - mv:   maxium valume of an element in the thetrahedral mesh 
            (the mesh is actually 3D but we only extract the surface panels)
    
    OUTPUTS:
    - verts:    coordinates of each vertices of the panelisation
    - faces:    triplets of indices representing the vertices of each triangular panel
    - tris:     triplets explicitly representing the coordinates of the vertices
                of each triangular face.
    """

    rz = []
    rz.append((0, R))
    for i in xrange(1, n):
        rz.append((R * np.sin(i * np.pi / n), R * np.cos(i * np.pi / n)))
    rz.append((0, -R))

    geob = GeometryBuilder()
    geob.add_geometry(*generate_surface_of_revolution(rz, radial_subdiv=m))

    mesh_info = MeshInfo()
    geob.set(mesh_info)

    mesh = build(mesh_info, max_volume=mv)

    verts = np.array(mesh.points)
    faces = np.array(mesh.faces)
    tris = verts[faces]
    bars = []
    return verts, bars, faces  # , tris
def createSphere(center, R, m, n, mv=1):
    """
    The function computes the panelisation of a sphere using the predefined
    tools available in the Python module meshpy.
    
    INPUTS:
    - R:    radius of the sphere (m)
    - m:    number of radial subdivisions of the mesh (integer)
    - n:    number of circumferential subdivisions of the mesh (integer)
    - mv:   maxium valume of an element in the thetrahedral mesh 
            (the mesh is actually 3D but we only extract the surface panels)
    
    OUTPUTS:
    - verts:    coordinates of each vertices of the panelisation
    - faces:    triplets of indices representing the vertices of each triangular panel
    - tris:     triplets explicitly representing the coordinates of the vertices
                of each triangular face.
    """
    
    rz = []
    rz.append((0, R))
    for i in xrange(1, n):
        rz.append((R * np.sin(i * np.pi / n), R * np.cos(i * np.pi / n)))
    rz.append((0, -R))

    geob = GeometryBuilder() 
    geob.add_geometry(*generate_surface_of_revolution(rz, radial_subdiv=m)) 

    mesh_info = MeshInfo() 
    geob.set(mesh_info) 

    mesh = build(mesh_info, max_volume=mv) 

    verts = np.array(mesh.points)
    faces = np.array(mesh.faces)
    tris = verts[faces]
    bars = []
    return verts, bars, faces  # , tris
Esempio n. 45
0
def triangulate(x, y, z, true_x=None, true_y=None, true_z=None):
    """Triangulate a point cloud.

    Given a 3-D point cloud, defined by x, y, z, perform a Delauny triangulation
    and return a list of elements.
    :param x: (Cartesian) x value.
    :param y: (Cartesian) y value.
    :param z: (Cartesian) z value.
    :returns: A list-of-lists containing connectivity of the resulting mesh.
    """

    print("COMPUTING DELAUNEY TRIANGULATION")
    # Set up the simplex vertices.
    pts = np.array((x, y, z)).T

    # Do the triangulation with MeshPy.
    # Currently, this seems like the fastest way.
    mesh_info = MeshInfo()
    mesh_info.set_points(pts)
    opts = Options("Q")
    mesh = build(mesh_info, options=opts)

    return mesh.elements
Esempio n. 46
0
def make_ball_mesh(r=0.5, subdivisions=10, max_volume=None,
        boundary_tagger=(lambda fvi, el, fn, all_v: [])):
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import make_ball

    points, facets, facet_holestarts, facet_markers = \
            make_ball(r, subdivisions)

    mesh_info = MeshInfo()

    mesh_info.set_points(points)
    mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers)
    generated_mesh = build(mesh_info, max_volume=max_volume)

    vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C")
    from hedge.mesh.element import Tetrahedron

    from hedge.mesh import make_conformal_mesh_ext
    return make_conformal_mesh_ext(
            vertices,
            [Tetrahedron(i, el_idx, vertices)
                for i, el_idx in enumerate(generated_mesh.elements)],
            boundary_tagger)
Esempio n. 47
0
def brep2lar(model, cycles, holes):
    V, FV, EV = model
    FE = crossRelation(V, FV, EV)
    mesh_info = MeshInfo()
    mesh_info.set_points(V)
    mesh_info.set_facets_ex(cycles)
    #mesh_info.set_holes(holes)
    mesh = build(mesh_info, options=Options("pqYY"))
    W = [v for h, v in enumerate(mesh.points)]
    CW = [tet for k, tet in enumerate(mesh.elements)]

    def simplify(fun):
        def simplify0(simplices):
            cellDict = defaultdict(tuple)
            for cell in CAT(AA(fun)(simplices)):
                cellDict[tuple(sorted(cell))] = tuple(cell)
            return cellDict.values()

        return simplify0

    FW = sorted(simplify(faces)(CW))
    EW = sorted(simplify(edges)(FW))
    return W, CW, FW, EW
Esempio n. 48
0
def main():
    import numpy
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import GeometryBuilder, Marker, make_box

    geob = GeometryBuilder()

    box_marker = Marker.FIRST_USER_MARKER
    extent_small = 0.3*numpy.ones(3, dtype=numpy.float64)
    points, facets, _, _ = \
            make_box(-extent_small, extent_small)

    geob.add_geometry(points, facets, facet_markers=box_marker)

    points, facets, _, facet_markers = \
            make_box(numpy.array([-1, -1, -1]), numpy.array([1, 1, 5]))

    geob.add_geometry(points, facets, facet_markers=facet_markers)

    mesh_info = MeshInfo()
    geob.set(mesh_info)
    #mesh_info.set_holes([(0, 0, 0)])

    # region attributes
    mesh_info.regions.resize(1)
    mesh_info.regions[0] = (
            # point in region
            [0, 0, 0] + [
                # region number
                1,
                # max volume in region
                0.001])

    mesh = build(mesh_info, max_volume=0.06,
            volume_constraints=True, attributes=True)
    print(("%d elements" % len(mesh.elements)))
    mesh.write_vtk("box-in-box.vtk")
Esempio n. 49
0
def create_ball_mesh(num_longi_points=10):

    radius = 5.0

    radial_subdiv = 2 * num_longi_points

    dphi = np.pi / num_longi_points

    # Make sure the nodes meet at the poles of the ball.
    def truncate(r):
        if abs(r) < 1e-10:
            return 0
        else:
            return r

    # Compute the volume of a canonical tetrahedron
    # with edgelength radius*dphi.
    a = radius * dphi
    canonical_tet_volume = np.sqrt(2.0) / 12 * a ** 3

    # Build outline for surface of revolution.
    rz = [
        (truncate(radius * np.sin(i * dphi)), radius * np.cos(i * dphi))
        for i in range(num_longi_points + 1)
    ]

    geob = GeometryBuilder()
    geob.add_geometry(
        *generate_surface_of_revolution(
            rz, closure=EXT_OPEN, radial_subdiv=radial_subdiv
        )
    )
    mesh_info = MeshInfo()
    geob.set(mesh_info)
    meshpy_mesh = build(mesh_info, max_volume=canonical_tet_volume)

    return np.array(meshpy_mesh.points), np.array(meshpy_mesh.elements)
Esempio n. 50
0
def make_tetgen_mesh(vert_list, face_list):

    # Make the tetgen mesh
    mesh_info = MeshInfo()

    # Points
    mesh_info.set_points(vert_list)

    # Faces
    mesh_info.set_facets(face_list)

    # --- TEMP ---
    '''
    # Make an object from the surface we are planning to tetrahedronalize
    mesh_new = bpy.data.meshes.new("pre_tet_mesh")
    mesh_new.from_pydata(vert_list,[],face_list)
    mesh_new.validate(verbose=False) # Important! and i dont know why
    mesh_new.update()
    obj_new = bpy.data.objects.new("pre_tet",mesh_new)
    context.scene.objects.link(obj_new)
    # return
    '''
    # --- FIN TEMP ---

    # Tetrahedralize
    # Options:
    # neighout = Write out neighbors
    # facesout = Write out faces
    # edgesout = Write out edges
    # regionattrib = Write out element_attributes = unique id for every tet in a distinct volume
    # nobisect = Dont alter surface
    print("> Starting TetGen")
    opts = Options(switches='pq', neighout = True, facesout = True, edgesout = True, regionattrib = True, verbose = True, docheck = True)
    mesh_built = build(mesh_info, options=opts)
    print("> Finished TetGen successfully")

    return mesh_built
Esempio n. 51
0
def make_extrusion_with_fine_core(rz, inner_r,
        max_volume_inner=1e-4, max_volume_outer=5e-2,
        radial_subdiv=20):

    min_z = min(rz_pt[1] for rz_pt in rz)
    max_z = max(rz_pt[1] for rz_pt in rz)

    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import generate_surface_of_revolution

    MINUS_Z_MARKER = 1
    PLUS_Z_MARKER = 2

    inner_points, inner_facets, inner_holes, inner_markers = \
            generate_surface_of_revolution(
                    [
                        (0, min_z),
                        (inner_r, min_z),
                        (inner_r, max_z),
                        (0, max_z),
                        ],
                    ring_markers=[
                        MINUS_Z_MARKER,
                        0,
                        PLUS_Z_MARKER
                        ],
                    radial_subdiv=radial_subdiv,
                    )

    inner_point_indices = tuple(range(len(inner_points)))

    outer_points, outer_facets, outer_holes, outer_markers = \
            generate_surface_of_revolution(
                    [(inner_r,min_z)] + rz + [(inner_r, max_z)],
                    ring_markers=[MINUS_Z_MARKER] + [0]*(len(rz)-1) + [PLUS_Z_MARKER],
                    point_idx_offset=len(inner_points),
                    radial_subdiv=radial_subdiv,
                    ring_point_indices=
                    [ inner_point_indices[:radial_subdiv] ]
                    + [None]*len(rz)
                    + [inner_point_indices[radial_subdiv:]]
                    )


    mesh_info = MeshInfo()
    mesh_info.set_points(inner_points + outer_points)
    mesh_info.set_facets_ex(
            inner_facets + outer_facets,
            inner_holes + outer_holes,
            inner_markers + outer_markers,
            )

    # set regional max. volume
    mesh_info.regions.resize(2)
    mesh_info.regions[0] = [0, 0, (max_z+min_z)/2, 0,
            max_volume_inner]
    mesh_info.regions[1] = [inner_r+(rz[0][0]-inner_r)/2, 0, (max_z+min_z)/2, 0,
            max_volume_outer]

    # add periodicity
    mesh_info.pbc_groups.resize(1)
    pbcg = mesh_info.pbc_groups[0]

    pbcg.facet_marker_1 = MINUS_Z_MARKER
    pbcg.facet_marker_2 = PLUS_Z_MARKER

    pbcg.set_transform(translation=[0,0,max_z-min_z])

    mesh = build(mesh_info, verbose=True, volume_constraints=True)
    #print "%d elements" % len(mesh.elements)
    #mesh.write_vtk("gun.vtk")

    fvi2fm = mesh.face_vertex_indices_to_face_marker

    def zper_boundary_tagger(fvi, el, fn, points):
        face_marker = fvi2fm[frozenset(fvi)]
        if face_marker == MINUS_Z_MARKER:
            return ["minus_z"]
        elif face_marker == PLUS_Z_MARKER:
            return ["plus_z"]
        else:
            return ["shell"]

    vertices = numpy.asarray(mesh.points, dtype=float, order="C")

    from hedge.mesh import make_conformal_mesh_ext
    from hedge.mesh.element import Tetrahedron
    return make_conformal_mesh_ext(
            vertices,
            [Tetrahedron(i, el_idx, vertices)
                for i, el_idx in enumerate(mesh.elements)],
            zper_boundary_tagger,
            periodicity=[None, None, ("minus_z", "plus_z")])
Esempio n. 52
0
def save_mesh(filepath,
              mesh,
              boundary_condition,
              use_graphics,
              fem_dimensions,
              mass_density,
              poisson_ratio,
              young_modulus,
              meshpy
             ):
    """Write mesh data out to ply file

       If graphics are checked to be exported, it will prep any UVs and normals it can and prepare
       a full list of faces FEM3D meshes have their mesh run through MeshPy which is a Python
       interface for TetGen
    """

    file = open(filepath, "w", encoding="utf8", newline="\n")
    fwrite = file.write

    verts = []
    faces = []
    elements = []
    uvcoords = {}
    normals = {}

    has_uv = bool(mesh.uv_textures) and mesh.uv_textures.active
    if has_uv and use_graphics:
        mesh.calc_tessface()
        uv_data = mesh.tessface_uv_textures.active.data
        for i, polygon in enumerate(mesh.polygons):
            uv = uv_data[i].uv1, uv_data[i].uv2, uv_data[i].uv3, uv_data[i].uv4
            for j, vert in enumerate(polygon.vertices):
                uvcoord = uv[j][0], uv[j][1]
                normal = mesh.vertices[vert].normal[:]
                vertcoord = mesh.vertices[vert].co[:]
                if vertcoord not in uvcoords:
                    uvcoords[vertcoord] = uvcoord
                if vertcoord not in normals:
                    normals[vertcoord] = normal

    if fem_dimensions == '3':
        from meshpy.tet import MeshInfo, build, Options

        bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
        bpy.context.scene.update()

        # get list of verts and faces direct from mesh
        mesh_verts = []
        for vert in mesh.vertices:
            mesh_verts.append(vert.co[:])

        mesh_faces = []
        for face in mesh.polygons:
            mesh_faces.append(face.vertices[:])

        args = meshpy
        mesh_info = MeshInfo()
        mesh_info.set_points(mesh_verts)
        mesh_info.set_facets(mesh_faces)
        tets = build(mesh_info, Options(args),
                     verbose=True,
                     attributes=False,
                     volume_constraints=False,
                     max_volume=None,
                     diagnose=False,
                     insert_points=None)

        # Ply prep by creating updated vert list and face list using tets.points and tets.elements
        for point in tets.points:
            verts.append((point[0], point[1], point[2]))

        for tet in tets.elements:
            elements.append((tet[0], tet[1], tet[2], tet[3]))

        for face in tets.faces:
            faces.append((face[2], face[1], face[0]))

    else:
        for vert in mesh.vertices:
            verts.append((vert.co[0], vert.co[1], vert.co[2]))

        for face in mesh.polygons:
            if len(face.vertices) == 3:
                faces.append((face.vertices[0], face.vertices[1], face.vertices[2]))
            else:
                faces.append((face.vertices[0], face.vertices[1], face.vertices[2]))
                faces.append((face.vertices[0], face.vertices[2], face.vertices[3]))

    fwrite("ply\n")
    fwrite("format ascii 1.0\n")
    fwrite("comment Created by OpenSurgSim FEM exporter for Blender\n")
    fwrite("comment MeshPy options '%s'\n" % meshpy)

    fwrite("element vertex %d\n" % len(verts))
    fwrite("property double x\n"
           "property double y\n"
           "property double z\n")

    if use_graphics:
        if fem_dimensions != '1':
            if normals:
                fwrite("property double nx\n"
                       "property double ny\n"
                       "property double nz\n")
            if has_uv:
                fwrite("property double s\n"
                       "property double t\n")
            fwrite("element face %d\n" % len(faces))
            fwrite("property list uint uint vertex_indices\n")

    if fem_dimensions == '1':
        fwrite("element 1d_element %d\n" % len(mesh.vertices)-1)
        fwrite("property list uint uint vertex_indices\n")
    elif fem_dimensions == '2':
        fwrite("element 2d_element %d\n" % len(faces))
        fwrite("property list uint uint vertex_indices\n")
    elif fem_dimensions == '3':
        fwrite("element 3d_element %d\n" % len(elements))
        fwrite("property list uint uint vertex_indices\n")

    fwrite("element material 1\n")
    fwrite("property double mass_density\n")
    fwrite("property double poisson_ratio\n")
    fwrite("property double young_modulus\n")

    if boundary_condition is not None:
        fwrite("element boundary_condition %d\n" % len(boundary_condition))
        fwrite("property uint vertex_index\n")
    fwrite("end_header\n")

    if fem_dimensions != '1':
        if use_graphics:
            for vert in verts:
                fwrite("%.6f %.6f %.6f" % vert[:])
                if vert in normals:
                    fwrite(" %.6f %.6f %.6f" % normals[vert][:])
                if has_uv and vert in uvcoords:
                    fwrite(" %.6f %.6f" % uvcoords[vert][:])
                fwrite("\n")
            for face in faces:
                fwrite("3 %d %d %d\n" % face[:])
        else:
            for vert in verts:
                fwrite("%.6f %.6f %.6f\n" % vert[:])
    else:
        for vert in mesh.vertices:
            fwrite("%.6f %.6f %.6f\n" % vert.co[:])

    if fem_dimensions is '1':
        for i in len(mesh.vertices)-1:
            fwrite("2 %d %d\n" % list(i, i+1))
    elif fem_dimensions is '2':
        for face in faces:
            fwrite("3 %d %d %d\n" % face[:])
    elif fem_dimensions is '3':
        for tet in elements:
            fwrite("4 %d %d %d %d\n" % tet[:])

    fwrite("%s %s %s\n" % (mass_density, poisson_ratio, young_modulus))

    if boundary_condition is not None:
        for index in boundary_condition:
            fwrite("%d\n" % index)

    file.close()
    print("writing %r done" % filepath)

    return {'FINISHED'}
Esempio n. 53
0
def make_box_mesh(a=(0, 0, 0), b=(1, 1, 1),
        max_volume=None, periodicity=None,
        boundary_tagger=(lambda fvi, el, fn, all_v: []),
        return_meshpy_mesh=False):
    """Return a mesh for a brick from the origin to `dimensions`.

    *max_volume* specifies the maximum volume for each tetrahedron.
    *periodicity* is either None, or a triple of bools, indicating
    whether periodic BCs are to be applied along that axis.
    See :func:`make_conformal_mesh` for the meaning of *boundary_tagger*.

    A few stock boundary tags are provided for easy application
    of boundary conditions, namely plus_[xyz] and minus_[xyz] tag
    the appropriate faces of the brick.
    """

    def count(iterable):
        result = 0
        for i in iterable:
            result += 1
        return result

    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import make_box

    points, facets, _, facet_markers = make_box(a, b)

    mesh_info = MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(facets, facet_markers)

    if periodicity is None:
        periodicity = (False, False, False)

    axes = ["x", "y", "z"]

    per_count = count(p for p in periodicity if p)

    marker_to_tag = {}
    mesh_periodicity = []
    periodic_tags = set()

    if per_count:
        mesh_info.pbc_groups.resize(per_count)
    pbc_group_number = 0
    for axis, axis_per in enumerate(periodicity):
        minus_marker = 1+2*axis
        plus_marker = 2+2*axis

        minus_tag = "minus_"+axes[axis]
        plus_tag = "plus_"+axes[axis]

        marker_to_tag[minus_marker] = minus_tag
        marker_to_tag[plus_marker] = plus_tag

        if axis_per:
            pbcg = mesh_info.pbc_groups[pbc_group_number]
            pbc_group_number += 1

            pbcg.facet_marker_1 = minus_marker
            pbcg.facet_marker_2 = plus_marker

            translation = [0, 0, 0]
            translation[axis] = b[axis]-a[axis]
            pbcg.set_transform(translation=translation)

            mesh_periodicity.append((minus_tag, plus_tag))
            periodic_tags.add(minus_tag)
            periodic_tags.add(plus_tag)
        else:
            mesh_periodicity.append(None)

    generated_mesh = build(mesh_info, max_volume=max_volume)

    fvi2fm = generated_mesh.face_vertex_indices_to_face_marker

    def wrapped_boundary_tagger(fvi, el, fn, all_v):
        face_tag = marker_to_tag[fvi2fm[frozenset(fvi)]]

        if face_tag in periodic_tags:
            return [face_tag]
        else:
            return [face_tag] + boundary_tagger(fvi, el, fn, all_v)

    from hedge.mesh import make_conformal_mesh_ext
    from hedge.mesh.element import Tetrahedron
    vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C")
    result = make_conformal_mesh_ext(
            vertices,
            [Tetrahedron(i, el_idx, vertices)
                for i, el_idx in enumerate(generated_mesh.elements)],
            wrapped_boundary_tagger,
            periodicity=mesh_periodicity)

    if return_meshpy_mesh:
        return result, generated_mesh
    else:
        return result
Esempio n. 54
0
    (b,b,b), (b,b,a), (b,a,a),(b,a,b),(a,b,b), (a,b,a), (a,a,a),(a,a,b)
    ])
mesh_info.set_facets([
    [0,1,2,3],
    [0,1,5,4],
    [0,4,7,3],
    [6,2,1,5],
    [6,2,3,7],
    [6,7,4,5]])

addpoints = [(0.0,0.0,0.0), (0.375,0.375,0.375)]
# addpoints = [array([0.0,0.0,0.0]), array(0.375,0.375,0.375)]

opts = Options("VO9pa0.04") # Overriding 'pq'  

mesh = build(mesh_info,options=opts, insert_points = addpoints)
# mesh = build(mesh_info,max_volume = 0.1)
vols = []
tets = []
points = []
print "Mesh Points:"
for i, p in enumerate(mesh.points):
    points.append(array(mesh.points[i]))
    print i, p
# print "Point numbers in tetrahedra:"
for i, tet in enumerate(mesh.elements):
    tets.append(tet)
    vpoints = array([mesh.points[iv] for iv in tet])
    vols.append(volTet2(vpoints))
vols = array(vols)
vols.sort()
Esempio n. 55
0
def ProcessGlobalAction(ActionType, GlobalAction, NumberedPoints, Elements, Points):
    ExtendedData = {'ElementPropertyIndex' : {}}
    if ActionType == 'SpecialEntities':
        Filters = json.loads(GlobalAction['Filters'])
        if not 'SpecialEntities' in ExtendedData:
            ExtendedData['SpecialEntities'] = []
        for Element in Elements:
            if Element and Element['filter'] in Filters:
                ExtendedData['SpecialEntities'].append(Element)
        return ExtendedData, False

    if ActionType == 'Nonlinear':
        Output = {}
        #for key in GlobalAction:
        #    if 'ElementPropertyMaxIndex' in ExtendedData:
        #        ExtendedData['ElementPropertyMaxIndex'] += 1
        #    else:
        #         ExtendedData['ElementPropertyMaxIndex'] = 1
        #    propertyindex = ExtendedData['ElementPropertyMaxIndex']
        #    ExtendedData['ElementPropertyIndex'][key] = propertyindex
        #    ExtendedData['NonlinearPropertyIndex'][key] = nonlinearindex
        #
        #
        #    ExtendedData['ElementPropertyIndex'][key] = workingindex #In this same notation we can get the index when writing elements
        #    Output[index] = ""
        return ExtendedData, Output #Here we have Output ready to be printed and ExtendedData, a mapper to Output
    if ActionType == 'ElementProperties':
        Output = {}
        for key in GlobalAction:
            if 'ElementPropertyMaxIndex' in ExtendedData:
                ExtendedData['ElementPropertyMaxIndex'] += 1
            else:
                ExtendedData['ElementPropertyMaxIndex'] = 1
            workingindex = ExtendedData['ElementPropertyMaxIndex']
            ExtendedData['ElementPropertyIndex'][key] = workingindex #In this same notation we can get the index when writing elements
            
            Output[workingindex] = GlobalAction[key]
        return ExtendedData, Output #Here we have Output ready to be printed and ExtendedData, a mapper to Output
    if ActionType == 'Orphans':
        Output = []
        for Number, Point in NumberedPoints['points'].iteritems():
            ElementAmount = len(Point['elementnumbers'])
            if ElementAmount < 2:
                print "Orphan node {}!".format(Number)
                Output.append({'element_type': 'POINT', 'position': Point['point'], 'layer': 'Errors', 'nodenumber': Number})
        return {'information':'addObjects'}, Output#Here we have Output ready to be printed and ExtendedData, a mapper to Output
    if ActionType == 'Meshing':

        EntityModelData = json.loads(GlobalAction['EntityModelData']) if 'EntityModelData' in GlobalAction else {}
        ExtendedModelData = json.loads(GlobalAction['ExtendedModelData']) if 'ExtendedModelData' in GlobalAction else {}
        Semantic = json.loads(GlobalAction['Semantic']) if 'Semantic' in GlobalAction else {}
        if 'exclude filters' in Semantic:
            if not 'ExcludeFilters' in ExtendedData: ExtendedData['ExcludeFilters'] = []
            ExtendedData['ExcludeFilters'] = ExtendedData['ExcludeFilters'] + Semantic['exclude filters']
        Boundaries = []
        Output = []
        Geometry = json.loads(GlobalAction['Geometry']) if 'Geometry' in GlobalAction else {}
        Parameters = json.loads(GlobalAction['Parameters']) if 'Parameters' in GlobalAction else {}
        AdditionalPointsFilters = Geometry['points'] if 'points' in Geometry else []
        for Filter in Geometry['boundaries']:
            print "Using filter {} as finite element domain boundary.".format(Filter)
            for Element in Elements:
                if Element and Element['filter'] == Filter and Element['elementclass'] in ['FACE_3NODES', 'FACE_4NODES', 'POLYLINE', 'PLINE_5NODES']:
                    Boundaries.append(Element)

        AdditionalPoints = []
        for Filter in AdditionalPointsFilters:
            print "Using filter {} as additional points container.".format(Filter)
            for Element in Elements:
                if Element and Element['filter'] == Filter and Element['elementclass'] in ['FACE_3NODES', 'FACE_4NODES', 'POLYLINE', 'LINE_2NODES']:
                    AdditionalPoints.extend(
                                            Element['points']
                                            )

        print "Assembling FE domain"

        mesh_info = MeshInfo()
        #additional_points = MeshInfo()
        #additional_points.set_points(list(set(AdditionalPoints)))
        MeshPoints = []
        MeshFacets = []
        MeshPointsIndex = {}
        PointIndex = 0

        for BoundaryElement in Boundaries:
            
            ElementPoints = BoundaryElement['points']

            MeshFacet = []
            if Parameters['type'] == 'divide_4p_faces':
                for point in [ElementPoints[0],ElementPoints[1],ElementPoints[2]]:
                    if not point in MeshPointsIndex:
                        MeshPointsIndex[point] = PointIndex
                        MeshPoints.append(False)
                        MeshPoints[PointIndex] = NumberedPoints['points'][point]['point']
                        PointIndex += 1
                    MeshFacet.append(MeshPointsIndex[point])
                MeshFacets.append(MeshFacet)
                MeshFacet = []
                if ElementPoints[2] != ElementPoints[3]:
                    for point in [ElementPoints[0],ElementPoints[2],ElementPoints[3]]:
                        if not point in MeshPointsIndex:
                            MeshPointsIndex[point] = PointIndex
                            MeshPoints.append(False)
                            MeshPoints[PointIndex] = NumberedPoints['points'][point]['point']
                            PointIndex += 1
                        MeshFacet.append(MeshPointsIndex[point])
                    MeshFacets.append(MeshFacet)
            else:
                for point in ElementPoints:
                    if not point in MeshPointsIndex:
                        MeshPointsIndex[point] = PointIndex
                        MeshPoints.append(False)
                        MeshPoints[PointIndex] = NumberedPoints['points'][point]['point']
                        PointIndex += 1
                    if not MeshPointsIndex[point] in MeshFacet:
                        MeshFacet.append(MeshPointsIndex[point])
                    else:
                        print "Mesh error or 3-point 3DFACE."
                MeshFacets.append(MeshFacet)
                MeshFacet = []

        for point in list(set(AdditionalPoints)):
            if not point in MeshPointsIndex: #See whether the point is already indexed by its native number
                MeshPointsIndex[point] = PointIndex
                MeshPoints.append(False)
                MeshPoints[PointIndex] = NumberedPoints['points'][point]['point']
                PointIndex += 1

        
        saveobject(MeshFacets, r'MeshFacets')
        saveobject(MeshPoints, r'MeshPoints')            
        mesh_info.set_facets(MeshFacets)
        mesh_info.set_points(MeshPoints)
        #insertaddpoints
        
        #points = np.array([list(x) for x in MeshPoints])
        #qhull = scipy.spatial.Delaunay(points)
        #mesh_info.Options(switches='pq')
        #mesh_info.set_points([
        #    (0,0,0), (12,0,0), (12,12,0), (0,12,0),
        #    (0,0,12), (12,0,12), (12,12,12), (0,12,12),
        #    ])
        #mesh_info.set_facets([
        #    [0,1,2,3],
        #    [4,5,6,7],
        #    [0,4,5,1],
        #    [1,5,6,2],
        #    [2,6,7,3],
        #    [3,7,4,0],
        #    ])
        
        #opts = Options(switches='pq')
        #opts.maxvolume = 0.0001
        #opts.parse_switches()

        mesh_info.regions.resize(1)
        mesh_info.regions[0] = [
                                MeshPoints[0][0], MeshPoints[0][1], MeshPoints[0][2], # point in volume -> first box
                                0, # region tag (user-defined number)
                                Parameters['maxvolume'], # max tet volume in region
                                ]
        mesh = build(mesh_info, options=Options(switches="pqT", epsilon=Parameters['tolerance']), volume_constraints=True)
        print "Created mesh with {} points, {} faces and {} elements.".format(len(mesh.points), len(mesh.faces), len(mesh.elements))
        #mesh = build(mesh_info, options=Options(switches="pTi", epsilon=Parameters['tolerance'], insertaddpoints=True), volume_constraints=True, insert_points=additional_points)
        #mesh.write_vtk("test.vtk")
        #mesh.points
        #mesh.elements
        #mesh.faces
        filename = "test"
        #mesh.save_elements(filename)
        #mesh.save_nodes(filename)
        #mesh.save_elements(filename)
        #mesh.save_faces(filename)
        #mesh.save_edges(filename)
        #mesh.save_neighbors(filename)
        #mesh.save_poly(filename)
        #for element in qhull.simplices:
        #    Position = [list(qhull.points[x]) for x in element]
        #    Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Elements'})
        #NumberedPoints['points'][compoundObject['points'][0]]['point']
        if not Boundaries: return False, False
        Precision = int(GlobalAction['Precision']) if 'Precision' in GlobalAction else 4

        if Semantic['output'].lower() == 'graphics':
            for face in mesh.faces:
                Position = [mesh.points[x] for x in face]
                Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Faces'})
            for element in mesh.elements:
                Position = [mesh.points[x] for x in element]
                Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Elements'})
            return {'information':'addObjects'}, Output
        elif Semantic['output'].lower() == 'fea':
            Points = {}
            for NumberedPoint in NumberedPoints['points']:
                Points[NumberedPoints['points'][NumberedPoint]['point']] = NumberedPoint
            NodeNumber = NumberedPoints['maximumNode']
            for element in mesh.elements:
                Position = [mesh.points[x] for x in element]
                for i, point in enumerate(Position):
                    Position[i] = [round(x, Precision) for x in point]

                #else:
                #    if tuple([round(x, PrepPrecision) for x in Coords]) in [(4.95,-17.69,58.9), (4.96,-17.69,58.9)]:
                #        pass                    
                #    object['points'][i] = tuple([round(x, PrepPrecision) for x in Coords])
                #    if not object['points'][i] in GlobalPointIndex:
                #        GlobalPointIndex.append(object['points'][i])



                ElementPoints = []
                ElementNumber = len(Elements)
                for point in Position:

                    #Update NumberedPoints and construct all necessary data for Elements
                    point = NeighborhoodRaw(tuple(point), Precision, Points)
                    if not tuple(point) in Points:
                        NodeNumber += 1
                        Points[tuple(point)] = NodeNumber
                        #PointsNumbered.append(None)
                        NumberedPoints['points'][NodeNumber] = {'point': tuple(point), 'elementnumbers': []}
                        NumberedPoints['maximumNode'] = NodeNumber
                    CurrentPointNumber = Points[tuple(point)]
                    ElementPoints.append(CurrentPointNumber)
                    NumberedPoints['points'][CurrentPointNumber]['elementnumbers'].append(ElementNumber)

                    #Update Points if possible


                #Update Elements
                Element = { 'points' : ElementPoints,
                'elementclass' : 'SOLID_4NODES',
                'elementnum': ElementNumber, #???
                'filter': Semantic['filter'],
                'entity_model_data': EntityModelData,
                'extended_model_data': ExtendedModelData,
                'generation_order': None,
                }
                Elements.append(None)
                Elements[ElementNumber] = Element
            return ExtendedData, False

    if ActionType == 'AddShells':
        ExtendedData = {}
        EntityModelData = json.loads(GlobalAction['EntityModelData']) if 'EntityModelData' in GlobalAction else {}
        ExtendedModelData = json.loads(GlobalAction['ExtendedModelData']) if 'ExtendedModelData' in GlobalAction else {}
        Filters = json.loads(GlobalAction['Filters']) if 'Filters' in GlobalAction else {}
        for Element in Elements:
            if not Element or not Element['filter'] in Filters: continue
            if Element['generation_order'] == 0 and Element['entity_model_data']['layer'] != "Concrete bases crown":
                ElementPoints = [Element['points'][0], Element['points'][1], Element['points'][2]]
                ElementNumber = len(Elements)
                NewElement = { 'points' : ElementPoints,
                'elementclass' : 'FACE_3NODES',
                'elementnum': ElementNumber, #???
                'filter': GlobalAction['AssignedFilter'],
                'entity_model_data': EntityModelData,
                'extended_model_data': ExtendedModelData,
                'generation_order': None,
                }
                Elements.append(None)
                Elements[ElementNumber] = NewElement

                if Element['elementclass'] == 'SOLID_8NODES':
                    ElementPoints = [Element['points'][0], Element['points'][2], Element['points'][3]]
                    ElementNumber = len(Elements)
                    NewElement = { 'points' : ElementPoints,
                    'elementclass' : 'FACE_3NODES',
                    'elementnum': ElementNumber, #???
                    'filter': GlobalAction['AssignedFilter'],
                    'entity_model_data': EntityModelData,
                    'extended_model_data': ExtendedModelData,
                    'generation_order': None,
                    }
                    Elements.append(None)
                    Elements[ElementNumber] = NewElement

                if Element['elementclass'] == 'SOLID_10NODES':
                    pass

                pass
                
        return {}, {}
    return False