def model_to_rectgrid(model): grid = pv.RectilinearGrid(np.array(model.dy), np.array(model.dx), -np.array(model.dz)) vals = np.log10(np.swapaxes(np.flip(model.vals, 2), 0, 1)).flatten(order='F') grid.cell_arrays['Resitivity'] = vals return grid
def test_grid_points(): """Test the points methods on UniformGrid and RectilinearGrid""" # test creation of 2d grids x_surf = y_surf = range(3) z_surf = np.ones(3) grid = pyvista.UniformGrid() grid.points = np.array([x_surf, y_surf, z_surf]).transpose() assert grid.n_points == 9 assert grid.n_cells == 4 del grid 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))
def to_vtk_structured(pos, fields): # pragma: no cover """Create a vtk structured rectilinear grid from a field. Parameters ---------- pos : :class:`list` the position tuple, containing main direction and transversal directions fields : :class:`dict` or :class:`numpy.ndarray` Structured fields to be saved. Either a single numpy array as returned by SRF, or a dictionary of fields with theirs names as keys. Returns ------- :class:`pyvista.RectilinearGrid` A PyVista rectilinear grid of the structured field data. Data arrays live on the point data of this PyVista dataset. """ x, y, z, fields = _vtk_structured_helper(pos=pos, fields=fields) try: import pyvista as pv grid = pv.RectilinearGrid(x, y, z) grid.point_arrays.update(fields) except ImportError: raise ImportError("Please install PyVista to create VTK datasets.") return grid
def export_to_vtk(self, vtk_filename="geo_grid.vtr", real_coords=True, **kwds): """Export grid to VTK for visualisation **Arguments**: - *vtk_filename* = string : vtk filename (obviously...) - *real_coords* = bool : model extent in "real world" coordinates **Optional Keywords**: - *grid* = numpy grid : grid to save to vtk (default: self.grid) - *var_name* = string : name of variable to plot (default: Geology) """ grid = kwds.get("grid", self.grid) var_name = kwds.get("var_name", "Geology") # define coordinates x = np.zeros(self.nx + 1) y = np.zeros(self.ny + 1) z = np.zeros(self.nz + 1) x[1:] = np.cumsum(self.delx) y[1:] = np.cumsum(self.dely) z[1:] = np.cumsum(self.delz) # plot in coordinates if real_coords: x += self.xmin y += self.ymin z += self.zmin out = pv.RectilinearGrid(x, y, z) out['var_name'] = grid out.save(vtk_filename)
def test_create_rectilinear_grid_from_specs(): # 3D example xrng = np.arange(-10, 10, 2) yrng = np.arange(-10, 10, 5) zrng = np.arange(-10, 10, 1) grid = pyvista.RectilinearGrid(xrng, yrng, zrng) assert grid.n_cells == 9 * 3 * 19 assert grid.n_points == 10 * 4 * 20 assert grid.bounds == [-10.0, 8.0, -10.0, 5.0, -10.0, 9.0] # 2D example cell_spacings = np.array([1., 1., 2., 2., 5., 10.]) x_coordinates = np.cumsum(cell_spacings) y_coordinates = np.cumsum(cell_spacings) grid = pyvista.RectilinearGrid(x_coordinates, y_coordinates) assert grid.n_cells == 5 * 5 assert grid.n_points == 6 * 6 assert grid.bounds == [1., 21., 1., 21., 0., 0.]
def test_implicit_distance(): surface = pyvista.Cone(direction=(0,0,-1), height=3.0, radius=1, resolution=50, ) xx = yy = zz = 1 - np.linspace(0, 51, 11) * 2 / 50 dataset = pyvista.RectilinearGrid(xx, yy, zz) res = dataset.compute_implicit_distance(surface) assert "implicit_distance" in res.point_arrays dataset.compute_implicit_distance(surface, inplace=True) assert "implicit_distance" in dataset.point_arrays
def test_clip_surface(): surface = pyvista.Cone(direction=(0,0,-1), height=3.0, radius=1, resolution=50, ) xx = yy = zz = 1 - np.linspace(0, 51, 51) * 2 / 50 dataset = pyvista.RectilinearGrid(xx, yy, zz) clipped = dataset.clip_surface(surface, invert=False) assert clipped.n_points < dataset.n_points clipped = dataset.clip_surface(surface, invert=False, compute_distance=True) assert clipped.n_points < dataset.n_points assert 'implicit_distance' in clipped.array_names
def test_xmlrectilineargridreader(tmpdir): tmpfile = tmpdir.join("temp.vtr") mesh = pyvista.RectilinearGrid() mesh.save(tmpfile.strpath) reader = pyvista.get_reader(tmpfile.strpath) assert reader.filename == tmpfile.strpath new_mesh = reader.read() assert isinstance(new_mesh, pyvista.RectilinearGrid) assert new_mesh.n_points == mesh.n_points assert new_mesh.n_cells == mesh.n_cells
def test_clip_surface(): surface = pyvista.Cone( direction=(0, 0, -1), height=3.0, radius=1, resolution=50, ) xx = yy = zz = 1 - np.linspace(0, 51, 51) * 2 / 50 dataset = pyvista.RectilinearGrid(xx, yy, zz) clipped = dataset.clip_surface(surface, invert=False) assert clipped.n_points < dataset.n_points
def test_clip_surface(): surface = pyvista.Cone(direction=(0,0,-1), height=3.0, radius=1, resolution=50, ) xx = yy = zz = 1 - np.linspace(0, 51, 11) * 2 / 50 dataset = pyvista.RectilinearGrid(xx, yy, zz) clipped = dataset.clip_surface(surface, invert=False) assert isinstance(clipped, pyvista.UnstructuredGrid) clipped = dataset.clip_surface(surface, invert=False, compute_distance=True) assert isinstance(clipped, pyvista.UnstructuredGrid) assert 'implicit_distance' in clipped.array_names clipped = dataset.clip_surface(surface.cast_to_unstructured_grid(),) assert isinstance(clipped, pyvista.UnstructuredGrid) assert 'implicit_distance' in clipped.array_names
def test_create_rectilinear_after_init(): x = np.array([0, 1, 2]) y = np.array([0, 5, 8]) z = np.array([3, 2, 1]) grid = pyvista.RectilinearGrid() grid.x = x assert grid.dimensions == [3, 1, 1] grid.y = y assert grid.dimensions == [3, 3, 1] grid.z = z assert grid.dimensions == [3, 3, 3] assert np.allclose(grid.x, x) assert np.allclose(grid.y, y) assert np.allclose(grid.z, z)
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.")
def cast_to_rectilinear_grid(self): """Cast this uniform grid to a :class:`pyvista.RectilinearGrid`.""" def gen_coords(i): coords = np.cumsum(np.insert(np.full(self.dimensions[i] - 1, self.spacing[i]), 0, 0) ) + self.origin[i] return coords xcoords = gen_coords(0) ycoords = gen_coords(1) zcoords = gen_coords(2) grid = pyvista.RectilinearGrid(xcoords, ycoords, zcoords) grid.point_arrays.update(self.point_arrays) grid.cell_arrays.update(self.cell_arrays) grid.field_arrays.update(self.field_arrays) grid.copy_meta_from(self) return grid
def load_rectilinear(): """Load a sample uniform grid. Returns ------- pyvista.RectilinearGrid Dataset. Examples -------- >>> from pyvista import examples >>> dataset = examples.load_rectilinear() >>> dataset.plot() """ return pyvista.RectilinearGrid(rectfile)
def test_grid_points(): """Test the points methods on UniformGrid and RectilinearGrid""" # test creation of 2d grids x = y = range(3) z = [ 0, ] xx, yy, zz = np.meshgrid(x, y, z, indexing='ij') points = np.c_[xx.ravel(order='F'), yy.ravel(order='F'), zz.ravel(order='F')] grid = pyvista.UniformGrid() with pytest.raises(AttributeError): grid.points = points grid.origin = (0.0, 0.0, 0.0) grid.dimensions = (3, 3, 1) grid.spacing = (1, 1, 1) assert grid.n_points == 9 assert grid.n_cells == 4 assert np.allclose(grid.points, points) 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.dimensions = [2, 2, 2] grid.spacing = [1, 1, 1] 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 grid = pyvista.RectilinearGrid() with pytest.raises(AttributeError): grid.points = points x, y, z = np.array([0, 1, 3]), np.array([0, 2.5, 5]), np.array([0, 1]) xx, yy, zz = np.meshgrid(x, y, z, indexing='ij') grid.x = x grid.y = y grid.z = z assert grid.dimensions == [3, 3, 2] assert np.allclose(grid.meshgrid, (xx, yy, zz)) assert np.allclose( grid.points, np.c_[xx.ravel(order='F'), yy.ravel(order='F'), zz.ravel(order='F')])
def test_save_rectilinear(extension, binary, tmpdir): filename = str(tmpdir.mkdir("tmpdir").join('tmp.%s' % extension)) ogrid = examples.load_rectilinear() ogrid.save(filename, binary) grid = pyvista.RectilinearGrid(filename) assert grid.n_cells == ogrid.n_cells assert np.allclose(grid.x, ogrid.x) assert np.allclose(grid.y, ogrid.y) assert np.allclose(grid.z, ogrid.z) assert grid.dimensions == ogrid.dimensions grid = pyvista.read(filename) assert isinstance(grid, pyvista.RectilinearGrid) assert grid.n_cells == ogrid.n_cells assert np.allclose(grid.x, ogrid.x) assert np.allclose(grid.y, ogrid.y) assert np.allclose(grid.z, ogrid.z) assert grid.dimensions == ogrid.dimensions
def volume_grid_geom_to_vtk(volgridgeom, origin=(0.0, 0.0, 0.0)): """Convert the 3D gridded volume to a :class:`pyvista.StructuredGrid` (or a :class:`pyvista.RectilinearGrid` when apprropriate) object contatining the 2D surface. Args: volgridgeom (:class:`omf.volume.VolumeGridGeometry`): the grid geometry to convert """ volgridgeom._validate_mesh() ox, oy, oz = volgridgeom.origin # Make coordinates along each axis x = ox + np.cumsum(volgridgeom.tensor_u) x = np.insert(x, 0, ox) y = oy + np.cumsum(volgridgeom.tensor_v) y = np.insert(y, 0, oy) z = oz + np.cumsum(volgridgeom.tensor_w) z = np.insert(z, 0, oz) # If axis orientations are standard then use a vtkRectilinearGrid if check_orientation(volgridgeom.axis_u, volgridgeom.axis_v, volgridgeom.axis_w): return pyvista.RectilinearGrid(x + origin[0], y + origin[1], z + origin[2]) # Otherwise use a vtkStructuredGrid # Build out all nodes in the mesh xx, yy, zz = np.meshgrid(x, y, z, indexing='ij') points = np.c_[xx.ravel('F'), yy.ravel('F'), zz.ravel('F')] # Rotate the points based on the axis orientations rotation_mtx = np.array( [volgridgeom.axis_u, volgridgeom.axis_v, volgridgeom.axis_w]) points = points.dot(rotation_mtx) output = pyvista.StructuredGrid() output.points = points output.dimensions = len(x), len(y), len(z) output.points += np.array(origin) return output
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))
""" Append Cell Centers ~~~~~~~~~~~~~~~~~~~ This example will demonstrate how to append a dataset's cell centers as a length 3 tuple array. This example demonstrates :class:`PVGeo.filters.AppendCellCenters` """ import pyvista import os from pyvista import examples from PVGeo.filters import AppendCellCenters ############################################################################### # Use an example mesh from pyvista dir_path = "./data" rectfile = os.path.join(dir_path, 'rectilinear.vtk') mesh = pyvista.RectilinearGrid(rectfile) print(mesh) ############################################################################### # Run the PVGeo algorithm centers = AppendCellCenters().apply(mesh) print(centers) ############################################################################### centers.plot()
def read_distributed_vtr(dir_name): files = natsorted(glob.glob(dir_name + "/*.vtr")) blocks = pyvista.MultiBlock([pyvista.RectilinearGrid(f) for f in files]) return blocks.combine()
def to_rectilinear_grid(self): """Create a PyVista ``RectilinearGrid``.""" import pyvista return pyvista.RectilinearGrid(self.dx, self.dy, self.dz)
# In[12]: dims = (10, 10, 10) grid = pyvista.UniformGrid(dims) # Using default spacing and origin spacing = (2, 1, 5) grid = pyvista.UniformGrid(dims, spacing) # Usign default origin origin = (10, 35, 50) grid = pyvista.UniformGrid(dims, spacing, origin) # Everything is specified grid.plot() # ### vtkRectilinearGrid # In[14]: xrng = np.arange(-10, 10, 2) yrng = np.arange(-10, 10, 5) zrng = np.arange(-10, 10, 1) grid = pyvista.RectilinearGrid(xrng, yrng, zrng) grid.plot() # In[ ]:
def test_read_rectilinear_grid_from_pathlib(): grid = pyvista.RectilinearGrid(pathlib.Path(examples.rectfile)) assert grid.n_cells == 16146 assert grid.n_points == 18144 assert grid.bounds == [-350.0, 1350.0, -400.0, 1350.0, -850.0, 0.0] assert grid.n_arrays == 1
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.")
# sphinx_gallery_thumbnail_number = 4 import pyvista as pv from pyvista import examples import numpy as np ############################################################################### surface = pv.Cone(direction=(0, 0, -1), height=3.0, radius=1, resolution=50, capping=False) # Make a gridded dataset n = 51 xx = yy = zz = 1 - np.linspace(0, n, n) * 2 / (n - 1) dataset = pv.RectilinearGrid(xx, yy, zz) # Preview the problem p = pv.Plotter() p.add_mesh(surface, color='w', label='Surface') p.add_mesh(dataset, color='gold', show_edges=True, opacity=0.75, label='To Clip') p.add_legend() p.show() ############################################################################### # Take a look at the implicit function used to perform the surface clipping by # using the :func:`pyvista.DataSetFilters.compute_implicit_distance` filter.
def load_rectilinear(): """Load a sample uniform grid.""" return pyvista.RectilinearGrid(rectfile)
def plot_datasets(dataset_type=None): """Plot the pyvista dataset types. This demo plots the following PyVista dataset types: * :class:`pyvista.PolyData` * :class:`pyvista.UnstructuredGrid` * :class:`pyvista.UniformGrid` * :class:`pyvista.RectilinearGrid` * :class:`pyvista.StructuredGrid` Parameters ---------- dataset_type : str, optional If set, plot just that dataset. Must be one of the following: * ``'PolyData'`` * ``'UnstructuredGrid'`` * ``'UniformGrid'`` * ``'RectilinearGrid'`` * ``'StructuredGrid'`` Examples -------- >>> from pyvista import demos >>> demos.plot_datasets() """ allowable_types = ['PolyData', 'UnstructuredGrid', 'UniformGrid', 'RectilinearGrid', 'StructuredGrid'] if dataset_type is not None: if dataset_type not in allowable_types: raise ValueError(f'Invalid dataset_type {dataset_type}. Must be one ' f'of the following: {allowable_types}') ########################################################################### # uniform grid image = pv.UniformGrid((6, 6, 1)) image.spacing = (3, 2, 1) ########################################################################### # RectilinearGrid xrng = np.array([0, 0.3, 1, 4, 5, 6, 6.2, 6.6]) yrng = np.linspace(-2, 2, 5) zrng = [1] rec_grid = pv.RectilinearGrid(xrng, yrng, zrng) ########################################################################### # structured grid ang = np.linspace(0, np.pi/2, 10) r = np.linspace(6, 10, 8) z = [0] ang, r, z = np.meshgrid(ang, r, z) x = r*np.sin(ang) y = r*np.cos(ang) struct_grid = pv.StructuredGrid(x[::-1], y[::-1], z[::-1]) ########################################################################### # polydata points = pv.PolyData([[1, 2, 2], [2, 2, 2]]) line = pv.Line() line.points += np.array((2, 0, 0)) line.clear_data() tri = pv.Triangle() tri.points += np.array([0, 1, 0]) circ = pv.Circle() circ.points += np.array([1.5, 1.5, 0]) poly = tri + circ ########################################################################### # unstructuredgrid pyr = pv.Pyramid() pyr.points *= 0.7 cube = pv.Cube(center=(2, 0, 0)) ugrid = circ + pyr + cube + tri if dataset_type is not None: pl = pv.Plotter() else: pl = pv.Plotter(shape='3/2') # polydata if dataset_type is None: pl.subplot(0) pl.add_text('4. PolyData') if dataset_type in [None, 'PolyData']: pl.add_points(points, point_size=20) pl.add_mesh(line, line_width=5) pl.add_mesh(poly) pl.add_mesh(poly.extract_all_edges(), line_width=2, color='k') # unstructuredgrid if dataset_type is None: pl.subplot(1) pl.add_text('5. UnstructuredGrid') if dataset_type in [None, 'UnstructuredGrid']: pl.add_mesh(ugrid) pl.add_mesh(ugrid.extract_all_edges(), line_width=2, color='k') # UniformGrid if dataset_type is None: pl.subplot(2) pl.add_text('1. UniformGrid') if dataset_type in [None, 'UniformGrid']: pl.add_mesh(image) pl.add_mesh(image.extract_all_edges(), color='k', style='wireframe', line_width=2) pl.camera_position = 'xy' # RectilinearGrid if dataset_type is None: pl.subplot(3) pl.add_text('2. RectilinearGrid') if dataset_type in [None, 'RectilinearGrid']: pl.add_mesh(rec_grid) pl.add_mesh(rec_grid.extract_all_edges(), color='k', style='wireframe', line_width=2) pl.camera_position = 'xy' # StructuredGrid if dataset_type is None: pl.subplot(4) pl.add_text('3. StructuredGrid') if dataset_type in [None, 'StructuredGrid']: pl.add_mesh(struct_grid) pl.add_mesh(struct_grid.extract_all_edges(), color='k', style='wireframe', line_width=2) pl.camera_position = 'xy' pl.show()