# -*- coding: utf-8 -*-
"""图 5-6　项目总工期的概率分布正态分布（教材第 92 页）
照原图绘制：钟形曲线 + 7 条虚线（μ-3σ … μ+3σ）+ 三段双向箭头（68.26%／95.46%／99.73%）。
"""
import os
import sys

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, save, NAV, ACC, INK

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图5-6-项目总工期的概率分布正态分布.png')

MU, SIG = 50.0, 9.0          # μ 与 σ（图内相对单位）
PEAK = 92.0                  # 峰值高度
BASE = 10.0                  # 横轴高度
FLAT = 1.55                  # 曲线相对 σ 的展宽系数（原图为示意钟形，画得比真正态宽）


def curve_y(x):
    return BASE + (PEAK - BASE) * np.exp(-0.5 * ((x - MU) / (FLAT * SIG)) ** 2)


def main():
    setup()
    fig, ax = canvas(11.0, 6.6, xlim=(0, 100), ylim=(-8, 102))

    xs = np.linspace(2, 98, 600)
    ax.plot(xs, curve_y(xs), color=NAV, lw=2.4, zorder=3)

    # 横轴
    ax.plot([2, 98], [BASE, BASE], color=INK, lw=0.9, zorder=2)

    ticks = [(-3, r'$\mu-3\sigma$'), (-2, r'$\mu-2\sigma$'), (-1, r'$\mu-\sigma$'),
             (0, r'$\mu$'), (1, r'$\mu+\sigma$'), (2, r'$\mu+2\sigma$'), (3, r'$\mu+3\sigma$')]
    for k, lab in ticks:
        x = MU + k * SIG
        ax.plot([x, x], [BASE - 1.0, BASE], color=INK, lw=0.9, zorder=2)
        ax.plot([x, x], [BASE, curve_y(x)], color='#4a5568', lw=1.0, ls=(0, (4, 3)), zorder=1)
        ax.text(x, BASE - 1.6, lab, ha='center', va='top', color=INK, fontsize=11)

    # 三段双向箭头
    bars = [(1, 66.0, '68.26%'), (2, 36.0, '95.46%'), (3, 16.0, '99.73%')]
    for k, y, lab in bars:
        x1, x2 = MU - k * SIG, MU + k * SIG
        ax.annotate('', xy=(x2, y), xytext=(x1, y),
                    arrowprops=dict(arrowstyle='<|-|>', color=ACC, lw=1.5,
                                    shrinkA=0, shrinkB=0, mutation_scale=13))
        ax.text(MU, y + 2.2, lab, ha='center', va='bottom', color=NAV, fontsize=12,
                bbox=dict(facecolor='white', edgecolor='none', pad=1.2), zorder=5)

    ax.text(50, -2.0, '图 5-6　项目总工期的概率分布正态分布', ha='center', va='center',
            color='#4a5568', fontsize=11)
    save(fig, OUT)


if __name__ == '__main__':
    main()
