"""silab/engine.py：迷你自动求导引擎
第 3 课写出来，第 4 课起加上 relu，之后各课都从这里 import。
"""


class Value:
    def __init__(self, data, parents=(), op=""):
        self.data = data          # 前向：这个数的值
        self.grad = 0.0           # 反向：损失对它的导数，先记为 0
        self.parents = parents    # 它是由哪几个数算出来的
        self.op = op              # 用什么运算算出来的
        self._backward = lambda: None   # 把自己的 grad 传给 parents 的规则

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other), "+")
        def _backward():
            self.grad += 1.0 * out.grad          # ∂(a+b)/∂a = 1
            other.grad += 1.0 * out.grad         # ∂(a+b)/∂b = 1
        out._backward = _backward
        return out

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other), "×")
        def _backward():
            self.grad += other.data * out.grad   # ∂(ab)/∂a = b
            other.grad += self.data * out.grad   # ∂(ab)/∂b = a
        out._backward = _backward
        return out

    def __pow__(self, k):                        # k 是普通数字
        out = Value(self.data ** k, (self,), f"^{k}")
        def _backward():
            self.grad += k * self.data ** (k - 1) * out.grad   # ∂(a^k)/∂a = k·a^(k-1)
        out._backward = _backward
        return out

    def relu(self):                              # 第 4 课新增：折一下
        out = Value(self.data if self.data > 0 else 0.0, (self,), "relu")
        def _backward():
            self.grad += (1.0 if self.data > 0 else 0.0) * out.grad   # 开着传 1，关着传 0
        out._backward = _backward
        return out

    def __neg__(self):
        return self * -1

    def __sub__(self, other):
        return self + (-other if isinstance(other, Value) else Value(-other))

    def __radd__(self, other):
        return self + other

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, k):                    # 只需要“除以一个普通数字”
        return self * (1.0 / k)

    def backward(self):
        order, seen = [], set()
        def visit(v):                            # 拓扑排序：先排好父节点，再排自己
            if v not in seen:
                seen.add(v)
                for p in v.parents:
                    visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0                          # ∂L/∂L = 1
        for v in reversed(order):
            v._backward()
