"""Exact rank displacement vs discrepancy, window moments and checks."""
from fractions import Fraction as F
from math import gcd,prod,sqrt
from motifs import primes
import csv,random
from pathlib import Path
root=Path(__file__).resolve().parents[1]/'resultats'

def stats(R,A):
 T=len(A); assert T>0;rho=F(T,R);c=0;ss=st=0; aset=set(A)
 for x in range(R):
  z=R*c-T*x;ss+=z*z;st+=z;c+=x in aset
 mu=F(st,R**2);var=F(ss,R**3)-mu*mu
 z=[F(a)-F(2*k+1,2)/rho for k,a in enumerate(A)]
 m=sum(z)/T;v=sum((x-m)**2 for x in z)/T
 assert m==-(mu+rho/2)/rho
 assert v==(var+(rho*rho-1)/12)/(rho*rho)
 return rho,mu,var,m,v

def correlation(ps,E,h):
 return prod(F(p-len({(-e)%p for e in E}|{(-e-h)%p for e in E}),p) for p in ps)

def windows(ps,E,lengths):
 rho=correlation(ps,E,0);mx=max(lengths);s=F(0);w=F(0);result={}
 for L in range(1,mx+1):
  if L>1:
   h=L-1;c=correlation(ps,E,h)-rho*rho;s+=c;w+=h*c
  if L in lengths:result[L]=L*rho*(1-rho)+2*(L*s-w)
 return result

def variance_green(ps,E):
 R=prod(ps);terms=[(1,0,1)]
 for p in ps:
  bad={-e%p for e in E};nu=len(bad);inter=[sum((b+h)%p in bad for b in bad) for h in range(p)]
  opt=[(None,p-2*nu)]+[(h,v) for h,v in enumerate(inter) if v]
  direct=[(h,p-2*nu+v) for h,v in enumerate(inter) if p-2*nu+v]
  opt=[(h,v) for h,v in opt if v]
  if len(direct)<len(opt):opt=direct
  terms=[(d if h is None else d*p,a if h is None else a+d*((h-a)*pow(d,-1,p)%p),w*v) for d,a,w in terms for h,v in opt]
 num=sum(w*(R//d)*(d*d-1-6*a*(d-a)) for d,a,w in terms)
 return F(num,12*R*R),len(terms)

def main():
 rng=random.Random(938);checks=0
 for R in range(1,65):
  for _ in range(10):
   A=sorted(rng.sample(range(R),rng.randrange(1,R+1)));stats(R,A);checks+=1
 for n in [2,3,5,7,11,13]:
  ps=primes(n);R=prod(ps)
  for E in [(0,),(0,2),(0,6),(0,2,6),(1,3)]:
   A=[a for a in range(R) if all(gcd(a+e,R)==1 for e in E)]
   if not A:continue
   rho,mu,v,m,v2=stats(R,A);assert variance_green(ps,E)[0]==v;checks+=1
   ls=[1,2,5,11];win=windows(ps,E,ls);aset=set(A)
   for L in ls:
    actual=sum((sum((x+h)%R in aset for h in range(L))-L*rho)**2 for x in range(R))/R
    assert actual==win[L];checks+=1
 for n in [5,7,11]:
  R=prod(primes(n))
  for g in [2,4,6,8,10]:
   A=[a for a in range(R) if gcd(a,R)==gcd(a+g,R)==1 and all(gcd(a+h,R)>1 for h in range(1,g))]
   if A:stats(R,A);checks+=1
 print('exact checks',checks)
 with (root/'unit_displacement.csv').open('w') as f:
  w=csv.writer(f);w.writerow(['n','m','R','rho','variance_rank','rms_displacement','radius_95_ceil','radius_99_ceil'])
  from math import ceil
  for n in [13,19,29,37,47,59,67,97,199]:
   ps=primes(n);R=prod(ps);rho=prod(F(p-1,p) for p in ps);v=(2**len(ps)*rho-1)/(12*rho*rho)
   w.writerow([n,len(ps),R,float(rho),str(v),sqrt(float(v)),ceil(sqrt(float(v)*20)+.5),ceil(sqrt(float(v)*100)+.5)])
 with (root/'window_variance.csv').open('w') as f:
  w=csv.writer(f);w.writerow(['n','E','length','mean','variance','sd'])
  for n in [19,37,59,67]:
   for E in [(0,),(0,2),(0,2,6)]:
    ps=primes(n);rho=correlation(ps,E,0)
    for L,v in windows(ps,E,[10,100,1000,10000]).items():w.writerow([n,str(E),L,float(rho*L),float(v),sqrt(float(v))])
if __name__=='__main__':main()
