statistics.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from django.db.models import Aggregate, FloatField, IntegerField
  2. __all__ = [
  3. 'CovarPop', 'Corr', 'RegrAvgX', 'RegrAvgY', 'RegrCount', 'RegrIntercept',
  4. 'RegrR2', 'RegrSlope', 'RegrSXX', 'RegrSXY', 'RegrSYY', 'StatAggregate',
  5. ]
  6. class StatAggregate(Aggregate):
  7. output_field = FloatField()
  8. def __init__(self, y, x, output_field=None, filter=None, default=None):
  9. if not x or not y:
  10. raise ValueError('Both y and x must be provided.')
  11. super().__init__(y, x, output_field=output_field, filter=filter, default=default)
  12. class Corr(StatAggregate):
  13. function = 'CORR'
  14. class CovarPop(StatAggregate):
  15. def __init__(self, y, x, sample=False, filter=None, default=None):
  16. self.function = 'COVAR_SAMP' if sample else 'COVAR_POP'
  17. super().__init__(y, x, filter=filter, default=default)
  18. class RegrAvgX(StatAggregate):
  19. function = 'REGR_AVGX'
  20. class RegrAvgY(StatAggregate):
  21. function = 'REGR_AVGY'
  22. class RegrCount(StatAggregate):
  23. function = 'REGR_COUNT'
  24. output_field = IntegerField()
  25. empty_result_set_value = 0
  26. class RegrIntercept(StatAggregate):
  27. function = 'REGR_INTERCEPT'
  28. class RegrR2(StatAggregate):
  29. function = 'REGR_R2'
  30. class RegrSlope(StatAggregate):
  31. function = 'REGR_SLOPE'
  32. class RegrSXX(StatAggregate):
  33. function = 'REGR_SXX'
  34. class RegrSXY(StatAggregate):
  35. function = 'REGR_SXY'
  36. class RegrSYY(StatAggregate):
  37. function = 'REGR_SYY'