3Blue1Brown Videos Source Code

repository·master·Indexed 25 days ago

https://github.com/3b1b/videos

Source code used to generate mathematical explanatory videos for the 3Blue1Brown YouTube channel. The repository primarily utilizes the manimgl library for animation and includes environment installation guides, Sublime Text workflow configurations, and specialized Python classes for visualizing mathematical concepts such as Fourier transforms, Cumulant Generating Functions, and the Central Limit Theorem.

Tokens
9.8K
Snippets
51
Records
71
Agent score
95%

What's inside 3b1b-videos

  1. Run a video scene with manimgl

    master

    To run a specific scene from a Python file, use the manimgl command.

    If you are running a file from a subdirectory and do not want to modify your system path, you may need to append the parent directories to sys.path at the top of your Python file:

    import sys
    sys.path.append(".")
    sys.path.append("..")
    sys.path.append("../../")

    Then, execute the file using one of the following commands:

    • To run the default scene in the file: manimgl <file_name>.py
    • To run a specific scene class within the file: manimgl <file_name>.py <SceneName>
    manimgl e_field.py
    # OR
    manimgl e_field.py WavesIn3D
  2. Install the video generation environment

    master

    To run the video samples in this repository, follow these steps:

    1. Install manimgl from source: The latest published version may not be up to date. Install it directly from the 3b1b/manim repository.
    2. Install LaTeX: Ensure a LaTeX distribution is installed on your system. For Ubuntu, use:
      sudo apt install texlive
      sudo apt install texlive-latex-extra
      sudo apt install texlive-fonts-extra
      sudo apt install texlive-science
    3. Clone this repository:
      git clone git@github.com:3b1b/videos.git
      cd videos
    git clone git@github.com:3b1b/videos.git
    cd videos
  3. Configure Sublime Text for Manim workflow

    master

    To replicate the 3Blue1Brown workflow in Sublime Text, follow these steps:

    1. Install the Terminus package via Package Control.
    2. Copy the files from the sublime_custom_commands directory of this repository into your Sublime Packages/User/ directory.
    3. Add custom keybindings to your Sublime settings (Sublime Text -> Settings -> Keybindings) to trigger the commands.

    Example keybindings:

    {
        "keys": ["shift+super+r"], "command": "manim_run_scene" 
    },
    {
        "keys": ["super+r"], "command": "manim_checkpoint_paste" 
    },
    {
        "keys": ["super+alt+r"], "command": "manim_recorded_checkpoint_paste" 
    },
    {
        "keys": ["super+ctrl+r"], "command": "manim_skipped_checkpoint_paste" 
    },
    {
        "keys": ["super+e"], "command": "manim_exit" 
    },
    {
        "keys": ["super+option+/"], "command": "comment_fold"
    }
    {
        "keys": ["shift+super+r"], "command": "manim_run_scene" },
        { "keys": ["super+r"], "command": "manim_checkpoint_paste" },
        { "keys": ["super+alt+r"], "command": "manim_recorded_checkpoint_paste" },
        { "keys": ["super+ctrl+r"], "command": "manim_skipped_checkpoint_paste" },
        { "keys": ["super+e"], "command": "manim_exit" },
        { "keys": ["super+option+/"], "command": "comment_fold"}
  4. Use interactive mode and checkpoint_paste()

    master

    You can interact with a scene using an iPython terminal by running manimgl with the -se flag and a line number:

    manimgl (file name) (scene name) -se (line_number)

    Once in interactive mode, use the checkpoint_paste() function to execute code from your clipboard:

    • checkpoint_paste(): Runs the code in the clipboard. If the code starts with a comment, the system saves the scene state at that comment. Subsequent calls to code starting with the same comment will revert to that saved state before running.
    • checkpoint_paste(skip): Runs the copied code without animations (all run times set to 0).
    • checkpoint_paste(record): Runs the animations in the copied code and renders them to a file.
  5. Create a sum plot for unscaled distributions

    master

    Use get_sum_plot to create a plot of the sum of $n$ variables without standardization. This is useful for showing how the sum distribution shifts and spreads as $n$ increases.

    Parameters:

    • dist: The base distribution.
    • n: Number of variables.
    • top_plot: A reference plot (used to match width/scaling).
    • x_range: Tuple (min, max) for the x-axis.
    • y_range: Tuple (min, max, step) for the y-axis.
    • x_num_range: Tuple (start, stop, step) for x-axis tick marks.
    • max_width: Maximum width of the plot.
    sum_plot = self.get_sum_plot(
        dist, 
        N, 
        top_plot, 
        x_range=(0, 500, 10),
        y_range=(0, 0.05, 0.1),
        x_num_range=(0, 600, 100),
        max_width=14
    )
  6. Generate LaTeX for reciprocal sums

    master

    The get_sum(n) method (used within ShowReciprocalSums and its subclasses) generates a LaTeX expression representing the sum of reciprocal odd numbers $\sum_{k=1}^{n} \frac{1}{2k+1}$. It handles truncation using \dots if the number of terms exceeds max_shown_parts.

    def get_sum(self, n):
        tex_parts = []
        tally = 0
        msp = self.max_shown_parts
        for k in range(1, n + 1):
            new_parts = [f"1 / {2 * k + 1}", "+"]
            if n > msp:
                if k < msp - 1 or k == n:
                    tex_parts.extend(new_parts)
                elif k == msp - 1:
                    tex_parts.extend([R"\cdots", "+"])
            else:
                tex_parts.extend(new_parts)
            tally += 1 / (2 * k + 1)
        tex_parts[-1] = "="
        tex_parts.append(R"{:.06f}\dots".format(tally))
        return OldTex(*tex_parts)
  7. Annotate a plot with mean and standard deviation

    master

    Use get_mu_sigma_annotations to generate visual indicators (lines, arrows, and labels) for the mean ($\mu$) and standard deviation ($\sigma$) on a given plot.

    Parameters:

    • plot: The plot object containing axes and bars.
    • mu_tex: LaTeX string for the mean label (e.g., R"\mu").
    • sigma_tex: LaTeX string for the standard deviation label (e.g., R"\sigma").
    • min_height: Minimum height for the mean line.
    • x_min: The minimum x-value for coordinate calculations.
    mean_label, sd_label = self.get_mu_sigma_annotations(
        sum_plot, 
        "350", 
        "17.1", 
        min_height=1.0, 
        x_min=n
    )
  8. Create a variable display with a slider

    master

    Use get_variable_display(name, color, value_range) to create an interactive UI component consisting of a LaTeX equation, a vertical number line, and a slider. It returns a tuple containing the VGroup (the UI component) and a ValueTracker used to control the value.

    • name: The LaTeX string for the variable (e.g., R"\mu").
    • color: The color to apply to the variable in the equation and the slider.
    • value_range: A tuple (min, max) defining the slider's limits.
  9. Create axes for statistical plots

    master

    Use get_axes(x_range, y_range) to generate a NumberPlane configured for statistical visualizations. The axes are automatically shifted to the bottom of the frame and include formatted numbers on both axes.

    • x_range: A tuple (min, max) for the x-axis.
    • y_range: A tuple (min, max, step) for the y-axis.

    Returns a NumberPlane object.

    axes = self.get_axes(
        x_range=(-4, 4),
        y_range=(-1.0, 2.0, 1.0),
    )
  10. Mathematical helper functions for sinc and rect functions

    master

    This module provides mathematical helper functions used for generating graphs and animations related to the Borwein video.

    • sinc(x): Computes the normalized sinc function $\frac{\sin(x)}{x}$ using np.sinc(x / PI).
    • multi_sinc(x, n): Computes the product of sinc functions $\prod_{k=0}^{n-1} \text{sinc}(\frac{x}{2k+1})$.
    • rect_func(x): Returns a rectangular function that is $1.0$ for $-0.5 < x < 0.5$ and $0.0$ otherwise.
    def sinc(x):
        return np.sinc(x / PI)
    
    def multi_sinc(x, n):
        return np.prod([sinc(x / (2 * k + 1)) for k in range(n)})
    
    def rect_func(x):
        result = np.zeros_like(x)
        result[(-0.5 < x) & (x < 0.5)] = 1.0
        return result