def k3d_plot(img, color_range=None): import k3d import numpy as np if color_range is None: img_array = sitk.GetArrayFromImage(img).ravel() color_range = [img_array.min(), img_array.max()] im_sitk = img img = sitk.GetArrayFromImage(im_sitk) size = np.array(im_sitk.GetSize()) * np.array(im_sitk.GetSpacing()) im_sitk.GetSize() volume = k3d.volume( img.astype(np.float32), alpha_coef=1000, shadow='dynamic', samples=1200, shadow_res=64, shadow_delay=50, color_range=color_range, color_map=(np.array(k3d.colormaps.matplotlib_color_maps.Gist_heat).reshape(-1,4) * np.array([1,1.75,1.75,1.75])).astype(np.float32), compression_level=9 ) volume.transform.bounds = [-size[0]/2,size[0]/2, -size[1]/2,size[1]/2, -size[2]/2,size[2]/2] plot = k3d.plot(camera_auto_fit=False) plot += volume plot.lighting = 2 plot.display()
def voxel2k3d(neuron, legendgroup, showlegend, label, color, **kwargs): """Convert VoxelNeuron to k3d object.""" # Skip empty neurons if min(neuron.shape) == 0: return [] img = neuron.grid if img.dtype not in (np.float32, np.float64): img = img.astype(np.float32) with warnings.catch_warnings(): warnings.simplefilter("ignore") trace_data = [k3d.volume(img.T, bounds=neuron.bbox.flatten(), interpolation=False, )] return trace_data
def getNotebookBackend(actors2show, zoom, viewup): vp = settings.plotter_instance if isinstance(vp.shape, str) or sum(vp.shape) > 2: colors.printc("Multirendering is not supported in jupyter.", c=1) return #################################################################################### # https://github.com/InsightSoftwareConsortium/itkwidgets # /blob/master/itkwidgets/widget_viewer.py if 'itk' in settings.notebookBackend: from itkwidgets import view settings.notebook_plotter = view(actors=actors2show, cmap='jet', ui_collapsed=True, gradient_opacity=False) #################################################################################### elif settings.notebookBackend == 'k3d': try: import k3d # https://github.com/K3D-tools/K3D-jupyter except: print("Cannot find k3d, install with: pip install k3d") return actors2show2 = [] for ia in actors2show: if not ia: continue if isinstance(ia, vtk.vtkAssembly): #unpack assemblies acass = ia.unpack() actors2show2 += acass else: actors2show2.append(ia) # vbb, sizes, _, _ = addons.computeVisibleBounds() # kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5] settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle], menu_visibility=True, # height=int(vp.size[1]/2), ) # settings.notebook_plotter.grid = kgrid settings.notebook_plotter.lighting = 1.2 # set k3d camera settings.notebook_plotter.camera_auto_fit = True if settings.plotter_instance and settings.plotter_instance.camera: k3dc = utils.vtkCameraToK3D(settings.plotter_instance.camera) if zoom: k3dc[0] /= zoom k3dc[1] /= zoom k3dc[2] /= zoom settings.notebook_plotter.camera = k3dc # else: # vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5] # vss = numpy.linalg.norm([vsx, vsy, vsz]) # if zoom: # vss /= zoom # vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target # if viewup == 'z': # vup = (0,0,1) # camera up vector # vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01 # camera position # elif viewup == 'x': # vup = (1,0,0) # vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2] # camera position # else: # vup = (0,1,0) # vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5 # camera position # settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2], # vfp[0], vfp[1], vfp[2], # vup[0], vup[1], vup[2] ] if not vp.axes: settings.notebook_plotter.grid_visible = False for ia in actors2show2: if isinstance(ia, (vtk.vtkCornerAnnotation, vtk.vtkAssembly)): continue kobj = None kcmap= None name = None if hasattr(ia, 'filename'): if ia.filename: name = os.path.basename(ia.filename) if ia.name: name = os.path.basename(ia.name) #####################################################################scalars # work out scalars first, Points Lines are also Mesh objs if isinstance(ia, (Mesh, shapes.Line, Points)): # print('scalars', ia.name, ia.N()) iap = ia.GetProperty() if isinstance(ia, (shapes.Line, Points)): iapoly = ia.polydata() else: iapoly = ia.clone().clean().triangulate().computeNormals().polydata() vtkscals = None color_attribute = None if ia.mapper().GetScalarVisibility(): vtkdata = iapoly.GetPointData() vtkscals = vtkdata.GetScalars() if vtkscals is None: vtkdata = iapoly.GetCellData() vtkscals = vtkdata.GetScalars() if vtkscals is not None: c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(iapoly) c2p.Update() iapoly = c2p.GetOutput() vtkdata = iapoly.GetPointData() vtkscals = vtkdata.GetScalars() if vtkscals is not None: if not vtkscals.GetName(): vtkscals.SetName('scalars') scals_min, scals_max = ia.mapper().GetScalarRange() color_attribute = (vtkscals.GetName(), scals_min, scals_max) lut = ia.mapper().GetLookupTable() lut.Build() kcmap=[] nlut = lut.GetNumberOfTableValues() for i in range(nlut): r,g,b,a = lut.GetTableValue(i) kcmap += [i/(nlut-1), r,g,b] #####################################################################Volume if isinstance(ia, Volume): # print('Volume', ia.name, ia.dimensions()) kx, ky, kz = ia.dimensions() arr = ia.getPointArray() kimage = arr.reshape(-1, ky, kx) colorTransferFunction = ia.GetProperty().GetRGBTransferFunction() kcmap=[] for i in range(128): r,g,b = colorTransferFunction.GetColor(i/127) kcmap += [i/127, r,g,b] kbounds = numpy.array(ia.imagedata().GetBounds()) \ + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\ * numpy.array([-1,1] * 3) kobj = k3d.volume(kimage.astype(numpy.float32), color_map=kcmap, #color_range=ia.imagedata().GetScalarRange(), alpha_coef=10, bounds=kbounds, name=name, ) settings.notebook_plotter += kobj #####################################################################text elif hasattr(ia, 'info') and 'formula' in ia.info.keys(): pos = (ia.GetPosition()[0],ia.GetPosition()[1]) kobj = k3d.text2d(ia.info['formula'], position=pos) settings.notebook_plotter += kobj #####################################################################Mesh elif isinstance(ia, Mesh) and ia.N() and len(ia.faces()): # print('Mesh', ia.name, ia.N(), len(ia.faces())) kobj = k3d.vtk_poly_data(iapoly, name=name, # color=_rgb2int(iap.GetColor()), color_attribute=color_attribute, color_map=kcmap, opacity=iap.GetOpacity(), wireframe=(iap.GetRepresentation()==1)) if iap.GetInterpolation() == 0: kobj.flat_shading = True settings.notebook_plotter += kobj #####################################################################Points elif isinstance(ia, Points) or ia.NPoints() == ia.NCells(): # print('Points', ia.name, ia.N()) kcols=[] if color_attribute is not None: scals = utils.vtk2numpy(vtkscals) kcols = k3d.helpers.map_colors(scals, kcmap, [scals_min,scals_max]).astype(numpy.uint32) # sqsize = numpy.sqrt(numpy.dot(sizes, sizes)) kobj = k3d.points(ia.points().astype(numpy.float32), color=_rgb2int(iap.GetColor()), colors=kcols, opacity=iap.GetOpacity(), shader="dot", point_size=3, # point_size=iap.GetPointSize()*sqsize/800, name=name, ) settings.notebook_plotter += kobj #####################################################################Line elif ia.polydata(False).GetNumberOfLines(): # print('Line', ia.name, ia.N(), len(ia.faces()), # ia.polydata(False).GetNumberOfLines(), len(ia.lines()), # color_attribute, [vtkscals]) # kcols=[] # if color_attribute is not None: # scals = utils.vtk2numpy(vtkscals) # kcols = k3d.helpers.map_colors(scals, kcmap, # [scals_min,scals_max]).astype(numpy.uint32) # sqsize = numpy.sqrt(numpy.dot(sizes, sizes)) for i, ln_idx in enumerate(ia.lines()): if i>200: print('WARNING: K3D nr of line segments is limited to 200.') break pts = ia.points()[ln_idx] kobj = k3d.line(pts.astype(numpy.float32), color=_rgb2int(iap.GetColor()), # colors=kcols, opacity=iap.GetOpacity(), shader="thick", # width=iap.GetLineWidth()*sqsize/1000, name=name, ) settings.notebook_plotter += kobj #################################################################################### elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window: import panel # https://panel.pyviz.org/reference/panes/VTK.html vp.renderer.ResetCamera() settings.notebook_plotter = panel.pane.VTK(vp.window, width=int(vp.size[0]/1.5), height=int(vp.size[1]/2)) #################################################################################### elif 'ipyvtk' in settings.notebookBackend and hasattr(vp, 'window') and vp.window: from ipyvtklink.viewer import ViewInteractiveWidget vp.renderer.ResetCamera() settings.notebook_plotter = ViewInteractiveWidget(vp.window) #################################################################################### elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window: import PIL.Image try: import IPython except ImportError: raise Exception('IPython not available.') from vedo.io import screenshot settings.screeshotLargeImage = True nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2) pil_img = PIL.Image.fromarray(nn) settings.notebook_plotter = IPython.display.display(pil_img) return settings.notebook_plotter
def getNotebookBackend(actors2show, zoom, viewup): vp = settings.plotter_instance #################################################################################### # https://github.com/InsightSoftwareConsortium/itkwidgets # /blob/master/itkwidgets/widget_viewer.py if 'itk' in settings.notebookBackend: from itkwidgets import view if sum(vp.shape) != 2: colors.printc("Warning: multirendering is not supported in jupyter.", c=1) settings.notebook_plotter = view(actors=actors2show, cmap='jet', ui_collapsed=True, gradient_opacity=False) #################################################################################### elif settings.notebookBackend == 'k3d': import k3d # https://github.com/K3D-tools/K3D-jupyter if vp.shape[0] != 1 or vp.shape[1] != 1: colors.printc("Warning: multirendering is not supported in jupyter.", c=1) actors2show2 = [] for ia in actors2show: if isinstance(ia, vtk.vtkAssembly): #unpack assemblies acass = ia.unpack() #for a in acass: # a.SetScale(ia.GetScale()) actors2show2 += acass else: actors2show2.append(ia) vbb, sizes, min_bns, max_bns = addons.computeVisibleBounds() kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5] settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle], menu_visibility=True, height=int(vp.size[1]/2) ) settings.notebook_plotter.grid = kgrid settings.notebook_plotter.lighting = 1.2 # set k3d camera settings.notebook_plotter.camera_auto_fit = False eps = 1 + numpy.random.random()*1.0e-04 # workaround to bug in k3d # https://github.com/K3D-tools/K3D-jupyter/issues/180 if settings.plotter_instance and settings.plotter_instance.camera: k3dc = utils.vtkCameraToK3D(settings.plotter_instance.camera) k3dc[2] = k3dc[2]*eps settings.notebook_plotter.camera = k3dc else: vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5] vss = numpy.linalg.norm([vsx, vsy, vsz]) if zoom: vss /= zoom vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target if viewup == 'z': vup = (0,0,1) # camera up vector vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01 # camera position elif viewup == 'x': vup = (1,0,0) vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2] # camera position else: vup = (0,1,0) vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5 # camera position settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2]*eps, vfp[0], vfp[1], vfp[2], vup[0], vup[1], vup[2] ] if not vp.axes: settings.notebook_plotter.grid_visible = False for ia in actors2show2: kobj = None kcmap= None if isinstance(ia, Mesh) and ia.N(): iap = ia.GetProperty() #ia.clean().triangulate().computeNormals() #ia.triangulate()) iapoly = ia.clone().clean().triangulate().computeNormals().polydata() vtkscals = None color_attribute = None if ia.mapper().GetScalarVisibility(): vtkdata = iapoly.GetPointData() vtkscals = vtkdata.GetScalars() if vtkscals is None: vtkdata = iapoly.GetCellData() vtkscals = vtkdata.GetScalars() if vtkscals is not None: c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(iapoly) c2p.Update() iapoly = c2p.GetOutput() vtkdata = iapoly.GetPointData() vtkscals = vtkdata.GetScalars() if vtkscals is not None: if not vtkscals.GetName(): vtkscals.SetName('scalars') scals_min, scals_max = ia.mapper().GetScalarRange() color_attribute = (vtkscals.GetName(), scals_min, scals_max) lut = ia.mapper().GetLookupTable() lut.Build() kcmap=[] nlut = lut.GetNumberOfTableValues() for i in range(nlut): r,g,b,a = lut.GetTableValue(i) kcmap += [i/(nlut-1), r,g,b] if iapoly.GetNumberOfPolys() > 0: name = None if ia.filename: name = os.path.basename(ia.filename) kobj = k3d.vtk_poly_data(iapoly, name=name, color=colors.rgb2int(iap.GetColor()), color_attribute=color_attribute, color_map=kcmap, opacity=iap.GetOpacity(), wireframe=(iap.GetRepresentation()==1)) if iap.GetInterpolation() == 0: kobj.flat_shading = True else: kcols=[] if color_attribute is not None: scals = vtk_to_numpy(vtkscals) kcols = k3d.helpers.map_colors(scals, kcmap, [scals_min,scals_max]).astype(numpy.uint32) sqsize = numpy.sqrt(numpy.dot(sizes, sizes)) if ia.NPoints() == ia.NCells(): kobj = k3d.points(ia.points().astype(numpy.float32), color=colors.rgb2int(iap.GetColor()), colors=kcols, opacity=iap.GetOpacity(), shader="3d", point_size=iap.GetPointSize()*sqsize/400, #compression_level=9, ) else: kobj = k3d.line(ia.points().astype(numpy.float32), color=colors.rgb2int(iap.GetColor()), colors=kcols, opacity=iap.GetOpacity(), shader="thick", width=iap.GetLineWidth()*sqsize/1000, ) settings.notebook_plotter += kobj elif isinstance(ia, Volume): kx, ky, kz = ia.dimensions() arr = ia.getPointArray() kimage = arr.reshape(-1, ky, kx) colorTransferFunction = ia.GetProperty().GetRGBTransferFunction() kcmap=[] for i in range(128): r,g,b = colorTransferFunction.GetColor(i/127) kcmap += [i/127, r,g,b] #print('vol scal range', ia.imagedata().GetScalarRange()) #print(numpy.min(kimage), numpy.max(kimage)) kbounds = numpy.array(ia.imagedata().GetBounds()) \ + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\ * numpy.array([-1,1] * 3) kobj = k3d.volume(kimage.astype(numpy.float32), color_map=kcmap, #color_range=ia.imagedata().GetScalarRange(), alpha_coef=10, bounds=kbounds, ) settings.notebook_plotter += kobj elif hasattr(ia, 'info') and 'formula' in ia.info.keys(): pos = (ia.GetPosition()[0],ia.GetPosition()[1]) kobj = k3d.text2d(ia.info['formula'], position=pos) settings.notebook_plotter += kobj #################################################################################### elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window: import panel # https://panel.pyviz.org/reference/panes/VTK.html vp.renderer.ResetCamera() settings.notebook_plotter = panel.pane.VTK(vp.window, width=int(vp.size[0]/1.5), height=int(vp.size[1]/2)) #################################################################################### elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window: import PIL.Image try: import IPython except ImportError: raise Exception('IPython not available.') return from vtkplotter.vtkio import screenshot settings.screeshotLargeImage = True nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2) pil_img = PIL.Image.fromarray(nn) settings.notebook_plotter = IPython.display.display(pil_img) return settings.notebook_plotter
def plot_regions_3d( atlas, regions_to_plot=[["HVC", "Nuclei"]], downsample_pct=1, polygon_simplification=0, additional_volumes=[], verbose=False, height=1024, ): """ plots brain regions on top of brain """ # collect data brain_data = np.swapaxes(atlas.voxel_data.loc["Brain", "voxels"], 0, 2) # get axis boundaries bounds = np.array([ atlas.xmin, atlas.xmax, atlas.ymin, atlas.ymax, atlas.zmin, atlas.zmax ]).astype("int") # the zero point in voxels, relative to y sinus zero_point = utils.um_to_vox( [0, 0, 0], atlas.voxel_data.loc["Brain", "affine"], atlas.um_mult, atlas.y_sinus_um_transform, ) # downsample if downsample_pct < 1: brain_data = scipy.ndimage.zoom(brain_data, downsample_pct) # make a volume plot of the brain brain_volume = k3d.volume( brain_data, color_range=[0, 1], color_map=k3d.basic_color_maps.Binary, samples=128, alpha_coef=0.25, bounds=bounds, compression_level=9, ) addl_vols = [] for vol in additional_volumes: bg_image_data = atlas.voxel_data.loc[vol, "voxels"] affine = atlas.voxel_data.loc[vol, "affine"] xm, ym, zm = utils.vox_to_um([0, 0, 0], affine, atlas.um_mult, atlas.y_sinus_um_transform) xma, yma, zma = utils.vox_to_um( list(np.shape(bg_image_data)), affine, atlas.um_mult, atlas.y_sinus_um_transform, ) img_bg_extent = np.concatenate( np.array([[xm, xma], [ym, yma], [zm, zma]])) bg_image_data = np.uint8( utils.norm01(np.swapaxes(bg_image_data, 0, 2)) * 256) addl_vol = k3d.volume( bg_image_data, color_range=[70, 100], color_map=k3d.matplotlib_color_maps.Greys, samples=128, alpha_coef=10.0, bounds=img_bg_extent, compression_level=9, ) addl_vols.append(addl_vol) # set atlas a region for y sinus atlas.region_vox.loc["y_sinus"] = [ "y_sinus", "y_sinus", np.nan, np.nan, np.nan ] atlas.region_vox.loc["y_sinus", "coords_vox"] = zero_point color_pal = atlas.label_cmap.colors # loop through regions regs = [] for ri, (reg, type_) in enumerate(tqdm(regions_to_plot, leave=False)): color = (np.array(color_pal[ri % len(color_pal)]) * 255).astype("int") # get voxel_data lab = atlas.brain_labels[atlas.brain_labels.type_ == type_].loc[ reg, "label"] vox_data = np.swapaxes( np.array(atlas.voxel_data.loc[type_, "voxels"] == lab), 0, 2) """addl_vol = k3d.volume( vox_data, color_range=[0, 1], color_map=k3d.matplotlib_color_maps.Greys, samples=128, alpha_coef=10.0, bounds=bounds, compression_level=9, ) addl_vols.append(addl_vol)""" # convert to vtk format vtk_dat = vox2vtk(vox_data, zero_point=zero_point) # simplify polygon if polygon_simplification > 0: vtk_dat = vtk_reduce(vtk_dat, polygon_simplification=polygon_simplification, verbose=verbose) # shape of voxel data xs, ys, zs = vox_data.shape region_bounds = [ 0, (bounds[1] - bounds[0]) / zs, 0, (bounds[3] - bounds[2]) / ys, 0, (bounds[5] - bounds[4]) / xs, ] # print(np.shape(vox_data), region_bounds, np.sum(vox_data)) # create mesh plot region = k3d.vtk_poly_data( vtk_dat.GetOutput(), color=utils.rgb2hex(color[0], color[1], color[2]), bounds=region_bounds, ) regs.append(region) origins = [-5000, 0, 0, 0, -5000, 0, 0, 0, -5000] vectors = [10000, 0, 0, 0, 10000, 0, 0, 0, 10000] colors = [0xFF0000, 0xFF0000, 0x00FF00, 0x00FF00, 0x0000FF, 0x0000FF] vec = k3d.vectors(origins, vectors, colors=colors, line_width=100, use_head=True, head_size=1000) plot = k3d.plot(height=height, background_color=0xFEFEFE) plot += brain_volume for vol in addl_vols: plot += vol # plot regions for region in regs: plot += region plot += vec plot.display() plot.camera_auto_fit = False # plot.grid_visible = False # camera loc, center or rocation, angle (?) plot.camera = [-22977, 18052, 8696, 0, 0, 0, 0.14, -0.16, 0.997] widget_controllers(atlas, vec, plot, bounds, regions_to_plot) return plot, vec
def getNotebookBackend(actors2show, zoom, viewup): vp = settings.plotter_instance if zoom == 'tight': zoom=1 # disable it if isinstance(vp.shape, str) or sum(vp.shape) > 2: colors.printc("Multirendering is not supported in jupyter.", c=1) return #################################################################################### # https://github.com/InsightSoftwareConsortium/itkwidgets # /blob/master/itkwidgets/widget_viewer.py if 'itk' in settings.notebookBackend: from itkwidgets import view settings.notebook_plotter = view(actors=actors2show, cmap='jet', ui_collapsed=True, gradient_opacity=False) #################################################################################### elif settings.notebookBackend == 'k3d': try: import k3d # https://github.com/K3D-tools/K3D-jupyter except: print("Cannot find k3d, install with: pip install k3d") return actors2show2 = [] for ia in actors2show: if not ia: continue if isinstance(ia, vtk.vtkAssembly): #unpack assemblies acass = ia.unpack() actors2show2 += acass else: actors2show2.append(ia) # vbb, sizes, _, _ = addons.computeVisibleBounds() # kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5] settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle], menu_visibility=settings.k3dMenuVisibility, height=settings.k3dPlotHeight, antialias=settings.k3dAntialias, ) # settings.notebook_plotter.grid = kgrid settings.notebook_plotter.lighting = settings.k3dLighting # set k3d camera settings.notebook_plotter.camera_auto_fit = settings.k3dCameraAutoFit settings.notebook_plotter.grid_auto_fit = settings.k3dGridAutoFit settings.notebook_plotter.axes_helper = settings.k3dAxesHelper if settings.plotter_instance and settings.plotter_instance.camera: k3dc = utils.vtkCameraToK3D(settings.plotter_instance.camera) if zoom: k3dc[0] /= zoom k3dc[1] /= zoom k3dc[2] /= zoom settings.notebook_plotter.camera = k3dc # else: # vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5] # vss = numpy.linalg.norm([vsx, vsy, vsz]) # if zoom: # vss /= zoom # vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target # if viewup == 'z': # vup = (0,0,1) # camera up vector # vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01 # camera position # elif viewup == 'x': # vup = (1,0,0) # vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2] # camera position # else: # vup = (0,1,0) # vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5 # camera position # settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2], # vfp[0], vfp[1], vfp[2], # vup[0], vup[1], vup[2] ] if not vp.axes: settings.notebook_plotter.grid_visible = False for ia in actors2show2: if isinstance(ia, (vtk.vtkCornerAnnotation, vtk.vtkAssembly)): continue kobj = None kcmap= None name = None if hasattr(ia, 'filename'): if ia.filename: name = os.path.basename(ia.filename) if ia.name: name = os.path.basename(ia.name) #####################################################################scalars # work out scalars first, Points Lines are also Mesh objs if isinstance(ia, (Mesh, shapes.Line, Points)): # print('scalars', ia.name, ia.N()) iap = ia.GetProperty() if isinstance(ia, (shapes.Line, Points)): iapoly = ia.polydata() else: iapoly = ia.clone().clean().triangulate().computeNormals().polydata() vtkscals = None color_attribute = None if ia.mapper().GetScalarVisibility(): vtkdata = iapoly.GetPointData() vtkscals = vtkdata.GetScalars() if vtkscals is None: vtkdata = iapoly.GetCellData() vtkscals = vtkdata.GetScalars() if vtkscals is not None: c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(iapoly) c2p.Update() iapoly = c2p.GetOutput() vtkdata = iapoly.GetPointData() vtkscals = vtkdata.GetScalars() if vtkscals is not None: if not vtkscals.GetName(): vtkscals.SetName('scalars') scals_min, scals_max = ia.mapper().GetScalarRange() color_attribute = (vtkscals.GetName(), scals_min, scals_max) lut = ia.mapper().GetLookupTable() lut.Build() kcmap=[] nlut = lut.GetNumberOfTableValues() for i in range(nlut): r,g,b,a = lut.GetTableValue(i) kcmap += [i/(nlut-1), r,g,b] #####################################################################Volume if isinstance(ia, Volume): # print('Volume', ia.name, ia.dimensions()) kx, ky, kz = ia.dimensions() arr = ia.pointdata[0] kimage = arr.reshape(-1, ky, kx) colorTransferFunction = ia.GetProperty().GetRGBTransferFunction() kcmap=[] for i in range(128): r,g,b = colorTransferFunction.GetColor(i/127) kcmap += [i/127, r,g,b] kbounds = numpy.array(ia.imagedata().GetBounds()) \ + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\ * numpy.array([-1,1] * 3) kobj = k3d.volume(kimage.astype(numpy.float32), color_map=kcmap, #color_range=ia.imagedata().GetScalarRange(), alpha_coef=10, bounds=kbounds, name=name, ) settings.notebook_plotter += kobj #####################################################################text elif hasattr(ia, 'info') and 'formula' in ia.info.keys(): pos = (ia.GetPosition()[0],ia.GetPosition()[1]) kobj = k3d.text2d(ia.info['formula'], position=pos) settings.notebook_plotter += kobj #####################################################################Mesh elif isinstance(ia, Mesh) and ia.N() and len(ia.faces()): # print('Mesh', ia.name, ia.N(), len(ia.faces())) kobj = k3d.vtk_poly_data(iapoly, name=name, # color=_rgb2int(iap.GetColor()), color_attribute=color_attribute, color_map=kcmap, opacity=iap.GetOpacity(), wireframe=(iap.GetRepresentation()==1)) if iap.GetInterpolation() == 0: kobj.flat_shading = True settings.notebook_plotter += kobj #####################################################################Points elif isinstance(ia, Points): # print('Points', ia.name, ia.N()) kcols=[] if color_attribute is not None: scals = utils.vtk2numpy(vtkscals) kcols = k3d.helpers.map_colors(scals, kcmap, [scals_min,scals_max]).astype(numpy.uint32) # sqsize = numpy.sqrt(numpy.dot(sizes, sizes)) kobj = k3d.points(ia.points().astype(numpy.float32), color=_rgb2int(iap.GetColor()), colors=kcols, opacity=iap.GetOpacity(), shader=settings.k3dPointShader, point_size=iap.GetPointSize(), name=name, ) settings.notebook_plotter += kobj #####################################################################Lines elif ia.polydata(False).GetNumberOfLines(): # print('Line', ia.name, ia.N(), len(ia.faces()), # ia.polydata(False).GetNumberOfLines(), len(ia.lines()), # color_attribute, [vtkscals]) # kcols=[] # if color_attribute is not None: # scals = utils.vtk2numpy(vtkscals) # kcols = k3d.helpers.map_colors(scals, kcmap, # [scals_min,scals_max]).astype(numpy.uint32) # sqsize = numpy.sqrt(numpy.dot(sizes, sizes)) for i, ln_idx in enumerate(ia.lines()): if i>200: print('WARNING: K3D nr of line segments is limited to 200.') break pts = ia.points()[ln_idx] kobj = k3d.line(pts.astype(numpy.float32), color=_rgb2int(iap.GetColor()), opacity=iap.GetOpacity(), shader=settings.k3dLineShader, # width=iap.GetLineWidth()*sqsize/1000, name=name, ) settings.notebook_plotter += kobj #################################################################################### elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window: import panel # https://panel.pyviz.org/reference/panes/VTK.html vp.renderer.ResetCamera() settings.notebook_plotter = panel.pane.VTK(vp.window, width=int(vp.size[0]/1.5), height=int(vp.size[1]/2)) #################################################################################### elif 'ipyvtk' in settings.notebookBackend and hasattr(vp, 'window') and vp.window: from ipyvtklink.viewer import ViewInteractiveWidget vp.renderer.ResetCamera() settings.notebook_plotter = ViewInteractiveWidget(vp.window) #################################################################################### elif 'ipygany' in settings.notebookBackend: from ipygany import PolyMesh, Scene, IsoColor, RGB, Component from ipygany import Alpha, ColorBar, colormaps, PointCloud from ipywidgets import FloatRangeSlider, Dropdown, VBox, AppLayout, jslink bgcol = colors.rgb2hex(colors.getColor(vp.backgrcol)) actors2show2 = [] for ia in actors2show: if not ia: continue if isinstance(ia, vedo.Assembly): #unpack assemblies assacts = ia.unpack() for ja in assacts: if isinstance(ja, vedo.Assembly): actors2show2 += ja.unpack() else: actors2show2.append(ja) else: actors2show2.append(ia) pmeshes = [] colorbar = None for obj in actors2show2: # print("ipygany processing:", [obj], obj.name) if isinstance(obj, vedo.shapes.Line): lg = obj.diagonalSize()/1000 * obj.GetProperty().GetLineWidth() vmesh = vedo.shapes.Tube(obj.points(), r=lg, res=4).triangulate() vmesh.c(obj.c()) faces = vmesh.faces() # todo: Lines elif isinstance(obj, Mesh): vmesh = obj.triangulate() faces = vmesh.faces() elif isinstance(obj, Points): vmesh = obj faces = [] elif isinstance(obj, Volume): vmesh = obj.isosurface() faces = vmesh.faces() elif isinstance(obj, vedo.TetMesh): vmesh = obj.tomesh(fill=False) faces = vmesh.faces() else: print("ipygany backend: cannot process object type", [obj]) continue vertices = vmesh.points() scals = vmesh.inputdata().GetPointData().GetScalars() if scals and not colorbar: # there is an active array, only pick the first aname = scals.GetName() arr = vmesh.pointdata[aname] parr = Component(name=aname, array=arr) if len(faces): pmesh = PolyMesh(vertices=vertices, triangle_indices=faces, data={aname: [parr]}) else: pmesh = PointCloud(vertices=vertices, data={aname: [parr]}) rng = scals.GetRange() colored_pmesh = IsoColor(pmesh, input=aname, min=rng[0], max=rng[1]) if obj.scalarbar: colorbar = ColorBar(colored_pmesh) colormap_slider_range = FloatRangeSlider(value=rng, min=rng[0], max=rng[1], step=(rng[1] - rng[0]) / 100.) jslink((colored_pmesh, 'range'), (colormap_slider_range, 'value')) colormap = Dropdown( options=colormaps, description='Colormap:' ) jslink((colored_pmesh, 'colormap'), (colormap, 'index')) else: if len(faces): pmesh = PolyMesh(vertices=vertices, triangle_indices=faces) else: pmesh = PointCloud(vertices=vertices) if vmesh.alpha() < 1: colored_pmesh = Alpha(RGB(pmesh, input=tuple(vmesh.color())), input=vmesh.alpha()) else: colored_pmesh = RGB(pmesh, input=tuple(vmesh.color())) pmeshes.append(colored_pmesh) if colorbar: scene = AppLayout( left_sidebar=Scene(pmeshes, background_color=bgcol), right_sidebar=VBox((colormap_slider_range, #not working colorbar, colormap)), pane_widths=[2, 0, 1], ) else: scene = Scene(pmeshes, background_color=bgcol) settings.notebook_plotter = scene #################################################################################### elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window: import PIL.Image try: import IPython except ImportError: raise Exception('IPython not available.') from vedo.io import screenshot settings.screeshotLargeImage = True nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2) pil_img = PIL.Image.fromarray(nn) settings.notebook_plotter = IPython.display.display(pil_img) return settings.notebook_plotter
def density_field(res,box,box_kw={},plot=None): bounds=[ box[0],box[0]+2*box[3], box[1],box[1]+2*box[4], box[2],box[2]+2*box[5] ] print(bounds) if plot is None: plot = k3d.plot() objs=[] if len(res.shape) >3: for i in range(res.shape[0]): objs.append(k3d.volume(np.array(res[i],dtype='float16'),bounds=bounds)) plot+=objs[-1] else: objs.append(k3d.volume(np.array(res,dtype='float16'),bounds=bounds)) plot+=objs[-1] #points = k3d.points(g0_sites,point_size=0.02) #points1 = k3d.points(g1_sites,point_size=0.005) #plot += points #plot += points1 plot += plot_simulation_box(box,**box_kw) plot.display() global _w_x global _x global _w_y global _y global _w_z global _z global _sphere _w_x=0.05 _x =0.14 _w_y=0.05 _y =0.14 _w_z=0.05 _z =0.14 _sphere=False global _rot_a global _rot_b global _rot_c global _rot_Q _rot_a = 0.0 _rot_b = 0.0 _rot_c = 0.0 _rot_Q = np.eye(4) def rotate_plane(Q,ps): prs=[] for p in ps: p=np.array(p) prs.append(Q.dot(p).tolist()) return prs def global_clipping_planes(): if _sphere: return sph_tangents_cover(_w_x,7,_x,_y,_z) else: return rotate_plane(_rot_Q,[[1,0,0,_w_x-_x],[-1,0,0,_w_x+_x], [0,1,0,_w_y-_y],[0,-1,0,_w_y+_y], [0,0,1,_w_z-_z],[0,0,-1,_w_z+_z] ]) button=widgets.Button(description='Center on 1') @button.on_click def button1_on_click(b): global _x global _y global _z print('finding maximum in spherical domain with r={}, center=({},{},{})'.format(_w_x,_x,_y,_z)) idx, (_z,_y,_x)=get_max_in_spherical_domain(ress[0],_w_x,_z,_y,_x) #_x,_y,_z=-_x,-_y,-_z print('center=({},{},{}), idx={} shape={}'.format(_x,_y,_z,idx,ress[0].shape)) print('value={}'.format(ress[0][idx])) plot.clipping_planes=global_clipping_planes() display(button)#,button2,button3) @interact(spherical=widgets.Checkbox(value=False)) def g(spherical): global _sphere _sphere=spherical plot.clipping_planes=global_clipping_planes() @interact(a=widgets.FloatSlider(value=0,min=0,max=2*np.pi,step=0.01)) def g(a): global _rot_a global _rot_Q _rot_a=a _rot_Q=rotation(_rot_a,_rot_b,_rot_c) plot.clipping_planes=global_clipping_planes() @interact(b=widgets.FloatSlider(value=0,min=0,max=2*np.pi,step=0.01)) def g(b): global _rot_b global _rot_Q _rot_b=b _rot_Q=rotation(_rot_a,_rot_b,_rot_c) plot.clipping_planes=global_clipping_planes() @interact(c=widgets.FloatSlider(value=0,min=0,max=2*np.pi,step=0.01)) def g(c): global _rot_c global _rot_Q _rot_c=c _rot_Q=rotation(_rot_a,_rot_b,_rot_c) plot.clipping_planes=global_clipping_planes() @interact(x=widgets.FloatSlider(value=box[0]+box[3],min=box[0],max=box[0]+2*box[3],step=box[3]/100)) def g(x): global _x _x=x plot.clipping_planes=global_clipping_planes() @interact(w_x=widgets.FloatSlider(value=box[3]/5,min=0.0,max=2*box[3],step=box[3]/100)) def g(w_x): global _w_x _w_x=w_x plot.clipping_planes=global_clipping_planes() @interact(y=widgets.FloatSlider(value=box[1]+box[4],min=box[1],max=box[1]+2*box[4],step=box[4]/100)) def g(y): global _y _y=y plot.clipping_planes=global_clipping_planes() @interact(w_y=widgets.FloatSlider(value=2*box[4],min=0,max=2*box[4],step=box[4]/100)) def g(w_y): global _w_y _w_y=w_y plot.clipping_planes=global_clipping_planes() @interact(z=widgets.FloatSlider(value=box[2]+box[5],min=box[2],max=box[2]+2*box[5],step=box[5]/100)) def g(z): global _z _z=z plot.clipping_planes=global_clipping_planes() @interact(w_z=widgets.FloatSlider(value=2*box[5],min=0.0,max=2*box[5],step=box[5]/100)) def g(w_z): global _w_z _w_z=w_z plot.clipping_planes=global_clipping_planes() return plot