def show_grayscale_volume(vol: GrayscaleVolume, neurodata_vis_spec: dict): import ipyvolume.pylab as p3 fig = p3.figure() p3.volshow(vol.data, tf=linear_transfer_function([0, 0, 0], max_opacity=0.1)) return fig
def update_image(self, intensity_image): with self.output: p3.volshow(intensity_image.T, controls=self._first_time) self._first_time = False p3.xlim(*self.limits[0]) p3.ylim(*self.limits[1]) p3.zlim(*self.limits[2])
def show_image(index=0): p3.figure() p3.volshow(indexed_timeseries.data[index], tf=linear_transfer_function([0, 0, 0], max_opacity=.3)) output.clear_output(wait=True) with output: p3.show()
def _update_image(self): with self.output: grid = self.get_grid() if self.smooth_pre: for i in range(grid.shape[0]): grid[i] = vaex.grids.gf(grid[i], self.smooth_pre) f = vaex.dataset._parse_f(self.f) fgrid = f(grid) if self.smooth_post: for i in range(grid.shape[0]): fgrid[i] = vaex.grids.gf(fgrid[i], self.smooth_post) ngrid, fmin, fmax = self.normalise(fgrid) print(ngrid.shape) if len(ngrid.shape) == 4: #if ngrid.shape[0] == 1: ngrid = ngrid[-1] p3.volshow(ngrid.T, controls=self._first_time) vx, vy, vz = self.vgrids[:3] vcount = self.vcount if vx is not None and vy is not None and vz is not None and vcount is not None: vcount = vcount[-1] # no multivolume render, just take the last selection vx = vx[-1] vy = vy[-1] vz = vz[-1] print(vx.shape) ok = np.isfinite(vx) & np.isfinite(vy) & np.isfinite(vz) vcount_min = None vcount_max = None if self.vcount_limits is not None: try: vcount_min, vcount_max = self.vcount_limits except: vcount_min = self.vcount_limits if vcount_min is not None: ok &= (vcount > vcount_min) if vcount_max is not None: ok &= (vcount < vcount_max) x, y, z = ipyvolume.examples.xyz(self.get_vshape()[0], limits=self.limits, sparse=False, centers=True) v1d = [k[ok] for k in [x, y, z, vx, vy, vz]] vsize = 5 vcolor = "grey" if self._first_time: self.quiver = p3.quiver(*v1d, size=vsize, color=vcolor) else: self.quiver.x = x[ok] self.quiver.y = y[ok] self.quiver.z = z[ok] self.quiver.vx = vx[ok] self.quiver.vy = vy[ok] self.quiver.vz = vz[ok] p3.xlim(*self.limits[0]) p3.ylim(*self.limits[1]) p3.zlim(*self.limits[2]) self._first_time = False
def test_quick(): x, y, z = ipyvolume.examples.xyz() p3.volshow(x*y*z) ipyvolume.quickvolshow(x*y*z, lighting=True) ipyvolume.quickvolshow(x*y*z, lighting=True, level=1, opacity=1, level_width=1) x, y, z, u, v, w = np.random.random((6, 100)) ipyvolume.quickscatter(x, y, z) ipyvolume.quickquiver(x, y, z, u, v, w)
def update_figure(index=0): p3.figure() p3.volshow( indexed_timeseries.data[index].transpose([1, 0, 2]), tf=linear_transfer_function([0, 0, 0], max_opacity=0.3), ) output.clear_output(wait=True) self.figure = output with output: p3.show()
def test_volshow(): x, y, z = ipyvolume.examples.xyz() p3.volshow(x * y * z) p3.volshow(x * y * z, level=1) p3.volshow(x * y * z, opacity=1) p3.volshow(x * y * z, level_width=1) p3.save("tmp/ipyolume_volume.html")
def show_plane_segmentation_3d_mask(plane_seg: PlaneSegmentation): import ipyvolume.pylab as p3 nrois = len(plane_seg) image_masks = plane_seg["image_mask"] fig = p3.figure() for icolor, color in enumerate(color_wheel): vol = np.zeros(image_masks.shape[1:]) sel = np.arange(icolor, nrois, len(color_wheel)) for isel in sel: vol += plane_seg["image_mask"][isel] p3.volshow(vol, tf=linear_transfer_function(color, max_opacity=0.3)) return fig
def test_volshow_max_shape(): x, y, z = ipyvolume.examples.xyz(shape=32) I = x * y * z v = p3.volshow(I, max_shape=16, extent=[[0, 32]] * 3) assert v.data.shape == (16, 16, 16) data = v.data p3.xlim(0, 16)
def ball(rmax=3, rmin=0, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs): """Show a ball.""" import ipyvolume.pylab as p3 __, __, __, r, _theta, _phi = xyz(shape=shape, limits=limits, spherical=True) data = r * 0 data[(r < rmax) & (r >= rmin)] = 0.5 if "data_min" not in kwargs: kwargs["data_min"] = 0 if "data_max" not in kwargs: kwargs["data_max"] = 1 data = data.T if draw: vol = p3.volshow(data=data, **kwargs) if show: p3.show() return vol else: return data
def show_plane_segmentation_3d(plane_seg: PlaneSegmentation): import ipyvolume.pylab as p3 nrois = len(plane_seg) dims = np.array([max(max(plane_seg['voxel_mask'][i][dim]) for i in range(nrois)) for dim in ['x', 'y', 'z']]).astype('int') + 1 fig = p3.figure() for icolor, color in enumerate(color_wheel): vol = np.zeros(dims) sel = np.arange(icolor, nrois, len(color_wheel)) for isel in sel: dat = plane_seg['voxel_mask'][isel] vol[tuple(dat['x'].astype('int')), tuple(dat['y'].astype('int')), tuple(dat['z'].astype('int'))] = 1 p3.volshow(vol, tf=linear_transfer_function(color, max_opacity=.3)) return fig
def example_ylm(m=0, n=2, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs): import ipyvolume.pylab as p3 __, __, __, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True) radial = np.exp(-(r - 2) ** 2) data = np.abs(scipy.special.sph_harm(m, n, theta, phi) ** 2) * radial if draw: vol = p3.volshow(data=data, **kwargs) if show: p3.show() return vol else: return data
def show_plane_segmentation_3d_voxel(plane_seg: PlaneSegmentation): import ipyvolume.pylab as p3 nrois = len(plane_seg) voxel_mask = plane_seg["voxel_mask"] mx, my, mz = 0, 0, 0 for voxel in voxel_mask: for x, y, z, _ in voxel: mx = max(mx, x) my = max(my, y) mz = max(mz, z) fig = p3.figure() for icolor, color in enumerate(color_wheel): vol = np.zeros((mx + 1, my + 1, mz + 1)) sel = np.arange(icolor, nrois, len(color_wheel)) for isel in sel: dat = voxel_mask[isel] for x, y, z, value in dat: vol[x, y, z] = value p3.volshow(vol, tf=linear_transfer_function(color, max_opacity=0.3)) return fig
def update_image(self, intensity_image): with self.output: with self.figure: limits = copy.deepcopy(self.limits) if self._first_time: self.volume = p3.volshow(intensity_image.T, controls=self._first_time, extent=limits) if 1: #hasattr(self.figure, 'extent_original'): # v0.5 check self.volume.data_original = None self.volume.data = intensity_image.T self.volume.extent = copy.deepcopy(self.limits) self.volume.data_min = np.nanmin(intensity_image) self.volume.data_max = np.nanmax(intensity_image) self.volume.show_min = self.volume.data_min self.volume.show_max = self.volume.data_max self._first_time = False self.figure.xlim = limits[0] self.figure.ylim = limits[1] self.figure.zlim = limits[2]
def update_image(self, intensity_image): with self.output: with self.figure: limits = copy.deepcopy(self.limits) if self._first_time: self.volume = p3.volshow(intensity_image.T, controls=self._first_time, extent=limits) if 1: #hasattr(self.figure, 'extent_original'): # v0.5 check self.volume.data_original = None self.volume.data = intensity_image.T self.volume.extent = copy.deepcopy(self.limits) self.volume.data_min = np.nanmin(intensity_image) self.volume.data_max = np.nanmax(intensity_image) self.volume.show_min = self.volume.data_min self.volume.show_max = self.volume.data_max self._first_time = False self.figure.xlim = limits[0] self.figure.ylim = limits[1] self.figure.zlim = limits[2]
def create_ivol(vstruct, width=500, height=400, ssize=5, min_voxels=None, max_voxels=None, **volargs): """ Parameters ---------- vstruct: dict width: int height: int ssize: int min_voxels : int minimum number of voxels in density cube max_voxels : int maximum number of voxels in density cube volargs: dict Returns ------- Examples -------- >>> from jsonextended import edict >>> dstruct = { ... 'type': 'repeat_density', ... 'dtype': 'charge', ... 'name': '', ... 'dcube':np.ones((3,3,3)), ... 'centre':[0,0,0], ... 'cell_vectors':{ ... 'a':[2.,0,0], ... 'b':[0,2.,0], ... 'c':[0,0,2.]}, ... 'color_bbox': 'black', ... 'transforms': [] ... } >>> cstruct = { ... 'type': 'repeat_cell', ... 'name': '', ... 'centre':[0,0,0], ... 'cell_vectors':{ ... 'a':[2.,0,0], ... 'b':[0,2.,0], ... 'c':[0,0,2.]}, ... 'color_bbox': 'black', ... 'sites': [{ ... 'label': "Fe", ... 'ccoord': [1,1,1], ... 'color_fill': "red", ... 'color_outline': None, ... 'transparency': 1, ... 'radius': 1, ... }], ... 'bonds': [], ... 'transforms': [] ... } >>> vstruct = {"elements": [dstruct, cstruct], "transforms": []} >>> new_struct, fig, controls = create_ivol(vstruct) >>> print(edict.apply(edict.filter_keys(new_struct, ["ivol"], list_of_dicts=True), ... "ivol", lambda x: [v.__class__.__name__ for v in x], list_of_dicts=True)) {'elements': [{'ivol': ['Figure', 'Mesh']}, {'ivol': ['Mesh', 'Scatter']}]} """ new_struct = apply_transforms(vstruct) bonds = compute_bonds( new_struct ) #edict.filter_keyvals(vstruct, {"type": "repeat_cell"}, keep_siblings=True)) # ivolume currently only allows one volume rendering per plot # voltypes = edict.filter_keyvals(vstructs,[('type','repeat_density')]) vol_index = [ i for i, el in enumerate(vstruct['elements']) if el['type'] == 'repeat_density' ] assert len( vol_index) <= 1, "ipyvolume only allows one volume rendering per scene" p3.clear() fig = p3.figure(width=width, height=height, controls=True) fig.screen_capture_enabled = True # the volume rendering must be created first, # for appropriately scaled axis if vol_index: volstruct = new_struct['elements'][vol_index[0]] a = volstruct['cell_vectors']['a'] b = volstruct['cell_vectors']['b'] c = volstruct['cell_vectors']['c'] centre = volstruct['centre'] #print(centre) # convert dcube to cartesian out = cube_frac2cart(volstruct['dcube'], a, b, c, centre, max_voxels=max_voxels, min_voxels=min_voxels, make_cubic=True) new_density, (xmin, ymin, zmin), (xmax, ymax, zmax) = out vol = p3.volshow(new_density, **volargs) if volstruct["color_bbox"] is not None: a = np.asarray(a) b = np.asarray(b) c = np.asarray(c) o = np.asarray(centre) - 0.5 * (a + b + c) mesh = _create_mesh([ o, o + a, o + b, o + c, o + a + b, o + a + c, o + c + b, o + a + b + c ], color=volstruct["color_bbox"], line_indices=[[0, 1], [0, 2], [0, 3], [2, 4], [2, 6], [1, 4], [1, 5], [3, 5], [3, 6], [7, 6], [7, 4], [7, 5]]) vol = [vol, mesh] # todo better way of storing ivol components? volstruct['ivol'] = vol # appropriately scale axis p3.xlim(xmin, xmax) p3.ylim(ymin, ymax) p3.zlim(zmin, zmax) for element in new_struct['elements']: if element['type'] == 'repeat_density': continue elif element['type'] == 'repeat_cell': scatters = [] if element["color_bbox"] is not None: a = np.asarray(element['cell_vectors']['a']) b = np.asarray(element['cell_vectors']['b']) c = np.asarray(element['cell_vectors']['c']) centre = element['centre'] o = np.asarray(centre) - 0.5 * (a + b + c) mesh = _create_mesh([ o, o + a, o + b, o + c, o + a + b, o + a + c, o + c + b, o + a + b + c ], color=element["color_bbox"], line_indices=[[0, 1], [0, 2], [0, 3], [2, 4], [2, 6], [1, 4], [1, 5], [3, 5], [3, 6], [7, 6], [7, 4], [7, 5]]) scatters.append(mesh) for color, radius in set([(s['color_fill'], s['radius']) for s in element["sites"]]): scatter = edict.filter_keyvals(element, { "color_fill": color, "radius": radius }, "AND", keep_siblings=True, list_of_dicts=True) scatter = edict.combine_lists(scatter, ["sites"], deepcopy=False) scatter = edict.remove_keys(scatter, ["sites"], deepcopy=False) x, y, z = np.array(scatter['ccoord']).T s = p3.scatter(x, y, z, marker='sphere', size=ssize * radius, color=color) scatters.append(s) element['ivol'] = scatters elif element['type'] == 'repeat_poly': polys = [] for poly in element['polys']: mesh = _create_mesh(poly, element['color'], element['solid']) polys.append(mesh) element['ivol'] = polys else: raise ValueError("unknown element type: {}".format( element['type'])) for bond in bonds: p1, p2, c1, c2, radius = bond meshes = _create_bond(p1, p2, c1, c2, radius) # split up controls if vol_index: (level_ctrls, figbox, extractrl1, extractrl2) = p3.gcc().children controls = OrderedDict([('transfer function', [level_ctrls]), ('lighting', [extractrl1, extractrl2])]) else: # figbox = p3.gcc().children controls = {} return new_struct, fig, controls