#!/usr/bin/env python3
"""Runs the three steps of the reduction (article p56-p57) as far as their sources state them.

Part A  the tree automaton of Rosenstiehl, Fiksel and Holliger 1972, section 3.5 (limb states
        omega, I, 0, 1, 2; one transition rule), on random networks with random limb numbering.
Part B  the walk around the tree by the rule of the same section ("the first limb of x, moving
        clockwise from p(l_{i-1}), that is found marked").
Part C  rules a', b', c' of the article (p54) on a ring of any length, under a discretisation
        that is OURS, stated in the line's pass; the article gives the rules only for n = 8.

No argument: prints a summary. Deterministic (fixed seeds).
"""
import random
from collections import deque

OMEGA, IDLE = "w", "I"


def random_network(n, d, rng):
    """A connected network: p maps a limb (x, r) to the limb it is joined to; absent = dead."""
    if True:
        free = [(x, r) for x in range(n) for r in range(d)]
        rng.shuffle(free)
        p = {}
        order = list(range(n))
        rng.shuffle(order)
        for i in range(1, n):          # a random tree first, so that the graph is connected
            x = order[i]
            lx = next(l for l in free if l[0] == x)
            ly = rng.choice([l for l in free if l[0] in order[:i]])
            free.remove(lx); free.remove(ly)
            p[lx], p[ly] = ly, lx
        extra = rng.randrange(0, len(free) // 2 + 1)   # then extra edges: loops and multi-edges allowed
        for _ in range(extra):
            a = free.pop(); b = free.pop()
            p[a], p[b] = b, a
        return p


def tree_automaton(n, d, p, a):
    """Section 3.5 (c): a quiescent automaton reading q on some limb sets all its live limbs to q+1."""
    state = {(x, r): (IDLE if (x, r) in p else OMEGA) for x in range(n) for r in range(d)}
    for r in range(d):
        if (a, r) in p:
            state[(a, r)] = 0
    t = 0
    while True:
        new = dict(state)
        for x in range(n):
            live = [r for r in range(d) if (x, r) in p]
            if live and all(state[(x, r)] == IDLE for r in live):
                read = [state[p[(x, r)]] for r in live if state[p[(x, r)]] in (0, 1, 2)]
                if read:
                    assert len(set(read)) == 1
                    for r in live:
                        new[(x, r)] = (read[0] + 1) % 3
        if new == state:
            return state, t
        state, t = new, t + 1


def entrance_limbs(n, d, p, a, state):
    """Section 3.5 (d): V = the limb of least number reading q-1, at each vertex but a."""
    V = {}
    for x in range(n):
        if x == a:
            continue
        q = next(state[(x, r)] for r in range(d) if (x, r) in p)
        V[x] = min(r for r in range(d) if (x, r) in p and state[p[(x, r)]] == (q - 1) % 3)
    return V


def distances(n, d, p, a):
    dist = {a: 0}
    todo = deque([a])
    while todo:
        x = todo.popleft()
        for r in range(d):
            if (x, r) in p and p[(x, r)][0] not in dist:
                dist[p[(x, r)][0]] = dist[x] + 1
                todo.append(p[(x, r)][0])
    return dist


def walk(n, d, p, a, V):
    marked = set()
    for x, r in V.items():
        marked.add((x, r)); marked.add(p[(x, r)])
    first = min(r for r in range(d) if (a, r) in marked)
    word, limb = [], (a, first)
    while True:
        word.append(limb)
        y, s = p[limb]
        r = next((s + k) % d for k in range(1, d + 1) if (y, (s + k) % d) in marked)
        limb = (y, r)
        if limb == (a, first):
            return word, marked


def part_ab(trials=2000):
    rng = random.Random(1974)
    for _ in range(trials):
        n, d = rng.randrange(2, 40), rng.randrange(2, 6)
        p = random_network(n, d, rng)
        a = rng.randrange(n)
        state, theta = tree_automaton(n, d, p, a)
        dist = distances(n, d, p, a)
        assert theta == max(dist.values()), "theta is the eccentricity of a"
        V = entrance_limbs(n, d, p, a, state)
        assert len(V) == n - 1
        for x, r in V.items():                         # every branch goes one step nearer to a
            assert dist[p[(x, r)][0]] == dist[x] - 1
        word, marked = walk(n, d, p, a, V)
        assert len(word) == 2 * n - 2 and set(word) == marked and len(set(word)) == len(word)
        visits = {}
        for (x, r) in word:
            visits[x] = visits.get(x, 0) + 1
        deg = {}
        for (x, r) in marked:
            deg[x] = deg.get(x, 0) + 1
        assert visits == deg
        for j, (x, r) in enumerate(word):              # the j-th letter leaves a vertex labelled by time j
            assert dist[x] <= j
    return trials


def ring(n, trace=None):
    """Rules a', b', c' on a ring of n cells; cell 0 is the initiator. Returns the set of firing times."""
    emitter = {0}
    sig = []                                           # [cell, direction, slowness m, time of emission]
    def emit(c, dirs, kinds, t):
        if trace is not None and c not in emitter:
            trace.setdefault(t, []).append(c + 1)
        emitter.add(c)
        for dr in dirs:
            for m in kinds:
                sig.append([c, dr, m, t, False])         # last: has it left its emitter?
    emit(0, (+1, -1), (1, 3), 0)
    fired = {}
    for t in range(1, 20 * n + 20):
        for c in range(n):                             # c': decided on the state at t-1
            if c not in fired and all(((c + k) % n) in emitter for k in (-1, 0, 1)):
                fired[c] = t
        if len(fired) == n:
            break
        for s in sig:
            if (t - s[3]) % s[2] == 0:
                s[0] = (s[0] + s[1]) % n
                s[4] = True
        here = {}
        for s in sig:
            here.setdefault(s[0], []).append(s)
        dead, births = [], []
        for c, ss in here.items():                     # meeting in one cell
            ss = [s for s in ss if s[4]]
            if {s[1] for s in ss} == {+1, -1}:
                kinds = {s[2] for s in ss}
                births.append((c, (+1, -1), tuple(kinds)))
                dead += ss
        for c, ss in here.items():                     # meeting between two cells: two emitters
            right = [s for s in ss if s[1] == +1 and s not in dead]
            left = [s for s in here.get((c + 1) % n, []) if s[1] == -1 and s not in dead]
            if right and left and n > 2:
                kinds = tuple({s[2] for s in right + left})
                births.append((c, (-1,), kinds))
                births.append(((c + 1) % n, (+1,), kinds))
                dead += right + left
        sig[:] = [s for s in sig if s not in dead]
        for c, dirs, kinds in births:
            emit(c, dirs, kinds, t)
    return sorted(set(fired.values())), len(fired)


if __name__ == "__main__":
    print("A, B: %d random networks: tree of shortest paths, theta = eccentricity, walk of 2n-2 letters: all hold" % part_ab())
    ok, bad = [], []
    for n in range(3, 201):
        times, count = ring(n)
        (ok if (len(times) == 1 and count == n) else bad).append((n, times))
    print("C: ring lengths 3..200 that fire all at once:", len(ok), "; that do not:", len(bad))
    print("   n=8 fires at", ring(8)[0], "; n=14 at", ring(14)[0])
    for n in (8, 14):
        tr = {}
        ring(n, tr)
        print("   n=%d, cells numbered from 1 as in the article; time: new emitters" % n, {t: sorted(c) for t, c in sorted(tr.items())})
    print("   first failures:", bad[:8])
    print("   firing time by n:", [(n, t[0]) for n, t in ok[:30]])
