def get_data_vtk(self, points_interpol, interpolation_method="linear"): """ Get interpolated data for points_interpol using vtks built-in interpolation methods """ kernels = { "voronoi": vtk.vtkVoronoiKernel(), "gaussian": vtk.vtkGaussianKernel(), "shepard": vtk.vtkShepardKernel(), "linear": vtk.vtkLinearKernel() } pointnumpyarray = np.array( [points_interpol[pt] for pt in points_interpol]) out_u_grid = vtk.vtkUnstructuredGrid() r = vtk.vtkPoints() r.SetData(numpy_to_vtk(pointnumpyarray)) out_u_grid.SetPoints(r) locator = vtk.vtkStaticPointLocator() locator.SetDataSet(self.output) locator.BuildLocator() interpolator = vtk.vtkPointInterpolator() interpolator.SetInputData(out_u_grid) interpolator.SetSourceData(self.output) interpolator.SetKernel(kernels[interpolation_method]) interpolator.SetLocator(locator) interpolator.Update() return interpolator.GetOutput().GetPointData()
def probeUnstructuredGridVTKOverLine(self, lineVTK, readerUnstructuredGridVTK, varName, kernel="gaussian", radius=None, nullValue=None): """ Interpolate the data from the Unstructured Grid VTK onto a line (profile). The unstructured grid VTK is supposed to be a 2D surface in 3D space, such as the mesh used in 2D hydraulics models. To probe on them, the surface has to be flattened first. Parameters ---------- lineVTK : vtkLineSource or vtkPoints coordinates of points in the vtkLineSource; the points don't need to ordered, thus they can be just a bunch of points readerUnstructuredGridVTK : vtkUnstructuredGridReader Unstructured Grid VTK reader varName : str name of the variable to be probed kernel : str name of the kernel for interpolation (linear, gaussin, voronoi, Shepard" radius : float radius for interpolation kernels nullValue: float value to be assigned to invalid probing points Returns ------- points: numpy arrays [number of points, 3]; points on the profile probed result array: elev: elevation (z) of points in the profile """ # Get data from the Unstructured Grid VTK reader data = readerUnstructuredGridVTK.GetOutput() # make sure the data is stored at points (for smoother interpolation) cell2point = vtk.vtkCellDataToPointData() cell2point.SetInputData(data) cell2point.Update() data = cell2point.GetOutput() #after this, all data are stored at points, not cell centers. bounds = data.GetBounds() #print("Unstructured Grid VTK bounds = ", bounds) #print("Unstructured Grid number of cells: ", data.GetNumberOfCells()) #print("Unstructured Grid number of points: ", data.GetNumberOfPoints()) if radius is None: boundingArea = (bounds[1] - bounds[0]) * (bounds[3] - bounds[2]) #assume 2D Grid averageCellArea = boundingArea/data.GetNumberOfCells() #average cell area radius = np.sqrt(averageCellArea) #average size of cell radius = 2.0*radius #double the search radius ### make a transform to set all Z values to zero ### flattener = vtk.vtkTransform() flattener.Scale(1.0, 1.0, 0.0) ### flatten the input in case it's not already flat ### i_flat = vtk.vtkTransformFilter() if isinstance(lineVTK, vtk.vtkLineSource): i_flat.SetInputConnection(lineVTK.GetOutputPort()) elif isinstance(lineVTK, vtk.vtkPoints): polydata_temp = vtk.vtkPolyData() polydata_temp.SetPoints(lineVTK) i_flat.SetInputData(polydata_temp) else: raise Exception("lineVTK type,", type(lineVTK),", not supported. Only vtkLineSource and vtkPoints are supported.") i_flat.SetTransform(flattener) ### transfer z elevation values to the source's point scalar data ### s_elev = vtk.vtkElevationFilter() s_elev.SetInputData(data) s_elev.SetHighPoint(0, 0, bounds[5]) s_elev.SetLowPoint(0, 0, bounds[4]) s_elev.SetScalarRange(bounds[4], bounds[5]) s_elev.Update() #print("s_elev = ", s_elev.GetUnstructuredGridOutput()) ### flatten the source data; the Z elevations are already in the scalars data ### s_flat = vtk.vtkTransformFilter() s_flat.SetInputConnection(s_elev.GetOutputPort()) s_flat.SetTransform(flattener) # build the probe using vtkPointInterpolator # construct the interpolation kernel if kernel == 'gaussian': kern = vtk.vtkGaussianKernel() kern.SetSharpness(2) kern.SetRadius(radius) elif kernel == 'voronoi': kern = vtk.vtkVoronoiKernel() elif kernel == 'linear': kern = vtk.vtkLinearKernel() kern.SetRadius(radius) elif kernel == 'Shepard': kern = vtk.vtkShepardKernel() kern.SetPowerParameter(2) kern.SetRadius(radius) else: raise Exception("The specified kernel is not supported.") probe = vtk.vtkPointInterpolator() probe.SetInputConnection(i_flat.GetOutputPort()) probe.SetSourceConnection(s_flat.GetOutputPort()) probe.SetKernel(kern) if nullValue is not None: probe.SetNullValue(nullValue) else: probe.SetNullPointsStrategyToClosestPoint() probe.Update() # (This approach of using vtkProbeFilter is replaced by vtkPointInterpolator for smoother result) # vtkProbeFilter, the probe line is the input, and the underlying dataset is the source. #probe = vtk.vtkProbeFilter() #probe.SetInputConnection(i_flat.GetOutputPort()) #probe.SetSourceConnection(s_flat.GetOutputPort()) #probe.Update() # get the data from the VTK-object (probe) to an numpy array #print("varName =", varName) #print(probe.GetOutput().GetPointData().GetArray(varName)) varProbedValues = VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray(varName)) numPoints = probe.GetOutput().GetNumberOfPoints() # get the number of points on the line # get the elevation from the VTK-object (probe) to an numpy array elev = VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray("Elevation")) # intialise the points on the line x = np.zeros(numPoints) y = np.zeros(numPoints) z = np.zeros(numPoints) points = np.zeros((numPoints, 3)) # get the coordinates of the points on the line for i in range(numPoints): x[i], y[i], z[i] = probe.GetOutput().GetPoint(i) points[i, 0] = x[i] points[i, 1] = y[i] points[i, 2] = z[i] return points, varProbedValues, elev
def interpolateToVolume(mesh, kernel='shepard', radius=None, N=None, bounds=None, nullValue=None, dims=(25, 25, 25)): """ Generate a ``Volume`` by interpolating a scalar or vector field which is only known on a scattered set of points or mesh. Available interpolation kernels are: shepard, gaussian, or linear. :param str kernel: interpolation kernel type [shepard] :param float radius: radius of the local search :param list bounds: bounding box of the output Volume object :param list dims: dimensions of the output Volume object :param float nullValue: value to be assigned to invalid points |interpolateVolume| |interpolateVolume.py|_ """ if isinstance(mesh, vtk.vtkPolyData): output = mesh else: output = mesh.polydata() if radius is None and not N: colors.printc( "Error in interpolateToVolume(): please set either radius or N", c='r') raise RuntimeError # Create a probe volume probe = vtk.vtkImageData() probe.SetDimensions(dims) if bounds is None: bounds = output.GetBounds() probe.SetOrigin(bounds[0], bounds[2], bounds[4]) probe.SetSpacing((bounds[1] - bounds[0]) / dims[0], (bounds[3] - bounds[2]) / dims[1], (bounds[5] - bounds[4]) / dims[2]) # if radius is None: # radius = min(bounds[1]-bounds[0], bounds[3]-bounds[2], bounds[5]-bounds[4])/3 locator = vtk.vtkPointLocator() locator.SetDataSet(output) locator.BuildLocator() if kernel == 'shepard': kern = vtk.vtkShepardKernel() kern.SetPowerParameter(2) elif kernel == 'gaussian': kern = vtk.vtkGaussianKernel() elif kernel == 'linear': kern = vtk.vtkLinearKernel() else: print('Error in interpolateToVolume, available kernels are:') print(' [shepard, gaussian, linear]') raise RuntimeError() if radius: kern.SetRadius(radius) interpolator = vtk.vtkPointInterpolator() interpolator.SetInputData(probe) interpolator.SetSourceData(output) interpolator.SetKernel(kern) interpolator.SetLocator(locator) if N: kern.SetNumberOfPoints(N) kern.SetKernelFootprintToNClosest() else: kern.SetRadius(radius) if nullValue is not None: interpolator.SetNullValue(nullValue) else: interpolator.SetNullPointsStrategyToClosestPoint() interpolator.Update() return Volume(interpolator.GetOutput())
intActor1 = vtk.vtkActor() intActor1.SetMapper(intMapper1) # Create an outline outline1 = vtk.vtkStructuredGridOutlineFilter() outline1.SetInputData(output) outlineMapper1 = vtk.vtkPolyDataMapper() outlineMapper1.SetInputConnection(outline1.GetOutputPort()) outlineActor1 = vtk.vtkActor() outlineActor1.SetMapper(outlineMapper1) # Shepard kernel------------------------------------------------------- shepardKernel = vtk.vtkShepardKernel() shepardKernel.SetPowerParameter(2) shepardKernel.SetRadius(0.5) interpolator2 = vtk.vtkPointInterpolator() interpolator2.SetInputConnection(plane.GetOutputPort()) interpolator2.SetSourceData(output) interpolator2.SetKernel(shepardKernel) interpolator2.SetLocator(locator) interpolator2.SetNullPointsStrategyToMaskPoints() # Time execution timer.StartTimer() interpolator2.Update() timer.StopTimer() time = timer.GetElapsedTime()
def npInterpolateVTK2D(npPoints, npValues, npTargetPoints, ParametreInterpolatorVTK=None): # Set SParameters if not define if ParametreInterpolatorVTK == None: ParametreInterpolatorVTK = { 'kernel': 'Gaussian', 'Radius': 20., 'Sharpness': 2. } print('[' + ParametreInterpolatorVTK['kernel'] + ' Interpolation - Radius =' + str(ParametreInterpolatorVTK['Radius']) + ' - Sharpness =' + str(ParametreInterpolatorVTK['Sharpness']) + '] processing... ') # Set Source Points UnGrid = vtk.vtkUnstructuredGrid() vtkP = vtk.vtkPoints() for [x, y] in npPoints: vtkP.InsertNextPoint(x, y, 0.) UnGrid.SetPoints(vtkP) # Set source Point Values l, c = npValues.shape for i in range(0, c): vtkFA = vtk.vtkFloatArray() vtkFA.SetName('Values' + str(i)) for v in npValues: vtkFA.InsertNextValue(v[i]) UnGrid.GetPointData().AddArray(vtkFA) # Set Target Points vtkTP = vtk.vtkPoints() for [x, y] in npTargetPoints: vtkTP.InsertNextPoint(x, y, 0.) vtkTargetPointsPolyData = vtk.vtkPolyData() vtkTargetPointsPolyData.SetPoints(vtkTP) if ParametreInterpolatorVTK['kernel'] == 'Gaussian': Kernel = vtk.vtkGaussianKernel() Kernel.SetSharpness(ParametreInterpolatorVTK['Sharpness']) Kernel.SetRadius(ParametreInterpolatorVTK['Radius']) if ParametreInterpolatorVTK['kernel'] == 'Voronoi': Kernel = vtk.vtkVoronoiKernel() if ParametreInterpolatorVTK['kernel'] == 'Shepard': Kernel = vtk.vtkShepardKernel() Kernel.SetRadius(ParametreInterpolatorVTK['Radius']) interp = vtk.vtkPointInterpolator2D() interp.SetInputData(vtkTargetPointsPolyData) interp.SetSourceData(UnGrid) interp.SetKernel(Kernel) # interp.GetLocator().SetNumberOfPointsPerBucket(1) interp.InterpolateZOff() interp.SetNullPointsStrategyToMaskPoints() interp.Update() outputInterp = interp.GetOutput() pointsArr = outputInterp.GetPoints().GetData() nppointsArr = vtk_to_numpy(pointsArr) pdata = outputInterp.GetPointData() # Convert volocities into Numpy Array npOutputValues = np.zeros((len(npTargetPoints), c)) for i in range(0, c): vtkOutputValues = pdata.GetArray('Values' + str(i)) npOutputValues[:, i] = vtk_to_numpy(vtkOutputValues) return npOutputValues