import pandas as pd
import numpy as np

class Shewhart:
    # Channels one-by-one
    def __init__(self, first_points, wsize=10, rate = 1):
        # rate - how much of the moving window to be added to the found point
        self.mu0 = np.mean(first_points)
        self.std0 = np.std(first_points)
        self.counter = 1
        self._wsize = wsize
        self._rate = rate
        self._prev = 0
        self._decs = [0]

    def iterate(self, sample):
        self.counter = self.counter + 1
        new_mu = np.mean(sample)
        self.std0 = np.std(sample) + 1e-100
        v = 0 - new_mu
        b = v/self.std0
        si = (b/self.std0)*(np.sum(sample) - self.mu0*len(sample) - len(sample)*(v/2))
        self._decs.append(si - self._prev)
        if si - self._prev > 0:
            return 1,self.counter + int(self._wsize*self._rate)
        else:
            self._prev = si
            return 0, 0

if __name__ == "__main__":
    directory = "/media/synology/Documents/TUT/MSThesis/Scripts/Data/NoBaseline/"
    file1 = 'JasmineFlaskNoBaseline1.mat.csv'
    data = pd.read_csv(directory + file1)
    ims_abs = data['IMS_abs1']
    ts = [ims_abs[i+1] - ims_abs[i] for i in range(len(ims_abs)-1)]
    cs = Shewhart(ts[:10], 15)
    for i in range(len(ts)):
        sample = ts[i:i+10]
        f,cp = cs.iterate(sample)
        if f==True:
            break
    print(cp)

        
