early_start.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from joblib import load
  2. from loguru import logger
  3. from sqlalchemy.orm import Session
  4. from app.api.errors.iot import MissingIOTDataError
  5. from app.core.config import settings
  6. from app.crud.model_path.early_start import model_path_early_start_dtr
  7. from app.models.domain.devices import ACATFCEarlyStartPredictionRequest
  8. from app.models.ml_models_path.early_start import EarlyStartDTRModelPath
  9. from app.schemas.season import Season
  10. class EarlyStartTimeDTRBuilder:
  11. """
  12. Build early start time by decision tree regression.
  13. """
  14. def __init__(self, model_path: EarlyStartDTRModelPath, season: Season):
  15. self.summer_model_path = (
  16. f"{settings.ML_MODELS_DIR}{model_path.summer_model_path}"
  17. )
  18. self.winter_model_path = (
  19. f"{settings.ML_MODELS_DIR}{model_path.winter_model_path}"
  20. )
  21. self.season = season
  22. async def get_prediction(self, indoor_temp: float, outdoor_temp: float) -> float:
  23. try:
  24. if self.season == Season.cooling:
  25. model = load(self.summer_model_path)
  26. elif self.season == Season.heating:
  27. model = load(self.winter_model_path)
  28. else:
  29. return 0
  30. except (FileNotFoundError, IsADirectoryError) as e:
  31. logger.debug(e)
  32. return 0
  33. try:
  34. pre = model.predict([[indoor_temp, outdoor_temp]])
  35. pre_time = pre[0]
  36. except (ValueError, IndexError) as e:
  37. logger.debug(e)
  38. pre_time = 0
  39. except TypeError:
  40. raise MissingIOTDataError
  41. return pre_time
  42. async def build_acatfc_early_start_prediction(params: ACATFCEarlyStartPredictionRequest, db: Session) -> float:
  43. model_path = model_path_early_start_dtr.get_path_by_device(db, params.device_id)
  44. builder = EarlyStartTimeDTRBuilder(model_path, params.season)
  45. hour = await builder.get_prediction(params.space_realtime_temperature, params.outdoor_realtime_temperature)
  46. return hour * 60