statistics.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. output_field = FloatField()
  9. def __init__(self, y, x, output_field=None, filter=None):
  10. if not x or not y:
  11. raise ValueError('Both y and x must be provided.')
  12. super().__init__(y, x, output_field=output_field, filter=filter)
  13. class Corr(StatAggregate):
  14. function = 'CORR'
  15. class CovarPop(StatAggregate):
  16. def __init__(self, y, x, sample=False, filter=None):
  17. self.function = 'COVAR_SAMP' if sample else 'COVAR_POP'
  18. super().__init__(y, x, filter=filter)
  19. class RegrAvgX(StatAggregate):
  20. function = 'REGR_AVGX'
  21. class RegrAvgY(StatAggregate):
  22. function = 'REGR_AVGY'
  23. class RegrCount(StatAggregate):
  24. function = 'REGR_COUNT'
  25. output_field = IntegerField()
  26. def convert_value(self, value, expression, connection):
  27. return 0 if value is None else value
  28. class RegrIntercept(StatAggregate):
  29. function = 'REGR_INTERCEPT'
  30. class RegrR2(StatAggregate):
  31. function = 'REGR_R2'
  32. class RegrSlope(StatAggregate):
  33. function = 'REGR_SLOPE'
  34. class RegrSXX(StatAggregate):
  35. function = 'REGR_SXX'
  36. class RegrSXY(StatAggregate):
  37. function = 'REGR_SXY'
  38. class RegrSYY(StatAggregate):
  39. function = 'REGR_SYY'