# -*- coding: utf-8 -*-
"""Read, Chapter 18 / Appendix D (V.A, V.D, V.E): the arithmetic behind the headline figures.
No data needed: the inputs are the case tables the chapter states. Standard library only (Python 3.8+).

Fisher one-tailed p for a 2x2 table (sign hold, sign fail, non-sign hold, non-sign fail) = the probability,
with margins fixed, that no hold falls in a sign case: C(non-sign, holds) / C(N, holds)."""
from math import comb

def fisher_none_in_sign(sh, sf, nh, nf):
    assert sh == 0
    holds, nonsign, N = nh, nh + nf, sh + sf + nh + nf
    return comb(nonsign, holds) / comb(N, holds)

def binom_tail(k, n, p):
    return sum(comb(n, i) * p**i * (1 - p)**(n - i) for i in range(k, n + 1))

def show(label, p): print(f'{label:<62} p = {p:.3g}   (1 in {1/p:,.1f})' if 1/p < 20 else f'{label:<62} p = {p:.3g}   (1 in {1/p:,.0f})')

print('Ledger tables (Appendix D V.D; Chapter 18 "Whether the alignment is design or coincidence")')
show('letter-group, 13 cases (0,9,4,0)', fisher_none_in_sign(0, 9, 4, 0))
show('letter-group + 3 alif-free openings, 16 cases (0,11,4,1)', fisher_none_in_sign(0, 11, 4, 1))
show('letter-group, yaa pair as holds, 15 cases (0,9,6,0)', fisher_none_in_sign(0, 9, 6, 0))
show('letter-group + alif-free, pair as holds, 18 cases (0,11,6,1)', fisher_none_in_sign(0, 11, 6, 1))
show('formula-only, 13 cases (0,3,4,6)', fisher_none_in_sign(0, 3, 4, 6))
show('formula-only, pair as holds (0,3,6,6)', fisher_none_in_sign(0, 3, 6, 6))
show('formula-only + 2 sign controls (0,5,4,6)', fisher_none_in_sign(0, 5, 4, 6))
show('formula-only + controls, pair as holds (0,5,6,6)', fisher_none_in_sign(0, 5, 6, 6))
print()
print('Frozen frame (Appendix D III.c, V.E): 14 openings, rate 1/19')
show('five of fourteen hold (pending yaa pair counted)', binom_tail(5, 14, 1/19))
show('three of fourteen hold (counted strictly)', binom_tail(3, 14, 1/19))
show('alignment, strict: sign 0/6 vs non-sign 3/8 (letter-group)', fisher_none_in_sign(0, 6, 3, 5))
show('alignment, strict: sign 0/5 vs non-sign 3/9 (formula-only)', fisher_none_in_sign(0, 5, 3, 6))
show('alignment, pair counted: sign 0/6 vs non-sign 5/3 (letter-group)', fisher_none_in_sign(0, 6, 5, 3))
show('alignment, pair counted: sign 0/5 vs non-sign 5/4 (formula-only)', fisher_none_in_sign(0, 5, 5, 4))
print()
print('Historical frame, V.A trials (calibrated per-trial probabilities as stated in Appendix D V.A)')
P = {'T-alpha Qaf-50': 0.044, 'T-beta Ayn-Sin-Qaf': 0.053, 'T-gamma Ha-Mim': 0.053, 'T-delta Sad as recited': 0.053}
a, b, g, d = P.values()
show('three hard-tier trials (headline)', a * b * g)
show('three hard-tier trials, flat 1/19', (1/19)**3)
show('four trials incl. Sad as recited (sensitivity)', a * b * g * d)
show('four trials, flat 1/19', (1/19)**4)
show('five trials with the pending yaa pair, flat 1/19', (1/19)**5)
