trade.py

Checks: LIMIT: The chain theorem.

Cited on: LIMIT.

To run it: save trade.py; standard library only.

"""trade.py -- can two items of incomparable degree trade the global
clock forever?

QUESTION. A greedy walk's holders of clock moves fall strictly in
degree under a price with kappa(d', r') > kappa(d, r) whenever d' >= d
and r' > r: a change of holder Z -> Y needs kappa(d_Y, r_Y) <=
kappa(d_Z, r_Z) with r_Y > r_Z, which a total order on degrees turns
into d_Y < d_Z. Over degrees only partially ordered, two incomparable
items A and B could trade the clock forever; at bounded gaps they
cannot trade it in turn (that needs g_(k+1) > g_(k-1) + g_k). At
unbounded gaps, the doubling ladder's, is there a pair that does?

DESIGN. The doubling ladder 1, 2, 4, 8, ...; the supply two items A and
B, both born covered (no openings), of incomparable degree, so the
chain's hypothesis asks only that each item's price rise strictly with
its door. Each price is piecewise linear in the door r through knots
(r, value), exact rationals, and constant slope past the last knot. The
knots are read off the walk wanted, derived by hand:
  T = 1: both at 0 bid door 2; A clocks, A(2) < B(2). A lands at 2.
  T = 2: A door 1, B door 3; A keeps. A at 3.
  T = 4: A door 2, B door 5; A keeps. A at 5.
  T = 8: A door 4, B door 9; B takes the clock, B(9) < A(4). B at 9.
  T = 16: B door 8, A door 12; B keeps (B(8) < B(9) < A(4) < A(12)).
  T = 32: B door 16, A door 28; A takes it back, A(28) < B(16).
  T = 2^n, n >= 6: the holder, landed at 2^(n-1) + 1, bids door
  2^(n-1); the rival, landed at 2^(n-2) + 1, bids door 2^n - 2^(n-2) =
  3 * 2^(n-2); the rival takes it when
  rival(3 * 2^(n-2)) < holder(2^(n-1)).
The wanted inequalities chain as
  A(2) < B(2) < B(9) < A(4) < A(28) < B(16) < B(48) < A(32) < A(96)
  < B(64) < B(192) < A(128) < A(384) < B(256) < ...,
each item's doors rising along it, so knots ranked along the chain give
two strictly increasing prices: A at (1, 1/2), (2, 1), (4, 4), (28, 5),
then A(2^(2i+1)) = 4i and A(3 * 2^(2i+1)) = 4i + 1 for i >= 2; B at
(1, 3/2), (2, 2), (9, 3), then B(2^(2i)) = 4i - 2 and B(3 * 2^(2i)) =
4i - 1 for i >= 2. The walk is
limit.py's walk rewritten small: menu, least price, the canonical
tie-break (clock first, lower degree, lower exponent; no tie is met).

PREDICTIONS, fixed before the engine:
  (P1) The holders read A, A, A, B, B, A, then alternate B, A, B, ...
       at every notch from 64 on, over 40 clock moves (notch 2^40).
  (P2) Both exponents are unbounded: each item's exponent exceeds 2^37
       by the last move. Two deep coordinates, so the chain's "exactly
       one" needs its total order.
  (P3) Each item's price rises strictly with its door at every door up
       to 2^41 (asserted at the knots and checked at 4096 random doors).
  (P4) Control: replace B's price by A's shifted one degree up (B =
       A + 1 at every door, the two now comparable, B above A); the
       chain's theorem then holds and the walk keeps one holder, A,
       at every move.
KILL: any clock move from T = 64 on whose holder repeats the last's.

FINDINGS. The kill missed; every prediction held. Holders
AAABBABABA...BA over 40 clock moves, at the notches 2^0 to 2^39 (the
notch after the last, 2^40, read by no move); the eight first
read A door 2 at price 1, A door 1 at 1/2, A door 2 at 1, B door 9 at 3,
B door 8 at 20/7, A door 28 at 5, B door 48 at 7, A door 96 at 9. Final
exponents 2^39 + 1 and 2^38 + 1: two deep coordinates on the doubling
ladder. The control (B = A + 1) holds A at all 40. A planted break, A's
knot at 96 raised from 9 to 11 (past B(64) = 10), read AAABBABBBBBB at
12 clock moves, now the script's plant arm: B keeps the clock from
notch 128, so the kill can fire.
Two items alone change holder only while the gaps grow: if Y takes the
clock from Z at door D and Z takes it back at a later notch at door D',
then kappa(d_Y, D) <= kappa(d_Z, g) < kappa(d_Z, D') <= kappa(d_Y, g'),
g the gap at Y's take and g' at Z's, so D < g' and D' >= g + g' > D.
LEMMA asserts both along the trading walk: each taker's door is below
the gap at the next change of holder, and the takers' doors rise.
The construction is the proof: along the chain each item's doors rise,
so ranked knots give two strictly rising prices, and from notch 64 the
pattern repeats every two clock moves with every door four times larger
and every rank raised by 4.

RUN RECORD. 8292 checks pass, under a second. With LEMMA added, 8327
checks pass, under a second.
"""
import random
from fractions import Fraction as F

CHECKS = [0]


def check(cond, msg):
    CHECKS[0] += 1
    if not cond:
        raise SystemExit("FAIL " + msg)


def knots(item, top):
    """The hand-derived knots of item 'A' or 'B', doors up to 2^top."""
    if item == "A":
        ks = [(1, F(1, 2)), (2, F(1)), (4, F(4)), (28, F(5))]
        i = 2
        while 2 ** (2 * i + 1) <= 2 ** top:
            ks += [(2 ** (2 * i + 1), F(4 * i)), (3 * 2 ** (2 * i + 1), F(4 * i + 1))]
            i += 1
    else:
        ks = [(1, F(3, 2)), (2, F(2)), (9, F(3))]
        i = 2
        while 2 ** (2 * i) <= 2 ** top:
            ks += [(2 ** (2 * i), F(4 * i - 2)), (3 * 2 ** (2 * i), F(4 * i - 1))]
            i += 1
    return ks


def price_of(ks):
    def p(r):
        for (r0, v0), (r1, v1) in zip(ks, ks[1:]):
            if r0 <= r <= r1:
                return v0 + (v1 - v0) * F(r - r0, r1 - r0)
        (r0, v0), (r1, v1) = ks[-2], ks[-1]
        return v1 + (v1 - v0) / (r1 - r0) * (r - r1)
    return p


def walk(prices, nclocks):
    """Both items born covered; the doubling ladder; each move a clock
    move (no openings exist). Returns the holders and the final state."""
    exp, T, holders, doors = {x: 0 for x in prices}, 1, [], []
    for _ in range(nclocks):
        bids = sorted((prices[x](T + 1 - exp[x]), x) for x in prices)
        check(bids[0][0] != bids[1][0], f"a tie at notch {T}")
        x = bids[0][1]
        doors.append((T, x, T + 1 - exp[x]))
        exp[x], holders = T + 1, holders + [x]
        T *= 2                        # next member of 1, 2, 4, ... at or above T + 1
    return holders, exp, T, doors


def main():
    top = 42
    A, B = price_of(knots("A", top)), price_of(knots("B", top))
    # P3: strict rise at every door up to 2^41, at the knots and at random
    for name, ks in (("A", knots("A", top)), ("B", knots("B", top))):
        check(all(v0 < v1 for (_, v0), (_, v1) in zip(ks, ks[1:])),
              f"{name}'s knots fall")
    rng = random.Random(1)
    p = {"A": A, "B": B}
    for _ in range(4096):
        r = rng.randrange(1, 2 ** 41)
        for x in "AB":
            check(p[x](r) < p[x](r + 1), f"{x} not rising at {r}")
    print("P3: both prices rise strictly at every knot and at 4096 random doors")
    holders, exp, T, doors = walk(p, 40)
    print("P1: holders", "".join(holders), "final notch 2^%d" % (T.bit_length() - 1))
    for T0, x, r in doors[:8]:
        print(f"    notch {T0:4d}: {x} at door {r}, price {p[x](r)}")
    check("".join(holders[:6]) == "AAABBA", "the opening holders")
    late = holders[6:]
    check(all(a != b for a, b in zip(late, late[1:])) and late[0] != holders[5],
          "KILL: a holder repeats from notch 64 on")
    print("P2: exponents", {x: f"2^{(exp[x] - 1).bit_length() - 1} + 1"
                            for x in exp})
    check(exp == {"A": 2 ** 39 + 1, "B": 2 ** 38 + 1}, "the final exponents")
    check(min(exp.values()) > 2 ** 37, "an exponent stayed bounded")
    # LEMMA: at each change of holder the taker's door is below the gap at
    # the next change, and the takers' doors rise
    takes = [(T0, r) for i, (T0, x, r) in enumerate(doors)
             if i and x != doors[i - 1][1]]
    for (_, D), (T1, D1) in zip(takes, takes[1:]):
        check(D < T1 - T1 // 2 < D1, f"LEMMA at notch {T1}")
    print(f"LEMMA: {len(takes)} changes of holder, each taker's door below "
          f"the next change's gap, the doors rising")
    # P4: the control, B = A + 1, comparable and above A
    hc, _, _, _ = walk({"A": A, "B": lambda r: A(r) + 1}, 40)
    print("P4: control holders", "".join(hc))
    check(set(hc) == {"A"}, "the control changed holder")
    # the planted break: A's knot at 96 raised from 9 to 11, past B(64)
    kp = [(r, v + 2 if r == 96 else v) for r, v in knots("A", top)]
    hp, _, _, _ = walk({"A": price_of(kp), "B": B}, 12)
    print("plant: holders", "".join(hp))
    check("".join(hp) == "AAABBABBBBBB", "the planted break read otherwise")
    print(f"trade: {CHECKS[0]} checks pass")


if __name__ == "__main__":
    main()