Exemple #1
0
def test_vtk_tetrahedralize():
    sphere = pv.Sphere(theta_resolution=10, phi_resolution=10)
    tet = tetgen.TetGen(sphere)
    tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
    grid = tet.grid
    assert grid.n_cells
    assert grid.n_points
Exemple #2
0
def test_tetrahedralize_swithces():
    sphere = pv.Sphere(theta_resolution=10, phi_resolution=10)
    tet = tetgen.TetGen(sphere)
    tet.tetrahedralize(switches="pq1.1/10YQ")
    grid = tet.grid
    assert grid.n_cells
    assert grid.n_points
Exemple #3
0
def test_numpy_tetrahedralize(tmpdir):
    v = np.array([
        [0, 0, 0],
        [1, 0, 0],
        [1, 1, 0],
        [0, 1, 0],
        [0, 0, 1],
        [1, 0, 1],
        [1, 1, 1],
        [0, 1, 1],
    ])

    f = np.vstack([[0, 1, 2], [2, 3, 0], [0, 1, 5], [5, 4, 0], [1, 2, 6],
                   [6, 5, 1], [2, 3, 7], [7, 6, 2], [3, 0, 4], [4, 7, 3],
                   [4, 5, 6], [6, 7, 4]])

    tgen = tetgen.TetGen(v, f)

    nodes, elems = tgen.tetrahedralize()
    assert np.any(nodes)
    assert np.any(elems)

    # test save as well
    filename = str(tmpdir.mkdir("tmpdir").join("test_mesh.vtk"))
    tgen.write(filename)
Exemple #4
0
def test_pv_box():
    box = pv.Box((-1.0, 1.0, -5.0, 5.0, -1.0, 1.0))
    #box = examples.load_hexbeam()
    tet = tetgen.TetGen(box.triangulate())
    tet.tetrahedralize(order=1, mindihedral=20, minratio=2.0)

    print("tet: ", tet.mesh.points)
    grid = tet.grid
    verts = grid.points
    print("Cells: \n", grid.cells)
    print("Points: \n", verts)
    cell_arr = extract_tets(grid.cells)
    print(cell_arr)
    constraints = [[1, [1, 1, 1]], [3, [1, 1, 1]], [4, [1, 1, 1]],
                   [6, [1, 1, 1]]]

    loads = [[0, 10., 0.0, 0], [2, 10., 0.0, 0], [5, 10., 0.0, 0],
             [7, 10., 0.0, 0]]
    poisson = 0.3
    youngs = 2000

    displacements = solve_full(cell_arr, verts, poisson, youngs, constraints,
                               loads)
    print(pd.DataFrame(displacements))
    magnitudes = get_displacement_magnitudes(displacements)

    display_tets(verts, cell_arr, magnitudes)
Exemple #5
0
 def filter(self):
     # TODO: check if watertight
     # TODO: replace with CGAL to avoid AGPL
     tetrahedralizer = tetgen.TetGen(self.mesh.pyvista.extract_surface())
     tetrahedralizer.make_manifold()
     tetrahedralizer.tetrahedralize(**self.kwargs)
     return self.mesh.mesh_class(offset=1)(tetrahedralizer.grid,
                                           parents=[self.mesh])
Exemple #6
0
def test_nested_spheres():
    spherebig = pv.Sphere(1, (0, 0, 0))
    spheresmall = pv.Sphere(0.5, (0, 0, 0))
    allspheres = spherebig.boolean_add(spheresmall)
    v = allspheres.points
    f = allspheres.faces.reshape(-1, 4)[:, 1:]
    tet = tetgen.TetGen(v, f)
    nodes, elems, elemattrs = tet.tetrahedralize(regionattrib=1)
    return nodes, elems, elemattrs
Exemple #7
0
def test_tetrahedralize():
    sphere = vtki.PolyData(examples.spherefile)
    tet = tetgen.TetGen(sphere)
    tet.Tetrahedralize(order=1, mindihedral=20, minratio=1.5)
    grid = tet.grid
    assert grid.GetNumberOfCells()
    assert grid.GetNumberOfPoints()
    assert np.all(grid.quality > 0)
    return grid
def generate_dual_tetrahedrons(mesh, internal_mesh):
    # Meshes are of trimesh type
    diff = trimesh.boolean.difference((mesh, internal_mesh))
    new_verts = diff.vertices
    new_faces = diff.faces

    tet = tetgen.TetGen(new_verts, new_faces)
    tet.tetrahedralize(order=1)
    grid = tet.grid
    tets = simplefem.extract_tets(grid.cells)
    verts = grid.points

    #new_tets = remove_tets_internal(internal_mesh, tets, verts)
    new_tets = remove_tets_convex(internal_mesh, tets, verts)
    verts = np.array(verts)
    new_tets = np.array(new_tets)
    #simplefem.display_tets(verts, new_tets)
    return verts, new_tets
Exemple #9
0
def test_numpy_tetrahedralize():
    v = np.array([[0, 0, 0], [1, 0, 0],
                  [1, 1, 0], [0, 1, 0],
                  [0, 0, 1], [1, 0, 1],
                  [1, 1, 1], [0, 1, 1],])

    f = np.vstack([[0, 1, 2], [2, 3, 0],
                   [0, 1, 5], [5, 4, 0],
                   [1, 2, 6], [6, 5, 1],
                   [2, 3, 7], [7, 6, 2],
                   [3, 0, 4], [4, 7, 3],
                   [4, 5, 6], [6, 7, 4]])

    tgen = tetgen.TetGen(v, f)

    nodes, elems = tgen.tetrahedralize()
    assert np.any(nodes)
    assert np.any(elems)
Exemple #10
0
def functional_tet_example():
    sphere = pv.Sphere(theta_resolution=10, phi_resolution=10)
    tet = tetgen.TetGen(sphere)
    tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
    grid = tet.grid
    assert grid.n_cells
    assert grid.n_points

    cells = grid.cells.reshape(-1, 5)[:, 1:]
    cell_center = grid.points[cells].mean(1)

    # extract cells below the 0 xy plane
    mask = cell_center[:, 2] < 0
    cell_ind = mask.nonzero()[0]
    subgrid = grid.extract_cells(cell_ind)

    # plot this
    subgrid.plot(scalars=subgrid.quality,
                 stitle='quality',
                 cmap='bwr',
                 flip_scalars=True)

    # advanced plotting
    plotter = pv.Plotter()
    plotter.set_background('w')
    plotter.add_mesh(subgrid, 'lightgrey', lighting=True)
    plotter.add_mesh(grid, 'r', 'wireframe')
    plotter.add_legend([[' Input Mesh ', 'r'], [' Tessellated Mesh ',
                                                'black']])
    plotter.show()

    plotter = pv.Plotter()
    plotter.set_background('w')
    plotter.add_mesh(grid, 'r', 'wireframe')
    plotter.plot(auto_close=False, interactive_update=True)
    for i in range(500):
        single_cell = grid.extract_cells([i])
        plotter.add_mesh(single_cell)
        plotter.update()
    plotter.close()
Exemple #11
0
cow_mesh = examples.download_cow().triangulate()

cpos = [(13., 7.6, -13.85),
 (0.44, -0.4, -0.37),
 (-0.28, 0.9, 0.3)]

cpos=[(15.87144235049248, 4.879216382405231, -12.14248864876951),
 (1.1623113035352375, -0.7609060338348953, 0.3192320579894903),
 (-0.19477922834083672, 0.9593375398915212, 0.20428542963665386)]

cow_mesh.plot(cpos=cpos)

###############################################################################

tet = tetgen.TetGen(cow_mesh)
tet.make_manifold()
tet.tetrahedralize()

cow_grid = tet.grid

###############################################################################

# plot half the cow
mask = np.logical_or(cow_grid.points[:, 0] < 0, cow_grid.points[:, 0] > 4)
half_cow = cow_grid.extract_points(mask)

###############################################################################

plotter = pv.Plotter()
plotter.add_mesh(half_cow, color='w', show_edges=True)
Exemple #12
0
def test_mesh_repair():
    cowfile = os.path.join(path, 'cow.ply')
    tet = tetgen.TetGen(cowfile)
    tet.make_manifold()
    tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
Exemple #13
0
    def gen_mesh_from_surf(self,
                           raw_input=None,
                           filename=None,
                           tri=None,
                           points=None,
                           surface_mesh=None):
        """
        Generates a mesh from a surface mesh or file.
        """

        if filename:
            self.check_compatibility(filename)

        from stl import mesh
        import tetgen

        #put rawinput in correct place
        if type(raw_input) == str:
            filename = raw_input
        elif isinstance(raw_input, SurfaceMesh):
            surface_mesh = raw_input

        assert (filename or (tri and points)
                or surface_mesh), 'No input geometry specified'

        if filename:
            mesh = mesh.Mesh.from_file(filename)
            points = np.unique(mesh.points.reshape(mesh.points.shape[0] * 3,
                                                   3),
                               axis=0)
            tri = [[
                points.tolist().index(x[0:3].tolist()),
                points.tolist().index(x[3:6].tolist()),
                points.tolist().index(x[6:9].tolist())
            ] for x in mesh.points]

        elif surface_mesh:
            points = surface_mesh.points
            tri = surface_mesh.tri

        points = np.array(points)
        tri = np.array(tri)

        #        assert points!=None and tri!=None, 'Empty geometry, check input is specified correctly'

        mesh = pv.PolyData(points, np.c_[np.tile(3, tri.shape[0]),
                                         tri].flatten())

        tet = tetgen.TetGen(mesh)
        tet.make_manifold()
        tet.tetrahedralize()

        grid = tet.grid

        # plot half
        #        mask = np.logical_or(grid.points[:, 0] < 0, grid.points[:, 0] > 4)
        #        half = grid.extract_selection_points(mask)
        #
        #        ###############################################################################
        #
        #        plotter = pv.BackgroundPlotter()
        #        plotter.add_mesh(half, color='w', show_edges=True)
        #        plotter.add_mesh(grid, color='r', style='wireframe', opacity=0.2)
        ##        plotter.camera_position = cpos
        #        plotter.show()

        self.points = grid.points
        self.elements = grid.cells.reshape(-1, 11)[:, 1:5]
        #        return grid
        return self.points, self.elements
Exemple #14
0
Using external modules to create a mesh
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tetrahedralize a sphere
"""
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
import tetgen
import numpy as np

###############################################################################
# Using PyVista
# ~~~~~~~~~~~~~
# Create a surface mesh using ``pyvista`` and then tetrahedralize it.
sphere = pv.Sphere()
tet = tetgen.TetGen(sphere)
tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
grid = tet.grid
grid.plot(show_edges=True)

###############################################################################
# Use pyvista to plot

# get cell centroids
cell_center = grid.cell_centers().points

# extract cells below the 0 xy plane
mask = cell_center[:, 2] < 0
cell_ind = mask.nonzero()[0]
subgrid = grid.extract_cells(cell_ind)
Exemple #15
0
def inertia_high_fidelity(W, L, D, t, rho_sa, n_sa):
    """Hi-fidelity inertia tensor calculation using tetgen to
    create a 3D tetrahedron mesh of the solar panels. Then
    compute the intertia tensor from the sum of the element
    interias
    """
    import tetgen

    I_sax = np.zeros(W.size)
    I_say = np.zeros(W.size)
    I_saz = np.zeros(W.size)
    m_sa = np.zeros(W.size)
    for i in range(W.size):
        Wi = W[i]
        Li = L[i]
        # set vertices
        verts = np.array(
            [
                [-Wi / 2, D, t / 2],
                [Wi / 2, D, t / 2],
                [Wi / 2, D, -t / 2],
                [-Wi / 2, D, -t / 2],
                [-Wi / 2, D + Li, t / 2],
                [Wi / 2, D + Li, t / 2],
                [Wi / 2, D + Li, -t / 2],
                [-Wi / 2, D + Li, -t / 2],
            ]
        )
        # set facets
        facets = np.array(
            [
                [0, 1, 2],
                [0, 2, 3],
                [0, 1, 5],
                [0, 5, 4],
                [0, 3, 7],
                [0, 4, 7],
                [1, 2, 5],
                [2, 5, 6],
                [3, 2, 6],
                [3, 6, 7],
                [4, 5, 6],
                [4, 6, 7],
            ]
        )
        tet = tetgen.TetGen(verts, facets)
        nodes, elems = tet.tetrahedralize(quality=1, verbose=0)
        # Compute inertia tensor from tetrahedrons
        nelem = elems.shape[0]
        dIxx = np.zeros(nelem)
        dIyy = np.zeros(nelem)
        dIzz = np.zeros(nelem)
        dMass = np.zeros(nelem)
        for j, el in enumerate(elems):
            # Gather element nodes
            pts = nodes[el]
            a = pts[0]
            b = pts[1]
            c = pts[2]
            d = pts[3]
            # Find centroid x, y, z coordinates
            xx = (a[0] + b[0] + c[0] + d[0]) / 4.0
            yy = (a[1] + b[1] + c[1] + d[1]) / 4.0
            zz = (a[2] + b[2] + c[2] + d[2]) / 4.0
            # Find element volume
            dV = (
                1
                / 6.0
                * abs(
                    (a[0] - d[0])
                    * ((b[1] - d[1]) * (c[2] - d[2]) - (b[2] - d[2]) * (c[1] - d[1]))
                    + (a[1] - d[1])
                    * ((b[2] - d[2]) * (c[0] - d[0]) - (b[0] - d[0]) * (c[2] - d[2]))
                    + (a[2] - d[2])
                    * ((b[0] - d[0]) * (c[1] - d[1]) - (b[1] - d[1]) * (c[0] - d[0]))
                )
            )
            # Compute element inertia
            dMass[j] = rho_sa * dV
            dIxx[j] = rho_sa * dV * (yy * yy + zz * zz)
            dIyy[j] = rho_sa * dV * (xx * xx + zz * zz)
            dIzz[j] = rho_sa * dV * (xx * xx + yy * yy)
        I_sax[i] = np.sum(dIxx) ** 2
        I_say[i] = np.sum(dIyy) ** 2
        I_saz[i] = np.sum(dIzz) ** 2
        m_sa[i] = np.sum(dMass)

    return I_sax, I_say, I_saz, m_sa
Exemple #16
0
"""
Sphere
~~~~~~

Tetrahedralize a sphere
"""
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
import tetgen
import numpy as np

###############################################################################
sphere = pv.Sphere()
tet = tetgen.TetGen(sphere)
tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
grid = tet.grid
grid.plot(show_edges=True)

###############################################################################

# get cell centroids
cells = grid.cells.reshape(-1, 5)[:, 1:]
cell_center = grid.points[cells].mean(1)

# extract cells below the 0 xy plane
mask = cell_center[:, 2] < 0
cell_ind = mask.nonzero()[0]
subgrid = grid.extract_cells(cell_ind)

# advanced plotting
plotter = pv.Plotter()
Exemple #17
0
def plot_mesh(vertices,
              faces=None,
              input_file_name=None,
              darkmode=True,
              background_color='k',
              text=None,
              window_size=[1280, 720],
              font_color='w',
              cpos=[(3.77, 3.77, 3.77), (0.0069, -0.0045, 0.0),
                    (0.0, 0.0, 1.0)]):
    '''visualize the mesh surface using vtk and return an img.  
	vertices is a numpy array of vertices with faces.
	faces is a numpy array of indices specifying the faces of the surface of the mesh using ^those vertices.
	input_file_name is a string giving the path to a file containing ^those faces (e.g. *.ply or *.stl).
	an example text=f'time={tme:.1f}'
	window_size = [1280,720] is the standard aspect ratio for youtube,
	'''
    #visualize the mesh surface
    pv.set_plot_theme('document')

    #get the vtk object (wrapped by pyvista from withing tetgen.  Faces recorded by trimesh))
    if faces is None:
        if input_file_name is None:
            Exception('either faces or input_file_name must be specified')
        mesh_trimesh = trimesh.load(input_file_name)
        faces = mesh_trimesh.faces

    tet = tetgen.TetGen(vertices, faces)
    # #fault tolerant tetrahedralization
    vertices_tet, elements_tet = tet.tetrahedralize(order=1,
                                                    mindihedral=0.,
                                                    minratio=10.,
                                                    nobisect=False,
                                                    steinerleft=100000)  #
    tet.make_manifold()
    grid = tet.grid

    # advanced plotting
    plotter = pv.Plotter()
    if darkmode:
        plotter.set_background(background_color)
        plotter.add_mesh(grid, 'lightgrey', lighting=True)
        #looks like tron plotter.add_mesh(grid, 'r', 'wireframe')
    else:
        plotter.add_mesh(grid, 'lightgrey', lighting=True)
        font_color = 'k'
    if text is not None:
        plotter.add_text(text,
                         position='upper_left',
                         font_size=24,
                         color=font_color,
                         font='times')
    #font options
    # FONT_KEYS = {'arial': vtk.VTK_ARIAL,
    #              'courier': vtk.VTK_COURIER,
    #              'times': vtk.VTK_TIMES}

    #cpos is (camera position, focal point, and view up)
    #for movies, just set the camera position to some constant value.

    _cpos, img = plotter.show(title=None,
                              return_img=True,
                              cpos=cpos,
                              window_size=window_size,
                              use_ipyvtk=False,
                              interactive=False,
                              auto_close=True)
    plotter.deep_clean()
    del plotter
    pv.close_all()
    return img
Exemple #18
0
"""
Super Toroid
~~~~~~~~~~~~

Tetrahedralize a super toroid surface
"""
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
import tetgen
import numpy as np

###############################################################################
toroid = pv.SuperToroid()
tet = tetgen.TetGen(toroid)
tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
grid = tet.grid
grid.plot()

###############################################################################

# get cell centroids
cells = grid.cells.reshape(-1, 5)[:, 1:]
cell_center = grid.points[cells].mean(1)

# extract cells below the 0 xy plane
mask = cell_center[:, 2] < 0
cell_ind = mask.nonzero()[0]
subgrid = grid.extract_cells(cell_ind)

# advanced plotting
plotter = pv.Plotter()
Exemple #19
0
def test_load_arrays():
    sphere = pv.Sphere()
    v = sphere.points
    f = sphere.faces.reshape(-1, 4)[:, 1:]
    tet = tetgen.TetGen(v, f)
Exemple #20
0
def build_mesh_from_3Dmask(mask, STEP_SIZE, SPACING):
    '''update_outlier
    build a mesh from a 3D mask
    mask :
    STEP_SIZE :
    SPACING :
    surface : if true only surfacic mesh


    '''
    labels, n_labels = measurements.label(mask)

    ls_cells = []
    ls_points = []
    #for i in range(1, 3):
    print(n_labels)
    for i in range(1, n_labels + 1):
        label = (labels == i) * 1
        #print('IDX {}, n vox{}'.format(i, np.sum(label)))
        try:
            verts, faces, normals, values = measure.marching_cubes_lewiner(
                label,
                step_size=STEP_SIZE,
                spacing=SPACING,
                allow_degenerate=True)
            verts = np.round(verts)
            faces_1_adapted = np.ones([faces.shape[0], faces.shape[1] + 1]) * 3
            faces_1_adapted[:, 1:] = faces
            surf = polyv.PolyData(verts, faces_1_adapted)
            tet = tetgen.TetGen(surf)
            tet.make_manifold()
            tet.tetrahedralize(order=1,
                               mindihedral=10,
                               steinerleft=-1,
                               minratio=1.01)
            grid = tet.grid
            #print(grid.number_of_cells)
            if i > 1:
                PREVIOUS_NUMBER_OF_VERTICES = points_concat.reshape(
                    [-1, 3]).shape[0]
                ls_points.append(grid.points)
                cells = grid.cells.reshape([-1, 5])
                cells[:, 1:] += PREVIOUS_NUMBER_OF_VERTICES
                cells = cells.reshape([-1])
                ls_cells.append(cells)
                cells_concat = np.concatenate(ls_cells, axis=0)
                points_concat = np.concatenate(ls_points, axis=0)
                n_cells = cells_concat.reshape([-1, 5]).shape[0]
            else:
                ls_cells.append(grid.cells)
                ls_points.append(grid.points)
                # fig,ax=plt.subplots()
                # ax.imshow(label[200,:,:])
                cells_concat = np.concatenate(ls_cells, axis=0)
                points_concat = np.concatenate(ls_points, axis=0)
                n_cells = cells_concat.reshape([-1, 5]).shape[0]

        except:
            print('erreur {}'.format(i))

    cell_type = np.array([vtk.VTK_TETRA] * n_cells)
    offset = np.arange(0, n_cells * 5, step=5)
    grid = polyv.UnstructuredGrid(offset, cells_concat, cell_type,
                                  points_concat)
    return grid