Exemple #1
0
def _write_legacy_vtu(x, fname):
    """
    Write a legacy VTK unstructured grid file.

    """
    # Voxel local points relative to its centre of geometry:
    voxel_local_points = asarray([[-1,-1,-1],[ 1,-1,-1],[-1, 1,-1],[ 1, 1,-1],
                                [-1,-1, 1],[ 1,-1, 1],[-1, 1, 1],[ 1, 1, 1]])\
                                  * 0.5 # scaling
    # Voxel world points:
    points = []
    # Culled input array -- as list:
    xculled = []

    try:
        depth, rows, columns = x.shape
    except ValueError:
        sys.exit('Array dimensions not equal to 3, possibly 2-dimensional.\n')

    for i in xrange(depth):
        for j in xrange(rows):
            for k in xrange(columns):
                if x[i, j, k] > THRESHOLD:
                    xculled.append(x[i, j, k])
                    points += (voxel_local_points + [k, j, i]).tolist()

    voxels = arange(len(points)).reshape(len(xculled), 8).tolist()
    topology = UnstructuredGrid(points, voxel=voxels)
    file_header = \
    'ToPy data, created '\
    + str(datetime.now()).rsplit('.')[0]
    scalars = CellData(Scalars(xculled, name='Densities', lookup_table =\
    'default'))
    vtk = VtkData(topology, file_header, scalars)
    vtk.tofile(fname, 'binary')
Exemple #2
0
    def toVTK(self, fName, dx, dy, mask=False, clip=False, force=False, method='ct'):
        """ Convert a 3D volume of interpolated values to vtk for visualization in Paraview """

        print('toVTK')

        self.getAttribute(xy=True, elevation=True, force=force)
        
        self.getMean3D(dx=dx, dy=dy, mask=mask, clip=clip, force=force, method=method)
        self.getZGrid()
        self.points.getBounds()

        x,y,intPoints = interpolation.getGridLocations2D(self.points.bounds, dx, dy)
        z=self.zGrid


        from pyvtk import VtkData, UnstructuredGrid, PointData, CellData, Scalars

        # Get the 3D dimensions
        mx = x.size
        my = y.size
        mz = z.size
        
        nPoints = mx*my*mz
        nCells = (mx-1)*(my-1)*(mz-1)

        # Interpolate the elevation to the grid nodes
        if (method == 'ct'):
            tx,ty, vals = self.points.interpCloughTocher(self.elevation, dx = dx,dy=dy, mask = mask, clip = clip, extrapolate='nearest')
        elif (method == 'mc'):
            tx,ty, vals = self.points.interpMinimumCurvature(self.elevation, dx = dx, dy=dy, mask = mask, clip = clip)
            
        vals = vals[:my,:mx]
        vals = vals.reshape(mx*my)

        # Set up the nodes and voxel indices
        points = np.zeros([nPoints,3], order='F')
        points[:,0] = np.tile(x,my*mz)
        points[:,1] = np.tile(y.repeat(mx),mz)
        points[:,2] = np.tile(vals,mz)-z.repeat(mx*my)

        # Create the cell indices into the points
        p = np.arange(nPoints).reshape((mz,my,mx))
        voxels = np.zeros([nCells,8],dtype=np.int)
        iCell = 0
        for k in range(mz-1):
            k1 = k + 1
            for j in range(my-1):
                j1 = j + 1
                for i in range(mx-1):
                    i1 = i + 1
                    voxels[iCell,:] = [p[k1,j,i],p[k1,j,i1],p[k1,j1,i1],p[k1,j1,i], p[k,j,i],p[k,j,i1],p[k,j1,i1],p[k,j1,i]]
                    iCell += 1

        # Create the various point data
        pointID = Scalars(np.arange(nPoints),name='Point iD')
        pointElev = Scalars(points[:,2],name='Point Elevation (m)')

        tmp=self.mean3D.reshape(np.size(self.mean3D))
        tmp1 = np.log10(1.0/tmp)
        pointRes = Scalars(tmp1, name = 'log10(Resistivity) (Ohm m)')
        tmp1 = np.log10(tmp)

        pointCon = Scalars(tmp1, name = 'log10(Conductivity) (S/m)')
        
        PData = PointData(pointID, pointElev, pointRes, pointCon)
        CData = CellData(Scalars(np.arange(nCells),name='Cell iD'))
        vtk = VtkData(
              UnstructuredGrid(points,
                               hexahedron=voxels),
#                               ),
              PData,
              CData,
              'Some Name'
              )

        vtk.tofile(fName, 'ascii')
Exemple #3
0
def _data_item(is_cell_data, data, step):
    sd = data[step, :]
    if is_cell_data:
        return CellData(Scalars(sd, 'cell_data', lookup_table='default'))
    return PointData(Scalars(sd, 'vertex_data'))
def save_vtk(fname,
             xyz,
             triangles=None,
             values=None,
             vectors=None,
             triangle_values=None):
    """Saves a point cloud or triangle mesh as a .vtk file.

    Files can be opened with Paraview or displayed using the PyVista library.

    Args:
        fname (string): filename.
        xyz (Tensor): (N,3) point cloud or vertices.
        triangles (integer Tensor, optional): (T,3) mesh connectivity. Defaults to None.
        values (Tensor, optional): (N,D) values, supported by the vertices. Defaults to None.
        vectors (Tensor, optional): (N,3) vectors, supported by the vertices. Defaults to None.
        triangle_values (Tensor, optional): (T,D) values, supported by the triangles. Defaults to None.
    """

    # Encode the points/vertices as a VTK structure:
    if triangles is None:  # Point cloud
        structure = PolyData(points=numpy(xyz), vertices=np.arange(len(xyz)))
    else:  # Surface mesh
        structure = PolyData(points=numpy(xyz), polygons=numpy(triangles))

    data = [structure]
    pointdata, celldata = [], []

    # Point values - one channel per column of the `values` array:
    if values is not None:
        values = numpy(values)
        if len(values.shape) == 1:
            values = values[:, None]
        features = values.T
        pointdata += [
            Scalars(f, name=f"features_{i:02d}")
            for i, f in enumerate(features)
        ]

    # Point vectors - one vector per point:
    if vectors is not None:
        pointdata += [Vectors(numpy(vectors), name="vectors")]

    # Store in the VTK object:
    if pointdata != []:
        pointdata = PointData(*pointdata)
        data.append(pointdata)

    # Triangle values - one channel per column of the `triangle_values` array:
    if triangle_values is not None:
        triangle_values = numpy(triangle_values)
        if len(triangle_values.shape) == 1:
            triangle_values = triangle_values[:, None]
        features = triangle_values.T
        celldata += [
            Scalars(f, name=f"features_{i:02d}")
            for i, f in enumerate(features)
        ]

        celldata = CellData(*celldata)
        data.append(celldata)

    #  Write to hard drive:
    vtk = VtkData(*data)
    os.makedirs(os.path.dirname(fname), exist_ok=True)
    vtk.tofile(fname)