pulse2percept.utils.animation

HTMLAnimation

Fast, dependency-free HTML/JavaScript animations.

HTMLAnimation renders the static parts of the figure exactly once and packs all frames into a single, color-mapped sprite sheet that is blitted into a <canvas> by a small vanilla-JavaScript player. This is typically two orders of magnitude faster and produces much smaller notebooks and doc pages.

The sheet is encoded as JPEG by default, which roughly halves it again; pass fmt='png' if you need the frames to be pixel-exact.

Functions

frame_interval(time[, fps, tol])

Determine the delay between two frames of an animation

Classes

HTMLAnimation(fig, func[, frames, image, ...])

A FuncAnimation with a fast player

class pulse2percept.utils.animation.HTMLAnimation(fig, func, frames=None, *args, image=None, frame_data=None, labels=None, fmt='jpg', **kwargs)[source]

A FuncAnimation with a fast player

Behaves exactly like FuncAnimation (including save and to_html5_video), but renders to HTML through a self-contained JavaScript player instead of Matplotlib’s to_jshtml. Instead of re-rendering the whole figure once per frame, the static parts of the figure are rendered once and all frames are shipped as a single color-mapped sprite sheet.

Added in version 0.10.0.

Parameters:
  • fig – Passed to FuncAnimation

  • func – Passed to FuncAnimation

  • frames – Passed to FuncAnimation

  • *args – Passed to FuncAnimation

  • **kwargs – Passed to FuncAnimation

  • image (matplotlib.image.AxesImage) – The image artist that is updated by func. Its position, colormap, and normalization determine how the frames are drawn

  • frame_data (ndarray) – Either (Y, X, T) scalar data, (Y, X, 3, T) RGB data, or (Y, X, 4, T) RGBA data, matching what func displays in image

  • labels (list of str or None) – Per-frame titles. If None, the title is left alone

  • fmt ({'jpg', 'png'}, optional) – Whether to encode the frames as JPEG or PNG. JPEG is typically an order of magnitude smaller, PNG is lossless

Notes

  • Frames are quantized to 256 levels and embedded at most at the size at which they are displayed, exactly like Matplotlib would rasterize them.

  • The per-frame title is drawn by the browser, so it uses DejaVu Sans if available and falls back to the default sans-serif font otherwise.

to_jshtml(fps=None, embed_frames=True, default_mode=None)[source]

Generate an HTML representation of the animation

Parameters:
  • fps (float or None) – Frames per second. If None, uses the animation’s interval.

  • embed_frames (bool) – Unused; frames are always embedded.

  • default_mode ({'loop', 'once', 'reflect'} or None) – What the animation should do once it has played through. If None, uses ‘loop’ or ‘once’, depending on repeat.

new_frame_seq()[source]

Return a new sequence of frame information.

new_saved_frame_seq()[source]

Return a new sequence of saved/cached frame information.

pause()[source]

Pause the animation.

resume()[source]

Resume the animation.

save(filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None, *, progress_callback=None)[source]

Save the animation as a movie file by drawing every frame.

Parameters:
  • filename (str) – The output filename, e.g., mymovie.mp4.

  • writer (MovieWriter or str, default: :rc:`animation.writer`) – A MovieWriter instance to use or a key that identifies a class to use, such as ‘ffmpeg’.

  • fps (int, optional) – Movie frame rate (per second). If not set, the frame rate from the animation’s frame interval.

  • dpi (float, default: :rc:`savefig.dpi`) – Controls the dots per inch for the movie frames. Together with the figure’s size in inches, this controls the size of the movie.

  • codec (str, default: :rc:`animation.codec`.) – The video codec to use. Not all codecs are supported by a given MovieWriter.

  • bitrate (int, default: :rc:`animation.bitrate`) – The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.

  • extra_args (list of str or None, optional) – Extra command-line arguments passed to the underlying movie encoder. These arguments are passed last to the encoder, just before the output filename. The default, None, means to use :rc:`animation.[name-of-encoder]_args` for the builtin writers.

  • metadata (dict[str, str], default: {}) – Dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.

  • extra_anim (list, default: []) – Additional Animation objects that should be included in the saved movie file. These need to be from the same .Figure instance. Also, animation frames will just be simply combined, so there should be a 1:1 correspondence between the frames from the different animations.

  • savefig_kwargs (dict, default: {}) – Keyword arguments passed to each ~.Figure.savefig call used to save the individual frames.

  • progress_callback (function, optional) –

    A callback function that will be called for every frame to notify the saving progress. It must have the signature

    def func(current_frame: int, total_frames: int) -> Any
    

    where current_frame is the current frame number and total_frames is the total number of frames to be saved. total_frames is set to None, if the total number of frames cannot be determined. Return values may exist but are ignored.

    Example code to write the progress to stdout:

    progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
    

Notes

fps, codec, bitrate, extra_args and metadata are used to construct a .MovieWriter instance and can only be passed if writer is a string. If they are passed as non-None and writer is a .MovieWriter, a RuntimeError will be raised.

to_html5_video(embed_limit=None)[source]

Convert the animation to an HTML5 <video> tag.

This saves the animation as an h264 video, encoded in base64 directly into the HTML5 video tag. This respects :rc:`animation.writer` and :rc:`animation.bitrate`. This also makes use of the interval to control the speed, and uses the repeat parameter to decide whether to loop.

Parameters:

embed_limit (float, optional) – Limit, in MB, of the returned animation. No animation is created if the limit is exceeded. Defaults to :rc:`animation.embed_limit` = 20.0.

Returns:

An HTML5 video tag with the animation embedded as base64 encoded h264 video. If the embed_limit is exceeded, this returns the string “Video too large to embed.”

Return type:

str

pulse2percept.utils.animation.frame_interval(time, fps=None, tol=0.01)[source]

Determine the delay between two frames of an animation

Added in version 0.10.0.

Parameters:
  • time (array_like) – The time points of the animation (in ms)

  • fps (float or None) – Frames per second. If None, the interval is inferred from time, which is not supported for a non-homogeneous time axis.

  • tol (float, optional) – Tolerance within which two time steps count as equal

Returns:

interval – The delay between two frames (in ms). A single-frame animation has no time step of its own and falls back on SINGLE_FRAME_INTERVAL.

Return type:

float