사랑하는 사람에게

2023. 12. 22. 16:54Ray 수학

https://youtube.com/shorts/GDwlkotFxn0

 

- YouTube

 

www.youtube.com

 

 

사랑하는 사람에게.mp4
19.40MB

 

 

 

from manim import *
from colour import Color

class h1(Scene):
    def construct(self):
        scale_factor = 0.1

        heart_curve = ParametricFunction(
            lambda t: np.array([
                scale_factor * 16 * np.sin(t)**3,
                scale_factor * (13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)),
                0
            ]), color="#FF0000", t_range=[0, 2 * PI]
        )

        formula_text = MathTex(
            r"&x = 16 \sin^3(t)", 
            r"\\ y = 13 \cos(t) - &5 \cos(2t) - 2 \cos(3t) - \cos(4t)",
        ).scale(0.5).to_edge(DOWN)

        heart_fill = heart_curve.copy()
        heart_fill.set_fill("#FF0000", opacity=0.4)

        self.play(Create(heart_curve), Write(formula_text),run_time=3)
        self.play(FadeIn(heart_fill), run_time=1)
        self.wait(1)

 

 

from manim import *


class h2(Scene):
    def construct(self):
        heart_curve = ImplicitFunction(
            lambda x, y: (x**2 + (y + 0.5) ** 2 - 1) ** 3 - x**2 * (y + 0.5) ** 3,
            x_range=[-2, 2],
            y_range=[-1.5, 1.5],
            color="#FF0000",
        ).scale(1.2)

        heart_fill = heart_curve.copy()
        heart_fill.set_fill("#FF0000", opacity=0.4)

        heart_equation = (
            MathTex(r"(x^2 + y^2 -1)^3 - x^2 y^3 = 0").scale(0.5).to_edge(DOWN)
        )

        self.play(Create(heart_curve), Write(heart_equation), run_time=3)
        self.play(FadeIn(heart_fill), run_time=1)
        self.wait(1)

 

from manim import *


class h3(Scene):
    def construct(self):
        heart_curve = ParametricFunction(
            lambda theta: np.array(
                [
                    (
                        2
                        - 2 * np.sin(theta)
                        + np.sin(theta) * np.sqrt(np.abs(np.cos(theta)))
                    )
                    * np.cos(theta),
                    (
                        2
                        - 2 * np.sin(theta)
                        + np.sin(theta) * np.sqrt(np.abs(np.cos(theta)))
                    )
                    * np.sin(theta)
                    + 1,
                    0,
                ]
            ),
            t_range=[0, 2 * PI],
            color="#FF0000",
        ).scale(0.7)

        heart_fill = heart_curve.copy()
        heart_fill.set_fill("#FF0000", opacity=0.4)

        heart_equation = (
            MathTex(
                r"r = 2 - 2\sin(\theta) + \sin(\theta) \sqrt{\left| \cos(\theta) \right|}"
            )
            .scale(0.5)
            .to_edge(DOWN)
        )

        # 곡선 그리기 및 내부 채우기
        self.play(Create(heart_curve), Write(heart_equation), run_time=3)
        self.play(FadeIn(heart_fill), run_time=1)
        self.wait(2)

 

from manim import *


class h4(Scene):
    def construct(self):
        def custom_function(x, y):
            return x**2 + ((y + 0.5) - np.sqrt(abs(x))) ** 2 - 2

        heart_curve = ImplicitFunction(
            custom_function, x_range=[-2, 2], y_range=[-2, 2], color="#FF0000"
        ).scale(1)

        heart_fill = heart_curve.copy()
        heart_fill.set_fill("#FF0000", opacity=0.5)

        heart_equation = (
            MathTex(r"x^2 + (y - \sqrt{|x|})^2 = 1").scale(0.5).to_edge(DOWN)
        )

        # 곡선 그리기 및 내부 채우기
        self.play(Create(heart_curve), Write(heart_equation), run_time=3)
        self.play(FadeIn(heart_fill), run_time=1)
        self.wait(2)

 

import numpy as np
from manim import *

class h5(Scene):
    def construct(self):
        def custom_function(x):
            complex_value = np.lib.scimath.sqrt(np.cos(x)) * np.cos(200 * x) + (np.lib.scimath.sqrt(abs(x)) - np.pi/4) * (4 - x**2)**0.01
            real_part = np.real(complex_value)
            return np.array([x, real_part, 0])

        t_range = [-1.6, 1.6]
        
        graph = ParametricFunction(lambda x: custom_function(x), t_range=t_range, color="#FF0000").scale(1.5)

        graph_equation = MathTex(
            r"f(x) = \text{Re}\{\sqrt{\cos(x)}\cos(200x) + \left(\sqrt{|x|}-\frac{\pi}{4}\right)(4-x^2)^{0.01}\}"
        ).scale(0.4).to_edge(DOWN)

        self.play(Create(graph), Write(graph_equation), run_time=5)
        self.wait(2)

 

import numpy as np
from manim import *


class h6(Scene):
    def construct(self):
        heart_eq = (
            ImplicitFunction(
                lambda x, y: x**2
                + (
                    (y + 2)
                    - 2 * (x**2 + np.abs(x) - 6) / (3 * (x**2 + np.abs(x) + 2))
                )
                ** 2
                - 36,
                x_range=[-10, 10],
                y_range=[-10, 10],
                color="#FF0000",
            )
            .scale(0.25)
            .move_to(UP * 0.01)
        )

        heart_fill = heart_eq.copy()
        heart_fill.set_fill("#FF0000", opacity=0.4)

        heart_equation = (
            MathTex(
                r"x^2 + \left[ y - \frac{2(x^2 + \vert x \vert - 6)}{3(x^2 + \vert x \vert + 2)} \right]^2 = 36"
            )
            .scale(0.4)
            .to_edge(DOWN)
        )

        self.play(Create(heart_eq), Write(heart_equation), run_time=3)
        self.play(FadeIn(heart_fill), run_time=1)
        self.wait(2)

 

import numpy as np
from skimage import measure
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d.art3d import Line3DCollection

# 메시 해상도 설정
n = 100
x = np.linspace(-n / 20, n / 20, n)
y = np.linspace(-n / 20, n / 20, n)
z = np.linspace(-n / 20, n / 20, n)
X, Y, Z = np.meshgrid(x, y, z)


# 하트 모양 함수 정의
def f_heart(x, y, z):
    F = (
        (2 * x**2 + y**2 + z**2 - 1) ** 3
        - 1 / 10 * x**2 * z**3
        - y**2 * z**3
    )
    return F


# 메시 값 계산
vol = f_heart(X, Y, Z)
verts, faces, normals, values = measure.marching_cubes(vol, 0, spacing=(0.1, 0.1, 0.1))

# 3D 그래픽 설정
fig = plt.figure(figsize=(16, 9))
ax = fig.add_subplot(111, projection="3d")
ax.set_axis_off()

# 배경 색상 설정
fig.patch.set_facecolor("black")
ax.patch.set_facecolor("black")

# 부드러운 색상 그라데이션과 조명 효과 적용
surf = ax.plot_trisurf(
    verts[:, 0],
    verts[:, 1],
    faces,
    verts[:, 2],
    color="#FF0000",
    alpha=0,
    antialiased=True,
)

# 선 컬렉션 생성 및 선 두께 조정
lines = [np.array([verts[i], verts[j], verts[k]]) for i, j, k in faces]
line_collection = Line3DCollection(lines, colors="#FF0000", alpha=0.0, linewidths=1)
ax.add_collection3d(line_collection)

# 하트의 중심을 계산
heart_center = np.mean(verts, axis=0)


def update(frame):
    ax.view_init(20, 80)
    if frame < 30:  # 0.5초 동안 빈 화면
        return
    elif 30 <= frame < 150:
        num_lines = int(len(lines) * (frame - 30) / 120)
        line_collection.set_segments(lines[:num_lines])
        line_collection.set_alpha(0.3)
    elif 150 <= frame < 240:
        alpha = (frame - 150) / 90
        line_collection.set_alpha(1 - alpha)
        surf.set_alpha(alpha)
    elif frame >= 240:  # 2초 동안 회전
        ax.view_init(20, (frame + 80) // 4)

    ax.set_xlim(heart_center[0] - 1, heart_center[0] + 1)
    ax.set_ylim(heart_center[1] - 1, heart_center[1] + 1)
    ax.set_zlim(heart_center[2] - 1, heart_center[2] + 1)


ani = FuncAnimation(fig, update, frames=np.arange(0, 640, 1), interval=17)

ani.save("heart_animation.mp4", writer="ffmpeg", dpi=300)

plt.close()

 

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation

# Define the parameters and the function for the 3D plot
u = np.linspace(-np.pi, np.pi, 200)
v = np.linspace(-1, 1, 200)
u, v = np.meshgrid(u, v)
x = np.cos(u) * (4 * np.sqrt(1 - v**2) * np.sin(np.abs(u)) ** np.abs(u))
y = v
z = np.sin(u) * (4 * np.sqrt(1 - v**2) * np.sin(np.abs(u)) ** np.abs(u))

# Create the plot
fig = plt.figure(figsize=(16, 9))
ax = fig.add_subplot(111, projection="3d")


# Function to update the plot
def update(frame):
    ax.clear()
    ax.set_axis_off()
    fig.patch.set_facecolor("black")
    ax.patch.set_facecolor("black")

    if frame < 60:
        step = int(200 * frame / 60)
        ax.plot_wireframe(
            x[:, :step], y[:, :step], z[:, :step], color="red", linewidth=0.5
        )
        ax.view_init(azim=-60, elev=0, roll=-90)
    elif frame < 80:
        line_alpha = max(0, 1 - (frame - 60) / 20)
        surface_alpha = min(0.5, (frame - 60) / 20)
        ax.plot_wireframe(x, y, z, color="red", alpha=line_alpha)
        ax.plot_surface(x, y, z, color="red", alpha=surface_alpha)
        ax.view_init(azim=-60, elev=0, roll=-90)
    else:
        ax.plot_surface(x, y, z, color="red")
        azim = -60 + (80 - frame)
        ax.view_init(azim=azim, elev=0, roll=-90)

    return (fig,)


# Create an animation
ani = FuncAnimation(fig, update, frames=np.arange(0, 200, 1), interval=50)

ani.save("h8.mp4", writer="ffmpeg", dpi=300, savefig_kwargs={"facecolor": "black"})

plt.close()

 

import numpy as np
from manim import *


class h9(Scene):
    def construct(self):
        # 정의된 파라메트릭 함수
        def heart_curve(t):
            x = t
            y = (
                0.64 * np.sqrt(np.abs(x)) - 0.8 + 1.2 ** np.abs(x) * np.cos(200 * x)
            ) * np.sqrt(np.cos(x))
            return np.array([x, y, 0])

        # 파라메트릭 함수의 범위 설정 및 초기 선 두께 설정
        heart_path = ParametricFunction(
            heart_curve,
            t_range=[-np.pi / 2, np.pi / 2],
            color="#FF0000",
            stroke_width=1,
        )

        # 그래프 및 방정식 표시
        heart_equation = (
            MathTex(
                r"y = (0.64 \sqrt{\vert x \vert} - 0.8 + 1.2^{\vert x \vert} \cos(200x)) \sqrt{\cos(x)}"
            )
            .scale(0.4)
            .to_edge(DOWN)
        )

        # 그래프 생성 및 방정식 작성
        self.play(Create(heart_path), Write(heart_equation), run_time=4)

        # 선 두께 변경
        self.play(heart_path.animate.set_stroke(width=3), run_time=2)

        self.wait(2)

 

import numpy as np
from manim import *


class h10(Scene):
    def construct(self):
        # 계수를 위한 ValueTracker 초기화 (시작 계수는 0)
        coefficient_tracker = ValueTracker(0)

        # 계수를 사용한 함수 정의
        def get_graph(coef):
            f = (
                lambda x: np.sqrt(np.maximum(np.cos(x), 0)) * np.cos(coef * x)
                + 0.5 * np.sqrt(np.abs(x))
                - 1
            )
            return FunctionGraph(
                f,
                x_range=[-1.6, 1.6],
                color="#FF0000",
                stroke_width=2,
            ).scale(1)

        # 그래프 방정식 표시
        graph_equation = (
            MathTex(r"f(x) = \sqrt{\cos(x)} \cos(80x) + 0.5 \sqrt{\vert x \vert}")
            .scale(0.4)
            .to_edge(DOWN)
        )

        # 초기 그래프 (계수 0) 생성
        graph = get_graph(0)

        # 선 그리기 및 함수 방정식 작성 (동시에 실행)
        self.play(Create(graph), Write(graph_equation), run_time=1.5)

        # 계수 변경 (0에서 80으로)
        self.play(
            coefficient_tracker.animate.set_value(80),
            UpdateFromFunc(
                graph, lambda m: m.become(get_graph(coefficient_tracker.get_value()))
            ),
            run_time=3,
            rate_func=linear,
        )

        # 함수 방정식 작성 완료 대기
        self.wait(3)