def test_load_structured_bad_filename(): with pytest.raises(Exception): pyvista.StructuredGrid('not a file') filename = os.path.join(test_path, 'test_grid.py') with pytest.raises(Exception): grid = pyvista.StructuredGrid(filename)
def test_load_structured_bad_filename(): with pytest.raises(FileNotFoundError): pyvista.StructuredGrid('not a file') filename = os.path.join(test_path, 'test_grid.py') with pytest.raises(ValueError): grid = pyvista.StructuredGrid(filename)
def test_init_structured(): xrng = np.arange(-10, 10, 2) yrng = np.arange(-10, 10, 2) zrng = np.arange(-10, 10, 2) x, y, z = np.meshgrid(xrng, yrng, zrng) grid = pyvista.StructuredGrid(x, y, z) assert np.allclose(sgrid.x, x) assert np.allclose(sgrid.y, y) assert np.allclose(sgrid.z, z) grid_a = pyvista.StructuredGrid(grid) assert np.allclose(grid_a.points, grid.points)
def _generate_vtk_err(): """Simple operation which generates a VTK error.""" x, y, z = np.meshgrid(np.arange(-10, 10, 0.5), np.arange(-10, 10, 0.5), np.arange(-10, 10, 0.5)) mesh = pyvista.StructuredGrid(x, y, z) x2, y2, z2 = np.meshgrid(np.arange(-1, 1, 0.5), np.arange(-1, 1, 0.5), np.arange(-1, 1, 0.5)) mesh2 = pyvista.StructuredGrid(x2, y2, z2) alg = vtk.vtkStreamTracer() obs = pyvista.Observer() obs.observe(alg) alg.SetInputDataObject(mesh) alg.SetSourceData(mesh2) alg.Update()
def generateSurface(p, xLim=(0, 10), yLim=(0, 10), size=6, tau=3, cmap='Blues'): x = np.linspace(xLim[0], xLim[1], 200) y = np.linspace(yLim[0], yLim[1], 200) X, Y = np.meshgrid(x, y, indexing='ij') tempX = X - size tempX[tempX >= 0] = 0 tempX = 1 - np.exp(tempX / tau) tempY = 1 - 0.05 * np.abs(Y) - 0.001 * np.abs(Y)**2 putGrid = pv.StructuredGrid(X, Y, tempX * tempY * 10) putGrid.point_arrays['put'] = tempX.flatten(order='F') p.add_mesh(putGrid, scalars='put', opacity=0.6, cmap=cmap, show_scalar_bar=False) return
def set_structured_grid(self, regular_grid=None, data: Union[dict, gp.Solution, str] = 'Default', name='lith', **kwargs): if regular_grid is None: regular_grid = self.model.grid.regular_grid g_values = regular_grid.values g_3D = g_values.reshape(*regular_grid.resolution, 3).T rg = pv.StructuredGrid(*g_3D) self.set_scalar_data(rg, data, name) if name == 'lith': n_faults = self.model.faults.df['isFault'].sum() cmap = mcolors.ListedColormap(list(self.lith_c[n_faults:])) kwargs['cmap'] = kwargs.get('cmap', cmap) self.vista_rgrids_mesh[name] = rg actor = self.p.add_mesh(rg, **kwargs) self.vista_rgrids_actors[name] = actor return actor
def _plotting3D(self, val, disp, title, colormap): pyvista.global_theme.axes.box = False pyvista.global_theme.axes.x_color = 'black' pyvista.global_theme.axes.y_color = 'black' pyvista.global_theme.axes.z_color = 'black' pyvista.global_theme.font.color = 'black' grid = pyvista.StructuredGrid(disp[:, 0, :].flatten(order="C"), disp[:, 1, :].flatten(order="C"), disp[:, 2, :].flatten(order="C")) grid.cell_data[title] = val.flatten(order="C")[:-1] grid.plot(off_screen=False, full_screen=False, interactive=True, parallel_projection=True, show_axes=True, show_bounds=False, # scalars=colors, render_lines_as_tubes=True, style='wireframe', line_width=10, cmap=colormap, lighting='three lights', show_scalar_bar=True, background='w')
def grid_from_sph_coords(theta, phi, r): """Create a structured grid from arrays of spherical coordinates. Parameters ---------- theta: array-like Azimuthal angle in degrees ``[0, 360]``. phi: array-like Polar (zenith) angle in degrees ``[0, 180]``. r: array-like Distance (radius) from the point of origin. Returns ------- pyvista.StructuredGrid Structured grid. """ x, y, z = np.meshgrid(np.radians(theta), np.radians(phi), r) # Transform grid to cartesian coordinates x_cart = z * np.sin(y) * np.cos(x) y_cart = z * np.sin(y) * np.sin(x) z_cart = z * np.cos(y) # Make a grid object return pyvista.StructuredGrid(x_cart, y_cart, z_cart)
def supertorus(yScale, xScale, Height, InternalRadius, Vertical, Horizontal, deltaX=0, deltaY=0, deltaZ=0): # initial range for values used in parametric equation n = 100 u = np.linspace(-np.pi, np.pi, n) t = np.linspace(-np.pi, np.pi, n) u, t = np.meshgrid(u, t) # a1: Y Scale <0, 2> a1 = yScale # a2: X Scale <0, 2> a2 = xScale # a3: Height <0, 5> a3 = Height # a4: Internal radius <0, 5> a4 = InternalRadius # e1: Vertical squareness <0.25, 1> e1 = Vertical # e2: Horizontal squareness <0.25, 1> e2 = Horizontal # Definition of parametric equation for supertorus x = a1 * (a4 + np.sign(np.cos(u)) * np.abs(np.cos(u)) ** e1) *\ np.sign(np.cos(t)) * np.abs(np.cos(t)) ** e2 y = a2 * (a4 + np.sign(np.cos(u)) * np.abs(np.cos(u)) ** e1) *\ np.sign(np.sin(t)) * np.abs(np.sin(t)) ** e2 z = a3 * np.sign(np.sin(u)) * np.abs(np.sin(u)) ** e1 grid = pyvista.StructuredGrid(x + deltaX + 5, y + deltaY + 5, z + deltaZ) return grid
def gridFromCylCoords(r, theta, z) -> pv.StructuredGrid: """ " Create PyVista StructuredGrid out of cylinder coordinates. Parameters ---------- r : numpy.ndarray Radial distances theta : numpy.ndarray Polar angles (in radians) z : numpy.ndarray Z-coordinates (heights) Returns ------- pyvista.StructuredGrid Mesh given the coordinates Notes ----- Last updated: 18.6.2021 """ x, y, z = np.meshgrid(r, theta, z) # Transform grid to cartesian coordinates x_cart = x * np.cos(y) y_cart = x * np.sin(y) z_cart = z # Make a grid object return pv.StructuredGrid(x_cart, y_cart, z_cart)
def test_project_points_to_plane(): # Define a simple Gaussian surface n = 20 x = np.linspace(-200, 200, num=n) + np.random.uniform(-5, 5, size=n) y = np.linspace(-200, 200, num=n) + np.random.uniform(-5, 5, size=n) xx, yy = np.meshgrid(x, y) A, b = 100, 100 zz = A * np.exp(-0.5 * ((xx / b)**2. + (yy / b)**2.)) poly = pyvista.StructuredGrid(xx, yy, zz).extract_geometry() poly['elev'] = zz.ravel(order='f') # Wrong normal length with pytest.raises(TypeError): poly.project_points_to_plane(normal=(0, 0, 1, 1)) # allow Sequence but not Iterable with pytest.raises(TypeError): poly.project_points_to_plane(normal={0, 1, 2}) # Test the filter projected = poly.project_points_to_plane(origin=poly.center, normal=(0, 0, 1)) assert np.allclose(projected.points[:, -1], poly.center[-1]) projected = poly.project_points_to_plane(normal=(0, 1, 1)) assert projected.n_points # finally, test inplace poly.project_points_to_plane(normal=(0, 1, 1), inplace=True) assert np.allclose(poly.points, projected.points)
def glyphs(grid_sz=3, **kwargs): """Create several parametric supertoroids using VTK's glyph table functionality.""" n = 10 values = np.arange(n) # values for scalars to look up glyphs by # taken from: rng = np.random.default_rng() params = rng.uniform(0.5, 2, size=(n, 2)) # (n1, n2) parameters for the toroids geoms = [pv.ParametricSuperToroid(n1=n1, n2=n2) for n1, n2 in params] # get dataset where to put glyphs x, y, z = np.mgrid[:grid_sz, :grid_sz, :grid_sz] mesh = pv.StructuredGrid(x, y, z) # add random scalars rng_int = rng.integers(0, n, size=x.size) mesh.point_arrays['scalars'] = rng_int # construct the glyphs on top of the mesh; don't scale by scalars now return mesh.glyph(geom=geoms, indices=values, scale=False, factor=0.3, rng=(0, n - 1))
def plot_structured_grid(self, regular_grid=None, data: Union[dict, str] = 'Default', name='lith', **kwargs): # Remove previous actor with the same name: try: self.p.remove_actor(self.vista_rgrids_actors[name]) except KeyError: pass self.update_colot_lot() if regular_grid is None: regular_grid = self.model.grid.regular_grid g_values = regular_grid.values g_3D = g_values.reshape(*regular_grid.resolution, 3).T rg = pv.StructuredGrid(*g_3D) self.plot_scalar_data(rg, data, name) if name == 'lith': n_faults = self.model.faults.df['isFault'].sum() cmap = mcolors.ListedColormap(list(self._color_lot[n_faults:])) kwargs['cmap'] = kwargs.get('cmap', cmap) self.vista_rgrids_mesh[name] = rg actor = self.p.add_mesh(rg, **kwargs) self.vista_rgrids_actors[name] = actor return actor
def create_regular_mesh(self, scalar_field: str = 'all', data: Union[dict, str] = 'Default', series: str = '', render_topography: bool = True, ): regular_grid = self.model._grid.regular_grid if regular_grid.values is self._grid_values: regular_grid_mesh = self.regular_grid_mesh else: # If the regular grid changes we need to create a new grid. Otherwise we can append it to the # previous self._grid_values = regular_grid.values grid_3d = self._grid_values.reshape(*regular_grid.resolution, 3).T regular_grid_mesh = pv.StructuredGrid(*grid_3d) # Set the scalar field-Activate it-getting cmap? regular_grid_mesh, cmap = self.set_scalar_data(regular_grid_mesh, data=data, scalar_field=scalar_field, series=series) if render_topography == True and regular_grid.mask_topo.shape[0] != 0 and True: main_scalar = 'id' if scalar_field == 'all' else regular_grid_mesh.array_names[-1] regular_grid_mesh[main_scalar][regular_grid.mask_topo.ravel(order='C')] = -100 regular_grid_mesh = regular_grid_mesh.threshold(-99, scalars=main_scalar) return regular_grid_mesh, cmap
def construct_to_save(self, env): batch_points = env.batch[self.points_key].detach().to('cpu').numpy() all_meshes = [] all_grids = [] for i, points in enumerate(batch_points): mesh = pv.StructuredGrid(points[0], points[1], points[2]) grid = {'points': points} for prop in self.properties: data_prop = env.batch[prop][i].detach().to('cpu').numpy() self.assign_prop_to_mesh(mesh, prop, data_prop) grid[prop] = data_prop for prop, name in zip([env.y_true, env.y_pred], ['y_true', 'y_pred']): prop = prop.detach().to('cpu').numpy()[i] self.assign_prop_to_mesh(mesh, name, prop) grid[name] = prop all_meshes.append(mesh) all_grids.append(grid) self.meshes_to_save = all_meshes self.grids_to_save = all_grids
def read_raster_output_vtk(input_f, directory='', scale=1): # Read in the data filename = os.path.join(directory, input_f) data = xr.open_rasterio(filename) values = np.asarray(data) nans = values == data.nodatavals if np.any(nans): values[nans] = np.nan # Make a mesh xx, yy = np.meshgrid(data['x'], data['y']) zz = values.reshape(xx.shape) # will make z-comp the values in the file # zz = np.zeros_like(xx) # or this will make it flat mesh = pv.StructuredGrid(xx, yy, scale * zz) mesh['elevation'] = values.ravel(order='F') mesh = mesh.warp_by_scalar() mesh.save(os.path.splitext(filename)[0] + '_scale{}.vtk'.format(scale)) # save as a vtk file return mesh ## Example use: # height_scale = 1 # input_f = 'test.tif' # directory = 'C:\folder\subfolder' # topo = read_raster_output_vtk(input_f, directory, scale=height_scale) # topo.plot()
def dem_data_process(self, dem_array_data, height_adjustment_factor, dem_mesh_xy='mesh_xy', dem_arrays='dem_array', dem_bounds='bounds', dem_grid_res='grid_res'): """The whole data process from dem data to pv.StructuredGrid Args: dem_array_data (pandas.core.frame.DataFrame): original dem data height_adjustment_factor (int): Height scaling factor, default 20 . dem_mesh_xy(str): set mesh_xy column name according to dem files dem_arrays(str): set dem array column name according to dem files dem_bounds(str): set bounds column name according to dem files dem_grid_res(str): set grid_res column name according to dem files Returns: Grid(pyvista.core.pointset.StructuredGrid) """ dem_array_data = self.dem_data_initial(dem_array_data, dem_bounds, dem_grid_res) xx, yy = dem_array_data[dem_mesh_xy] dem_array = dem_array_data[dem_arrays] grid = pv.StructuredGrid(xx, yy, dem_array * height_adjustment_factor) return grid
def read_raster(filename, out_crs="EPSG:3857", use_z=False): """Read a raster to a ``pyvista.StructuredGrid``. This will handle coordinate transformations. """ # Read in the data data = xr.open_rasterio(filename) values = np.asarray(data) nans = values == data.nodatavals if np.any(nans): # values = np.ma.masked_where(nans, values) values[nans] = np.nan # Make a mesh xx, yy = np.meshgrid(data["x"], data["y"]) if use_z and values.shape[0] == 1: # will make z-comp the values in the file zz = values.reshape(xx.shape) else: # or this will make it flat zz = np.zeros_like(xx) mesh = pv.StructuredGrid(xx, yy, zz) pts = mesh.points lon, lat = transform(data.crs, out_crs, pts[:, 0], pts[:, 1]) mesh.points[:, 0] = lon mesh.points[:, 1] = lat mesh["data"] = values.reshape(mesh.n_points, -1, order="F") return mesh
def render(self, ve=3, name='TEST.gif'): sy, sx, sz = np.shape(self.strat) x = np.linspace(self.xmin, self.xmin + sx * self.dx, sx) y = np.linspace(self.ymin, self.ymin + sy * self.dy, sy) xx, yy = np.meshgrid(x, y) zz = self.topo[:, :, 0] * ve grid = pv.StructuredGrid(xx, yy, zz) plotter = pv.Plotter() plotter.add_mesh(grid) plotter.show(auto_close=False) plotter.open_gif(name) pts = grid.points.copy() for i in range(4, sz - 1, 4): strat = topostrat(self.topo[:, :, 0:i + 1]) zz = strat[:, :, i] * ve pts[:, -1] = zz.T.ravel() plotter.update_coordinates(pts, render=False) plotter.write_frame() # this will trigger the render plotter.render() plotter.close()
def load_structured(): """Load a simple StructuredGrid.""" x = np.arange(-10, 10, 0.25) y = np.arange(-10, 10, 0.25) x, y = np.meshgrid(x, y) r = np.sqrt(x**2 + y**2) z = np.sin(r) return pyvista.StructuredGrid(x, y, z)
def test_quality_struct(): x = np.arange(-10, 10, 5) y = np.arange(-10, 10, 5) z = np.arange(-10, 10, 5) x, y, z = np.meshgrid(x, y, z) grid = pv.StructuredGrid(x, y, z) qual = pyansys.quality(grid) assert (qual == 1).all()
def test_invalid_init_structured(): xrng = np.arange(-10, 10, 2) yrng = np.arange(-10, 10, 2) zrng = np.arange(-10, 10, 2) x, y, z = np.meshgrid(xrng, yrng, zrng) z = z[:, :, :2] with pytest.raises(Exception): grid = pyvista.StructuredGrid(x, y, z)
def intensity(fname, h, k, l, intensity, B=np.eye(3)): T = np.eye(4) T[:3, :3] = B grid = pv.StructuredGrid(h, k, l) grid.point_data['intensity'] = intensity.flatten(order='F') grid.transform(T) grid.save(fname, binary=True)
def generateSurface1(p, xLim=(0, 10), yLim=(0, 10), size=6, tau=3, cmap='Blues', yShift=0): x = np.linspace(xLim[0], xLim[1], 200) y = np.linspace(yLim[0], yLim[1], 200) X, Y = np.meshgrid(x, y, indexing='ij') tempX = X - size tempX[tempX >= 0] = 0 tempX = 1 - np.exp(tempX / tau) tempY = 1 - 0.05 * np.abs(Y - np.sin(X) * 1.5) - 0.001 * np.abs(Y - np.sin(X) * 1.5)**2 putGrid = pv.StructuredGrid(X, Y + yShift, tempX * tempY * 10) putGrid.point_arrays['put'] = tempX.flatten(order='F') p.add_mesh(putGrid, scalars='put', opacity=0.6, cmap=cmap, show_scalar_bar=False) # Generate the sine plot ... xPts = X[:, 0] zPts = np.zeros(len(xPts)) yPts = -np.sin(xPts) * 1.5 points = np.column_stack((xPts, yPts, zPts)) path = pv.PolyData() path.points = points cells = np.arange(0, len(points), dtype=np.int) cells = np.insert(cells, 0, len(points)) path.lines = cells path["value"] = np.ones(xPts.shape) tube = path.tube(radius=0.1, scalars='value', radius_factor=10) p.add_mesh(tube, color='#a3e4d7') temp = p.add_point_labels([(18, 2, 0)], ['stock price'], font_family='times', font_size=30, fill_shape=False, shape=None, bold=False, text_color='#a3e4d7', show_points=False, point_size=0, point_color=(0.3, 0.3, 0.3)) return
def q5_plot(corse=0.1, len=10): u = np.arange(-1 * len, len, corse) v = np.arange(-1 * len, len, corse) u, v = np.meshgrid(u, v) denometer = u**2 + v**2 + 1 x = 2 * u / denometer y = 2 * v / denometer z = (u**2 + v**2 - 1) / denometer grid = pv.StructuredGrid(x, y, z) grid.plot(screenshot="Q5")
def test_glyph(): for i, dataset in enumerate(DATASETS): result = dataset.glyph() assert result is not None assert isinstance(result, pyvista.PolyData) # Test different options for glyph filter sphere = pyvista.Sphere(radius=3.14) sphere_sans_arrays = sphere.copy() # make cool swirly pattern vectors = np.vstack((np.sin(sphere.points[:, 0]), np.cos(sphere.points[:, 1]), np.cos(sphere.points[:, 2]))).T # add and scale sphere.vectors = vectors * 0.3 sphere.point_arrays['foo'] = np.random.rand(sphere.n_points) sphere.point_arrays['arr'] = np.ones(sphere.n_points) result = sphere.glyph(scale=False) result = sphere.glyph(scale='arr') result = sphere.glyph(scale='arr', orient='Normals', factor=0.1) result = sphere.glyph(scale='arr', orient='Normals', factor=0.1, tolerance=0.1) result = sphere.glyph(scale='arr', orient='Normals', factor=0.1, tolerance=0.1, clamping=False, rng=[1, 1]) # passing one or more custom glyphs; many cases for full coverage geoms = [ pyvista.Sphere(), pyvista.Arrow(), pyvista.ParametricSuperToroid() ] indices = range(len(geoms)) result = sphere.glyph(geom=geoms[0]) result = sphere.glyph(geom=geoms, indices=indices, rng=(0, len(geoms))) result = sphere.glyph(geom=geoms) result = sphere.glyph(geom=geoms, scale='arr', orient='Normals', factor=0.1, tolerance=0.1) result = sphere.glyph(geom=geoms[:1], indices=[None]) result = sphere_sans_arrays.glyph(geom=geoms) with pytest.raises(TypeError): # wrong type for the glyph sphere.glyph(geom=pyvista.StructuredGrid()) with pytest.raises(TypeError): # wrong type for the indices sphere.glyph(geom=geoms, indices=set(indices)) with pytest.raises(ValueError): # wrong length for the indices sphere.glyph(geom=geoms, indices=indices[:-1])
def supertorus(yScale, xScale, Height, InternalRadius, Vertical, Horizontal, deltaX=0, deltaY=0, deltaZ=0): """Graphing parametric supertoroidal surfaces Args: yScale ([type]): [description] xScale ([type]): [description] Height ([type]): [description] InternalRadius ([type]): [description] Vertical ([type]): [description] Horizontal ([type]): [description] deltaX (int, optional): [description]. Defaults to 0. deltaY (int, optional): [description]. Defaults to 0. deltaZ (int, optional): [description]. Defaults to 0. Returns: [type]: [description] """ # initial range for values used in parametric equation n = 100 u = np.linspace(-np.pi, np.pi, n) t = np.linspace(-np.pi, np.pi, n) u, t = np.meshgrid(u, t) # a1: Y Scale <0, 2> a1 = yScale # a2: X Scale <0, 2> a2 = xScale # a3: Height <0, 5> a3 = Height # a4: Internal radius <0, 5> a4 = InternalRadius # e1: Vertical squareness <0.25, 1> e1 = Vertical # e2: Horizontal squareness <0.25, 1> e2 = Horizontal # Definition of parametric equation for supertorus x = a1 * (a4 + np.sign(np.cos(u)) * np.abs(np.cos(u)) ** e1) *\ np.sign(np.cos(t)) * np.abs(np.cos(t)) ** e2 y = a2 * (a4 + np.sign(np.cos(u)) * np.abs(np.cos(u)) ** e1) *\ np.sign(np.sin(t)) * np.abs(np.sin(t)) ** e2 z = a3 * np.sign(np.sin(u)) * np.abs(np.sin(u))**e1 grid = pyvista.StructuredGrid(x + deltaX + 5, y + deltaY + 5, z + deltaZ) return grid
def test_xmlstructuredgridreader(tmpdir): tmpfile = tmpdir.join("temp.vts") mesh = pyvista.StructuredGrid() mesh.save(tmpfile.strpath) reader = pyvista.get_reader(tmpfile.strpath) assert reader.filename == tmpfile.strpath new_mesh = reader.read() assert isinstance(new_mesh, pyvista.StructuredGrid) assert new_mesh.n_points == mesh.n_points assert new_mesh.n_cells == mesh.n_cells
def __create_grid(data): shape = np.shape(data) # M.B. plot add to params az_grid = np.deg2rad(np.linspace(-60, 60, shape[1])) el_grid = np.deg2rad(np.linspace(-60, 60, shape[0])) az_mesh, el_mesh = np.meshgrid(az_grid, el_grid) r_mesh = data x_mesh = np.cos(az_mesh) * np.cos(el_mesh) * r_mesh y_mesh = np.sin(az_mesh) * np.cos(el_mesh) * r_mesh z_mesh = np.sin(el_mesh) * r_mesh grid = pv.StructuredGrid(x_mesh, y_mesh, z_mesh) return grid
def extended_line(self, fbo: FboItem): import pyvista as pv from pyvista import examples import numpy as np # Extract the data archive and load these files # 2D array of XYZ coordinates path = examples.download_gpr_path().points # 2D array of the data values from the imaging equipment data = examples.download_gpr_data_array() ############################################################################### assert len( path ) in data.shape, "Make sure coordinates are present for every trace." # If not, you'll need to interpolate the path! # Grab the number of samples (in Z dir) and number of traces/soundings nsamples, ntraces = data.shape # Might be opposite for your data, pay attention here # Define the Z spacing of your 2D section z_spacing = 0.12 # Create structured points draping down from the path points = np.repeat(path, nsamples, axis=0) # repeat the Z locations across tp = np.arange(0, z_spacing * nsamples, z_spacing) tp = path[:, 2][:, None] - tp points[:, -1] = tp.ravel() ############################################################################### # Make a StructuredGrid from the structured points grid = pv.StructuredGrid() grid.points = points grid.dimensions = nsamples, ntraces, 1 # Add the data array - note the ordering! grid["values"] = data.ravel(order="F") ############################################################################### # And now we can plot it! or process or do anything, because it is a PyVista # mesh and the possibilities are endless with PyVista cpos = [(1217002.366883762, 345363.80666238244, 3816.828857791056), (1216322.4753436751, 344033.0310674846, 3331.052985309526), (-0.17716571330686096, -0.25634368781817973, 0.9502106207279767)] fbo.add_mesh(grid, cmap="seismic", clim=[-1, 1]) fbo.add_mesh(pv.PolyData(path), color='orange') fbo.set_plot_theme("night") fbo.update()