def RequestData(self, request, inInfo, outInfo):
        info = inInfo[0].GetInformationObject(0)
        inp = dsa.WrapDataObject(vtk.vtkDataSet.GetData(info))

        if self.Cache is not None:
            self.DoParticle(self.Cache, inp)
            # print('data request')
        else:
            # First time step. Initialize.

            # This is where we will store the coordinates of all points
            # at all times
            self.OutputPoints = np.zeros(
                (len(self.TimeValues) * self.NumPts, 3))

            # First time step uses the seed locations as the particle points
            pts = vtk.vtkPoints()
            pts.DeepCopy(self.Source.GetOutput().GetPoints())
            self.Points = dsa.vtkDataArrayToVTKArray(pts.GetData())
            self.OutputPoints[0:self.NumPts, :] = self.Points

            # This will be a point array showing the time value of each
            # output point. This is necessary to differentiate output
            # points since we store all timesteps in the output.
            self.TimeValuesArray = np.empty(len(self.TimeValues) * self.NumPts)
            self.TimeValuesArray[0:self.NumPts] = self.TimeValues[0]

        if self.UpdateTimeIndex < len(self.TimeValues) - 1:
            # If we are not done, ask the pipeline to re-execute us.
            self.UpdateTimeIndex += 1
            request.Set(
                vtk.vtkStreamingDemandDrivenPipeline.CONTINUE_EXECUTING(), 1)
            c = inp.NewInstance()
            c.ShallowCopy(inp.VTKObject)
            c = dsa.WrapDataObject(c)
            self.Cache = c
        else:
            # Stop execution
            request.Remove(
                vtk.vtkStreamingDemandDrivenPipeline.CONTINUE_EXECUTING())
            # Reset for next potential execution.
            self.UpdateTimeIndex = 0
            # Create output
            outputPts = dsa.numpyTovtkDataArray(self.OutputPoints)
            pts = vtk.vtkPoints()
            pts.SetData(outputPts)
            output = dsa.WrapDataObject(
                vtk.vtkUnstructuredGrid.GetData(outInfo))
            output.SetPoints(pts)
            tvs = dsa.numpyTovtkDataArray(self.TimeValuesArray)
            tvs.SetName("Time Values")
            output.GetPointData().SetScalars(tvs)
            # Clean up
            self.Cache = None
            self.OutputPoints = None
            self.Points = None
        return 1
Esempio n. 2
0
    def RequestData(self, request, inInfo, outInfo):

        output = dsa.WrapDataObject(vtk.vtkRectilinearGrid.GetData(outInfo))
        info = outInfo.GetInformationObject(0)
        exts = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_EXTENT())
        whole = info.Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT())

        # Dimensions for each processor
        nx = exts[1] - exts[0] + 1
        ny = exts[3] - exts[2] + 1
        nz = exts[5] - exts[4] + 1

        # Read Data file
        f = Dataset(self.__DFileName, 'r')

        data = np.zeros([nz, ny, nx, self.nvar])
        for i, field in enumerate(self._fields):
            data[:, :, :, i] = f.variables[field][exts[4]:exts[5] + 1,
                                                  exts[2]:exts[3] + 1,
                                                  exts[0]:exts[1] + 1]
        f.close()
        del f

        # Read Grid file
        f = Dataset(self.__GFileName, 'r')
        x = f.variables[self._grid_var_names[0]][exts[0]:exts[1] + 1]
        y = f.variables[self._grid_var_names[1]][exts[2]:exts[3] + 1]
        z = f.variables[self._grid_var_names[2]][exts[4]:exts[5] + 1]
        f.close()
        del f

        # output.SetDimensions([self.nx,self.ny,self.nz])
        output.SetExtent(exts)
        output.SetXCoordinates(dsa.numpyTovtkDataArray(x, "X"))
        output.SetYCoordinates(dsa.numpyTovtkDataArray(y, "Y"))
        output.SetZCoordinates(dsa.numpyTovtkDataArray(z, "Z"))

        for i, field in enumerate(self._fields):
            output.PointData.append(data[:, :, :, i].ravel(), field)

        if self._grids:
            Z, Y, X = np.meshgrid(z, y, x, indexing='ij')

        if 'x' in self._grids:
            output.PointData.append(X.ravel(), 'x')
            del X
        if 'y' in self._grids:
            output.PointData.append(Y.ravel(), 'y')
            del Y
        if 'z' in self._grids:
            output.PointData.append(Z.ravel(), 'z')
            del Z

        output.PointData.SetActiveScalars(self._fields[0])

        del data, x, y, z
        return 1
Esempio n. 3
0
    def Execute(self):

        polyData = vtk.vtkPolyData()
        wpPolyData = dsa.WrapDataObject(polyData)

        points = self.ArrayDict['Points']
        vtkPoints = dsa.numpyTovtkDataArray(points, 'Points')
        wpPolyData.Points = vtkPoints

        self.PrintLog('converting point data')
        for pointDataKey in self.ArrayDict['PointData'].keys():
            pointDataItem = self.ArrayDict['PointData'][pointDataKey]
            wpPolyData.PointData.append(pointDataItem, name=pointDataKey)

        self.PrintLog('converting cell data')
        for cellKey in self.ArrayDict['CellData'].keys():
            if cellKey == 'CellPointIds':
                cellDataArray = vtk.vtkCellArray()
                for cellId in self.ArrayDict['CellData']['CellPointIds']:
                    numberOfCellPoints = cellId.size
                    cellDataArray.InsertNextCell(numberOfCellPoints)
                    for cellPoint in cellId:
                        cellDataArray.InsertCellPoint(cellPoint)
                wpPolyData.VTKObject.SetLines(cellDataArray)
            else:
                cellDataItem = self.ArrayDict['CellData'][cellKey]
                wpPolyData.CellData.append(cellDataItem, name=cellKey)

        self.Centerlines = wpPolyData.VTKObject
    def RequestData(self, request, inInfo, outInfo):
        info = outInfo.GetInformationObject(0)
        # The time step requested
        t = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP())
        timeStep = self.__TimeSteps[1] - self.__TimeSteps[0]
        t_index = (np.round(t / timeStep).astype(int) + self.__TimeOffset) % (len(self.__TimeSteps)-1)
        print(f"UPDATE_TIME_STEP: {t} / index {t_index}")
        data = self.create_bin_sphere(self.__Size, self.__Center, self.__Radius)

        output = vtk.vtkImageData.GetData(outInfo)
        output.SetDimensions(data.shape)
        output.SetSpacing(self.__Vox)

        # Make a VTK array from the numpy array (using pointers)
        scalarsSphere = dsa.numpyTovtkDataArray(data.ravel(order='F'))
        scalarsSphere.SetName("scalars_sphere")
        output.GetPointData().SetScalars(scalarsSphere)

        """
        a = np.zeros((3, self.__Size[0], self.__Size[1], self.__Size[2]), order='F')
        a[0,:] = self.__ArrayVelocity[:,:,:,0,t_index]
        a[1,:] = self.__ArrayVelocity[:,:,:,1,t_index]
        a[2,:] = self.__ArrayVelocity[:,:,:,2,t_index]


        # Make a VTK array from the numpy array (using pointers)
        v = dsa.numpyTovtkDataArray(a.ravel(order='A').reshape(
            self.__Size[0] * self.__Size[1] * self.__Size[2], 3))
        v.SetName("vectors")
        output.GetPointData().SetVectors(v)
        """
        return 1
Esempio n. 5
0
    def Execute(self):

        self.PrintLog('Converting Numpy Array to vtkImageData')
        self.Image = vtk.vtkImageData()
        self.Image.SetDimensions(self.ArrayDict['Dimensions'])
        self.Image.SetOrigin(self.ArrayDict['Origin'])
        self.Image.SetSpacing(self.ArrayDict['Spacing'])
        self.Image.SetExtent((0, self.ArrayDict['Dimensions'][0] - 1,
                                0, self.ArrayDict['Dimensions'][1] - 1,
                                0, self.ArrayDict['Dimensions'][2] - 1,))


        self.PrintLog('converting point data')
        for pointKey in self.ArrayDict['PointData'].keys():
            if np.issubdtype(self.ArrayDict['PointData'][pointKey].dtype, np.floating):
                pointDataArrayType = vtk.VTK_FLOAT
            else:
                for checkDt in [int, np.uint8, np.uint16, np.uint32, np.uint64]:
                    if np.issubdtype(self.ArrayDict['PointData'][pointKey].dtype, checkDt):
                        pointDataArrayType = vtk.VTK_INT
                        break
                    else:
                        continue

            flatArray = self.ArrayDict['PointData'][pointKey].ravel(order='F')

            pointDataArray = dsa.numpyTovtkDataArray(flatArray, name=pointKey, array_type=pointDataArrayType)

            self.Image.GetPointData().SetActiveScalars(pointKey)
            self.Image.GetPointData().SetScalars(pointDataArray)
Esempio n. 6
0
    def Execute(self):

        polyData = vtk.vtkPolyData()
        wpPolyData = dsa.WrapDataObject(polyData)

        points = self.ArrayDict['Points']
        vtkPoints = dsa.numpyTovtkDataArray(points, 'Points')
        wpPolyData.Points = vtkPoints

        self.PrintLog('converting point data')
        for pointDataKey in self.ArrayDict['PointData'].keys():
            pointDataItem = self.ArrayDict['PointData'][pointDataKey]
            wpPolyData.PointData.append(pointDataItem, name=pointDataKey)

        self.PrintLog('converting cell data')
        for cellKey in self.ArrayDict['CellData'].keys():
            if cellKey == 'CellPointIds':
                cellDataArray = vtk.vtkCellArray()
                for cellId in self.ArrayDict['CellData']['CellPointIds']:
                    numberOfCellPoints = cellId.size
                    cellDataArray.InsertNextCell(numberOfCellPoints)
                    for cellPoint in cellId:
                        cellDataArray.InsertCellPoint(cellPoint)
                wpPolyData.VTKObject.SetLines(cellDataArray)
            else:
                cellDataItem = self.ArrayDict['CellData'][cellKey]
                wpPolyData.CellData.append(cellDataItem, name=cellKey)

        self.Centerlines = wpPolyData.VTKObject
Esempio n. 7
0
    def RequestData(self, request, inInfo, outInfo):
        logging.info('')
        start = timer()

        # input polydata
        # have to make a copy otherwise polys will not show up in the render
        # even though GetNumberOfCells() says they should be there
        tmp = vtk.vtkPolyData.GetData(inInfo[0])
        inp = vtk.vtkPolyData()
        inp.ShallowCopy(tmp)

        # change color of all cells
        if self._color:
            ncells = inp.GetNumberOfCells()
            c = self._colorcycle.next()
            vtkarray = dsa.numpyTovtkDataArray(np.tile(c, (ncells, 1)))
            inp.GetCellData().SetScalars(vtkarray)

        # add to world mesh
        self._worldmesh.AddInputData(inp)
        self._worldmesh.Update()

        logging.info('Number of cells: in = {} total = {}'.format(
            inp.GetNumberOfCells(),
            self._worldmesh.GetOutput().GetNumberOfCells()))

        # output world mesh
        out = vtk.vtkPolyData.GetData(outInfo)
        out.ShallowCopy(self._worldmesh.GetOutput())

        end = timer()
        logging.info('Execution time {:.4f} seconds'.format(end - start))

        return 1
 def RequestData(self, request, inInfo, outInfo):
     output = dsa.WrapDataObject(vtk.vtkRectilinearGrid.GetData(outInfo))
     info = outInfo.GetInformationObject(0)
     exts = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_EXTENT())
     dims = [exts[1]-exts[0]+1, exts[3]-exts[2]+1, exts[5]-exts[4]+1]
     output.SetExtent(exts)
     xaxis = np.linspace(0., 1., dims[0])
     yaxis = np.linspace(0., 1., dims[1])
     zaxis = np.linspace(0., 1., dims[2])
     xaxis = xaxis**2
     yaxis = np.sqrt(yaxis)
     zaxis = zaxis*np.sqrt(zaxis)
     output.SetXCoordinates(dsa.numpyTovtkDataArray( xaxis , "X"))
     output.SetYCoordinates(dsa.numpyTovtkDataArray( yaxis , "Y"))
     output.SetZCoordinates(dsa.numpyTovtkDataArray( zaxis , "Z"))
     return 1
Esempio n. 9
0
 def RequestData(self, request, inInfo, outInfo):
     output = dsa.WrapDataObject(vtk.vtkRectilinearGrid.GetData(outInfo))
     info = outInfo.GetInformationObject(0)
     exts = info.Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT())
     dims = [exts[1]-exts[0]+1, exts[3]-exts[2]+1, exts[5]-exts[4]+1]
     output.SetExtent(exts)
     xaxis = np.linspace(0., 1., dims[0])
     yaxis = np.linspace(0., 1., dims[1])
     zaxis = np.linspace(0., 1., dims[2])
     xaxis = xaxis**2
     yaxis = np.sqrt(yaxis)
     zaxis = zaxis*np.sqrt(zaxis)
     output.SetXCoordinates(dsa.numpyTovtkDataArray( xaxis , "X"))
     output.SetYCoordinates(dsa.numpyTovtkDataArray( yaxis , "Y"))
     output.SetZCoordinates(dsa.numpyTovtkDataArray( zaxis , "Z"))
     return 1
Esempio n. 10
0
    def RequestData(self, request, inInfo, outInfo):
        logging.info('')
        start = timer()

        # input polydata
        # have to make a copy otherwise polys will not show up in the render
        # even though GetNumberOfCells() says they should be there
        tmp = vtk.vtkPolyData.GetData(inInfo[0])
        inp = vtk.vtkPolyData()
        inp.ShallowCopy(tmp)

        # change color of all cells
        if self._color:
            ncells = inp.GetNumberOfCells()
            c = self._colorcycle.next()
            vtkarray = dsa.numpyTovtkDataArray(np.tile(c, (ncells, 1)))
            inp.GetCellData().SetScalars(vtkarray)

        # add to world mesh
        self._worldmesh.AddInputData(inp)
        self._worldmesh.Update()

        logging.info('Number of cells: in = {} total = {}'
                     .format(inp.GetNumberOfCells(),
                             self._worldmesh.GetOutput().GetNumberOfCells()))

        # output world mesh
        out = vtk.vtkPolyData.GetData(outInfo)
        out.ShallowCopy(self._worldmesh.GetOutput())

        end = timer()
        logging.info('Execution time {:.4f} seconds'.format(end - start))

        return 1
Esempio n. 11
0
def unwrap_vtk_array(a, array_type=None):
    if is_numpy_string(a.dtype) or is_vtk_string(array_type):
        return _numpy_to_string(a, array_type=array_type)
    if any([np.issubdtype(a.dtype, d) for d in [np.integer, np.floating]]):
        return dsa.numpyTovtkDataArray(a, array_type=array_type)
    if np.issubdtype(a.dtype, np.object_):
        return _numpy_to_variant(a)
    raise ValueError('Unsupported array type: {0}'.format(type(a)))
Esempio n. 12
0
def numpy2PolyData(data):
    vtkArr = dsa.numpyTovtkDataArray(data)
    pts = v.vtkPoints()
    pts.SetData(vtkArr)
    pd = v.vtkPolyData()
    pd.SetPoints(pts)
    vgf = v.vtkVertexGlyphFilter()
    vgf.SetInputData(pd)
    vgf.Update()
    return vgf.GetOutput()
Esempio n. 13
0
def writeToVTK(x, fileName):
    """ Write flattened vector to VTK file. """
    X = x.reshape((-1, 3))
    pos = X[:72, :]
    posArr = dsa.numpyTovtkDataArray(pos, name='Points')
    rot = X[72:, :]
    ori = np.zeros_like(rot)
    get_orientations(rot, ori)
    normals = dsa.numpyTovtkDataArray(ori, name='PointNormals')
    pts = v.vtkPoints()
    pts.SetData(posArr)
    pd = v.vtkPolyData()
    pd.SetPoints(pts)
    pd.GetPointData().SetNormals(normals)
    polyData = dsa.WrapDataObject(pd)
    polyData.SetPolys(triangulate(polyData))
    w = v.vtkPolyDataWriter()
    w.SetFileName(fileName)
    w.SetInputData(pd)
    w.Write()
Esempio n. 14
0
    def ProbeVelocity(self, data):
        # Update the particle locations we sample at
        pts = dsa.numpyTovtkDataArray(self.Points)
        self.ProbePoints.GetPoints().SetData(pts)

        self.Probe.SetSourceData(data)

        # Sample
        self.Probe.Update()
        p = dsa.WrapDataObject(self.Probe.GetOutput())
        # All we care about is the vector values/
        return p.PointData['vectors']
Esempio n. 15
0
 def stuff_vtu(self, outpt):
   outpt.SetPoints(dsa.VTKArray(np.array(self.points).astype('f4')))
   outpt.PointData.append(dsa.VTKArray(np.array(self.V).astype('f4')), 'V')
   outpt.PointData.append(dsa.VTKArray(np.array(self.PV).astype('f4')), 'PV')
   outpt.PointData.append(dsa.VTKArray(np.array(self.I).astype('f4')), 'I')
   ct = dsa.numpyTovtkDataArray(np.array([vtk.VTK_VERTEX]*outpt.GetNumberOfPoints()).astype('u1'))
   co = dsa.numpy_support.numpy_to_vtkIdTypeArray(np.array(range(0, 2*outpt.GetNumberOfPoints(), 2)))
   ca = vtk.vtkCellArray()
   for i in range(outpt.GetNumberOfPoints()):
     ca.InsertNextCell(1, [i])
   outpt.VTKObject.SetCells(ct, co, ca)
   for v in self.vars:
     outpt.PointData.append(dsa.VTKArray(np.array(v[2]).astype('f4')), v[0])
Esempio n. 16
0
def SampleTetrahedra(vtu, pdf, n):
  points = np.ascontiguousarray(vtu.Points).astype('f4')
  pdf    = np.ascontiguousarray(vtu.CellData[pdf]).astype('f4')
  tets   = np.ascontiguousarray(vtu.Cells).astype('i4')
  ccode.SampleTetrahedra(n, vtu.GetNumberOfPoints(), vtu.GetNumberOfCells(), points, pdf, tets)
  n = ccode.GetNumberOfSamples()
  s = np.ctypeslib.as_array(C.cast(ccode.GetSamples(), C.POINTER(C.c_float)),shape=(n, 3))
  samples = dsa.WrapDataObject(vtk.vtkUnstructuredGrid())
  co = dsa.numpy_support.numpy_to_vtkIdTypeArray(np.arange(n).astype('i8')*2)
  ca = vtk.vtkCellArray()
  ca.SetCells(n, dsa.numpy_support.numpy_to_vtkIdTypeArray(np.column_stack(([1]*n, range(n))).reshape((2*n,))))
  ct = dsa.numpyTovtkDataArray(np.array([vtk.VTK_VERTEX]*n).astype('u1'))
  samples.VTKObject.SetCells(ct, co, ca)
  samples.Points = dsa.numpy_support.numpy_to_vtk(s)
  return samples
Esempio n. 17
0
 def t_coords(self, t_coords: np.ndarray):
     """Set the active texture coordinates using an np.ndarray."""
     if not isinstance(t_coords, np.ndarray):
         raise TypeError('Texture coordinates must be a numpy array')
     if t_coords.ndim != 2:
         raise ValueError('Texture coordinates must be a 2-dimensional array')
     valid_length = self.valid_array_len
     if t_coords.shape[0] != valid_length:
         raise ValueError(f'Number of texture coordinates ({t_coords.shape[0]}) must match number of points ({valid_length})')
     if t_coords.shape[1] != 2:
         raise ValueError('Texture coordinates must only have 2 components,'
                          f' not ({t_coords.shape[1]})')
     vtkarr = numpyTovtkDataArray(t_coords, name='Texture Coordinates')
     self.SetTCoords(vtkarr)
     self.Modified()
Esempio n. 18
0
def SampleVTI(vti, pdf, n):
  e = vti.VTKObject.GetExtent()
  o = vti.VTKObject.GetOrigin()
  s = vti.VTKObject.GetSpacing()
  dimensions = np.array([(e[2*i+1] - e[2*i])+1 for i in range(3)]).astype('i4')
  origin     = np.array([o[i] - e[2*i]*s[i] for i in range(3)]).astype('f4')
  spacing    = np.array(s).astype('f4')
  pdf        = np.ascontiguousarray(vti.PointData[pdf]).astype('f4')
  ccode.SampleVTI(n, dimensions, origin, spacing, pdf);
  n = ccode.GetNumberOfSamples()
  s = np.ctypeslib.as_array(C.cast(ccode.GetSamples(), C.POINTER(C.c_float)),shape=(n, 3))
  samples = dsa.WrapDataObject(vtk.vtkUnstructuredGrid())
  co = dsa.numpy_support.numpy_to_vtkIdTypeArray(np.arange(n).astype('i8')*2)
  ca = vtk.vtkCellArray()
  ca.SetCells(n, dsa.numpy_support.numpy_to_vtkIdTypeArray(np.column_stack(([1]*n, range(n))).reshape((2*n,)).astype('i8')))
  ct = dsa.numpyTovtkDataArray(np.array([vtk.VTK_VERTEX]*n).astype('u1'))
  samples.VTKObject.SetCells(ct, co, ca)
  samples.Points = dsa.numpy_support.numpy_to_vtk(s)
  return samples
Esempio n. 19
0
def triangulate(pd):
    """
    Generates a triangle mesh for a spherical point cloud. It is assumed that
    'pd' is an object of dsa.PolyData type.
    """
    # Project on a sphere
    sphereXyz = alg.norm(pd.Points) * np.linalg.norm(pd.Points, axis=1).mean()
    sphereXyz = np.around(sphereXyz, decimals=2)
    sphereArr = dsa.numpyTovtkDataArray(sphereXyz, name='SpherePts')
    pts = v.vtkPoints()
    pts.SetData(sphereArr)
    sphere = v.vtkPolyData()
    sphere.SetPoints(pts)

    # Store the original point ids
    idf = v.vtkIdFilter()
    idf.SetIdsArrayName('PointIds')
    idf.PointIdsOn()
    idf.SetInputData(sphere)

    # Delaunay3D to make a convex hull
    d3d = v.vtkDelaunay3D()
    d3d.SetInputConnection(idf.GetOutputPort())

    # Extract the surface
    surf = v.vtkDataSetSurfaceFilter()
    surf.SetInputConnection(d3d.GetOutputPort())
    surf.Update()

    # Now make a new cell array mapping to the old ids
    polyCells = v.vtkCellArray()
    sphereCells = surf.GetOutput().GetPolys()
    sphereCells.InitTraversal()
    origIds = surf.GetOutput().GetPointData().GetArray('PointIds')
    ptIds = v.vtkIdList()
    while (sphereCells.GetNextCell(ptIds)):
        polyCells.InsertNextCell(3)
        polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(0))))
        polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(1))))
        polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(2))))

    return polyCells
 def RequestData(self, request, inInfo, outInfo):
     output = dsa.WrapDataObject(vtk.vtkStructuredGrid.GetData(outInfo))
     info = outInfo.GetInformationObject(0)
     exts = info.Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT())
     dims = [exts[1]-exts[0]+1, exts[3]-exts[2]+1, exts[5]-exts[4]+1]
     output.SetExtent(exts)
     Raxis = np.linspace(1., 2., dims[0])
     Thetaaxis = np.linspace(0.,np.pi*0.5, dims[1])
     xc, yc = np.meshgrid(Raxis, Thetaaxis, indexing="xy")
     X = xc * np.cos(yc)
     Y = xc * np.sin(yc)
     print X.size, X.shape
     Z=np.zeros(X.size).reshape(X.shape)
     coordinates = algs.make_vector(X.ravel(),Y.ravel(),Z.ravel())
     pts = vtk.vtkPoints()
     pts.SetData(dsa.numpyTovtkDataArray(coordinates , "Points"))
     output.SetPoints(pts)
     output.PointData.append(xc.ravel(), "radius")
     output.PointData.append(yc.ravel(), "angle")
     return 1
Esempio n. 21
0
    def RequestData(self, request, inInfo, outInfo):
        info = outInfo.GetInformationObject(0)
        # We produce only the extent that we are asked (UPDATE_EXTENT)
        ue = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_EXTENT())
        ue = np.array(ue)

        output = vtk.vtkImageData.GetData(outInfo)

        # Parameters of the grid to produce
        dims = ue[1::2] - ue[0::2] + 1
        origin = 0
        spacing = 0.1

        # The time step requested
        t = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP())

        # The velocity vs y
        y = origin + spacing * np.arange(ue[2], ue[3] + 1)
        u = np.exp(-y / np.sqrt(2)) * np.sin(t - y / np.sqrt(2))

        # Set the velocity for all points of the grid which
        # has of dimensions 3, dims[0], dims[1]. The first number
        # is because of 3 components in the vector. Note the
        # memory layout VTK uses is a bit unusual. It's Fortran
        # ordered but the velocity component increases fastest.
        a = np.zeros((3, dims[0], dims[1]), order='F')
        a[0, :] = u

        output.SetExtent(*ue)
        output.SetSpacing(0.5, 0.1, 0.1)

        # Make a VTK array from the numpy array (using pointers)
        v = dsa.numpyTovtkDataArray(
            a.ravel(order='A').reshape(dims[0] * dims[1], 3))
        v.SetName("vectors")
        output.GetPointData().SetVectors(v)

        return 1
Esempio n. 22
0
 def RequestData(self, request, inInfo, outInfo):
     output = dsa.WrapDataObject(vtk.vtkMultiBlockDataSet.GetData(outInfo))
     for i in range(self.__NumberOfBlocks):
         block = vtk.vtkImageData()
         imin = 0
         imax = self.__CompositeBlockDims[0] - 1
         jmin = (i % 2) * (self.__CompositeBlockDims[1] // 2)
         jmax = ((i % 2) + 1) * (self.__CompositeBlockDims[1] // 2)
         kmin = (i // 2) * (self.__CompositeBlockDims[2] // 2)
         kmax = ((i // 2) + 1) * (self.__CompositeBlockDims[2] // 2)
         print("block extents ", i, " = ", imin, imax, jmin, jmax, kmin,
               kmax)
         block.SetExtent(imin, imax, jmin, jmax, kmin, kmax)
         nbOfCells = (imax - imin) * (jmax - jmin) * (kmax - kmin)
         # the value of 'i' will be the block color
         blockcolor = np.ones(nbOfCells).astype('ushort') * i
         vtkBlockColors = dsa.numpyTovtkDataArray(blockcolor)
         vtkBlockColors.SetName("vtkCompositeIndex")
         block.GetCellData().SetScalars(vtkBlockColors)
         block.SetOrigin(0, (i % 2) - 1.0 * (i % 2), 0)
         block.SetSpacing(1, 1, 1)
         output.SetBlock(i, block)
     return 1
Esempio n. 23
0
    def RequestData(self, request, inInfo, outInfo):
        logging.info('{}'.format(self._name))
        start = timer()

        # get the depth values
        vfa = vtk.vtkFloatArray()
        ib = self._imageBounds
        self._renWin.GetZbufferData(ib[0], ib[1], ib[2], ib[3], vfa)

        # add noise
        if self._noise is not 0.0:
            nvfa = numpy_support.vtk_to_numpy(vfa)
            nvfa += self._noise * nvfa * np.random.normal(0.0, 1.0, nvfa.shape)
            vfa = dsa.numpyTovtkDataArray(nvfa)

        # pack the depth values into the output vtkImageData
        info = outInfo.GetInformationObject(0)
        ue = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_EXTENT())
        out = vtk.vtkImageData.GetData(outInfo)
        out.GetPointData().SetScalars(vfa)
        out.SetExtent(ue)

        # append meta data to the vtkImageData containing intrinsic parameters
        out.sizex = self._renWin.GetSize()[0]
        out.sizey = self._renWin.GetSize()[1]
        out.viewport = self._ren.GetViewport()
        vtktmat = self._ren.GetActiveCamera().GetCompositeProjectionTransformMatrix(
            self._ren.GetTiledAspectRatio(),
            0.0, 1.0)
        vtktmat.Invert()
        out.tmat = self._vtkmatrix_to_numpy(vtktmat)

        end = timer()
        logging.info('Execution time {:.4f} seconds'.format(end - start))

        return 1
Esempio n. 24
0
    def RequestData(self, request, inInfo, outInfo):
        logging.info('{}'.format(self._name))
        start = timer()

        # get the depth values
        vfa = vtk.vtkFloatArray()
        ib = self._imageBounds
        self._renWin.GetZbufferData(ib[0], ib[1], ib[2], ib[3], vfa)

        # add noise
        if self._noise is not 0.0:
            nvfa = numpy_support.vtk_to_numpy(vfa)
            nvfa += self._noise * np.random.normal(0.0, 1.0, nvfa.shape)
            vfa = dsa.numpyTovtkDataArray(nvfa)

        # pack the depth values into the output vtkImageData
        info = outInfo.GetInformationObject(0)
        ue = info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_EXTENT())
        out = vtk.vtkImageData.GetData(outInfo)
        out.GetPointData().SetScalars(vfa)
        out.SetExtent(ue)

        # append meta data to the vtkImageData containing intrinsic parameters
        out.sizex = self._renWin.GetSize()[0]
        out.sizey = self._renWin.GetSize()[1]
        out.viewport = self._ren.GetViewport()
        vtktmat = self._ren.GetActiveCamera(
        ).GetCompositeProjectionTransformMatrix(
            self._ren.GetTiledAspectRatio(), 0.0, 1.0)
        vtktmat.Invert()
        out.tmat = self._vtkmatrix_to_numpy(vtktmat)

        end = timer()
        logging.info('Execution time {:.4f} seconds'.format(end - start))

        return 1
Esempio n. 25
0
usg = v.vtkUnstructuredGrid()
usg.Allocate(198, 198)
ids = v.vtkIdList()
origIds = d2d.GetOutput().GetPointData().GetArray('OrigIds')
while (meshTemp.GetNextCell(ids)):
    n = ids.GetNumberOfIds()
    uIds = v.vtkIdList()
    for i in range(n):
        uIds.InsertNextId(int(origIds.GetTuple1(ids.GetId(i))))
    usg.InsertNextCell(5, uIds)

# Insert Projection Lines
uPts = v.vtkPoints()
uPtsArr = np.vstack([proj3, rPts])
uPtsArr[N - 1] = c
uPts.SetData(dsa.numpyTovtkDataArray(uPtsArr))
for i in range(N - 1):
    uIds = v.vtkIdList()
    uIds.InsertNextId(N - 1)
    uIds.InsertNextId(i)
    uIds.InsertNextId(i + N)
    usg.InsertNextCell(4, uIds)

usg.SetPoints(uPts)
wr = v.vtkUnstructuredGridWriter()
wr.SetFileName('Scene.vtk')
wr.SetInputData(usg)
wr.Write()

# Now write the final spherical mesh to polydate file
Esempio n. 26
0
    def Execute(self):
        if self.Surface == None:
            self.PrintError('Error: No Input Surface.')

        if self.InsideValue > 255:
            self.PrintError('Error: Cannot assign InsideValue of image to value greater than 255')

        # Step 1: Convert the input surface into an image mask of unsigned char type and spacing = PolyDataToImageDataSpacing
        #         Where voxels lying inside the surface are set to 255 and voxels outside the image are set to value 0. 

        # since we are creating a new image container from nothing, calculate the origin, extent, and dimensions for the
        # vtkImageDataObject from the surface parameters.
        bounds = self.Surface.GetBounds()
        dim = []   # list of size: 3, type: int
        for i in range(3):
            dim.append(int(math.ceil((bounds[i * 2 + 1] - bounds[i * 2]) / self.PolyDataToImageDataSpacing[i])))

        origin = [bounds[0] + self.PolyDataToImageDataSpacing[0] / 2,
                  bounds[2] + self.PolyDataToImageDataSpacing[1] / 2,
                  bounds[4] + self.PolyDataToImageDataSpacing[2] / 2]

        extent = [0, dim[0] - 1,
                  0, dim[1] - 1,
                  0, dim[2] - 1]

        whiteImage = vtk.vtkImageData()
        whiteImage.SetSpacing(self.PolyDataToImageDataSpacing[0],
                              self.PolyDataToImageDataSpacing[1], 
                              self.PolyDataToImageDataSpacing[2])
        whiteImage.SetDimensions(dim[0], dim[1], dim[2])
        whiteImage.SetExtent(extent[0], extent[1],
                             extent[2], extent[3],
                             extent[4], extent[5])
        whiteImage.SetOrigin(origin[0], origin[1], origin[2])
        whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)

        # initially set all values of the image to a value self.InsideValue
        npFillImagePoints = np.zeros(whiteImage.GetNumberOfPoints(), dtype=np.uint8)
        npFillImagePoints[:] = self.InsideValue
        # it is much faster to use the vtk data set adaptor functions to fill the point data tupples that it is to
        # loop over each index and set values individually. 
        pointDataArray = dsa.numpyTovtkDataArray(npFillImagePoints, name='ImageScalars', array_type=vtk.VTK_UNSIGNED_CHAR)
        whiteImage.GetPointData().SetActiveScalars('ImageScalars')
        whiteImage.GetPointData().SetScalars(pointDataArray)

        # The vtkPolyDataToImageStencil class will convert polydata into an image stencil, masking an image. 
        # The polydata can either be a closed surface mesh or a series of polyline contours (one contour per slice).
        polyDataToImageStencilFilter = vtk.vtkPolyDataToImageStencil()
        polyDataToImageStencilFilter.SetInputData(self.Surface)
        polyDataToImageStencilFilter.SetOutputSpacing(self.PolyDataToImageDataSpacing[0], 
                                                      self.PolyDataToImageDataSpacing[1], 
                                                      self.PolyDataToImageDataSpacing[2])
        polyDataToImageStencilFilter.SetOutputOrigin(origin[0], origin[1], origin[2])
        polyDataToImageStencilFilter.Update()

        # vtkImageStencil combines to images together by using a "cookie-cutter" operation. 
        imageStencil = vtk.vtkImageStencil()
        imageStencil.SetInputData(whiteImage)
        imageStencil.SetStencilConnection(polyDataToImageStencilFilter.GetOutputPort())
        imageStencil.ReverseStencilOff()
        imageStencil.SetBackgroundValue(self.OutsideValue)
        imageStencil.Update()

        self.Image = imageStencil.GetOutput()
def numpy2vtk(arr,dset,aa):
    vtkdata = dsa.numpyTovtkDataArray(arr)
    vtkarray = dsa.vtkDataArrayToVTKArray(vtkdata,dset)
    vtkarray.Association = aa
    return vtkarray
Esempio n. 28
0
def RequestData():
    import numpy as np
    from vtk.numpy_interface import dataset_adapter as dsa
    from vtk.util import numpy_support as ns

    ipoints = inputs[0]
    number_of_glyphs = ipoints.GetNumberOfPoints()

    glyph = inputs[1]

    glyph_points = [scale * xscale, scale * yscale, scale * zscale
                    ] * glyph.Points
    points_per_glyph = glyph_points.shape[0]

    cells_per_glyph = len(glyph.CellTypes)

    if forward not in ipoints.PointData.keys():
        print 'can\'t find forward array'
        return

    U = ipoints.PointData[forward]

    if up not in ipoints.PointData.keys():
        print 'can\'t find up array'
        return

    V = ipoints.PointData[up]

    W = dsa.VTKArray(np.cross(U, V))

    l = np.linalg.norm(U, axis=1)
    U = U / np.where(l == 0, 1.0, l)
    l = np.linalg.norm(U, axis=1)
    V = V / np.where(l == 0, 1.0, l)
    l = np.linalg.norm(W, axis=1)
    W = W / np.where(l == 0, 1.0, l)

    P = ipoints.Points

    p = P[0]
    u = U[0]
    v = V[0]
    w = W[0]

    opoints = []
    for i, p, u, v, w in zip(range(len(P)), P, U, V, W):
        opoints.append(p + glyph_points[:, 0][:, np.newaxis] * u +
                       glyph_points[:, 1][:, np.newaxis] * v +
                       glyph_points[:, 2][:, np.newaxis] * w)

    opolys = [glyph.Cells]
    for i in range(1, len(P)):
        o = np.zeros(len(glyph.Cells))
        k = 0
        for j in range(len(glyph.Cells)):
            if k == 0:
                k = glyph.Cells[j]
                o[j] = k
            else:
                k = k - 1
                o[j] = glyph.Cells[j] + i * points_per_glyph
        opolys.append(o)

    opoints = dsa.numpyTovtkDataArray(np.vstack(opoints))

    ids = [np.array([i] * points_per_glyph) for i in range(len(P))]
    ids = dsa.numpyTovtkDataArray(np.vstack(ids).flatten(), name='ID')

    oug = vtk.vtkUnstructuredGrid()

    pts = vtk.vtkPoints()
    pts.SetData(opoints)
    oug.SetPoints(pts)

    ct = np.hstack([glyph.CellTypes for i in range(number_of_glyphs)])
    co = np.hstack([
        glyph.CellLocations + i * len(glyph.Cells)
        for i in range(number_of_glyphs)
    ])
    opolys = np.hstack(opolys).astype('i8')

    # print '11111111'
    # if dbg == 1:
    # return

    ct = dsa.numpyTovtkDataArray(ct)
    co = dsa.numpy_support.numpy_to_vtkIdTypeArray(co)
    opolys = ns.numpy_to_vtkIdTypeArray(opolys)
    # print 'XYXYXYXY'
    # if dbg == 2:
    # return

    ca = vtk.vtkCellArray()
    ca.SetCells(number_of_glyphs * cells_per_glyph, opolys)

    # print 'BBBBBBBB'
    # if dbg == 3:
    # return

    oug.SetCells(ct, co, ca)
    oug.GetPointData().AddArray(ids)
    # print 'CCCCCCC'
    # if dbg == 4:
    # return

    oug.GetPointData().AddArray(
        dsa.numpyTovtkDataArray(np.vstack(
            [glyph.PointData['Normals'] for i in range(number_of_glyphs)]),
                                name='Normals'))

    for n in ipoints.PointData.keys():
        if n != 'Normals':
            a = [[ipoints.PointData[n][i]] * points_per_glyph
                 for i in range(number_of_glyphs)]
            oug.GetPointData().AddArray(
                dsa.numpyTovtkDataArray(np.concatenate(a), name=n))

    # print 'DDDDDDDDDDDDDDDDDDDDDDDDDDD'
    # print dir(self)
    # print 'DDDDDDDDDDDDDDDDDDDDDDDDDDD'
    # print self.GetUnstructuredGridOutput()
    # print 'DDDDDDDDDDDDDDDDDDDDDDDDDDD'
    self.GetUnstructuredGridOutput().Initialize()
    # print self.GetUnstructuredGridOutput()
    # print 'DDDDDDDDDDDDDDDDDDDDDDDDDDD'

    # if dbg == 5:
    # return

    self.GetUnstructuredGridOutput().ShallowCopy(oug)
    # print self.GetUnstructuredGridOutput()

    return
Esempio n. 29
0
    def Execute(self):
        if self.Surface == None:
            self.PrintError('Error: No Input Surface.')

        if self.InsideValue > 255:
            self.PrintError(
                'Error: Cannot assign InsideValue of image to value greater than 255'
            )

        # Step 1: Convert the input surface into an image mask of unsigned char type and spacing = PolyDataToImageDataSpacing
        #         Where voxels lying inside the surface are set to 255 and voxels outside the image are set to value 0.

        # since we are creating a new image container from nothing, calculate the origin, extent, and dimensions for the
        # vtkImageDataObject from the surface parameters.
        bounds = self.Surface.GetBounds()
        dim = []  # list of size: 3, type: int
        for i in range(3):
            dim.append(
                int(
                    math.ceil((bounds[i * 2 + 1] - bounds[i * 2]) /
                              self.PolyDataToImageDataSpacing[i])))

        origin = [
            bounds[0] + self.PolyDataToImageDataSpacing[0] / 2,
            bounds[2] + self.PolyDataToImageDataSpacing[1] / 2,
            bounds[4] + self.PolyDataToImageDataSpacing[2] / 2
        ]

        extent = [0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1]

        whiteImage = vtk.vtkImageData()
        whiteImage.SetSpacing(self.PolyDataToImageDataSpacing[0],
                              self.PolyDataToImageDataSpacing[1],
                              self.PolyDataToImageDataSpacing[2])
        whiteImage.SetDimensions(dim[0], dim[1], dim[2])
        whiteImage.SetExtent(extent[0], extent[1], extent[2], extent[3],
                             extent[4], extent[5])
        whiteImage.SetOrigin(origin[0], origin[1], origin[2])
        whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)

        # initially set all values of the image to a value self.InsideValue
        npFillImagePoints = np.zeros(whiteImage.GetNumberOfPoints(),
                                     dtype=np.uint8)
        npFillImagePoints[:] = self.InsideValue
        # it is much faster to use the vtk data set adaptor functions to fill the point data tupples that it is to
        # loop over each index and set values individually.
        pointDataArray = dsa.numpyTovtkDataArray(
            npFillImagePoints,
            name='ImageScalars',
            array_type=vtk.VTK_UNSIGNED_CHAR)
        whiteImage.GetPointData().SetActiveScalars('ImageScalars')
        whiteImage.GetPointData().SetScalars(pointDataArray)

        # The vtkPolyDataToImageStencil class will convert polydata into an image stencil, masking an image.
        # The polydata can either be a closed surface mesh or a series of polyline contours (one contour per slice).
        polyDataToImageStencilFilter = vtk.vtkPolyDataToImageStencil()
        polyDataToImageStencilFilter.SetInputData(self.Surface)
        polyDataToImageStencilFilter.SetOutputSpacing(
            self.PolyDataToImageDataSpacing[0],
            self.PolyDataToImageDataSpacing[1],
            self.PolyDataToImageDataSpacing[2])
        polyDataToImageStencilFilter.SetOutputOrigin(origin[0], origin[1],
                                                     origin[2])
        polyDataToImageStencilFilter.Update()

        # vtkImageStencil combines to images together by using a "cookie-cutter" operation.
        imageStencil = vtk.vtkImageStencil()
        imageStencil.SetInputData(whiteImage)
        imageStencil.SetStencilConnection(
            polyDataToImageStencilFilter.GetOutputPort())
        imageStencil.ReverseStencilOff()
        imageStencil.SetBackgroundValue(self.OutsideValue)
        imageStencil.Update()

        self.Image = imageStencil.GetOutput()
Esempio n. 30
0
from vtk . numpy_interface import dataset_adapter as dsa
from vtk . numpy_interface import algorithms as algs
import h5py as h5
f1=h5.File("/pkg/etc/clion/system/cmake/generated/2774870a/2774870a/Debug/example/em/tokamak0007.h5")
x=f1["/record/0/H"][:]['p']['v']
coords=algs.make_vector(x[:,0],x[:,1],x[:,2])
pts=vtk.vtkPoints()
pts.SetData(dsa.numpyTovtkDataArray ( coords , " Points "))
output.SetPoints(pts)
Esempio n. 31
0
output = self.GetOutput()

# TODO: Generate the data as you want.
from vtk.numpy_interface import dataset_adapter as dsa
from vtk.numpy_interface import algorithms as algs
import h5py as h5
f1 = h5.File(
    "/pkg/clion/etc/clion/system/cmake/generated/2774870a/2774870a/Debug/example/em/tokamak.h5"
)
x = f1["/record/H"][:, :][:, req_time, 0]
y = f1["/record/H"][:, :][:, req_time, 1]
z = f1["/record/H"][:, :][:, req_time, 2]
coords = algs.make_vector(x, y, z)
pts = vtk.vtkPoints()
pts.SetData(dsa.numpyTovtkDataArray(coords, "Points"))
output.SetPoints(pts)
# Now mark the timestep produced.
output.GetInformation().Set(output.DATA_TIME_STEP(), req_time)

########################################################################################################
## Script (RequestInformation)
########################################################################################################


def SetOutputTimesteps(algorithm, timesteps):
    executive = algorithm.GetExecutive()
    outInfo = executive.GetOutputInformation(0)
    outInfo.Remove(executive.TIME_STEPS())
    for timestep in timesteps:
        outInfo.Append(executive.TIME_STEPS(), timestep)
def RequestData():
    import numpy as np
    from time import time
    from vtk.numpy_interface import dataset_adapter as dsa
    from vtk.util import numpy_support as ns

    ipoints = inputs[0]
    number_of_glyphs = ipoints.GetNumberOfPoints()

    glyph = inputs[1]

    glyph_points = [scale * xscale, scale * yscale, scale * zscale
                    ] * glyph.Points
    points_per_glyph = glyph_points.shape[0]

    cells_per_glyph = len(glyph.CellTypes)

    if forward not in ipoints.PointData.keys():
        print('can\'t find forward array')
        return

    U = ipoints.PointData[forward]

    if up not in ipoints.PointData.keys():
        print('can\'t find up array')
        return

    V = ipoints.PointData[up]

    W = dsa.VTKArray(np.cross(U, V))

    l = np.linalg.norm(U, axis=1)
    U = U / np.where(l == 0, 1.0, l)
    l = np.linalg.norm(U, axis=1)
    V = V / np.where(l == 0, 1.0, l)
    l = np.linalg.norm(W, axis=1)
    W = W / np.where(l == 0, 1.0, l)

    P = ipoints.Points

    p = P[0]
    u = U[0]
    v = V[0]
    w = W[0]

    xpts = glyph_points[:, 0][:, np.newaxis]
    ypts = glyph_points[:, 1][:, np.newaxis]
    zpts = glyph_points[:, 2][:, np.newaxis]

    opoints = []
    for i, p, u, v, w in zip(range(len(P)), P, U, V, W):
        opoints.append(p + xpts * u + ypts * v + zpts * w)

    opolys = [glyph.Cells.reshape(-1, 4)]

    ijk = glyph.Cells.reshape((-1, 4))[:, 1:4]

    for i in range(1, len(P)):
        nijk = np.column_stack(
            ([3] * ijk.shape[0], ijk + i * points_per_glyph))
        opolys.append(nijk)

    opoints = dsa.numpyTovtkDataArray(np.vstack(opoints))

    ids = [np.array([i] * points_per_glyph) for i in range(len(P))]
    ids = dsa.numpyTovtkDataArray(np.vstack(ids).flatten(), name='ID')

    oug = vtk.vtkUnstructuredGrid()

    pts = vtk.vtkPoints()
    pts.SetData(opoints)
    oug.SetPoints(pts)

    ct = np.hstack([glyph.CellTypes for i in range(number_of_glyphs)])
    co = np.hstack([
        glyph.CellLocations + i * len(glyph.Cells)
        for i in range(number_of_glyphs)
    ])
    opolys = np.hstack(opolys).astype('i8')

    ct = dsa.numpyTovtkDataArray(ct)
    co = dsa.numpy_support.numpy_to_vtkIdTypeArray(co)
    opolys = ns.numpy_to_vtkIdTypeArray(opolys)

    ca = vtk.vtkCellArray()
    ca.SetCells(number_of_glyphs * cells_per_glyph, opolys)

    oug.SetCells(ct, co, ca)
    oug.GetPointData().AddArray(ids)

    oug.GetPointData().AddArray(
        dsa.numpyTovtkDataArray(np.vstack(
            [glyph.PointData['Normals'] for i in range(number_of_glyphs)]),
                                name='Normals'))

    if 'Texture Coordinates' in glyph.PointData.keys():
        a = np.vstack([
            glyph.PointData['Texture Coordinates']
            for i in range(len(ipoints.Points))
        ])
        oug.GetPointData().SetTCoords(dsa.numpyTovtkDataArray(a))

    for n in ipoints.PointData.keys():
        if n != 'Normals':
            a = [[ipoints.PointData[n][i]] * points_per_glyph
                 for i in range(number_of_glyphs)]
            oug.GetPointData().AddArray(
                dsa.numpyTovtkDataArray(np.concatenate(a), name=n))

    self.GetUnstructuredGridOutput().Initialize()
    self.GetUnstructuredGridOutput().ShallowCopy(oug)

    return
Esempio n. 33
0
def RequestData():
    import numpy as np
    from vtk.numpy_interface import dataset_adapter as dsa
    from math import ceil, floor

    sl = self.GetUnstructuredGridInput()
    nsl = dsa.WrapDataObject(sl)

    arclen = nsl.PointData['arclen']

    nv = nsl.Cells[nsl.CellLocations]  # number of verts in each line
    ns = nsl.CellLocations + 1  # index of first vertex in each line
    ne = ns + nv  # index one past the last vertex

    lines = [nsl.Cells[i:j]
             for i, j in zip(ns, ne)]  # divide into distinct lines

    llen = arclen[[l[-1] for l in lines]]  # length of each line
    totlen = sum(llen)  # total length
    sdist = totlen / nsamples  # appx distance between samples

    nPerLine = np.array([int(ceil(l / sdist))
                         for l in llen])  # samples in each line
    nPerLine = np.where(nPerLine < 3, 3, nPerLine)

    iarrays = {
        'points': nsl.Points
    }  # initialize source arrays with input points
    oarrays = {
        'points': []
    }  # initialize destination arrays with (empty) points

    for n in nsl.PointData.keys():
        iarrays[n] = nsl.PointData[
            n]  # add input point data arrays to source arrays
        oarrays[n] = []  # add empty destination arrays

    for i, line in enumerate(lines):  # for each input line...
        ns = nPerLine[i]  #   number in this line
        sdist1 = float(llen[i] /
                       (ns - 1))  #   inter-sample distance in this line
        x = arclen[line]  #   X axis is arc len along line
        y = range(len(line))  #   Y is index along line
        s = [i * sdist1 for i in range(ns)
             ]  #   s's are the sample points along the line in arclen
        d = np.interp(s, x, y)  #   d's are the interpolant values
        ds = np.floor(d).astype('i4')  #   index of interval start
        dd = d - ds  #   delta in interval
        de = np.where(dd == 0, ds,
                      ds + 1)  #   index of interval end (unless dd is zero)
        si = line[ds]  #   offset of starting value in arrays
        se = line[de]  #   offset of ending value in arrays
        for n in iarrays:  #   for each array we are interpolating...
            ia = iarrays[n]  #     input array
            sv = ia[si]  #     start values
            ev = ia[si]  #     end values
            v = sv + dd * (ev - sv)  #     interpolation
            oarrays[n].append(v)

    ptsa = np.concatenate(oarrays['points']).astype('f4')

    oug = self.GetUnstructuredGridOutput()

    op = vtk.vtkPoints()
    op.SetNumberOfPoints(ptsa.shape[0])

    for i, p in enumerate(ptsa):
        op.InsertPoint(i, p[0], p[1], p[2])

    oug.SetPoints(op)

    for n in oarrays:
        if n != 'points':
            a = dsa.numpyTovtkDataArray(np.concatenate(oarrays[n]))
            a.SetName(n)
            oug.GetPointData().AddArray(a)

    ct = dsa.numpyTovtkDataArray(
        np.array([vtk.VTK_VERTEX] * oug.GetNumberOfPoints()).astype('u1'))
    co = dsa.numpy_support.numpy_to_vtkIdTypeArray(
        np.array(range(0, 2 * oug.GetNumberOfPoints(), 2)))

    ca = vtk.vtkCellArray()
    for i in range(oug.GetNumberOfPoints()):
        ca.InsertNextCell(1, [i])

    oug.SetCells(ct, co, ca)
Esempio n. 34
0
def main(argv):
    import vtk
    from vtk.numpy_interface import dataset_adapter as dsa
    from vtk.numpy_interface import algorithms as algs 
    import numpy as np
    ### get parameters
    
    import os
    if not os.path.exists(OD):
        os.makedirs(OD)
    print '!!!Output to DIR: ',OD    

    if not read_fields_from_file:    

        ### Readin stage
        # using parallel openfoam reader
        ofr = vtk.vtkPOpenFOAMReader()
        # set reader's options 
        ofr.SetFileName(ID+IF)
	print '!!!open file: ',ID+IF
        ofr.SetDecomposePolyhedra(0)
        ofr.CacheMeshOn()
        ofr.SetCreateCellToPoint(0)
        ofr.DisableAllCellArrays()
        ofr.SetCellArrayStatus(fieldname,1)
        ofr.Update()

        # VTKArray is same as numpy array
        times = dsa.vtkDataArrayToVTKArray( ofr.GetTimeValues() ,ofr)
        # select the timestep between t0 and tf
        times = [t for t in times if t>=t0 and t<=tf]
	print '!!!available time steps: ',times
        N = len(times)
        np.save(times_filename,times)

        # using CellQuality to get cell's volumes as weight
        cq = vtk.vtkCellQuality()
        cq.SetInputConnection(0,ofr.GetOutputPort(0))
        cq.SetQualityMeasureToVolume()
        cq.Update()
        # cq is a composite dataset so I need GetBlock(0)
        geom = cq.GetOutputDataObject(0).GetBlock(0)

        # get volumes of cells V, size = L (number of cells)
        V = np.copy(dsa.WrapDataObject(geom).CellData['CellQuality'])
        # normalize it as weight 
        Vtotal = sum(V)
        V /= Vtotal
        
        # delete all other CellDataArray in geom DataSet, preserve its mesh structure and topology structure
        for i in range(geom.GetCellData().GetNumberOfArrays()):
            geom.GetCellData().RemoveArray(0)
        # add volume weight to it for saving
        geom.GetCellData().AddArray(dsa.numpyTovtkDataArray(V,'vol_weight'))

        # using *.vtu file format to save the vol_weight
        ugw = vtk.vtkXMLUnstructuredGridWriter()
        ugw.SetInputDataObject(geom)
        print '!!!Output vol_weight to file: ',geom_filename
        ugw.SetFileName(geom_filename)
        # using binary format
        ugw.SetDataModeToBinary()
        # enable compression
        ugw.SetCompressorTypeToZLib()
        # write to the file
        ugw.Write()
        # disconnect cq and ofr in order to isolate this dataset object from Update()
        cq.RemoveAllInputConnections(0)

        L = V.size # number of cells
        N = len(times) #number of timesteps
        # vector data is larger in size
        if field_is_vector == True:
            fields = np.zeros([N,L,3])
        else:
            fields = np.zeros([N,L])
        pipepout = ofr
        for i in range(N):
            t = times[i]
            print '!!!reading time:{}'.format(t)
            # set time value
            pipepout.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP(),t)
            # read in field data of new timestep
            pipepout.Update()
            # 
            d = dsa.WrapDataObject(pipepout.GetOutput().GetBlock(0))
            print '!!!reading field:{}'.format(fieldname)
            field = d.CellData[fieldname]
            # get the first component of composite dataset, it is the internalField
            fields[i]=np.copy(field)

        # write data to file
        print '!!!write field data to file:',fields_filename
        np.savez(fields_filename,fields)
    else: #read fields from file
        fields = np.load(fields_filename)['arr_0']
        
        ugr = vtk.vtkXMLUnstructuredGridReader()
        ugr.SetFileName(geom_filename)
        ugr.Update()
        geom = ugr.GetOutputDataObject(0)
        V = np.copy(dsa.WrapDataObject(geom).CellData['vol_weight'])
        
        times = np.load(times_filename)
        assert times.shape[0] == fields.shape[0]
        assert fields.shape[1] == V.shape[0]
        N = times.shape[0] 
        L = fields.shape[1]

        print 'Read in dataset complete'
    ### POD section


    # calculate average
    field_avg = np.average(fields, axis=0)
    if subtractAvg:
        fields = fields - field_avg

    import modred as mr
    
    if do_POD:
        # if field is a vector, reshape the fields and corresponding volument weight
        if field_is_vector:
            shp_vec = fields.shape
            shp_flat = (fields.shape[0],fields.shape[1]*fields.shape[2])
            fields = fields.reshape(shp_flat)
            V = np.tile(V,shp_vec[2])

        # POD
        print '!!!Doing POD analysis'
        modes, eigen_vals, eigen_vecs, correlation_mat = mr.compute_POD_matrices_snaps_method(fields.T,range(M),inner_product_weights=V,return_all=True)

        # if field is a vector, reshape the output matrix
        if field_is_vector:
            fields = fields.reshape(shp_vec)
            modes = np.asarray(modes).T.reshape((modes.shape[1],shp_vec[1],shp_vec[2]))
            V = V[:shp_vec[1]]

        if output_correlation_matrix:
            print "!!!output POD correlation matrix",POD_cm_filename
            np.savetxt(POD_cm_filename,correlation_mat,delimiter=',')

        if output_POD_temporal_modes: 
            print "!!!output POD temporal modes",POD_tm_filename
            # output temporal modes
            singular_vals = eigen_vals**0.5
            POD_mode_energy_normalized = eigen_vals/correlation_mat.trace()[0,0]
            cumsum_POD_mode_energy_normalized = np.cumsum(POD_mode_energy_normalized)
            # generate header string
            header_str = 'temporal modes\n'
            header_str += 'time,eigen value,singular value,normalized eigen value,accumulated normalized eigen value'
            for i in range(N-1):
                header_str += ',Mode{}'.format(i)
            header_str += '\n'
            for i in range(N-1):
                header_str += ',SV ={}'.format(singular_vals[i])
            header_str += '\n'
            for i in range(N-1):
                header_str += ',EV ={}'.format(eigen_vals[i])
            header_str += '\n'
            for i in range(N-1):
                header_str += ',NEnergy ={}'.format(POD_mode_energy_normalized[i])
            header_str += '\n'
            for i in range(N-1):
                header_str += ',CumsumEnergy ={}'.format(cumsum_POD_mode_energy_normalized[i])
            header_str += '\n'

            np.savetxt(POD_tm_filename, \
                        np.c_[times, \
                            eigen_vecs], \
                        delimiter = ',', \
                        header = header_str)
            

        if output_POD_spatial_modes:
            print "!!!output POD spatial Modes to ",POD_sm_filename
            #output to xml vtk unstructured grid file
            ugcd = geom.GetCellData()
            ugcd.Reset()
            ugcd.CopyAllOff()
            for i in range(ugcd.GetNumberOfArrays()):
                ugcd.RemoveArray(0)
            # import POD mode
            for i in range(M):
                ugcd.AddArray(dsa.numpyTovtkDataArray(modes[i],prefix+'_POD_mode_{}_{}'.format(fieldname,i)))
            # add average field
            ugcd.AddArray(dsa.numpyTovtkDataArray(field_avg,'field_{}_avg'.format(fieldname)))

            ugw = vtk.vtkXMLUnstructuredGridWriter()
            ugw.SetInputDataObject(geom)
            ugw.SetFileName(POD_sm_filename)
            ugw.Write()
        if doReconstruction:
            print "!!! do Reconstrution with {} POD modes at time {}".format(MR,ReconTime)
            #get an empty mesh
            ugcd = geom.GetCellData()
            ugcd.Reset()
            ugcd.CopyAllOff()
            for i in range(ugcd.GetNumberOfArrays()):
                ugcd.RemoveArray(0)
            # reconstruct from first MR POD modes
            # 
            ReconN = np.searchsorted(times,ReconTime)
            print "!!!actually, reconstruction is done at time {} rather than time {}".format(times[ReconN],ReconTime)
            recon_field = np.einsum("i...,i,i",modes[:MR],eigen_vals[:MR]**0.5,np.asarray(eigen_vecs)[ReconN,:MR])+field_avg;
            ugcd.AddArray(dsa.numpyTovtkDataArray(recon_field,prefix+'_POD_{}_Reconstructed_{}_{}'.format(MR,fieldname,ReconTime)))

            ugw = vtk.vtkXMLUnstructuredGridWriter()
            ugw.SetInputDataObject(geom)
            ugw.SetFileName(POD_reconstruction_filename)
            ugw.Write()
    if do_DMD:
        print "!!!Begin to calculate DMD modes"
        # if field is a vector, reshape the fields and corresponding volument weight
        if field_is_vector:
            shp_vec = fields.shape
            shp_flat = (fields.shape[0],fields.shape[1]*fields.shape[2])
            fields = fields.reshape(shp_flat)
            V = np.tile(V,shp_vec[2])

        # DMD, I do not know which mode is important, so I have to discard modes_
        modes_, ritz_vals, mode_norms, build_coeffs = mr.compute_DMD_matrices_snaps_method(fields.T,[],inner_product_weights=V,return_all=True)

        # if field is a vector, reshape the fields, V and output matrix
        if field_is_vector:
            fields = fields.reshape(shp_vec)
            V = V[:shp_vec[1]]
        # sorting
        eorder = np.argsort(mode_norms)[::-1]
        # re-order the outputs
        ritz_vals = ritz_vals[eorder]
        mode_norms = mode_norms[eorder]
        build_coeffs = build_coeffs[:,eorder]
        #build the DMD_modes
        DMD_modes = np.einsum('ijk,il->ljk', fields,build_coeffs[:,:M_DMD])
        
        if output_DMD_info:
            print "!!!output DMD info to :",DMD_info_filename
            # output modes info
            header_str = 'DMD modes info\n'
            header_str += 'ritz_vals.real,ritz_vals.imag,growth_rate, frequency, mode_norms\n'
            header_str += r'AU,AU,1/s, Hz, AU'
            dt = np.average(times[1:]-times[:-1]) #time step
            np.savetxt(DMD_info_filename, \
                        np.c_[ np.real(ritz_vals), \
                            np.imag(ritz_vals), \
                            np.log(np.abs(ritz_vals))/dt, \
                            np.angle(ritz_vals)/dt, \
                            mode_norms], \
                        delimiter = ',', \
                        header = header_str) 

        if output_DMD_build_coeffs:
            print "!!!output DMD build coeffs. to :",DMD_build_coeffs_filename
            np.savez(DMD_build_coeffs_filename, build_coeffs)
            
        if output_DMD_spatial_modes:
            print "!!!output DMD info to :",DMD_sm_filename
            #output to xml vtk unstructured grid file
            ugcd = geom.GetCellData()
            ugcd.Reset()
            ugcd.CopyAllOff()
            for i in range(ugcd.GetNumberOfArrays()):
                ugcd.RemoveArray(0)
            #import pi
            from numpy import pi
            
            for i in range(M_DMD):
                ugcd.AddArray(dsa.numpyTovtkDataArray(np.abs(DMD_modes[i]),prefix+'_DMD_mode_abs_{}_{}'.format(fieldname,i)))
                ugcd.AddArray(dsa.numpyTovtkDataArray(np.angle(DMD_modes[i])*180/pi,prefix+'_DMD_mode_angle_{}_{}'.format(fieldname,i)))


            ugw = vtk.vtkXMLUnstructuredGridWriter()
            ugw.SetInputDataObject(geom)
            ugw.SetFileName(DMD_sm_filename)
            ugw.Write()
Esempio n. 35
0
    def RequestData(self, request, inInfo, outInfo):

        logging.info('')
        start = timer()

        # input (vtkImageData)
        inp = vtk.vtkImageData.GetData(inInfo[0])

        # if the vtkImageData size has changed or this is the first time
        # save new size info and initialize containers
        if (self._sizex, self._sizey, self._viewport) != (inp.sizex, inp.sizey, inp.viewport):
            (self._sizex, self._sizey) = (inp.sizex, inp.sizey)
            self._viewport = inp.viewport
            self._init_containers()

        # the incoming depth image
        di = numpy_support.vtk_to_numpy(inp.GetPointData().GetScalars())\
            .reshape((self._sizey, self._sizex))

        # add z values to viewport_pts based on incoming depth image
        self._viewport_pts[2, :] = di.reshape(-1)

        # project to world coordinates
        self._world_pts = np.dot(inp.tmat, self._viewport_pts)
        self._world_pts = self._world_pts / self._world_pts[3]

        """ Remove invalid points """

        # index to pts outside sensor range (defined by vtkCamera clipping range)
        outside_range = ~(di < self._param_farplane_threshold)

        # find pixel neighbors with large differences in value
        # http://docs.scipy.org/doc/scipy/reference/tutorial/ndimage.html
        kh = np.array([[1, -1], [0, 0]])
        edges_h = abs(ndimage.convolve(di,
                                       kh,
                                       mode='nearest',
                                       origin=-1)) > self.param_convolution_theshold
        kv = np.array([[1, 0], [-1, 0]])
        edges_v = abs(ndimage.convolve(di,
                                       kv,
                                       mode='nearest',
                                       origin=-1)) > self.param_convolution_theshold

        # combine all the points found to be invalid
        # and set them to a value underneath the "floor of the environment"
        # http://stackoverflow.com/a/20528566/4068274
        invalid_index = np.logical_or.reduce((outside_range.reshape(-1),
                                              edges_h.reshape(-1),
                                              edges_v.reshape(-1)))
        self._world_pts[0:3, invalid_index] = np.array([[0.0], [-2.0], [0.0]])

        """ Update and set filter output """

        # update vtkPoints
        vtkarray = dsa.numpyTovtkDataArray(self._world_pts[0:3, :].T)
        self._points.SetData(vtkarray)

        # update output (vtkPolyData)
        out = vtk.vtkPolyData.GetData(outInfo)
        self._extract.Update()
        logging.info('Number of triangles: {}'.format(self._extract.GetOutput().GetNumberOfCells()))
        out.ShallowCopy(self._extract.GetOutput())

        end = timer()
        logging.info('Execution time {:.4f} seconds'.format(end - start))

        return 1
Esempio n. 36
0
def RequestData():
    import numpy as np
    from vtk.numpy_interface import dataset_adapter as dsa
    from math import ceil, floor

    sl = self.GetUnstructuredGridInput()  # The streamlines
    nsl = dsa.WrapDataObject(sl)  # wrap with a Python interface

    itime = nsl.PointData[
        'IntegrationTime']  # the time component of the streamlines

    nv = nsl.Cells[nsl.CellLocations]  # number of verts in each line
    ns = nsl.CellLocations + 1  # index of first vertex in each line
    ne = ns + nv  # index one past the last vertex

    lines = [nsl.Cells[i:j]
             for i, j in zip(ns, ne)]  # divide into distinct lines
    # lines[i] is a list of the ids of the
    # vertices that comprise each streamline

    # Get length (in integration time) of longest line.   Note - this assumes that the
    # forward- and backward- integrations are combined into one streamline (see JoinStreamlines)

    mint = itime[lines[0][0]]
    maxt = itime[lines[0][-1]]
    maxlen = itime[lines[0][-1]] - itime[lines[0][0]]
    if len(lines) > 1:
        for i in range(1, len(lines)):
            mt = itime[lines[i][-1]] - itime[lines[i][0]]
            if mt > maxlen:
                maxlen = mt
            if mint > itime[lines[i][0]]: mint = itime[lines[i][0]]
            if maxt < itime[lines[i][-1]]: maxt = itime[lines[i][-1]]

    # dt is the distance between samples in integration time - nt samples distributed along longest line

    dt = (maxt - mint) / nt

    # destination arrays for streamline points and any point-dependent data - eg. orientation data

    iarrays = {
        'points': nsl.Points
    }  # initialize source arrays with input points
    oarrays = {
        'points': []
    }  # initialize destination arrays with (empty) points

    for n in nsl.PointData.keys():
        iarrays[n] = nsl.PointData[
            n]  # add input point data arrays to source arrays
        oarrays[n] = []  # add empty destination arrays

    # for each sample time...

    for it in range(nt):

        sample_t = mint + (it + t) * dt  # the point in time to interpolate at

        for i, line in enumerate(lines):  # for each input line...

            # if this sample time is in the range for the current line...

            if sample_t >= itime[line[0]] and sample_t <= itime[line[-1]]:

                # index of first elt greater than sample_x (or 0, in which case we use the last)

                interval_end = np.argmax(
                    itime[line] > sample_t)  # linear search?
                if interval_end == 0: interval_end = len(line) - 1

                # get indices of points and point-dependent data at either end of the interval
                endi = line[interval_end]
                starti = line[interval_end - 1]

                # interpolant value in interval
                d = (sample_t - itime[starti]) / (itime[endi] - itime[starti]
                                                  )  # interpolant in interval

                for n in iarrays:  #   for each array we are interpolating...
                    ia = iarrays[n]  #     input array
                    sv = ia[starti]  #     start values
                    ev = ia[endi]  #     end values
                    v = sv + d * (ev - sv)  #     interpolation
                    oarrays[n].append(v)

    # create an output vtkUnstructured data with the interpolated points and data

    ptsa = np.concatenate(oarrays['points']).reshape((-1, 3)).astype('f4')
    oug = vtk.vtkUnstructuredGrid()

    op = vtk.vtkPoints()
    op.SetNumberOfPoints(ptsa.shape[0])

    for i, p in enumerate(ptsa):
        op.InsertPoint(i, p[0], p[1], p[2])

    oug.SetPoints(op)

    for n in oarrays:
        if n != 'points':
            if oarrays[n][0].__class__ == dsa.VTKArray:
                ncomp = len(oarrays[n][0])
                a = dsa.numpyTovtkDataArray(
                    np.concatenate(oarrays[n]).reshape((-1, ncomp)))
            else:
                a = dsa.numpyTovtkDataArray(oarrays[n])
            a.SetName(n)
            oug.GetPointData().AddArray(a)

    ct = dsa.numpyTovtkDataArray(
        np.array([vtk.VTK_VERTEX] * oug.GetNumberOfPoints()).astype('u1'))
    co = dsa.numpy_support.numpy_to_vtkIdTypeArray(
        np.array(range(0, 2 * oug.GetNumberOfPoints(), 2)))

    ca = vtk.vtkCellArray()
    for i in range(oug.GetNumberOfPoints()):
        ca.InsertNextCell(1, [i])

    oug.SetCells(ct, co, ca)

    self.GetUnstructuredGridOutput().ShallowCopy(oug)
    def RequestData(self, request, inInfoVec, outInfoVec):
        import sys, os
        import vtk
        from vtkmodules.vtkCommonDataModel import vtkUnstructuredGrid, vtkImageData, vtkDataSet
        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'] + '/python/_sample.so'
        elif 'HOMEPATH' in os.environ:
            ccode_so = os.environ['HOMEPATH'] + '/python/_sample.so'
        else:
            code_so = '_sample.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.SampleTetrahedra.argtypes = [
            C.c_int, C.c_int, C.c_int, C.c_int,
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS"),
            np.ctypeslib.ndpointer(C.c_float, flags="C_CONTIGUOUS"),
            np.ctypeslib.ndpointer(C.c_int, flags="C_CONTIGUOUS")
        ]

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

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

        ccode.GetNumberOfSamples.restype = C.c_int

        ccode.GetSamples.restype = C.c_void_p

        obj = dsa.WrapDataObject(vtkDataSet.GetData(inInfoVec[0], 0))

        pdf = self.inputArray
        nSamples = self.nSamples

        if obj.GetClassName() == 'vtkImageData':

            a = vtkImageData.GetData(inInfoVec[0], 0)
            vti = dsa.WrapDataObject(vtkImageData.GetData(inInfoVec[0], 0))
            e = vti.VTKObject.GetExtent()
            o = vti.VTKObject.GetOrigin()
            s = vti.VTKObject.GetSpacing()
            dimensions = np.array([(e[2 * i + 1] - e[2 * i]) + 1
                                   for i in range(3)]).astype('i4')
            origin = np.array([o[i] + e[2 * i] * s[i]
                               for i in range(3)]).astype('f4')
            spacing = np.array(s).astype('f4')
            pdf = np.ascontiguousarray(vti.CellData[pdf]).astype('f4')
            ccode.SampleVTI(0, nSamples, dimensions, origin, spacing, pdf)

        elif obj.GetClassName() == 'vtkUnstructuredGrid':

            vtu = dsa.WrapDataObject(
                vtkUnstructuredGrid.GetData(inInfoVec[0], 0))
            points = np.ascontiguousarray(vtu.Points).astype('f4')
            pdf = np.ascontiguousarray(vtu.CellData[pdf]).astype('f4')
            tets = np.ascontiguousarray(vtu.Cells).astype('i4')
            ccode.SampleTetrahedra(0, nSamples, vtu.GetNumberOfPoints(),
                                   vtu.GetNumberOfCells(), points, pdf, tets)

        elif obj.GetClassName() == 'vtkRectilinearGrid':

            vtr = vtkRectilinearGrid.GetData(inInfoVec[0], 0)
            x_array = dsa.numpy_support.vtk_to_numpy(
                vtr.GetXCoordinates()).astype('f4')
            y_array = dsa.numpy_support.vtk_to_numpy(
                vtr.GetYCoordinates()).astype('f4')
            z_array = dsa.numpy_support.vtk_to_numpy(
                vtr.GetZCoordinates()).astype('f4')
            pdf = dsa.numpy_support.vtk_to_numpy(
                vtr.GetCellData().GetArray(pdf)).astype('f4')
            dim = (len(x_array), len(y_array), len(z_array))
            ccode.SampleRectilinear(0, dim, x_array, y_array, z_array, pdf)

        else:
            print(
                "SampleCellDensity requires vtkImageData or vtkUnstructuredGrid"
            )
            return 0

        n = ccode.GetNumberOfSamples()
        s = np.ctypeslib.as_array(C.cast(ccode.GetSamples(),
                                         C.POINTER(C.c_float)),
                                  shape=(n, 3))
        samples = dsa.WrapDataObject(vtk.vtkUnstructuredGrid())
        co = dsa.numpy_support.numpy_to_vtkIdTypeArray(
            np.arange(n).astype('i8') * 2)
        ca = vtk.vtkCellArray()
        ca.SetCells(
            n,
            dsa.numpy_support.numpy_to_vtkIdTypeArray(
                np.column_stack(([1] * n, range(n))).reshape(
                    (2 * n, )).astype('i8')))
        ct = dsa.numpyTovtkDataArray(
            np.array([vtk.VTK_VERTEX] * n).astype('u1'))
        samples.VTKObject.SetCells(ct, co, ca)
        samples.Points = dsa.numpy_support.numpy_to_vtk(s, deep=1)

        outpt = vtkUnstructuredGrid.GetData(outInfoVec, 0)
        outpt.ShallowCopy(samples.VTKObject)

        ccode.Cleanup()
        return 1
    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