"""Four identical copy neurons; functional probes after learning delayed coactivity."""
from fractions import Fraction as F
from itertools import product
from random import Random
import json

def observe(noise):
    rng=Random(1011)
    observations=[]
    # An externally driven wave, with a two-tick plateau on the last unit.
    for _ in range(64):
        trajectory=((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1),(0,0,0,1))
        trial=[tuple(b^int(rng.random()<noise) for b in x) for x in trajectory]
        observations.extend(zip(trial,trial[1:]))
    return observations

def learn(data):
    return tuple(max(range(4),key=lambda i:sum(a[i]*b[j] for a,b in data)) for j in range(4))

def probes(w):
    out=[]
    for start in range(4):
        state=[int(i==start) for i in range(4)];hist=[state]
        for _ in range(4):
            state=[state[i] for i in w];hist.append(state)
        transport=sum(hist[1][i] for i in range(4) if i!=start)
        retain=hist[2][start]
        # Exact read-out of the externally specified final query bit after three ticks.
        out.append([transport,retain,hist[3][3]])
    return out

def evaluate(w):
    obs=probes(w)
    correct=sum(row[2]==int(i==0) for i,row in enumerate(obs))
    return dict(wiring=w,probes=obs,query_accuracy=str(F(correct,4)))

def run():
    fixed=evaluate((0,1,2,3));random=[]
    rng=Random(3110)
    for _ in range(256):random.append(F(evaluate(tuple(rng.randrange(4) for j in range(4)))['query_accuracy']))
    population = sum(F(evaluate(w)['query_accuracy']) for w in product(range(4),repeat=4))/256
    data={str(e):evaluate(learn(observe(e))) for e in [0,.05,.20]}
    # Identical channels cannot be distinguished from time series, even with infinitely many repeats.
    all_on=[((1,1,1,1),(1,1,1,1))]*64
    assert learn(all_on)==(0,0,0,0)
    return dict(trials=64,links=4,fixed=fixed,random_mean=str(sum(random)/len(random)),uniform_exact=str(population),learned=data,
                indistinguishable=4**4,active_readout_unit=3)
if __name__=='__main__':print(json.dumps(run(),indent=2))
