statistics.py 1.5 KB

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