[vtkusers] Convert a structured to an unstructured grid

Armin Wehrfritz dkxls23 at gmail.com
Thu Nov 10 04:30:26 EST 2016


To follow up on my own post: I figured out the problem. It was a matter
of setting the scalar array in the structured grid correctly, i.e changing
> sg.GetPointData().AddArray(a)
to
> sg.GetPointData().SetScalars(a)
fixed the problem.

I included my final version of the script for reference below.


-Armin








#!/usr/bin/env python

from __future__ import division, print_function

import numpy as np

import vtk
from vtk.numpy_interface import algorithms as algs
from vtk.numpy_interface import dataset_adapter as dsa


Nx = 11
Ny = 21

# Generate a grid using numpy
tx = np.linspace(0, 1, Ny)
ty = np.linspace(0, 1, Nx)
x1, y1 = np.linspace(0, 1, Nx), np.linspace(0, 2, Ny)
x2, y2 = x1, y1
x = x1[None,:] + np.outer(tx, (x2 - x1))
y = y1[:,None] + np.outer((y2 - y1), ty)
z = np.zeros_like(x)

# Generate the vtk points
coordinates = algs.make_vector(np.stack((x, x)).ravel(),
                                np.stack((y, y)).ravel(),
                                np.stack((z, z + 0.1)).ravel())
pts = vtk.vtkPoints()
pts.SetData(dsa.numpyTovtkDataArray(coordinates, "Points"))

# Generate a structured grid
sg = vtk.vtkStructuredGrid()
sg.SetDimensions(Nx, Ny, 2)
sg.SetPoints(pts)
sg.GetCellData().SetScalars(dsa.numpyTovtkDataArray(np.arange((Nx-1)*(Ny-1)),
                                                     "CellID"))
print('#Cells (structured):', sg.GetNumberOfCells())

# Write the structured grid
sw = vtk.vtkXMLStructuredGridWriter()
sw.SetDataModeToAscii()
sw.SetFileName('grid.vts')
sw.SetInputDataObject(sg)
sw.Write()

# Generate an unstructured grid using the threshold filter
t = vtk.vtkThreshold()
t.SetInputDataObject(sg)
t.ThresholdByUpper(-1)
t.Update()
print('#Cells (unstructured):', t.GetOutput().GetNumberOfCells())

# Write the unstructured grid
uw = vtk.vtkXMLUnstructuredGridWriter()
uw.SetDataModeToAscii()
uw.SetFileName('grid.vtu')
uw.SetInputConnection(t.GetOutputPort())
uw.Write()


More information about the vtkusers mailing list