statistics.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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):
  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)
  12. class Corr(StatAggregate):
  13. function = 'CORR'
  14. class CovarPop(StatAggregate):
  15. def __init__(self, y, x, sample=False, filter=None):
  16. self.function = 'COVAR_SAMP' if sample else 'COVAR_POP'
  17. super().__init__(y, x, filter=filter)
  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. def convert_value(self, value, expression, connection):
  26. return 0 if value is None else value
  27. class RegrIntercept(StatAggregate):
  28. function = 'REGR_INTERCEPT'
  29. class RegrR2(StatAggregate):
  30. function = 'REGR_R2'
  31. class RegrSlope(StatAggregate):
  32. function = 'REGR_SLOPE'
  33. class RegrSXX(StatAggregate):
  34. function = 'REGR_SXX'
  35. class RegrSXY(StatAggregate):
  36. function = 'REGR_SXY'
  37. class RegrSYY(StatAggregate):
  38. function = 'REGR_SYY'