import logging import numbers import os import time try: from config import APP_NAME as ROOT_LOGGER_NAME except ImportError: ROOT_LOGGER_NAME = 'root' logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__) class continues_statistic(dict): def __init__(self, mean=None, min_val=None, max_val=None, quantifier=None): dict.__init__(self) if mean is None: self.__init_data__(None, None, None, None) elif min_val is not None and max_val is not None and quantifier is not None: self.__init_data__(mean, min_val, max_val, quantifier) else: self.__init_data__(mean, mean, mean, 1) def __init_data__(self, mean, min_val, max_val, quantifier): self['quantifier'] = quantifier self['max_val'] = max_val self['min_val'] = min_val self['mean'] = mean def expand(self, value): if self['quantifier'] is None: self.__init_data__(value, value, value, 1) else: cs_sum = self + continues_statistic(value) for key in self: self[key] = cs_sum[key] def __add__(self, other): rv = continues_statistic() rv['mean'] = (self.mean * self.quantifier + other.mean * other.quantifier) / (self.quantifier + other.quantifier) rv['min_val'] = min(self.min, other.min) rv['max_val'] = max(self.max, other.max) rv['quantifier'] = self.quantifier + other.quantifier return rv @property def mean(self): return self.get('mean') @property def min(self): return self.get('min_val') @property def max(self): return self.get('max_val') @property def quantifier(self): return self.get('quantifier') def pop(self): rv = continues_statistic(self.mean, self.min, self.max, self.quantifier) self.__init_data__(None, None, None, None) return rv def __str__(self): return "mean=%(mean)s, min=%(min_val)s, max=%(max_val)s, quantifier=%(quantifier)s" % self class continues_statistic_multivalue(dict): def __init__(self, **kwargs): dict.__init__(self) for key in kwargs: if type(kwargs[key]) is continues_statistic: self[key] = kwargs[key] elif type(kwargs[key]) is dict: self[key] = continues_statistic(**kwargs[key]) else: self[key] = continues_statistic(kwargs[key]) def expand(self, **kwargs): for key in kwargs: if key in self: self[key].expand(kwargs[key]) else: self[key] = continues_statistic(kwargs[key]) def pop(self, key=None): if key is None: rv = continues_statistic_multivalue(**self) self.clear() return rv else: return self[key].pop() def __str__(self): return '\n'.join([key + ': ' + str(self[key]) for key in self]) class ringbuffer(list): def __init__(self, *args, **kwargs): self.__max_length__ = kwargs.pop('length') list.__init__(self, *args, **kwargs) self.__reduce_list__() def __reduce_list__(self): while len(self) > self.__max_length__: self.pop(0) def append(self, *args, **kwargs): rv = list.append(self, *args, **kwargs) self.__reduce_list__() return rv