from manim import *
import numpy as np
from numpy import array
run_time = 1
data = [[1, 2], [3, 4]]
def dot(pos, **kwargs):
    return Dot(pos, **kwargs)
import sympy as sp
import numpy as np
class RiemannToIntegral(Scene):
    def construct(self):
        # ========== SymPy 符号积分部分 ==========
        x_sym = sp.Symbol('x')
        f_sym = x_sym**2                         # 被积函数：f(x) = x²
        f = sp.lambdify(x_sym, f_sym, "numpy")   # 转为 NumPy 函数
        a, b = 0, 2                               # 积分区间 [0, 2]
        # SymPy 自动求精确积分和原函数
        exact_integral = sp.integrate(f_sym, (x_sym, a, b))  # ∫₀² x² dx = 8/3
        F_sym = sp.integrate(f_sym, x_sym)                   # 原函数 F(x) = x³/3
        # ========== Manim 坐标系与曲线 ==========
        axes = Axes(
            x_range=[-0.5, 2.5, 0.5], y_range=[-0.5, 5, 1],
            x_length=6, y_length=5, axis_config={"color": BLUE}
        )
        curve = axes.plot(f, x_range=[a, b], color=YELLOW, stroke_width=3)
        # ========== 黎曼和矩形生成函数 ==========
        def get_riemann_rects(n):
            """生成 n 个右端点黎曼和矩形"""
            dx = (b - a) / n                      # 每个矩形的宽度
            rects = VGroup()
            total_area = 0
            for i in range(1, n + 1):
                xi = a + i * dx                   # 右端点横坐标
                yi = f(xi)                        # 矩形高度 f(xi)
                area_i = yi * dx                  # 单个矩形面积
                total_area += area_i
                rect = Rectangle(
                    width=axes.x_length * dx / (b - a),       # 缩放到屏幕宽度
                    height=axes.y_length * yi / 5,            # 缩放到屏幕高度
                    fill_opacity=0.3, fill_color=BLUE,
                    stroke_color=BLUE_B, stroke_width=0.2,
                ).move_to(axes.c2p(xi - dx/2, yi/2))          # 左下角定位
                rects.add(rect)
            return rects, total_area
        # ========== 动画流程：n 递增，矩形逼近曲线下面积 ==========
        self.play(Create(axes), Create(curve))
        current_rects = None
        for n in [2, 4, 8, 16, 32]:
            new_rects, area_sum = get_riemann_rects(n)
            if current_rects is None:
                self.play(Create(new_rects))
            else:
                self.play(ReplacementTransform(current_rects, new_rects))
            current_rects = new_rects
            self.wait(0.3)
        # 展示精确积分值（SymPy 计算结果）
        exact_val = float(exact_integral)
        result_label = MathTex(
            f"\\int_{{{a}}}^{{{b}}} x^2 \\,dx = \\frac{{8}}{{3}} \\approx {exact_val:.4f}",
            color=GREEN, font_size=30
        ).to_edge(DOWN)
        self.play(Write(result_label))
        self.wait(2)