diff --git a/py_src/low_delta_t/handler.py b/py_src/low_delta_t/handler.py index 474776d..f7fe833 100644 --- a/py_src/low_delta_t/handler.py +++ b/py_src/low_delta_t/handler.py @@ -5,7 +5,7 @@ from datetime import timedelta import numpy as np from requests.exceptions import ConnectionError as RequestConnectionError, HTTPError -from python_lib.utils import parse_event, fetch_trends, build_index, build_df +from python_lib.utils import parse_event, fetch_trends, build_index, build_df, AnomalyError # the minimum acceptable length of the datapoints array MIN_DATAPOINTS_LENGTH = int(7 * 24) @@ -46,6 +46,8 @@ def run(event, _context): # compute estimated design load from max(tons) over past year max_tons = max(tons[point_name].values()) model_df = build_df(recent) + if any(x not in model_df for x in recent_points): + raise(AnomalyError(f"Missing trends from {recent_points}")) # model partial load ratio for the recent period from all fetched data model_df["PLR"] = model_df[tons_name] / max_tons # model partial temperature ratio @@ -53,15 +55,19 @@ def run(event, _context): # DTpred = PLR^0.173 * PT^0.067 * 15.603 model_df["DT_PRED"] = (model_df["PLR"] ** 0.173) * (model_df["PT"] ** 0.067) * 15.603 # compare actual delta-t with modeled normal, and detect anomaly if it falls below model by more than variance - actual_dt = np.sum(model_df[rtemp_name] - model_df[stemp_name]) - model_dt = np.sum(model_df["DT_PRED"]) + actual_dt = np.mean(model_df[rtemp_name] - model_df[stemp_name]) + model_dt = np.mean(model_df["DT_PRED"]) if actual_dt < model_dt * 0.9: - response[ "body" ] = f"""{point_name} actual_dt {actual_dt} model_dt {model_dt} for the period {start_time:%Y-%m-%d %H:%M} to {now:%Y-%m-%d %H:%M}""" + response[ "body" ] = f"""{point_name} actual_dt {actual_dt:.2f} model_dt {model_dt:.2f} for the period {start_time:%Y-%m-%d %H:%M} to {now:%Y-%m-%d %H:%M}""" except RequestConnectionError as err: response[ "body" ] = f"""{point_name} ConnectionError: {err.response.text} {start_time:%Y-%m-%d %H:%M} to {now:%Y-%m-%d %H:%M}""" + except AnomalyError as err: + response[ + "body" + ] = f"""{point_name} Error: {err} {start_time:%Y-%m-%d %H:%M} to {now:%Y-%m-%d %H:%M}""" except HTTPError as err: response[ "body" diff --git a/py_src/python_lib/utils.py b/py_src/python_lib/utils.py index abf2dc9..50733ca 100644 --- a/py_src/python_lib/utils.py +++ b/py_src/python_lib/utils.py @@ -12,6 +12,8 @@ PORTAL_API_URL = os.environ.get("PORTAL_API_URL", "/") QUERY_URL = f"{PORTAL_API_URL}query" +class AnomalyError(Exception): + "Anomaly Exception class" def parse_event(event): """