| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- from datetime import datetime
- from pprint import pprint
- from config.settings import DECIMAL_PLACES
- from database.mongo import mongo_measures
- from routes.calculations.pipelines import count_temp_measures_pipeline, get_percent
- from schemas.fincas import FincaBase as FincaBaseSchema
- from schemas.tables import (
- DegreesAccumulatedAvgMonth as DegreesAccumulatedAvgMonthSchema,
- )
- def ensure_non_empty(result, key):
- """
- Ensures that the result list is not empty and that we are not rounding None
- """
- if len(result) > 0:
- value = result[0].get(key)
- if value is not None:
- return round(value, 2)
- def monthly_avr_day_degrees(
- finca: FincaBaseSchema, start_datetime: datetime, end_datetime: datetime
- ) -> DegreesAccumulatedAvgMonthSchema:
- finca_data = mongo_measures[finca.station_code]
- degrees_accumulated_agg = finca_data.aggregate(
- [
- {
- "$match": {
- "date": {
- "$gte": start_datetime,
- "$lte": end_datetime,
- },
- "temp": {"$ne": None},
- },
- },
- {
- "$group": {
- "_id": {
- "day": {"$dayOfMonth": "$date"},
- "month": {"$month": "$date"},
- "year": {"$year": "$date"},
- },
- "dailyDegrees": {"$avg": "$temp"},
- }
- },
- {
- "$set": {
- "dailyDegrees": {
- "$cond": [
- {"$gt": ["$dailyDegrees", 10]},
- {"$add": ["$dailyDegrees", -10]},
- 0,
- ],
- }
- }
- },
- {
- "$group": {
- "_id": {
- "month": "$_id.month",
- "year": "$_id.year",
- },
- "avgDailyDegrees": {"$avg": "$dailyDegrees"},
- }
- },
- ]
- )
- degrees_accumulated = list(degrees_accumulated_agg)
- months = {}
- for month in degrees_accumulated:
- value = month.get("avgDailyDegrees")
- if value is not None:
- value = round(value, DECIMAL_PLACES)
- months[str(month.get("_id", {}).get("month"))] = value
- data_count = finca_data.count(
- count_temp_measures_pipeline(start_datetime, end_datetime)
- )
- total_count = (end_datetime - start_datetime).total_seconds() // (60 * 10)
- data_percentage = get_percent(data_count, total_count)
- summary = DegreesAccumulatedAvgMonthSchema(
- station=FincaBaseSchema(
- station_code=finca.station_code,
- title=finca.title,
- ),
- initial_date=start_datetime,
- final_date=end_datetime,
- months=months,
- data_percentage=data_percentage,
- )
- return summary
|