from scipy.stats import ks_2samp
from IKS import IKS
import numpy as np
from time import time
from itertools import chain
from random import random

from collections import deque

initial = np.random.normal(loc = 0, scale = 1, size = 500)

stream = list(chain(*[np.random.normal(loc = 1.0 * (i % 2), scale = 1, size = 500) for i in range(10)]))

######################
## TEST IKS
######################

start = time()

iks_statistics = [] # collect statistics generated by IKS
iks = IKS() # group 0 = reference; group 1 = sliding

sliding = deque()

for val in initial:
  iks.Add((val, random()), 0)
  wrnd = (val, random()) # we only need to keep RND component for values in the sliding window
  iks.Add(wrnd, 1)
  sliding.append(wrnd)

# process sliding window
for val in stream:
  iks.Remove(sliding.popleft(), 1)
  wrnd = (val, random())
  iks.Add(wrnd, 1)
  sliding.append(wrnd)

  iks_statistics.append(iks.KS())

finish = time()
print(f'Elapsed time for IKS to process stream: {round(finish - start, 2)} sec')

######################
## TEST ks_2samp
######################

start = time()

ks_2samp_statistics = [] # collect statistics gerated by ks_2samp
sliding = deque(initial) # sliding window

for val in stream:
  sliding.popleft()
  sliding.append(val)

  ks_2samp_statistics.append(ks_2samp(initial, sliding).statistic)

finish = time()
print(f'Elapsed time for ks_2samp to process stream: {round(finish - start, 2)} sec')

max_diff = np.max(np.abs(np.array(iks_statistics) - np.array(ks_2samp_statistics)))

print(f'Maximum difference between IKS and ks_2samp: {max_diff}')