Exemple #1
0
def test_multi_block_init_vtk():
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkStructuredGrid())
    multi = pyvista.MultiBlock(multi)
    assert isinstance(multi, pyvista.MultiBlock)
    assert multi.n_blocks == 2
    assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid)
    assert isinstance(multi.GetBlock(1), pyvista.StructuredGrid)
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkStructuredGrid())
    multi = pyvista.MultiBlock(multi, deep=True)
    assert isinstance(multi, pyvista.MultiBlock)
    assert multi.n_blocks == 2
    assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid)
    assert isinstance(multi.GetBlock(1), pyvista.StructuredGrid)
    # Test nested structure
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkImageData())
    nested = vtk.vtkMultiBlockDataSet()
    nested.SetBlock(0, vtk.vtkUnstructuredGrid())
    nested.SetBlock(1, vtk.vtkStructuredGrid())
    multi.SetBlock(2, nested)
    # Wrap the nested structure
    multi = pyvista.MultiBlock(multi)
    assert isinstance(multi, pyvista.MultiBlock)
    assert multi.n_blocks == 3
    assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid)
    assert isinstance(multi.GetBlock(1), pyvista.UniformGrid)
    assert isinstance(multi.GetBlock(2), pyvista.MultiBlock)
Exemple #2
0
def draw_grid():
    xArray = vtk.vtkDoubleArray()
    yArray = vtk.vtkDoubleArray()
    zArray = vtk.vtkDoubleArray()

    for x in range(-60, 61):
        xArray.InsertNextValue(x)
    # for y in range(-10, 10):
    #     yArray.InsertNextValue(y)
    for y in range(0, 1):
        yArray.InsertNextValue(y)
    for z in range(-80, 80):
        zArray.InsertNextValue(z)

    grid = vtk.vtkRectilinearGrid()
    grid.SetDimensions(121, 1, 161)
    grid.SetXCoordinates(xArray)
    grid.SetYCoordinates(yArray)
    grid.SetZCoordinates(zArray)

    # print(grid.GetPoint(0))

    gridMapper = vtk.vtkDataSetMapper()
    gridMapper.SetInputData(grid)

    gridActor = vtk.vtkActor()
    gridActor.SetMapper(gridMapper)
    gridActor.GetProperty().SetColor(0.75, 0.75, 0)
    gridActor.GetProperty().SetOpacity(0.1)
    # import pdb; pdb.set_trace()
    return gridActor
Exemple #3
0
    def from_rectilinearGrid(grid, size, origin=np.zeros(3)):
        """
        Create VTK of type vtk.vtkRectilinearGrid.

        This is the common type for results from the grid solver.

        Parameters
        ----------
        grid : numpy.ndarray of shape (3) of np.dtype = int
            Number of cells.
        size : numpy.ndarray of shape (3)
            Physical length.
        origin : numpy.ndarray of shape (3), optional
            Spatial origin.

        """
        geom = vtk.vtkRectilinearGrid()
        geom.SetDimensions(*(grid + 1))
        geom.SetXCoordinates(
            np_to_vtk(np.linspace(origin[0], origin[0] + size[0], grid[0] + 1),
                      deep=True))
        geom.SetYCoordinates(
            np_to_vtk(np.linspace(origin[1], origin[1] + size[1], grid[1] + 1),
                      deep=True))
        geom.SetZCoordinates(
            np_to_vtk(np.linspace(origin[2], origin[2] + size[2], grid[2] + 1),
                      deep=True))

        return VTK(geom)
Exemple #4
0
    def from_rectilinear_grid(grid, size, origin=np.zeros(3)):
        """
        Create VTK of type vtk.vtkRectilinearGrid.

        Parameters
        ----------
        grid : iterable of int, len (3)
            Number of cells along each dimension.
        size : iterable of float, len (3)
            Physical length along each dimension.
        origin : iterable of float, len (3), optional
            Coordinates of grid origin.

        Returns
        -------
        new : damask.VTK
            VTK-based geometry without nodal or cell data.

        """
        warnings.warn('Support for vtr files will be removed in DAMASK 3.1.0',
                      DeprecationWarning, 2)
        vtk_data = vtk.vtkRectilinearGrid()
        vtk_data.SetDimensions(*(np.array(grid) + 1))
        coord = [
            np_to_vtk(np.linspace(origin[i], origin[i] + size[i], grid[i] + 1),
                      deep=True) for i in [0, 1, 2]
        ]
        [coord[i].SetName(n) for i, n in enumerate(['x', 'y', 'z'])]
        vtk_data.SetXCoordinates(coord[0])
        vtk_data.SetYCoordinates(coord[1])
        vtk_data.SetZCoordinates(coord[2])

        return VTK(vtk_data)
def SetVtkGrid(x,y,z):
    """Set up the vtk rectilinear grid using x, y, z data.
    
    Parameters:
        x, y, z -- the points in the x, y and z directions respectively
    Returns:
        grid -- a vtkRectilinearGrid object
    """
    grid = vtkRectilinearGrid();
    grid.SetDimensions(len(x),len(y),len(z));
     
    xArray = vtkDoubleArray();
    for xCoord in x: xArray.InsertNextValue(xCoord)
     
    yArray = vtkDoubleArray();
    for yCoord in y: yArray.InsertNextValue(yCoord)
    
    zArray = vtkDoubleArray();
    for zCoord in z: zArray.InsertNextValue(zCoord)
     
    grid.SetXCoordinates(xArray);
    grid.SetYCoordinates(yArray);
    grid.SetZCoordinates(zArray);
    
    print "There are " + str(grid.GetNumberOfPoints()) + " points.";
    print "There are " + str(grid.GetNumberOfCells()) + " cells.";

    return grid
Exemple #6
0
    def from_rectilinear_grid(grid,size,origin=np.zeros(3)):
        """
        Create VTK of type vtk.vtkRectilinearGrid.

        This is the common type for grid solver results.

        Parameters
        ----------
        grid : iterable of int, len (3)
            Number of cells along each dimension.
        size : iterable of float, len (3)
            Physical lengths along each dimension.
        origin : iterable of float, len (3), optional
            Spatial origin coordinates.

        """
        vtk_data = vtk.vtkRectilinearGrid()
        vtk_data.SetDimensions(*(np.array(grid)+1))
        coord = [np_to_vtk(np.linspace(origin[i],origin[i]+size[i],grid[i]+1),deep=True) for i in [0,1,2]]
        [coord[i].SetName(n) for i,n in enumerate(['x','y','z'])]
        vtk_data.SetXCoordinates(coord[0])
        vtk_data.SetYCoordinates(coord[1])
        vtk_data.SetZCoordinates(coord[2])

        return VTK(vtk_data)
    def generateMesh(self, x, y, z, in_x, in_y, in_z):
        x_coord = vtk.vtkFloatArray()
        x_coord.InsertNextValue(x)

        y_coord = vtk.vtkFloatArray()
        y_coord.InsertNextValue(y)

        z_coord = vtk.vtkFloatArray()
        z_coord.InsertNextValue(z)

        grid = vtk.vtkRectilinearGrid()
        grid.SetDimensions(self.nx if in_x else 1, self.ny if in_y else 1, self.nz if in_z else 1)
        grid.SetXCoordinates(self.x_coords if in_x else x_coord);
        grid.SetYCoordinates(self.y_coords if in_y else y_coord);
        grid.SetZCoordinates(self.z_coords if in_z else z_coord);

        # We're going to generate all of the IDs of the cells in that rectilinear grid so we can extract them as an UnstructuredGrid
        # Why would we do such a thing?  Because there is some bug associated with RecitilinearGrids and clipping / rendering
        # So, instead I'm going to use RectilinearGrid for generating the cells and then "copy" it to an UnstructuredGrid using ExtractCells
        num_cells = grid.GetNumberOfCells()
        id_list = vtk.vtkIdList()
        for i in xrange(num_cells):
            id_list.InsertNextId(i)

        extract = vtk.vtkExtractCells()
        if vtk.VTK_MAJOR_VERSION <= 5:
            extract.SetInput(grid)
        else:
            extract.SetInputData(grid)
        extract.SetCellList(id_list)

        return extract.GetOutput()
Exemple #8
0
    def __init__(self, startX, startY, endX, endY, zValue=0, nPoints=20):

        self.xCoords = vtk.vtkFloatArray()
        self.yCoords = vtk.vtkFloatArray()
        self.zCoords = vtk.vtkFloatArray()

        for x in np.linspace(startX, endX, nPoints):
            self.xCoords.InsertNextValue(x)

        for y in np.linspace(startY, endY, nPoints):
            self.yCoords.InsertNextValue(y)

        for z in [zValue]:
            self.zCoords.InsertNextValue(z)

        self.rgrid = vtk.vtkRectilinearGrid()
        self.rgrid.SetDimensions(nPoints, nPoints, 1)
        self.rgrid.SetXCoordinates(self.xCoords)
        self.rgrid.SetYCoordinates(self.yCoords)
        self.rgrid.SetZCoordinates(self.zCoords)

        self.plane = vtk.vtkRectilinearGridGeometryFilter()
        self.plane.SetInputData(self.rgrid)
        self.plane.SetExtent(0, nPoints - 1, 0, nPoints - 1, 0, 0)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.plane.GetOutputPort())

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetRepresentationToWireframe()
        self.actor.GetProperty().SetColor((0, 0, 0))
        self.actor.GetProperty().EdgeVisibilityOn()

        return
Exemple #9
0
def test_multi_block_init_vtk():
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkTable())
    multi = pyvista.MultiBlock(multi)
    assert isinstance(multi, pyvista.MultiBlock)
    assert multi.n_blocks == 2
    assert isinstance(multi[0], pyvista.RectilinearGrid)
    assert isinstance(multi[1], vtk.vtkTable)
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkTable())
    multi = pyvista.MultiBlock(multi, deep=True)
    assert isinstance(multi, pyvista.MultiBlock)
    assert multi.n_blocks == 2
    assert isinstance(multi[0], pyvista.RectilinearGrid)
    assert isinstance(multi[1], vtk.vtkTable)
Exemple #10
0
def write_3d_mesh_tally_to_vtk(
        xs,
        ys,
        zs,
        tally_label: str,
        tally_data,
        error_data,
        outfile):
    try:
        import vtk
    except (ImportError, ModuleNotFoundError):
        msg = "Conversion to VTK requested," \
            "but the Python VTK module is not installed."
        raise ImportError(msg)

    vtk_box = vtk.vtkRectilinearGrid()

    vtk_box.SetDimensions(len(xs), len(ys), len(zs))

    vtk_x_array = vtk.vtkDoubleArray()
    vtk_x_array.SetName('x-coords')
    vtk_x_array.SetArray(xs, len(xs), True)
    vtk_box.SetXCoordinates(vtk_x_array)

    vtk_y_array = vtk.vtkDoubleArray()
    vtk_y_array.SetName('y-coords')
    vtk_y_array.SetArray(ys, len(ys), True)
    vtk_box.SetYCoordinates(vtk_y_array)

    vtk_z_array = vtk.vtkDoubleArray()
    vtk_z_array.SetName('z-coords')
    vtk_z_array.SetArray(zs, len(zs), True)
    vtk_box.SetZCoordinates(vtk_z_array)

    tally = np.array(tally_data)
    tally_data = vtk.vtkDoubleArray()
    tally_data.SetName(tally_label)
    tally_data.SetArray(tally, tally.size, True)

    error = np.array(error_data)
    error_data = vtk.vtkDoubleArray()
    error_data.SetName("error_tag")
    error_data.SetArray(error, error.size, True)

    vtk_box.GetCellData().AddArray(tally_data)
    vtk_box.GetCellData().AddArray(error_data)

    writer = vtk.vtkRectilinearGridWriter()

    writer.SetFileName(outfile)

    writer.SetInputData(vtk_box)

    print('Writing %s' % outfile)

    writer.Write()
Exemple #11
0
def writeVTR(vtr_name, scalar_fields, vector_fields, vtkX, vtkY, vtkZ,
             localZrange):
    """Writes a single VTR file per Python processor/variable

    Parameters:
     vtr_name - name of the VTR file
     scalar_fields - dictionary with scalar field arrays ordered [x, y, z], e.g. {'p': array[nx,ny,nz], 'rho0': array[nx,ny,nz]}
     vector_fields - dictionary with vector fields ordered [3, x, y, z], e.g. {'J': array[3,nx,ny,nz], 'B': array[3,nx,ny,nz]}
     vtkX, vtkY, vtkZ - VTR coordinates, see createVtrCoordinates()
     localZrange - local range for Z indices

    """
    Nx = vtkX.GetNumberOfTuples() - 1
    Ny = vtkY.GetNumberOfTuples() - 1
    Nz = vtkZ.GetNumberOfTuples() - 1
    numpoints = (Nx + 1) * (Ny + 1) * (Nz + 1)
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetExtent(0, Nx, 0, Ny, localZrange[0], localZrange[1])
    rtg.SetXCoordinates(vtkX)
    rtg.SetYCoordinates(vtkY)
    rtg.SetZCoordinates(vtkZ)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(
            0, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints * 3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0, 3).swapaxes(
            1, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints * 3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Exemple #12
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a grid
    grid = vtk.vtkRectilinearGrid()

    grid.SetDimensions(2, 3, 2)

    xArray = vtk.vtkDoubleArray()
    xArray.InsertNextValue(0.0)
    xArray.InsertNextValue(2.0)

    yArray = vtk.vtkDoubleArray()
    yArray.InsertNextValue(0.0)
    yArray.InsertNextValue(1.0)
    yArray.InsertNextValue(2.0)

    zArray = vtk.vtkDoubleArray()
    zArray.InsertNextValue(0.0)
    zArray.InsertNextValue(5.0)

    grid.SetXCoordinates(xArray)
    grid.SetYCoordinates(yArray)
    grid.SetZCoordinates(zArray)

    shrinkFilter = vtk.vtkShrinkFilter()
    shrinkFilter.SetInputData(grid)
    shrinkFilter.SetShrinkFactor(.8)

    # Create a mapper and actor
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(shrinkFilter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName('VisualizeRectilinearGrid')

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))
    renderer.GetActiveCamera().Roll(10.0)
    renderer.GetActiveCamera().Elevation(60.0)
    renderer.GetActiveCamera().Azimuth(30.0)
    renderer.ResetCamera()

    renderWindow.Render()
    renderWindowInteractor.Start()
Exemple #13
0
def ubcMesh2D(FileName, pdo=None):
    """
    Description
    -----------
    This method reads a UBC 2D Mesh file and builds an empty vtkRectilinearGrid for data to be inserted into. [Format Specs](http://giftoolscookbook.readthedocs.io/en/latest/content/fileFormats/mesh2Dfile.html)

    Parameters
    ----------
    `FileName` : str
    - The mesh filename as an absolute path for the input mesh file in UBC 3D Mesh Format.

    `pdo` : vtk.vtkRectilinearGrid, optional
    - The output data object

    Returns
    -------
    Returns a vtkRectilinearGrid generated from the UBC 3D Mesh grid. Mesh is defined by the input mesh file. No data attributes here, simply an empty mesh. Use the placeModelOnMesh() method to associate with model data.

    """
    if pdo is None:
        pdo = vtk.vtkRectilinearGrid()  # vtkRectilinearGrid

    # Read in data from file
    xpts, xdisc, zpts, zdisc = _ubcMesh2D_part(FileName)

    nx = np.sum(np.array(xdisc, dtype=int)) + 1
    nz = np.sum(np.array(zdisc, dtype=int)) + 1

    # Now generate the vtkRectilinear Grid
    def _genCoords(pts, disc, z=False):
        c = [float(pts[0])]
        for i in range(len(pts) - 1):
            start = float(pts[i])
            stop = float(pts[i + 1])
            num = int(disc[i])
            w = (stop - start) / num

            for j in range(1, num):
                c.append(start + (j) * w)
            c.append(stop)
        c = np.array(c, dtype=float)
        if z:
            c = -c[::-1]
        return nps.numpy_to_vtk(num_array=c, deep=True)

    xcoords = _genCoords(xpts, xdisc)
    zcoords = _genCoords(zpts, zdisc, z=True)
    ycoords = nps.numpy_to_vtk(num_array=np.zeros(1), deep=True)

    pdo.SetDimensions(nx, 2, nz)  # note this subtracts 1
    pdo.SetXCoordinates(xcoords)
    pdo.SetYCoordinates(ycoords)
    pdo.SetZCoordinates(zcoords)

    return pdo
Exemple #14
0
    def __init__(self,
                 nOutputPorts=1,
                 outputType='vtkRectilinearGrid',
                 **kwargs):
        ubcMeshReaderBase.__init__(self,
                                   nOutputPorts=nOutputPorts,
                                   outputType=outputType,
                                   **kwargs)

        self.__mesh = vtk.vtkRectilinearGrid()
        self.__models = []
def main():
    colors = vtk.vtkNamedColors()

    # Create a grid
    grid = vtk.vtkRectilinearGrid()
    grid.SetDimensions(2, 3, 1)

    xArray = vtk.vtkDoubleArray()
    xArray.InsertNextValue(0.0)
    xArray.InsertNextValue(2.0)

    yArray = vtk.vtkDoubleArray()
    yArray.InsertNextValue(0.0)
    yArray.InsertNextValue(1.0)
    yArray.InsertNextValue(2.0)

    zArray = vtk.vtkDoubleArray()
    zArray.InsertNextValue(0.0)

    grid.SetXCoordinates(xArray)
    grid.SetYCoordinates(yArray)
    grid.SetZCoordinates(zArray)

    print('There are', grid.GetNumberOfPoints(), 'points.')
    print('There are', grid.GetNumberOfCells(), 'cells.')

    for id in range(0, grid.GetNumberOfPoints()):
        p = [0] * 3
        p = grid.GetPoint(id)
        print('Point', id, ':(', p[0], ',', p[1], ',', p[2], ')')

    # Create a mapper and actor
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputData(grid)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName('RectilinearGrid')

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

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

    renderWindow.Render()
    renderWindowInteractor.Start()
Exemple #16
0
def writeVTR(vtr_name, scalar_fields, vector_fields, vtkX, vtkY, vtkZ, localZrange):
    """Writes a single VTR file per Python processor/variable

    Parameters:
     vtr_name - name of the VTR file
     scalar_fields - dictionary with scalar field arrays ordered [x, y, z], e.g. {'p': array[nx,ny,nz], 'rho0': array[nx,ny,nz]}
     vector_fields - dictionary with vector fields ordered [3, x, y, z], e.g. {'J': array[3,nx,ny,nz], 'B': array[3,nx,ny,nz]}
     vtkX, vtkY, vtkZ - VTR coordinates, see createVtrCoordinates()
     localZrange - local range for Z indices

    """

    Nx = vtkX.GetNumberOfTuples() - 1
    Ny = vtkY.GetNumberOfTuples() - 1
    Nz=0 #2D
    numpoints = (Nx+1)*(Ny+1)*(Nz+1)
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetExtent(0, Nx, 0, Ny, localZrange[0], localZrange[1]) 
    rtg.SetXCoordinates(vtkX)
    rtg.SetYCoordinates(vtkY)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(0,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints*3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0,3).swapaxes(1,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints*3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()                                                                                              
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
def gocad2simpegMeshIndex(gcFile,mesh,extractBoundaryCells=True,extractInside=True):
    """"
    Function to read gocad polystructure file and output indexes of mesh with in the structure.

    """

    # Make the polydata
    polyData = gocad2vtp(gcFile)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx,mesh.nNy,mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx,deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy,deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz,deep=1))
    # Add indexes cell data to the object
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC),deep=1)
    vtkInd.SetName('Index')
    vtkMesh.GetCellData().AddArray(vtkInd)

    # Define the extractGeometry
    extractImpDistRectGridFilt = vtk.vtkExtractGeometry() # Object constructor
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc) #
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    # Set extraction type
    if extractBoundaryCells is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()
    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if extractInside is True:
        extractImpDistRectGridFilt.ExtractInsideOn()
    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print "Extracting indices from grid..."
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index'))


    # Return the indexes inside
    return insideGrid
Exemple #18
0
    def set_vtk_data(self):
        """

        :return:
        """
        div1 = np.linspace(self.x_min, self.x_max, self.N)
        div2 = np.linspace(self.y_min, self.y_max, self.N)
        self.n3 = np.zeros_like(div1)
        self.n1, self.n2 = np.meshgrid(div1, div2)
        self.grid_nodes = np.array([
            self.n1,
            self.n2,
        ])

        #   predefine vtk array
        x = vtk.vtkFloatArray()
        y = vtk.vtkFloatArray()
        z = vtk.vtkFloatArray()

        N = len(self.n1.flatten())

        for n1_i in self.n1.flatten():
            x.InsertNextValue(n1_i)

        for n2_i in self.n2.flatten():
            y.InsertNextValue(n2_i)

        for n3_i in self.n3.flatten():
            z.InsertNextValue(n3_i)

        self.vtk_grid = vtk.vtkRectilinearGrid()
        self.vtk_grid.SetDimensions(N, N, N)
        self.vtk_grid.SetXCoordinates(x)
        self.vtk_grid.SetYCoordinates(y)
        self.vtk_grid.SetZCoordinates(z)

        #   extract a plane from the grid to see what we've got
        self.vtk_plane = vtk.vtkRectilinearGridGeometryFilter()
        self.vtk_plane.SetInputData(self.vtk_grid)
        self.vtk_plane.SetExtent(0, N - 1, 0, N - 1, 0, 0)

        self.vtk_mapper = vtk.vtkPolyDataMapper()
        self.vtk_mapper.SetInputConnection(self.vtk_plane.GetOutputPort())

        self.vtk_actor = vtk.vtkActor()
        self.vtk_actor.SetMapper(self.vtk_mapper)
        self.vtk_actor.GetProperty().SetRepresentationToWireframe()
        # self.vtk_actor.GetProperty().SetColor(self.color)
        self.vtk_actor.GetProperty().SetColor(.5, .5, .5)
Exemple #19
0
def writeVTR(vtr_name, scalar_fields, vector_fields, Nxc, Nyc, Nzlocal,
             vtkXcoordinates, vtkYcoordinates, vtkZcoordinates, rankproc,
             numproc):
    """Writes a single VTR file per Python processor/variable

    """
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetDimensions(Nxc + 1, Nyc + 1, Nzlocal)
    rtg.SetExtent(0, Nxc, 0, Nyc, rankproc * Nzc / numproc,
                  (rankproc + 1) * Nzc / numproc)
    rtg.SetXCoordinates(vtkXcoordinates)
    rtg.SetYCoordinates(vtkYcoordinates)
    rtg.SetZCoordinates(vtkZcoordinates)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(
            0, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints * 3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0, 3).swapaxes(
            1, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints * 3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Exemple #20
0
def build_plane(position, params, colour):
    """
    Generates floor plane using individual layered rectilinear grids   
    """
    x = np.arange(params[0], params[1], params[2])
    y = np.arange(params[0], params[1], params[2])
    z = np.arange(params[0], params[1], params[2])

    # Create a rectilinear grid by defining three arrays specifying the
    # coordinates in the x-y-z directions.
    x_coords = vtk.vtkFloatArray()
    for i in x:
        x_coords.InsertNextValue(i)
    
    y_coords = vtk.vtkFloatArray()
    for i in y:
        y_coords.InsertNextValue(i)
        
    z_coords = vtk.vtkFloatArray()
    for i in z:
        z_coords.InsertNextValue(i)
    
    # The coordinates are assigned to the rectilinear grid. Make sure that
    # the number of values in each of the XCoordinates, YCoordinates,
    # and ZCoordinates is equal to what is defined in SetDimensions().
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(len(x), len(y), len(z))
    rgrid.SetXCoordinates(x_coords)
    rgrid.SetYCoordinates(y_coords)
    rgrid.SetZCoordinates(z_coords)
    
    # Extract a plane from the grid
    plane = vtk.vtkRectilinearGridGeometryFilter()
    plane.SetInputData(rgrid)
    plane.SetExtent(0, 46, 0, 46, 0, 0)

    rgrid_mapper = vtk.vtkPolyDataMapper()
    rgrid_mapper.SetInputConnection(plane.GetOutputPort())
    
    wire_actor = vtk.vtkActor()
    wire_actor.SetMapper(rgrid_mapper)
    wire_actor.GetProperty().SetRepresentationToWireframe()
    wire_actor.GetProperty().SetColor(colour)
    wire_actor.SetOrientation(0, 0, 90)
    wire_actor.GetProperty().LightingOff()
    wire_actor.SetPosition(3000, -2000, position)
    
    return wire_actor
Exemple #21
0
 def createVTKGridFromCoordinates(_x, _y, _z):
     xCoords = vtk.vtkFloatArray()
     for i in _x:
         xCoords.InsertNextValue(i)
     yCoords = vtk.vtkFloatArray()
     for i in _y:
         yCoords.InsertNextValue(i)
     zCoords = vtk.vtkFloatArray()
     for i in _z:
         zCoords.InsertNextValue(i)
     rgrid = vtk.vtkRectilinearGrid()
     rgrid.SetDimensions(len(_x), len(_y), len(_z))
     rgrid.SetXCoordinates(xCoords)
     rgrid.SetYCoordinates(yCoords)
     rgrid.SetZCoordinates(zCoords)
     return rgrid
Exemple #22
0
    def __tensor_mesh_to_vtk(mesh, models=None):
        """
        Constructs a :class:`pyvista.RectilinearGrid`
        (or a :class:`pyvista.StructuredGrid`) object of this tensor mesh and the
        given models as ``cell_arrays`` of that grid.
        If the mesh is defined on a normal cartesian system then a rectilinear
        grid is generated. Otherwise, a structured grid is generated.

        Parameters
        ----------

        mesh : discretize.TensorMesh
            The tensor mesh to convert to a :class:`pyvista.RectilinearGrid`

        models : dict(numpy.ndarray)
            Name('s) and array('s). Match number of cells

        """
        # Deal with dimensionalities
        if mesh.dim >= 1:
            vX = mesh.vectorNx
            xD = mesh.nNx
            yD, zD = 1, 1
            vY, vZ = np.array([0, 0])
        if mesh.dim >= 2:
            vY = mesh.vectorNy
            yD = mesh.nNy
        if mesh.dim == 3:
            vZ = mesh.vectorNz
            zD = mesh.nNz
        # If axis orientations are standard then use a vtkRectilinearGrid
        if not mesh.reference_is_rotated:
            # Use rectilinear VTK grid.
            # Assign the spatial information.
            output = vtk.vtkRectilinearGrid()
            output.SetDimensions(xD, yD, zD)
            output.SetXCoordinates(nps.numpy_to_vtk(vX, deep=1))
            output.SetYCoordinates(nps.numpy_to_vtk(vY, deep=1))
            output.SetZCoordinates(nps.numpy_to_vtk(vZ, deep=1))
            return assign_cell_data(output, models=models)
        # Use a structured grid where points are rotated to the cartesian system
        ptsMat = InterfaceVTK.__get_rotated_nodes(mesh)
        dims = [mesh.nCx, mesh.nCy, mesh.nCz]
        # Assign the model('s) to the object
        return InterfaceVTK.__create_structured_grid(ptsMat,
                                                     dims,
                                                     models=models)
Exemple #23
0
def writeVTR(vtr_name, scalar_fields, vector_fields, Nxc, Nyc, Nzlocal, 
            vtkXcoordinates, vtkYcoordinates, vtkZcoordinates, rankproc, numproc):
    """Writes a single VTR file per Python processor/variable

    """
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetDimensions(Nxc+1, Nyc+1, Nzlocal)
    rtg.SetExtent(0, Nxc, 0, Nyc, rankproc*Nzc/numproc, (rankproc+1)*Nzc/numproc)
    rtg.SetXCoordinates(vtkXcoordinates)
    rtg.SetYCoordinates(vtkYcoordinates)
    rtg.SetZCoordinates(vtkZcoordinates)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(0,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints*3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0,3).swapaxes(1,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints*3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()                                                                                              
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Exemple #24
0
    def _query_mesh(self, xlim, ylim, xtire, ytire, rtire):
        """Use VTK structured grid to generate query mesh. This is also the mesh of final superposition results.
        Args:
            *lim: [min, max] range for xy directions
            *tire [n x 1 vec]: unique tire coordinates in x & y directions
            rtire [num]: tire radius to be densified
        Return:
            [N x 3 mat]: N grid points (x,y,z) of the query mesh.
        Note:
            query mesh will include the grid points & evaluation points at all depth
            In VTK there are 3 types of "structured" grids:
            - vtkImageData (vtkUniformGrid): constant spacing & axis aligned
            - vtkRectilinearGrid: axis aligned & vary spacing
            - vtkStructuredGrid: arbitrarily located points (cells may not be valid).
        """
        # 1. Generate densified XYZ axis coordinates
        spacing_sparse = rtire * cfg.SPACING_SPARSE_2D
        spacing_dense = rtire * cfg.SPACING_DENSE_2D
        xranges = np.hstack([(xtire - rtire).reshape(-1, 1),
                             (xtire + rtire).reshape(-1, 1)])
        yranges = np.hstack([(ytire - rtire).reshape(-1, 1),
                             (ytire + rtire).reshape(-1, 1)])
        xcoords = self._nonlinear_spacing(xlim, xranges, spacing_dense,
                                          spacing_sparse)
        ycoords = self._nonlinear_spacing(ylim, yranges, spacing_dense,
                                          spacing_sparse)
        zcoords = cfg.DEPTH_COORDS

        # 2. Generate VTK rectilinear grid
        grid = vtk.vtkRectilinearGrid()
        grid.SetDimensions(len(xcoords), len(ycoords),
                           len(zcoords))  # initialize mesh space
        print("> Query mesh generated with {} superposition points".format(
            grid.GetNumberOfPoints()))
        grid.SetXCoordinates(numpy_to_vtk(xcoords))
        grid.SetYCoordinates(numpy_to_vtk(ycoords))
        grid.SetZCoordinates(numpy_to_vtk(zcoords))

        coord = vtk.vtkPoints()
        grid.GetPoints(coord)

        self.queryMesh = grid

        return vtk_to_numpy(coord.GetData())  # N x 3
Exemple #25
0
	def makeCellVTKObject(mesh,model):
		"""
		Make and return a cell based VTK object for a simpeg mesh and model.

		Input:
		:param mesh, SimPEG TensorMesh object - mesh to be transfer to VTK
		:param model, dictionary of numpy.array - Name('s) and array('s). Match number of cells

		Output:
        :rtype: vtkRecilinearGrid object
        :return: vtkObj
		"""

		# Deal with dimensionalities
		if mesh.dim >= 1:
			vX = mesh.vectorNx
			xD = mesh.nNx
			yD,zD = 1,1
			vY, vZ = np.array([0,0])
		if mesh.dim >= 2:
			vY = mesh.vectorNy
			yD = mesh.nNy
		if mesh.dim == 3:
			vZ = mesh.vectorNz
			zD = mesh.nNz
		# Use rectilinear VTK grid.
		# Assign the spatial information.
		vtkObj = vtk.vtkRectilinearGrid()
		vtkObj.SetDimensions(xD,yD,zD)
		vtkObj.SetXCoordinates(npsup.numpy_to_vtk(vX,deep=1))
		vtkObj.SetYCoordinates(npsup.numpy_to_vtk(vY,deep=1))
		vtkObj.SetZCoordinates(npsup.numpy_to_vtk(vZ,deep=1))

		# Assign the model('s) to the object
		for item in model.iteritems():
			# Convert numpy array
			vtkDoubleArr = npsup.numpy_to_vtk(item[1],deep=1)
			vtkDoubleArr.SetName(item[0])
			vtkObj.GetCellData().AddArray(vtkDoubleArr)

		vtkObj.GetCellData().SetActiveScalars(model.keys()[0])
		vtkObj.Update()
		return vtkObj
Exemple #26
0
    def testRectilinear(self):
        rt = vtk.vtkRTAnalyticSource()
        rt.SetWholeExtent(-5, 5, -5, 5, -5, 5)
        rt.Update()
        i = rt.GetOutput()

        r = vtk.vtkRectilinearGrid()
        dims = i.GetDimensions()
        r.SetDimensions(dims)
        exts = i.GetExtent()
        orgs = i.GetOrigin()

        xs = vtk.vtkFloatArray()
        xs.SetNumberOfTuples(dims[0])
        for d in range(dims[0]):
            xs.SetTuple1(d, orgs[0] + exts[0] + d)
        r.SetXCoordinates(xs)

        ys = vtk.vtkFloatArray()
        ys.SetNumberOfTuples(dims[1])
        for d in range(dims[1]):
            ys.SetTuple1(d, orgs[1] + exts[2] + d)
        r.SetYCoordinates(ys)

        zs = vtk.vtkFloatArray()
        zs.SetNumberOfTuples(dims[2])
        for d in range(dims[2]):
            zs.SetTuple1(d, orgs[2] + exts[4] + d)
        r.SetZCoordinates(zs)

        s = vtk.vtkSphere()
        s.SetRadius(2)
        s.SetCenter(0,0,0)

        c = vtk.vtkTableBasedClipDataSet()
        c.SetInputData(r)
        c.SetClipFunction(s)
        c.SetInsideOut(1)

        c.Update()

        self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
    def testRectilinear(self):
        rt = vtk.vtkRTAnalyticSource()
        rt.SetWholeExtent(-5, 5, -5, 5, -5, 5)
        rt.Update()
        i = rt.GetOutput()

        r = vtk.vtkRectilinearGrid()
        dims = i.GetDimensions()
        r.SetDimensions(dims)
        exts = i.GetExtent()
        orgs = i.GetOrigin()

        xs = vtk.vtkFloatArray()
        xs.SetNumberOfTuples(dims[0])
        for d in range(dims[0]):
            xs.SetTuple1(d, orgs[0] + exts[0] + d)
        r.SetXCoordinates(xs)

        ys = vtk.vtkFloatArray()
        ys.SetNumberOfTuples(dims[1])
        for d in range(dims[1]):
            ys.SetTuple1(d, orgs[1] + exts[2] + d)
        r.SetYCoordinates(ys)

        zs = vtk.vtkFloatArray()
        zs.SetNumberOfTuples(dims[2])
        for d in range(dims[2]):
            zs.SetTuple1(d, orgs[2] + exts[4] + d)
        r.SetZCoordinates(zs)

        s = vtk.vtkSphere()
        s.SetRadius(2)
        s.SetCenter(0,0,0)

        c = vtk.vtkTableBasedClipDataSet()
        c.SetInputData(r)
        c.SetClipFunction(s)
        c.SetInsideOut(1)

        c.Update()

        self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
Exemple #28
0
    def getVTKrg(self):
        if not self.cart:
            print('Cylindrical meshtal cannot be plotted to RectangularGrid')

        if np.any(self.rotation != np.identity(3)):
            print('Rotated meshtal cannot be plotted to RectangularGrid')
            print('... but plotting anyway (no rotation)')

        xa = makeVTKarray(self.dims[3] + self.origin[3], 'X (cm)')
        ya = makeVTKarray(self.dims[2] + self.origin[2], 'Y (cm)')
        za = makeVTKarray(self.dims[1] + self.origin[1], 'Z (cm)')

        rg = vtk.vtkRectilinearGrid()
        rg.SetDimensions(self.ldims[3] + 1, self.ldims[2] + 1,
                         self.ldims[1] + 1)
        rg.SetXCoordinates(xa)
        rg.SetYCoordinates(ya)
        rg.SetZCoordinates(za)
        rgcd = rg.GetCellData()
        it = 0
        if self.etag != 'times':
            # Dataset energia total
            it = 1
            rgcd.AddArray(
                makeVTKarray(self.dat[-1, :, :, :], 'Value - Total',
                             self.scaleFac))
            rgcd.AddArray(makeVTKarray(self.err[-1, :, :, :], 'Error - Total'))
        # Dataset other bins
        for ie in range(self.ldims[0] - it):
            rgcd.AddArray(
                makeVTKarray(self.dat[ie, :, :, :],
                             'ValueBin-{0:03d}'.format(ie), self.scaleFac))
            rgcd.AddArray(
                makeVTKarray(self.err[ie, :, :, :],
                             'ErrorBin-{0:03d}'.format(ie)))
        return rg
Exemple #29
0
def main():
    colors = vtk.vtkNamedColors()

    x = [-1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, -0.911458, -0.859375, -0.807292, -0.755208,
         -0.703125, -0.651042, -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, -0.286458, -0.234375,
         -0.182292, -0.130209, -0.078125, -0.026042, 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458,
         0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, 0.651042, 0.703125, 0.755208, 0.807292, 0.859375,
         0.911458, 0.963542, 1.01562, 1.06771, 1.11979, 1.17188]
    y = [-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, -0.78125, -0.703125, -0.625, -0.546875, -0.46875,
         -0.390625, -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, 0.15625, 0.234375, 0.3125, 0.390625, 0.46875,
         0.546875, 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, 1.09375, 1.17188, 1.25]
    z = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.75, 1.8, 1.9, 2,
         2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.75, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, 3.8, 3.9]
    print(len(x), len(y), len(z))

    # Create a rectilinear grid by defining three arrays specifying the
    # coordinates in the x-y-z directions.
    xCoords = vtk.vtkDoubleArray()
    for i in range(0, len(x)):
        xCoords.InsertNextValue(x[i])
    yCoords = vtk.vtkDoubleArray()
    for i in range(0, len(y)):
        yCoords.InsertNextValue(y[i])
    zCoords = vtk.vtkDoubleArray()
    for i in range(0, len(z)):
        zCoords.InsertNextValue(z[i])

    # The coordinates are assigned to the rectilinear grid. Make sure that
    # the number of values in each of the XCoordinates, YCoordinates,
    # and ZCoordinates is equal to what is defined in SetDimensions().
    #
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(len(x), len(y), len(z))
    rgrid.SetXCoordinates(xCoords)
    rgrid.SetYCoordinates(yCoords)
    rgrid.SetZCoordinates(zCoords)

    # Extract a plane from the grid to see what we've got.
    plane = vtk.vtkRectilinearGridGeometryFilter()
    plane.SetInputData(rgrid)
    plane.SetExtent(0, len(x) - 1, 16, 16, 0, len(z) - 1)

    rgridMapper = vtk.vtkPolyDataMapper()
    rgridMapper.SetInputConnection(plane.GetOutputPort())

    wireActor = vtk.vtkActor()
    wireActor.SetMapper(rgridMapper)
    wireActor.GetProperty().SetColor(colors.GetColor3d("Banana"))
    wireActor.GetProperty().EdgeVisibilityOn()

    # Create the usual rendering stuff.
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renderer.AddActor(wireActor)
    renderer.SetBackground(colors.GetColor3d("Beige"))
    renderer.ResetCamera()
    renderer.GetActiveCamera().Elevation(60.0)
    renderer.GetActiveCamera().Azimuth(30.0)
    renderer.GetActiveCamera().Zoom(1.0)

    renWin.SetSize(640, 480)

    # Interact with the data.
    renWin.Render()
    iren.Start()
Exemple #30
0
    assert (r.GetOutput().GetOrigin() == (5, 5, 5))

    w.SetInputData(d)
    w.SetFileName("test-dim.vtk")
    w.SetWriteExtent(True)
    w.Write()

    r.Modified()
    r.Update()

    os.remove("test-dim.vtk")

    assert (r.GetOutput().GetExtent() == (5, 10, 5, 10, 5, 10))
    assert (r.GetOutput().GetOrigin() == (0, 0, 0))

    rg = vtk.vtkRectilinearGrid()
    extents = (1, 3, 1, 3, 1, 3)
    rg.SetExtent(extents)
    pts = vtk.vtkFloatArray()
    pts.InsertNextTuple1(0)
    pts.InsertNextTuple1(1)
    pts.InsertNextTuple1(2)
    rg.SetXCoordinates(pts)
    rg.SetYCoordinates(pts)
    rg.SetZCoordinates(pts)

    w = vtk.vtkRectilinearGridWriter()
    w.SetInputData(rg)
    w.SetFileName("test-dim.vtk")
    w.Write()
def GetSource(dataType):
    s = vtk.vtkRTAnalyticSource()

    if dataType == 'ImageData':
        return s

    elif dataType == 'UnstructuredGrid':
        dst = vtk.vtkDataSetTriangleFilter()
        dst.SetInputConnection(s.GetOutputPort())
        return dst

    elif dataType == 'RectilinearGrid':
        s.Update()

        input = s.GetOutput()

        rg = vtk.vtkRectilinearGrid()
        rg.SetExtent(input.GetExtent())
        dims = input.GetDimensions()
        spacing = input.GetSpacing()

        x = vtk.vtkFloatArray()
        x.SetNumberOfTuples(dims[0])
        for i in range(dims[0]):
            x.SetValue(i, spacing[0]*i)

        y = vtk.vtkFloatArray()
        y.SetNumberOfTuples(dims[1])
        for i in range(dims[1]):
            y.SetValue(i, spacing[1]*i)

        z = vtk.vtkFloatArray()
        z.SetNumberOfTuples(dims[2])
        for i in range(dims[2]):
            z.SetValue(i, spacing[2]*i)

        rg.SetXCoordinates(x)
        rg.SetYCoordinates(y)
        rg.SetZCoordinates(z)

        rg.GetPointData().ShallowCopy(input.GetPointData())

        pf.SetInputData(rg)
        return pf

    elif dataType == 'StructuredGrid':
        s.Update()

        input = s.GetOutput()

        sg = vtk.vtkStructuredGrid()
        sg.SetExtent(input.GetExtent())
        pts = vtk.vtkPoints()
        sg.SetPoints(pts)
        npts = input.GetNumberOfPoints()
        for i in range(npts):
            pts.InsertNextPoint(input.GetPoint(i))
        sg.GetPointData().ShallowCopy(input.GetPointData())

        pf.SetInputData(sg)
        return pf

    elif dataType == 'Table':
        s.Update()
        input = s.GetOutput()

        table = vtk.vtkTable()
        RTData = input.GetPointData().GetArray(0)
        nbTuples = RTData.GetNumberOfTuples()

        array = vtk.vtkFloatArray()
        array.SetName("RTData")
        array.SetNumberOfTuples(nbTuples)

        for i in range(0, nbTuples):
            array.SetTuple1(i, float(RTData.GetTuple1(i)))

        table.AddColumn(array)

        pf.SetInputData(table)
        return pf
Exemple #32
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import vtk
import numpy as np
from vtk.util import numpy_support

px = np.linspace(0.0, 10.0, 11)
py = np.linspace(0.0, 5.0, 6)
pz = np.linspace(0.0, 8.0, 9)
print px.size

rgrid = vtk.vtkRectilinearGrid()
rgrid.SetDimensions(px.size, py.size, pz.size)
rgrid.SetXCoordinates(numpy_support.numpy_to_vtk(px))
rgrid.SetYCoordinates(numpy_support.numpy_to_vtk(py))
rgrid.SetZCoordinates(numpy_support.numpy_to_vtk(pz))

print numpy_support.numpy_to_vtk(px)

mapper = vtk.vtkDataSetMapper()
mapper.SetInputData(rgrid)
#mapper.ScalarVisibilityOff()

actor = vtk.vtkActor()
actor.GetProperty().SetRepresentationToWireframe()
actor.GetProperty().SetColor(0, 0, 0)
actor.SetMapper(mapper)

ren = vtk.vtkRenderer()
ren.SetBackground(0.1, 0.2, 0.4)
Exemple #33
0
classWindowsExceptions = set([
"vtkWin32VideoSource", # Update() works the first time but a subsequent run calls up the webcam which crashes on close.

"vtkCMLMoleculeReader",
"vtkCPExodusIIInSituReader",
"vtkMINCImageWriter",
"vtkQtInitialization"
])

classExceptions = set()

emptyPD = vtk.vtkPolyData()
emptyID = vtk.vtkImageData()
emptySG = vtk.vtkStructuredGrid()
emptyUG = vtk.vtkUnstructuredGrid()
emptyRG = vtk.vtkRectilinearGrid()

# This will hold the classes to be tested.
vtkClasses = set()
classNames = None

# Keep a record of the classes tested.
nonexistentClasses = set()
abstractClasses = set()
noConcreteImplementation = set()
noUpdate = set()
noShutdown = set()
noSetInput = set()
noObserver = set()
emptyInputWorked = set()
emptyInputFailed = set()
Exemple #34
0
def GetSource(dataType):
    s = vtk.vtkRTAnalyticSource()
    # Fake serial source
    if rank == 0:
        s.Update()

    if dataType == 'ImageData':
        return s.GetOutput()

    elif dataType == 'UnstructuredGrid':
        dst = vtk.vtkDataSetTriangleFilter()
        dst.SetInputData(s.GetOutput())
        dst.Update()
        return dst.GetOutput()

    elif dataType == 'RectilinearGrid':

        input = s.GetOutput()

        rg = vtk.vtkRectilinearGrid()
        rg.SetExtent(input.GetExtent())
        dims = input.GetDimensions()
        spacing = input.GetSpacing()

        x = vtk.vtkFloatArray()
        x.SetNumberOfTuples(dims[0])
        for i in range(dims[0]):
            x.SetValue(i, spacing[0]*i)

        y = vtk.vtkFloatArray()
        y.SetNumberOfTuples(dims[1])
        for i in range(dims[1]):
            y.SetValue(i, spacing[1]*i)

        z = vtk.vtkFloatArray()
        z.SetNumberOfTuples(dims[2])
        for i in range(dims[2]):
            z.SetValue(i, spacing[2]*i)

        rg.SetXCoordinates(x)
        rg.SetYCoordinates(y)
        rg.SetZCoordinates(z)

        rg.GetPointData().ShallowCopy(input.GetPointData())

        return rg

    elif dataType == 'StructuredGrid':

        input = s.GetOutput()

        sg = vtk.vtkStructuredGrid()
        sg.SetExtent(input.GetExtent())
        pts = vtk.vtkPoints()
        sg.SetPoints(pts)
        npts = input.GetNumberOfPoints()
        for i in xrange(npts):
            pts.InsertNextPoint(input.GetPoint(i))
        sg.GetPointData().ShallowCopy(input.GetPointData())

        return sg
Exemple #35
0
    def getvtkdata(self, ci, timestep):
        PI= 3.141592654
        contour=False
        firstval = ci.datafields.split(',')[0]
        #print ("First: ", firstval)
        if ((firstval == 'vo') or (firstval == 'qc') or (firstval == 'cvo') or (firstval == 'pcvo') or (firstval == 'qcc')):
            datafields = 'u'
            computation = firstval #We are doing a computation, so we need to know which one.
            if ((firstval == 'cvo') or (firstval == 'qcc') or (firstval == 'pcvo')):
                overlap = 3 #This was 2, but due to rounding because of the spacing, 3 is required.
                #Save a copy of the original request
                oci = jhtdblib.CutoutInfo()
                oci.xstart = ci.xstart
                oci.ystart = ci.ystart
                oci.zstart = ci.zstart
                oci.xlen = ci.xlen
                oci.ylen = ci.ylen
                oci.zlen = ci.zlen
                ci = self.expandcutout(ci, overlap) #Expand the cutout by the overlap
                contour = True               
        else:
            datafields = ci.datafields.split(',') #There could be multiple components, so we will have to loop
            computation = ''
        #Split component into list and add them to the image

        #Check to see if we have a value for vorticity or q contour
        fieldlist = list(datafields)
        image = vtk.vtkImageData()
        rg = vtk.vtkRectilinearGrid()              
        for field in fieldlist:
            if (ci.xlen > 61 and ci.ylen > +61 and ci.zlen > 61 and ci.xstep ==1 and ci.ystep ==1 and ci.zstep ==1 and not contour):
                #Do this if cutout is too large
                #Note: we don't want to get cubed data if we are doing cubes for contouring.
                data=GetData().getcubedrawdata(ci, timestep, field)
            else:
                data=GetData().getrawdata(ci, timestep, field)                  
            vtkdata = numpy_support.numpy_to_vtk(data.flat, deep=True, array_type=vtk.VTK_FLOAT)            
            components = Datafield.objects.get(shortname=field).components
            vtkdata.SetNumberOfComponents(components)
            vtkdata.SetName(Datafield.objects.get(shortname=field).longname)  
            
            #We need to see if we need to subtract one on end of extent edges.
            image.SetExtent(ci.xstart, ci.xstart+((ci.xlen+ci.xstep-1)/ci.xstep)-1, ci.ystart, ci.ystart+((ci.ylen+ci.ystep-1)/ci.ystep)-1, ci.zstart, ci.zstart+((ci.zlen+ci.zstep-1)/ci.zstep)-1)
            #image.SetExtent(ci.xstart, ci.xstart+int(ci.xlen)-1, ci.ystart, ci.ystart+int(ci.ylen)-1, ci.zstart, ci.zstart+int(ci.zlen)-1)
            image.GetPointData().AddArray(vtkdata)
            if (Datafield.objects.get(shortname=field).longname == "Velocity"):
                #Set the Velocity Array as vectors in the image.
                image.GetPointData().SetVectors(image.GetPointData().GetArray("Velocity"))
#Get spacing from database and multiply it by the step.  Don't do this on the contour--it is performed later on.
            #if (contour):
                #We need to scale the threshold to the spacing of the dataset.  This is because we build the cubes
                #on a 1 spacing cube in order to get proper overlap on the contours.  
                #ci.threshold = ci.threshold*Dataset.objects.get(dbname_text=ci.dataset).xspacing
            #else:
            xspacing = Dataset.objects.get(dbname_text=ci.dataset).xspacing
            yspacing = Dataset.objects.get(dbname_text=ci.dataset).yspacing
            zspacing = Dataset.objects.get(dbname_text=ci.dataset).zspacing  


            #Check if we need a rectilinear grid, and set it up if so.
            if (ci.dataset == 'channel'):
                ygrid = jhtdblib.JHTDBLib().getygrid()
                #print("Ygrid: ")
                #print (ygrid)                
                #Not sure about contouring channel yet, so we are going back to original variables at this point.
                rg.SetExtent(ci.xstart, ci.xstart+((ci.xlen+ci.xstep-1)/ci.xstep)-1, ci.ystart, ci.ystart+((ci.ylen+ci.ystep-1)/ci.ystep)-1, ci.zstart, ci.zstart+((ci.zlen+ci.zstep-1)/ci.zstep)-1)
                #components = Datafield.objects.get(shortname=field).components
                #vtkdata.SetNumberOfComponents(components)
                #vtkdata.SetName(Datafield.objects.get(shortname=field).longname)
                rg.GetPointData().AddArray(vtkdata)
                #import pdb;pdb.set_trace()
                #This isn't possible--we will have to do something about this in the future.
                #rg.SetSpacing(ci.xstep,ci.ystep,ci.zstep)
                xg = np.arange(0,2047.0)
                zg = np.arange(0,1535.0)
                for x in xg:
                        xg[x] = 8*PI/2048*x
                for z in zg:
                        zg[z] = 3*PI/2048*z
                vtkxgrid=numpy_support.numpy_to_vtk(xg, deep=True,
                    array_type=vtk.VTK_FLOAT)
                vtkzgrid=numpy_support.numpy_to_vtk(zg, deep=True,
                    array_type=vtk.VTK_FLOAT)
                vtkygrid=numpy_support.numpy_to_vtk(ygrid,
                    deep=True, array_type=vtk.VTK_FLOAT)
                rg.SetXCoordinates(vtkxgrid)
                rg.SetZCoordinates(vtkzgrid)
                rg.SetYCoordinates(vtkygrid)
                image = rg #we rewrite the image since we may be doing a
                           #computation below
            else:
                image.SetSpacing(xspacing*ci.xstep,yspacing*ci.ystep,zspacing*ci.zstep)
        #See if we are doing a computation
        if (computation == 'vo'):
            start = time.time()
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            vorticity.SetInputData(image)
            #print("Computing Vorticity")
            vorticity.Update()
            end = time.time()
            comptime = end-start
            print("Vorticity Computation time: " + str(comptime) + "s")
            return image
        elif (computation == 'cvo' or computation == 'pcvo'):
            start = time.time()
            
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            
            vorticity.SetInputData(image)
            #print("Computing Voricity")
            vorticity.Update()
            vend = time.time()
            comptime = vend-start
            print("Vorticity Computation time: " + str(comptime) + "s")
            mag = vtk.vtkImageMagnitude()
            cp = vtk.vtkCellDataToPointData()
            cp.SetInputData(vorticity.GetOutput())
            #print("Computing magnitude")
            cp.Update()
            mend = time.time()
            image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
            mag.SetInputData(image)
            mag.Update()
            comptime = mend-vend
            print("Magnitude Computation time: " + str(comptime) + "s")
            c = vtk.vtkContourFilter()
            c.SetValue(0,ci.threshold)
            c.SetInputData(mag.GetOutput())
            print("Computing Contour with threshold", ci.threshold)
            c.Update()
            cend = time.time()
            comptime = cend-mend
            print("Contour Computation time: " + str(comptime) + "s")
            #Now we need to clip out the overlap
            box = vtk.vtkBox()    
            #set box to requested size
            #The OCI deepcopy didn't seem to work.  Manually taking the overlap again.
            box.SetBounds(oci.xstart*xspacing, (oci.xstart+oci.xlen)*xspacing, oci.ystart*yspacing, (oci.ystart+oci.ylen)*yspacing, oci.zstart*yspacing,(oci.zstart+oci.zlen)*yspacing)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            #import pdb;pdb.set_trace()
            cropdata = clip.GetOutput()
            #Cleanup
            image.ReleaseData()
            #mag.ReleaseData()
            #box.ReleaseData()
            #clip.ReleaseData()
            #image.Delete()
            #box.Delete()
            #vorticity.Delete()
            end = time.time()
            comptime = end-start
            print("Total Computation time: " + str(comptime) + "s")
            #return cropdata
            #We need the output port for appending, so return the clip instead
            return clip

        elif (computation == 'qcc'):
            start = time.time()
            q = vtk.vtkGradientFilter()
            q.SetInputData(image)
            q.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
            q.ComputeQCriterionOn()
            q.Update()
            image.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion"))
            #mag = vtk.vtkImageMagnitude()
            #mag.SetInputData(image)
            #mag.Update()
            mend = time.time()
            comptime = mend-start
            #print("Magnitude Computation time: " + str(comptime) + "s")
            c = vtk.vtkContourFilter()
            c.SetValue(0,ci.threshold)
            c.SetInputData(image)
            print("Computing Contour with threshold", ci.threshold)
            c.Update()
            cend = time.time()
            comptime = cend-mend
            print("Q Contour Computation time: " + str(comptime) + "s")
            #clip out the overlap here
            box = vtk.vtkBox()    
            #set box to requested size
            box.SetBounds(oci.xstart, oci.xstart+oci.xlen-1, oci.ystart, oci.ystart+oci.ylen-1, oci.zstart,oci.zstart+oci.zlen-1)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            cropdata = clip.GetOutput()
            end = time.time()
            comptime = end-start
            print("Computation time: " + str(comptime) + "s")
            #return cropdata
            return clip
        else:
            return image
Exemple #36
0
# create the vtr grid
xArray = vtk.vtkDoubleArray()
for val in sorted(x):
    xArray.InsertNextValue(val)

yArray = vtk.vtkDoubleArray()
for val in sorted(y):
    yArray.InsertNextValue(val)

zArray = vtk.vtkDoubleArray()
for val in sorted(z):
    zArray.InsertNextValue(val)


# create the vtkRectilinearGrid
grid = vtk.vtkRectilinearGrid()
grid.SetDimensions(xArray.GetNumberOfTuples(), yArray.GetNumberOfTuples(), zArray.GetNumberOfTuples())
grid.SetXCoordinates(xArray)
grid.SetYCoordinates(yArray)
grid.SetZCoordinates(zArray)
grid.Update()


# the ordering of points inside the vtkRectilinearGrid might be different
# from that in the grid file, so a map between them is needed
if opts.verbose:
    sys.stdout.write("Creating map from (x,y,z) points to index in griddeddata function values\n")
nx = len(x)
ny = len(y)
nz = len(z)
grid_index = {} # given a point, this gives the index in fcn
Exemple #37
0
def GetSource(dataType):
    s = vtk.vtkRTAnalyticSource()

    if dataType == 'ImageData':
        return s

    elif dataType == 'UnstructuredGrid':
        dst = vtk.vtkDataSetTriangleFilter()
        dst.SetInputConnection(s.GetOutputPort())
        return dst

    elif dataType == 'RectilinearGrid':
        s.Update()

        input = s.GetOutput()

        rg = vtk.vtkRectilinearGrid()
        rg.SetExtent(input.GetExtent())
        dims = input.GetDimensions()
        spacing = input.GetSpacing()

        x = vtk.vtkFloatArray()
        x.SetNumberOfTuples(dims[0])
        for i in range(dims[0]):
            x.SetValue(i, spacing[0] * i)

        y = vtk.vtkFloatArray()
        y.SetNumberOfTuples(dims[1])
        for i in range(dims[1]):
            y.SetValue(i, spacing[1] * i)

        z = vtk.vtkFloatArray()
        z.SetNumberOfTuples(dims[2])
        for i in range(dims[2]):
            z.SetValue(i, spacing[2] * i)

        rg.SetXCoordinates(x)
        rg.SetYCoordinates(y)
        rg.SetZCoordinates(z)

        rg.GetPointData().ShallowCopy(input.GetPointData())

        pf.SetInputData(rg)
        return pf

    elif dataType == 'StructuredGrid':
        s.Update()

        input = s.GetOutput()

        sg = vtk.vtkStructuredGrid()
        sg.SetExtent(input.GetExtent())
        pts = vtk.vtkPoints()
        sg.SetPoints(pts)
        npts = input.GetNumberOfPoints()
        for i in range(npts):
            pts.InsertNextPoint(input.GetPoint(i))
        sg.GetPointData().ShallowCopy(input.GetPointData())

        pf.SetInputData(sg)
        return pf
 def __init__(self):
     self.__mesh = vtk.vtkRectilinearGrid()
     self.__dims = [-1, -1, -1]
Exemple #39
0
    def render_geometry(self, vx, vy, vz, mv, **kwargs):
        """ create geometry """

        self.hasData = False
        gridData = kwargs.get('gridData', True)

        if gridData:
            self.gridfunc = vtk.vtkStructuredGrid()
        else:
            self.gridfunc = vtk.vtkRectilinearGrid()

        # check data structure
        if type(vx) is not numpy.ndarray or type(vy) is not numpy.ndarray:
            logging.error('X,Y vectors must be numpy arrays')
            return False

        if type(vz) is not numpy.ndarray:
            logging.error('Z vector must be numpy array')
            return False

        if isinstance(mv, (list, tuple)) and len(mv) > 0:
            logging.error('V scalars must be numpy array')
            return False

        if len(vx) == 0 or len(vy) == 0 or len(vz) == 0:
            logging.error('Zero size data')
            return False

        mva = isinstance(mv, numpy.ndarray) and mv.any()

        if vz.ndim != 2:
            logging.error('Z must be 2 dimensional numpy matrix')
            return False

        if vz[0].size != vy.size:
            logging.error('Y dimension not match')
            return False

        if vz.transpose()[0].size != vx.size:
            logging.error('X dimension not match')
            return False

        if mva:
            if mv.size != vz.size or vz[0].size != mv[0].size or vz[1].size != mv[1].size:
                logging.error('Z and V dimension not match')
                return False

        Nx = vx.size
        Ny = vy.size
        Nz = vz.size

        # put data, z, into a 2D structured grid
        self.Points = vtk.vtkPoints()
        [self.Points.InsertNextPoint(vx[i], vy[j], vz[i, j]) for j in xrange(Ny) for i in xrange(Nx)]

        if gridData:
            self.gridfunc.SetDimensions(Nx, Ny, 1)
            self.gridfunc.SetPoints(self.Points)
        else:
            xCoords = vtk.vtkFloatArray()
            [xCoords.InsertNextValue(vx[i]) for i in xrange(Nx)]

            yCoords = vtk.vtkFloatArray()
            [yCoords.InsertNextValue(vy[j]) for j in xrange(Ny)]

            s = list(vz.flatten())
            vz = numpy.array(s)
            # vz.sort()
            Nz = vz.size

            zCoords = vtk.vtkFloatArray()
            [zCoords.InsertNextValue(vz[k]) for k in xrange(Nz)]

            vCoords = vtk.vtkFloatArray()
            [vCoords.InsertNextValue(n) for n in xrange(1)]

            self.gridfunc.SetDimensions(Nx, Ny, 1)
            self.gridfunc.SetXCoordinates(xCoords)
            self.gridfunc.SetYCoordinates(yCoords)
            self.gridfunc.SetZCoordinates(vCoords)

        # get scalar field from z/v-values
        self.Colors = vtk.vtkFloatArray()
        self.Colors.SetNumberOfComponents(1)
        self.Colors.SetNumberOfTuples(Nx * Ny)

        pt = mv if mva else vz
        [self.Colors.InsertComponent(i + j * Nx, 0, pt[i, j]) for j in xrange(Ny) for i in xrange(Nx)]

        self.gridfunc.GetPointData().SetScalars(self.Colors)
        self.hasData = True

        # scaling
        Xrange = vx.max() - vx.min()
        Yrange = vy.max() - vy.min()

        # filter none
        Zrange = numpy.nanmax(vz) - numpy.nanmin(vz)

        # must have x or y ranges
        if 0 in (Xrange, Yrange):
            logging.error('Zero X or Y Axis Range: %s', (Xrange, Yrange))
            self.hasData = False
            raise Exception('Zero X or Y Axis Range: %s', (Xrange, Yrange))

        self.XLimit = (vx.min(), vx.max())
        self.YLimit = (vy.min(), vy.max())
        self.ZLimit = (numpy.nanmin(vz), numpy.nanmax(vz))

        # check for constant Z range
        if Zrange == 0:
            Zrange = max(Xrange, Yrange)

        self.XScale = float(Zrange) / float(Xrange)
        self.YScale = float(Zrange) / float(Yrange)
        self.ZScale = float(Zrange) / float(Zrange)

        # fire callbacks
        if self.hasData:
            self.fireCallbacks(callback='OnDataRange')

        logging.debug('Parameters: %s' % str((
            Nx, Ny, Nz, ':', Xrange, Yrange, Zrange, ':', self.XScale, self.YScale,
            self.ZScale, ':', self.XLimit, self.YLimit, self.ZLimit)))

        return self.hasData
def main(args):
    
    
    # Load config file
    config_module = imp.load_source('config', args.config_path)
    
    # Get cfg dict
    cfg = config_module.cfg
    
    # Get model
    model = config_module.get_model(interp=True)
    
    # Compile functions
    print('Compiling theano functions...')
    tfuncs, tvars = make_test_functions(cfg, model)
    
    # Load model weights
    print('Loading weights from {}'.format(args.weights_fname))
    checkpoints.load_weights(args.weights_fname, model['l_latents'])
    checkpoints.load_weights(args.weights_fname, model['l_out'])
    
    # prepare data loader
    loader = (data_loader(cfg, args.testing_fname))

    
    # Load test set into local memory and get inferred latent values for each
    # element of the test set. Consider not doing this if you have limited RAM.
    print('Evaluating on test set')
    ygnd = np.empty([1,1,32,32,32],dtype=np.uint8)
    cc = np.empty([1,10],dtype=np.float32)
    counter = 0
    for x_shared, y_shared in loader:
        ygnd = np.append(ygnd,x_shared,axis=0)
        cc = np.append(cc,y_shared,axis=0) 

    # Get rid of first entries. Yeah, you could do this better by starting with a regular ole' python list,
    # appending inside the for loop and then just calling np.asarray, but I didn't really know any python
    # when I wrote this. Sue me.*
    #
    # *Please don't sue me
    ygnd = np.delete(ygnd,0,axis=0)
    cc = np.delete(cc,0,axis=0)
    
    print('Test set evaluation complete, render time!')
    
    # Total number of models loaded and encoded
    num_instances = len(ygnd)-1;
    
    # Seed the rng for repeatable operation
    np.random.seed(1)
    
    # Index of shuffled data
    display_ix = np.random.choice(len(ygnd), num_instances,replace=False)

    # Resolution: Number of blocks per side on each voxel. Setting this to less than 3
    # results in some ugly renderings, though it will be faster. Setting it higher makes it
    # prettier but can slow it down. With this setting, I can run interpolation in real-time on
    # a laptop with 16GB RAM and a GT730M. A setup with a real graphics card should be able to do
    # much, much more.
    v_res = 3
    
    # Dimensionality of the voxel grid
    dim = 32

    # Function to produce the data matrix for rendering. 
    def make_data_matrix(x,intensity):  
        return intensity*np.repeat(np.repeat(np.repeat(x[0][0],v_res,axis=0),v_res,axis=1),v_res,axis=2)

    # VTK Image Importer
    dataImporter = vtk.vtkImageImport()

    # Make the initial data matrix
   
    # initial random latent vector
    z_1 = np.random.randn(1,cfg['num_latents']).astype(np.float32)
    
    if cfg['cc']: # If augmenting with class-conditional vector
        cc_1 = np.zeros((1,10),dtype=np.float32)
        cc_1[0,np.random.randint(10)] = 1
        data_matrix = make_data_matrix(np.asarray(tfuncs['pred'](z_1,cc_1),dtype=np.uint8),128)
    else:
        data_matrix = make_data_matrix(np.asarray(tfuncs['pred'](z_1),dtype=np.uint8),128)
        
    # VTK bookkeeping stuff to prepare the central model
    data_string = data_matrix.tostring()
    dataImporter.CopyImportVoidPointer(data_string, len(data_string))
    dataImporter.SetDataScalarTypeToUnsignedChar()
    dataImporter.SetNumberOfScalarComponents(1)
    dataImporter.SetDataExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1)
    dataImporter.SetWholeExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1)
    
    # Prepare the interpolant endpoints
    
    # endpoint data importer
    edi = [0,0,0,0]
    
    # Endpoint data matrices    
    dm = [0,0,0,0]
    
    # Endpoint Latent values
    eZ = [0,0,0,0]

    # Endpoint sigmas
    eS = [0,0,0,0]
    
    # Endpoint class-conditional values
    eCC = [0,0,0,0]
    
    # Endpoint intensity values for colormapping
    eIs = [64,128,192,255]
    
    # VTK Bookkeeping stuff for interpolant endpoints
    for i in xrange(4):
        eZ[i] = tfuncs['Zfn'](ygnd[None,display_ix[i]])[0]
        eS[i] = tfuncs['sigma_fn'](ygnd[None,display_ix[i]])[0]
        eCC[i] = cc[None,display_ix[i]] # This may need changing to preserve shape? to be a 1x10 matrix instead of a 10x1?
        dm[i] = make_data_matrix(ygnd[None,display_ix[i]],eIs[i]).tostring()
        edi[i] = vtk.vtkImageImport()
        edi[i].CopyImportVoidPointer(dm[i], len(dm[i]))
        edi[i].SetDataScalarTypeToUnsignedChar()
        edi[i].SetNumberOfScalarComponents(1)
        edi[i].SetDataExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1)
        edi[i].SetWholeExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1)
  
    
        
    # Prepare color and transparency values
    colorFunc = vtk.vtkColorTransferFunction()
    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    alphaChannelFunc.AddPoint(64,1)
    alphaChannelFunc.AddPoint(128,1.0)
    alphaChannelFunc.AddPoint(192,1.0)
    alphaChannelFunc.AddPoint(255,1.0)
    
    colorFunc.AddRGBPoint(0, 0.0, 0.0, 0.0)
    colorFunc.AddRGBPoint(64, 0.0, 0.4, 0.8)
    colorFunc.AddRGBPoint(128,0.8,0.0,0.0)
    colorFunc.AddRGBPoint(192,0.8,0.0,0.7)
    colorFunc.AddRGBPoint(255,0.0,0.8,0.0)

    # Prepare volume properties.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)
    volumeProperty.ShadeOn() # Keep this on unless you want everything to look terrible
    volumeProperty.SetInterpolationTypeToNearest()
    
    # Optional settings
    # volumeProperty.SetSpecular(0.2)
    # volumeProperty.SetAmbient(0.4)
    # volumeProperty.SetDiffuse(0.6)
     
    # More VTK Bookkeeping stuff.
    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
    
    # Specify the data and raycast methods for the rendered volumes.
    volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetInputConnection(dataImporter.GetOutputPort())
    
    # Endpoint volumeMappers
    evm = [0,0,0,0]
    for i in xrange(4):
        evm[i] = vtk.vtkVolumeRayCastMapper()
        evm[i].SetVolumeRayCastFunction(compositeFunction)
        evm[i].SetInputConnection(edi[i].GetOutputPort())

     
    # Prepare the volume for the draggable model.
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)
    volume.SetPosition([0, 0, 0])
    
    # Endpoint volumes
    ev = [0,0,0,0]
    vps = [[0,-150.0,-150.0],[0,150.0,-150.0],[0,-150.0,150.0],[0,150.0,150.0]]
    for i in xrange(4):
        ev[i] = vtk.vtkVolume()
        ev[i].SetMapper(evm[i])
        ev[i].SetProperty(volumeProperty)
        ev[i].SetPosition(vps[i])
        ev[i].DragableOff()
        ev[i].PickableOff()
    
    # Simple linear 2D Interpolation function for interpolation between latent values.
    # Feel free to extend this to use more advanced interpolation methods.
    def interp2d(x,y,z_):
        x1 = vps[0][1]+97.5
        x2 = vps[1][1]
        y1 = vps[0][2]+97.5
        y2 = vps[2][2]

        return ( ( (z_[0] * (x2-x) * (y2-y)) + 
                   (z_[1] * (x-x1) * (y2-y)) + 
                   (z_[2] * (x2-x) * (y-y1)) + 
                   (z_[3] * (x-x1) * (y-y1)) ) /
                   ( (x2-x1) * (y2-y1) ) )
    
    
    ### Interactor Style
    # This class defines the user interface, and how the system reacts to different user inputs.
    class MyInteractorStyle(vtk.vtkInteractorStyleSwitch):
     
        def __init__(self,parent=None):
            

            # Index indicating which models are currently selected for endpoints
            self.ix = 0
            
            # Togglable flag indicating if the center model is being dragged or not
            self.drag = 0;
            
            # Picker
            self.picker = vtk.vtkCellPicker()
            self.picker.SetTolerance(0.001)
            
            # Set up observers. These functions watch for specific user actions.
            self.SetCurrentStyleToTrackballActor()
            self.GetCurrentStyle().AddObserver("MiddleButtonReleaseEvent",self.middleButtonReleaseEvent)
            self.GetCurrentStyle().AddObserver("MouseMoveEvent",self.mouseMoveEvent)
            self.SetCurrentStyleToTrackballCamera()
            self.GetCurrentStyle().AddObserver("MiddleButtonPressEvent",self.middleButtonPressEvent)
            self.GetCurrentStyle().AddObserver("KeyPressEvent",self.keyPress)
            

        #
        def mouseMoveEvent(self,obj,event):
            # Re-render every time the user moves the mouse while clicking.
            # If you have a slow computer, consider changing this to be thresholded so as to only have a certain resolution
            # (i.e. to only change if the mouse moves a certain distance, rather than any move)
           
           if self.drag and self.picker.GetProp3D():
                
                # Move object. This is a rewrite of the raw move object code;
                # Normally you would do this with the built-in version of this function and extend 
                # it pythonically in the normal way, but the python bindings for VTK don't expose
                # this function in that way (it's all hard-coded in C++) so this is a simple
                # re-implementation that gives more control over how the object is moved.
                # Specifically, this constrains the draggable object to only move in-plane
                # and prevents it going out of bounds.
                
                center = self.picker.GetProp3D().GetCenter()
                display_center = [0,0,0]
                new_point = [0,0,0,0]
                old_point = [0,0,0,0]
                motion_vector = [0,0]
                event_pos = self.GetCurrentStyle().GetInteractor().GetEventPosition()
                last_event_pos = self.GetCurrentStyle().GetInteractor().GetLastEventPosition()
                self.ComputeWorldToDisplay(self.GetDefaultRenderer(),
                                            center[0],
                                            center[1],
                                            center[2],
                                            display_center)
                
                self.ComputeDisplayToWorld(self.GetDefaultRenderer(),
                                            event_pos[0],
                                            event_pos[1],
                                            display_center[2],
                                            new_point)
                
                self.ComputeDisplayToWorld(self.GetDefaultRenderer(),
                                            last_event_pos[0],
                                            last_event_pos[1],
                                            display_center[2],
                                            old_point)
                
                # Calculate the position change, making sure to confine the object to within the boundaries.
                # Consider finding a way to do this so that it depends on position of center instead of mouse
                new_point[1] = max(min(vps[1][1], new_point[1]), vps[0][1]+97.5)
                new_point[2] = max(min(vps[2][2], new_point[2]), vps[0][2]+97.5)
                old_point[1] = max(min(vps[1][1], self.picker.GetProp3D().GetCenter()[1]), vps[0][1]+97.5)
                old_point[2] = max(min(vps[2][2], self.picker.GetProp3D().GetCenter()[2]), vps[0][2]+97.5)
                
                # Increment the position
                self.picker.GetProp3D().AddPosition(0,new_point[1]-old_point[1],new_point[2]-old_point[2])
                
                # Update Data
                if cfg['cc']:
                    data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1],
                                                                                       volume.GetCenter()[2],eZ)],
                                                                              interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eCC)),
                                                                                        dtype=np.uint8),
                                                                                        int(interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eIs))).tostring()
                else:
                    data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eZ)]),
                                                                                        dtype=np.uint8),
                                                                                        int(interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eIs))).tostring()
                # Update the renderer's pointer to the data so that the GUI has the updated data.
                dataImporter.CopyImportVoidPointer(data_string, len(data_string))
                # Update the window.
                self.GetCurrentStyle().GetInteractor().Render()
            
                return
  
        # If the middle button is used to select the center object, change to
        # dragging mode. Else, use it to pan the view.
        def middleButtonPressEvent(self,obj,event):
            
            clickPos = self.GetCurrentStyle().GetInteractor().GetEventPosition()
            self.picker.Pick(clickPos[0],clickPos[1],0,self.GetDefaultRenderer())
            
            if self.picker.GetProp3D():
                self.SetCurrentStyleToTrackballActor()
                self.drag=1
                
                # Optional: Add the ability to modify interpolant endpoints.
                # else:
                    # If we click an interpolant endpoint, change that endpoint somehow. 
                    # self.drag = 0
            
            
            self.GetCurrentStyle().OnMiddleButtonDown()     
            # self.GetCurrentStyle().HighlightProp3D(volume)
            return
        
        # When we release, change style from TrackballActor to TrackballCamera.
        def middleButtonReleaseEvent(self,obj,event):
            self.SetCurrentStyleToTrackballCamera()
            self.drag=0
            self.GetCurrentStyle().OnMiddleButtonUp()
            return
        
        # If the user presses an arrow key, swap out interpolant endpoints and re-render.
        # If the user hits space, sample randomly in the latent space and re-render.
        # If class-conditional vectors are enabled and the user hits 1-9, render a random
        # class-conditional object.
        def keyPress(self,obj,event):
            key=self.GetCurrentStyle().GetInteractor().GetKeySym()
            if key == 'Right':
                # Increment index of which models we're using, re-render all endpoints
                self.ix+=1
                for i in xrange(4):
                    eZ[i] = tfuncs['Zfn'](ygnd[None,display_ix[self.ix+i]])[0]
                    eS[i] = tfuncs['sigma_fn'](ygnd[None,display_ix[self.ix+i]])[0]
                    eCC[i] = cc[None,display_ix[self.ix+i]]
                    dm[i] = make_data_matrix(ygnd[None,display_ix[self.ix+i]],eIs[i]).tostring()
                    edi[i].CopyImportVoidPointer(dm[i], len(dm[i]))
                if cfg['cc']:
                    data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1],
                                                                                       volume.GetCenter()[2],eZ)],
                                                                              interp2d(volume.GetCenter()[1],
                                                                                       volume.GetCenter()[2],eCC)),
                                                                                        dtype=np.uint8),
                                                                                        int(interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eIs))).tostring()
                else:                                                                        
                    data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eZ)]),
                                                                                        dtype=np.uint8),
                                                                                        int(interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eIs))).tostring()
                dataImporter.CopyImportVoidPointer(data_string, len(data_string))
                
            
            elif key == 'Left' and (self.ix > 0):
                self.ix-=1
                for i in xrange(4):
                    eZ[i] = tfuncs['Zfn'](ygnd[None,display_ix[self.ix+i]])[0]
                    eS[i] = tfuncs['sigma_fn'](ygnd[None,display_ix[self.ix+i]])[0]
                    eCC[i] = cc[None,display_ix[self.ix+i]]
                    dm[i] = make_data_matrix(ygnd[None,display_ix[self.ix+i]],eIs[i]).tostring()
                    edi[i].CopyImportVoidPointer(dm[i], len(dm[i]))
                if cfg['cc']:
                    data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1],
                                                                                       volume.GetCenter()[2],eZ)],
                                                                              interp2d(volume.GetCenter()[1],
                                                                                       volume.GetCenter()[2],eCC)),
                                                                                        dtype=np.uint8),
                                                                                        int(interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eIs))).tostring()

                else:        
                    data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eZ)]),
                                                                                        dtype=np.uint8),
                                                                                        int(interp2d(volume.GetCenter()[1],
                                                                                        volume.GetCenter()[2],eIs))).tostring()
                dataImporter.CopyImportVoidPointer(data_string, len(data_string))
            elif key == 'space':
                # Random Z, with optional weighting.
                Z_rand = 0.5*np.random.randn(1,cfg['num_latents']).astype(np.float32)
                
                # Optionally, sample using the interpolated sigmas as well.
                # Z_rand = np.square(np.exp(interp2d(volume.GetCenter()[1],volume.GetCenter()[2],eS))*np.random.randn(1,cfg['num_latents']).astype(np.float32))
               
                if cfg['cc']: # if class-conditional, take the class vector into account
                    cc_rand = np.zeros((1,10),dtype=np.float32)
                    cc_rand[0,np.random.randint(10)] = 1
                    data_string = make_data_matrix(np.asarray(tfuncs['pred'](interp2d(volume.GetCenter()[1],
                                                                                       volume.GetCenter()[2],eZ)+Z_rand,cc_rand),
                                                                            dtype=np.uint8),
                                                                            int(interp2d(volume.GetCenter()[1],
                                                                            volume.GetCenter()[2],eIs))).tostring()
                else:
                    data_string = make_data_matrix(np.asarray(tfuncs['pred'](Z_rand),
                                                                            dtype=np.uint8),
                                                                            int(interp2d(volume.GetCenter()[1],
                                                                            volume.GetCenter()[2],eIs))).tostring()
                dataImporter.CopyImportVoidPointer(data_string, len(data_string))
            
                # Generate random Class-conditional Z
            elif 0<= int(float(key))<=9 and cfg['cc']:
                cc_rand = np.zeros((1,10),dtype=np.float32)
                cc_rand[0,int(float(key))] = 5
                Z_rand = np.square(np.exp(interp2d(volume.GetCenter()[1],volume.GetCenter()[2],eS)))*np.random.randn(1,cfg['num_latents']).astype(np.float32)+interp2d(volume.GetCenter()[1],volume.GetCenter()[2],eZ)
                data_string = make_data_matrix(np.asarray(tfuncs['pred'](Z_rand,cc_rand),
                                                                            dtype=np.uint8),
                                                                            int(interp2d(volume.GetCenter()[1],
                                                                            volume.GetCenter()[2],eIs))).tostring()
                dataImporter.CopyImportVoidPointer(data_string, len(data_string))                                                            
                # print(key)
                
            # Render and pass event on
            self.GetCurrentStyle().GetInteractor().Render()   
            self.GetCurrentStyle().OnKeyPress()    
            return
            
    # Initialize the render window
    renderer = vtk.vtkRenderer()
    renderWin = vtk.vtkRenderWindow()
    renderWin.AddRenderer(renderer)

    # Initialize the render interactor
    renderInteractor = vtk.vtkRenderWindowInteractor()
    style = MyInteractorStyle()
    style.SetDefaultRenderer(renderer)
    renderInteractor.SetInteractorStyle(style)#volume_set=volume,Lvolume_set = Lvolume, Rvolume_set = Rvolume))
    renderInteractor.SetRenderWindow(renderWin)

    # Make boundary plane
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(1,2,2)
    xCoords = vtk.vtkFloatArray()
    xCoords.InsertNextValue(30)
    yCoords = vtk.vtkFloatArray()
    yCoords.InsertNextValue(vps[0][1]+97.5)
    yCoords.InsertNextValue(vps[1][1])
    rgrid.SetXCoordinates(xCoords)
    rgrid.SetYCoordinates(yCoords)
    rgrid.SetZCoordinates(yCoords)
    plane = vtk.vtkRectilinearGridGeometryFilter()
    plane.SetInputData(rgrid) 
    rgridMapper = vtk.vtkPolyDataMapper()
    rgridMapper.SetInputConnection(plane.GetOutputPort())
    wireActor = vtk.vtkActor()
    wireActor.SetMapper(rgridMapper)
    wireActor.GetProperty().SetRepresentationToWireframe()
    wireActor.GetProperty().SetColor(0, 0, 0)
    wireActor.PickableOff()
    wireActor.DragableOff()
    
    # Add model, endpoints, and boundary plane to renderer
    renderer.AddActor(wireActor)
    for i in xrange(4):
        renderer.AddVolume(ev[i])
    renderer.AddVolume(volume) 

    # set background to white. Optionally change it to a fun color, like "Lifeblood of the Untenderized."    
    renderer.SetBackground(1.0,1.0,1.0)

    # Set initial window size. You can drag the window to change size, but keep in mind that
    # the larger the window, the slower this thing runs. On my laptop, I get little spikes
    # of lag when I run this on full screen, though a more graphics-cardy setup should do fine.
    renderWin.SetSize(400, 400)
     
    # Exit function
    def exitCheck(obj, event):
        if obj.GetEventPending() != 0:
            obj.SetAbortRender(1)
     
    # Add exit function
    renderWin.AddObserver("AbortCheckEvent", exitCheck)
    
    # initialize interactor
    renderInteractor.Initialize()

    # Start application!
    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(20)
    renderer.GetActiveCamera().Dolly(2.8)
    renderer.ResetCameraClippingRange()    
    renderWin.Render()
    renderInteractor.Start()
Exemple #41
0
def gocad2vtk(gcFile, mesh, bcflag, inflag):
    """"
    Function to read gocad polystructure file and output indexes of
    mesh with in the structure.

    """
    print("Reading GOCAD ts file...", bcflag, inflag)
    vrtx, trgl = read_GOCAD_ts(gcFile)
    vrtx, trgl = np.vstack(vrtx), np.vstack(trgl)
    # Adjust the index
    trgl = trgl - 1

    # Make vtk pts
    ptsvtk = vtk.vtkPoints()
    ptsvtk.SetData(npsup.numpy_to_vtk(vrtx, deep=1))

    # Make the polygon connection
    polys = vtk.vtkCellArray()
    for face in trgl:
        poly = vtk.vtkPolygon()
        poly.GetPointIds().SetNumberOfIds(len(face))
        for nrv, vert in enumerate(face):
            poly.GetPointIds().SetId(nrv, vert)
        polys.InsertNextCell(poly)

    # Make the polydata, structure of connections and vrtx
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(ptsvtk)
    polyData.SetPolys(polys)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx, mesh.nNy, mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx, deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy, deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz, deep=1))
    # Add indexes
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC), deep=1)
    vtkInd.SetName('Index')
    vtkMesh.GetCellData().AddArray(vtkInd)

    extractImpDistRectGridFilt = vtk.vtkExtractGeometry()
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc)
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    if bcflag is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()

    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if inflag is True:
        extractImpDistRectGridFilt.ExtractInsideOn()

    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print("Extracting indices from grid...")
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index'))

    # Return the indexes inside
    return insideGrid
Exemple #42
0
         y_start=p_coordinate[1]*(shape[1]-1)
         y_end=y_start+shape[1]
         z_start=p_coordinate[2]*(shape[2]-1)
         z_end=z_start+shape[2]
         k=0 #Counts the 6 components
         for group in list_group:
             list_array=group._f_listNodes("Array") #List of all recorded arrays in "group"
             for array in list_array:
                 num=scipy.int64(repr(array).split()[0][17:])
                 if num==cycle:
                     num_final=num
                     Fields_local[k,x_start:x_end,y_start:y_end,z_start:z_end]=array.read()
             k=k+1
         h5proc_file.close()
 #Write the .vtr file
     rtg = vtk.vtkRectilinearGrid()
     
     rtg.SetDimensions(Nxc+1,Nyc+1,Nzlocal)
     rtg.SetExtent(0,Nxc,0,Nyc,rankproc*Nzc/numproc,(rankproc+1)*Nzc/numproc)
     rtg.SetXCoordinates(vtkXcoordinates)
     rtg.SetYCoordinates(vtkYcoordinates)
     rtg.SetZCoordinates(vtkZcoordinates)
     
     Bx=Fields_local[0,:,:,:].swapaxes(0,2).flatten().astype("float32")
     By=Fields_local[1,:,:,:].swapaxes(0,2).flatten().astype("float32")
     Bz=Fields_local[2,:,:,:].swapaxes(0,2).flatten().astype("float32")
     Ex=Fields_local[3,:,:,:].swapaxes(0,2).flatten().astype("float32")
     Ey=Fields_local[4,:,:,:].swapaxes(0,2).flatten().astype("float32")
     Ez=Fields_local[5,:,:,:].swapaxes(0,2).flatten().astype("float32")
     
     vtk_dataBx = vtk.vtkFloatArray()
Exemple #43
0
def write_vtr(data, fname='tmp/data.vtr', down_sampling=(5, 5, 5)):
    """
    Write the reconstructed data (img stackes) to vtr file (retangular grid)

    Parameters
    ----------
    data          :  np.3darray
        reconstructed 3D image stacks with axis=0 as the omega
    fname         :  str
        file name of the output vtr file
    down_sampling :  tuple 
        down sampling steps along three axes

    Returns
    -------
    None
    """
    # vtk is only used here, therefore doing an in module import
    import vtk
    from vtk.util import numpy_support
    
    # convert to unit8 can significantly reduce the output vtr file
    # size, or just do a severe down-sampling
    data = _normalize_imgstacks(data[::down_sampling[0], 
                                     ::down_sampling[1], 
                                     ::down_sampling[2],]) * 255
    
    # --init rectangular grid
    rGrid = vtk.vtkRectilinearGrid()
    coordArray = [vtk.vtkDoubleArray(),
                  vtk.vtkDoubleArray(),
                  vtk.vtkDoubleArray(),
                 ]
    coords = np.array([np.arange(data.shape[i]) for i in range(3)])
    coords = [0.5 * np.array([3.0 * coords[i][0] - coords[i][0 + int(len(coords[i]) > 1)]] + \
                             [coords[i][j-1] + coords[i][j] for j in range(1,len(coords[i]))] + \
                             [3.0 * coords[i][-1] - coords[i][-1 - int(len(coords[i]) > 1)]]
                            ) 
              for i in range(3)
             ]
    grid = np.array(list(map(len,coords)),'i')
    rGrid.SetDimensions(*grid)
    for i,points in enumerate(coords):
        for point in points:
            coordArray[i].InsertNextValue(point)

    rGrid.SetXCoordinates(coordArray[0])
    rGrid.SetYCoordinates(coordArray[1])
    rGrid.SetZCoordinates(coordArray[2])
    
    # vtk requires x to be the fast axis
    # NOTE:
    #    Proper coordinate transformation is required to connect the 
    #    tomography data with other down-stream analysis (such as FF-HEDM
    #    and NF-HEDM).
    imgstacks = np.swapaxes(data, 0, 2)
    
    VTKarray = numpy_support.numpy_to_vtk(num_array=imgstacks.flatten().astype(np.uint8),
                                          deep=True,
                                          array_type=vtk.VTK_UNSIGNED_CHAR,
                                         )
    VTKarray.SetName('img')
    rGrid.GetCellData().AddArray(VTKarray)
    
    rGrid.Modified()
    if vtk.VTK_MAJOR_VERSION <= 5: 
        rGrid.Update()

    # output to file
    writer = vtk.vtkXMLRectilinearGridWriter()
    writer.SetFileName(fname)
    writer.SetDataModeToBinary()
    writer.SetCompressorTypeToZLib()
    if vtk.VTK_MAJOR_VERSION <= 5: 
        writer.SetInput(rGrid)
    else:                          
        writer.SetInputData(rGrid)
    writer.Write()
Exemple #44
0
    def getvtkimage(self, webargs, timestep):
        #Setup query
        DBSTRING = os.environ['db_connection_string']
        conn = pyodbc.connect(DBSTRING, autocommit=True)
        cursor = conn.cursor()
        #url = "http://localhost:8000/cutout/getcutout/"+ token + "/" + dataset + "/" + datafield + "/" + ts + "," +te + "/" + xs + "," + xe +"/" + ys + "," + ye +"/" + zs + "," + ze
        w = webargs.split("/")
        ts = int(w[3].split(',')[0])
        te = int(w[3].split(',')[1])
        xs = int(w[4].split(',')[0])
        xe = int(w[4].split(',')[1])
        ys = int(w[5].split(',')[0])
        ye = int(w[5].split(',')[1])
        zs = int(w[6].split(',')[0])
        ze = int(w[6].split(',')[1])
        extent = (xs, ys, zs, xe, ye, ze)
        overlap = 2 #Used only on contours--vorticity and Q-criterion
        #Look for step parameters
        if (len(w) > 9):
            step = True;
	    s = w[8].split(",")
            tstep = s[0]
            xstep = float(s[1])
            ystep = float(s[2])
            zstep = float(s[3])
            filterwidth = w[9]
        else:
            step = False;
            xstep = 1
            ystep = 1
            zstep = 1
            filterwidth = 1
        cfieldlist = w[2].split(",")
        firstval = cfieldlist[0]    
        maxrange = self.getmaxrange(w[1])     
        if ((firstval == 'vo') or (firstval == 'qc') or (firstval == 'cvo') or (firstval == 'qcc')):
            component = 'u'
            computation = firstval #We are doing a computation, so we need to know which one.
            #check to see if we have a threshold (only for contours)
            if (len(cfieldlist) > 1):
                threshold = float(cfieldlist[1])
            else:
                threshold = .6
            #New:  We need an expanded cutout if contouring.  Push the cutout out by 2 in all directions (unless at boundary).
            if ((firstval == 'cvo') or (firstval == 'qcc')):
                newextent = self.expandcutout(extent, maxrange[0], maxrange[1], maxrange[2], overlap)
                contour = True                
        else:
            component = w[2] #There could be multiple components, so we will have to loop
            computation = ''
        #Split component into list and add them to the image

        #Check to see if we have a value for vorticity or q contour
        fieldlist = list(component)

        for field in fieldlist:
            print("Field = %s" % field)
            cursor.execute("{CALL turbdev.dbo.GetAnyCutout(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",w[1], field, timestep, extent[0], extent[1], extent[2], xstep, ystep, zstep, 1,1,extent[3], extent[4], extent[5],filterwidth,1)
            #If data spans across multiple servers, we get multiple sets, so concatenate them.
            row = cursor.fetchone()
            raw = row[0]
            part = 0            
            print ("First part size is %d" % len(row[0]))
            while(cursor.nextset()):           
                row = cursor.fetchone()
                raw = raw + row[0]
                part = part +1
                print ("added part %d" % part)
                print ("Part size is %d" % len(row[0]))
            print ("Raw size is %d" % len(raw))
            data = np.frombuffer(raw, dtype=np.float32)
            conn.close()
            vtkdata = numpy_support.numpy_to_vtk(data, deep=True, array_type=vtk.VTK_FLOAT)
            components = self.numcomponents(field)
            vtkdata.SetNumberOfComponents(components)
            vtkdata.SetName(self.componentname(field))
            image = vtk.vtkImageData()
            if (step):
                xes = int(extent[3])/int(xstep)-1
                yes = int(extent[4])/int(ystep)-1
                zes = int(extent[5])/int(zstep)-1
                image.SetExtent(extent[0], extent[0]+extent[3], extent[1], extent[1]+extent[4], extent[2], extenet[2]+extenet[5])
                print("Step extent=" +str(xes))
                print("xs=" + str(xstep) + " ys = "+ str(ystep) +" zs = " + str(zstep))
            else:
                image.SetExtent(extent[0], extent[0]+extent[3]-1, extent[1], extent[1]+extent[4]-1, extent[2], extent[2]+extent[5]-1)
            image.GetPointData().SetVectors(vtkdata)

            if (step): #Magnify to original size
                image.SetSpacing(xstep,ystep,zstep)

        #Check if we need a rectilinear grid, and set it up if so.
        if (w[1] == 'channel'):
            ygrid = self.getygrid()
            #print("Ygrid: ")
            #print (ygrid)
            rg = vtk.vtkRectilinearGrid()
            #Not sure about contouring channel yet, so we are going back to original variables at this point.
            rg.SetExtent(xs, xs+xe-1, ys, ys+ye-1, zs, zs+ze-1)
            rg.GetPointData().SetVectors(vtkdata)

            xg = np.arange(float(xs),float(xe))
            zg = np.arange(float(zs),float(ze))
            for x in xg:
                    xg[x] = 8*3.141592654/2048*x
            for z in zg:
                    zg[z] = 3*3.141592654/2048*z
            vtkxgrid=numpy_support.numpy_to_vtk(xg, deep=True,
                array_type=vtk.VTK_FLOAT)
            vtkzgrid=numpy_support.numpy_to_vtk(zg, deep=True,
                array_type=vtk.VTK_FLOAT)
            vtkygrid=numpy_support.numpy_to_vtk(ygrid,
                deep=True, array_type=vtk.VTK_FLOAT)
            rg.SetXCoordinates(vtkxgrid)
            rg.SetZCoordinates(vtkzgrid)
            rg.SetYCoordinates(vtkygrid)
            image = rg #we rewrite the image since we may be doing a
                       #computation below
        #See if we are doing a computation
        if (computation == 'vo'):
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            vorticity.SetInputData(image)
            print("Computing Vorticity")
            vorticity.Update()
        elif (computation == 'cvo'):
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            vorticity.SetInputData(image)
            print("Computing Voricity")
            vorticity.Update()
            mag = vtk.vtkImageMagnitude()
            cp = vtk.vtkCellDataToPointData()
            cp.SetInputData(vorticity.GetOutput())
            print("Computing magnitude")
            cp.Update()
            image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
            mag.SetInputData(image)
            mag.Update()
            c = vtk.vtkContourFilter()
            c.SetValue(0,threshold)
            c.SetInputData(mag.GetOutput())
            print("Computing Contour")
            c.Update()
            #Now we need to clip out the overlap
            box = vtk.vtkBox()    
            #set box to requested size
            box.SetBounds(xs, xs+xe-1, ys, ys+ye-1, zs,zs+ze-1)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            cropdata = clip.GetOutput()
            return cropdata

        elif (computation == 'qcc'):
            q = vtk.vtkGradientFilter()
            q.SetInputData(image)
            q.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
            q.ComputeQCriterionOn()
            q.Update()
            #newimage = vtk.vtkImageData()
            image.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion"))
            mag = vtk.vtkImageMagnitude()
            mag.SetInputData(image)
            mag.Update()
            c = vtk.vtkContourFilter()
            c.SetValue(0,threshold)
            c.SetInputData(mag.GetOutput())
            c.Update()
            #clip out the overlap here
            box = vtk.vtkBox()    
            #set box to requested size
            box.SetBounds(xs, xs+xe-1, ys, ys+ye-1, zs,zs+ze-1)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            cropdata = clip.GetOutput()
            return cropdata
        else:
            return image
Exemple #45
0
def surface2inds(vrtx, trgl, mesh, boundaries=True, internal=True):
    """"
    Function to read gocad polystructure file and output indexes of
    mesh with in the structure.

    """
    import vtk
    import vtk.util.numpy_support as npsup

    # Adjust the index
    trgl = trgl - 1

    # Make vtk pts
    ptsvtk = vtk.vtkPoints()
    ptsvtk.SetData(npsup.numpy_to_vtk(vrtx, deep=1))

    # Make the polygon connection
    polys = vtk.vtkCellArray()
    for face in trgl:
        poly = vtk.vtkPolygon()
        poly.GetPointIds().SetNumberOfIds(len(face))
        for nrv, vert in enumerate(face):
            poly.GetPointIds().SetId(nrv, vert)
        polys.InsertNextCell(poly)

    # Make the polydata, structure of connections and vrtx
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(ptsvtk)
    polyData.SetPolys(polys)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx, mesh.nNy, mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx, deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy, deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz, deep=1))
    # Add indexes
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC), deep=1)
    vtkInd.SetName('Index')
    vtkMesh.GetCellData().AddArray(vtkInd)

    extractImpDistRectGridFilt = vtk.vtkExtractGeometry()  # Object constructor
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc)  #
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    if boundaries is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()

    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if internal is True:
        extractImpDistRectGridFilt.ExtractInsideOn()

    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print("Extracting indices from grid...")
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index'))

    # Return the indexes inside
    return insideGrid
Exemple #46
0
rgWriter.SetDataModeToBinary()
rgWriter.SetWriteExtent(3, 46, 6, 32, 1, 5)
rgWriter.SetCompressor(None)
if rgWriter.GetByteOrder():
    rgWriter.SetByteOrder(0)
else:
    rgWriter.SetByteOrder(1)
rgWriter.Write()

# read the extracted grid
reader = vtk.vtkXMLRectilinearGridReader()
reader.SetFileName(file0)
reader.WholeSlicesOff()
reader.Update()

rg0 = vtk.vtkRectilinearGrid()
rg0.DeepCopy(reader.GetOutput())
mapper0 = vtk.vtkDataSetMapper()
mapper0.SetInputData(rg0)

actor0 = vtk.vtkActor()
actor0.SetMapper(mapper0)

# read the whole grid
reader.SetFileName(file1)
reader.WholeSlicesOn()
reader.Update()

rg1 = vtk.vtkRectilinearGrid()
rg1.DeepCopy(reader.GetOutput())
mapper1 = vtk.vtkDataSetMapper()
Exemple #47
0
 def clear_mesh(self):
     """Use to clean/rebuild the mesh
     """
     self.__mesh = vtk.vtkRectilinearGrid()
     ubcMeshReaderBase.clear_models(self)