This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
Vispy depends on NumPy and PyOpenGL. A backend library is necessary (PyQt4 or PySide for example).
This recipe has been tested with the development version of Vispy. You should clone the GitHub repository and install Vispy with python setup.py install
.
The API used in this recipe might change in future versions.
import numpy as np
from vispy import app
from vispy import gloo
c = app.Canvas(keys='interactive')
vispy.gloo
, we need to write shaders. These programs written in a C-like language run on the GPU and give us full flexibility for our visualizations. Here, we create a trivial vertex shader that directly displays 2D data points (stored in the a_position
variable) in the canvas. We give more details in There's more.vertex = """
attribute vec2 a_position;
void main (void)
{
gl_Position = vec4(a_position, 0.0, 1.0);
}
"""
fragment = """
void main()
{
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
}
"""
program = gloo.Program(vertex, fragment)
a_position
to a (1000, 2)
NumPy array containing the coordinates of 1000 data points. In the default coordinate system, the coordinates of the four canvas corners are (+/-1, +/-1)
.program['a_position'] = np.c_[
np.linspace(-1.0, +1.0, 1000).astype(np.float32),
np.random.uniform(-0.5, +0.5, 1000).astype(np.float32)]
@c.connect
def on_resize(event):
gloo.set_viewport(0, 0, *event.size)
on_draw
function renders the entire scene. First, we clear the window in white (it is necessary to do that at every frame). Then, we draw a succession of line segments using our OpenGL program.@c.connect
def on_draw(event):
gloo.clear((1,1,1,1))
program.draw('line_strip')
c.show()
app.run();
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).