Ejemplo n.º 1
0
def test_create_uniform_grid_from_specs():
    # create UniformGrid
    dims = [10, 10, 10]
    grid = pyvista.UniformGrid(dims)  # Using default spacing and origin
    assert grid.dimensions == [10, 10, 10]
    assert grid.extent == [0, 9, 0, 9, 0, 9]
    assert grid.origin == [0.0, 0.0, 0.0]
    assert grid.spacing == [1.0, 1.0, 1.0]
    spacing = [2, 1, 5]
    grid = pyvista.UniformGrid(dims, spacing)  # Using default origin
    assert grid.dimensions == [10, 10, 10]
    assert grid.origin == [0.0, 0.0, 0.0]
    assert grid.spacing == [2.0, 1.0, 5.0]
    origin = [10, 35, 50]
    grid = pyvista.UniformGrid(dims, spacing,
                               origin)  # Everything is specified
    assert grid.dimensions == [10, 10, 10]
    assert grid.origin == [10.0, 35.0, 50.0]
    assert grid.spacing == [2.0, 1.0, 5.0]
    assert grid.dimensions == [10, 10, 10]
Ejemplo n.º 2
0
def test_compute_cell_sizes():
    for i, dataset in enumerate(datasets):
        result = dataset.compute_cell_sizes()
        assert result is not None
        assert isinstance(result, type(dataset))
        assert 'Area' in result.scalar_names
        assert 'Volume' in result.scalar_names
    # Test the volume property
    grid = pyvista.UniformGrid((10,10,10))
    volume = float(np.prod(np.array(grid.dimensions) - 1))
    assert np.allclose(grid.volume, volume)
Ejemplo n.º 3
0
def test_uniform_setters():
    grid = pyvista.UniformGrid()
    grid.dimensions = [10, 10, 10]
    assert grid.GetDimensions() == (10, 10, 10)
    assert grid.dimensions == [10, 10, 10]
    grid.spacing = [5, 2, 1]
    assert grid.GetSpacing() == (5, 2, 1)
    assert grid.spacing == [5, 2, 1]
    grid.origin = [6, 27.7, 19.8]
    assert grid.GetOrigin() == (6, 27.7, 19.8)
    assert grid.origin == [6, 27.7, 19.8]
Ejemplo n.º 4
0
def test_clear_arrays():
    # First try on an empty mesh
    grid = pyvista.UniformGrid((10, 10, 10))
    # Now try something more complicated
    grid.clear_arrays()
    grid['foo-p'] = np.random.rand(grid.n_points)
    grid['foo-c'] = np.random.rand(grid.n_cells)
    grid.field_arrays['foo-f'] = np.random.rand(grid.n_points * grid.n_cells)
    assert grid.n_arrays == 3
    grid.clear_arrays()
    assert grid.n_arrays == 0
Ejemplo n.º 5
0
def numpy_to_texture(image):
    """Convert a NumPy image array to a vtk.vtkTexture"""
    if not isinstance(image, np.ndarray):
        raise TypeError('Unknown input type ({})'.format(type(image)))
    if image.ndim != 3 or image.shape[2] != 3:
        raise AssertionError('Input image must be nn by nm by RGB')
    grid = pyvista.UniformGrid((image.shape[1], image.shape[0], 1))
    grid.point_arrays['Image'] = np.flip(image.swapaxes(0, 1), axis=1).reshape(
        (-1, 3), order='F')
    grid.set_active_scalar('Image')
    return image_to_texture(grid)
Ejemplo n.º 6
0
    def fast_vis(self,
                 plot,
                 show_outline: bool = True,
                 show_centroids: bool = True):
        """Adds the basic lattice features to a pyvista plotter and returns it. 
        It is mainly used to rapidly visualize the content of the lattice 
        for visual confirmation

        Args:
            plot (pyvista.Plotter): a pyvista plotter
            show_outline (bool, optional): If `True`, adds the bounding box of the lattice to the plot
            show_centroids (bool, optional): If `True`, adds the centroid of cells to the plot

        Returns:
            pyvista.Plotter: the same pyvista plotter containing lattice features

        ** Usage Example: **
        ```python
        p = pyvista.Plotter()
        lattice.fast_vis(p)
        ```
        """
        # Set the grid dimensions: shape + 1 because we want to inject our values on the CELL data
        grid = pv.UniformGrid()
        grid.dimensions = np.array(self.shape) + 1
        # The bottom left corner of the data set
        grid.origin = self.minbound - self.unit * 0.5
        grid.spacing = self.unit  # These are the cell sizes along each axis
        # Add the data values to the cell data
        grid.cell_arrays["values"] = self.flatten(order="F").astype(
            float)  # Flatten the array!
        # filtering the voxels
        threshed = grid.threshold([0.9, 1.1])

        # adding the voxels: light red
        plot.add_mesh(threshed,
                      show_edges=True,
                      color="#ff8fa3",
                      opacity=0.3,
                      label="Cells")

        if show_outline:
            # adding the boundingbox wireframe
            plot.add_mesh(grid.outline(), color="grey", label="Domain")

        if show_centroids:
            # adding the voxel centroids: red
            plot.add_mesh(pv.PolyData(self.centroids),
                          color='#ff244c',
                          point_size=5,
                          render_points_as_spheres=True,
                          label="Cell Centroids")

        return plot
Ejemplo n.º 7
0
def wrap(vtkdataset):
    """Wrap any given VTK data object to its appropriate PyVista data object.

    Other formats that are supported include:
    * 2D :class:`numpy.ndarray` of XYZ vertices
    * 3D :class:`numpy.ndarray` representing a volume. Values will be scalars.

    """
    wrappers = {
        'vtkUnstructuredGrid': pyvista.UnstructuredGrid,
        'vtkRectilinearGrid': pyvista.RectilinearGrid,
        'vtkStructuredGrid': pyvista.StructuredGrid,
        'vtkPolyData': pyvista.PolyData,
        'vtkImageData': pyvista.UniformGrid,
        'vtkStructuredPoints': pyvista.UniformGrid,
        'vtkMultiBlockDataSet': pyvista.MultiBlock,
        'vtkTable': pyvista.Table,
        # 'vtkParametricSpline': pyvista.Spline,
    }
    # Otherwise, we assume a VTK data object was passed
    if hasattr(vtkdataset, 'GetClassName'):
        key = vtkdataset.GetClassName()
    elif vtkdataset is None:
        return None
    elif isinstance(vtkdataset, np.ndarray):
        if vtkdataset.ndim == 1 and vtkdataset.shape[0] == 3:
            return pyvista.PolyData(vtkdataset)
        if vtkdataset.ndim > 1 and vtkdataset.ndim < 3 and vtkdataset.shape[
                1] == 3:
            return pyvista.PolyData(vtkdataset)
        elif vtkdataset.ndim == 3:
            mesh = pyvista.UniformGrid(vtkdataset.shape)
            mesh['values'] = vtkdataset.ravel(order='F')
            mesh.active_scalars_name = 'values'
            return mesh
        else:
            print(vtkdataset.shape, vtkdataset)
            raise NotImplementedError(
                'NumPy array could not be converted to PyVista.')
    elif is_meshio_mesh(vtkdataset):
        return from_meshio(vtkdataset)
    else:
        raise NotImplementedError(
            'Type ({}) not able to be wrapped into a PyVista mesh.'.format(
                type(vtkdataset)))
    try:
        wrapped = wrappers[key](vtkdataset)
    except KeyError:
        logging.warning(
            'VTK data type ({}) is not currently supported by pyvista.'.format(
                key))
        return vtkdataset  # if not supported just passes the VTK data object
    return wrapped
Ejemplo n.º 8
0
def read(filename, attrs=None):
    """Read any VTK file.

    It will figure out what reader to use then wrap the VTK object for
    use in PyVista.

    Parameters
    ----------
    attrs : dict, optional
        A dictionary of attributes to call on the reader. Keys of dictionary are
        the attribute/method names and values are the arguments passed to those
        calls. If you do not have any attributes to call, pass ``None`` as the
        value.

    """
    filename = os.path.abspath(os.path.expanduser(filename))
    if not os.path.isfile(filename):
        raise IOError('File ({}) not found'.format(filename))
    ext = get_ext(filename)

    # From the extension, decide which reader to use
    if attrs is not None:
        reader = get_reader(filename)
        return standard_reader_routine(reader, filename, attrs=attrs)
    elif ext in '.vti':  # ImageData
        return pyvista.UniformGrid(filename)
    elif ext in '.vtr':  # RectilinearGrid
        return pyvista.RectilinearGrid(filename)
    elif ext in '.vtu':  # UnstructuredGrid
        return pyvista.UnstructuredGrid(filename)
    elif ext in ['.ply', '.obj', '.stl']:  # PolyData
        return pyvista.PolyData(filename)
    elif ext in '.vts':  # StructuredGrid
        return pyvista.StructuredGrid(filename)
    elif ext in ['.vtm', '.vtmb']:
        return pyvista.MultiBlock(filename)
    elif ext in ['.e', '.exo']:
        return read_exodus(filename)
    elif ext in ['.vtk']:
        # Attempt to use the legacy reader...
        return read_legacy(filename)
    else:
        # Attempt find a reader in the readers mapping
        try:
            reader = get_reader(filename)
            return standard_reader_routine(reader, filename)
        except KeyError:
            pass
    raise IOError(
        "This file was not able to be automatically read by pyvista.")
Ejemplo n.º 9
0
def test_compute_cell_sizes():
    for i, dataset in enumerate(DATASETS):
        result = dataset.compute_cell_sizes()
        assert result is not None
        assert isinstance(result, type(dataset))
        assert 'Area' in result.scalar_names
        assert 'Volume' in result.scalar_names
    # Test the volume property
    grid = pyvista.UniformGrid((10, 10, 10))
    volume = float(np.prod(np.array(grid.dimensions) - 1))
    assert np.allclose(grid.volume, volume)
    # Now test composite data structures
    output = COMPOSITE.compute_cell_sizes()
    assert output.n_blocks == COMPOSITE.n_blocks
Ejemplo n.º 10
0
def create_vtkcube(density, origin, voxelsize, fname):
    """
    Export Cube as VTK file (can be used in e.g. ParaView)
    and create a range of 3D cube plots with pyvista
    :param density: 3D cube in shape (xdim, ydim, zdim)
    :param origin: origin cooridnates of cube
    :param voxelsize: voxel sizes in (xsize, ysize, zsize)
    :param fname: path + filename for files
    """
    grid = pv.UniformGrid()
    grid.dimensions = np.array(density.shape) + 1
    grid.origin = origin
    grid.spacing = voxelsize
    grid.cell_arrays["values"] = density.flatten(order="F")
    grid.save(fname)
Ejemplo n.º 11
0
    def create_pyvista_grid(self) -> pv.grid.UniformGrid:
        """Generate UniformGrid object for 3D plotting of the seismic.

        Args:
            seismic (Seismic): Seismic object.

        Returns:
            (pv.grid.UniformGrid)
        """
        grid = pv.UniformGrid()
        grid.spacing = (1, 1, 1)  # TODO: cell sizes? vertical exaggeration etc
        grid.dimensions = np.array(self.data.shape) + 1
        grid.cell_arrays["values"] = self.data.flatten(order="F")
        # TODO: correct orientation of cube
        return grid
Ejemplo n.º 12
0
def test_save_uniform(extension, binary, tmpdir):
    filename = str(tmpdir.mkdir("tmpdir").join('tmp.%s' % extension))
    ogrid = examples.load_uniform()
    ogrid.save(filename, binary)
    grid = pyvista.UniformGrid(filename)
    assert grid.n_cells == ogrid.n_cells
    assert grid.origin == ogrid.origin
    assert grid.spacing == ogrid.spacing
    assert grid.dimensions == ogrid.dimensions
    grid = pyvista.read(filename)
    assert isinstance(grid, pyvista.UniformGrid)
    assert grid.n_cells == ogrid.n_cells
    assert grid.origin == ogrid.origin
    assert grid.spacing == ogrid.spacing
    assert grid.dimensions == ogrid.dimensions
def buildGrid(values, origin=(0, 0, 0), spacing=(10, 10, 10)):
    # Spatial reference
    grid = pv.UniformGrid()

    # Grid dimensions (shape + 1)
    grid.dimensions = np.array(values.shape) + 1

    # Spatial reference params
    grid.origin = origin
    grid.spacing = spacing

    # Grid data
    grid.cell_arrays["values"] = values.flatten(order="F")

    return grid
Ejemplo n.º 14
0
def plot_3d_reals_pyvista(O, nshow=4):
    '''Plot realizations in in O.sim in 3D using pyvista
    
    Paramaters
    ----------
    O : mpslib object
        
    nshow : int (def=4)
        show a maxmimum of 'nshow' realizations
    '''
    import numpy as np
    import pyvista
    
    if not(hasattr(O,'sim')):
        print('No data to plot (no "sim" attribute)')
        return -1
    if (O.sim is None):
        print('No data to plot ("sim" attribute i "None")')
        return -1
    
    nr = O.par['n_real']
    nshow = np.min((nshow,nr))
    
    
    nxy = np.ceil(np.sqrt(nshow)).astype('int')
    
    plotter = pyvista.Plotter( shape=(nxy,nxy))

    i=-1
    for ix in range(nxy):
        for iy in range(nxy):
            i=i+1;
            plotter.subplot(iy,ix)

            Data = O.sim[i]
            grid = pyvista.UniformGrid()
            grid.dimensions = np.array(Data.shape) + 1

            grid.origin = O.par['origin']
            grid.spacing = O.par['grid_cell_size']
            grid.cell_arrays['values'] = Data.flatten(order='F') # Flatten the array!

            plotter.add_mesh(grid.slice_orthogonal())
            plotter.add_text('#%d' % (i+1))
            plotter.show_grid()

        
    plotter.show()
Ejemplo n.º 15
0
    def plot(self, plane_widget=True, plot_gradient=False):
        if not plot_gradient:
            gridvalues = self.image_sequence.array
        else:
            gridvalues = self.image_gradients.array
        surf = self.init_surf
        outputsurf = self.surface
        image = pv.UniformGrid()
        image.dimensions = gridvalues.shape
        image.point_arrays["values"] = gridvalues.flatten(order="F")
        plotter = pv.BackgroundPlotter()
        plotter.add_mesh(image, cmap="bone", opacity=0.5)

        def makemesh(surf, meshtype="StructuredGrid", points='evalpts'):

            if points == 'evalpts':
                pts = np.array(surf.evalpts)
                pts_square = pts.reshape((*surf.data['sample_size'], -1))
            elif points == 'ctrlpts':
                pts = np.array(surf.ctrlpts)
                pts_square = pts.reshape((*surf.data['size'], -1))

            if meshtype.lower() == 'PolyData'.lower():
                mesh = pv.PolyData(pts_square)

            if meshtype.lower() == 'StructuredGrid'.lower():
                mesh = pv.StructuredGrid()
                mesh.points = pts
                mesh.dimensions = [*np.flip(surf.data['sample_size']), 1]
            return mesh

        plotter.add_mesh(makemesh(surf), color='blue')
        plotter.add_mesh(makemesh(surf, 'PolyData'), color='blue')

        plotter.add_mesh(makemesh(outputsurf), color='red')
        plotter.add_mesh(makemesh(outputsurf, 'PolyData'), color='red')

        plotter.add_mesh(makemesh(surf, 'PolyData', 'ctrlpts'), color='cyan')
        plotter.add_mesh(makemesh(outputsurf, 'PolyData', 'ctrlpts'),
                         color='orange')

        if plane_widget:
            plotter.add_mesh_clip_plane(image)

        plotter.show_grid()
        plotter.show()

        return plotter
Ejemplo n.º 16
0
def create_uniform_vector(u,v,w, spacing):
    vel = np.sqrt(u **2 + v**2 + w**2)

    mesh = pv.UniformGrid()
    mesh.dimensions = np.array(u.shape) + 1

    # grid.origin = (100, 33, 55.6)  # The bottom left corner of the data set
    mesh.spacing = spacing  # These are the cell sizes along each axis
    
    mesh.cell_arrays["u"] = u.flatten(order="F")  # Flatten the array!
    mesh.cell_arrays["v"] = v.flatten(order="F") 
    mesh.cell_arrays["w"] = w.flatten(order="F")

    mesh.cell_arrays["Velocity"] = vel.flatten(order="F")
    mesh.set_active_scalars("Velocity")
    return mesh
Ejemplo n.º 17
0
def load_uniform():
    """Load a sample uniform grid.

    Returns
    -------
    pyvista.UniformGrid
        Dataset.

    Examples
    --------
    >>> from pyvista import examples
    >>> dataset = examples.load_uniform()
    >>> dataset.plot()

    """
    return pyvista.UniformGrid(uniformfile)
Ejemplo n.º 18
0
def plotCSD3d_pyvistaSlice(coords,
                           path=None,
                           filename_root='Solution.dat',
                           **kwargs):  # add kwards or *args for pyvista plot

    if path is None:
        cwd = os.getcwd()
        path = cwd

    filename = path + filename_root

    data_2_plot = np.genfromtxt(filename)
    coord_x = data_2_plot[:, 0]
    coord_y = data_2_plot[:, 1]
    coord_z = data_2_plot[:, 2]
    coord = data_2_plot[:, :-1]

    opacity = [0, 0, 0.1, 0.3, 0.6, 0.9, 1]
    grid = pv.UniformGrid()
    spc = (max(coord_x) - min(coord_x)) / 10
    xdim = int(round((max(coord_x) - min(coord_x)) / spc))
    ydim = int(round((max(coord_y) - min(coord_y)) / spc))
    zdim = int(round((max(coord_z) - min(coord_z)) / spc))
    grid.dimensions = (xdim, ydim, zdim)
    grid.dimensions = np.array(grid.dimensions) + 1
    grid.origin = (min(coord_x), min(coord_y), min(coord_z)
                   )  # The bottom left corner of the data set
    grid.spacing = (spc, spc, spc)  # These are the cell sizes along each axis

    pv.set_plot_theme('document')
    poly = pv.PolyData(coord)
    print('interpolation spacing=' + str(spc))
    interpolated = grid.interpolate(poly, radius=spc * 2)
    cmap = plt.cm.get_cmap('jet', 10)
    contours = interpolated.contour()

    single_slice = interpolated.slice(normal=[0, 1, 0])
    p = pv.Plotter(notebook=False)
    p.add_mesh(interpolated.outline(), color="k")
    p.add_mesh(single_slice, cmap=cmap)
    p.view_xz()
    p.add_axes()
    p.show_axes()
    p.show_grid()
    p.show_bounds(font_size=16)
    p.show(auto_close=True)
Ejemplo n.º 19
0
    def _from_array(self, image):
        """Create a texture from a np.ndarray."""
        if not 2 <= image.ndim <= 3:
            # we support 2 [single component image] or 3 [e.g. rgb or rgba] dims
            raise ValueError('Input image must be nn by nm by RGB[A]')

        if image.ndim == 3:
            if not 3 <= image.shape[2] <= 4:
                raise ValueError('Third dimension of the array must be of size 3 (RGB) or 4 (RGBA)')
            n_components = image.shape[2]
        elif image.ndim == 2:
            n_components = 1

        grid = pyvista.UniformGrid((image.shape[1], image.shape[0], 1))
        grid.point_arrays['Image'] = np.flip(image.swapaxes(0, 1), axis=1).reshape((-1, n_components), order='F')
        grid.set_active_scalars('Image')
        return self._from_image_data(grid)
Ejemplo n.º 20
0
def create_grid(dataset, dimensions=(101, 101, 101)):
    """Creates a uniform grid surrounding the given dataset with the specified
    dimensions. This grid is commonly used for interpolating the input dataset.
    """
    bounds = np.array(dataset.bounds)
    if dimensions is None:
        # TODO: we should implement an algorithm to automaitcally deterime an
        # "optimal" grid size by looking at the sparsity of the points in the
        # input dataset - I actaully think VTK might have this implemented
        # somewhere
        raise NotImplementedError('Please specifiy dimensions.')
    dimensions = np.array(dimensions)
    image = pyvista.UniformGrid()
    image.dimensions = dimensions
    image.spacing = (bounds[1::2] - bounds[:-1:2]) / (dimensions - 1)
    image.origin = bounds[::2]
    return image
Ejemplo n.º 21
0
def test_plot_multi_component_array():
    """"Test adding a texture to a plot"""
    image = pyvista.UniformGrid((3, 3, 3))

    # fixed this to allow for image regression testing
    # image['array'] = np.random.randn(*image.dimensions).ravel(order='f')
    image['array'] = np.array([
        -0.2080155, 0.45258783, 1.03826775, 0.38214289, 0.69745718,
        -2.04209996, 0.7361947, -1.59777205, 0.74254271, -0.27793002,
        -1.5788904, -0.71479534, -0.93487136, -0.95082609, -0.64480196,
        -1.79935993, -0.9481572, -0.34988819, 0.17934252, 0.30425682,
        -1.31709916, 0.02550247, -0.27620985, 0.89869448, -0.13012903,
        1.05667384, 1.52085349
    ])

    plotter = pyvista.Plotter()
    plotter.add_mesh(image, scalars='array')
    plotter.show(before_close_callback=verify_cache_image)
Ejemplo n.º 22
0
    def vectors(self, factor=1):
        # You need to install PyVista to use this function!
        grid = pv.UniformGrid()
        grid.dimensions = np.array(self.xvoxels.voxels.shape) + 1
        grid.origin = self.xvoxels.lower
        grid.spacing = self.xvoxels.voxel_size
        grid.cell_data.values = self.xvoxels.voxels.flatten(order="F")

        vectors = grid.cell_centers()

        vectors["vectors"] = np.vstack((
            self.xvoxels.voxels.flatten(order="F"),
            self.yvoxels.voxels.flatten(order="F"),
            self.zvoxels.voxels.flatten(order="F"),
        )).T

        vectors.active_vectors_name = 'vectors'
        return vectors.glyph(factor=factor)
Ejemplo n.º 23
0
def test_grid_points():
    """Test the points mehtods on UniformGrid and inearGrid"""
    points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1],
                       [1, 0, 1], [1, 1, 1], [0, 1, 1]])
    grid = pyvista.UniformGrid()
    grid.points = points
    assert grid.dimensions == [2, 2, 2]
    assert grid.spacing == [1, 1, 1]
    assert grid.origin == [0., 0., 0.]
    assert np.allclose(np.unique(grid.points, axis=0), np.unique(points,
                                                                 axis=0))
    opts = np.c_[grid.x, grid.y, grid.z]
    assert np.allclose(np.unique(opts, axis=0), np.unique(points, axis=0))
    # Now test rectilinear grid
    del grid
    grid = pyvista.RectilinearGrid()
    grid.points = points
    assert grid.dimensions == [2, 2, 2]
    assert np.allclose(np.unique(grid.points, axis=0), np.unique(points,
                                                                 axis=0))
Ejemplo n.º 24
0
    def vectors(self, factor=1):
        # You need to install PyVista to use this function!
        grid = pv.UniformGrid()

        shape = self.xpixels.pixels.shape
        grid.dimensions = [shape[0] + 1, shape[1] + 1, 1]
        grid.origin = list(self.xpixels.lower) + [0]
        grid.spacing = list(self.xpixels.pixel_size) + [0]
        grid.cell_data.values = self.xpixels.pixels.flatten(order="F")

        vectors = grid.cell_centers()

        vectors["vectors"] = np.vstack((
            self.xpixels.pixels.flatten(order="F"),
            self.ypixels.pixels.flatten(order="F"),
            np.zeros(len(self.xpixels.pixels.flatten())),
        )).T

        vectors.active_vectors_name = 'vectors'
        return vectors.glyph(factor=factor)
    def plot(self, plane_widget=True, **kwargs):

        # Display the arrows
        plotter = pv.BackgroundPlotter()

        cmap = kwargs.pop('cmap', 'bone')
        opacity = kwargs.pop('opacity', 0.5)

        grid = pv.UniformGrid()
        grid.dimensions = self.array.shape
        grid.point_arrays["values"] = self.array.flatten(order="F")
        plotter.add_mesh(grid, cmap=cmap, opacity=opacity, **kwargs)

        if plane_widget:
            plotter.add_mesh_clip_plane(grid)

        plotter.show_grid()
        plotter.show()

        return plotter
Ejemplo n.º 26
0
def numpy_to_pvgrid(Data, origin=(0, 0, 0), spacing=(1, 1, 1)):
    '''
    Convert 3D numpy array to pyvista uniform grid
    
    '''
    import numpy as np

    if module_exists('pyvista', 1):
        import pyvista
    else:
        return 1
    # Create the spatial reference
    grid = pyvista.UniformGrid()
    # Set the grid dimensions: shape + 1 because we want to inject our values on the CELL data
    grid.dimensions = np.array(Data.shape) + 1
    # Edit the spatial reference
    grid.origin = origin  # The bottom left corner of the data set
    grid.spacing = spacing  # These are the cell sizes along each axis
    # Add the data values to the cell data
    grid.cell_arrays['values'] = Data.flatten(order='F')  # Flatten the array!

    return grid
Ejemplo n.º 27
0
def test_wrappers():
    vtk_data = vtk.vtkPolyData()
    pv_data = pyvista.wrap(vtk_data)
    assert isinstance(pv_data, pyvista.PolyData)

    class Foo(pyvista.PolyData):
        """A user defined subclass of pyvista.PolyData."""
        pass

    default_wrappers = pyvista._wrappers.copy()
    # Use try...finally to set and reset _wrappers
    try:
        pyvista._wrappers['vtkPolyData'] = Foo

        pv_data = pyvista.wrap(vtk_data)
        assert isinstance(pv_data, Foo)

        tri_data = pv_data.delaunay_2d()

        assert isinstance(tri_data, Foo)

        uniform_grid = pyvista.UniformGrid()
        surface = uniform_grid.extract_surface()

        assert isinstance(surface, Foo)

        surface.delaunay_2d(inplace=True)
        assert isinstance(surface, Foo)

        sphere = pyvista.Sphere()
        assert isinstance(sphere, Foo)

        circle = pyvista.Circle()
        assert isinstance(circle, Foo)

    finally:
        pyvista._wrappers = default_wrappers  # always reset back to default
Ejemplo n.º 28
0
    def showVolume(self):
        data = self.extractVolume()
        self.plotter.clear()
        # self.plotter.show_bounds(grid=True, location='back')

        grid = pv.UniformGrid()
        grid.dimensions = numpy.array(data.shape) + 1
        x1, x2, y1, y2, z1, z2 = self.getVolumeBounds()
        grid.origin = (0, 0, 0)  # The bottom left corner of the data set
        w, h, d = data.shape
        grid.spacing = ((x2 - x1) / w, (y2 - y1) / h, (z2 - z1) / d
                        )  # These are the cell sizes along each axis
        grid.cell_arrays["values"] = data.flatten(order="F")

        # /////////////////////////////////////////////////////////
        # example https://docs.pyvista.org/examples/00-load/create-uniform-grid.html
        if self.type.currentText() == 'vr':
            self.plotter.add_volume(grid,
                                    opacity=self.opacity.currentText(),
                                    cmap=self.cmap.currentText(),
                                    blending=self.blending.currentText())

        elif self.type.currentText() == 'threshold':
            self.plotter.add_mesh_threshold(grid)

        elif self.type.currentText() == 'isovalue':
            self.plotter.add_mesh_isovalue(
                pv.wrap(data))  # TODO, aspect ratio not working

        elif self.type.currentText() == 'slice':
            self.plotter.add_mesh_slice(grid)

        else:
            raise Exception("internal error")

        self.plotter.reset_camera()
Ejemplo n.º 29
0
def load_uniform():
    """Load a sample uniform grid."""
    return pyvista.UniformGrid(uniformfile)
Ejemplo n.º 30
0
def read(filename, attrs=None, file_format=None):
    """Read any VTK file.

    It will figure out what reader to use then wrap the VTK object for
    use in PyVista.

    Parameters
    ----------
    filename : str
        The string path to the file to read. If a list of files is
        given, a :class:`pyvista.MultiBlock` dataset is returned with
        each file being a separate block in the dataset.

    attrs : dict, optional
        A dictionary of attributes to call on the reader. Keys of
        dictionary are the attribute/method names and values are the
        arguments passed to those calls. If you do not have any
        attributes to call, pass ``None`` as the value.

    file_format : str, optional
        Format of file to read with meshio.

    Examples
    --------
    Load an example mesh
    >>> import pyvista
    >>> from pyvista import examples
    >>> mesh = pyvista.read(examples.antfile)

    Load a vtk file

    >>> mesh = pyvista.read('my_mesh.vtk')  # doctest:+SKIP

    Load a meshio file

    >>> mesh = pyvista.read("mesh.obj")  # doctest:+SKIP
    """
    if isinstance(filename, (list, tuple)):
        multi = pyvista.MultiBlock()
        for each in filename:
            if isinstance(each, (str, pathlib.Path)):
                name = os.path.basename(str(each))
            else:
                name = None
            multi[-1, name] = read(each)
        return multi
    filename = os.path.abspath(os.path.expanduser(str(filename)))
    if not os.path.isfile(filename):
        raise FileNotFoundError('File ({}) not found'.format(filename))
    ext = get_ext(filename)

    # Read file using meshio.read if file_format is present
    if file_format:
        return read_meshio(filename, file_format)

    # From the extension, decide which reader to use
    if attrs is not None:
        reader = get_reader(filename)
        return standard_reader_routine(reader, filename, attrs=attrs)
    elif ext in '.vti':  # ImageData
        return pyvista.UniformGrid(filename)
    elif ext in '.vtr':  # RectilinearGrid
        return pyvista.RectilinearGrid(filename)
    elif ext in '.vtu':  # UnstructuredGrid
        return pyvista.UnstructuredGrid(filename)
    elif ext in ['.ply', '.obj', '.stl']:  # PolyData
        return pyvista.PolyData(filename)
    elif ext in '.vts':  # StructuredGrid
        return pyvista.StructuredGrid(filename)
    elif ext in ['.vtm', '.vtmb']:
        return pyvista.MultiBlock(filename)
    elif ext in ['.e', '.exo']:
        return read_exodus(filename)
    elif ext in ['.vtk']:
        # Attempt to use the legacy reader...
        return read_legacy(filename)
    elif ext in ['.jpeg', '.jpg']:
        return read_texture(filename).to_image()
    else:
        # Attempt find a reader in the readers mapping
        try:
            reader = get_reader(filename)
            return standard_reader_routine(reader, filename)
        except KeyError:
            # Attempt read with meshio
            try:
                from meshio._exceptions import ReadError
                try:
                    return read_meshio(filename)
                except ReadError:
                    pass
            except SyntaxError:
                # https://github.com/pyvista/pyvista/pull/495
                pass

    raise IOError(
        "This file was not able to be automatically read by pyvista.")