Esempio n. 1
0
def image_to_vtk(path,
                 cell_data,
                 origin=(0.0, 0.0, 0.0),
                 spacing=(1.0, 1.0, 1.0)):
    """
    Writes numpy data to VTK

    Numpy arrays have to be contiguous in memory - if this is a problem call :func:`numpy.ascontiguousarray` first

    Patched version of same pyevtk function that also supports vector-valued data

    Args:
        path: path with file name, without file ending (.vtk) where data should be stored
        cell_data: dictionary, mapping name of the data to a 3D numpy array, or to a 3-tuple of 3D numpy arrays
                   in case of vector-valued data
        origin: 3-tuple describing the origin of the field in 3D
        spacing: 3-tuple describing the grid spacing in x,y, z direction

    Returns:
        path to file that was written

    Examples:
        >>> from tempfile import TemporaryDirectory
        >>> import os
        >>> import numpy as np
        >>> with TemporaryDirectory() as tmp_dir:
        ...     path = os.path.join(tmp_dir, 'out')
        ...     size = (20, 20, 20)
        ...     res_file = image_to_vtk(path, cell_data={'vector': (np.ones(size), np.ones(size), np.ones(size)),
        ...                                              'scalar': np.zeros(size)
        ...                                              })
    """

    # Extract dimensions
    start = (0, 0, 0)
    end = None

    keys = list(cell_data.keys())
    data = cell_data[keys[0]]
    if hasattr(data, 'shape'):
        end = data.shape
    elif isinstance(data, tuple):
        shapes = set(d.shape for d in data)
        if len(shapes) > 1:
            raise ValueError("All components have to have the same shape")
        end = shapes.pop()

    # Write data to file
    w = VtkFile(path, VtkImageData)
    w.openGrid(start=start, end=end, origin=origin, spacing=spacing)
    w.openPiece(start=start, end=end)
    _addDataToFile(w, cell_data, pointData=None)
    w.closePiece()
    w.closeGrid()
    _appendDataToFile(w, cell_data, pointData=None)
    w.save()
    return w.getFileName()
Esempio n. 2
0
def meshToVTK(path, v, f, pointData):
    assert v.shape[1] == f.shape[1] == 3
    # assert c.shape[0] == v.shape[0]

    offsets = np.arange(start=3,
                        stop=3 * f.shape[0] + 1,
                        step=3,
                        dtype=np.int32)

    cell_types = np.empty(f.shape[0], dtype=np.uint8)
    cell_types[:] = VtkTriangle.tid

    # connectivity = np.empty(3 * f.shape[0], dtype=np.int32)
    connectivity = np.ravel(f).astype(np.int32)

    (x, y, z) = (np.ravel(v[:, 0]), np.ravel(v[:, 1]), np.ravel(v[:, 2]))

    w = VtkFile(path, VtkUnstructuredGrid)
    w.openGrid()
    w.openPiece(ncells=f.shape[0], npoints=v.shape[0])

    w.openElement("Points")
    w.addData("points", (x, y, z))
    w.closeElement("Points")
    w.openElement("Cells")
    w.addData("connectivity", connectivity)
    w.addData("offsets", offsets)
    w.addData("types", cell_types)
    w.closeElement("Cells")

    _addDataToFile(w, cellData=None, pointData=pointData)

    w.closePiece()
    w.closeGrid()
    w.appendData((x, y, z))
    w.appendData(connectivity)
    w.appendData(offsets)
    w.appendData(cell_types)

    _appendDataToFile(w, cellData=None, pointData=pointData)

    w.save()
    return w.getFileName()
Esempio n. 3
0
def meshToVTK(path, v, f, pointData):
	assert v.shape[1] == f.shape[1] == 3
	# assert c.shape[0] == v.shape[0]
	
	offsets = np.arange(start = 3, stop = 3 * f.shape[0] + 1,
		step = 3, dtype=np.int32)
	
	cell_types = np.empty(f.shape[0], dtype=np.uint8)
	cell_types[:] = VtkTriangle.tid
	
	# connectivity = np.empty(3 * f.shape[0], dtype=np.int32)
	connectivity = np.ravel(f).astype(np.int32)
	
	(x, y, z) = (np.ravel(v[:, 0]),
		np.ravel(v[:, 1]),
		np.ravel(v[:, 2]))
	
	w = VtkFile(path, VtkUnstructuredGrid)
	w.openGrid()
	w.openPiece(ncells = f.shape[0], npoints = v.shape[0])
	
	w.openElement("Points")
	w.addData("points", (x, y, z))
	w.closeElement("Points")
	w.openElement("Cells")
	w.addData("connectivity", connectivity)
	w.addData("offsets", offsets)
	w.addData("types", cell_types)
	w.closeElement("Cells")
	
	_addDataToFile(w, cellData = None, pointData = pointData)
	
	w.closePiece()
	w.closeGrid()
	w.appendData((x, y, z))
	w.appendData(connectivity)
	w.appendData(offsets)
	w.appendData(cell_types)
	
	_appendDataToFile(w, cellData = None, pointData = pointData)
	
	w.save()
	return w.getFileName()
Esempio n. 4
0
print 'Vel: %f %f' % (Vel.min(),Vel.max())
print nxtot, nytot, nztot, rhosc
print rho.shape

nx, ny, nz = nxtot/nskip, nytot/nskip, nztot/nskip
lx, ly, lz = 1.0, 0.20, 1.0
dx, dy, dz = lx/nx, ly/ny, lz/nz
ncells = nx * ny * nz
npoints = (nx + 1) * (ny + 1) * (nz + 1)
x = np.arange(0, lx + 0.1*dx, dx, dtype='float64')
y = np.arange(0, ly + 0.1*dy, dy, dtype='float64')
z = np.arange(0, lz + 0.1*dz, dz, dtype='float64')
start, end = (0,0,0), (nx, ny, nz)

w = VtkFile(OutputFile, VtkRectilinearGrid)
w.openGrid(start = start, end = end)
w.openPiece( start = start, end = end)

# Point data
#passive = np.zeros(npoints, dtype="float64", order='F')
#w.openData("Point", scalars = "Passive")
#w.addData("Passive", passive)
#w.closeData("Point")

# Cell data
#pressure = np.zeros([nx, ny, nz], dtype="float64", order='F')
if mhd:
  w.openData("Cell", scalars = ("Density","RhoNeutros","GasPressure"), vectors = ("Velocity","Magnetic"))
else:
  w.openData("Cell", scalars = "Density", vectors = ("Velocity"))
w.addData("Density", rrho)
Esempio n. 5
0
from pyevtk.vtk import VtkFile, VtkRectilinearGrid
import numpy as np

nx, ny, nz = 6, 6, 2
lx, ly, lz = 1.0, 1.0, 1.0
dx, dy, dz = lx / nx, ly / ny, lz / nz
ncells = nx * ny * nz
npoints = (nx + 1) * (ny + 1) * (nz + 1)
x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')
y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')
z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')
start, end = (0, 0, 0), (nx, ny, nz)

w = VtkFile("./evtk_test", VtkRectilinearGrid)
w.openGrid(start=start, end=end)
w.openPiece(start=start, end=end)

# Point data
temp = np.random.rand(npoints)
vx = vy = vz = np.zeros([nx + 1, ny + 1, nz + 1], dtype="float64", order='F')
w.openData("Point", scalars="Temperature", vectors="Velocity")
w.addData("Temperature", temp)
w.addData("Velocity", (vx, vy, vz))
w.closeData("Point")

# Cell data
pressure = np.zeros([nx, ny, nz], dtype="float64", order='F')
w.openData("Cell", scalars="Pressure")
w.addData("Pressure", pressure)
w.closeData("Cell")
Esempio n. 6
0
def _write_vtu_series(grid, coordinates, connectivity, data, filename_base,
                      last_step, is_cell_data):
    steps = last_step + 1 if last_step is not None else len(data)
    fn_tpl = "{}_{:08d}"

    npoints = len(coordinates[0])
    ncells = len(connectivity)

    ref = grid.reference_element
    if ref is ref is referenceelements.triangle:
        points_per_cell = 3
        vtk_el_type = VtkTriangle.tid
    elif ref is referenceelements.square:
        points_per_cell = 4
        vtk_el_type = VtkQuad.tid
    else:
        raise NotImplementedError(
            "vtk output only available for grids with triangle or rectangle reference elments"
        )

    connectivity = connectivity.reshape(-1)
    cell_types = np.empty(ncells, dtype='uint8')
    cell_types[:] = vtk_el_type
    offsets = np.arange(start=points_per_cell,
                        stop=ncells * points_per_cell + 1,
                        step=points_per_cell,
                        dtype='int32')

    group = VtkGroup(filename_base)
    for i in range(steps):
        fn = fn_tpl.format(filename_base, i)
        vtk_data = data[i, :]
        w = VtkFile(fn, VtkUnstructuredGrid)
        w.openGrid()
        w.openPiece(ncells=ncells, npoints=npoints)

        w.openElement("Points")
        w.addData("Coordinates", coordinates)
        w.closeElement("Points")
        w.openElement("Cells")
        w.addData("connectivity", connectivity)
        w.addData("offsets", offsets)
        w.addData("types", cell_types)
        w.closeElement("Cells")
        if is_cell_data:
            _addDataToFile(w, cellData={"Data": vtk_data}, pointData=None)
        else:
            _addDataToFile(w, cellData=None, pointData={"Data": vtk_data})

        w.closePiece()
        w.closeGrid()
        w.appendData(coordinates)
        w.appendData(connectivity).appendData(offsets).appendData(cell_types)
        if is_cell_data:
            _appendDataToFile(w, cellData={"Data": vtk_data}, pointData=None)
        else:
            _appendDataToFile(w, cellData=None, pointData={"Data": vtk_data})

        w.save()
        group.addFile(filepath=fn + '.vtu', sim_time=i)
    group.save()
Esempio n. 7
0
def gridToVTK_with_start(path, x, y, z, cellData=None, pointData=None, fieldData=None, start=None):
    """
    Write data values as a rectilinear or rectangular grid.
    Parameters
    ----------
    path : str
        name of the file without extension where data should be saved.
    x : array-like
        x coordinate axis.
    y : array-like
        y coordinate axis.
    z : array-like
        z coordinate axis.
    cellData : dict, optional
        dictionary containing arrays with cell centered data.
        Keys should be the names of the data arrays.
        Arrays must have the same dimensions in all directions and must contain
        only scalar data.
    pointData : dict, optional
        dictionary containing arrays with node centered data.
        Keys should be the names of the data arrays.
        Arrays must have same dimension in each direction and
        they should be equal to the dimensions of the cell data plus one and
        must contain only scalar data.
    fieldData : dict, optional
        dictionary with variables associated with the field.
        Keys should be the names of the variable stored in each array.
    start : tuple, optional
        start position of data extent.
    Returns
    -------
    str
        Full path to saved file.
    Notes
    -----
    coordinates of the nodes of the grid. They can be 1D or 3D depending if
    the grid should be saved as a rectilinear or logically structured grid,
    respectively.
    Arrays should contain coordinates of the nodes of the grid.
    If arrays are 1D, then the grid should be Cartesian,
    i.e. faces in all cells are orthogonal.
    If arrays are 3D, then the grid should be logically structured
    with hexahedral cells.
    In both cases the arrays dimensions should be
    equal to the number of nodes of the grid.
    """

    import numpy as np
    from pyevtk.vtk import VtkFile, VtkStructuredGrid
    
    # Extract dimensions
    if start is None:
        start = (0, 0, 0)
    s = x.shape
    end = (start[0]+s[0]-1, start[1]+s[1]-1, start[2]+s[2]-1)

    w = VtkFile(path, VtkStructuredGrid)
    w.openGrid(start=start, end=end)
    w.openPiece(start=start, end=end)
    w.openElement("Points")
    w.addData("coordinates", (x, y, z))
    w.closeElement("Points")
    # Point data
    if pointData:
        keys = list(pointData.keys())
        w.openData("Point", scalars=keys[0])
        for key in keys:
            data = pointData[key]
            w.addData(key, data)
        w.closeData("Point")
    # Cell data
    if cellData:
        keys = list(cellData.keys())
        w.openData("Cell", scalars=keys[0])
        for key in keys:
            data = cellData[key]
            w.addData(key, data)
        w.closeData("Cell")
    # Field data
    # https://www.visitusers.org/index.php?title=Time_and_Cycle_in_VTK_files#XML_VTK_files
    if fieldData:
        keys = list(fieldData.keys())
        w.openData("Field")  # no attributes in FieldData
        for key in keys:
            data = fieldData[key]
            w.addData(key, data)
        w.closeData("Field")
    w.closePiece()
    w.closeGrid()
    # Write coordinates
    w.appendData((x, y, z))
    # Write data
    if pointData is not None:
        keys = list(pointData.keys())
        for key in keys:
            data = pointData[key]
            w.appendData(data)
    if cellData is not None:
        keys = list(cellData.keys())
        for key in keys:
            data = cellData[key]
            w.appendData(data)
    if fieldData is not None:
        keys = list(fieldData.keys())
        for key in keys:
            data = fieldData[key]
            w.appendData(data)
    w.save()
    return w.getFileName()