Example #1
0
def PlotAntsPlane():
    """
    Demonstrate how to create a plot class to plot multiple meshes while
    adding scalars and text.
    Plot two ants and airplane
    """

    # load and shrink airplane
    airplane = vtkInterface.PolyData(planefile)
    airplane.points /= 10
    # pts = airplane.GetNumpyPoints() # gets pointer to array
    # pts /= 10  # shrink

    # rotate and translate ant so it is on the plane
    ant = vtkInterface.PolyData(antfile)
    ant.RotateX(90)
    ant.Translate([90, 60, 15])

    # Make a copy and add another ant
    ant_copy = ant.Copy()
    ant_copy.Translate([30, 0, -10])

    # Create plotting object
    plobj = vtkInterface.PlotClass()
    plobj.AddMesh(ant, 'r')
    plobj.AddMesh(ant_copy, 'b')

    # Add airplane mesh and make the color equal to the Y position
    plane_scalars = airplane.points[:, 1]
    plobj.AddMesh(airplane, scalars=plane_scalars, stitle='Plane Y\nLocation')
    plobj.AddText('Ants and Plane Example')
    plobj.Plot()
Example #2
0
def MakeLine(points):
    """
    Generates line from points.  Assumes points are ordered as line segments.

    Parameters
    ----------
    points : np.ndarray
        Points representing line segments.  For example, two line segments 
        would be represented as:

        np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]])

    Returns
    -------
    lines : vtki.PolyData
        PolyData with lines and cells.

    Examples
    --------
    This example plots two line segments at right angles to each other line.

    >>> import vtkInterface as vtki
    >>> points = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]])
    >>> lines = vtki.MakeLine(points)
    >>> lines.Plot()

    """
    # Assuming ordered points, create array defining line order
    npoints = points.shape[0] - 1
    lines = np.vstack((2 * np.ones(npoints, np.int), np.arange(npoints),
                       np.arange(1, npoints + 1))).T.ravel()

    return vtkInterface.PolyData(points, lines)
Example #3
0
def MakePointMesh(points, deep=True):
    """ Convert numpy points to vtkPoints """

    # Data checking
    if not points.flags['C_CONTIGUOUS']:
        points = np.ascontiguousarray(points)

    # Convert to vtk objects
    vtkpoints = vtk.vtkPoints()
    vtkpoints.SetData(numpy_to_vtk(points, deep=True))

    npoints = points.shape[0]

    pcell = np.vstack((np.ones(npoints, dtype=np.int64),
                       np.arange(npoints, dtype=np.int64))).ravel('F')

    # Convert to a vtk array
    vtkcells = vtk.vtkCellArray()
    vtkcells.SetCells(npoints, numpy_to_vtkIdTypeArray(pcell, deep=True))

    # Create polydata object
    mesh = vtkInterface.PolyData()
    mesh.SetPoints(vtkpoints)
    mesh.SetPolys(vtkcells)

    # return cleaned mesh
    return mesh
Example #4
0
def MeshfromVF(points, triangles_in, clean=True, deep_points=True):
    """ Generates mesh from points and triangles """

    # Add face padding if necessary
    if triangles_in.shape[1] == 3:
        triangles = np.empty((triangles_in.shape[0], 4), dtype=np.int64)
        triangles[:, -3:] = triangles_in
        triangles[:, 0] = 3

    else:
        triangles = triangles_in

    # Data checking
    if not points.flags['C_CONTIGUOUS']:
        points = np.ascontiguousarray(points)

    if not triangles.flags['C_CONTIGUOUS'] or triangles.dtype != 'int64':
        triangles = np.ascontiguousarray(triangles, 'int64')

    # Convert to vtk objects
    vtkpoints = MakevtkPoints(points, deep=deep_points)

    # Convert to a vtk array
    vtkcells = vtk.vtkCellArray()
    vtkcells.SetCells(triangles.shape[0],
                      numpy_to_vtkIdTypeArray(triangles, deep=True))

    mesh = vtkInterface.PolyData()
    mesh.SetPoints(vtkpoints)
    mesh.SetPolys(vtkcells)

    if clean:
        mesh.Clean()
    return mesh
Example #5
0
    def ExtractSurface(self, pass_pointid=True, pass_cellid=True):
        """
        Extract surface mesh of the grid

        Parameters
        ----------
        pass_pointid : bool, optional
            Adds a point scalar "vtkOriginalPointIds" that idenfities which
            original points these surface points correspond to

        pass_cellid : bool, optional
            Adds a cell scalar "vtkOriginalPointIds" that idenfities which
            original cells these surface cells correspond to

        Returns
        -------
        extsurf : vtki.PolyData
            Surface mesh of the grid
        """
        surf_filter = vtk.vtkDataSetSurfaceFilter()
        surf_filter.SetInputData(self)
        if pass_pointid:
            surf_filter.PassThroughCellIdsOn()
        if pass_cellid:
            surf_filter.PassThroughPointIdsOn()
        surf_filter.Update()
        return vtki.PolyData(surf_filter.GetOutput())
Example #6
0
class TestPolyData(object):
    sphere = vtki.PolyData(spherefile)

    def test_loadfromfile(self):
        sphere = vtki.PolyData(spherefile)
        assert sphere.GetNumberOfPoints()
        assert sphere.GetNumberOfCells()
        assert hasattr(sphere, 'points')
Example #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
Example #8
0
def reada4db():
    with open("WS_neu_mitMPCundMasse_v9_500kg__Traegheit_3Contact.inp") as f:
        bodyText = f.read()
        # node_search = re.compile('*NODE\n( +[0-9\.\+e\-,]+\n*){202,2500}', re.S)
        node_search = re.compile('\*NODE\n( +[0-9\.\+e\-, ]+\n){202,25000}',
                                 re.S)
        cell_search = re.compile(
            '\*ELEMENT[, A-Z=;0-9_]*\n( +[0-9\.\+e\-, ]+\n*){3,150000}', re.S)

        locationOfNodes = re.finditer(node_search, bodyText)
        locationOfCells = re.finditer(cell_search, bodyText)

        vertices = [
            list(map(float,
                     item.split(",")[1:]))
            for item in next(locationOfNodes)[0].split("\n")
        ][:-1]

        cellPoints = None
        cellIds = None
        for items in locationOfCells:
            if cellPoints is None:
                cellPoints = [
                    list(map(float,
                             item.split(",")[1:]))
                    for item in items[0].split("\n")[1:]
                ][:-1]
                # print(len(cellPoints))

                cellPoints = [[len(item)] + item for item in cellPoints]
                cellIds = [
                    item.split(",")[0] for item in items[0].split("\n")[1:]
                ][:-1]
            else:

                newCellPoints = [
                    list(map(float,
                             item.split(",")[1:]))
                    for item in items[0].split("\n")[1:]
                ][:-1]
                newCellPoints = [[len(item)] + item for item in newCellPoints]
                cellPoints = cellPoints + newCellPoints
                cellIds = cellIds + [
                    item.split(",")[0] for item in items[0].split("\n")[1:]
                ][:-1]

        cellPoints = np.hstack(cellPoints)
        cellIds = np.array(cellIds)
        vertices[0] = [0, 0, 0]
        vertices = np.array(vertices)

        # print(cellIds.shape)
        surf = vtkInterface.PolyData(vertices, cellPoints)

        # surf.Plot()
        surf.Write("sample.vtk")
Example #9
0
def MakeLine(points):
    """ Generates line from points.  Assumes points are ordered """

    # Assuming ordered points, create array defining line order
    npoints = points.shape[0] - 1
    lines = np.vstack((2 * np.ones(npoints, np.int), np.arange(npoints),
                       np.arange(1, npoints + 1))).T.ravel()

    # Create polydata object
    return vtkInterface.PolyData(points, lines)
Example #10
0
def CreateVectorPolyData(orig, vec):
    """ Creates a vtkPolyData object composed of vectors """

    # shape, dimention checking
    if not isinstance(orig, np.ndarray):
        orig = np.asarray(orig)

    if not isinstance(vec, np.ndarray):
        vec = np.asarray(vec)

    if orig.ndim != 2:
        orig = orig.reshape((-1, 3))
    elif orig.shape[1] != 3:
        raise Exception('orig array must be 3D')

    if vec.ndim != 2:
        vec = vec.reshape((-1, 3))
    elif vec.shape[1] != 3:
        raise Exception('vec array must be 3D')

    # Create vtk points and cells objects
    vpts = vtk.vtkPoints()
    vpts.SetData(numpy_to_vtk(np.ascontiguousarray(orig), deep=True))

    npts = orig.shape[0]
    cells = np.hstack((np.ones((npts, 1), 'int'), np.arange(npts).reshape(
        (-1, 1))))

    if cells.dtype != ctypes.c_int64 or cells.flags.c_contiguous:
        cells = np.ascontiguousarray(cells, ctypes.c_int64)
    vcells = vtk.vtkCellArray()
    vcells.SetCells(npts, numpy_to_vtkIdTypeArray(cells, deep=True))

    # Create vtkPolyData object
    pdata = vtk.vtkPolyData()
    pdata.SetPoints(vpts)
    pdata.SetVerts(vcells)

    # Add vectors to polydata
    name = 'vectors'
    vtkfloat = numpy_to_vtk(np.ascontiguousarray(vec), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveVectors(name)

    # Add magnitude of vectors to polydata
    name = 'mag'
    scalars = (vec * vec).sum(1)**0.5
    vtkfloat = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveScalars(name)

    return vtkInterface.PolyData(pdata)
Example #11
0
def WithVTK(plot=True):
    """ Tests VTK interface and mesh repair of Stanford Bunny Mesh """
    mesh = vtki.PolyData(bunny_scan)
    meshfix = pymeshfix.MeshFix(mesh)
    if plot:
        print('Plotting input mesh')
        meshfix.Plot()
    meshfix.Repair()
    if plot:
        print('Plotting repaired mesh')
        meshfix.Plot()

    return meshfix.mesh
Example #12
0
def PlotBoundaries(mesh, **args):
    """ Plots boundaries of a mesh """
    featureEdges = vtk.vtkFeatureEdges()
    featureEdges.SetInputData(mesh)
    featureEdges.FeatureEdgesOff()
    featureEdges.BoundaryEdgesOn()
    featureEdges.NonManifoldEdgesOn()
    featureEdges.ManifoldEdgesOff()
    featureEdges.Update()
    edges = vtkInterface.PolyData(featureEdges.GetOutput())

    plobj = PlotClass()
    plobj.AddMesh(edges, 'r', style='wireframe')
    plobj.AddMesh(mesh)
    plobj.Plot()
Example #13
0
def test_repairVTK():
    meshin = vtki.PolyData(bunny_scan)
    meshfix = pymeshfix.MeshFix(meshin)
    meshfix.Repair()

    # check arrays and output mesh
    assert np.any(meshfix.v)
    assert np.any(meshfix.f)
    meshout = meshfix.mesh
    assert meshfix.mesh.GetNumberOfPoints()

    # test for any holes
    pdata = meshout.ExtractEdges(non_manifold_edges=False,
                                 feature_edges=False,
                                 manifold_edges=False)
    assert pdata.GetNumberOfPoints() == 0
Example #14
0
def test_native():
    out_file = 'repaired.ply'

    # test write permissions
    curdir = os.getcwd()
    if not os.access(curdir, os.W_OK):
        raise Exception('Cannot write output mesh here at %s' % curdir)

    pymeshfix._meshfix.CleanFromFile(bunny_scan, out_file, verbose=False)
    outmesh = vtki.PolyData(out_file)
    os.remove(out_file)
    assert outmesh.GetNumberOfPoints()

    # test for any holes
    pdata = outmesh.ExtractEdges(non_manifold_edges=False,
                                 feature_edges=False,
                                 manifold_edges=False)
    assert pdata.GetNumberOfPoints() == 0
Example #15
0
def MakeVTKPointsMesh(points):
    """ Create a PolyData object from a numpy array containing just points """
    if points.ndim != 2:
        points = points.reshape((-1, 3))

    npoints = points.shape[0]

    # Make VTK cells array
    cells = np.hstack((np.ones(
        (npoints, 1)), np.arange(npoints).reshape(-1, 1)))
    cells = np.ascontiguousarray(cells, dtype=np.int64)
    vtkcells = vtk.vtkCellArray()
    vtkcells.SetCells(npoints, numpy_to_vtkIdTypeArray(cells, deep=True))

    # Convert points to vtk object
    vtkPoints = vtkInterface.MakevtkPoints(points)

    # Create polydata
    pdata = vtkInterface.PolyData()
    pdata.SetPoints(vtkPoints)
    pdata.SetVerts(vtkcells)
    return pdata
Example #16
0
def CreateVectorPolyData(orig, vec):
    """ Creates a vtkPolyData object composed of vectors """

    # Create vtk points and cells objects
    vpts = vtk.vtkPoints()
    vpts.SetData(numpy_to_vtk(np.ascontiguousarray(orig), deep=True))

    npts = orig.shape[0]
    cells = np.hstack((np.ones((npts, 1), 'int'), np.arange(npts).reshape(
        (-1, 1))))

    if cells.dtype != np.int64 or cells.flags.c_contiguous:
        cells = np.ascontiguousarray(cells, np.int64)
    vcells = vtk.vtkCellArray()
    vcells.SetCells(npts, numpy_to_vtkIdTypeArray(cells, deep=True))

    # Create vtkPolyData object
    pdata = vtk.vtkPolyData()
    pdata.SetPoints(vpts)
    pdata.SetVerts(vcells)

    # Add vectors to polydata
    name = 'vectors'
    vtkfloat = numpy_to_vtk(np.ascontiguousarray(vec), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveVectors(name)

    # Add magnitude of vectors to polydata
    name = 'mag'
    scalars = (vec * vec).sum(1)**0.5
    vtkfloat = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveScalars(name)

    return vtkInterface.PolyData(pdata)
Example #17
0
#        contour = mp.fill_contour(contour, fill_xy=True)

#        pl.PlotImage(data, res=resolution)

    ################################################################################
        ''' Run MarchingCubes in skimage and convert to VTK format '''
#        contour = contour[:46]

        xyzres = resolution
        A.contour = contour

        verts, faces, normals, values = measure.marching_cubes_lewiner(
            A.contour, 0, spacing=list(resolution / np.min(resolution)), step_size=1,
            allow_degenerate=False)
        faces = np.hstack(np.c_[np.full(faces.shape[0], 3), faces])
        A.mesh = vi.PolyData(verts, faces)

        del faces, verts, normals, values

        ''' Process mesh '''
        bounds = A.mesh.GetBounds()
        A.mesh.ClipPlane([np.ceil(bounds[0]), 0, 0], [(xyzres[0] + 0.0001), 0, 0])
        A.mesh.ClipPlane([np.floor(bounds[1]), 0, 0], [-(xyzres[0] + 0.0001), 0, 0])
        A.mesh.ClipPlane([0, np.ceil(bounds[2]), 0], [0, (xyzres[1] + 0.0001), 0])
        A.mesh.ClipPlane([0, np.floor(bounds[3]), 0], [0, -(xyzres[1] + 0.0001), 0])
        A.mesh.ClipPlane([0, 0, np.ceil(bounds[4])], [0, 0, (xyzres[2] + 0.0001)])
        A.mesh.ClipPlane([0, 0, np.floor(bounds[5])], [0, 0, -(xyzres[2] + 0.0001)])
        A.mesh = mp.ECFT(A.mesh, 100)
        A.mesh = mp.correct_bad_mesh(A.mesh)

        A.mesh = mp.ECFT(A.mesh, 100)
Example #18
0
    if plot:
        print('Plotting input mesh')
        meshfix.Plot()
    meshfix.Repair()
    if plot:
        print('Plotting repaired mesh')
        meshfix.Plot()

    return meshfix.mesh


if __name__ == '__main__':
    """ Functional Test: vtk and native """
    out_file = 'repaired.ply'
    Native()
    outmesh = vtki.PolyData(out_file)
    os.remove(out_file)
    assert outmesh.GetNumberOfPoints()

    # test for any holes
    pdata = outmesh.ExtractEdges(non_manifold_edges=False,
                                 feature_edges=False,
                                 manifold_edges=False)
    assert pdata.GetNumberOfPoints() == 0

    # test vtk
    meshin = vtki.PolyData(bunny_scan)
    meshfix = pymeshfix.MeshFix(meshin)
    meshfix.Repair()

    # check arrays and output mesh
Example #19
0
def LoadSphere():
    """ Loads sphere ply mesh """
    return vtkInterface.PolyData(spherefile)
Example #20
0
def LoadAnt():
    """ Load ply ant mesh """
    return vtkInterface.PolyData(antfile)
Example #21
0
def PlotAnt():
    """ Plot a red ant in wireframe"""
    ant = vtkInterface.PolyData(antfile)
    ant.Plot(color='r', style='wireframe')
Example #22
0
def PlotAirplane():
    """ Plot a white airplane """
    airplane = vtkInterface.PolyData(planefile)
    airplane.Plot()
Example #23
0
def PlotSphere():
    """ Plot a white airplane """
    sphere = vtkInterface.PolyData(spherefile)
    sphere.Plot()
Example #24
0
def test_loadfromfile():
    sphere = vtki.PolyData(spherefile)
    assert sphere.GetNumberOfPoints()
    assert sphere.GetNumberOfCells()
    assert hasattr(sphere, 'points')
Example #25
0
def LoadAirplane():
    """ Load ply airplane mesh """
    return vtkInterface.PolyData(planefile)