def test_colormap(): """Test named colormaps.""" autumn = get_colormap('autumn') assert autumn.glsl_map is not "" assert len(autumn[0.]) == 1 assert len(autumn[0.5]) == 1 assert len(autumn[1.]) == 1 assert len(autumn[[0., 0.5, 1.]]) == 3 assert len(autumn[np.array([0., 0.5, 1.])]) == 3 fire = get_colormap('fire') assert_array_equal(fire[0].rgba, np.ones((1, 4))) assert_array_equal(fire[1].rgba, np.array([[1, 0, 0, 1]])) grays = get_colormap('grays') assert_array_equal(grays[.5].rgb, np.ones((1, 3)) * .5) hot = get_colormap('hot') assert_allclose(hot[0].rgba, [[0, 0, 0, 1]], 1e-6, 1e-6) assert_allclose(hot[0.5].rgba, [[1, .52272022, 0, 1]], 1e-6, 1e-6) assert_allclose(hot[1.].rgba, [[1, 1, 1, 1]], 1e-6, 1e-6) # Test the GLSL and Python mapping. for name in get_colormaps(): colormap = get_colormap(name) Function(colormap.glsl_map) colors = colormap[np.linspace(-2., 2., 50)] assert colors.rgba.min() >= 0 assert colors.rgba.max() <= 1
def __init__(self, volumes, clim=None, threshold=None, relative_step_size=0.8, cmap1='grays', cmap2='grays', emulate_texture=False, n_volume_max=10): # Choose texture class tex_cls = TextureEmulated3D if emulate_texture else Texture3D # We store the data and colormaps in a CallbackList which can warn us # when it is modified. self.volumes = CallbackList() self.volumes.on_size_change = self._update_all_volumes self.volumes.on_item_change = self._update_volume self._vol_shape = None self._need_vertex_update = True # Create OpenGL program vert_shader, frag_shader = get_shaders(n_volume_max) super(MultiVolumeVisual, self).__init__(vcode=vert_shader, fcode=frag_shader) # Create gloo objects self._vertices = VertexBuffer() self._texcoord = VertexBuffer( np.array([ [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1], ], dtype=np.float32)) # Set up textures self.textures = [] for i in range(n_volume_max): self.textures.append(tex_cls((10, 10, 10), interpolation='linear', wrapping='clamp_to_edge')) self.shared_program['u_volumetex{0}'.format(i)] = self.textures[i] self.shared_program.frag['cmap{0:d}'.format(i)] = Function(get_colormap('grays').glsl_map) self.shared_program['a_position'] = self._vertices self.shared_program['a_texcoord'] = self._texcoord self._draw_mode = 'triangle_strip' self._index_buffer = IndexBuffer() self.shared_program.frag['sampler_type'] = self.textures[0].glsl_sampler_type self.shared_program.frag['sample'] = self.textures[0].glsl_sample # Only show back faces of cuboid. This is required because if we are # inside the volume, then the front faces are outside of the clipping # box and will not be drawn. self.set_gl_state('translucent', cull_face=False) self.relative_step_size = relative_step_size self.freeze() # Add supplied volumes self.volumes.extend(volumes)
def __init__(self, **kwargs): app.Canvas.__init__(self, **kwargs) self.geometry = 0, 0, 400, 400 mesh = create_sphere(10, 10, radius=2.) vertices = mesh.get_vertices() tris = mesh.get_faces() data=vertices[:, 2] self.filled_buf = gloo.IndexBuffer(tris) self.program = ModularProgram(VERT_CODE, FRAG_CODE) colormap = get_colormap('autumn') self.color = Function(colormap.glsl_map) self.program.frag['color'] = self.color('floor(v_value*10.+0.5)/10.') # Set attributes self.program['a_position'] = gloo.VertexBuffer(vertices) self.program['a_value'] = gloo.VertexBuffer(normalize(data, data.min(), data.max())) # Handle transformations self.init_transforms() gloo.set_clear_color((1, 1, 1, 1)) gloo.set_state(depth_test=True) self._timer = app.Timer('auto', connect=self.update_transforms) self._timer.start()
def _update_volume(self, volumes, index): data, clim, cmap = volumes[index] cmap = get_colormap(cmap) if clim is None: clim = data.min(), data.max() data = data.astype(np.float32) if clim[1] == clim[0]: if clim[0] != 0.: data *= 1.0 / clim[0] else: data -= clim[0] data /= clim[1] - clim[0] self.shared_program['u_volumetex{0:d}'.format(index)].set_data(data) self.shared_program.frag['cmap{0:d}'.format(index)] = Function(cmap.glsl_map) print(self.shared_program.frag) if self._vol_shape is None: self.shared_program['u_shape'] = data.shape[::-1] self._vol_shape = data.shape elif data.shape != self._vol_shape: raise ValueError("Shape of arrays should be {0} instead of {1}".format(self._vol_shape, data.shape)) self.shared_program['u_n_tex'] = len(self.volumes)
def test_colormap_single_hue(): """Test colormap support using a single hue()""" with TestingCanvas(size=size, bgcolor='w') as c: idata = np.linspace(255, 0, size[0]*size[1]).astype(np.ubyte) data = idata.reshape((size[0], size[1])) image = Image(cmap=get_colormap('single_hue', 255), clim='auto', parent=c.scene) image.set_data(data) assert_image_approved(c.render(), "visuals/colormap_hue.png")
def test_colormap_CubeHelix(): """Test colormap support using cubehelix colormap in only blues""" with TestingCanvas(size=size, bgcolor='w') as c: idata = np.linspace(255, 0, size[0]*size[1]).astype(np.ubyte) data = idata.reshape((size[0], size[1])) image = Image(cmap=get_colormap('cubehelix', rot=0, start=0), clim='auto', parent=c.scene) image.set_data(data) assert_image_approved(c.render(), "visuals/colormap_cubehelix.png")
def add_surf(self, surf, color=SKIN_COLOR, vertex_colors=None, values=None, limits_c=None, colormap=COLORMAP): """Add surfaces to the visualization. Parameters ---------- surf : instance of phypno.attr.anat.Surf surface to be plotted color : tuple or ndarray, optional 4-element tuple, representing RGB and alpha, between 0 and 1 vertex_colors : ndarray ndarray with n vertices x 4 to specify color of each vertex values : ndarray, optional vector with values for each vertex limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy """ if color is not None and len(color) == 3: color = r_[array(color), 1.] # make sure it's an array if values is not None: if limits_c is None: limits_c = nanmin(values), nanmax(values) norm_values = normalize(values, *limits_c) cm = get_colormap(colormap) vertex_colors = cm[norm_values].rgba hasnan = isnan(vertex_colors).all(axis=1) vertex_colors[hasnan, :] = color if vertex_colors is not None: color = None meshdata = MeshData(vertices=surf.vert, faces=surf.tri, vertex_colors=vertex_colors) mesh = SimpleMesh(meshdata, color) self._plt.view.add(mesh) surf_center = mean(surf.vert, axis=0) if surf_center[0] < 0: azimuth = 270 else: azimuth = 90 self._plt.view.camera.center = surf_center self._plt.view.camera.scale_factor = SCALE_FACTOR self._plt.view.camera.elevation = ELEVATION self._plt.view.camera.azimuth = azimuth self._plt.view.border_color = 'w' # border around surf self._surf.append(mesh)
def __init__(self, *args, **kwargs): kwargs.update(width = 40) visuals.LineVisual.__init__(self, *args, **kwargs) self.unfreeze() try: colormap = get_colormap(self._color) color = Function(colormap.glsl_map) except KeyError: color = Color(self._color).rgba self.non_selected_color = color self.freeze()
def genShape(vizMTX, offset=0, scale=1.0, colorize=False): thetas, phis = _np.meshgrid(_np.linspace(0, _np.pi, 181), _np.linspace(0, 2 * _np.pi, 360)) rs = offset + scale * vizMTX.reshape((181, -1)).T xs = rs * _np.sin(thetas) * _np.cos(phis) ys = rs * _np.sin(thetas) * _np.sin(phis) zs = rs * _np.cos(thetas) if colorize: cm = color.get_colormap('viridis') colors = cm[vizMTX] return scene.visuals.GridMesh(xs, ys, zs, colors=colors.rgba.reshape((181, -1, 4))) else: return scene.visuals.GridMesh(xs, ys, zs)
def genSphere(vizMTX, colorize=False): # visObj = scene.visuals.Sphere(radius=1, rows=362, cols=91, method='latitude', face_colors=colors) thetas, phis = _np.meshgrid(_np.linspace(0, _np.pi, 181), _np.linspace(0, 2 * _np.pi, 360)) rs = 1 xs = rs * _np.sin(thetas) * _np.cos(phis) ys = rs * _np.sin(thetas) * _np.sin(phis) zs = rs * _np.cos(thetas) if colorize: cm = color.get_colormap('viridis') colors = cm[vizMTX] return scene.visuals.GridMesh(xs, ys, zs, colors=colors.rgba.reshape((181, -1, 4))) else: return scene.visuals.GridMesh(xs, ys, zs)
def genScatter(vizMTX, colorize=False): vizMTX = vizMTX.reshape([-1, 1]) # Recreate angles angles = _np.array(generateAngles()) sphCoords = _np.concatenate((angles, _np.atleast_2d(vizMTX)), axis=1) xyzCoords = _np.array(sph2cart(*sphCoords.T)) scatterObj = scene.visuals.Markers() if colorize: cm = color.get_colormap('viridis') colors = cm[_np.squeeze(vizMTX)] scatterObj.set_data(xyzCoords.T, size=10, edge_color=None, face_color=colors) else: scatterObj.set_data(xyzCoords.T, size=10, edge_color=None, face_color='black') return scatterObj
def __init__(self, name, parameters, initial_plug='null', prng=None): Structure.__init__(self, name) self.params = parameters if not prng: self.prng = np.random.RandomState() else: self.prng = prng self.initial_plug = initial_plug L = self.params['L0'] N = int(self.params['N']) self.duration = self.params['span'] self.dt = self.params['dt'] self.spbL = self.add_point(idx=0, init_pos=[-L/2, 0, 0], color="gray") self.spbR = self.add_point(idx=1, init_pos=[L/2, 0, 0], color="gray") self.add_link(self.spbL, self.spbR) self.initial_plug = initial_plug self.chromosomes = [] # Generate colors cmap = get_colormap("husl") colors = cmap.map(np.linspace(0, 1, 3)) # Convert colors to html def _c(color): return "#{0:02x}{1:02x}{2:02x}".format(*np.round(color*255).astype('int')) colors = [_c(color) for color in colors] for color, n in zip(colors, range(N)): ch = Chromosome(n, self, color) self.chromosomes.append(ch) self.update_geometry()
def _prepare_chan_colors(color, chan_colors, values, limits_c, colormap): """Return colors for all the channels based on various inputs. Parameters ---------- color : tuple 3-, 4-element tuple, representing RGB and alpha, between 0 and 1 chan_colors : ndarray array with colors for each channel values : ndarray array with values for each channel limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy Returns ------- 1d / 2d array colors for all the channels or for each channel individually tuple of two float or None limits for the values """ if values is not None: if limits_c is None: limits_c = min(values), max(values) norm_values = normalize(values, *limits_c) cm = get_colormap(colormap) colors = cm[norm_values].rgba else: colors = array(color) # make sure it's an array if len(colors) == 3: colors = r_[colors, 1.] return colors, limits_c
# vispy: gallery 30 # ----------------------------------------------------------------------------- # Copyright (c) 2015, Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """Using Colorbars with the Canvas to demo different types""" from vispy import app from vispy import gloo from vispy.visuals import ColorBarVisual from vispy.color import get_colormap from vispy.visuals.transforms import NullTransform from vispy.visuals.transforms.transform_system import TransformSystem colormap = get_colormap("ice") def style_colorbar(colorbar): colorbar.label.font_size = 18 colorbar.label.color = "black" colorbar.clim = (0, 10) colorbar.ticks[0].font_size = 14 colorbar.ticks[1].font_size = 14 colorbar.ticks[0].color = "black" colorbar.ticks[1].color = "black" colorbar.border_width = 2 colorbar.border_color = "black"
def set_cmap(self, label, cmap): index = self.volumes[label]['index'] self.volumes[label]['cmap'] = cmap if isinstance(cmap, six.string_types): cmap = get_colormap(cmap) self.shared_program.frag['cmap{0:d}'.format(index)] = Function(cmap.glsl_map)
connset = set() while len(conn) < nedges: i, j = np.random.randint(npts, size=2) if i == j: continue p = 0.7 if types[i] == types[j] else 0.01 if np.random.random() < p: if (i, j) in connset: continue connset.add((i, j)) connset.add((j, i)) conn.append([i, j]) edges[:] = conn # Assign colors to each point based on its type cmap = color.get_colormap('cubehelix') typ_colors = np.array([cmap.map(x)[0, :3] for x in np.linspace(0.2, 0.8, typ)]) colors[:] = typ_colors[types] # Add some RGB noise and clip colors *= 1.1 ** np.random.normal(size=colors.shape) colors = np.clip(colors, 0, 1) # Display the data canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 lines = scene.Line(pos=pos, connect=edges, antialias=False, method='gl',
# -*- coding: utf-8 -*- # vispy: gallery 30 # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """Using Colorbars with the Canvas to demo different types""" from vispy import app from vispy import gloo from vispy.visuals import ColorBarVisual from vispy.color import get_colormap colormap = get_colormap("viridis") def style_colorbar(colorbar): colorbar.label.font_size = 18 colorbar.label.color = "black" colorbar.clim = (0, 10) colorbar.ticks[0].font_size = 14 colorbar.ticks[1].font_size = 14 colorbar.ticks[0].color = "black" colorbar.ticks[1].color = "black" colorbar.border_width = 1 colorbar.border_color = "black" return colorbar
from vispy import app from vispy import gloo from vispy.visuals.transforms import STTransform from vispy.visuals import ColorBarVisual, ImageVisual from vispy.color import Color, get_colormap import numpy as np ESCAPE_MAGNITUDE = 2 MIN_MAGNITUDE = 0.002 MAX_ITERATIONS = 50 colormap = get_colormap("hot") def get_num_escape_turns(x, y): """Returns the number of iterations it took to escape as normalized values. Parameters ---------- x: float the x coordinates of the point y: float the y coordinates of the point Returns
def __init__(self, nb_boxes, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), vertex_values=None, meshdata=None, shading=None, mode='triangles', variable_vis=False, **kwargs): # Visual.__init__ -> prepare_transforms() -> uses shading if shading is not None: raise ValueError('"shading" must be "None"') self.shading = shading self._variable_vis = variable_vis if variable_vis: Visual.__init__(self, vcode=vertex_template_vis, fcode=fragment_template_vis, **kwargs) else: Visual.__init__(self, vcode=vertex_template, fcode=fragment_template, **kwargs) self.set_gl_state('translucent', depth_test=True, cull_face=False) # Define buffers self._vertices = VertexBuffer(np.zeros((0, 3), dtype=np.float32)) self._normals = None self._faces = IndexBuffer() self._normals = VertexBuffer(np.zeros((0, 3), dtype=np.float32)) self._ambient_light_color = Color((0.3, 0.3, 0.3, 1.0)) self._light_dir = (10, 5, -5) self._shininess = 1. / 200. self._cmap = get_colormap('cubehelix') self._clim = 'auto' self._mode = mode # Uniform color self._color = Color(color) # primitive mode self._draw_mode = mode # Init self._bounds = None # Note we do not call subclass set_data -- often the signatures # do no match. VarVisMeshVisual.set_data(self, vertices=vertices, faces=faces, vertex_colors=vertex_colors, face_colors=face_colors, color=color, vertex_values=vertex_values, meshdata=meshdata) self.freeze()
import sys from vispy import scene from vispy.color import get_colormap import numpy as np from scipy.special import sph_harm canvas = scene.SceneCanvas(keys='interactive') view = canvas.central_widget.add_view() thetas, phis = np.meshgrid(np.linspace(0, np.pi, 100), np.linspace(0, 2*np.pi, 150)) shape = thetas.shape linear_shape = thetas.shape[0] * thetas.shape[1] cm = get_colormap('hot') for l in range(3): for m in range(l+1): harmonic_values = sph_harm(m, l, phis, thetas).real rs = 1. + 0.4*harmonic_values xs = rs * np.sin(thetas) * np.cos(phis) ys = rs * np.sin(thetas) * np.sin(phis) zs = rs * np.cos(thetas) xs -= 4.5 zs -= 4.5 xs += 2.5 * l zs += 2.5 * m
"""Using Colorbars with the Canvas with the Mandlebrot set""" from vispy import app from vispy import gloo from vispy.visuals.transforms import STTransform from vispy.visuals import ColorBarVisual, ImageVisual from vispy.color import Color, get_colormap import numpy as np ESCAPE_MAGNITUDE = 2 MIN_MAGNITUDE = 0.002 MAX_ITERATIONS = 50 colormap = get_colormap("hot") def get_num_escape_turns(x, y): """Returns the number of iterations it took to escape as normalized values. Parameters ---------- x: float the x coordinates of the point y: float the y coordinates of the point Returns
from vispy.io import load_data_file data = np.load(load_data_file('electrophys/iv_curve.npz'))['arr_0'] data *= 1000 # V -> mV dt = 1e-4 # this data is sampled at 10 kHz # create figure with plot fig = vp.Fig() plt = fig[0, 0] plt._configure_2d() plt.title.text = 'Current Clamp Recording' plt.ylabel.text = 'Membrane Potential (mV)' plt.xlabel.text = 'Time (ms)' selected = None # plot data cmap = get_colormap('hsl', value=0.5) colors = cmap.map(np.linspace(0.1, 0.9, data.shape[0])) t = np.arange(data.shape[1]) * (dt * 1000) for i, y in enumerate(data): line = plt.plot((t, y), color=colors[i]) line.interactive = True line.unfreeze() # make it so we can add a new property to the instance line.data_index = i line.freeze() # Build visuals used for cursor cursor_text = vp.Text("", pos=(0, 0), anchor_x='left', anchor_y='center', font_size=8, parent=plt.view.scene) cursor_line = vp.Line(parent=plt.view.scene) cursor_symbol = vp.Markers(pos=np.array([[0, 0]]), parent=plt.view.scene)
def __init__(self, n_volume_max=10, threshold=None, relative_step_size=0.8, emulate_texture=False): # Choose texture class tex_cls = TextureEmulated3D if emulate_texture else Texture3D self._n_volume_max = n_volume_max self._initial_shape = True self._vol_shape = (10, 10, 10) self._need_vertex_update = True # Create OpenGL program vert_shader, frag_shader = get_shaders(n_volume_max) # We deliberately don't use super here because we don't want to call # VolumeVisual.__init__ Visual.__init__(self, vcode=vert_shader, fcode=frag_shader) # Create gloo objects self._vertices = VertexBuffer() self._texcoord = VertexBuffer( np.array([ [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1], ], dtype=np.float32)) self.textures = [] for i in range(n_volume_max): # Set up texture object self.textures.append(tex_cls(self._vol_shape, interpolation='linear', wrapping='clamp_to_edge')) # Pass texture object and default colormap to shader program self.shared_program['u_volumetex_{0}'.format(i)] = self.textures[i] self.shared_program.frag['cmap{0:d}'.format(i)] = Function(get_colormap('grays').glsl_map) # Make sure all textures are disbaled self.shared_program['u_enabled_{0}'.format(i)] = 0 self.shared_program['u_weight_{0}'.format(i)] = 1 self.shared_program['a_position'] = self._vertices self.shared_program['a_texcoord'] = self._texcoord self.shared_program['u_shape'] = self._vol_shape[::-1] self._draw_mode = 'triangle_strip' self._index_buffer = IndexBuffer() self.shared_program.frag['sampler_type'] = self.textures[0].glsl_sampler_type self.shared_program.frag['sample'] = self.textures[0].glsl_sample # Only show back faces of cuboid. This is required because if we are # inside the volume, then the front faces are outside of the clipping # box and will not be drawn. self.set_gl_state('translucent', cull_face=False) self.relative_step_size = relative_step_size self.volumes = defaultdict(dict) self._data_shape = None self._block_size = np.array([1,1,1]) try: self.freeze() except AttributeError: # Older versions of VisPy pass
from vispy import plot as vp from vispy.color import get_colormap import vispy # create figure with plot fig = vp.Fig() ax_left = fig[0, 0] ax_right = fig[0, 1] ax_left._configure_2d() ax_left.title.text = 'Current Clamp Recording' ax_left.ylabel.text = 'Membrane Potential (mV)' ax_left.xlabel.text = 'Time (ms)' selected = None cmap = get_colormap('hsl', value=0.5) # colors = cmap.map(np.linspace(0.1, 0.9, df.shape[0])) colors = cmap.map(np.linspace(0.1, 0.9, CYCLE)) ax_right.histogram(df.iloc[:,3]) df = df.groupby("cycle_no") for i, (group_name, data) in enumerate(df): line = ax_left.plot((data["cycle_cnt"],data["val"]), color=colors[i]) line.interactive = True line.unfreeze() # make it so we can add a new property to the instance line.data_index = i line.freeze() if __name__ == '__main__':
"""Using Colorbars with the Canvas with the Mandlebrot set""" from vispy import app from vispy import gloo from vispy.visuals.transforms import (NullTransform, STTransform, TransformSystem) from vispy.visuals import ColorBarVisual, ImageVisual from vispy.color import Color, get_colormap import numpy as np MAX_AMPLITUDE = 2 MAX_ITERATIONS = 30 colormap = get_colormap("RdBu") def get_num_escape_turns(x, y): """Returns the number of iterations it took to escape as normalized values. Parameters ---------- x: float the x coordinates of the point y: float the y coordinates of the point Returns
size=colorbar_size) canvas1 = SeismicCanvas(title='Planarity', visual_nodes=visual_nodes, xyz_axis=xyz_axis, colorbar=colorbar, **canvas_params) # Image 2: seismic overlaid by fault semblance. semblance_vol = np.memmap('./F3_semblance.dat', dtype='>f4', mode='r', shape=volume_shape) # Get a colormap with alpha decreasing when value decreases. original_cmap = get_colormap('RdYeBuCy') alpha = np.linspace(0, 1, 128) # 128 color samples rgba = np.array([original_cmap.map(x) for x in alpha]).squeeze() rgba[:, -1] = alpha semblance_cmap = Colormap(rgba) semblance_range = (0.25, 1.0) visual_nodes = volume_slices([seismic_vol, semblance_vol], cmaps=[seismic_cmap, semblance_cmap], clims=[seismic_range, semblance_range], interpolation='bilinear', **slicing) xyz_axis = XYZAxis() colorbar = Colorbar(cmap=semblance_cmap, clim=semblance_range, label_str='Fault Semblance',
from vispy import app from vispy import gloo from vispy.visuals.transforms import (NullTransform, STTransform, TransformSystem) from vispy.visuals import ColorBarVisual, ImageVisual from vispy.color import Color, get_colormap import numpy as np MAX_AMPLITUDE = 2 MAX_ITERATIONS = 30 colormap = get_colormap("RdBu") def get_num_escape_turns(x, y): """Returns the number of iterations it took to escape as normalized values. Parameters ---------- x: float the x coordinates of the point y: float the y coordinates of the point Returns
def __init__( self, vol, clim=None, method='mip', threshold=None, relative_step_size=0.8, cmap='grays', gamma=1.0, clim_range_threshold=0.2, emulate_texture=False, interpolation='linear', ): tex_cls = TextureEmulated3D if emulate_texture else Texture3D # Storage of information of volume self._vol_shape = () self._clim = None self._texture_limits = None self._gamma = gamma self._need_vertex_update = True self._clim_range_threshold = clim_range_threshold # Set the colormap self._cmap = get_colormap(cmap) # Create gloo objects self._vertices = VertexBuffer() self._texcoord = VertexBuffer( np.array( [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1], ], dtype=np.float32, )) self._interpolation = interpolation self._tex = tex_cls( (10, 10, 10), interpolation=self._interpolation, wrapping='clamp_to_edge', ) # Create program Visual.__init__(self, vcode=VERT_SHADER, fcode="") self.shared_program['u_volumetex'] = self._tex self.shared_program['a_position'] = self._vertices self.shared_program['a_texcoord'] = self._texcoord self.shared_program['gamma'] = self._gamma self._draw_mode = 'triangle_strip' self._index_buffer = IndexBuffer() # Only show back faces of cuboid. This is required because if we are # inside the volume, then the front faces are outside of the clipping # box and will not be drawn. self.set_gl_state('translucent', cull_face=False) # Set data self.set_data(vol, clim) # Set params self.method = method self.relative_step_size = relative_step_size self.threshold = threshold if (threshold is not None) else vol.mean() self.freeze()
import sys from vispy import scene from vispy.color import get_colormap import numpy as np from scipy.special import sph_harm canvas = scene.SceneCanvas(keys='interactive') view = canvas.central_widget.add_view() thetas, phis = np.meshgrid(np.linspace(0, np.pi, 100), np.linspace(0, 2 * np.pi, 150)) shape = thetas.shape linear_shape = thetas.shape[0] * thetas.shape[1] cm = get_colormap('hot') for l in range(3): for m in range(l + 1): harmonic_values = sph_harm(m, l, phis, thetas).real rs = 1. + 0.4 * harmonic_values xs = rs * np.sin(thetas) * np.cos(phis) ys = rs * np.sin(thetas) * np.sin(phis) zs = rs * np.cos(thetas) xs -= 4.5 zs -= 4.5 xs += 2.5 * l zs += 2.5 * m
def cmap(self, cmap): self._cmap = get_colormap(cmap) self.shared_program.frag['cmap'] = Function(self._cmap.glsl_map) self.update()
connset = set() while len(conn) < nedges: i, j = np.random.randint(npts, size=2) if i == j: continue p = 0.7 if types[i] == types[j] else 0.01 if np.random.random() < p: if (i, j) in connset: continue connset.add((i, j)) connset.add((j, i)) conn.append([i, j]) edges[:] = conn # Assign colors to each point based on its type cmap = color.get_colormap('cubehelix') typ_colors = np.array([cmap.map(x)[0, :3] for x in np.linspace(0.2, 0.8, typ)]) colors[:] = typ_colors[types] # Add some RGB noise and clip colors *= 1.1**np.random.normal(size=colors.shape) colors = np.clip(colors, 0, 1) # Display the data canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 lines = scene.Line(pos=pos, connect=edges,
def __init__(self, icurves, highlight=None, clrmap="husl", colors=None, parent=None): """ :param icurves: input curve or list of curves :param clrmap: (optional) what colormap name from vispy.colormap to use :param colors: (optional) use list of colors instead of colormap """ self.canvas = scene.SceneCanvas( size=(1280, 900), position=(200, 200), keys="interactive", bgcolor=bg_clr, parent=parent, ) self.grid = self.canvas.central_widget.add_grid(spacing=0) self.view = self.grid.add_view(row=0, col=1, camera="panzoom") curves = np.array(icurves) if len(curves.shape) == 1: ## Single curve curves = np.array([icurves]) nb_traces, size = curves.shape # the Line visual requires a vector of X,Y coordinates xy_curves = np.dstack((np.tile(np.arange(size), (nb_traces, 1)), curves)) # Specify which points are connected # Start by connecting each point to its successor connect = np.empty((nb_traces * size - 1, 2), np.int32) connect[:, 0] = np.arange(nb_traces * size - 1) connect[:, 1] = connect[:, 0] + 1 # Prevent vispy from drawing a line between the last point # of a curve and the first point of the next curve for i in range(size, nb_traces * size, size): connect[i - 1, 1] = i - 1 if highlight is not None: # cheat by predrawing a single line over the highlighted one scene.Line(pos=xy_curves[highlight], color=highlighted, parent=self.view.scene) scene.Line(pos=xy_curves, color=others, parent=self.view.scene, connect=connect) else: if colors is None: colormap = color.get_colormap(clrmap)[np.linspace( 0.0, 1.0, nb_traces * size)] else: colormap = color.get_colormap(clrmap)[colors] scene.Line(pos=xy_curves, color=colormap, parent=self.view.scene, connect=connect) self.x_axis = scene.AxisWidget(orientation="bottom") self.y_axis = scene.AxisWidget(orientation="left") self.x_axis.stretch = (1, 0.05) self.y_axis.stretch = (0.05, 1) self.grid.add_widget(self.x_axis, row=1, col=1) self.grid.add_widget(self.y_axis, row=0, col=0) self.x_axis.link_view(self.view) self.y_axis.link_view(self.view) self.view.camera.set_range(x=(-1, size), y=(curves.min(), curves.max())) self.canvas.show() if parent is None: self.canvas.app.run()
def cmap(self, cm): self._cmap = get_colormap(cm) self.fshader['color_transform'] = FunctionChain(None, [Function(_c2l), Function(self._cmap.glsl_map)])
# -*- coding: utf-8 -*- # vispy: gallery 30 # ----------------------------------------------------------------------------- # Copyright (c) 2015, Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """Using Colorbars with the Canvas to demo different types""" from vispy import app from vispy import gloo from vispy.visuals import ColorBarVisual from vispy.color import get_colormap colormap = get_colormap("viridis") def style_colorbar(colorbar): colorbar.label.font_size = 18 colorbar.label.color = "black" colorbar.clim = (0, 10) colorbar.ticks[0].font_size = 14 colorbar.ticks[1].font_size = 14 colorbar.ticks[0].color = "black" colorbar.ticks[1].color = "black" colorbar.border_width = 3 colorbar.border_color = "black"
def cmap(self, cmap): self._cmap = get_colormap(cmap) self.mesh_data_changed()
def cmap(self, cmap): self._cmap = get_colormap(cmap) self._need_colortransform_update = True self.update()
def test_color_colormap(attribute): """Test setting edge/face color with a colormap""" # create Shapes using with a colormap shape = (10, 4, 2) np.random.seed(0) data = 20 * np.random.random(shape) properties = {'shape_type': _make_cycled_properties([0, 1.5], shape[0])} shapes_kwargs = { 'properties': properties, f'{attribute}_color': 'shape_type', f'{attribute}_colormap': 'gray', } layer = Shapes(data, **shapes_kwargs) assert layer.properties == properties color_mode = getattr(layer, f'{attribute}_color_mode') assert color_mode == 'colormap' color_array = transform_color(['black', 'white'] * int((shape[0] / 2))) attribute_color = getattr(layer, f'{attribute}_color') assert np.all(attribute_color == color_array) # change the color cycle - face_color should not change setattr(layer, f'{attribute}_color_cycle', ['red', 'blue']) attribute_color = getattr(layer, f'{attribute}_color') assert np.all(attribute_color == color_array) # Add new shape and test its color new_shape = np.random.random((1, 4, 2)) layer.selected_data = {0} layer.add(new_shape) attribute_color = getattr(layer, f'{attribute}_color') assert len(attribute_color) == shape[0] + 1 np.testing.assert_allclose( attribute_color, np.vstack((color_array, transform_color('black'))), ) # Check removing data adjusts colors correctly layer.selected_data = {0, 2} layer.remove_selected() assert len(layer.data) == shape[0] - 1 attribute_color = getattr(layer, f'{attribute}_color') assert len(attribute_color) == shape[0] - 1 np.testing.assert_allclose( attribute_color, np.vstack(( color_array[1], color_array[3:], transform_color('black'), )), ) # adjust the clims setattr(layer, f'{attribute}_contrast_limits', (0, 3)) layer.refresh_colors(update_color_mapping=False) attribute_color = getattr(layer, f'{attribute}_color') np.testing.assert_allclose(attribute_color[-2], [0.5, 0.5, 0.5, 1]) # change the colormap new_colormap = 'viridis' setattr(layer, f'{attribute}_colormap', new_colormap) attribute_colormap = getattr(layer, f'{attribute}_colormap') assert attribute_colormap[1] == get_colormap(new_colormap)
def vispy_or_mpl_colormap(name): """Try to get a colormap from vispy, or convert an mpl one to vispy format. Parameters ---------- name : str The name of the colormap. Returns ------- colormap : napari.utils.Colormap The found colormap. Raises ------ KeyError If no colormap with that name is found within vispy or matplotlib. """ if name in _VISPY_COLORMAPS_TRANSLATIONS: cmap = get_colormap(name) colormap = convert_vispy_colormap(cmap, name=name) else: try: mpl_cmap = getattr(cm, name) if name in _MATPLOTLIB_COLORMAP_NAMES: display_name = _MATPLOTLIB_COLORMAP_NAMES[name] else: display_name = name except AttributeError: suggestion = _MATPLOTLIB_COLORMAP_NAMES_REVERSE.get( name ) or _MATPLOTLIB_COLORMAP_NAMES_REVERSE.get(name) if suggestion: raise KeyError( trans._( 'Colormap "{name}" not found in either vispy or matplotlib but you might want to use "{suggestion}".', deferred=True, name=name, suggestion=suggestion, ) ) else: colormaps = set(_VISPY_COLORMAPS_ORIGINAL).union( set(_MATPLOTLIB_COLORMAP_NAMES) ) raise KeyError( trans._( 'Colormap "{name}" not found in either vispy or matplotlib. Recognized colormaps are: {colormaps}', deferred=True, name=name, colormaps=", ".join( sorted([f'"{cm}"' for cm in colormaps]) ), ) ) mpl_colors = mpl_cmap(np.linspace(0, 1, 256)) colormap = Colormap( name=name, display_name=display_name, colors=mpl_colors ) return colormap
def edge_colormap(self, colormap: Union[str, Colormap]): self._edge_colormap = get_colormap(colormap) if isinstance(colormap, str): self._edge_colormap_name = colormap else: self._edge_colormap_name = 'unknown_colormap'
def __init__(self, n_volume_max=10, threshold=None, relative_step_size=0.8, emulate_texture=False): # Choose texture class tex_cls = TextureEmulated3D if emulate_texture else Texture3D self._n_volume_max = n_volume_max self._initial_shape = True self._vol_shape = (10, 10, 10) self._need_vertex_update = True # Create OpenGL program vert_shader, frag_shader = get_shaders(n_volume_max) # We deliberately don't use super here because we don't want to call # VolumeVisual.__init__ Visual.__init__(self, vcode=vert_shader, fcode=frag_shader) # Create gloo objects self._vertices = VertexBuffer() self._texcoord = VertexBuffer( np.array([ [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1], ], dtype=np.float32)) self.textures = [] for i in range(n_volume_max): # Set up texture object self.textures.append( tex_cls(self._vol_shape, interpolation='linear', wrapping='clamp_to_edge')) # Pass texture object and default colormap to shader program self.shared_program['u_volumetex_{0}'.format(i)] = self.textures[i] self.shared_program.frag['cmap{0:d}'.format(i)] = Function( get_colormap('grays').glsl_map) # Make sure all textures are disbaled self.shared_program['u_enabled_{0}'.format(i)] = 0 self.shared_program['u_weight_{0}'.format(i)] = 1 self.shared_program['a_position'] = self._vertices self.shared_program['a_texcoord'] = self._texcoord self.shared_program['u_shape'] = self._vol_shape[::-1] self._draw_mode = 'triangle_strip' self._index_buffer = IndexBuffer() self.shared_program.frag['sampler_type'] = self.textures[ 0].glsl_sampler_type self.shared_program.frag['sample'] = self.textures[0].glsl_sample # Only show back faces of cuboid. This is required because if we are # inside the volume, then the front faces are outside of the clipping # box and will not be drawn. self.set_gl_state('translucent', cull_face=False) self.relative_step_size = relative_step_size self.volumes = defaultdict(dict) self._data_shape = None self._block_size = np.array([1, 1, 1]) try: self.freeze() except AttributeError: # Older versions of VisPy pass