Created
September 17, 2018 07:47
-
-
Save thelonecabbage/0315f75df4c28d55b919bb03e5b31b9b to your computer and use it in GitHub Desktop.
Integer Only Sampling Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Sample(): | |
def __init__(self, values=None, *args, **kwargs): | |
self.reset(values) | |
def reset(self, values=None): | |
values = values or (0, 0, None, None, None, 0) | |
(self._total, self._cnt, self._min, self._max, self._first, self._ex2) = values | |
def append(self, value): | |
# self._all.append(value) | |
self._total += value | |
self._cnt += 1 | |
if self._min is None or self._min < value: | |
self._min = value | |
if self._max is None or self._max > value: | |
self._max = value | |
self._variance(value) | |
def _variance(self, value): | |
if self._first is None: | |
self._first = value | |
else: | |
delta = value - self._first | |
self._ex2 += delta ** 2 | |
@property | |
def _ex(self): | |
return self._total - self._first * self._cnt | |
@property | |
def variance(self): | |
vv = 0 | |
if self._cnt == 0: | |
vv = 0 | |
elif self._cnt > 100: | |
vv = (self._ex2 - (self._ex ** 2) / self._cnt) / (self._cnt - 1) | |
else: | |
vv = (self._ex2 - (self._ex ** 2) / self._cnt) / (self._cnt) | |
return vv | |
@property | |
def standard_deviation(self): | |
return self.variance ** 0.5 | |
@property | |
def avg(self): | |
total = self._total | |
cnt = self._cnt | |
if self._cnt == 0: | |
cnt = 1 | |
elif self._cnt >= 3: | |
total -= (self._min + self._max) | |
cnt -= 2 | |
return total / cnt | |
@property | |
def tuple(self): | |
return (self._total, self._cnt, self._min, self._max, self._first, self._ex2) | |
@property | |
def json(self): | |
return { | |
'total': self._total, | |
'count': self._cnt, | |
'min': self._min, | |
'max': self._max, | |
'first': self._first, | |
'ex2': self._ex2} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Class is intended for micropython based micro-controllers. The identical class can be run on a server, to rehydrate an identical instance.
Floating point calculations are only done in properties intended to be called from the server instance (or JIT on the MCU).
The class can record a large number of samples, without increasing memory footprint or CPU usage.
Keeps average with largest and smallest values removed, as well as Standard Deviation.