|
| 1 | +""" |
| 2 | + Implementation of a moving statistics by extending CircularBuffer. |
| 3 | + This computes Standard deviation in the same way that MovingAverage |
| 4 | + is computed. |
| 5 | +""" |
| 6 | +from circBuffer import CircularBuffer |
| 7 | + |
| 8 | +class Statistics(CircularBuffer): |
| 9 | + |
| 10 | + def __init__(self, size): |
| 11 | + """Store buffer in given storage.""" |
| 12 | + CircularBuffer.__init__(self, size) |
| 13 | + self.total = 0 |
| 14 | + self.sumSq = 0 |
| 15 | + |
| 16 | + def getAverage(self): |
| 17 | + """Returns moving average (zero if no elements).""" |
| 18 | + if self.count == 0: |
| 19 | + return 0 |
| 20 | + return self.total/self.count |
| 21 | + |
| 22 | + def getStdev(self): |
| 23 | + """Returns moving stdev (zero if fewer than one element).""" |
| 24 | + if self.count <= 1: |
| 25 | + return 0 |
| 26 | + var = (self.sumSq - self.total*self.total/self.count)/self.count |
| 27 | + return var ** 0.5 |
| 28 | + |
| 29 | + def remove(self): |
| 30 | + """Removes oldest value from non-empty buffer.""" |
| 31 | + removed = CircularBuffer.remove(self) |
| 32 | + self.total -= removed |
| 33 | + self.sumSq -= removed*removed |
| 34 | + return removed |
| 35 | + |
| 36 | + def add(self, value): |
| 37 | + """Adds value to buffer, overwrite as needed.""" |
| 38 | + if self.isFull(): |
| 39 | + delta = self.buffer[self.low] |
| 40 | + else: |
| 41 | + delta = 0 |
| 42 | + |
| 43 | + self.total += value - delta |
| 44 | + self.sumSq += value*value - delta*delta |
| 45 | + CircularBuffer.add(self,value) |
| 46 | + |
| 47 | + def __repr__(self): |
| 48 | + """String representation of moving average.""" |
| 49 | + if self.isEmpty(): |
| 50 | + return 'ma:[]' |
| 51 | + return 'ma:[{0:s}]:{1:f} {2:f}'.format(','.join(map(str,self)), |
| 52 | + self.getAverage(), |
| 53 | + self.getStdev()) |
| 54 | +if __name__ == '__main__': |
| 55 | + b = Statistics(5) |
| 56 | + for _ in range(10): |
| 57 | + b.add(_*_) |
| 58 | + print (b) |
| 59 | + |
| 60 | + |
| 61 | +""" |
| 62 | +Sample Output: |
| 63 | +
|
| 64 | +ma:[0]:0.000000 0.000000 |
| 65 | +ma:[0,1]:0.500000 0.500000 |
| 66 | +ma:[0,1,4]:1.666667 1.699673 |
| 67 | +ma:[0,1,4,9]:3.500000 3.500000 |
| 68 | +ma:[0,1,4,9,16]:6.000000 5.899152 |
| 69 | +ma:[1,4,9,16,25]:11.000000 8.648699 |
| 70 | +ma:[4,9,16,25,36]:18.000000 11.436783 |
| 71 | +ma:[9,16,25,36,49]:27.000000 14.240786 |
| 72 | +ma:[16,25,36,49,64]:38.000000 17.052859 |
| 73 | +ma:[25,36,49,64,81]:51.000000 19.869575 |
| 74 | +""" |
0 commit comments