montly_precip.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from datetime import datetime
  2. from pprint import pprint
  3. from config.settings import DECIMAL_PLACES
  4. from cruds.measures import get_finca_measures
  5. from database.mongo import mongo_measures
  6. from routes.calculations.pipelines import count_precip_measures_pipeline, get_percent
  7. from schemas.fincas import FincaBase as FincaBaseSchema
  8. from schemas.tables import MonthlyPrecipitations as MonthlyPrecipitationsSchema
  9. def montly_precipitations(
  10. finca: FincaBaseSchema, start_datetime: datetime, end_datetime: datetime
  11. ) -> MonthlyPrecipitationsSchema:
  12. finca_data = mongo_measures[finca.station_code]
  13. accumulated_precip_agg = finca_data.aggregate(
  14. [
  15. {
  16. "$match": {
  17. "date": {
  18. "$gte": start_datetime,
  19. "$lte": end_datetime,
  20. },
  21. "precip": {"$ne": None},
  22. },
  23. },
  24. {
  25. "$group": {
  26. "_id": {
  27. "month": {"$month": "$date"},
  28. "year": {"$year": "$date"},
  29. },
  30. "sumPrecip": {"$sum": "$precip"},
  31. }
  32. },
  33. ]
  34. )
  35. accumulated_precip = list(accumulated_precip_agg)
  36. data_count = finca_data.count(
  37. count_precip_measures_pipeline(start_datetime, end_datetime)
  38. )
  39. total_count = (end_datetime - start_datetime).total_seconds() // (60 * 10)
  40. data_percentage = get_percent(data_count, total_count)
  41. months = {}
  42. for month in accumulated_precip:
  43. value = month.get("sumPrecip")
  44. if value is not None:
  45. value = round(value, DECIMAL_PLACES)
  46. months[str(month.get("_id", {}).get("month"))] = value
  47. summary = MonthlyPrecipitationsSchema(
  48. station=FincaBaseSchema(
  49. station_code=finca.station_code,
  50. title=finca.title,
  51. ),
  52. initial_date=start_datetime,
  53. final_date=end_datetime,
  54. months=months,
  55. data_percentage=data_percentage,
  56. )
  57. return summary