import tensorflow as tf import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler import os # Define the model path model_path = "models/lstm_energy_model" # Check if the model directory exists and load it if not os.path.exists(model_path): raise FileNotFoundError(f"Error: Model directory {model_path} does not exist. Please run train_lstm_model.py to generate the model.") try: model = tf.keras.models.load_model(model_path) print(f"✅ Model loaded successfully from {model_path}") except Exception as e: raise RuntimeError(f"Error loading model from {model_path}: {e}") def detect_energy_anomalies(file_path): """ Detect anomalies in energy generation data (time-series) using LSTM. Args: - file_path (str): Path to the CSV/JSON file containing energy generation data Returns: - anomaly (str): Energy anomaly detection result """ # Load energy generation data if not os.path.exists(file_path): raise FileNotFoundError(f"Error: Data file {file_path} not found.") try: data = pd.read_csv(file_path) except Exception as e: raise RuntimeError(f"Failed to load {file_path}: {e}") if 'energy_generation' not in data.columns: raise ValueError("CSV file must contain an 'energy_generation' column.") if len(data) < 60: raise ValueError(f"Dataset must have at least 60 rows for LSTM prediction. Found {len(data)} rows.") energy_data = data['energy_generation'].values.reshape(-1, 1) # Normalize data for LSTM scaler = MinMaxScaler(feature_range=(0, 1)) energy_data = scaler.fit_transform(energy_data) # Prepare data for LSTM X = [] for i in range(60, len(energy_data)): X.append(energy_data[i-60:i, 0]) X = np.array(X) if X.shape[0] == 0: raise ValueError("Not enough data points to prepare for LSTM prediction (need at least 60 time steps).") X = X.reshape((X.shape[0], X.shape[1], 1)) # Predict with LSTM model prediction = model.predict(X) last_predicted_value = prediction[-1][0] # Get last prediction # Define threshold for anomaly threshold = 0.1 anomaly = "Anomaly Detected" if abs(last_predicted_value - energy_data[-1][0]) > threshold else "No Anomaly" return anomaly