def mixed_type_ug():
    """A slightly more complex example of how to generate an
    unstructured grid with different cell types.  Returns a created
    unstructured grid.
    """
    points = array([[0,0,0], [1,0,0], [0,1,0], [0,0,1], # tetra
                    [2,0,0], [3,0,0], [3,1,0], [2,1,0],
                    [2,0,1], [3,0,1], [3,1,1], [2,1,1], # Hex
                    ], 'f')
    # shift the points so we can show both.
    points[:,1] += 2.0
    # The cells
    cells = array([4, 0, 1, 2, 3, # tetra
                   8, 4, 5, 6, 7, 8, 9, 10, 11 # hex
                   ])
    # The offsets for the cells, i.e. the indices where the cells
    # start.
    offset = array([0, 5])
    tetra_type = tvtk.Tetra().cell_type # VTK_TETRA == 10
    hex_type = tvtk.Hexahedron().cell_type # VTK_HEXAHEDRON == 12
    cell_types = array([tetra_type, hex_type])
    # Create the array of cells unambiguously.
    cell_array = tvtk.CellArray()
    cell_array.set_cells(2, cells)
    # Now create the UG.
    ug = tvtk.UnstructuredGrid(points=points)
    # Now just set the cell types and reuse the ug locations and cells.
    ug.set_cells(cell_types, offset, cell_array)
    return ug
def make_data():
    points = N.array([[0,0,0], [1,0,0], [0,1,0], [0,0,1], # tets
                    [1,0,0], [2,0,0], [1,1,0], [1,0,1],
                    [2,0,0], [3,0,0], [2,1,0], [2,0,1],
                    ], 'f')
    tets = N.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
    tet_type = tvtk.Tetra().cell_type
    ug = tvtk.UnstructuredGrid(points=points)
    ug.set_cells(tet_type, tets)
    # Setup the point attributes.
    temp = N.random.random(12)
    v = N.random.randn(12, 3)
    ten = N.random.randn(12, 9)
    a = tvtk.FloatArray(name='p')
    a.from_array(N.random.randn(12))
    ug.point_data.add_array(a)
    ug.point_data.scalars = temp
    ug.point_data.scalars.name = 't'
    ug.point_data.vectors = v
    ug.point_data.vectors.name = 'v'
    ug.point_data.tensors = ten
    ug.point_data.tensors.name = 'ten'
    # Setup the cell attributes.
    temp = N.random.random(3)
    v = N.random.randn(3, 3)
    ten = N.random.randn(3, 9)
    ug.cell_data.scalars = temp
    ug.cell_data.scalars.name = 't'
    ug.cell_data.vectors = v
    ug.cell_data.vectors.name = 'v'
    ug.cell_data.tensors = ten
    ug.cell_data.tensors.name = 'ten'
    return ug
Exemple #3
0
def get_complete_structure(tetrahedrons):
    """
    Visualize the complete tetrahedron mesh of all regions of the tetrahedron mesh
    :param tetrahedrons: list of tetrahedrons (of type Tetrahedron)
    :return: data for mayavi data source
    """
    vertices = list()
    tets = list()

    index = 0
    for tetrahedron in tetrahedrons:
        tet_vertices_indices = []
        for i in range(4):
            v = tetrahedron.get_vertex(i)
            vertices.append([v.x, v.y, v.z])
            tet_vertices_indices.append(index)
            index += 1

        tets.append(tet_vertices_indices)

    vertices = np.array(vertices)
    tets = np.array(tets)
    tet_type = tvtk.Tetra().cell_type
    unstructured_grid = tvtk.UnstructuredGrid(points=vertices)
    unstructured_grid.set_cells(tet_type, tets)
    return unstructured_grid
def single_type_ug():
    """Simple example showing how to create an unstructured grid
    consisting of cells of a single type.
    """
    points = array(
        [
            [0, 0, 0],
            [1, 0, 0],
            [0, 1, 0],
            [0, 0, 1],  # tets
            [1, 0, 0],
            [2, 0, 0],
            [1, 1, 0],
            [1, 0, 1],
            [2, 0, 0],
            [3, 0, 0],
            [2, 1, 0],
            [2, 0, 1],
        ],
        'f')
    tets = array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
    tet_type = tvtk.Tetra().cell_type
    ug = tvtk.UnstructuredGrid(points=points)
    ug.set_cells(tet_type, tets)
    return ug
Exemple #5
0
def unstructured_grid():
    points = array(
        [
            [0, 1.2, 0.6],
            [1, 0, 0],
            [0, 1, 0],
            [1, 1, 1],  # tetra
            [1, 0, -0.5],
            [2, 0, 0],
            [2, 1.5, 0],
            [0, 1, 0],
            [1, 0, 0],
            [1.5, -0.2, 1],
            [1.6, 1, 1.5],
            [1, 1, 1],  # Hex
        ],
        'f')
    # The cells
    cells = array([
        4,
        0,
        1,
        2,
        3,  # tetra
        8,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11  # hex
    ])
    # The offsets for the cells, i.e. the indices where the cells
    # start.
    offset = array([0, 5])
    tetra_type = tvtk.Tetra().cell_type  # VTK_TETRA == 10
    hex_type = tvtk.Hexahedron().cell_type  # VTK_HEXAHEDRON == 12
    cell_types = array([tetra_type, hex_type])
    # Create the array of cells unambiguously.
    cell_array = tvtk.CellArray()
    cell_array.set_cells(2, cells)
    # Now create the UG.
    ug = tvtk.UnstructuredGrid(points=points)
    # Now just set the cell types and reuse the ug locations and cells.
    ug.set_cells(cell_types, offset, cell_array)
    scalars = random.random(points.shape[0])
    ug.point_data.scalars = scalars
    ug.point_data.scalars.name = 'scalars'
    return ug
Exemple #6
0
def write_vtk_mesh(mesh, fileName):
    node = mesh.entity('node')
    GD = mesh.geo_dimension()
    if GD == 2:
        node = np.concatenate(
            (node, np.zeros((node.shape[0], 1), dtype=mesh.ftype)), axis=1)
    ug = tvtk.UnstructuredGrid(points=node)

    if mesh.meshtype is 'hex':
        cell_type = tvtk.Hexahedron().cell_type
        cell = mesh.ds.cell
    elif mesh.meshtype is 'tri':
        cell_type = tvtk.Triangle().cell_type
        cell = mesh.ds.cell
        for key, value in mesh.cellData.items():
            i = ug.cell_data.add_array(value)
            ug.cell_data.get_array(i).name = key
        for key, value in mesh.pointData.items():
            i = ug.point_data.add_array(value)
            ug.point_data.get_array(i).name = key
    elif mesh.meshtype is 'polyhedron':
        cell_type = tvtk.Polygon().cell_type
        NF, faces = mesh.to_vtk()
        cell = tvtk.CellArray()
        cell.set_cells(NF, faces)
    elif mesh.meshtype is 'polygon':
        cell_type = tvtk.Polygon().cell_type
        NC, cells = mesh.to_vtk()
        cell = tvtk.CellArray()
        cell.set_cells(NC, cells)
    elif mesh.meshtype is 'tet':
        cell_type = tvtk.Tetra().cell_type
        cell = mesh.ds.cell
        for key, value in mesh.cellData.items():
            i = ug.cell_data.add_array(value)
            ug.cell_data.get_array(i).name = key
        for key, value in mesh.pointData.items():
            i = ug.point_data.add_array(value)
            ug.point_data.get_array(i).name = key
    ug.set_cells(cell_type, cell)
    write_data(ug, fileName)
Exemple #7
0
def write_vtk_mesh(mesh, fileName):
    point = mesh.point
    if point.shape[1] == 2:
        point = np.concatenate(
            (point, np.zeros((point.shape[0], 1), dtype=np.float)), axis=1)
    ug = tvtk.UnstructuredGrid(points=point)

    if mesh.meshtype is 'hex':
        cell_type = tvtk.Hexahedron().cell_type
        cell = mesh.ds.cell
    elif mesh.meshtype is 'tri':
        cell_type = tvtk.Triangle().cell_type
        cell = mesh.ds.cell
        for key, value in mesh.cellData.items():
            i = ug.cell_data.add_array(value)
            ug.cell_data.get_array(i).name = key
        for key, value in mesh.pointData.items():
            i = ug.point_data.add_array(value)
            ug.point_data.get_array(i).name = key
    elif mesh.meshtype is 'polyhedron':
        cell_type = tvtk.Polygon().cell_type
        NF, faces = mesh.to_vtk()
        cell = tvtk.CellArray()
        cell.set_cells(NF, faces)
        ug.cell_data.scalars = mesh.cellData['flag']
    elif mesh.meshtype is 'polygon':
        cell_type = tvtk.Polygon().cell_type
        NC, cells = mesh.to_vtk()
        cell = tvtk.CellArray()
        cell.set_cells(NC, cells)
    elif mesh.meshtype is 'tet':
        cell_type = tvtk.Tetra().cell_type
        cell = mesh.ds.cell
        for key, value in mesh.cellData.items():
            i = ug.cell_data.add_array(value)
            ug.cell_data.get_array(i).name = key
        for key, value in mesh.pointData.items():
            i = ug.point_data.add_array(value)
            ug.point_data.get_array(i).name = key
    ug.set_cells(cell_type, cell)
    write_data(ug, fileName)
Exemple #8
0
    def _readData(self):
        from tvtk.api import tvtk
        import h5py
        import numpy

        filename = "output/%s_%s.h5" % (cell, resolution)
        h5 = h5py.File(filename, 'r', driver="sec2")

        elastThick = 40.0e+3
        eqslip = 4.0

        cells = h5['topology/cells'][:]
        (ncells, ncorners) = cells.shape
        vertices = h5['geometry/vertices'][:] / elastThick
        (nvertices, spaceDim) = vertices.shape
        disp = h5['vertex_fields/displacement'][tindex, :, :] / eqslip
        h5.close()

        if cell == "tet4":
            assert (spaceDim == 3)
            assert (ncorners == 4)
            cellType = tvtk.Tetra().cell_type
        elif cell == "hex8":
            assert (spaceDim == 3)
            assert (ncorners == 8)
            cellType = tvtk.Hexahedron().cell_type
        else:
            raise ValueError("Unknown cell '%s'." % cell)

        if (resolution != "6.7km" and resolution != "20km"):
            raise ValueError("Unavailable resolution '%s'." % resolution)

        data = tvtk.UnstructuredGrid()
        data.points = vertices
        data.set_cells(cellType, cells)
        data.point_data.vectors = disp
        data.point_data.vectors.name = "Displacement [m]"
        return data
Exemple #9
0
    def View(self, engine="mpl", **kwargs):
        """ 
          Plots the mesh in a figure. Supports 2D and 3D mesh with two visualization backends. Call signature ::\n
         
                 Tmesh.View()
          
          - engine: 
            -  `mpl` to use a matplotlib as 2D and 3D scatter plotting backend
            -  `myv` (default) to use Mayavi for 2D and 3D mesh rendering (using `tvtk`)
          - kwargs:
              - if 'engine' argument is set to `mpl` then Matplotlib's keywords are used:
                  - linestyle or ls	: '-' , '--' , '-.' ...
                  - linewidth or lw	float value in points
                  - marker: 'x' , 'o' , 'v' ...
                  - color: 'r' (red), 'k' (black) , 'b' (blue) ...
                  - [check url: http://matplotlib.org/1.3.1/api/artist_api.html#module-matplotlib.lines] \n\n
          
          
         - if 'engine' argument is set to "myv" then Mayavi's keywords are used:
          
           - color:	the color of the vtk object. Overides the colormap, if any, when specified. This is specified as a triplet of float ranging from 0 to 1, eg (1, 1, 1) for white.
           - colormap:	type of colormap to use.
           - extent:	[xmin, xmax, ymin, ymax, zmin, zmax] Default is the x, y, z arrays extent. Use this to change the extent of the object created.
      """

        dim = self.dimNode
        nb_points_real = self.GetNumberOfPoints()
        nb_points = nb_points_real + 1  # the fictitious node of index 0 and coordinates [0,0]

        ### a dict constructor is necessary so that the class's member
        ### dictionary wont be affected when fictitious triangles are suppressed
        real_elements_dict = dict(self.elements_dict)

        # the 'enumerate' function is really nice !
        for i, connec_list in enumerate(real_elements_dict.values()):
            if 0 in connec_list: del real_elements_dict[i + 1]
            # i+1 because enumerate starts at 0 while my dict starts at 1

        # The lists have to be cast into numpy arrays before using the TRI plot
        points = np.asarray(self.nodes_dict.values())
        simplexes = np.asarray(real_elements_dict.values())

        # Extracting columns
        x = points[:, 0]
        y = points[:, 1]

        if dim == 2:
            # points_2d is used in mayavi rendering
            points_2d = np.column_stack([points, np.zeros((nb_points, 1))])
        elif dim == 3:
            # z is used in matplotlib rendering
            z = points[:, 2]
            # points_3d is used in mayavi rendering
            points_3d = points

        if engine == "mpl":

            if dim == 2:
                plt.figure()
                plt.gca().set_aspect('equal')
                plt.triplot(x, y, simplexes, **kwargs)
                plt.title('Mesh')
                plt.show()

            elif dim == 3:
                # TODO: add line connection between scattered points
                fig = plt.figure()
                ax = fig.add_subplot(111, projection='3d', aspect='equal')
                ax.scatter3D(x, y, z, **kwargs)
                ax.set_xlabel('X Label')
                ax.set_ylabel('Y Label')
                ax.set_zlabel('Z Label')
                plt.axis()
                plt.show()

        elif engine == "myv":

            if dim == 2:
                #this way works
                #              z = np.zeros_like(x)
                #              triangles = []
                #              for trigl in real_elements_dict.values(): triangles.append(tuple(trigl))
                #              ml.triangular_mesh(x, y, z, triangles, representation = 'wireframe')

                #another way
                simplex_type = 5  # = 10 for tetrahedron
                ug = tvtk.UnstructuredGrid(points=points_2d)

            if dim == 3:
                simplex_type = tvtk.Tetra().cell_type  # = 10 for tetrahedron
                ug = tvtk.UnstructuredGrid(points=points_3d)

            ug.set_cells(simplex_type, simplexes)
            fig = ml.figure(bgcolor=(1, 1, 1),
                            fgcolor=(0, 0, 0),
                            figure=ug.class_name[3:])
            surf = ml.pipeline.surface(ug, opacity=0.01)
            RGB = (0, 0, 0.5)
            #edge_color = tuple(i/255 for i in RGB)
            ml.pipeline.surface(ml.pipeline.extract_edges(surf), color=RGB)
Exemple #10
0
    6,
    7,
    8,
    9,
    10,
    11,  # hex
    3,
    3,
    1,
    5
])
# The offsets for the cells, i.e. the indices where the cells
# start.
# offset = np.array([0, 5, 14])
offset = np.array([0, 5, 14])
tetra_type = tvtk.Tetra().cell_type  # VTK_TETRA == 10
hex_type = tvtk.Hexahedron().cell_type  # VTK_HEXAHEDRON == 12
cell_types = np.array([tetra_type, hex_type, 5])
# Create the array of cells unambiguously.
cell_array = tvtk.CellArray()
cell_array.set_cells(3, cells)
print('cell_array')
print(cell_array)
# Now create the UG.
ug = tvtk.UnstructuredGrid(points=surf_points)
# Now just set the cell types and reuse the ug locations and cells.
ug.set_cells(cell_types, offset, cell_array)
mlab.pipeline.surface(ug)
# mlab.show()

mlab.show()