Animations#

Activity that moves (waves, bumps, sequences) is easiest to understand in motion. Three functions turn simulation output into Matplotlib animations:

Function

Input

Returns

animate_1D

one or more (time, neurons) arrays, drawn as lines over the neuron axis

the figure; the animation is fig.animation

animate_2D

(time, neurons) or (time, height, width) values on a grid

a FuncAnimation

animator

(time, height, width) image frames

an ArtistAnimation

In a notebook, display an animation with IPython.display.HTML(anim.to_jshtml()), which embeds every frame; save it with anim.save("file.gif", writer="pillow") (or .mp4 with ffmpeg installed). Keep figures small and frames few: each frame is stored as an image.

1. Setup#

import matplotlib.pyplot as plt
import numpy as np
from IPython.display import HTML

import braintools

plt.rcParams["figure.dpi"] = 60
plt.rcParams["animation.embed_limit"] = 30      # MB
rng = np.random.default_rng(7)

2. A Moving Bump in a Ring: animate_1D#

A ring of 100 neurons carries a bump of activity that drifts around the ring, as in head-direction or working-memory models. dynamical_vars holds the time-varying data as arrays of shape (time, neurons) or as dicts {'ys': ..., 'xs': ..., 'legend': ...}; static_vars are drawn unchanged in every frame (here a firing threshold). frame_step skips frames and dt labels the time.

n, n_steps, dt = 100, 120, 2.0                        # neurons, steps, ms per step
angle = np.linspace(-np.pi, np.pi, n, endpoint=False)
center = np.cumsum(rng.normal(0.05, 0.03, n_steps))    # bump position drifts
rates = 30 * np.exp(3 * (np.cos(angle[None] - center[:, None]) - 1)) + rng.normal(0, 1, (n_steps, n))

fig = braintools.visualize.animate_1D(
    dynamical_vars={"ys": rates, "xs": np.degrees(angle), "legend": "rate"},
    static_vars={"ys": np.full(n, 20.0), "xs": np.degrees(angle), "legend": "threshold"},
    dt=dt, frame_step=4, xlabel="Preferred direction (deg)", ylabel="Rate (Hz)",
    figsize=(5, 3), show=False)
html = fig.animation.to_jshtml()
plt.close(fig)
HTML(html)

animate_1D returns the figure; the animation object is attached as fig.animation, which keeps it alive (an animation without a reference is discarded before rendering anything) and gives access to to_jshtml() and save(...). The title shows the time of each frame; frame \(t\) is labelled \((t + 1)\,\Delta t\), the convention for values recorded after each simulation step.

3. A Wave on a Sheet: animate_2D#

A 30 × 30 sheet of neurons with a plane wave of activity, slowly turning. animate_2D accepts values of shape (time, height * width) with net_size=(height, width), or (time, height, width) directly. val_min/val_max fix the color scale across frames (by default the range of all values):

h = w = 30
yy, xx = np.mgrid[0:h, 0:w] / h
frames = []
for k in range(60):
    direction = 0.02 * k
    phase = 2 * np.pi * (np.cos(direction) * xx + np.sin(direction) * yy) * 2 - 0.3 * k
    frames.append(np.maximum(np.cos(phase), 0) ** 3 + 0.1 * rng.random((h, w)))
frames = np.array(frames)                                 # (60, 30, 30)

anim = braintools.visualize.animate_2D(frames.reshape(60, -1), net_size=(h, w), dt=1.0, frame_step=2,
                                       cmap="magma", figsize=(4, 3.6), show=False)
html = anim.to_jshtml()
plt.close(anim._fig)
HTML(html)

4. Image Sequences: animator#

animator(data, fig, ax) is the simplest option: it shows each (height, width) frame of a (time, height, width) array as an image on the given axes (which it turns off) and returns an ArtistAnimation; num_steps limits the number of frames and interval sets the delay in milliseconds. A typical use is spiking input, such as a Poisson-encoded image. Here a disk is encoded as spikes with rate proportional to pixel intensity:

img = ((np.mgrid[0:28, 0:28] - 13.5) ** 2).sum(0) < 80                      # a 28 x 28 disk
spikes = rng.random((40, 28, 28)) < 0.3 * img                                # 40 time steps of Poisson spikes
fig, ax = plt.subplots(figsize=(3, 3))
anim = braintools.visualize.animator(spikes.astype(float), fig, ax, interval=80, cmap="gray")
html = anim.to_jshtml()
plt.close(fig)
HTML(html)

Each frame shows a different random subset of the disk’s pixels; the image only emerges when frames are averaged, which is what a downstream neuron integrating over time does.

5. Saving#

All three can be saved with Matplotlib’s writers: GIFs with the built-in Pillow writer, MP4 with ffmpeg if it is installed. animate_1D and animate_2D also take save_path (a name ending in .gif uses Pillow, otherwise MP4 with ffmpeg) together with gif_dpi / video_fps:

import os
import tempfile

path = os.path.join(tempfile.mkdtemp(), "spikes.gif")
anim.save(path, writer="pillow", fps=10)
print(f"saved {os.path.getsize(path) / 1024:.0f} kB to {os.path.basename(path)}")
saved 32 kB to spikes.gif

Summary#

  • animate_1D animates line plots of (time, neurons) data, with static reference lines; the animation is fig.animation.

  • animate_2D animates values on a 2-D grid with a fixed color scale.

  • animator turns a stack of image frames into an animation on existing axes.

  • Display in notebooks with HTML(anim.to_jshtml()) (and close the figure to avoid a duplicate static image); save with anim.save(..., writer="pillow").