def test_load_structured_bad_filename(): with pytest.raises(Exception): vtki.StructuredGrid('not a file') filename = os.path.join(test_path, 'test_grid.py') with pytest.raises(Exception): grid = vtki.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 = vtki.StructuredGrid(x, y, z) assert np.allclose(sgrid.x, x) assert np.allclose(sgrid.y, y) assert np.allclose(sgrid.z, z) grid_a = vtki.StructuredGrid(grid) assert np.allclose(grid_a.points, grid.points)
def read(filename): """This will read any VTK file! It will figure out what reader to use then wrap the VTK object for use in ``vtki`` """ def legacy(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.Update() return reader.GetOutputDataObject(0) ext = os.path.splitext(filename)[1] if ext.lower() in '.vtk': # Use a legacy reader and wrap the result return wrap(legacy(filename)) else: # From the extension, decide which reader to use if ext.lower() in '.vti': # ImageData return vtki.UniformGrid(filename) elif ext.lower() in '.vtr': # RectilinearGrid return vtki.RectilinearGrid(filename) elif ext.lower() in '.vtu': # UnstructuredGrid return vtki.UnstructuredGrid(filename) elif ext.lower() in '.ply': # PolyData return vtki.PolyData(filename) elif ext.lower() in '.vts': # UnstructuredGrid return vtki.StructuredGrid(filename) else: # Attempt to use the legacy reader... try: return wrap(legacy(filename)) except: pass raise IOError("This file was not able to be automatically read by vtki.")
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 = vtki.StructuredGrid(x, y, z)
def load_structured(): """ Loads 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 vtki.StructuredGrid(x, y, z)
def test_save_structured(extension, binary, tmpdir): filename = str(tmpdir.mkdir("tmpdir").join('tmp.%s' % extension)) sgrid.save(filename, binary) grid = vtki.StructuredGrid(filename) assert grid.x.shape == sgrid.y.shape assert grid.n_cells assert grid.points.shape == sgrid.points.shape
def grid_surface(points): """Inserts structured points onto a grid and adds an elevation filter """ points[:, 1] = points[::-1, 1] xu = np.unique(points[:, 0]) yu = np.unique(points[:, 1]) xx, yy = np.meshgrid(xu, yu) zz = points[:, 2].reshape(xx.shape) zz = np.flip(zz, axis=0) # Remove the last row because this is buggy xx = xx[0:-2, :] yy = yy[0:-2, :] zz = zz[0:-2, :] return vtki.StructuredGrid(xx, yy, zz).elevation()
def test_struct_example(): 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) # create and plot structured grid grid = vtki.StructuredGrid(x, y, z) cpos = grid.plot(off_screen=True) # basic plot assert isinstance(cpos, list) # Plot mean curvature cpos_curv = grid.plot_curvature(off_screen=True) assert isinstance(cpos_curv, list)
def read(filename, attrs=None): """This will read any VTK file! It will figure out what reader to use then wrap the VTK object for use in ``vtki``. 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)) 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 vtki.UniformGrid(filename) elif ext in '.vtr': # RectilinearGrid return vtki.RectilinearGrid(filename) elif ext in '.vtu': # UnstructuredGrid return vtki.UnstructuredGrid(filename) elif ext in ['.ply', '.obj', '.stl']: # PolyData return vtki.PolyData(filename) elif ext in '.vts': # StructuredGrid return vtki.StructuredGrid(filename) elif ext in ['.vtm', '.vtmb']: return vtki.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 vtki.")
def test_creatingagifmovie(tmpdir, off_screen=True): if tmpdir: filename = str(tmpdir.mkdir("tmpdir").join('wave.gif')) else: filename = '/tmp/wave.gif' 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) # Create and structured surface grid = vtki.StructuredGrid(x, y, z) # Make copy of points pts = grid.points.copy() # Start a plotter object and set the scalars to the Z height plotter = vtki.Plotter(off_screen=off_screen) plotter.add_mesh(grid, scalars=z.ravel()) plotter.plot(autoclose=False) # Open a gif plotter.open_gif(filename) # Update Z and write a frame for each updated position nframe = 5 for phase in np.linspace(0, 2 * np.pi, nframe + 1)[:nframe]: z = np.sin(r + phase) pts[:, -1] = z.ravel() plotter.update_coordinates(pts) plotter.update_scalars(z.ravel()) plotter.write_frame() # Close movie and delete object plotter.close()
import vtki import numpy as np # Make a grid: x, y, z = np.meshgrid(np.linspace(-5, 5, 20), np.linspace(-5, 5, 20), np.linspace(-5, 5, 5)) grid = vtki.StructuredGrid(x, y, z) vectors = np.sin(grid.points)**3 # Compute a direction for the vector field grid.point_arrays['mag'] = np.linalg.norm(vectors, axis=1) grid.point_arrays['vec'] = vectors # Make a geometric obhect to use as the glyph geom = vtki.Arrow() # This could be any dataset # Perform the glyph glyphs = grid.glyph(orient='vec', scale='mag', factor=0.8, geom=geom) # plot using the plotting class p = vtki.Plotter() p.add_mesh(glyphs) p.show()
surf.plot(texture=tex) ################################################################################ # But what if your dataset doesn't have texture coordinates? Then you can # harness the :func:`vtki.DataSetFilters.texture_map_to_plane` filter to # properly map an image to a dataset's surface. # For example, let's map that same image of bricks to a curvey surface: # create a structured surface 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) curvsurf = vtki.StructuredGrid(x, y, z) # Map the curved surface to a plane - use best fitting plane curvsurf.texture_map_to_plane(inplace=True) curvsurf.plot(texture=tex) ################################################################################ # Note that this process can be completed with any image texture! # use the puppy image tex = examples.download_puppy_texture() curvsurf.plot(texture=tex) ################################################################################ # Textures from Files
def plot_wave(fps=30, frequency=1, wavetime=3, interactive=False, off_screen=False, notebook=None): """ Plot a 3D moving wave in a render window. Parameters ---------- fps : int, optional Maximum frames per second to display. Defaults to 30. frequency: float, optional Wave cycles per second. Defaults to 1 wavetime : float, optional The desired total display time in seconds. Defaults to 3 seconds. interactive: bool, optional Allows the user to set the camera position before the start of the wave movement. Default False. off_screen : bool, optional Enables off screen rendering when True. Used for automated testing. Disabled by default. Returns ------- points : np.ndarray Position of points at last frame. """ # camera position cpos = [(6.879481857604187, -32.143727535933195, 23.05622921691103), (-0.2336056403734026, -0.6960083534590372, -0.7226721553894022), (-0.008900669873416645, 0.6018246347860926, 0.7985786667826725)] # Make data 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) # Create and plot structured grid sgrid = vtki.StructuredGrid(X, Y, Z) # Get pointer to points points = sgrid.points.copy() # Start a plotter object and set the scalars to the Z height plotter = vtki.Plotter(off_screen=off_screen, notebook=notebook) plotter.add_mesh(sgrid, scalars=Z.ravel()) plotter.camera_position = cpos plotter.plot( title='Wave Example', window_size=[800, 600], # auto_close=False, interactive=interactive) auto_close=False, interactive_update=True) # Update Z and display a frame for each updated position tdelay = 1. / fps tlast = time.time() tstart = time.time() while time.time() - tstart < wavetime: # get phase from start telap = time.time() - tstart phase = telap * 2 * np.pi * frequency Z = np.sin(R + phase) points[:, -1] = Z.ravel() # update plotting object, but don't automatically render plotter.update_coordinates(points, render=False) plotter.update_scalars(Z.ravel(), render=False) # Render and get time to render rstart = time.time() plotter.update() # plotter.render() rstop = time.time() # time delay tpast = time.time() - tlast if tpast < tdelay and tpast >= 0: time.sleep(tdelay - tpast) # get render time and actual FPS # rtime = rstop - rstart # act_fps = 1 / (time.time() - tlast + 1E-10) tlast = time.time() # Close movie and delete object plotter.close() return points