TI/Boxcar
Z Brain-wiki
dziedziczenie vs kompozycja
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 12:45:41 2019
@author: tgub
"""
#boxcar kompozycja
class boxcar_com():
def __init__(self,N):
self.__sum=0
self.__sum2=0
self.__N=N
self.__list=[]
def __str__(self):return self.__list.__str__()
def __repr__(self):return self.__list.__repr__()
def __getitem__(self,index):
print('tutaj blad index =',index)
return self.__list[index]
def append(self,elem):
self.__sum+=elem
self.__sum2+=elem*elem
if len(self.__list)>=self.__N:
self.__sum-=self.__list[0]
self.__sum2-=self.__list[0]*self.__list[0]
self.__list.pop(0)
self.__list.append(elem)
print('append com',elem)
@property
def mean(self):
return self.__sum/len(self.__list)
@property
def var(self):
return self.__sum2/(len(self.__list))-self.mean*self.mean
#boxcar dziedziczenie
class boxcar_inh(list):
def __init__(self,N):
super().__init__([])
self.__sum=0
self.__sum2=0
self.__N=N
def __setitem__(self,index,value):
raise TypeError
def append(self,elem):
self.__sum+=elem
self.__sum2+=elem*elem
if len(self)>=self.__N:
self.__sum-=self[0]
self.__sum2-=self[0]*self[0]
self.pop(0)
super().append(elem)
print('append inh',elem)
@property
def mean(self):
return self.__sum/len(self)
@property
def var(self):
return self.__sum2/(len(self))-self.mean*self.mean
ac=boxcar_com(5)
ai=boxcar_inh(5)
ac.append(1)
ai.append(1)
ac.append(2)
ai.append(2)
ac.append(3)
ai.append(3)
ac.append(4)
ai.append(4)
ac.append(5)
ai.append(5)
print('ac',ac.mean,ac.var,ac)
print('ai',ai.mean,ai.var,ai)
ac.append(6)
ai.append(6)
print('ac',ac.mean,ac.var,ac)
print('ai',ai.mean,ai.var,ai)
ac.append(7)
ai.append(7)
print('ac',ac.mean,ac.var,ac)
print('ai',ai.mean,ai.var,ai)
FFT w boxcar
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 8 11:06:03 2019
@author: tgub
"""
import matplotlib.pyplot as plt
import numpy as np
#boxcar dziedziczenie
class boxcar(list):
#prosta implementacja:
#https://docs.scipy.org/doc/numpy/reference/routines.fft.html
@staticmethod
def myfft(arr):
n=len(arr)
A=np.zeros(n,dtype='complex_')
for k in range(n):
for m in range(n):
A[k]+=arr[m]*np.exp(-2j*np.pi*m*k/n)
return A
def __init__(self,N):
super().__init__([0]*N)
self.__sum=0
self.__sum2=0
self.__N=N
self.__fft=boxcar.myfft(self)
self.__exp1=np.exp(2j*np.pi/N*np.arange(N))
self.__exp2=np.exp(-2j*np.pi*(N-1)/N*np.arange(N))
def __setitem__(self,index,value):
raise TypeError
def append(self,elem):
self.__sum+=elem
self.__sum2+=elem*elem
self.__sum-=self[0]
self.__sum2-=self[0]*self[0]
#update fft
self.__fft=(self.__fft-self[0])*self.__exp1+elem*self.__exp2
self.pop(0)
super().append(elem)
@property
def mean(self):
return self.__sum/len(self)
@property
def var(self):
return self.__sum2/(len(self))-self.mean*self.mean
@property
def fft(self):
return self.__fft.copy()
sygnal = np.sin(np.arange(1000))
x=boxcar(100)
for i in range(700):
x.append(sygnal[i])
plt.plot(x.fft.imag+1.0)
plt.plot(boxcar.myfft(x).imag)
plt.show()