"""
=============================================================================
Stanford CS144 · 第 8 讲 · 03_circuit_vs_packet.py —— 电路交换和分组交换
=============================================================================

【这个脚本要回答的问题】（讲义 §1）
    电话网用了一百年，为什么 Internet 不用它的办法？反过来，电路交换有什么是分组交换做不到的？

【三部分】
    A：短消息：建立电路的代价。
    B：电话网怎样算容量：Erlang B 公式（公式 + 模拟）。
    C：一条电话线和一条 Internet 路径：时延的稳定性和链路的利用率。

【运行方式】
    python3 03_circuit_vs_packet.py      # 约 1 秒，结果每次相同
"""

import heapq
import random

import course_path
course_path.use("lecture01")

from console import print_header, print_table, observations, si_time, si_rate, si_bytes, pct
from hopsim import Hop, StoreForwardPath
from netsim import Simulator


def packet_time(size, n_hops, rate, prop_total):
    """
    用模拟器算：一条消息切成分组，走完路径要多久（路径空闲）。

    【参数】size：消息字节数；n_hops：跳数；rate：每跳速率；prop_total：总传播时延
    【返回】最后一个比特到达的时刻（秒）
    【边界】每个分组最多 1460 字节载荷 + 40 字节头部。消息比 1460 短时，分组也短。
    """
    sim = Simulator()
    hops = [Hop(rate, prop_total / n_hops) for _ in range(n_hops)]
    last = []
    path = StoreForwardPath(sim, hops, on_deliver=lambda r: last.append(r.delivered_at))
    remaining = size
    while remaining > 0:
        chunk = min(1460, remaining)
        path.send(chunk + 40)
        remaining -= chunk
    sim.run()
    return max(last)


def part_a_setup_cost():
    """
    发一条消息要多久：电路（先建立）vs 分组（直接发）。

    【返回】dict：消息大小 → (电路用时, 分组用时)
    【思路】
        电路：建立时信令要走一个来回，每一跳还要处理（选线路、预留时隙，这里假设每跳 10 ms）。之后独占一条固定速率的电路。
        分组：直接发，每跳存储转发。这里假设路径不忙（路径很忙时分组交换要排队，见 Part C）。
    """
    print_header("Part A · 发一条消息要多久：10 跳的路径，单程传播 20 ms，每跳 1 Mbit/s")
    n_hops = 10
    prop = 0.020
    setup_per_hop = 0.010
    rate = 1e6
    rows = []
    out = {}
    for size in (100, 1000, 10_000, 100_000, 1_000_000, 10_000_000):
        setup = 2 * prop + n_hops * setup_per_hop
        circuit = setup + size * 8 / rate + prop
        packet = packet_time(size, n_hops, rate, prop)
        out[size] = (circuit, packet)
        rows.append([si_bytes(size), si_time(setup), si_time(circuit), si_time(packet), "分组" if packet < circuit else "电路"])
    print_table(["消息大小", "建立电路", "电路的总时间", "分组的总时间", "更快的是"], rows)
    print("\n  消息很短时，建立电路的时间比传输本身长得多。计算机之间的流量绝大部分正是这种短消息：")
    print("  原课讲义的说法是，建立和拆除电路代价太高，打电话时可以接受，只想发一小段数据就没有道理了。")
    print("  消息很长时，电路的优势才显现：没有分组头部（这里 1000 字节要多发 40 字节），也没有逐跳存储转发。")
    return out


def erlang_b(servers, load):
    """
    Erlang B 公式：线路数和负载一定时，一个新呼叫被拒绝的概率。

    【参数】servers：线路数；load：负载（Erlang，等于平均同时呼叫数）
    【返回】概率
    【思路】用递推公式算，比直接算阶乘稳定：B(0)=1；B(n)=a·B(n-1)/(n+a·B(n-1))。
        这是 A. K. Erlang 1917 年为哥本哈根电话公司推导的，比 Internet 早了半个多世纪。
    """
    b = 1.0
    for n in range(1, servers + 1):
        b = load * b / (n + load * b)
    return b


def simulate_blocking(servers, load, calls=200000, seed=1):
    """
    模拟：泊松到达的呼叫，指数分布的通话时长（平均 1），占满就拒绝。

    【参数】servers：线路数；load：负载；calls：呼叫总数；seed：随机种子
    【返回】被拒绝的比例
    【Python 小知识】heapq 是小顶堆，这里放每条占用线路的结束时刻，堆顶就是最早结束的。
    """
    rng = random.Random(seed)
    t = 0.0
    busy = []
    blocked = 0
    for _ in range(calls):
        t += rng.expovariate(load)
        while busy and busy[0] <= t:
            heapq.heappop(busy)
        if len(busy) >= servers:
            blocked += 1
        else:
            heapq.heappush(busy, t + rng.expovariate(1.0))
    return blocked / calls


def part_b_erlang():
    """
    电话网怎样算容量。

    【返回】dict：(线路数, 负载) → (公式, 模拟)
    """
    print_header("Part B · 电话网的工程：线路数和拒绝率（Erlang B，1917 年）")
    rows = []
    out = {}
    for servers, load in ((10, 5.0), (10, 8.0), (10, 10.0), (100, 80.0), (100, 90.0), (1000, 950.0)):
        formula = erlang_b(servers, load)
        simulated = simulate_blocking(servers, load, calls=400000)
        out[(servers, load)] = (formula, simulated)
        rows.append([servers, load, pct(load / servers), pct(formula, 2), pct(simulated, 2)])
    print_table(["线路数", "负载（平均同时呼叫数）", "平均利用率", "拒绝率（公式）", "拒绝率（模拟）"], rows)
    print("\n  同样是 80%～95% 的利用率，线路越多，拒绝率越低：这就是大规模带来的统计复用。")
    print("  电路交换遇到拥塞的方式是**拒绝新呼叫**（忙音）：已经接通的不受影响。")
    print("  分组交换遇到拥塞的方式是**所有人都变慢**。这是两种根本不同的合约（第 1 讲）。")
    return out


def part_c_bursty(seed=1):
    """
    计算机的流量是突发的：用电路（每个用户独占一份）和用分组（共享）比较。

    【参数】seed：随机种子
    【返回】dict：实验结果
    【思路】20 个用户，每人偶尔发一阵数据（平均 50 ms，1 Mbit/s 的峰值），大部分时间安静，平均只用 5%。
        电路：每人固定一条 1 Mbit/s 的电路（总共要 20 Mbit/s）。
        分组：共享一条 4 Mbit/s 的链路（只要 1/5 的容量）。
    """
    print_header("Part C · 突发的流量：20 个用户，平均只用峰值的 5%")
    rng = random.Random(seed)
    n_users = 20
    peak = 1e6
    on_mean = 0.050
    off_mean = 0.950
    duration = 200.0
    bursts = []
    for user in range(n_users):
        t = rng.expovariate(1 / off_mean)
        while t < duration:
            length = rng.expovariate(1 / on_mean)
            bursts.append((t, user, length))
            t += length + rng.expovariate(1 / off_mean)
    bursts.sort()
    total_bits = sum(length * peak for _t, _u, length in bursts)

    # 电路：每个突发在自己的电路上发，时延就是它自己的长度，互不影响
    circuit_capacity = n_users * peak
    circuit_utilization = total_bits / (circuit_capacity * duration)

    # 分组：所有突发切成 1500 字节的分组，共享一条链路
    rows = []
    out = dict(circuit_utilization=circuit_utilization)
    rows.append(["每人一条电路", si_rate(circuit_capacity), pct(circuit_utilization), "0 s", "0 s"])
    for capacity in (2e6, 3e6, 4e6, 8e6):
        sim = Simulator(seed=seed)
        extra = []

        def done(record):
            ideal = 1500 * 8 / peak            # 这个分组按峰值速率本来要花的时间
            extra.append(max(0.0, record.delivered_at - record.tag - ideal))

        path = StoreForwardPath(sim, [Hop(capacity, 0.0)], on_deliver=done)
        for t, _user, length in bursts:
            n_packets = max(1, int(length * peak / (1500 * 8)))
            for i in range(n_packets):
                send_at = t + i * 1500 * 8 / peak
                sim.at(send_at, path.send, 1500, send_at)
        sim.run()
        extra.sort()
        utilization = total_bits / (capacity * duration)
        p50 = extra[len(extra) // 2]
        p99 = extra[int(len(extra) * 0.99)]
        out[capacity] = (utilization, p50, p99)
        rows.append([f"共享一条链路", si_rate(capacity), pct(utilization), si_time(p50), si_time(p99)])
    print_table(["做法", "总容量", "链路利用率", "额外时延（中位数）", "额外时延（99%）"], rows)
    print("\n  每人一条电路时，95% 的容量都闲着，但没有任何额外的时延。")
    print("  共享时容量省了很多，代价是偶尔要排队。这就是统计复用（第 1 讲的实验，第 9 讲会给出更好的模型）。")
    print("  计算机的流量越突发，分组交换的优势越大。电话的流量很平稳，所以电路很合适。")
    return out


def main():
    """运行各部分，打印结论。"""
    a = part_a_setup_cost()
    b = part_b_erlang()
    c = part_c_bursty()

    print_header("结论")
    observations([
        f"100 字节的消息：电路 {si_time(a[100][0])}，分组 {si_time(a[100][1])}。10 MB 的消息：电路 {si_time(a[10_000_000][0])}，分组 {si_time(a[10_000_000][1])}。",
        f"Erlang B：10 条线路、负载 8 时拒绝率 {pct(b[(10, 8.0)][0], 2)}（模拟 {pct(b[(10, 8.0)][1], 2)}）；100 条线路、负载 80 时 {pct(b[(100, 80.0)][0], 2)}。同样的利用率，规模越大越好。",
        f"突发流量：每人一条电路的利用率只有 {pct(c['circuit_utilization'])}；共享 4 Mbit/s 时利用率 {pct(c[4e6][0])}，99% 的分组额外时延 {si_time(c[4e6][2])}。",
    ])


if __name__ == "__main__":
    main()
