def create_array_plot(path, time_indices, source_expr, img_gen_func, times): pv.set_plot_theme("document") nind = len(time_indices) size = 8 print("start array plot generation") fig, axes = plt.subplots(nind, 3, figsize=(size*3.3, nind*size)) for j, idx in enumerate(time_indices): for i,view in enumerate(views): p, _ = img_gen_func(j, view=view) img = p.screenshot(transparent_background=False, return_img=True, window_size=None, filename=path + f"_{view}_{times[idx]:.3f}.png") p.clear() #fig2,ax2 = plt.subplots() #ax2.imshow(img) #ax2.axis('off') #fig2.tight_layout() #fig2.savefig(path + f"{view}_{times[idx]:.4f}.pdf") axes[j,i].imshow(img) axes[j,i].set_title(f"t = {times[idx]:.3f} s",fontsize=26) axes[j,i].axis('off') fig.tight_layout() fig.savefig(path + "_array_plot.pdf")
def visualize(points, predict): pv.set_plot_theme("document") plt = pv.Plotter(shape=(4, 2), window_size=(400, 800)) for i in range(4): plt.subplot(i, 0) plt.add_mesh( points[i], render_points_as_spheres=True, point_size=8.0, ambient=0.1, diffuse=0.8, specular=0.5, specular_power=100.0, ) plt.subplot(i, 1) mesh = pv.PolyData(predict[i]) mesh["colors"] = np.arange(predict[i].shape[0]) plt.add_mesh( mesh, render_points_as_spheres=True, point_size=8.0, ambient=0.1, diffuse=0.8, specular=0.5, specular_power=100.0, ) plt.link_views() plt.camera_position = [ (5.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0), ] plt.show("ShapeNet") plt.close()
def render_surface(self, scalar_func): obj = numpy_to_pyvista(self.v, self.f) pv.set_plot_theme('document') surf_plotter = pv.Plotter() surf_plotter.link_views() surf_plotter.add_mesh(obj, scalars=scalar_func, cmap='jet') return surf_plotter
def create_movie(disloc_files, solutes_files, output_name): pv.set_plot_theme("document") plotter = pv.Plotter() plotter.open_movie(output_name) plotter.remove_scalar_bar() display = True plotter.view_isometric() plotter.view_xz() plotter.add_axes(interactive=True) for disloc_f, solutes_f in tqdm(zip(disloc_files, solutes_files)): # import pdb; pdb.set_trace() plotter.remove_actor(['disloc', 'solute']) dislocation = pv.read(disloc_f) solutes = pv.read(solutes_f) plotter.add_mesh(dislocation, name = 'disloc', show_scalar_bar=False, render_lines_as_tubes=True, line_width=10) # plotter.add_mesh(solutes, show_scalar_bar=False,name = 'solute',) plotter.add_mesh(solutes, # name = 'solute', show_scalar_bar=False, render_points_as_spheres=True, point_size=20,) if display: print('Orient the view, then press "q" to close window and produce movie') plotter.show(auto_close=False) display = False plotter.write_frame() plotter.close()
def test_themes(theme): try: pyvista.set_plot_theme(theme.name) assert pyvista.global_theme == theme.value() finally: # always return to testing theme pyvista.set_plot_theme('testing')
def plot_grid(self, filename='Data/Results/dome.vtu', lighting=False, property='PORO', show_edges=True, specular=0.0, specular_power=0.0, show_scalar_bar=True, cmap='viridis'): r""" Plot the grid with PyVista. Parameters ---------- filename : string, default is 'Data/Results/dome.vtu' String holding the path to VTU file. lighting : boolean, default is False Enable or disable view direction lighting. property : string, default is 'PORO' String holding the name of property that will be plotted. show_edges : boolean, default is True Shows the edges of a mesh. Does not apply to a wireframe representation. specular : float, default is 0.0 The specular lighting coefficient. specular_power : float, default is 0.0 The specular power. Between 0.0 and 128.0. show_scalar_bar : boolean, default is True If False, a scalar bar will not be added to the scene. cmap : string, default is 'viridis' Name of the Matplotlib colormap to us when mapping the 'scalars'. See available Matplotlib colormaps. Notes ----- https://www.pyvista.org/ """ import matplotlib.pyplot as plt import pyvista as pv # Check if file exists and can be open misc.file_open_exception(filename) # Check if grid is already defined if self._grid_type == 'corner-point': misc.check_corner_point_grid(self._cart_dims, self._coord, self._zcorn) else: misc.check_cartesian_grid(self._cart_dims, self._dx, self._dy, self._dz, self._tops) # Set theme pv.set_plot_theme("document") # Color map cmap = plt.cm.get_cmap(cmap, 5) # Mesh to be plotted mesh = pv.UnstructuredGrid(misc.get_path(filename)) # Remove ghost cells if they are present in the mesh if 'ACTNUM' in mesh.array_names: ghosts = np.argwhere(mesh["ACTNUM"] < 1) mesh.remove_cells(ghosts) # Plot the grid mesh.plot(lighting=lighting, specular=specular, specular_power=specular_power, show_edges=show_edges, scalars=property, show_scalar_bar=show_scalar_bar, cmap=cmap)
def test_set_theme(): theme = pyvista.themes.DarkTheme() try: pyvista.set_plot_theme(theme) assert pyvista.global_theme == theme finally: # always return to testing theme pyvista.set_plot_theme('testing')
def plot2d(**kargs): cmd_args = get_cmd() args = update_args(cmd_args, dict_args=kargs) args = check_args(args) pv.set_plot_theme("document") for f in args.fName: print('\n', '-' * 80, '\n', f) print(f) fpng = _plot_(f, args) yield(fpng)
def displayer(numpy_mask): data_matrix = numpy_mask opacity = [0, 0, 0, 4, 8, 0, 0] data = pv.wrap(data_matrix) pv.set_plot_theme("night") #print(type(data)) #pyvista.core.grid.UniformGrid' #print(dir(data)) #x = pickle.dumps(data) #print(x) #print(BytesIO(data)) return data
def plot_obj_vtk(obj_path, vtk_path): pv.set_plot_theme("default") obj = pv.read(obj_path) vtk = pv.read(vtk_path) plotter = pv.Plotter() plotter.add_axes() plotter.add_mesh(obj, label='My Mesh', show_scalar_bar=False) plotter.add_mesh(vtk, label='Rays', cmap="jet", show_scalar_bar=False) plotter.show_bounds() plotter.show(cpos="xy", screenshot="obj_vtk.png")
def plot_mesh_montage(vb, fb=None, nb=None, strategy='mesh', labelb=None, grid_on=False, clr='lightcoral', normal_clr='lightblue', smooth_shade_on=False, show_edges=False, normal_scale=1): """ :param vb: tensor | list - [b x nv x 3] batch of meshes or list of length b with tensors [nvx3] :param fb: tensor | list | None - (optional) [b x nf x 3] batch of face indices OR a list of length b with tensors [nfx3] OR a [nf x 3] in the case of a uniform face array for all meshes :param nb: tensor | list | None - (optional) [b x nf|nv x 3] batch of normals. See above :param labelb: list of titles for each mesh, or None * For other arguments, see plot_mesh * For windows keyboard options, see: https://docs.pyvista.org/plotting/plotting.html """ if isinstance(vb, (np.ndarray, np.generic)): n_meshes = vb.shape[0] else: n_meshes = len(vb) pv.set_plot_theme("document") # White background n_rows = math.floor(math.sqrt(n_meshes)) n_cols = math.ceil(n_meshes / n_rows) shape = (n_rows, n_cols) p = pv.Plotter(shape=shape) r, c = np.unravel_index(range(n_meshes), shape) for i in range(n_meshes): f = fb if fb is None or (hasattr(fb, 'shape') and len(fb.shape) == 2) else fb[i] # Uniform faces support. fb[i] is equiv to fb[i,:,:] n = nb if nb is None else nb[i] label = labelb if labelb is None else labelb[i] p.subplot(r[i], c[i]) mesh_append(p, v=vb[i], f=f, n=n, strategy=strategy, label=label, grid_on=grid_on, normal_scale=normal_scale, clr=clr, normal_clr=normal_clr, smooth_shade_on=smooth_shade_on, show_edges=show_edges) p.link_views() p.show()
def test_issue_566(): from pyvista import set_plot_theme set_plot_theme('document') geo_model = gp.create_model('Model1') geo_model = gp.init_data(geo_model, extent=[0, 791, 0, 200, -582, 0], resolution=[100, 10, 100]) geo_model.set_default_surfaces() geo_model.add_surface_points(X=223, Y=0.01, Z=-94, surface='surface1')
def plot_seeg_3dbrain(raw): """Convenience function for plotting 3d brain and the 3 leads.""" # camera position for ventral view cpos = [ (192.1355480872916, -142.5172055994041, -261.47527261474386), (24.065850569725583, -19.416839467317363, 15.642167878335641), (0.20039110730958792, 0.9346693866417147, -0.29366058943283213), ] pv.set_plot_theme("document") plotter = pv.Plotter(off_screen=True, window_size=[350, 700]) cloud = helper.plot_3d_brain() actor = plotter.add_mesh(cloud, opacity=1) xyz_all = np.array([ich["loc"][:3] for ich in raw.info["chs"]]) picks_all = [range(8), range(8, 14), range(14, 19)] colors = ["purple", "#41A859", "dodgerblue"] # plot each lead in a different color for i, picks in enumerate(picks_all): ch_names = ["ecog%i" % i for i in picks] lead1 = raw.copy().pick_channels(ch_names) xyz = np.array([ich["loc"][:3] for ich in lead1.info["chs"]]) # slightly adjust coordinates to prevent electrodes from being invisible xyz[:, 0] += 4 xyz[:, 2] -= 4 electrodes = pv.PolyData(xyz) act_electrodes = plotter.add_mesh( electrodes, point_size=25, color=colors[i], render_points_as_spheres=True, ) xyz_all[:, 0] += 4 xyz_all[:, 2] -= 4 for ii, pick in enumerate(picks1): electrodes = pv.PolyData(xyz_all[pick]) act_electrodes = plotter.add_mesh( electrodes, point_size=40, color=colors_sel[ii], render_points_as_spheres=True, ) plotter.show(cpos=cpos, title=str(cpos), screenshot="../figures/3dbrain_seeg.png") plotter.screenshot("../figures/3dbrain_seeg.png", transparent_background=True) plotter.close()
def plot_heatmap(vtk_path): pv.set_plot_theme("Paraview") vtk = pv.read(vtk_path) plotter = pv.Plotter() plotter.add_axes() plotter.show_bounds(ticks="outside") plotter.add_mesh(vtk, show_scalar_bar=False) plotter.add_scalar_bar(title="Incident flux, (W)", width=0.5, position_x=0.25, position_y=0.9) plotter.show(cpos="xz", screenshot="heatmap.png")
def disp_results(filename, items): pv.set_plot_theme("document") mesh = pv.PolyData(filename + '.STL') plotter = pv.Plotter() plotter.add_mesh(mesh, opacity=0.3, color='#FFFFFF') shapetypes = [ 'O ring', 'Through hole', 'Blind hole', 'Triangular passage', 'Rectangular passage', 'Circular through slot', 'Triangular through slot', 'Rectangular through slot', 'Rectangular blind slot', 'Triangular pocket', 'Rectangular pocket', 'Circular end pocket', 'Triangular blind step', 'Circular blind step', 'Rectangular blind step', 'Rectangular through step', '2-sides through step', 'Slanted through step', 'Chamfer', 'Round', 'Vertical circular end blind slot', 'Horizontal circular end blind slot', '6-sides passage', '6-sides pocket' ] colors = [ '#000080', '#FF0000', '#FFFF00', '#00BFFF', '#DC143C', '#DAA520', '#DDA0DD', '#708090', '#556B2F', '#483D8B', '#CD5C5C', '#21618C', '#1C2833', '#4169E1', '#1E90FF', '#FFD700', '#FF4500', '#646464', '#DC143C', '#98FB98', '#9370DB', '#8B4513', '#00FF00', '#008080' ] flag = np.zeros(24) for i in range(items.shape[0]): if flag[int(items[i, 6])] == 0: plotter.add_mesh(pv.Cube((0, 0, 0), 0, 0, 0, (items[i, 0], items[i, 3], items[i, 1], items[i, 4], items[i, 2], items[i, 5])), opacity=1, color=colors[int(items[i, 6])], style='wireframe', line_width=2, label=shapetypes[int(items[i, 6])]) #print(shapetypes[int(items[i,6])]) flag[int(items[i, 6])] = 1 else: plotter.add_mesh(pv.Cube((0, 0, 0), 0, 0, 0, (items[i, 0], items[i, 3], items[i, 1], items[i, 4], items[i, 2], items[i, 5])), opacity=1, color=colors[int(items[i, 6])], style='wireframe', line_width=2) plotter.add_legend() plotter.show()
def test_backwards_compatibility(): try: color = (0.1, 0.4, 0.7) pyvista.rcParams['color'] = color assert pyvista.rcParams['color'] == color # test nested values init_value = pyvista.rcParams['axes']['show'] pyvista.rcParams['axes']['show'] = not init_value assert pyvista.rcParams['axes']['show'] is not init_value finally: # always return to testing theme pyvista.set_plot_theme('testing')
def plot_results(mapdl: MapdlCorba, theme="document"): mapdl.post1() pv.set_plot_theme(theme) plotter = pv.Plotter(shape=(2, 2)) mapdl.result.plot_nodal_stress(0, comp="x", show_displacement=True, cpos="xy", plotter=plotter, add_text=False, title="Nodal stress X") plotter.subplot(0, 1) mapdl.result.plot_nodal_stress(0, comp="y", show_displacement=True, cpos="xy", plotter=plotter, add_text=False, title="Nodal stress y") plotter.subplot(1, 0) mapdl.result.plot_nodal_solution(0, comp='norm', show_displacement=True, lighting=False, background='w', text_color='k', show_edges=True, cpos='xy', add_text=False, plotter=plotter, title="Displacement norm") plotter.subplot(1, 1) mapdl.result.plot_nodal_solution(0, comp='x', show_displacement=True, lighting=False, background='w', text_color='k', show_edges=True, cpos='xy', add_text=False, plotter=plotter, title="Displacement X") # mapdl.result.plot_nodal_displacement(0, show_displacement=True, cpos="xy") plotter.link_views() plotter.show(full_screen=True) #plotter.show(screenshot=True) #plotter.screenshot(f'multiplot_results') return
def new_plot(self, ph_opacity = .1,el_opacity = 1, po_opacity = 1): import pyvista as pv pv.set_plot_theme("night") plotter = pv.Plotter() if self.photon_mesh: plotter.add_mesh(self.photon_mesh, line_width = 0.001, color='white', opacity=ph_opacity) if self.electron_mesh: plotter.add_mesh(self.electron_mesh, line_width = 0.001, color='blue', opacity=el_opacity) if self.positron_mesh: plotter.add_mesh(self.positron_mesh,line_width = 0.001, color='red', opacity=po_opacity) return plotter
def test_themes(): old_rcParms = dict(pyvista.rcParams) # must cache old rcParams pyvista.set_plot_theme('paraview') pyvista.set_plot_theme('document') pyvista.set_plot_theme('night') pyvista.set_plot_theme('default') for key, value in old_rcParms.items(): pyvista.rcParams[key] = value
def plot_geometry(mapdl: MapdlCorba, theme="document"): pv.set_plot_theme(theme) plotter = pv.Plotter(shape=(2, 2)) mapdl.nplot(plotter=plotter, knum=False, color='') plotter.subplot(0, 1) mapdl.lplot(plotter=plotter, color='') #color_lines=True) # color="#000000") plotter.subplot(1, 0) mapdl.aplot(plotter=plotter, color='') plotter.subplot(1, 1) mapdl.eplot(plotter=plotter, color='') plotter.link_views() plotter.show() # plotter.show(screenshot=True) # plotter.screenshot(f'multiplot_example') return
def run(self): # Init on consumer side: pv.set_plot_theme("document") while 1: try: if self.last_plotted_epoch != -1 and self.sd['poison']: # Plotted at least one time + Poison print(f'Pipe poison detected. Displaying one last time, and then exiting plotting supervisor') self.try_update_data(final=True) self.plot_data() break except (BrokenPipeError, EOFError): # Missing parent print(f'Producer missing. Exiting plotting supervisor') break self.try_update_data() self.plot_data()
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)
def multiblock_gif(mb, s): # mb = mb.clip_box([0, 31.5, -2, 0.1, 0, 0], invert=False) pv.set_plot_theme("document") plotter = pv.Plotter(window_size=(1300, 600)) plotter.open_gif('mbgif.gif') plotter.open_movie('mbgif.mp4', framerate=1) # camera xc = (mb.bounds[1] + mb.bounds[0]) / 2 yc = (mb.bounds[3] + mb.bounds[2]) * 2.5 / 4 cam = [[xc, yc, mb.length], [xc, yc, 0], [0, 1, 0]] plotter.camera_position = cam # color bar args sba = dict(width=0.5, position_x=0.25, height=0.1, position_y=0.025) # data plotter.show(auto_close=False) for vtk in mb: vtk = prepare_cov(vtk, 'cov') plotter.add_mesh( vtk, scalars=s, opacity='cov', show_edges=False, edge_color='darkgrey', show_scalar_bar=True, scalar_bar_args=sba, stitle='volumetric water content', cmap='viridis', clim=(0.2, 0.6), ) plotter.show_bounds( mesh=vtk, grid='k', location='outer', ticks=True, font_size=14, font_family='times', use_2d=True, padding=0, xlabel='m', ylabel='m', ) plotter.write_frame() plotter.clear() plotter.close()
def __init__(self,model=None): """Initilaization method for the MeshVisualization class This method initializes a new instance of the MeshVisualization class and visualizes the mesh of the passed GmshModel instance. Within the method, basic visualization settings are defined, before the visualization method is called. Parameters: model: GmshModel object instance model for which the mesh has to be visualized """ # plausibility checks for input arguments if model is None: raise TypeError("No model instance to visualize passed. For the visualization of a model, that model has to be known. Check your input data.") self.model=model # set plotting theme pv.set_plot_theme("paraview") # use Paraview style for plotting # get necessary model information for the default configuration physicalIDs=model.getIDsFromTags(model.gmshAPI.getPhysicalGroups(dim=model.dimension)) # get group IDs for physical groups of the highest dimension modelBBox=model._getGmshModelBoundingBox() # get the overall bounding box of the Gmsh model # define settings self.defaultSettings={ "lowerThreshold": min(physicalIDs), # set lower threshold value to minimum value of active scalar field "upperThreshold": max(physicalIDs), # set upper threshold value to minimum value of active scalar field "boxBounds": modelBBox.T.reshape(6) # define bounds of extraction box to match bounds of the model (factor 1.25 will be applied automatically) } self.currentSettings=cp.deepcopy(self.defaultSettings) # copy default settings as initial version of current settings # initialize arrays required for proper mesh visualization self.plotterObj=pv.Plotter(title="GmshModel Mesh Visualization") # initialize plotterObj from pyvista and set title self.mesh=None # initialize mesh self.thresholdAlgorithm=None # initialize threshold algorithm self.extractionBox=vtk.vtkBox() # initiliaze dummy extraction box to update information of boxWidget self.extractionBoxBounds=pv.PolyData() # initialize dummy extraction box bounds to store information of boxWidget bounds self.extractionAlgorithm=None # initialize extraction algorithm self.activeWidgets=[] # initialize list of active widgets # visualize the model mesh self.visualizeMesh()
def visualize(points, labels, predict=None): pv.set_plot_theme("document") categories = dsets.ModelNet40.categories plt = pv.Plotter(shape=(4, 4), window_size=(800, 800)) for row in range(4): for col in range(4): i = row * 4 + col plt.subplot(row, col) plt.add_mesh( points[i], render_points_as_spheres=True, point_size=8.0, ambient=0.1, diffuse=0.8, specular=0.5, specular_power=100.0, ) plt.add_text( categories[labels[i]], font_size=13, position="upper_edge", font="arial", shadow=False, ) if predict is not None: if predict is not None: color = "red" if predict[i] != labels[i] else "green" plt.add_text( categories[predict[i]], font_size=13, color=color, position="lower_edge", font="arial", shadow=False, ) plt.link_views() plt.camera_position = [ (0.0, 0.0, -5.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0), ] plt.show("ModelNet40") plt.close()
def plot_mesh(v, f=None, n=None, strategy='mesh', grid_on=False, clr='lightcoral', normal_clr='lightblue', label=None, smooth_shade_on=False, show_edges=False, cmap=None, normal_scale=1): """ :param v: tensor - A numpy or torch [nv x 3] vertex tensor :param f: tensor | None - (optional) A numpy or torch [nf x 3] vertex tensor OR None :param n: tensor | None - (optional) A numpy or torch [nf x 3] or [nv x3] vertex or face normals. Must input f when inputting a face-normal tensor :param strategy: One of ['spheres','cloud','mesh'] :param grid_on: bool - Plots an xyz grid with the mesh. Default is False :param clr: str or [R,G,B] float list or tensor - Plots mesh with color clr. clr = v is cool :param normal_clr: str or [R,G,B] float list or tensor - Plots mesh normals with color normal_clr :param label: str - (optional) - When inputted, displays a legend with the title label :param smooth_shade_on: bool - Plot a smooth version of the facets - just like 3D-Viewer :param show_edges: bool - Show edges in black. Only applicable for strategy == 'mesh' For color list, see pyvista.plotting.colors * For windows keyboard options, see: https://docs.pyvista.org/plotting/plotting.html """ pv.set_plot_theme("document") # White background p = pv.Plotter() mesh_append(p, v=v, f=f, n=n, grid_on=grid_on, strategy=strategy, clr=clr, normal_clr=normal_clr, label=label, smooth_shade_on=smooth_shade_on, show_edges=show_edges, cmap=cmap, normal_scale=normal_scale) p.show()
def PlotMesh3D(self, NodeNumber=True, ElementNumber=True, Loads=True, BC=True, FontMag=1): pyvista.set_plot_theme('document') 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' pyvista.global_theme.transparent_background = True plotter = pyvista.Plotter( lighting='three lights', off_screen=False, ) mesh = pyvista.PolyData(self.Nodes, np.vstack((np.ones(np.array(self.El).shape[0], int)*2, (np.array(self.El)-1).T)).T) plotter.add_mesh( mesh.copy(), render_lines_as_tubes=False, line_width=2-5, style='wireframe', cmap="turbo", color="#1f77b4", show_scalar_bar=False, culling=True, ) plotter.enable_parallel_projection() plotter.add_mesh( mesh.copy(), render_points_as_spheres=True, point_size=5, style='points', cmap="turbo", color="#1f77b4", show_scalar_bar=False, culling=True, ) plotter.show( full_screen=False, interactive=True, )
def test_themes(theme): pyvista.set_plot_theme(theme) if theme != 'default': assert pyvista.rcParams != pyvista.DEFAULT_THEME pyvista.set_plot_theme('default') assert pyvista.rcParams == pyvista.DEFAULT_THEME # always return to testing theme pyvista.set_plot_theme('testing')
names=['time', 'vtu']) files = files.dropna() time_list = files['time'].tolist() list_vtu = files['vtu'].tolist() list_vtu = [i.replace('.pvtu', '.0000.vtu') for i in list_vtu] #Read VTK data for i in range(0, len(list_vtu)): #Read DF from VTK files exec(f'df_{i} = pv.read(f\'{currentPath}/{list_vtu[i]}\')') #Selecet a data to apply the slice exec(f'df = df_{0}') #Choose the white background for the figure pv.set_plot_theme("document") #Convert Cell data to point data, and then do it the opposite way #to spread the cell data to the entire cell region df = df.cell_data_to_point_data() df = df.point_data_to_cell_data() #Select a slice of the domain single_slice = df.slice(normal=[0, 1, 0], origin=[0, 0, 0]) #Create a plotter plotter = pv.Plotter(off_screen=None) plotter.camera.position = (0, 2.5, 0.55) plotter.camera.focal_point = (0, 0, 0.55) plotter.camera.roll -= 90
from matplotlib.colors import rgb2hex from PyPDF2 import PdfFileWriter, PdfFileReader from scipy.spatial.transform import Rotation as R from matplotlib.colors import LinearSegmentedColormap sys.path.append(r"D:\git_pulls\Phenotypic_PointCloud_Analysis") # script_dir = pathlib.Path(os.path.dirname(os.path.realpath(__file__))) from Code.visual_utils import * from Code.pycpd_registrations_3D import consolidate_vtk, consolidate_case directory = pathlib.Path(r"D:\Desktop\Carla\paper_3_final\results") os.chdir(directory) # Set the theme, default, dark, pv.set_plot_theme("default") rename_dict = {"__": "_"} # Define the input name and read in to memory for visualization mesh_name = "consolidated_means.vtk" input_mesh = pv.read(mesh_name) # This expects variable names to follow a convention. rename_dict = {"_std": "_standard_dev", "__": "_", "_coef": "_coef_var"} input_mesh = scalar_name_cleanup(input_mesh=input_mesh, replace_dict=rename_dict) input_mesh.save(f"{mesh_name}") max_norm_list = [ item for item in list(input_mesh.point_arrays) if "max_norm" in item