見出し画像

理系のためのManim入門 *随時更新*

[初投稿日  2023年9月30日]
最終更新日: 2025-08-24

そもそも Manim って何?

ChatGPT 先生に聞いてみましょう。

Manim(Mathematical Animation Engine)は、数学や物理を視覚的に表現するためのPythonのアニメーションエンジンです。Manimは、3Blue1Brownとして知られるYouTuberであるGrant Sandersonによって開発され、彼の数学の教育動画で幅広く使用されています。

ChatGPTの回答

つまり Python でコードを書いたら、数式やグラフをアニメーションとして動画化してくれるのが Manim です。次のような動画が作れます。

3B1B先生, 偉大すぎる. さすが世界一の数学系Youtuber(当社調べ).

私もmanimを利用して, いくつかYoutube動画を作りました. 


Manim を書くのに必要なもの

Manim を利用するうえで必要なのは、

  1. やる気

  2. Python の知識

  3. TeX 記法の知識

  4. コンピュータ視覚関連の知識

とくに最低限の Python と TeX の知識が必要です。

Manim のインストール方法


Manim CE と Manim GL

Manim は誰でも無料で利用できます。今回は ManimCE を使います。

Manimには2つのバージョンがあり ManimCE と ManimGL です。配布されているのは ManimCE の方で開発が進んでいる段階ですので仕様変更が多いです。

ManimGLのほうは 3b1b氏本人が利用していると思われるバージョンです。ManimGLはレンダリングが速く、リアルタイムにアニメーションを作成できるものらしいです。

ManimCE と ManimGL には互換性はありません。

Manim CE のホームページ: https://www.manim.community/ 


Manim を動かすのに必要なソフト

  • LaTeX (数式のレンダリングするやつ)

  • Python (プログラム書くやつ)

  • FFmpeg (動画エンコードするやつ)

  • Manim CE (本体)

  • VScode + Manim Sideview (編集が便利になるやつ)


まず LaTeX, Python, FFmpeg をそれぞれインストールしておきましょう。

Metachick-2021様の記事が参考になります。


Python のインストール

普通にPythonをインストールしましょう。わからない場合は他の方の記事を参照してください。

さらに Python でパッケージをインストールできるよう pip を使えるようにしておきます。


Python のバージョン

Python の最新バージョンは Python 3.12 です(当記事投稿時点)。普通にManim を動かすうえではPython 3.12で大丈夫です。古すぎる Python 3.7以前などは動かない可能性があります。

(余談ですが、後述のphysicsプラグインのインストールのために、Python 3.10にダウングレードした経緯があります。そのため最初からPython 3.10をインストールする場合もあります。)

windows 11 環境変数の設定(パス登録)

Windowsマーク > 設定(歯車)を開く > システム > バージョン情報 > システムの詳細設定 > 環境変数(N) … 

これでパス( Path )を登録します。

Manim のインストール

以下をコマンドプロンプトで実行してダウンロードします。

pip install manim

ここでエラーが出る場合は Python と setuptools, pip のインストールを再確認してください。自分の場合は, 

pip install setuptools

を実行してから pip install manim に成功しました。

Manim のパス設定

Pythonの入っているフォルダで
Python312\Lib\site-packages\manim
の位置にmanimが入っているので環境変数のPathに追加しておきます。


コマンドプロンプトでmanim -versionを実行してバージョンが表示されればOKです。

manim -version


画像
manim インストール確認画面



Manim で Hello World を画像表示する

VScodeを開きます。 

適当なディレクトリで main.py を作成して次のコードを書きます。

from manim import *

class HelloWorld(Scene):
    def construct(self):
        text = Tex("Hello World !")
        self.add(text)

緑色のボタンを押して

画像
緑のボタン

HelloWorldを選択すると

画像
クラス名の選択
画像
Preview

無事に Hello World ! できました。

Manim Sideview の設定

manim をレンダリングするとデフォルトだと右側にプレビューが見えます。このプレビュー画面の設定をします. 

VScodeの歯車 > 設定 から manim と検索します。
私は以下の項目のチェックを外しました。

  • Checkered Background

  • Run On Save



Manim アニメーションの基本


Python ファイルの一番上に

from manim import *

を書きます。次にクラスを定義します。

from manim import *

class MyAnimation(Scene):

今回はクラス名をMyAnimation にしました。()の中身であるSceneについては、描画したいことによって変わります。

次にコンストラクタを定義します。

from manim import *

class MyAnimation(Scene):
    def construct(self):


次に描きたいものを定義します。

from manim import *

class MyAnimation(Scene):
    def construct(self):
        circle = Circle(radius=1.0)

このように定義したものをMObjectといいます。今回は circle という名前のMObject を 半径1の円として定義しました。

最後に描画したいMObjectを表示させます。

from manim import *

class MyAnimation(Scene):
    def construct(self):
        circle = Circle(radius=1.0)

        self.add(circle)

これで次のような円を描画できます。この時点ではまだ動画になっておらず単なる画像です

画像

少し右に動かしてみましょう。 self.play () という関数に動かしたいMobject と動かし方をいれることでアニメーションが作れます

from manim import *

class MyAnimation(Scene):
    def construct(self):
        circle = Circle(radius=1.0)

        self.add(circle)
        self.play(circle.animate.shift(RIGHT))
        self.wait()

今回は circle というMObjectを右に動かすアニメーション animate.shift(RIGHT) を再生しました。

用語

MObjects : Math Object の意味。 円や四角、関数グラフやカメラも含む。



公式ドキュメントを読もう

まずは公式ドキュメントをよく読みましょう。大抵のことは公式ドキュメントをよく読むことで解決します。

ManimCE のドキュメント: https://docs.manim.community/en/stable/index.html 

ドキュメントはチュートリアルも兼ねています。Manim CEのドキュメントにあるサンプルコードを色々試してみましょう。


Discord に参加しよう

Manim CEの開発者コミュニティのDiscord が存在します。英語さえできればHelp forumで質問が可能です。


Manim Tips

Manim のノウハウを乱雑に書いていきます。

クラス名

from manim import *

class Myscene(Scene):

この場合 Myscene がクラス名である。クラスごとにレンダリングします。
manim ファイル名 クラス名 

manim main.py Myscene で実行することができます。

生成した画像や動画は pyのファイル名のフォルダに保存されます。
media > image > ファイル名 

レンダリングするクラスを変える(VScode)

緑色のボタンを押すとクラス名の選択をして、レンダリングされます。

しかしVScodeを閉じるまで、同じクラスのレンダリングしかされないので、
Previewの右下の↩ボタンでクラスを変更します。

画像
右下の↩ボタンでクラス変更

Mobject Galleryのテンプレート (VScode)

拡張機能 Manim Sideview の機能に Mobject Gallery があります。
Manimのテンプレート機能です。


Ctrl +Shift + P を押して Manim: Open Mobject Gallery を選択すると開けます。

画像

利用したい Mobject をクリックすると ソースコードにペーストされます。


表示して消す

ShowCreationThenFadeOut

曲がった矢印

from manim import *

class CurvedArrowExample(Scene):
    def construct(self):
        curvedArrow = CurvedArrow(start_point=np.array([-3.5,0,0]) , end_point=np.array([3.5,0,0]))

        self.play(ShowCreationThenFadeOut(curvedArrow))
        self.wait(2)

https://youtu.be/5CjamCi1ld8



画像
CurvedArrow


Mobject を回転する・角度をつける


45度角度をつけるには .rotate(PI / 4) をつける。

Mobject: 楕円

from manim import *

class EllipseExample(Scene):
    def construct(self):
        ellipse_1 = Ellipse(width=3.0, height=3.0, color = WHITE , fill_opacity=0.1)
        ellipse_2 = Ellipse(width=3.0, height=1.0, color=RED_C)
        
        self.play(Create(ellipse_1))
        self.play(Create(ellipse_2))
        self.wait(1)

2dだけど3dに見えなくもない。


Mobject 多角形

頂点の配列を読み込んで多角形を作る

from manim import *

class PolygonExample(Scene):
    def construct(self):
        position_list = [
            [1, 1, 0], 
            [0, 1, 0], 
            [1, 0, 0], 
            [-1, 0, 0], 
        ]
        Polygon_01 = Polygon(*position_list, color = PURE_GREEN, fill_opacity=0.1).rotate(PI / 4).scale(2)
        
        self.play(Create(Polygon_01))
        self.wait(1)
        


2次元平面の軸 (Axes)と 罫線 (NumberPlane), 関数 y=x+2


from manim import *

class Myscene(Scene):
    def construct(self):
        npl = NumberPlane(
            x_range=[-15, 15, 1],  
            y_range=[-15, 15, 1],  
            axis_config={"color": WHITE},  
        )
        
        axes = Axes(
            x_range=[-20, 20, 1],  
            y_range=[-20, 20, 1],  
            axis_config={"color": WHITE},
            y_length=npl.get_height(),
            x_length=npl.get_width(),
        )

        axes.add_coordinates()
        self.play(FadeIn(npl), run_time=1.0)
        self.play(Create(axes))
        self.wait(1)

        f = axes.plot(lambda x: x+2, color=LIGHT_PINK)

        self.play(Create(f))
        self.wait(1)


グラフを描写

軸と3つの関数を描写する。

from manim import *

class Myscene(Scene):
    CONFIG = {
        "x_min": -4,
        "x_max": 4,
        "y_min": -2,
        "y_max": 2,
        "graph_origin": ORIGIN,
        "function_color": WHITE,
        "axes_color": BLUE
    }

    def construct(self):
        #Make  graph
        axes = Axes(axis_config={'tip_shape': StealthTip})
        func_graph =  axes.plot(lambda x: 1 / (1 + np.exp(-x)), color=WHITE)
        graph_title = Tex("sigmoid function")
        graph_title.scale(1.5)
        graph_title.to_corner(UP + LEFT)

        func_graph_2 =  axes.plot(lambda x: np.tanh(x), color=PURE_GREEN)
        graph_title_2 = Tex("tanh function")
        graph_title_2.scale(1.5)
        graph_title_2.to_corner(UP + LEFT)

        func_graph_3 =  axes.plot(lambda x: np.maximum(0, x), color=YELLOW_C)
        graph_title_3 = Tex("ReLU function")
        graph_title_3.scale(1.5)
        graph_title_3.to_corner(UP + LEFT)


        #Display  graph
        self.add(axes)
        self.play(Create(func_graph))
        self.add(graph_title)
        self.wait(1)
        self.play(FadeOut(graph_title))
        self.play(Create(func_graph_2))
        self.add(graph_title_2)
        self.wait(1)
        self.play(FadeOut(graph_title_2))
        self.play(Create(func_graph_3))
        self.add(graph_title_3)
        self.wait(2)


色コード



画像
Manim 色コード


YELLOW_C が鮮やかで見やすい。

PURE_GREEN は映画マトリックスのような色

コードブロック

manimで画面にプログラミングコードを表示させる方法

画像ファイル(png)を表示

画像を取り込みます。

from manim import *

class Images(Scene):
    def construct(self):
        img = ImageMobject('path_to_image_file.png')
        img.scale(2)  # Resize to be twice as big
        img.shift(1 * UP)  # Move the image

        self.add(img)  # Display the image
        self.play(img.animate.shift(RIGHT)) # Move the image to right

画像ファイルのキャッシュが残っていてなかなか切り替わらないことがあります。

背景色を変える

背面に単色の長方形を置いて背景色を変更します。

from manim import *

class WhiteBackground(Scene):
    def construct(self):
        BackgroundColor = Rectangle(width=15.0, height=9.0, color=WHITE).set_fill(WHITE,1)
        self.add(BackgroundColor)


Manim でエラーが出るときの対処法

古い関数を使用しない

Manimでは、頻繁に記法の変更が行われています。

例えば、"ShowCreation"は"Create"に置き換えられました。

エラーが発生した場合は、古い記法を使用していないかどうかを確認しましょう。数年前のブログ記事などには、古い記法で書かれている可能性があります。

この記事の記法も、古い記法になっている場合があるので注意してください。

参考にしているブログやWebページの投稿日時に注意しましょう。

Manimのバージョンを確認する

  • 古いバージョンのManimコードを使っている。

  • ManimCEでManimGLの記法を使っている。

  • Manim のプラグインのバージョンが異なる。

使っているOSによって仕様が異なる場合もあります。


インデントのミス

Pythonのインデントのミスでレンダリング出来ない場合があります。特に下の部分

 def construct(self):

記法ミス

細かい大文字・小文字のミスに注意しましょう。例えば色を指定するときに、大文字で YELLOW_C と書くべき所を Yellow_C などにしてしまうとエラーが出ます。


プラグイン  manim-physics


Manim で物理シミュレーションをするためのプラグインです。重力やオブジェクトの衝突の演算ができます。


from manim import *

from manim_physics import *
# use a SpaceScene to utilize all specific rigid-mechanics methods
class TwoObjectsFalling(SpaceScene):
    def construct(self):
        circle = Circle().shift(UP)
        circle.set_fill(RED, 1)
        circle.shift(DOWN + RIGHT)

        rect = Square().shift(UP)
        rect.rotate(PI / 4)
        rect.set_fill(YELLOW_A, 1)
        rect.shift(UP * 2)
        rect.scale(0.5)

        ground = Line([-4, -3.5, 0], [4, -3.5, 0])
        wall1 = Line([-4, -3.5, 0], [-4, 3.5, 0])
        wall2 = Line([4, -3.5, 0], [4, 3.5, 0])
        walls = VGroup(ground, wall1, wall2)
        self.add(walls)

        self.play(
            DrawBorderThenFill(circle),
            DrawBorderThenFill(rect),
        )
        self.make_rigid_body(rect, circle)  # Mobjects will move with gravity
        self.make_static_body(walls)  # Mobjects will stay in place
        self.wait(5)
        # during wait time, the circle and rect would move according to the simulate updater


Manim Physics の公式ドキュメント

Manim Physics のパッケージの説明サイト


manim-physics のインストール

pip install manim-physics

でプラグインをインストールできます。

私はインストールがうまくできなかったため、Pythonのバージョンを3.10にしました。以下の手順でインストールできました。

  • 公式サイトから Python 3.10 をインストールする.

  • python -V
    でバージョンを確認する

  • python -m ensurepip
    で pip を使えるようにする

  • python - pip install --upgrade pip 
    で pipを最新のものにする

  • pip install manim
    でmanimをインストール

  • pip install manim-physics
    で manim-physics をインストール


3b1bの動画のソースを読む


3b1b 氏は ManimGL を使用しています. 

ManimGLのリポジトリ: https://github.com/3b1b/manim 
ManimGL のドキュメント: https://3b1b.github.io/manim/ 

GitHub で 3b1bの動画に出てきたアニメーションのソースコードが閲覧できます. 

3b1bのソースコード: https://github.com/3b1b/videos 


参考



いいなと思ったら応援しよう!

ピックアップされています

エレン先生、数学を語る

  • 199本

コメント

3
KKさん
KKさん

質問してよろしいでしょうか?Pythonはすでにインストール済で、Manimもインストールしてあるのですが、何かさらに別のものをインストールしないといけないようです。https://www.ffmpeg.org/download.html←このサイトにあるアプリをダウンロードしないといけないとかなんとか…ダウンロードはしたのですが解凍と、インストールのやり方がわからなくて困っています。Windows11を使っています。お知恵を拝借願えないでしょうか?

はとまつ
はとまつ

> 元・神童のKKさん へ

基本的にコチラのサイトと同じ手順となります。
https://jp.videoproc.com/edit-convert/how-to-download-and-install-ffmpeg.htm

https://www.ffmpeg.org/download.html で windows を選択
② Windows builds by BtbN をクリック。
③ ffmpeg-master-latest-win64-gpl-shared.zip をクリックしてダウンロードと解凍する。
④ ffmpeg-master-latest-win64-gpl-sharedというフォルダをコピーして別の場所に移す。
僕の場合はローカルディスク C:\Program Filesにペーストしました。
⑤ binフォルダのパス (C:\Program Files\ffmpeg-master-latest-win64-gpl-shared\bin) を登録する。
パスの登録は記事内でも触れています。

もし他に質問があればXの方でDMを頂けたら可能な限り回答します。

KKさん
KKさん

先ほどVS code でアニメーション再生できました。公式サイト(https://github.com/BtbN/FFmpeg-Builds/releases)から FFmpeg をダウンロードする際に50種類も並んでいて、私が当初選んだのはアニメーション対応でないものだったようです。データ容量の大きいものを選びなおしたら、今度はうまくいきました。

ほかの皆さんはここで戸惑わなかったのですか?私は猛烈に頭を抱えてしまいました。

コメントするには、 ログイン または 会員登録 をお願いします。
理系のためのManim入門 *随時更新*|はとまつ
word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word

mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1