"""Tests on Lab 03's printed results (01_sample_size.py, 02_comparisons.py, 03_cost.py; planning math,
no real AI system): the margin table, the cost of +-0.4%, the cases a 2-point comparison needs on
different and on shared cases, and the cost of 10 changes.
Run: pytest test_size_practice.py"""
from size_practice import cost, cost_over_changes, discordance, margin_at, n_for_margin, n_paired, n_unpaired


def test_margin_table():
    # at about 90% right: +-3, +-2, +-1, +-0.4 points
    assert [n_for_margin(0.9, m) for m in (0.03, 0.02, 0.01, 0.004)] == [385, 865, 3458, 21609]
    # the safe guess, 50%: the most cases for any margin
    assert [n_for_margin(0.5, m) for m in (0.03, 0.02, 0.01, 0.004)] == [1068, 2401, 9604, 60023]
    # 5x thinner margin, 25x the cases
    assert round(n_for_margin(0.9, 0.004) / n_for_margin(0.9, 0.02)) == 25
    # 99% confidence instead of 95%: 1.7x, not 25x
    assert n_for_margin(0.9, 0.02, confidence=0.99) == 1493


def test_a_wrong_guess():
    # planned for 90% (865 cases), the system really scores 70%: +-3.1 points, not +-2
    assert round(margin_at(0.7, 865) * 100, 1) == 3.1
    assert round(margin_at(0.9, 865) * 100, 1) == 2.0


def test_what_04_costs():
    ask = cost(n_for_margin(0.9, 0.004))
    assert round(ask["total_usd"]) == 21739
    assert round(ask["labeling_hours"]) == 540
    assert round(ask["runs"] * 0.006) == 130  # the model + judge share
    one = cost(n_for_margin(0.9, 0.01))
    assert round(one["total_usd"]) == 3479 and round(one["labeling_hours"]) == 86
    assert round(ask["total_usd"] / one["total_usd"]) == 6  # option B: 6x cheaper
    # two separate +-1 point scores can't be told apart under about 1.4 points
    assert round(2 ** 0.5 * margin_at(0.9, 3458) * 100, 1) == 1.4


def test_comparison_on_different_cases():
    assert n_unpaired(0.80, 0.82) == 6039  # per version: 12,078 labeled cases in all
    assert 2 * n_unpaired(0.80, 0.81) == 49282  # half the gain, about 4x the cases


def test_paired_comparison():
    a_only, b_only = discordance(0.80, 0.82, 0.6)
    assert round((a_only + b_only) * 100, 1) == 12.4  # about 1 case in 8 disagrees
    assert n_paired(a_only, b_only) == 2423
    assert [n_paired(*discordance(0.80, 0.82, r)) for r in (0.3, 0.8)] == [4233, 1217]
    # option C's paired check, at about 90% right, catching a 2-point drop
    assert n_paired(*discordance(0.90, 0.88, 0.6)) == 1549
    try:
        discordance(0.80, 0.90, 0.8)
    except ValueError:
        pass
    else:
        raise AssertionError("80% vs 90% can't be as alike as rho = 0.8: raise ValueError")


def test_labels_you_keep():
    unpaired, paired = cost_over_changes(0.80, 0.02, 0.6, 10)
    assert round(unpaired) == 66828
    assert round(paired) == 2583
    first_u, first_p = cost_over_changes(0.80, 0.02, 0.6, 1)
    assert round(first_u) == 12150 and round(first_p) == 2452
    assert round(paired - cost_over_changes(0.80, 0.02, 0.6, 9)[1]) == 15  # each later paired check
