You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

statistics.py 2.0 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from django.db.models import FloatField, IntegerField
  2. from django.db.models.aggregates import Aggregate
  3. __all__ = [
  4. 'CovarPop', 'Corr', 'RegrAvgX', 'RegrAvgY', 'RegrCount', 'RegrIntercept',
  5. 'RegrR2', 'RegrSlope', 'RegrSXX', 'RegrSXY', 'RegrSYY', 'StatAggregate',
  6. ]
  7. class StatAggregate(Aggregate):
  8. def __init__(self, y, x, output_field=FloatField()):
  9. if not x or not y:
  10. raise ValueError('Both y and x must be provided.')
  11. super(StatAggregate, self).__init__(y=y, x=x, output_field=output_field)
  12. self.x = x
  13. self.y = y
  14. self.source_expressions = self._parse_expressions(self.y, self.x)
  15. def get_source_expressions(self):
  16. return self.y, self.x
  17. def set_source_expressions(self, exprs):
  18. self.y, self.x = exprs
  19. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  20. return super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
  21. class Corr(StatAggregate):
  22. function = 'CORR'
  23. class CovarPop(StatAggregate):
  24. def __init__(self, y, x, sample=False):
  25. self.function = 'COVAR_SAMP' if sample else 'COVAR_POP'
  26. super(CovarPop, self).__init__(y, x)
  27. class RegrAvgX(StatAggregate):
  28. function = 'REGR_AVGX'
  29. class RegrAvgY(StatAggregate):
  30. function = 'REGR_AVGY'
  31. class RegrCount(StatAggregate):
  32. function = 'REGR_COUNT'
  33. def __init__(self, y, x):
  34. super(RegrCount, self).__init__(y=y, x=x, output_field=IntegerField())
  35. def convert_value(self, value, expression, connection, context):
  36. if value is None:
  37. return 0
  38. return int(value)
  39. class RegrIntercept(StatAggregate):
  40. function = 'REGR_INTERCEPT'
  41. class RegrR2(StatAggregate):
  42. function = 'REGR_R2'
  43. class RegrSlope(StatAggregate):
  44. function = 'REGR_SLOPE'
  45. class RegrSXX(StatAggregate):
  46. function = 'REGR_SXX'
  47. class RegrSXY(StatAggregate):
  48. function = 'REGR_SXY'
  49. class RegrSYY(StatAggregate):
  50. function = 'REGR_SYY'