pulse2percept.utils.animation
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 per animated
image, which a small vanilla-JavaScript player blits into a <canvas>. 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
|
Determine the delay between two frames of an animation |
Classes
|
A |
- class pulse2percept.utils.animation.HTMLAnimation(fig, func, frames=None, *args, image=None, frame_data=None, frame_index=None, labels=None, title=None, fmt='jpg', intervals=None, **kwargs)[source]
A
FuncAnimationwith a fast playerBehaves exactly like
FuncAnimation(includingsaveandto_html5_video), but renders to HTML through a self-contained JavaScript player instead of Matplotlib’sto_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
FuncAnimationfunc – Passed to
FuncAnimationframes – Passed to
FuncAnimation*args – Passed to
FuncAnimation**kwargs – Passed to
FuncAnimationimage (matplotlib.image.AxesImage or list thereof) – The image artist(s) updated by
func. Their position, colormap, and normalization determine how the frames are drawnframe_data (ndarray or list thereof) – One array per image: either (Y, X, T) scalar data, (Y, X, 3, T) RGB data, or (Y, X, 4, T) RGBA data, matching what
funcdisplaysframe_index (list of (array_like or None), optional) –
One entry per image, giving the frame of
frame_datathat each display frame shows. None (the default, or per image) advances that image one frame at a time. This is what lets a still image or a source sampled at another rate share a clock with the rest of the figure.Added in version 0.11.0.
labels (list of str or None) – Per-frame titles. If None, the title is left alone
title (matplotlib.text.Text, optional) –
The artist that
labelsare drawn into. Defaults to the title of the first image’s Axes; passfig.suptitle('')to label a figure with more than one animated panel.Added in version 0.11.0.
fmt ({'jpg', 'png'}, optional) – Whether to encode the frames as JPEG or PNG. JPEG is typically an order of magnitude smaller, PNG is lossless
intervals (array_like or None, optional) –
How long each frame stays up (in ms), one value per frame. If None, every frame is shown for
intervalms. Frames of unequal duration are what lets an animation follow an irregular time axis.Added in version 0.10.0.
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.
Changed in version 0.11.0: A figure may animate more than one image.
- to_jshtml(fps=None, embed_frames=True, default_mode=None)[source]
Generate an HTML representation of the animation
- Parameters:
fps (float or None) – Display sampling rate in Hz. If None, show every percept frame using its recorded timing. Otherwise resample onto a regular display clock using zero-order hold. Playback duration is preserved to within one display frame. May also be given as a unitful frequency.
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.
- 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 (AbstractMovieWriter subclass or str, default:
rcParams[“animation.writer”](default:'ffmpeg')) –The writer used to grab the frames and create the movie file. This can be an instance of an AbstractMovieWriter subclass or a string. The builtin writers are
str
class
’ffmpeg’
.FFMpegWriter
’ffmpeg_file’
.FFMpegFileWriter
’imagemagick’
.ImageMagickWriter
’imagemagick_file’
.ImageMagickFileWriter
’pillow’
.PillowWriter
’html’
.HTMLWriter
fps (int, optional) – Movie frame rate (per second). If not set, the frame rate from the animation’s frame interval.
dpi (float, default:
rcParams[“savefig.dpi”](default:'figure')) – 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:
rcParams[“animation.codec”](default:'h264').) – The video codec to use. Not all codecs are supported by a given MovieWriter.bitrate (int, default:
rcParams[“animation.bitrate”](default:-1)) – 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
rcParams[“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
rcParams[“animation.writer”](default:'ffmpeg') andrcParams[“animation.bitrate”](default:-1). 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
rcParams[“animation.embed_limit”](default:20.0) = 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:
- 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.May be given as a plain number of hertz or as a unitful frequency (e.g.
0.03 * kHz); seepulse2percept.units.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: