"""
Numerical illustration of
  "Where Profits Are Owned: The Cross-Country Incidence of the Global Minimum Tax"
  (GMT_ITAX.tex, Section 4 "Numerical results" and Appendix B)

Reproduces Tables 1-3, Figure 1 (reaction functions, Appendix B) and every
number quoted in Section 4, in Appendix B (group ratio, slopes of the reaction
functions) and in the footnote on the number of havens.

Primitives
  activity   pi11 = pi12 = pi22 = 1, pi21 = 0
  ownership  sigma11 = 1 - s, sigma21 = s, sigma22 = 1, sigma12 = 0   (s = 0 baseline)
  cost       s(m) = gamma m^2 / 2, gamma = 1
  utility    U(C,G) = C + b G - c G^2 - theta C G,  b = 1.6, c = 0.3
             (theta = 0: Assumption 2; theta != 0: Appendix B, Figure 1)
  exogenous income y_i = 0

Two solvers are used and cross-checked:
  * interior FOC  MRS_i = Omega_i / (1 + eps_i)   (Proposition 1), quasi-linear case;
  * global best response by direct maximisation of U_i over tau_i, handling the
    kink at tau_i = tauM and corners in m_i, iterated to a Nash equilibrium.

Requires numpy, scipy and matplotlib.  Run:  python gmt_ownership_numerics.py
Writes fig_reaction.pdf in the working directory.
"""

import numpy as np
from scipy.optimize import brentq, minimize_scalar

b, c, gamma = 1.6, 0.3, 1.0
Ghat = b / (2 * c)
PI = np.array([[1.0, 1.0],     # MNE 1 produces in 1 and 2
               [0.0, 1.0]])    # MNE 2 produces in 2 only
TOL = 5e-5                      # tolerance for checks against 4-decimal tables


# ----------------------------------------------------------------------------
# Primitives
# ----------------------------------------------------------------------------
def matrices(s=0.0):
    """D_ik = sum_j sigma_ij pi_jk ; B_k = sum_i pi_ik ; Omega_i = D_ii / B_i.

    D_ik is the profit produced in k that residents of i own: the object through
    which ownership enters every result.  Omega_i < 1 means part of the domestic
    base is owned by foreigners, so part of the domestic tax is exported.
    s > 0 lets residents of the host country (2) own a share of the
    headquarters multinational (1): this is the departure from the
    domestic-ownership case."""
    sigma = np.array([[1.0 - s, 0.0],
                      [s,       1.0]])
    D = sigma @ PI
    B = PI.sum(axis=0)
    return D, B, np.diag(D) / B


def shifted(tau, tauM):
    """Lemma 1: m_j = min{max{(tau_j - tauM)/gamma, 0}, 1}."""
    return np.clip((np.asarray(tau, float) - tauM) / gamma, 0.0, 1.0)


def allocation(tau, tauM, D, B, y=0.0):
    tau = np.asarray(tau, float)
    m = shifted(tau, tauM)
    phi = 1 - tau * (1 - m) - tauM * m - gamma * m**2 / 2
    C = D @ phi + y
    G = tau * B * (1 - m)
    return m, phi, C, G


def utility(C, G, theta=0.0):
    return C + b * G - c * G**2 - theta * C * G


def welfare(i, tau, tauM, D, B, theta=0.0, y=0.0):
    _, _, C, G = allocation(tau, tauM, D, B, y)
    return utility(C[i], G[i], theta)


def mrs(C, G, theta=0.0):
    return (b - 2 * c * G - theta * C) / (1 - theta * G)


# ----------------------------------------------------------------------------
# Solver 1: interior FOC, quasi-linear case (theta = 0)
# ----------------------------------------------------------------------------
def foc_gap(t, tauM, Bi, Om):
    m = (t - tauM) / gamma
    eps = -t / (gamma * (1 - m))
    return (b - 2 * c * t * Bi * (1 - m)) - Om / (1 + eps)


def interior_rate(tauM, Bi, Om):
    """Root of the FOC on the interior domain tauM < tau < tauM + gamma, 1+eps > 0."""
    grid = np.linspace(tauM + 1e-9, tauM + gamma * 0.999, 20001)
    ok = [t for t in grid if gamma * (1 - (t - tauM) / gamma) > t]
    vals = [foc_gap(t, tauM, Bi, Om) for t in ok]
    for k in range(1, len(ok)):
        if vals[k - 1] * vals[k] < 0:
            return brentq(foc_gap, ok[k - 1], ok[k], args=(tauM, Bi, Om), xtol=1e-14)
    raise RuntimeError("no interior root")


def equilibrium(tauM, s=0.0):
    """Nash equilibrium of the two non-havens at a given floor.
    a_i (foreign exposure of resident ownership) is the ratio between the
    shifted profit residents own anywhere and the part produced at home; it is
    the sufficient statistic for the sign of the direct trade-off."""
    D, B, Om = matrices(s)
    tau = np.array([interior_rate(tauM, B[i], Om[i]) for i in range(2)])
    m, phi, C, G = allocation(tau, tauM, D, B)
    W = utility(C, G)
    a = np.array([(D[i] @ m) / (D[i, i] * m[i]) for i in range(2)])
    return dict(tau=tau, m=m, C=C, G=G, W=W, a=a, D=D, B=B, Om=Om,
                MRS=b - 2 * c * G)


def dtau_closed_form(e):
    """Lemma 4, closed form of d tau_i / d tauM."""
    tau, m, B, M = e["tau"], e["m"], e["B"], e["MRS"]
    num = tau * (b - 2 * c * gamma * B * (1 - m)**2)
    den = 2 * c * B * (1 - m) * (gamma * (1 - m) - tau)**2 + M * (gamma * (1 - m) + tau)
    return num / den


def decomposition(tauM, s=0.0):
    """Proposition 2 with U_C = 1: mechanical, revenue, externality, total.

    mech  : loss of resident owners on the profit they own that is shifted,
            wherever it is produced (follows ownership);
    rev   : revenue recovered on the domestic base, whoever owns it
            (follows production);
    ext   : ownership externality, the welfare cost of the other non-haven's
            rate response on the profit residents own there.  The envelope
            theorem removes the own-rate response, not this one."""
    e = equilibrium(tauM, s)
    D, B, m, tau, M = e["D"], e["B"], e["m"], e["tau"], e["MRS"]
    dt = dtau_closed_form(e)
    rows = []
    for i in range(2):
        j = 1 - i
        mech = -(D[i] @ m)
        rev = M[i] * tau[i] * B[i] / gamma
        ext = -D[i, j] * (1 - m[j]) * dt[j]
        rows.append(dict(mech=mech, rev=rev, ext=ext, tot=mech + rev + ext))
    return rows, e, dt


# ----------------------------------------------------------------------------
# Solver 2: global best responses (any theta, kink and corners included)
# ----------------------------------------------------------------------------
def best_response(i, tau_other, tauM, D, B, theta=0.0, tmax=1.5):
    """Global best response of country i.  With theta = 0 (quasi-linear
    utility) it does not depend on tau_other: the reported bases of the two
    non-havens do not interact, so the reaction functions are flat.  With
    theta != 0 the other rate changes the income of residents who own profit
    abroad and, through the demand for the public good, the chosen rate."""
    def negW(t):
        tau = [t, tau_other] if i == 0 else [tau_other, t]
        return -welfare(i, tau, tauM, D, B, theta)

    grid = np.linspace(0.0, tmax, 6001)
    vals = np.array([negW(t) for t in grid])
    k = int(np.argmin(vals))
    lo, hi = grid[max(k - 1, 0)], grid[min(k + 1, len(grid) - 1)]
    cands = [grid[k]]
    # refine on each smooth piece: below the floor, and between floor and full shifting
    breaks = sorted({lo, hi, *[x for x in (tauM, tauM + gamma) if lo < x < hi]})
    for a_, b_ in zip(breaks[:-1], breaks[1:]):
        r = minimize_scalar(negW, bounds=(a_, b_), method="bounded",
                            options={"xatol": 1e-14})
        cands += [r.x, a_, b_]
    best = min(cands, key=negW)
    # polish an interior optimum on the first-order condition F_i = 0
    if abs(best - tauM) > 1e-6 and tauM < best < tauM + gamma:
        def Fi(t):
            tau = [t, tau_other] if i == 0 else [tau_other, t]
            return F(i, tau, tauM, D, B, theta)
        a_, b_ = max(best - 1e-3, tauM + 1e-12), best + 1e-3
        if Fi(a_) * Fi(b_) < 0:
            best = brentq(Fi, a_, b_, xtol=1e-15)
    return best


def nash(tauM, s=0.0, theta=(0.0, 0.0), start=(0.3, 0.4)):
    D, B, _ = matrices(s)
    tau = np.array(start, float)
    for _ in range(1000):
        new = np.array([best_response(0, tau[1], tauM, D, B, theta[0]),
                        best_response(1, tau[0], tauM, D, B, theta[1])])
        if np.max(np.abs(new - tau)) < 1e-12:
            return new
        tau = new
    raise RuntimeError("best-response iteration did not converge")


# ----------------------------------------------------------------------------
# Figure 1 objects: F_i = dU_i/dtau_i and its derivatives
# ----------------------------------------------------------------------------
def F(i, tau, tauM, D, B, theta):
    """F_i = dU_i/dtau_i = U_C c_i + U_G g_i on the interior domain (analytic)."""
    tau = np.asarray(tau, float)
    m, _, C, G = allocation(tau, tauM, D, B)
    UC = 1 - theta * G[i]
    UG = b - 2 * c * G[i] - theta * C[i]
    ci = -D[i, i] * (1 - m[i])
    gi = B[i] * ((1 - m[i]) - tau[i] / gamma)
    return UC * ci + UG * gi


def strategic_objects(tauM, s, theta):
    D, B, Om = matrices(s)
    tau = nash(tauM, s, theta)
    h = 1e-6
    Rn, dhat, Ra = np.zeros(2), np.zeros(2), np.zeros(2)
    for i in range(2):
        j = 1 - i
        th = theta[i]

        def Fi(t, tM=tauM):
            return F(i, t, tM, D, B, th)

        e_i = np.eye(2)[i]; e_j = np.eye(2)[j]
        Fii = (Fi(tau + h * e_i) - Fi(tau - h * e_i)) / (2 * h)
        Fij = (Fi(tau + h * e_j) - Fi(tau - h * e_j)) / (2 * h)
        FiM = (Fi(tau, tauM + h) - Fi(tau, tauM - h)) / (2 * h)
        Rn[i] = -Fij / Fii
        dhat[i] = -FiM / Fii
        # closed form of the slope (Appendix B)
        m, _, C, G = allocation(tau, tauM, D, B)
        UC = 1 - th * G[i]
        UG = b - 2 * c * G[i] - th * C[i]
        ci = -D[i, i] * (1 - m[i])
        gi = B[i] * ((1 - m[i]) - tau[i] / gamma)
        Fii_cf = (UC * D[i, i] - 2 * UG * B[i]) / gamma - 2 * th * ci * gi - 2 * c * gi**2
        Ra[i] = -th * D[i, j] * (1 - m[j]) * gi / Fii_cf
        assert abs(Fii - Fii_cf) < 1e-6, (Fii, Fii_cf)
    mult = np.array([(dhat[i] + Rn[i] * dhat[1 - i]) / (1 - Rn[0] * Rn[1]) for i in range(2)])
    hh = 1e-4
    # the interior problem is smooth in tauM, so a central difference is used
    # even at tauM = 0 (tauM - hh < 0 only shifts the haven rate slightly)
    direct = (nash(tauM + hh, s, theta, tau) - nash(tauM - hh, s, theta, tau)) / (2 * hh)
    return tau, Rn, Ra, mult, direct


def check(label, got, want, tol=TOL):
    flag = "ok " if abs(got - want) <= tol else "XX "
    print(f"   [{flag}] {label}: {got:.4f} (paper {want})")


# ============================================================================
if __name__ == "__main__":
    grid = [0.00, 0.05, 0.10, 0.15, 0.20]

    # ---------------------------------------------------------------- Table 1
    print("\nTable 1 (tab:equilibrium)")
    for tM in grid:
        e = equilibrium(tM)
        # cross-check the interior FOC against global best responses
        assert np.allclose(e["tau"], nash(tM), atol=1e-7)
        print(f"{tM:.2f} & {e['tau'][0]:.4f} & {e['tau'][1]:.4f} & {e['m'][0]:.4f} & "
              f"{e['m'][1]:.4f} & {e['G'][0]:.4f} & {e['G'][1]:.4f} & {e['W'][0]:.4f} & "
              f"{e['W'][1]:.4f} & {e['a'][0]:.3f} & {e['a'][1]:.3f} \\\\")

    e0 = equilibrium(0.0)
    print("  text:")
    check("Ghat", Ghat, 2.667, 5e-4)
    lhs = gamma * e0["B"] * (1 - e0["m"])**2
    check("gamma B_1 (1-m_1)^2", lhs[0], 0.567, 5e-4)
    check("gamma B_2 (1-m_2)^2", lhs[1], 0.762, 5e-4)
    for tM, want in [(0.0, 1.49), (0.20, 4.95)]:
        e = equilibrium(tM); t1, m1 = e["tau"][0], e["m"][0]
        check(f"a*_1 at tauM={tM}", t1 * (1 - m1) / (m1 * (gamma * (1 - m1) - t1)), want, 5e-3)
    for tM in grid:
        e = equilibrium(tM)
        rhs = gamma * e["B"] * (1 - e["m"])**2
        assert np.all(Ghat / rhs >= 2), "factor-of-two claim fails"

    # ---------------------------------------------------------------- Table 2
    print("\nTable 2 (tab:decomposition), d tau_j/d tauM from (dtau)")
    for tM in [0.00, 0.10, 0.20]:
        rows, e, dt = decomposition(tM)
        # closed form vs numerical derivative of the equilibrium
        h = 1e-6
        num = (equilibrium(tM + h)["tau"] - equilibrium(max(tM - h, 0))["tau"]) / (h + min(h, tM) if tM > 0 else h)
        assert np.allclose(dt, num, atol=1e-4)
        for i, r in enumerate(rows):
            print(f"{tM:.2f} & {i+1} & ${r['mech']:+.4f}$ & ${r['rev']:+.4f}$ & "
                  f"${r['ext']:+.4f}$ & ${r['tot']:+.4f}$ \\\\")
    rows0, _, dt0 = decomposition(0.0)
    print("  text:")
    check("d tau_1/d tauM at 0", dt0[0], 0.194, 5e-4)
    check("d tau_2/d tauM at 0", dt0[1], 0.322, 5e-4)
    check("externality share, country 1, tauM=0 (%)",
          100 * rows0[0]["ext"] / rows0[0]["tot"], 43, 0.5)
    e = equilibrium(0.20); m1, t1, a1 = e["m"][0], e["tau"][0], e["a"][0]
    check("eta_1 at 0.20", 1 / (gamma * m1), 12.14, 5e-3)
    check("T(a_1) at 0.20", a1 * (1 - m1) / (t1 * ((1 - m1) + a1 * m1)), 10.30, 5e-3)
    print("   direct trade-off (mech+rev) and a_1 vs a*_1, country 1:")
    for tM in grid:
        r, e, _ = decomposition(tM); t1, m1 = e["tau"][0], e["m"][0]
        ast = t1 * (1 - m1) / (m1 * (gamma * (1 - m1) - t1))
        print(f"     tauM={tM:.2f}  direct={r[0]['mech']+r[0]['rev']:+.4f}  "
              f"ext={r[0]['ext']:+.4f}  a1={e['a'][0]:.3f}  a*1={ast:.3f}  "
              f"ext/total={100*r[0]['ext']/r[0]['tot']:.0f}%")

    # ---------------------------------------------------------------- Table 3
    print("\nTable 3 (tab:portfolio), tauM = 0")
    for s in [0.0, 0.1, 0.2, 0.3, 0.4]:
        rows, e, _ = decomposition(0.0, s)
        print(f"{s:.2f} & {e['Om'][0]:.3f} & {e['Om'][1]:.3f} & {e['a'][0]:.3f} & "
              f"{e['a'][1]:.3f} & ${rows[0]['tot']:+.4f}$ & ${rows[1]['tot']:+.4f}$ \\\\")
    print("  text:")
    check("tau_1 at s=0.4", equilibrium(0.0, 0.4)["tau"][0], 0.3707)
    s_star = brentq(lambda s: decomposition(0.0, s)[0][0]["tot"], 0.3, 0.5, xtol=1e-12)
    check("switch point s*", s_star, 0.3760)

    # ------------------------------------------- Figure 1: numbers in the text
    # Slopes R'_i, responses to the floor and the mixed case theta_1 != theta_2
    # quoted in Appendix B, in the paragraph that discusses Figure 1.
    print("\nFigure 1, numbers in Appendix B: s = 0.2, tauM = 0")
    for th in [(-0.15, -0.15), (0.0, 0.0), (0.15, 0.15), (0.15, -0.15)]:
        tau, Rn, Ra, mult, direct = strategic_objects(0.0, 0.2, th)
        assert np.allclose(Rn, Ra, atol=1e-8), (Rn, Ra)          # (thetaslope) = numerical
        assert np.allclose(mult, direct, atol=1e-5), (mult, direct)  # (multiplier) = numerical
        assert np.all(np.sign(Rn) == np.sign(th)) or th == (0.0, 0.0)
        D, B, _ = matrices(0.2)
        _, _, C, G = allocation(tau, 0.0, D, B)
        for i in range(2):
            assert 1 - th[i] * G[i] > 0 and b - 2 * c * G[i] - th[i] * C[i] > 0
        print(f"{th[0]:+.2f} & {th[1]:+.2f} & {tau[0]:.4f} & {tau[1]:.4f} & "
              f"${Rn[0]:+.4f}$ & ${Rn[1]:+.4f}$ & {mult[0]:.4f} & {mult[1]:.4f} \\\\")
    print("  text (no cross-ownership, s = 0):")
    for th, want in [(0.15, 0.034), (-0.15, -0.016)]:
        _, Rn, Ra, _, _ = strategic_objects(0.0, 0.0, (th, th))
        check(f"R'_1 with theta_1={th}", Rn[0], want, 5e-4)
        assert abs(Rn[1]) < 1e-8

    # ---------------------------------------------------------------- Figure 1
    # Reaction functions as deviations from the Nash rates.  The slopes are of
    # order 1e-2, so in levels the three curves would look parallel; drawn as
    # deviations they cross at the origin and only the slope is visible.
    # theta < 0: the public good is normal, a higher foreign rate lowers
    #            resident income and the demand for the public good, the
    #            domestic rate falls: strategic substitutes.
    # theta > 0: the public good is inferior, the opposite: strategic
    #            complements.
    # theta = 0: flat, as under domestic ownership for any preferences.
    print("\nFigure 1 (fig:reaction), s = 0.2, tauM = 0")
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    s_fig, tM_fig = 0.2, 0.0
    D, B, _ = matrices(s_fig)
    cases = [(-0.15, r"$\theta=-0.15$: strategic substitutes", "-"),
             (0.0,   r"$\theta=0$: flat (quasi-linear)",        "--"),
             (0.15,  r"$\theta=0.15$: strategic complements",   "-.")]
    fig, ax = plt.subplots(1, 2, figsize=(10, 4))
    for th, lab, ls in cases:
        eq = nash(tM_fig, s_fig, (th, th))
        g2 = np.linspace(eq[1] - 0.2, eq[1] + 0.2, 41)
        g1 = np.linspace(eq[0] - 0.2, eq[0] + 0.2, 41)
        br1 = np.array([best_response(0, t2, tM_fig, D, B, th) for t2 in g2]) - eq[0]
        br2 = np.array([best_response(1, t1, tM_fig, D, B, th) for t1 in g1]) - eq[1]
        ax[0].plot(g2 - eq[1], 1000 * br1, ls, color="k", label=lab)
        ax[1].plot(g1 - eq[0], 1000 * br2, ls, color="k", label=lab)
        print(f"   theta={th:+.2f}: slope country 1 = {(br1[-1]-br1[0])/0.4:+.4f}, "
              f"slope country 2 = {(br2[-1]-br2[0])/0.4:+.4f}")
    ax[0].set_xlabel(r"$\tau_2-\tau_2^{*}$")
    ax[0].set_ylabel(r"$\tau_1^{BR}(\tau_2)-\tau_1^{*}$  ($\times 10^{3}$)")
    ax[0].set_title("Headquarters country ($D_{12}=0.8$)", fontsize=10)
    ax[1].set_xlabel(r"$\tau_1-\tau_1^{*}$")
    ax[1].set_ylabel(r"$\tau_2^{BR}(\tau_1)-\tau_2^{*}$  ($\times 10^{3}$)")
    ax[1].set_title("Host country ($D_{21}=0.2$)", fontsize=10)
    ax[0].legend(fontsize=8, frameon=False, loc="upper left")
    for a_ in ax:
        a_.grid(alpha=.3); a_.axhline(0, color="gray", lw=.5); a_.axvline(0, color="gray", lw=.5)
    plt.tight_layout()
    plt.savefig("fig_reaction.pdf")
    print("   written fig_reaction.pdf")

    # ------------------------------------------------ High floor (Section 3.6)
    print("\nHigh floor")
    D, B, Om = matrices(0.0)
    M_at = lambda tM, i: b - 2 * c * tM * B[i]
    stop = [brentq(lambda tM: M_at(tM, i) * (1 - tM / gamma) - Om[i], 0.01, 0.99) for i in range(2)]
    tau0 = [(b - Om[i]) / (2 * c * B[i]) for i in range(2)]
    check("shifting ends, country 1", stop[0], 0.2967)
    check("shifting ends, country 2", stop[1], 0.5)
    check("tau0_1", tau0[0], 1.0)
    check("tau0_2", tau0[1], 0.9167)
    check("G_1 at tau0_1", tau0[0] * B[0], 1.0)
    check("G_2 at tau0_2", tau0[1] * B[1], 1.833, 5e-4)
    for tM in [0.5, 0.6, 1.0]:
        tau = nash(tM, start=(tM, tM))
        _, _, C, G = allocation(tau, tM, D, B)
        print(f"   tauM={tM}: tau={np.round(tau,4)}  MRS={np.round(b-2*c*G,4)}  "
              f"W={np.round(utility(C,G),4)}")
    tau = nash(0.6, start=(0.6, 0.6)); _, _, C, G = allocation(tau, 0.6, D, B)
    W6 = utility(C, G)
    check("MRS_1 at 0.6", (b - 2 * c * G)[0], 1.24)
    check("MRS_2 at 0.6", (b - 2 * c * G)[1], 0.88)
    check("W_1 at 0.6", W6[0], 1.6520)
    check("W_2 at 0.6", W6[1], 1.8880)
    check("loss country 1 at 0.6", e0["W"][0] - W6[0], 0.1092)
    check("gain country 2 at 0.6", W6[1] - e0["W"][1], 0.5085)
    tau = nash(1.0, start=(1.0, 0.9)); _, _, C, G = allocation(tau, 1.0, D, B)
    check("W_1 at 1", utility(C, G)[0], 1.3833)
    check("W_2 at 1", utility(C, G)[1], 2.0083)
    # unilateral re-optimisation by country 1, tau_2 at pre-reform value
    t2 = e0["tau"][1]
    t1 = best_response(0, t2, 0.6, D, B)
    Wuni = welfare(0, [t1, t2], 0.6, D, B)
    check("W_1, only country 1 re-optimises", Wuni, 1.8692)
    check("its gain", Wuni - e0["W"][0], 0.1080)
    dt2 = 0.6 - t2
    check("Delta tau_2", dt2, 0.2172)
    check("D12 * Delta tau_2", D[0, 1] * dt2, 0.2172)
    assert abs((Wuni - D[0, 1] * dt2) - W6[0]) < 1e-10          # exact decomposition
    ext_marg = D[0, 1] * (1 - e0["m"][1]) * dt2
    check("term with factor 1-m_2", ext_marg, 0.1341)
    check("loss with factor 1-m_2", ext_marg - (Wuni - e0["W"][0]), 0.0260, 1.5e-4)

    # ------------------------------------------------ Appendix B: group ratio
    print("\nGroup ratio (eq:groupratio), host country, tauM = 0, rho = 1")
    D, B, Om = matrices(0.0)
    j = 1
    for y_share, want in [(0.0, 0.21), (0.5, 0.14), (1.0, 0.10)]:
        div = e0["C"][j]                         # dividend income with y = 0
        Cj = div * (1 + y_share)
        r = (D[j, j] * (1 - e0["m"][j]) / Cj) * \
            (gamma * (D[j] @ e0["m"]) / (B[j] * (e0["MRS"][j] - Om[j])))
        check(f"y = {y_share} x dividends", r, want, 5e-3)

    # ------------------------------------------------ Footnote: number of havens
    print("\nHavens needed to deter the deviation tau_1 = tauM (tauM = 0.20)")
    e = equilibrium(0.20); D, B, _ = matrices(0.0); tM = 0.20
    def W_dev(H):
        tau = np.array([tM, e["tau"][1]])
        m, phi, C, G = allocation(tau, tM, D, B)
        G1 = tM * B[0] + tM * B[1] * m[1] / (H + 1)
        return utility(C[0], G1)
    H = 2
    while W_dev(H) > e["W"][0]:
        H += 1
    print(f"   deviation unprofitable from H = {H} (paper: 19)")
    D, B, _ = matrices(0.0)
    print("\nDone.")
