Exemplo n.º 1
0
    def sample(dataset, target, tolerance=None, pass_cell_arrays=True,
                    pass_point_arrays=True):
        """Resample scalar data from a passed mesh onto this mesh using
        :class:`vtk.vtkResampleWithDataSet`.

        Parameters
        ----------
        dataset: vtki.Common
            The source vtk data object as the mesh to sample values on to

        target: vtki.Common
            The vtk data object to sample from - point and cell arrays from
            this object are sampled onto the nodes of the ``dataset`` mesh

        tolerance: flaot, optional
            tolerance used to compute whether a point in the source is in a
            cell of the input.  If not given, tolerance automatically generated.

        pass_cell_arrays: bool, optional
            Preserve source mesh's original cell data arrays

        pass_point_arrays: bool, optional
            Preserve source mesh's original point data arrays
        """
        alg = vtk.vtkResampleWithDataSet() # Construct the ResampleWithDataSet object
        alg.SetInputData(dataset)  # Set the Input data (actually the source i.e. where to sample from)
        alg.SetSourceData(target) # Set the Source data (actually the target, i.e. where to sample to)
        alg.SetPassCellArrays(pass_cell_arrays)
        alg.SetPassPointArrays(pass_point_arrays)
        if tolerance is not None:
            alg.SetComputeTolerance(False)
            alg.SetTolerance(tolerance)
        alg.Update() # Perfrom the resampling
        return _get_output(alg)
Exemplo n.º 2
0
def resampleArrays(source, target, tol=None):
    """Resample point and cell data of a dataset on points from another dataset.

        :param float tol: set the tolerance used to compute whether
            a point in the target is in a cell of the source.
            Points without resampled values, and their cells, are be marked as blank.
        """
    rs = vtk.vtkResampleWithDataSet()
    rs.SetSourceData(target.polydata())
    rs.SetInputData(source.polydata())
    rs.SetPassPointArrays(True)
    rs.SetPassCellArrays(True)
    if tol:
        rs.SetComputeTolerance(False)
        rs.SetTolerance(tol)
    rs.Update()
    return rs.GetOutput()
Exemplo n.º 3
0
 def Initialize(self, variableList=None):
     '''
     Read the exodus data and resample the dataset onto the specified grid
     '''
     self.eReader.UpdateInformation()
     if variableList is None:
         self.eReader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, True)
     else:
         for var in variableList:
             self.eReader.SetNodeSetArrayStatus(var, True)
     self.tSteps = self.eReader.GetOutputInformation(0).\
         Get(vtk.vtkStreamingDemandDrivenPipeline.TIME_STEPS())
     self.resample = vtk.vtkResampleWithDataSet()
     self.resample.SetInputData(self.grid)
     self.resample.SetSourceConnection(self.eReader.GetOutputPort())
     self.resample.Update()
     self.data = self.resample.GetOutput()
     self.data_np = dsa.WrapDataObject(self.data)
    def RequestData(self, request, inInfoVec, outInfoVec):
        import sys, os
        import vtk
        for i in dir(vtk):
            if i[:5] == 'vtkRe':
                print(i)
        from vtk.numpy_interface import dataset_adapter as dsa
        import ctypes as C
        import numpy as np

        if 'HOME' in os.environ:
            ccode_so = os.environ[
                'HOME'] + '/ParaviewPythonModules/libSampleDataset.so'
        elif 'HOMEPATH' in os.environ:
            ccode_so = os.environ[
                'HOMEPATH'] + '/ParaviewPythonModules/libSampleDataset.so'
        else:
            ccode_so = 'SampleDataset.so'

        if not os.path.isfile(ccode_so):
            print('can\'t find so:', ccode_so)
            return

        ccode = C.CDLL(ccode_so)
        if not ccode:
            print('failed to load ', ccode.so)

        ccode.SampleCartesian.argtypes = [
            C.c_int,  # desired number of samples
            np.ctypeslib.ndpointer(C.c_float,
                                   flags="C_CONTIGUOUS"),  # origin  (3)
            np.ctypeslib.ndpointer(C.c_float,
                                   flags="C_CONTIGUOUS"),  # spacing (3)
            np.ctypeslib.ndpointer(C.c_int,
                                   flags="C_CONTIGUOUS"),  # counts  (3)
            C.c_float,  # minimum spacing
            C.c_float,  # maximum spacing
            C.c_int,  # pdep data?
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS"),  # data
            C.c_int,  # number of retained samples
            np.ctypeslib.ndpointer(C.c_float,
                                   flags="C_CONTIGUOUS"),  # retained samples
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS")
        ]  # new data interpolated on retained samples

        ccode.SampleTetrahedra.argtypes = [
            C.c_int,  # desired number of samples
            C.c_int,  # number of cells
            C.c_float,  # minimum spacing
            C.c_float,  # maximum spacing
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS"),  # points
            np.ctypeslib.ndpointer(C.c_int, flags="C_CONTIGUOUS"),  # cells
            C.c_int,  # pdep data?
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS"),  # data
            C.c_int,  # number of retained samples
            np.ctypeslib.ndpointer(C.c_float,
                                   flags="C_CONTIGUOUS"),  # retained samples
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS")
        ]  # new data interpolated on retained samples

        ccode.GetNumberOfSamples.restype = C.c_int
        ccode.GetSamples.argtypes = [
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS")
        ]

        # self.inputArray = 'PDF'
        print("Sample USING ", self.inputArray)

        if self.retained != None:
            r = vtk.vtkResampleWithDataSet()
            r.SetSourceData(vtk.vtkDataSet.GetData(inInfoVec[0], 0))
            r.SetInputData(self.retained)
            r.Update()
            rr = dsa.WrapDataObject(r.GetOutput())
            del r
            rs = rr.Points.astype('f4')
            rd = rr.PointData[self.inputArray].astype('f4')
            nRetained = rr.GetNumberOfPoints()
            del rr
        else:
            nRetained = 0
            rs = np.zeros(1).astype('f4')
            rd = np.zeros(1).astype('f4')

        inpt = vtk.vtkImageData.GetData(inInfoVec[0], 0)
        if inpt != None:
            inpt = dsa.WrapDataObject(inpt)

            o = inpt.VTKObject.GetOrigin()
            e = inpt.VTKObject.GetExtent()
            s = inpt.VTKObject.GetSpacing()

            k = np.array([e[i * 2 + 1] - e[i * 2] + 1
                          for i in range(3)]).astype('i4')
            o = np.array([o[i] + e[2 * i] * s[i]
                          for i in range(3)]).astype('f4')
            s = np.array(s).astype('f4')

            data = np.ascontiguousarray(
                inpt.PointData[self.inputArray]).astype('f4')

            ccode.SampleCartesian(self.samples, o, s, k, self.minSpacing,
                                  self.maxSpacing, 1, data, nRetained, rs, rd)

        else:
            inpt = vtk.vtkUnstructuredGrid.GetData(inInfoVec[0], 0)

            if inpt == None:
                print("Can only handle ImageData or UnstructuredGrid")
                return 1

            inpt = dsa.WrapDataObject(inpt)

            if np.min(inpt.CellTypes) < vtk.VTK_TETRA or np.max(
                    inpt.CellTypes) > vtk.VTK_TETRA:
                print(
                    "can handle only cartesian grids or unstructured grids containing only tetrahedra"
                )
                return 1

            nCells = inpt.GetNumberOfCells()
            points = np.ascontiguousarray(inpt.Points).astype('f4')
            tets = np.ascontiguousarray(inpt.Cells).astype('i4')
            data = np.ascontiguousarray(
                inpt.PointData[self.inputArray]).astype('f4')

            ccode.SampleTetrahedra(self.samples, nCells, self.minSpacing,
                                   self.maxSpacing, points, tets, 1, data,
                                   nRetained, rs, rd)

        nSamples = ccode.GetNumberOfSamples()
        samples = np.zeros(nSamples * 3).astype('f4')
        ccode.GetSamples(samples)
        samples = samples.reshape(-1, 3)

        print("Xreturn ", nSamples, " samples")

        so = dsa.WrapDataObject(vtk.vtkUnstructuredGrid())
        co = dsa.numpy_support.numpy_to_vtkIdTypeArray(
            np.arange(nSamples).astype('i8') * 2)
        ca = vtk.vtkCellArray()
        ca.SetCells(
            nSamples,
            dsa.numpy_support.numpy_to_vtkIdTypeArray(
                np.column_stack(([1] * nSamples, range(nSamples))).reshape(
                    (2 * nSamples, )).astype('i8')))
        ct = dsa.numpyTovtkDataArray(
            np.array([vtk.VTK_VERTEX] * nSamples).astype('u1'))
        so.VTKObject.SetCells(ct, co, ca)
        so.Points = dsa.numpy_support.numpy_to_vtk(samples, deep=1)

        print("hello")
        from vtk import vtkResampleWithDataSet
        r = vtkResampleWithDataSet()
        r.SetSourceData(inpt.VTKObject)
        r.SetInputData(so.VTKObject)
        r.Update()

        outpt = vtk.vtkUnstructuredGrid.GetData(outInfoVec, 0)
        outpt.ShallowCopy(r.GetOutput())

        if self.continuity:
            self.retained = r.GetOutput()

        del so
        del r

        return 1
Exemplo n.º 5
0
def main():
    points_fn, probe_fn = get_program_parameters()

    colors = vtk.vtkNamedColors()

    points_reader = vtk.vtkDelimitedTextReader()
    points_reader.SetFileName(points_fn)
    points_reader.DetectNumericColumnsOn()
    points_reader.SetFieldDelimiterCharacters('\t')
    points_reader.SetHaveHeaders(True)

    table_points = vtk.vtkTableToPolyData()
    table_points.SetInputConnection(points_reader.GetOutputPort())
    table_points.SetXColumn('x')
    table_points.SetYColumn('y')
    table_points.SetZColumn('z')
    table_points.Update()

    points = table_points.GetOutput()
    points.GetPointData().SetActiveScalars('val')
    range = points.GetPointData().GetScalars().GetRange()

    # Read a probe surface
    stl_reader = vtk.vtkSTLReader()
    stl_reader.SetFileName(probe_fn)
    stl_reader.Update()

    surface = stl_reader.GetOutput()
    bounds = np.array(surface.GetBounds())

    dims = np.array([101, 101, 101])
    box = vtk.vtkImageData()
    box.SetDimensions(dims)
    box.SetSpacing((bounds[1::2] - bounds[:-1:2]) / (dims - 1))
    box.SetOrigin(bounds[::2])

    # Gaussian kernel
    gaussian_kernel = vtk.vtkGaussianKernel()
    gaussian_kernel.SetSharpness(2)
    gaussian_kernel.SetRadius(12)

    interpolator = vtk.vtkPointInterpolator()
    interpolator.SetInputData(box)
    interpolator.SetSourceData(points)
    interpolator.SetKernel(gaussian_kernel)

    resample = vtk.vtkResampleWithDataSet()
    resample.SetInputData(surface)
    resample.SetSourceConnection(interpolator.GetOutputPort())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(resample.GetOutputPort())
    mapper.SetScalarRange(range)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    point_mapper = vtk.vtkPointGaussianMapper()
    point_mapper.SetInputData(points)
    point_mapper.SetScalarRange(range)
    point_mapper.SetScaleFactor(0.6)
    point_mapper.EmissiveOff()
    point_mapper.SetSplatShaderCode(
        "//VTK::Color::Impl\n"
        "float dist = dot(offsetVCVSOutput.xy,offsetVCVSOutput.xy);\n"
        "if (dist > 1.0) {\n"
        "  discard;\n"
        "} else {\n"
        "  float scale = (1.0 - dist);\n"
        "  ambientColor *= scale;\n"
        "  diffuseColor *= scale;\n"
        "}\n")

    point_actor = vtk.vtkActor()
    point_actor.SetMapper(point_mapper)

    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renderer.AddActor(actor)
    renderer.AddActor(point_actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    renWin.SetSize(640, 480)
    renWin.SetWindowName('PointInterpolator')

    renderer.ResetCamera()
    renderer.GetActiveCamera().Elevation(-45)

    iren.Initialize()

    renWin.Render()
    iren.Start()