Manim Animations

Manim is a animation library intially developed by the creator of the popular 3Blue1Brown YouTube channel and used extensively in his videos.

This page shows how Manim can be integrated with Quarto to create beautiful animations programmatically.

Examples

Basic Example

The example below show a very basic manim animatiom from code directly in this document. The code for the animation is shown in a seperate tab.

The code below is identical to that used to render the animation. It is slightly more complex than what is just required for the animation.

#| echo: false

## Imports 
from manim import *
from IPython.utils.capture import capture_output

# Configuration
config.media_width = "100%"
config.media_embed = True

# Manim animation definition
class CreateCircle(Scene):
    def construct(self):
        circle = Circle()  # create a circle
        circle.set_fill(PINK, opacity=0.5)  # set the color and transparency
        self.play(Create(circle))  # show the circle on screen

# Jupyter hack to run and capture the manim animation but surpressing additional outputs. 
with capture_output() as captured:
    get_ipython().run_line_magic(
        "manim",
        "-qh -v WARNING --progress_bar None CreateCircle",
    )

# Display the animation
video = captured.outputs[-1]
video.data["text/html"] = (
    video.data["text/html"]
    .replace(" autoplay", "")
    .replace(" loop", "")
)
video.display()

In addition the code a cell containing the following must be included before the code cell

#| include: false
%load_ext manim

As this is neccessary to configure the Jupyter-hack we’re relying on.

Less basic example: Element-wise addition

This example shows element-wise addition, a very common operation when using e.g. numpy.

The manim code is more substantial than before - but so is the resulting animation.

from manim import *
from IPython.utils.capture import capture_output

config.media_width = "100%"
config.media_embed = True

class ElementWiseAddition(Scene):
    def construct(self):
        self.camera.background_color = "#101820"

        title = Text("Element-wise addition", font_size=40, weight=BOLD)
        title.to_edge(UP)
        intro_title = Text("Element-wise addition", font_size=46, weight=BOLD)
        intro_subtitle = Text(
            "Combine matching positions",
            font_size=28,
            color=GRAY_B,
        )
        intro_expression = MathTex(
            r"\begin{bmatrix}2\\-1\\3\end{bmatrix}",
            "+",
            r"\begin{bmatrix}4\\5\\-2\end{bmatrix}",
            "=",
            r"\begin{bmatrix}6\\4\\1\end{bmatrix}",
            font_size=46,
        )
        intro_expression[0].set_color(BLUE_C)
        intro_expression[2].set_color(GREEN_C)
        intro_expression[4].set_color(YELLOW_C)
        title_card = VGroup(intro_title, intro_subtitle, intro_expression)
        title_card.arrange(DOWN, buff=0.45)
        self.add(title_card)
        self.wait(1.0)

        left_values = [2, -1, 3]
        right_values = [4, 5, -2]
        result_values = [a + b for a, b in zip(left_values, right_values)]

        left = Matrix([[value] for value in left_values], h_buff=1.0)
        right = Matrix([[value] for value in right_values], h_buff=1.0)
        result = Matrix([[value] for value in result_values], h_buff=1.0)

        left.set_color(BLUE_C)
        right.set_color(GREEN_C)
        result.set_color(YELLOW_C)

        plus = MathTex("+", font_size=56)
        equals = MathTex("=", font_size=56)
        expression = VGroup(left, plus, right, equals, result).arrange(RIGHT, buff=0.55)
        expression.move_to(ORIGIN).shift(UP * 0.15)

        left_label = Text("a", font_size=28, color=BLUE_C).next_to(left, DOWN)
        right_label = Text("b", font_size=28, color=GREEN_C).next_to(right, DOWN)
        result_label = Text("a + b", font_size=28, color=YELLOW_C).next_to(result, DOWN)

        self.play(
            ReplacementTransform(intro_title, title),
            FadeOut(intro_subtitle),
            FadeOut(intro_expression),
            run_time=0.8,
        )
        self.play(
            Create(left),
            FadeIn(plus),
            Create(right),
            FadeIn(equals),
            Create(result),
            FadeIn(left_label, right_label, result_label),
        )
        self.wait(0.4)

        result_entries = result.get_entries()
        for index, (a_value, b_value, sum_value) in enumerate(
            zip(left_values, right_values, result_values)
        ):
            left_entry = left.get_entries()[index]
            right_entry = right.get_entries()[index]
            result_entry = result_entries[index]

            guide = SurroundingRectangle(
                VGroup(left_entry, right_entry, result_entry),
                color=WHITE,
                buff=0.18,
            )
            calculation = MathTex(
                f"{a_value}", "+", f"{b_value}", "=", f"{sum_value}",
                font_size=40,
            )
            calculation[0].set_color(BLUE_C)
            calculation[2].set_color(GREEN_C)
            calculation[4].set_color(YELLOW_C)
            calculation.next_to(expression, DOWN, buff=0.75)

            left_copy = left_entry.copy()
            right_copy = right_entry.copy()

            self.play(Create(guide), run_time=0.3)
            self.play(
                TransformFromCopy(left_entry, calculation[0]),
                FadeIn(calculation[1]),
                TransformFromCopy(right_entry, calculation[2]),
                FadeIn(calculation[3]),
                run_time=0.7,
            )
            self.play(
                TransformFromCopy(VGroup(left_copy, right_copy), calculation[4]),
                result_entry.animate.set_color(YELLOW),
                run_time=0.7,
            )
            self.wait(0.25)
            self.play(FadeOut(guide), FadeOut(calculation), run_time=0.35)

        final_rule = Text(
            "Same position, same operation",
            font_size=28,
            color=GRAY_B,
        ).next_to(expression, DOWN, buff=0.75)
        self.play(FadeIn(final_rule), result.animate.scale(1.08))
        self.wait(1.2)

with capture_output() as captured:
    get_ipython().run_line_magic(
        "manim",
        "-qh -v WARNING --progress_bar None ElementWiseAddition",
    )

video = captured.outputs[-1]
video.data["text/html"] = (
    video.data["text/html"]
    .replace(" autoplay", "")
    .replace(" loop", "")
)
video.display()

Biological Example: Codon to protein

This animation shows how mRNA is translated into amino acids. This is substantially more invovled than the basic example. However, LLM’s are quite good at this type of task (this was made using Codex).

#| echo: false
from manim import *
from IPython.utils.capture import capture_output

config.media_width = "100%"
config.media_embed = True

class CodonToProtein(Scene):
    def construct(self):
        self.camera.background_color = "#0d1b1e"

        title = Text("Codon to protein", font_size=40, weight=BOLD)
        title.to_edge(UP)
        intro_title = Text("Codon to protein", font_size=46, weight=BOLD)
        intro_subtitle = Text(
            "Translate mRNA triplets into amino acids",
            font_size=27,
            color=GRAY_B,
        )
        intro_mrna = Text("AUG  GCU  UUC  GAA  UAG", font_size=34, color=YELLOW)
        intro_arrow = MathTex("\\Downarrow", font_size=42, color=GRAY_A)
        intro_protein = Text("Met - Ala - Phe - Glu - Stop", font_size=31, color=TEAL_C)
        title_card = VGroup(
            intro_title,
            intro_subtitle,
            intro_mrna,
            intro_arrow,
            intro_protein,
        )
        title_card.arrange(DOWN, buff=0.32)
        self.add(title_card)
        self.wait(1.0)

        sequence = "AUGGCUUUCGAAUAG"
        codons = ["AUG", "GCU", "UUC", "GAA", "UAG"]
        amino_acids = ["Met", "Ala", "Phe", "Glu", "Stop"]
        amino_colors = [TEAL_C, BLUE_C, PURPLE_C, ORANGE, RED_C]

        bases = VGroup()
        for base in sequence:
            box = RoundedRectangle(
                width=0.45,
                height=0.48,
                corner_radius=0.05,
                stroke_color=GRAY_A,
                fill_color="#142f35",
                fill_opacity=1,
            )
            label = Text(base, font_size=24, color=WHITE)
            bases.add(VGroup(box, label))

        bases.arrange(RIGHT, buff=0.08)
        bases.move_to(ORIGIN).shift(UP * 1.35)

        mrna_label = Text("mRNA", font_size=24, color=GRAY_B).next_to(bases, LEFT, buff=0.35)
        ribosome = RoundedRectangle(
            width=2.25,
            height=1.15,
            corner_radius=0.18,
            stroke_color=YELLOW_C,
            fill_color="#3a3f2d",
            fill_opacity=0.75,
        )
        ribosome.move_to(bases[1].get_center()).shift(DOWN * 0.1)
        ribosome_label = Text("ribosome", font_size=22, color=YELLOW_C)
        ribosome_label.next_to(ribosome, DOWN, buff=0.12)

        codon_window = SurroundingRectangle(
            VGroup(*bases[:3]),
            color=YELLOW,
            buff=0.08,
        )

        protein_count = len(amino_acids) - 1
        amino_spacing = 1.05
        chain_center = DOWN * 2.0
        chain_origin = chain_center + LEFT * ((protein_count - 1) * amino_spacing / 2)
        protein_label = Text("protein", font_size=24, color=GRAY_B)
        protein_label.next_to(chain_center + LEFT * 2.35, LEFT, buff=0.0)
        peptide_chain = VGroup()

        self.play(
            ReplacementTransform(intro_title, title),
            FadeOut(intro_subtitle),
            FadeOut(intro_mrna),
            FadeOut(intro_arrow),
            FadeOut(intro_protein),
            run_time=0.8,
        )
        self.play(FadeIn(mrna_label), LaggedStart(*[FadeIn(base) for base in bases], lag_ratio=0.04))
        self.play(FadeIn(ribosome), FadeIn(ribosome_label), Create(codon_window))
        self.wait(0.4)

        previous_amino = None
        for index, (codon, amino_acid, color) in enumerate(
            zip(codons, amino_acids, amino_colors)
        ):
            codon_group = VGroup(*bases[index * 3 : index * 3 + 3])
            target_center = codon_group.get_center()
            target_window = SurroundingRectangle(codon_group, color=YELLOW, buff=0.08)

            if index > 0:
                self.play(
                    ribosome.animate.move_to(target_center).shift(DOWN * 0.1),
                    Transform(codon_window, target_window),
                    run_time=0.75,
                )

            codon_text = Text(codon, font_size=34, color=YELLOW)
            codon_text.next_to(codon_group, DOWN, buff=0.95)

            if amino_acid == "Stop":
                stop_marker = Text("translation stops", font_size=30, color=RED_C)
                stop_marker.next_to(codon_text, DOWN, buff=0.25)
                self.play(Indicate(codon_group, color=RED_C), FadeIn(codon_text))
                self.play(FadeIn(stop_marker), ribosome.animate.set_stroke(RED_C))
                self.wait(1.1)
                self.play(FadeOut(codon_text), FadeOut(stop_marker))
                break

            amino_circle = Circle(
                radius=0.34,
                stroke_color=color,
                fill_color=color,
                fill_opacity=0.85,
            )
            amino_label = Text(amino_acid, font_size=22, color=WHITE)
            amino = VGroup(amino_circle, amino_label)
            amino.move_to(chain_origin + RIGHT * index * amino_spacing)

            codon_to_amino = MathTex(
                codon,
                "\\rightarrow",
                amino_acid,
                font_size=36,
            )
            codon_to_amino[0].set_color(YELLOW)
            codon_to_amino[2].set_color(color)
            codon_to_amino.next_to(codon_group, DOWN, buff=0.95)

            self.play(Indicate(codon_group, color=YELLOW), FadeIn(codon_to_amino))
            self.play(TransformFromCopy(codon_group, amino), run_time=0.8)

            if previous_amino is not None:
                bond = Line(
                    previous_amino.get_right(),
                    amino.get_left(),
                    color=GRAY_A,
                    stroke_width=5,
                )
                peptide_chain.add(bond)
                self.play(Create(bond), run_time=0.25)

            peptide_chain.add(amino)
            self.play(FadeOut(codon_to_amino), run_time=0.3)
            previous_amino = amino

        complete = Text(
            "Each triplet codon specifies one amino acid",
            font_size=28,
            color=GRAY_A,
        )
        complete.next_to(peptide_chain, DOWN, buff=0.55)
        complete.set_x(0)
        self.play(FadeIn(protein_label), FadeIn(complete))
        self.play(peptide_chain.animate.scale(1.08), run_time=0.6)
        self.wait(1.2)

with capture_output() as captured:
    get_ipython().run_line_magic(
        "manim",
        "-qh -v WARNING --progress_bar None CodonToProtein",
    )

video = captured.outputs[-1]
video.data["text/html"] = (
    video.data["text/html"]
    .replace(" autoplay", "")
    .replace(" loop", "")
)
video.display()

Biological example: Plasmid fragments

The following shows another biological inspired animation - showcasing the modular arithmetic of calculating fragment sizes of a circular plasmid.

from manim import *
from IPython.utils.capture import capture_output

config.media_width = "100%"
config.media_embed = True

class CircularPlasmidFragments(Scene):
    def construct(self):
        self.camera.background_color = "#101820"

        plasmid_size = 2999
        sites = [
            ("EcoRI", 53, BLUE_C),
            ("DraI", 1168, GREEN_C),
            ("DraI", 1187, GREEN_C),
            ("DraI", 1879, GREEN_C),
        ]
        fragments = [
            ("EcoRI 53", "DraI 1168", 1115, BLUE_C),
            ("DraI 1168", "DraI 1187", 19, TEAL_C),
            ("DraI 1187", "DraI 1879", 692, PURPLE_C),
            ("DraI 1879", "EcoRI 53", 1173, ORANGE),
        ]

        radius = 2.05
        map_shift = LEFT * 2.35 + DOWN * 0.15

        def bp_angle(position):
            return PI / 2 - TAU * (position / plasmid_size)

        def bp_point(position, r=radius):
            angle = bp_angle(position)
            return np.array([r * np.cos(angle), r * np.sin(angle), 0])

        def clockwise_arc(start, end, color, stroke_width=12, r=radius + 0.12):
            distance = (end - start) % plasmid_size
            arc = Arc(
                radius=r,
                start_angle=bp_angle(start),
                angle=-TAU * distance / plasmid_size,
                color=color,
                stroke_width=stroke_width,
            )
            arc.shift(map_shift)
            return arc

        def clockwise_arc_distance(start, distance, color, stroke_width=12, r=radius + 0.12):
            arc = Arc(
                radius=r,
                start_angle=bp_angle(start),
                angle=-TAU * distance / plasmid_size,
                color=color,
                stroke_width=stroke_width,
            )
            arc.shift(map_shift)
            return arc

        intro_title = Text("Circular plasmid fragments", font_size=44, weight=BOLD)
        intro_subtitle = Text(
            "pSP64 is 2999 bp, so the map does not have a true end",
            font_size=26,
            color=GRAY_B,
        )
        intro_circle = Circle(radius=1.0, color=YELLOW_C, stroke_width=6)
        intro_cut_a = Line(UP * 0.8, UP * 1.25, color=BLUE_C, stroke_width=8)
        intro_cut_b = Line(DOWN * 0.8, DOWN * 1.25, color=GREEN_C, stroke_width=8)
        intro_map = VGroup(intro_circle, intro_cut_a, intro_cut_b)
        title_card = VGroup(intro_title, intro_subtitle, intro_map)
        title_card.arrange(DOWN, buff=0.42)
        self.add(title_card)
        self.wait(1.0)

        title = Text("EcoRI + DraI digest of pSP64", font_size=36, weight=BOLD)
        title.to_edge(UP)

        circle = Circle(radius=radius, color="#f0e98a", stroke_width=5)
        inner_circle = Circle(radius=radius - 0.08, color="#d5ce73", stroke_width=2)
        plasmid_label = VGroup(
            Text("pSP64", font_size=42, weight=BOLD),
            Text("2999 bp", font_size=27, color=GRAY_A),
        )
        plasmid_label.arrange(DOWN, buff=0.12)

        site_mobjects = VGroup()
        for enzyme, position, color in sites:
            point = bp_point(position)
            tick = Line(
                bp_point(position, radius - 0.18),
                bp_point(position, radius + 0.26),
                color=color,
                stroke_width=7,
            )
            dot = Dot(point, radius=0.06, color=color)
            label = Text(f"{enzyme} ({position})", font_size=20, color=color)
            label.move_to(bp_point(position, radius + 0.72))
            if position in [1168, 1187]:
                label.shift(RIGHT * 0.35 + DOWN * (0.22 if position == 1187 else -0.04))
            site_mobjects.add(VGroup(tick, dot, label))

        map_group = VGroup(circle, inner_circle, plasmid_label, site_mobjects)
        map_group.shift(map_shift)

        key = VGroup(
            Text("Read from one cut site", font_size=25, color=GRAY_A),
            Text("clockwise to the next cut site", font_size=25, color=GRAY_A),
        )
        key.arrange(DOWN, aligned_edge=LEFT, buff=0.16)
        key.move_to(RIGHT * 3.0 + UP * 1.2)

        self.play(
            ReplacementTransform(intro_title, title),
            FadeOut(intro_subtitle),
            FadeOut(intro_map),
            run_time=0.7,
        )
        self.play(Create(circle), Create(inner_circle), FadeIn(plasmid_label))
        self.play(LaggedStart(*[FadeIn(site) for site in site_mobjects], lag_ratio=0.12))
        self.play(FadeIn(key))
        self.wait(0.4)

        fragment_text = Text("", font_size=1)
        previous_arc = None

        examples = [
            (53, 1168, "1168 - 53 = 1115 bp", BLUE_C),
            (1168, 1187, "1187 - 1168 = 19 bp", TEAL_C),
            (1187, 1879, "1879 - 1187 = 692 bp", PURPLE_C),
        ]

        for start, end, calculation, color in examples:
            arc = clockwise_arc(start, end, color)
            text = Text(calculation, font_size=28, color=color)
            text.move_to(RIGHT * 3.0 + DOWN * 0.25)

            if previous_arc is None:
                self.play(Create(arc), FadeIn(text), run_time=0.8)
            else:
                self.play(ReplacementTransform(previous_arc, arc), ReplacementTransform(fragment_text, text))
            self.wait(0.8)
            previous_arc = arc
            fragment_text = text

        wrap_to_end = clockwise_arc_distance(1879, plasmid_size - 1879, ORANGE)
        wrap_from_start = clockwise_arc_distance(0, 53, YELLOW_D)
        wrap_arcs = VGroup(wrap_to_end, wrap_from_start)
        wrap_steps = VGroup(
            Text("The last fragment crosses the numbering break", font_size=24, color=GRAY_A),
            Text("2999 - 1879 = 1120 bp", font_size=27, color=ORANGE),
            Text("then continue from 1 to 53", font_size=24, color=YELLOW_D),
            Text("1120 + 53 = 1173 bp", font_size=31, color=ORANGE),
        )
        wrap_steps.arrange(DOWN, aligned_edge=LEFT, buff=0.22)
        wrap_steps.move_to(RIGHT * 3.05 + DOWN * 0.18)

        self.play(
            ReplacementTransform(previous_arc, wrap_to_end),
            FadeOut(fragment_text),
            FadeIn(wrap_steps[0]),
            FadeIn(wrap_steps[1]),
        )
        self.play(Create(wrap_from_start), FadeIn(wrap_steps[2]), FadeIn(wrap_steps[3]))
        self.wait(1.3)

        fragment_bars = VGroup()
        max_fragment = max(fragment[2] for fragment in fragments)
        for _left_label, _right_label, size, color in fragments:
            width = 3.35 * size / max_fragment
            bar = Rectangle(
                width=width,
                height=0.28,
                fill_color=color,
                fill_opacity=0.9,
                stroke_width=0,
            )
            label = Text(f"{size} bp", font_size=22, color=WHITE)
            label.next_to(bar, RIGHT, buff=0.16)
            fragment_bars.add(VGroup(bar, label))

        fragment_bars.arrange(DOWN, aligned_edge=RIGHT, buff=0.22)
        fragment_heading = Text("Fragments in order around the circle", font_size=22, color=GRAY_A)
        fragment_summary = VGroup(fragment_heading, fragment_bars)
        fragment_summary.arrange(DOWN, aligned_edge=LEFT, buff=0.28)
        fragment_summary.move_to(RIGHT * 2.65 + DOWN * 0.1)
        final_note = Text(
            "The fragment sizes add back to 2999 bp",
            font_size=25,
            color=GRAY_A,
        )
        final_note.next_to(fragment_summary, DOWN, buff=0.35)

        self.play(
            FadeOut(key),
            FadeOut(wrap_steps),
            FadeOut(wrap_arcs),
            FadeIn(fragment_summary),
            FadeIn(final_note),
        )
        self.wait(1.2)


with capture_output() as captured:
    get_ipython().run_line_magic(
        "manim",
        "-qh -v WARNING --progress_bar None CircularPlasmidFragments",
    )

video = captured.outputs[-1]
video.data["text/html"] = (
    video.data["text/html"]
    .replace(" autoplay", "")
    .replace(" loop", "")
)
video.display()

Technical details

To include manim animations the pixi environemnt needs to have manim registered as a dependency, if it isn’t then it can be added with

pixi add manim

Additionally we need to make sure a LaTeX installation is available, this can be done using this task

[tasks.install-tinytex]
cmd = "quarto install tinytex --no-prompt && export PATH=\"$HOME/.TinyTeX/bin/x86_64-linux:$PATH\" && tlmgr install dvisvgm standalone preview"
description = "Install TinyTeX and Manim TeX dependencies for CI"

Which can be added to pixi.toml and run using pixi r install-tinytex.

Then if the manim source code should be part of the document we need to enable the manim Jupyter interface, this is done by having a cell like

#| include: false
%load_ext manim

Where the include: false-line tells Quarto to not display either the cell or the output of the cell when rendering but the code in the cell is run. Then code-blocks like those shown for the examples above can be inserted and manim animations will be rendered and shown.

Alternatively, the animations can be scripted and the produced videos can be included using the Quarto shortcode

{{< video path/to/video.mp4 >}}

If a project includes many animations this is probably preferable to keep rendering time down.

CI

If the animations are rendered as part of the CI the workflow should ensure that the LaTeX environemnt is installed, this can be done by adding the following to the .yml-file (e.g. publish.yml).

- name: Install TinyTeX
run: |
    pixi run install-tinytex
    echo "$HOME/.TinyTeX/bin/x86_64-linux" >> "$GITHUB_PATH"