Python vtk.util.numpy_support.vtk_to_numpy() Examples

The following are code examples for showing how to use vtk.util.numpy_support.vtk_to_numpy(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: paraviewweb-apache   Author: singularityhub   File: divvyProtocol.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def calc2DHistogram(self, key, numBins):
    result = np.zeros((numBins, numBins))
    # print(key[0], key[1])
    vtkX = self.dataTable.GetColumnByName(key[0])
    vtkY = self.dataTable.GetColumnByName(key[1])
    xrng = vtkX.GetRange()
    yrng = vtkY.GetRange()

    px = vtk_to_numpy(vtkX)
    py = vtk_to_numpy(vtkY)
    # clip puts maximum values into the last bin
    # ix = np.clip(np.floor((px - xrng[0]) * numBins / (xrng[1] - xrng[0])).astype(int), 0, numBins - 1)
    # iy = np.clip(np.floor((py - yrng[0]) * numBins / (yrng[1] - yrng[0])).astype(int), 0, numBins - 1)
    # for i, j in zip(ix, iy):
    #     result[i,j] += 1
    result = np.histogram2d(px, py, bins=numBins, range=[xrng, yrng])[0]
    return result 
Example 2
Project: telluricpy   Author: grosenkj   File: polydata.py    MIT License 6 votes vote down vote up
def extrudePolygon(polyObject,extrudeFactor,vector=None,centered=False):
    """
    Extrude polygons by a scalar factor.
    """
    extrude = vtk.vtkLinearExtrusionFilter()
    extrude.CappingOn()
    if vector is not None:
        extrude.SetExtrusionTypeToVectorExtrusion()
        extrude.SetVector(vector)
    else:
        extrude.SetExtrusionTypeToNormalExtrusion()
        polyObject = normFilter(polyObject)
    extrude.SetInputData(polyObject)
    extrude.SetScaleFactor(extrudeFactor)
    extrude.Update()
    ext = extrude.GetOutput()
    if centered and vector is not None:
        extPts = npsup.vtk_to_numpy(ext.GetPoints().GetData())
        newPts = vtk.vtkPoints()
        newNppts = extPts - (np.array(vector)*(extrudeFactor/2))
        newPts.SetData(npsup.numpy_to_vtk(newNppts,deep=1))
        ext.SetPoints(newPts)

    return ext 
Example 3
Project: pyvista   Author: pyvista   File: test_common.py    MIT License 6 votes vote down vote up
def test_shallow_copy_back_propagation():
    """Test that the original data object's points get modified after a
    shallow copy.

    Reference: https://github.com/pyvista/pyvista/issues/375#issuecomment-531691483
    """
    # Case 1
    points = vtk.vtkPoints()
    points.InsertNextPoint(0.0, 0.0, 0.0)
    points.InsertNextPoint(1.0, 0.0, 0.0)
    points.InsertNextPoint(2.0, 0.0, 0.0)
    original = vtk.vtkPolyData()
    original.SetPoints(points)
    wrapped = pyvista.PolyData(original, deep=False)
    wrapped.points[:] = 2.8
    orig_points = vtk_to_numpy(original.GetPoints().GetData())
    assert np.allclose(orig_points, wrapped.points)
    # Case 2
    original = vtk.vtkPolyData()
    wrapped = pyvista.PolyData(original, deep=False)
    wrapped.points = np.random.rand(5, 3)
    orig_points = vtk_to_numpy(original.GetPoints().GetData())
    assert np.allclose(orig_points, wrapped.points) 
Example 4
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 6 votes vote down vote up
def addCellScalars(self, scalars, name):
        """
        Add cell scalars and assigning it a name.
        """
        data = self.inputdata()
        if isinstance(scalars, str):
            scalars = vtk_to_numpy(data.GetPointData().GetArray(scalars))

        if len(scalars) != data.GetNumberOfCells():
            colors.printc("~times addCellScalars() Number of scalars != nr. of cells",
                          len(scalars), data.GetNumberOfCells(), c=1)
            raise RuntimeError()

        arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
        arr.SetName(name)
        data.GetCellData().AddArray(arr)
        data.GetCellData().SetActiveScalars(name)
        self._mapper.SetArrayName(name)
        if settings.autoResetScalarRange:
            self._mapper.SetScalarRange(np.min(scalars), np.max(scalars))
        self._mapper.SetScalarModeToUseCellData()
        self._mapper.ScalarVisibilityOn()
        return self 
Example 5
Project: discretize   Author: simpeg   File: test_tensor_vtk.py    MIT License 6 votes vote down vote up
def test_VTK_object_conversion(self):
            mesh = self.mesh
            vec = np.arange(mesh.nC)
            models = {'arange': vec}

            vtkObj = mesh.to_vtk(models)

            self.assertEqual(mesh.nC, vtkObj.GetNumberOfCells())
            self.assertEqual(mesh.nN, vtkObj.GetNumberOfPoints())
            self.assertEqual(len(models.keys()), vtkObj.GetCellData().GetNumberOfArrays())
            bnds = vtkObj.GetBounds()
            self.assertEqual(mesh.x0[0], bnds[0])
            self.assertEqual(mesh.x0[1], bnds[2])
            self.assertEqual(mesh.x0[2], bnds[4])

            for i in range(vtkObj.GetCellData().GetNumberOfArrays()):
                name = list(models.keys())[i]
                self.assertEqual(name, vtkObj.GetCellData().GetArrayName(i))
                arr = nps.vtk_to_numpy(vtkObj.GetCellData().GetArray(i))
                arr = arr.flatten(order='F')
                self.assertTrue(np.allclose(models[name], arr)) 
Example 6
Project: discretize   Author: simpeg   File: test_curvilinear_vtk.py    MIT License 6 votes vote down vote up
def test_VTK_object_conversion(self):
            mesh = self.mesh
            vec = np.arange(mesh.nC)
            models = {'arange': vec}

            vtkObj = mesh.to_vtk(models)

            self.assertEqual(mesh.nC, vtkObj.GetNumberOfCells())
            self.assertEqual(mesh.nN, vtkObj.GetNumberOfPoints())
            self.assertEqual(len(models.keys()), vtkObj.GetCellData().GetNumberOfArrays())
            bnds = vtkObj.GetBounds()
            self.assertEqual(mesh.x0[0], bnds[0])
            self.assertEqual(mesh.x0[1], bnds[2])
            self.assertEqual(mesh.x0[2], bnds[4])

            names = list(models.keys())
            for i in range(vtkObj.GetCellData().GetNumberOfArrays()):
                name = names[i]
                self.assertEqual(name, vtkObj.GetCellData().GetArrayName(i))
                arr = nps.vtk_to_numpy(vtkObj.GetCellData().GetArray(i))
                arr = arr.flatten(order='F')
                self.assertTrue(np.allclose(models[name], arr)) 
Example 7
Project: discretize   Author: simpeg   File: test_tree_vtk.py    MIT License 6 votes vote down vote up
def test_VTK_object_conversion(self):
            mesh = self.mesh
            vec = np.arange(mesh.nC)
            models = {'arange': vec}

            vtkObj = mesh.to_vtk(models)

            self.assertEqual(mesh.nC, vtkObj.GetNumberOfCells())
            # TODO: this is actually different?: self.assertEqual(mesh.nN, vtkObj.GetNumberOfPoints())
            # Remember that the tree vtk conversion adds two arrays
            self.assertEqual(len(models.keys())+2, vtkObj.GetCellData().GetNumberOfArrays())
            bnds = vtkObj.GetBounds()
            self.assertEqual(mesh.x0[0], bnds[0])
            self.assertEqual(mesh.x0[1], bnds[2])
            self.assertEqual(mesh.x0[2], bnds[4])

            names = list(models.keys())
            for name in names:
                arr = nps.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
                arr = arr.flatten(order='F')
                self.assertTrue(np.allclose(models[name], arr)) 
Example 8
Project: MeshParty   Author: sdorkenw   File: trimesh_vtk.py    Apache License 2.0 6 votes vote down vote up
def vtk_cellarray_to_shape(vtk_cellarray, ncells):
    """Turn a vtkCellArray into a numpyarray of a fixed shape
    assumes your cell array has uniformed sized cells

    Parameters
    ----------
    vtk_cellarray : vtk.vtkCellArray
        a cell array to convert
    ncells: int
        how many cells are in array

    Returns
    -------
    np.array
        cellarray, a ncells x K array of cells, where K is the
        uniform shape of the cells.  Will error if cells are not uniform

    """
    cellarray = vtk_to_numpy(vtk_cellarray)
    cellarray = cellarray.reshape(ncells, int(len(cellarray)/ncells))
    return cellarray[:, 1:] 
Example 9
Project: Pegamoid   Author: Jellby   File: pegamoid.py    GNU General Public License v3.0 6 votes vote down vote up
def update_range(self):
    minval, maxval = self.xyz.GetInput().GetScalarRange()
    if (maxval*minval < 0):
      maxval = max(abs(minval), abs(maxval))
      minval = 0.0
    else:
      minval, maxval = (min(abs(minval), abs(maxval)), max(abs(minval), abs(maxval)))
    if (maxval == 0):
      maxval = 1.0
    if (minval < 100):
      maxval = min(maxval, 100)
    if (maxval == minval):
      maxval *= 1.1
    if (minval == 0):
      minval = np.nanmin(abs(numpy_support.vtk_to_numpy(self.xyz.GetInput().GetPointData().GetScalars())))
      minval = max(minval, 1e-6*maxval)
    self._minval, self._maxval = (minval, maxval)
    self.isovalue = self.isovalue 
Example 10
Project: BrainSpace   Author: MICA-MNI   File: wrappers.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetTable(self):
        """Get table.

        Wraps the `GetTable` method of `vtkLookupTable` to return an ndarray.

        Returns
        ----------
        table : ndarray, shape = (n, 4)
            Table array used to map scalars to colors.
        """
        table = self.VTKObject.GetTable()
        return vtk_to_numpy(table) 
Example 11
Project: paraviewweb-apache   Author: singularityhub   File: divvyProtocol.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def calc1DHistogram(self, vtkX, xrng, numBins):
    result = np.zeros(numBins)
    px = vtk_to_numpy(vtkX)
    # ix = np.clip(np.floor((px - xrng[0]) * numBins / (xrng[1] - xrng[0])).astype(int), 0, numBins - 1)
    # indices, counts = np.unique(ix, return_counts = True)
    # for i in range(len(indices)):
    #   result[indices[i]] = counts[i]
    result = np.histogram(px, bins=numBins)[0]
    # make it json serializable
    return result.tolist() 
Example 12
Project: pyshemkf   Author: jjokella   File: plotfunctions.py    MIT License 5 votes vote down vote up
def my_vtk_coords(vtk_reader, coord):
    """
    Get array of x-coordinates, y-coordinates, or z-coordinates
    from vtk_reader instance.

    Parameters
    ----------
    vtk_reader: vtk Reader instance
        vtk Reader containing information about a vtk-file.

    coord : string
        'x', 'y', or 'z' depending on the wanted coordinate directin.

    Returns
    ----------
    numpy_coord : NumPy Array
        array of x-coordinates, y-coordinates, or z-coordinates.

    """

    if coord not in ['x', 'y', 'z']:
        raise RuntimeError(
            'coord input needs to be "x", "y", or "z"')

    vtk_output = vtk_reader.GetOutput()

    vtk_coord = (vtk_output.GetXCoordinates() if coord == 'x' else
                 (vtk_output.GetYCoordinates() if coord == 'y' else
                  (vtk_output.GetZCoordinates() if coord == 'z' else [])))

    numpy_coord = vtk_to_numpy(vtk_coord)

    return numpy_coord 
Example 13
Project: telluricpy   Author: grosenkj   File: dataset.py    MIT License 5 votes vote down vote up
def getDataArray(vtkObj,name,arrType='Cell'):
    """Function that returns the cell/point data array. """
    return npsup.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
    if arrType == 'Cell':
        return npsup.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
    elif arrType == 'Point':
        return npsup.vtk_to_numpy(vtkObj.GetPointData().GetArray(name))
    else:
        raise Exception('Not a support arrType') 
Example 14
Project: telluricpy   Author: grosenkj   File: surjection.py    MIT License 5 votes vote down vote up
def getVolumemetricSurjectMatrix(vtkDataSet1,vtkDataSet2):
    """
    Function to calculate and return a sparse matrix of surjection from vtkDataSet1 to vtkDataSet2.

    Based on a volumemetric estimation of intersecting cells.

    """
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    from telluricpy import vtkTools
    sp = simpeg.sp

    # Check the type of DataSet2
    if np.all(np.array([vtkDataSet2.GetCellType(i) for i in range(vtkDataSet2.GetNumberOfCells())]) == 11):
        useBox = True
    # Extract the indieces of the object
    indArr = npsup.vtk_to_numpy(vtkDataSet2.GetCellData().GetArray('id'))
    # Want to end up with nC2xnC1 sparse matrix
    iL = []
    jL = []
    valL = []
    for iV in indArr:
        # Get the base cell and calc volume.
        if useBox:
            jT,valT = _calculateVolumeByBoxClip(vtkDataSet1,vtkDataSet2,iV)
        else:
            jT,valT = _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV)
        # Insert the data
        iL.append(np.ones_like(jT)*iV)
        jL.append(jT)
        valL.append(valT)
    # Return the matrix
    i = np.concatenate(iL)
    j = np.concatenate(jL)
    val = np.concatenate(valL)
    # Make the
    outMat = simpeg.sp.csr_matrix((val,(i,j)),shape=(vtkDataSet2.GetNumberOfCells(),vtkDataSet1.GetNumberOfCells()),dtype=float)
    return outMat 
Example 15
Project: pyvista   Author: pyvista   File: grid.py    MIT License 5 votes vote down vote up
def points(self):
        """Return a pointer to the points as a numpy object."""
        x = vtk_to_numpy(self.GetXCoordinates())
        y = vtk_to_numpy(self.GetYCoordinates())
        z = vtk_to_numpy(self.GetZCoordinates())
        xx, yy, zz = np.meshgrid(x,y,z, indexing='ij')
        return np.c_[xx.ravel(order='F'), yy.ravel(order='F'), zz.ravel(order='F')] 
Example 16
Project: pyvista   Author: pyvista   File: grid.py    MIT License 5 votes vote down vote up
def x(self):
        """Get the coordinates along the X-direction."""
        return vtk_to_numpy(self.GetXCoordinates()) 
Example 17
Project: pyvista   Author: pyvista   File: grid.py    MIT License 5 votes vote down vote up
def y(self):
        """Get the coordinates along the Y-direction."""
        return vtk_to_numpy(self.GetYCoordinates()) 
Example 18
Project: pyvista   Author: pyvista   File: common.py    MIT License 5 votes vote down vote up
def points(self):
        """Return a pointer to the points as a numpy object."""
        pts = self.GetPoints()
        if pts is None:
            return None
        vtk_data = pts.GetData()
        arr = vtk_to_numpy(vtk_data)
        return pyvista_ndarray(arr, vtk_data) 
Example 19
Project: pyvista   Author: pyvista   File: common.py    MIT License 5 votes vote down vote up
def t_coords(self):
        """Return the active texture coordinates on the points."""
        if self.GetPointData().GetTCoords() is not None:
            return vtk_to_numpy(self.GetPointData().GetTCoords())
        return None 
Example 20
Project: vtkplotter   Author: marcomusy   File: shapes.py    MIT License 5 votes vote down vote up
def Star(pos=(0, 0, 0), n=5, r1=0.7, r2=1.0, line=False, c="lb", alpha=1):
    """
    Build a 2D star shape of `n` cusps of inner radius `r1` and outer radius `r2`.

    :param bool line: only build the outer line (no internal surface meshing).

    |extrude| |extrude.py|_
    """
    ps = vtk.vtkRegularPolygonSource()
    ps.SetNumberOfSides(n)
    ps.SetRadius(r2)
    ps.Update()
    pts = vtk_to_numpy(ps.GetOutput().GetPoints().GetData())

    apts=[]
    for i,p in enumerate(pts):
        apts.append(p)
        if i+1<n:
            apts.append((p+pts[i+1])/2*r1/r2)
    apts.append((pts[-1]+pts[0])/2*r1/r2)

    if line:
        apts.append(pts[0])
        actor = Line(apts).c(c).alpha(alpha)
    else:
        apts.append((0,0,0))
        cells=[]
        for i in range(2*n-1):
            cell = [2*n, i, i+1]
            cells.append(cell)
        cells.append([2*n, i+1, 0])
        actor = Actor([apts, cells], c, alpha)

    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    actor.name = "Star"
    return actor 
Example 21
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def getPointArray(self, name=0):
        """Return point array content as a ``numpy.array``.
        This can be identified either as a string or by an integer number."""
        data = None
        if hasattr(self, '_polydata') and self._polydata:
            data = self._polydata
        elif hasattr(self, '_image') and self._image:
            data = self._image
        return vtk_to_numpy(data.GetPointData().GetArray(name)) 
Example 22
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def getCellArray(self, name=0):
        """Return cell array content as a ``numpy.array``."""
        data = None
        if hasattr(self, '_polydata') and self._polydata:
            data = self._polydata
        elif hasattr(self, '_image') and self._image:
            data = self._image
        return vtk_to_numpy(data.GetCellData().GetArray(name)) 
Example 23
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def getPoints(self, transformed=True, copy=False):
        """
        Return the list of vertex coordinates of the input mesh.
        Same as `actor.coordinates()`.

        :param bool transformed: if `False` ignore any previous transformation
            applied to the mesh.
        :param bool copy: if `False` return the reference to the points
            so that they can be modified in place.
        """
        poly = self.polydata(transformed)
        if copy:
            return np.array(vtk_to_numpy(poly.GetPoints().GetData()))
        else:
            return vtk_to_numpy(poly.GetPoints().GetData()) 
Example 24
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def getConnectivity(self):
        """Get cell connettivity ids as a python ``list``. The format is:
            [[id0 ... idn], [id0 ... idm],  etc].

        Same as `faces()`.
        """
        arr1d = self.getPolygons()
        if len(arr1d) == 0:
            arr1d = vtk_to_numpy(self.polydata().GetStrips().GetData())

        #conn = arr1d.reshape(ncells, int(len(arr1d)/len(arr1d)))
        #return conn[:, 1:]
        # instead of:

        i = 0
        conn = []
        n = len(arr1d)
        for idummy in range(n):
            cell = []
            for k in range(arr1d[i]):
                cell.append(arr1d[i+k+1])
            conn.append(cell)
            i += arr1d[i]+1
            if i >= n:
                break
        return conn # cannot always make a numpy array of it! 
Example 25
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def normals(self, cells=False):
        """Retrieve vertex normals as a numpy array.

        :params bool cells: if `True` return cell normals.
        """
        if cells:
            vtknormals = self.polydata().GetCellData().GetNormals()
        else:
            vtknormals = self.polydata().GetPointData().GetNormals()
        return vtk_to_numpy(vtknormals) 
Example 26
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def cellCenters(self):
        """Get the list of cell centers of the mesh surface.

        |delaunay2d| |delaunay2d.py|_
        """
        vcen = vtk.vtkCellCenters()
        vcen.SetInputData(self.polydata(True))
        vcen.Update()
        return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData()) 
Example 27
Project: discretize   Author: simpeg   File: vtkModule.py    MIT License 5 votes vote down vote up
def vtk_to_tensor_mesh(TensorMesh, vtrGrid):
        """Converts a ``vtkRectilinearGrid`` or :class:`pyvista.RectilinearGrid`
        to a :class:`discretize.TensorMesh` object.

        """
        # Sort information
        hx = np.abs(np.diff(nps.vtk_to_numpy(vtrGrid.GetXCoordinates())))
        xR = nps.vtk_to_numpy(vtrGrid.GetXCoordinates())[0]
        hy = np.abs(np.diff(nps.vtk_to_numpy(vtrGrid.GetYCoordinates())))
        yR = nps.vtk_to_numpy(vtrGrid.GetYCoordinates())[0]
        zD = np.diff(nps.vtk_to_numpy(vtrGrid.GetZCoordinates()))
        # Check the direction of hz
        if np.all(zD < 0):
            hz = np.abs(zD[::-1])
            zR = nps.vtk_to_numpy(vtrGrid.GetZCoordinates())[-1]
        else:
            hz = np.abs(zD)
            zR = nps.vtk_to_numpy(vtrGrid.GetZCoordinates())[0]
        x0 = np.array([xR, yR, zR])

        # Make the object
        tensMsh = TensorMesh([hx, hy, hz], x0=x0)

        # Grap the models
        models = {}
        for i in np.arange(vtrGrid.GetCellData().GetNumberOfArrays()):
            modelName = vtrGrid.GetCellData().GetArrayName(i)
            if np.all(zD < 0):
                modFlip = nps.vtk_to_numpy(vtrGrid.GetCellData().GetArray(i))
                tM = tensMsh.r(modFlip, 'CC', 'CC', 'M')
                modArr = tensMsh.r(tM[:, :, ::-1], 'CC', 'CC', 'V')
            else:
                modArr = nps.vtk_to_numpy(vtrGrid.GetCellData().GetArray(i))
            models[modelName] = modArr

        # Return the data
        return tensMsh, models 
Example 28
Project: MeshParty   Author: sdorkenw   File: trimesh_vtk.py    Apache License 2.0 5 votes vote down vote up
def decimate_trimesh(trimesh, reduction=.1):
    """ routine to decimate a mesh through vtk

    Parameters
    ----------
    trimesh : trimesh_io.Mesh
        a mesh to decimate
    reduction: float
        factor to decimate (default .1)

    Returns
    -------
    np.array
        points, the Nx3 mesh of vertices
    np.array
        tris, the Kx3 indices of faces

    """

    poly = trimesh_to_vtk(trimesh.vertices, trimesh.faces)
    dec = vtk.vtkDecimatePro()
    dec.SetTargetReduction(reduction)
    dec.PreserveTopologyOn()
    dec.SetInputData(poly)
    dec.Update()
    out_poly = dec.GetOutput()

    points = vtk_to_numpy(out_poly.GetPoints().GetData())
    ntris = out_poly.GetNumberOfPolys()
    tris = vtk_cellarray_to_shape(out_poly.GetPolys().GetData(), ntris)
    return points, tris 
Example 29
Project: MeshParty   Author: sdorkenw   File: trimesh_vtk.py    Apache License 2.0 5 votes vote down vote up
def poly_to_mesh_components(poly):
    """ converts a vtkPolyData to its numpy components

    Parameters
    ----------
    poly : vtk.vtkPolyData
        a polydate object to convert to numpy components

    Returns
    -------
    np.array
        points, the Nx3 set of vertex locations
    np.array
        tris, the KxD set of faces (assumes a uniform cellarray)
    np.array
        edges, if exists uses the GetLines to make edges

    """
    points = vtk_to_numpy(poly.GetPoints().GetData())
    ntris = poly.GetNumberOfPolys()
    if ntris > 0:
        tris = vtk_cellarray_to_shape(poly.GetPolys().GetData(), ntris)
    else:
        tris = None
    nedges = poly.GetNumberOfLines()
    if nedges > 0:
        edges = vtk_cellarray_to_shape(poly.GetLines().GetData(), nedges)
    else:
        edges = None
    return points, tris, edges 
Example 30
Project: PVGeo   Author: OpenGeoVis   File: octree.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def place_model_on_octree_mesh(mesh, model, data_name='Data'):
        """Places model data onto a mesh. This is for the UBC Grid data reaers
        to associate model data with the mesh grid.

        Args:
            mesh (vtkUnstructuredGrid): The ``vtkUnstructuredGrid`` that is the
                mesh to place the model data upon. Needs to have been read in by ubcOcTree
            model (np.ndarray): A NumPy float array that holds all of the data
                to place inside of the mesh's cells.
            data_name (str): The name of the model data array once placed on the
                ``vtkUnstructuredGrid``.

        Return:
            vtkUnstructuredGrid:
                The input ``vtkUnstructuredGrid`` with model data appended.
        """
        if isinstance(model, dict):
            for key in model.keys():
                mesh = OcTreeReader.place_model_on_octree_mesh(mesh, model[key], data_name=key)
            return mesh
        # Make sure this model file fits the dimensions of the mesh
        numCells = mesh.GetNumberOfCells()
        if (numCells < len(model)):
            raise _helpers.PVGeoError('This model file has more data than the given mesh has cells to hold.')
        elif (numCells > len(model)):
            raise _helpers.PVGeoError('This model file does not have enough data to fill the given mesh\'s cells.')

        # This is absolutely crucial!
        # Do not play with unless you know what you are doing!
        # Also note that this assumes ``discretize`` handles addin this array
        ind_reorder = nps.vtk_to_numpy(
            mesh.GetCellData().GetArray('index_cell_corner'))

        model = model[ind_reorder]

        # Convert data to VTK data structure and append to output
        c = interface.convert_array(model, name=data_name, deep=True)
        # THIS IS CELL DATA! Add the model data to CELL data:
        mesh.GetCellData().AddArray(c)
        return mesh 
Example 31
Project: PVGeo   Author: OpenGeoVis   File: gslib_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_data_fidelity(self):
        """`GSLibReader`: data fidelity"""
        for i, title in enumerate(self.titles):
            arr = nps.vtk_to_numpy(self.TABLE.GetColumn(i))
            self.assertTrue(np.allclose(self.data[:,i], arr, rtol=RTOL))
        return 
Example 32
Project: PVGeo   Author: OpenGeoVis   File: gslib_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_data(self,):
        """`SGeMSGridReader`: data fidelity"""
        for i, title in enumerate(self.titles):
            arr = nps.vtk_to_numpy(self.GRID.GetCellData().GetArray(i))
            self.assertTrue(np.allclose(self.data[:,i], arr, rtol=RTOL))
        return 
Example 33
Project: PVGeo   Author: OpenGeoVis   File: readers_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_data_fidelity(self):
        """`XYZTextReader`: check data fidelity"""
        titles = self.header.split(', ')
        for i in range(self.ncols):
            arr = nps.vtk_to_numpy(self.TABLE.GetColumnByName(titles[i]))
            self.assertTrue(np.allclose(self.data[:,i], arr, rtol=RTOL))
        return 
Example 34
Project: PVGeo   Author: OpenGeoVis   File: readers_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_data(self, table, data):
        arr = nps.vtk_to_numpy(table.GetColumn(0))
        self.assertTrue(np.allclose(data, arr, rtol=RTOL))
        return arr

    ########################################### 
Example 35
Project: PVGeo   Author: OpenGeoVis   File: ubc_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_data(self, grid, data):
        arr = nps.vtk_to_numpy(grid.GetCellData().GetArray(0))
        self.assertTrue(np.allclose(data, arr, rtol=RTOL))
        return 
Example 36
Project: PVGeo   Author: OpenGeoVis   File: ubc_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reshapeArrs(self, mesh):
            for i in range(self.nt):
                ind_reorder = nps.vtk_to_numpy(
                    mesh.GetCellData().GetArray('index_cell_corner'))
                self.arrs[i] = self.arrs[i][ind_reorder] 
Example 37
Project: Pegamoid   Author: Jellby   File: pegamoid.py    GNU General Public License v3.0 5 votes vote down vote up
def set_transparency(self, white_background, black_background):
    wdata = numpy_support.vtk_to_numpy(white_background.GetPointData().GetScalars()).astype(float)
    bdata = numpy_support.vtk_to_numpy(black_background.GetPointData().GetScalars()).astype(float)
    if (bdata.shape[1] == 3):
      output = np.hstack((bdata, np.ones((bdata.shape[0], 1))))
    else:
      output = deepcopy(bdata)
    alpha = 255 - (wdata[:,0:3].max(1) - bdata[:,0:3].max(1))
    mask = alpha > 0
    output[:,0:3] *= 255/np.where(mask[:,np.newaxis], alpha[:,np.newaxis], 255)
    output[:,3] = alpha
    oi = vtk.vtkImageData()
    oi.CopyStructure(black_background)
    oi.GetPointData().SetScalars(numpy_support.numpy_to_vtk(output, 1, vtk.VTK_UNSIGNED_CHAR))
    return oi 
Example 38
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def set_all_point_colors(self, color):
        """
        Sets the color of every point.

        Args:
            color (tuple, list, np.ndarray, np.generic): a single rgb color in the form of [[int, int, int]]
        """
        np_color_data = numpy_support.vtk_to_numpy(self.point_colors)
        np_color_data = np.tile(color, (np_color_data.shape[0], 1))
        vtk_data = numpy_support.numpy_to_vtk(num_array=np_color_data, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.point_colors.DeepCopy(vtk_data) 
Example 39
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def set_point_colors(self, colors, point_indices=None):
        if point_indices is None:
            if isinstance(colors, (list, tuple, np.ndarray, np.generic)):
                vtk_data = numpy_support.numpy_to_vtk(num_array=colors, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
                self.point_colors.DeepCopy(vtk_data)
        elif isinstance(point_indices, (list, tuple, np.ndarray, np.generic)):
            np_color_data = numpy_support.vtk_to_numpy(self.point_colors)
            np_color_data[point_indices] = colors
            vtk_data = numpy_support.numpy_to_vtk(num_array=np_color_data, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
            self.point_colors.DeepCopy(vtk_data)

        # self.points_poly.GetPointData().GetScalars().Modified()
        self.points_poly.Modified() 
Example 40
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def setup_lerp_all_point_colors(self, color, fade_time):
        """
        Sets all points to the same color, but uses lerping to slowly change the colors.

        Args:
            color ():
            fade_time ():
        """
        np_color_data = numpy_support.vtk_to_numpy(self.point_colors)
        self.next_colors = np.tile(color, (np_color_data.shape[0], 1))
        self.prev_colors = numpy_support.vtk_to_numpy(self.point_colors)

        self.lerp_fade_time = fade_time
        self.remaining_lerp_fade_time = fade_time 
Example 41
Project: ogs5py   Author: GeoStat-Framework   File: vtkhelper.py    MIT License 5 votes vote down vote up
def _get_data(data):
    """Extract data as numpy arrays from a vtkObject."""
    arr_dict = {}
    no_of_arr = data.GetNumberOfArrays()
    for i in range(no_of_arr):
        arr = data.GetArray(i)
        if arr:
            arr_dict[arr.GetName()] = vtk2np(arr)
    return arr_dict 
Example 42
Project: ogs5py   Author: GeoStat-Framework   File: vtkhelper.py    MIT License 5 votes vote down vote up
def _get_cells(obj):
    """Extract cells and cell_data from a vtkDataSet and sort it by types."""
    cells, cell_data = {}, {}
    data = _get_data(obj.GetCellData())
    arr = vtk2np(obj.GetCells().GetData())
    loc = vtk2np(obj.GetCellLocationsArray())
    types = vtk2np(obj.GetCellTypesArray())

    for typ in VTK_TYP:
        if not isinstance(typ, int):
            continue
        cell_name = VTK_TYP[typ]
        n_no = NODE_NO[cell_name]
        cell_loc_i = np.where(types == typ)[0]
        loc_i = loc[cell_loc_i]
        # if there are no cells of the actual type continue
        if len(loc_i) == 0:
            # if not loc_i:
            continue
        arr_i = np.empty((len(loc_i), n_no), dtype=int)
        for i in range(n_no):
            arr_i[:, i] = arr[loc_i + i + 1]
        cells[cell_name] = arr_i
        cell_data_i = {}
        for data_i in data:
            cell_data_i[data_i] = data[data_i][cell_loc_i]
        if cell_data_i != {}:
            cell_data[cell_name] = cell_data_i

    return cells, cell_data


###############################################################################
# vtk-objects readers
############################################################################### 
Example 43
Project: ogs5py   Author: GeoStat-Framework   File: vtkhelper.py    MIT License 5 votes vote down vote up
def _unst_grid_read(obj):
    """Reader for vtk unstructured grid objects."""
    output = {}
    output["field_data"] = _get_data(obj.GetFieldData())
    output["points"] = vtk2np(obj.GetPoints().GetData())
    output["point_data"] = _get_data(obj.GetPointData())
    output["cells"], output["cell_data"] = _get_cells(obj)
    return output 
Example 44
Project: ogs5py   Author: GeoStat-Framework   File: vtkhelper.py    MIT License 5 votes vote down vote up
def _poly_data_read(obj):
    """Reader for vtk polygonal data objects."""
    output = {}
    output["points"] = vtk2np(obj.GetPoints().GetData())
    output["verts"] = _deflat_data(vtk2np(obj.GetVerts().GetData()))
    output["lines"] = _deflat_data(vtk2np(obj.GetLines().GetData()))
    output["polygons"] = _deflat_data(vtk2np(obj.GetPolys().GetData()))
    output["strips"] = _deflat_data(vtk2np(obj.GetStrips().GetData()))
    output["point_data"] = _get_data(obj.GetPointData())
    output["cell_data"] = _get_data(obj.GetCellData())
    output["field_data"] = _get_data(obj.GetFieldData())
    return output 
Example 45
Project: ogs5py   Author: GeoStat-Framework   File: vtkhelper.py    MIT License 5 votes vote down vote up
def _rect_grid_read(obj):
    """Reader for vtk rectangular grid objects."""
    output = {}
    output["dimensions"] = np.array(obj.GetDimensions())
    output["x"] = vtk2np(obj.GetXCoordinates())
    output["y"] = vtk2np(obj.GetYCoordinates())
    output["z"] = vtk2np(obj.GetZCoordinates())
    output["field_data"] = _get_data(obj.GetFieldData())
    output["point_data"] = _get_data(obj.GetPointData())
    output["cell_data"] = _get_data(obj.GetCellData())
    # reshape cell and point data according to the give dimensions
    dim = output["dimensions"]
    for arr in output["cell_data"]:
        output["cell_data"][arr] = np.squeeze(
            np.reshape(
                output["cell_data"][arr], np.maximum(dim - 1, 1), order="F"
            )
        )
    for arr in output["point_data"]:
        output["point_data"][arr] = np.reshape(
            output["point_data"][arr], dim, order="F"
        )
    return output


###############################################################################
# reader dictonaries
############################################################################### 
Example 46
Project: pyshemkf   Author: jjokella   File: plotfunctions.py    MIT License 4 votes vote down vote up
def my_vtk_to_numpy(vtk_reader):
    """
    Read array from vtk_reader and output as numpy array.

    Parameters
    ----------
    vtk_reader: vtk Reader instance
        vtk Reader containing information about a vtk-file.

    Returns
    ----------
    numpy_array: Numpy array
        Numpy array containing the variable array corresponding to
        the vtk_reader.
    """

    vtk_output = vtk_reader.GetOutput()

    # Grid properties
    grid_dimens = vtk_output.GetDimensions()  # Grid Dimensions
    grid_bounds = vtk_output.GetBounds()  # Grid Bounds

    # Reshape array to grid geometry
    if grid_bounds[0] == 0.0:  # CELLS
        vtk_array = vtk_output.GetCellData().GetArray(0)
        # vtk_to_numpy and reshape
        numpy_array = vtk_to_numpy(vtk_array)
        numpy_array = numpy_array.reshape(
            grid_dimens[0] - 1,
            1 if grid_dimens[1] == 1 else grid_dimens[1] - 1)
    else:  # POINTS
        vtk_array = vtk_output.GetPointData().GetArray(0)
        # vtk_to_numpy and reshape
        numpy_array = vtk_to_numpy(vtk_array)
        if vtk_reader.GetScalarsName() == 'v':
            numpy_array = numpy_array.reshape(grid_dimens[0], grid_dimens[1],
                                              3)
            numpy_array[:, :, 2] = np.sqrt(numpy_array[:, :, 0]**2 +
                                           numpy_array[:, :, 1]**2)
        else:
            if grid_dimens[0] > 1 and grid_dimens[1] > 1:
                if grid_dimens[2] > 1:  # 3D
                    numpy_array = numpy_array.reshape(
                        grid_dimens[2], grid_dimens[1], grid_dimens[0])
                    numpy_array = np.transpose(numpy_array, [2, 1, 0])
                else:  # 2D horizontal
                    numpy_array = numpy_array.reshape(grid_dimens[1],
                                                      grid_dimens[0])
                    numpy_array = np.transpose(numpy_array, [1, 0])
            elif grid_dimens[0] > 1 and grid_dimens[2] > 1:  # 2D vertical
                numpy_array = numpy_array.reshape(grid_dimens[2],
                                                  grid_dimens[0])
            else:
                raise RuntimeError('Shape of array wrong: ' +
                                   str(grid_dimens))

    return numpy_array 
Example 47
Project: pyshemkf   Author: jjokella   File: plotfunctions.py    MIT License 4 votes vote down vote up
def my_vtk_make_quiver(vtk_reader, ax, scale=None):
    """
    Read a field of arrows from vtk-file and insert it in axis.

    Parameters
    ----------
    vtk_reader: vtk Reader instance
        vtk Reader containing information about a vtk-file.

    ax : Axes
        The axes to draw to.

    Returns
    -------
    ax : array
        Axes containing plot.

    Notes
    -------
    Only regular grids supported!
    """
    # Quiver
    vtk_output = vtk_reader.GetOutput()

    # 1:Get Vector quantitiy
    v_vtk = vtk_output.GetPointData().GetArray(0)

    # Get grid properties
    (step_x, step_y, npts_x, npts_y, low_m_x, high_m_x, low_m_y,
     high_m_y) = my_vtk_grid_props(vtk_reader)[:8]

    # Generate regular grid, incl last cell
    x = np.arange(low_m_x, high_m_x + 1, step_x)
    y = np.arange(low_m_y, high_m_y + 1, step_y)
    X, Y = np.meshgrid(x, y)

    # vtk file to NumPy array
    v = vtk_to_numpy(v_vtk)

    # Vector components reshaped to grid
    vx = v[:, 0].reshape(npts_x, npts_y)
    vy = v[:, 1].reshape(npts_x, npts_y)

    # Arrows to axis
    ax.quiver(X, Y, vx, vy, scale=scale)

    return ax 
Example 48
Project: telluricpy   Author: grosenkj   File: polydata.py    MIT License 4 votes vote down vote up
def polyDataList2polyhedVTU(polyDataList):
    """
    Function that makes polyhedron ugrid from a list of watertight polygons stored in PolyData.



    """

    # What is needed is:
    #   allPoints -vtkPoints-
    #   pointsIds -vtkIdList- for each cell
    #   hedronFaces -vtkCellArray- with all the faces.
    # Insert cells with
    # ugrid.InsertNextCell(vtk.vtkPolyHedron,
    #           nrVerts,hedronVertPtsIds,nrFaces,faceCellArray.GetPointer())
    def makeIdList(polyData,ptsShift):
        """
        Make a vtkIdList for a polyhedron from a polydata
        """
        ptsIds = vtk.vtkIdList()
        numCellFaces = polyData.GetNumberOfCells()
        ptsIds.InsertNextId(numCellFaces) # Number of cell faces
        # Add the faces
        for cF in range(numCellFaces):
            numPtsInFace = polyData.GetCell(cF).GetNumberOfPoints()
            ptsIds.InsertNextId(numPtsInFace)
            for cPF in range(numPtsInFace):
                ptsIds.InsertNextId(polyData.GetCell(cF).GetPointId(cPF)+ptsShift)
        return ptsIds
    # Start
    unstructGrid = vtk.vtkUnstructuredGrid()
    nrPts = 0
    hedronList = []
    for vtkPolyData in polyDataList:
        pts = npsup.vtk_to_numpy(vtkPolyData.GetPoints().GetData())
        nrVert = pts.shape[0]
        cellIdList = makeIdList(vtkPolyData,nrPts)
        unstructGrid.InsertNextCell(vtk.VTK_POLYHEDRON,cellIdList)

        try:
            npPts = np.concatenate((npPts,pts))
        except NameError as e:
            npPts = pts.copy()
        nrPts = nrPts + pts.shape[0]

    # Make the grid
    # Set the points
    vtkPts = vtk.vtkPoints()
    vtkPts.SetData(npsup.numpy_to_vtk(npPts,deep=1))
    unstructGrid.SetPoints(vtkPts)

    # Return
    return unstructGrid 
Example 49
Project: telluricpy   Author: grosenkj   File: surjection.py    MIT License 4 votes vote down vote up
def _calculateVolumeByBoxClip(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a BoxClip filter to calculate the intersection, assumes the cell to
    be a voxel (=11) and aligned to the grid. This should work well for rectilinear
    and unstructured grids with all cells as voxels

    """
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    from telluricpy import vtkTools

    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    # Extrct the cell by the bounds first, significant speed up...
    if vtkDataSet1.IsA('vtkRectilinearGrid'):
        # Use a faster implementation of the rectgrid extraction
        extCells = _extractRectGridByBounds(vtkDataSet1,baseC)
    else:
        extCells = vtkTools.extraction.extractDataSetByBounds(vtkDataSet1,baseC)
    # Define the box clip and clip the first mesh with the cell
    cb = baseC.GetBounds()
    boxClip = vtk.vtkBoxClipDataSet()
    boxClip.SetInputConnection(extCells.GetOutputPort())
    boxClip.SetBoxClip(cb[0],cb[1],cb[2],cb[3],cb[4],cb[5])
    boxClip.Update()
    # Get the intersect grid
    intCells = boxClip.GetOutput()
    idList = npsup.vtk_to_numpy(intCells.GetCellData().GetArray('id'))
    uniIDs = np.unique(idList)
    # Extract cells from the first mesh that intersect the base cell
    # Calculate the volumes of the clipped cells and insert to the matrix
    volList =[]
    for i in range(intCells.GetNumberOfCells()):
        c = intCells.GetCell(i)
        cPts = c.GetPoints()
        volList.append(c.ComputeVolume(cPts.GetPoint(0),cPts.GetPoint(1),cPts.GetPoint(2),cPts.GetPoint(3)))
    volArr =  np.array(volList)
    # Calculate the volumes
    volCal = np.array([np.sum(volArr[idList == curId]) for curId in uniIDs])

    return uniIDs, volCal/np.sum(volCal) 
Example 50
Project: telluricpy   Author: grosenkj   File: surjection.py    MIT License 4 votes vote down vote up
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a boolean polydata filter to calculate the intersection,
    a general implementation but slow.

    """
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    from telluricpy import vtkTools

    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    baseVol = vtkTools.polydata.calculateVolume(baseC)
    # print iV, baseVol
    # Extract cells from the first mesh that intersect the base cell
    extractCells = vtkTools.extraction.extractDataSetWithPolygon(vtkDataSet1,baseC,extInside=True,extBoundaryCells=True,extractBounds=True)
    extInd = npsup.vtk_to_numpy(extractCells.GetCellData().GetArray('id'))
    # print extInd
    # Assert if there are no cells cutv
    assert extractCells.GetNumberOfCells() > 0, 'No cells in the clip, cell id {:d}'.format(iV)
    # Calculate the volumes of the clipped cells and insert to the matrix
    volL = []
    for nrCC,iR in enumerate(extInd):
        tempCell = vtkTools.dataset.thresholdCellId2vtp(extractCells,iR)
        # Find the intersection of the 2 cells
        boolFilt = vtk.vtkBooleanOperationPolyDataFilter()
        boolFilt.SetInputData(0,tempCell)
        boolFilt.SetInputData(1,baseC)
        boolFilt.SetOperationToIntersection()
        # If they intersect, calculate the volumes
        if boolFilt.GetOutput().GetNumberOfPoints() > 0:
            cleanInt = vtkTools.polydata.cleanPolyData(boolFilt.GetOutputPort())
            del3dFilt = vtk.vtkDelaunay3D()
            del3dFilt.SetInputData(cleanInt)
            del3dFilt.Update()
            # Get the output
            intC = vtkTools.extraction.vtu2vtp(del3dFilt.GetOutput())
            intVol = vtkTools.polydata.calculateVolume(tempCell)
            # Calculate the volume
            volVal = intVol/baseVol
            # print iR, intVol, volVal
            # Insert the value
            if volVal > 0.0:
                volL.append(volVal)
    return extInd,np.array(volL) 
Example 51
Project: pyvista   Author: pyvista   File: helpers.py    MIT License 4 votes vote down vote up
def convert_array(arr, name=None, deep=0, array_type=None):
    """Convert a NumPy array to a vtkDataArray or vice versa.

    Parameters
    -----------
    arr : ndarray or vtkDataArry
        A numpy array or vtkDataArry to convert
    name : str
        The name of the data array for VTK
    deep : bool
        if input is numpy array then deep copy values

    Return
    ------
    vtkDataArray, ndarray, or DataFrame:
        the converted array (if input is a NumPy ndaray then returns
        ``vtkDataArray`` or is input is ``vtkDataArray`` then returns NumPy
        ``ndarray``). If pdf==True and the input is ``vtkDataArry``,
        return a pandas DataFrame.

    """
    if arr is None:
        return
    if isinstance(arr, np.ndarray):
        if arr.dtype is np.dtype('O'):
            arr = arr.astype('|S')
        arr = np.ascontiguousarray(arr)
        try:
            # This will handle numerical data
            arr = np.ascontiguousarray(arr)
            vtk_data = nps.numpy_to_vtk(num_array=arr, deep=deep, array_type=array_type)
        except ValueError:
            # This handles strings
            typ = get_vtk_type(arr.dtype)
            if typ == 13:
                vtk_data = convert_string_array(arr)
        if isinstance(name, str):
            vtk_data.SetName(name)
        return vtk_data
    # Otherwise input must be a vtkDataArray
    if not isinstance(arr, (vtk.vtkDataArray, vtk.vtkBitArray, vtk.vtkStringArray)):
        raise TypeError('Invalid input array type ({}).'.format(type(arr)))
    # Handle booleans
    if isinstance(arr, vtk.vtkBitArray):
        arr = vtk_bit_array_to_char(arr)
    # Handle string arrays
    if isinstance(arr, vtk.vtkStringArray):
        return convert_string_array(arr)
    # Convert from vtkDataArry to NumPy
    return nps.vtk_to_numpy(arr) 
Example 52
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 4 votes vote down vote up
def scalars(self, name_or_idx=None, datatype="point"):
        """
        Retrieve point or cell scalars using array name or index number,
        and set it as the active one.

        If no input is given return the list of names of existing arrays.

        :param str datatype: search given name in point-data or cell-data

        .. hint:: |mesh_coloring.py|_
        """
        poly = self.polydata(False)

        # no argument: return list of available arrays
        if name_or_idx is None:
            ncd = poly.GetCellData().GetNumberOfArrays()
            npd = poly.GetPointData().GetNumberOfArrays()
            arrs = []
            for i in range(npd):
                #print(i, "PointData", poly.GetPointData().GetArrayName(i))
                arrs.append(["PointData", poly.GetPointData().GetArrayName(i)])
            for i in range(ncd):
                #print(i, "CellData", poly.GetCellData().GetArrayName(i))
                arrs.append(["CellData", poly.GetCellData().GetArrayName(i)])
            return arrs

        else:  # return a specific array (and set it as active one)

            pdata = poly.GetPointData()
            arr = None

            if 'point' in datatype.lower():
                if isinstance(name_or_idx, int):
                    name = pdata.GetArrayName(name_or_idx)
                else:
                    name = name_or_idx
                if name:
                    arr = pdata.GetArray(name)
                    data = pdata
                    self._mapper.SetScalarModeToUsePointData()


            if not arr or 'cell' in datatype.lower():
                cdata = poly.GetCellData()
                if isinstance(name_or_idx, int):
                    name = cdata.GetArrayName(name_or_idx)
                else:
                    name = name_or_idx
                if name:
                    arr = cdata.GetArray(name)
                    data = cdata
                    self._mapper.SetScalarModeToUseCellData()

            if arr:
                data.SetActiveScalars(name)
                self._mapper.ScalarVisibilityOn()
                if settings.autoResetScalarRange:
                    self._mapper.SetScalarRange(arr.GetRange())
                return vtk_to_numpy(arr)

            return None 
Example 53
Project: vtkplotter   Author: marcomusy   File: analysis.py    MIT License 4 votes vote down vote up
def densifyCloud(actor, targetDistance, closestN=6, radius=0, maxIter=None, maxN=None):
    """Adds new points to an input point cloud.
    The new points are created in such a way that all points in any local neighborhood are
    within a target distance of one another.

    The algorithm works as follows. For each input point, the distance to all points
    in its neighborhood is computed. If any of its neighbors is further than the target distance,
    the edge connecting the point and its neighbor is bisected and a new point is inserted at the
    bisection point. A single pass is completed once all the input points are visited.
    Then the process repeats to the limit of the maximum number of iterations.

    .. note:: Points will be created in an iterative fashion until all points in their
        local neighborhood are the target distance apart or less.
        Note that the process may terminate early due to the limit on the
        maximum number of iterations. By default the target distance is set to 0.5.
        Note that the TargetDistance should be less than the Radius or nothing will change on output.

    .. warning:: This class can generate a lot of points very quickly.
        The maximum number of iterations is by default set to =1.0 for this reason.
        Increase the number of iterations very carefully.
        Also, `maxN` can be set to limit the explosion of points.
        It is also recommended that a N closest neighborhood is used.
    """
    src = vtk.vtkProgrammableSource()
    def readPoints():
        output = src.GetPolyDataOutput()
        points = vtk.vtkPoints()
        pts = actor.coordinates()
        for p in pts:
            x, y, z = p
            points.InsertNextPoint(x, y, z)
        output.SetPoints(points)
    src.SetExecuteMethod(readPoints)

    dens = vtk.vtkDensifyPointCloudFilter()
    dens.SetInputConnection(src.GetOutputPort())
    dens.InterpolateAttributeDataOn()
    dens.SetTargetDistance(targetDistance)
    if maxIter: dens.SetMaximumNumberOfIterations(maxIter)
    if maxN: dens.SetMaximumNumberOfPoints(maxN)

    if radius:
        dens.SetNeighborhoodTypeToRadius()
        dens.SetRadius(radius)
    elif closestN:
        dens.SetNeighborhoodTypeToNClosest()
        dens.SetNumberOfClosestPoints(closestN)
    else:
        colors.printc("Error in densifyCloud: set either radius or closestN", c=1)
        raise RuntimeError()
    dens.Update()
    pts = vtk_to_numpy(dens.GetOutput().GetPoints().GetData())
    return shapes.Points(pts, c=None).pointSize(3) 
Example 54
Project: Pegamoid   Author: Jellby   File: pegamoid.py    GNU General Public License v3.0 4 votes vote down vote up
def write_cube(self, *args):
    if (self.surface is None):
      return
    result = QFileDialog.getSaveFileName(self, 'Save cube')
    if (not result):
      return
    try:
      filename, _ = result
    except ValueError:
      filename = result
    try:
      data = self.xyz.GetInput()
      ngrid = data.GetDimensions()
      grid = data.GetSpacing()
      orig = list(data.GetOrigin())
      transform = self.xyz.GetTransform().GetMatrix()
      try:
        note = ' {0}'.format(self.notes[self.orbital-1]['note'])
      except:
        note = ''
      with open(filename, 'w') as f:
        f.write('File generated by {0} from {1}\n'.format(__name__, self.filename))
        f.write('{0} {1}\n'.format(self.orbitalButton.currentText(), note))
        orig.append(1.0)
        transform.MultiplyPoint(orig, orig)
        f.write('{0:5d} {1:11.6f} {2:11.6f} {3:11.6f}\n'.format(len(self.orbitals.centers), *orig))
        for i in range(3):
          axis = [0, 0, 0, 0]
          axis[i] = grid[i]
          axis = transform.MultiplyPoint(axis)
          f.write('{0:5d} {1:11.6f} {2:11.6f} {3:11.6f}\n'.format(ngrid[i], *axis))
        for c in self.orbitals.centers:
          f.write('{0:5d} {0:11.6f} {1:11.6f} {2:11.6f} {3:11.6f}\n'.format(c['Z'], *c['xyz']))
        vol = numpy_support.vtk_to_numpy(data.GetPointData().GetScalars()).reshape(ngrid[::-1]).T
        for x in vol:
          for y in x:
            f.write('\n'.join(wrap_list(y, 6, '{:13.5E}')))
            f.write('\n')
    except Exception as e:
      error = 'Error writing cube file {0}:\n{1}'.format(filename, e)
      traceback.print_exc()
      self.show_error(error)

  # Copy an InpOrb file, changing header and index section 
Example 55
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 4 votes vote down vote up
def add_lines(self, lines, line_colors):
        """
        Adds multiple lines between any sets of points.

        Args:
            lines (list, tuple, np.ndarray, np.generic):
                An array in the format of [2, point_a, point_b, 2, point_c, point_d, ...]. The two is needed for VTK's
                  lines.
            line_colors (list, tuple, np.ndarray, np.generic):
                An array in the format of [[r1, g1, b1], [r2, g2, b2], ...], with the same length as the number of
                  lines.
        Returns:
            list: An array containing the memory locations of each of the newly inserted lines.

        """
        assert (isinstance(lines, (list, tuple, np.ndarray, np.generic)))
        assert (isinstance(line_colors, (list, tuple, np.ndarray, np.generic)))

        np_line_data = numpy_support.vtk_to_numpy(self.lines.GetData())
        np_line_color_data = numpy_support.vtk_to_numpy(self.line_colors)

        #todo: add lines in unused locations if possible
        mem_locations = range(int(len(np_line_data) / 3), int((len(np_line_data) + len(lines)) / 3))

        np_line_data = np.append(np_line_data, lines)

        if len(np_line_color_data) > 0:
            np_line_color_data = np.append(np_line_color_data, line_colors, axis=0)
        else:
            np_line_color_data = line_colors

        vtk_line_data = numpy_support.numpy_to_vtkIdTypeArray(np_line_data, deep=True)
        self.lines.SetCells(int(len(np_line_data) / 3), vtk_line_data)

        vtk_line_color_data = numpy_support.numpy_to_vtk(num_array=np_line_color_data,
                                                         deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.line_colors.DeepCopy(vtk_line_color_data)

        self.lines_poly.Modified()

        self.line_id_array.add_ids(mem_locations)

        return mem_locations 
Example 56
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 4 votes vote down vote up
def del_lines(self, line_indices):
        #todo: change idarray to use tuples of (start,end) locations and set this to delete those partitions
        """
        Delete specific lines.

        Args:
            line_indices (tuple, list, np.ndarray, np.generic):
                An array of integers or a single integer representing line memory locations(s) to delete.
        """
        np_data = numpy_support.vtk_to_numpy(self.lines.GetData())

        np_color_data = numpy_support.vtk_to_numpy(self.line_colors)

        if isinstance(line_indices, (tuple, list, np.ndarray, np.generic)):
            last_loc = -1
            loc = 0
            np_new_data = []
            np_new_color_data = []
            for i in range(len(line_indices)):
                loc = self.line_id_array.pop_id(line_indices[i])
                if loc==None:
                    #todo: put warning here
                    continue

                if len(np_new_data) > 0:
                    np_new_data = np.append(np_new_data, np_data[(last_loc + 1) * 3:loc * 3], axis=0)
                else:
                    np_new_data = np_data[(last_loc + 1) * 3:loc * 3]

                if len(np_new_color_data) > 0:
                    np_new_color_data = np.append(np_new_color_data, np_color_data[(last_loc + 1):loc], axis=0)
                else:
                    np_new_color_data = np_color_data[(last_loc + 1):loc]

                last_loc = loc

            last_loc = loc
            loc = len(np_data) / 3

            np_data = np.append(np_new_data, np_data[(last_loc + 1) * 3:loc * 3], axis=0)

            np_data = np_data.astype(np.int64)

            np_color_data = np.append(np_new_color_data, np_color_data[(last_loc + 1):loc], axis=0)
        else:
            raise TypeError("Deletion list should be tuple, list, np.ndarray, or np.generic")

        vtk_data = numpy_support.numpy_to_vtkIdTypeArray(np_data, deep=True)
        self.lines.SetCells(int(len(np_data) / 3), vtk_data)

        vtk_data = numpy_support.numpy_to_vtk(num_array=np_color_data, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.line_colors.DeepCopy(vtk_data)

        self.lines_poly.Modified()