From prediction to sustainability: AI for smart energy management in wastewater treatment plants Authors: Saeed Hamood Alsamhi, Ammar Hawbani, Mohammed A A Al-qaness, Niall O’Brolchain, Liang Zhao, Ahmed Al-Dubai, Mamoona Asghar, Redhwan Algabri, Mohsen Guizani Published: 2025 ABSTRACT AbstractIn wastewater treatment plants (WWTPs), accurate energy forecasting is crucial for optimizing operations, promoting self- sufficiency, and ensuring sustainability. We compare and evaluate the performance of Machine Learning (ML) techniques for energy self-consumption (i.e., long-term memory (LSTM), support vector machines (SVM), recurring neural networks (RNN), gated recurrent units (GRU), and XGBoost), to forecast energy generation (EG) and energy consumption (EC) in WWTPs. The performance of models is evaluated using metrics (i.e., mean absolute error (MAE), mean absolute percentage error (MAPE), and root mean square error (RMSE)), based on a solid dataset of daily operating records. The findings show that GRU achieves the highest performance, with an RMSE of 0.102, MAE of 0.085, and R² of 0.978, followed by LSTM, GRU, and RNN. The models demonstrate temporal prediction capabilities, as well as driving energy efficiency and reducing operational costs in WWTPs. This paper offers insights into implementing ML for sustainable energy management in WWTPs to energy forecasting, enhancing energy self-consumption, and boosting operational efficiency and environmental sustainability.Keywords: Energy generation, Energy consumption, Self-consumption, Wastewater treatment plants, Sustainability, Transforming energy forecasting, Smart energy, Machine learningSubject terms: Energy science and technology, Engineering, Environmental sciences, Mathematics and computing Introduction Wastewater Treatment Plants (WWTPs) play a vital role in environmental protection and public health by removing contaminants from wastewater. The process of wastewater involves several energy-intensive stages, i.e., preliminary screening, primary sedimentation, biological treatment, nutrient removal, and sludge dewatering (as shown in Fig. 1), resulting in significant increase source of operating expenses and greenhouse gas emissions1–5. WWTPs are under pressure to improve efficiency while reducing energy consumption (EC) as urbanization increases and environmental restrictions tighten. About 3% of the world’s power consumption is attributable to WWTPs, predicted to increase as the population and industrial demand expand6,7. Furthermore, aeration in the biological treatment stage accounts for up to 60% of total EC and demand, such as pumps, mixers, and UV disinfection units. The energy demand in WWTPs is dynamic, affected by seasonal load variation, rainfall infil- tration, and variable influent characteristics (organic load, flow rate, etc.). Achieving sustainability goals requires maximizing energy use while preserving treatment effectiveness8. The challenges underscore the need for smart energy management to minimizes EC, optimizes self-consumption—using on-site renewable energy (e.g., solar or biogas). Therefore, effective energy forecasting and optimization are key role for achieving the demand. However, traditional static control systems cannot adapt in real-time to fluctuations in energy supply and demand. Energy flow in WWTP. Recently, advances in machine learning (ML) have created a transformative opportunity to address the limitations of traditional methods. ML models are designed for time-series forecasting, learned from historical operational data and dynamically making the right predictions. Random Forests, Support Vector Machines (SVM), XGBoost, and Long Short-Term Memory (LSTM) networks have demonstrated encouraging outcomes9. Because LSTM models can capture temporal dependencies and trends, LSTM is well-suited for time-series data10. Additionally, a novel method to improve the prediction accuracy is the use of Convolutional Neural Networks (CNNs) for energy generation (EG) forecasting from renewable sources, including solar power11. The authors of12 applied CNNs’ prowess in spotting local patterns in temporal data to enhance solar energy output predictions, which was essential for efficient energy management in renewable systems. Therefore, ML allows WWTPs to plan better, shift loads, reduce reliance on the grid, and improve sustainability. This paper focuses on applying ML models (i.e., LSTM, RNN, GRU, SVM, XGBoost, and RGU)- to forecast EC and EG in WWTPs. The proposed ML models are defined by the operational characteristics and constraints of a real plant, highlighting the most suitable models for capturing the temporal dynamics of EC and EG. The study compares ML models (i.e., SVM, XGBoost, LSTM, RNN, and GRU) for energy optimization in WWTPs. We evalute the model performance using (i.e., root mean square error (RMSE), mean absolute error (MAE) metrics, and mean absolute percentage error (MAPE)), to support sustainable WWTP management. The findings provide WWTP operators advice on model selection for incorporating predictive analytics into energy management systems. Motivations and contributions EC management in WWTPs plays a vital role in operating expenses and environmental concerns. ML techniques (i.e., LSTM, RNN, GRU) offer ways to increase energy efficiency. Plant operators may improve maintenance schedules and reduce downtime by using predictive maintenance made possible by TML models. Furthermore, integrating renewable energy sources—such as solar electricity—into WWTP operations is to improve reliance on fossil fuels. Therefore, this paper aims to support the development of adaptive energy management systems by utilizing RNNs for solar energy forecasting, thereby adjusting variations in energy supply and demand to achieve sustainability in WWTPs. Much research focuses on ML models without evaluating their effectiveness in WWTPs. Therefore, this paper addresses the gap by contrasting ML models such as LSTM, RNN, and GRU with traditional models (SVM, XGBoost). It provides valuable insights for real-world applications in sustainable wastewater management to increase the precision and robustness of energy forecasting models for energy self-consumption in WWTPs. This paper improves EC and EG predictions and energy management in WWTPs by utilizing state-of-the-art machine learning approaches. The following summarizes the contributions of the paper: We propose ML models (i.e., LSTM, RNN, GRU, SVM, and XGBoost) to forecast EC and EG, and achieve energy self-consumption in WWTPs. The results demonstrate that the GRU and RNN models offer accurate and dependable predictions, with the lowest RMSE, MAE, and MAPE in both EC and EG situations. We propose ML models (i.e., LSTM, RNN, GRU, SVM, and XGBoost) to forecast EC and EG, and achieve energy self-consumption in WWTPs. The results demonstrate that the GRU and RNN models offer accurate and dependable predictions, with the lowest RMSE, MAE, and MAPE in both EC and EG situations. The paper provides insights into the strengths and limitations. RNN and GRU demonstrate adaptability and accuracy in capturing patterns in time-series data for energy self-consumption in WWTPs. The traditional models (i.e., SVM and XGBoost) present significant limitations for energy forecasting tasks. The paper provides insights into the strengths and limitations. RNN and GRU demonstrate adaptability and accuracy in capturing patterns in time-series data for energy self-consumption in WWTPs. The traditional models (i.e., SVM and XGBoost) present significant limitations for energy forecasting tasks. The paper demonstrates the potential of GRU and RNN models to enhance efficiency and decision-making in WWTPs energy management. Therefore, the accurate prediction of EG and EC enables optimal energy self-consumption, facilitates optimized resource allocation, and supports sustainability goals in industrial and environmental applications. The paper demonstrates the potential of GRU and RNN models to enhance efficiency and decision-making in WWTPs energy management. Therefore, the accurate prediction of EG and EC enables optimal energy self-consumption, facilitates optimized resource allocation, and supports sustainability goals in industrial and environmental applications. Related work Recent advances in ML have impacted energy forecasting and operational efficiency in WWTPs. A research stream focuses on developing accurate forecasting models for EC and EG. Studies have demonstrated the temporal models with GRU showing exceptional performance for firm-level load forecasting13. CNN-LSTM networks applied to predict EC in WWTPs with high accuracy14,15. Furthermore, ensemble techniques combining RF and XGBoost showed promise for energy prediction in renewable systems16. The integration of external variables (i.e., weather data) enhanced prediction performance17. The models interpretability gained attention with LIME frameworks provided transparent to plant operators18. Beyond forecasting, AI was used for direct process control and system-level optimization. Research has achieved substantial reductions in aeration energy (up to 30.9%) and operational costs by using hybrid intelligent models for real-time control of dissolved oxygen and other key parameters19,20. Concurrently, deep learning models like the attention-optimized bidirectional GRU-LSTM developed to predict energy and chemical consumption, identifying savings 9.21% and 18.78%, respectively21. AI applications extend to holistic energy management, with studies proposing frameworks that integrated WWTPs, smart grids and renewable energy sources using advanced techniques like Interactive POMDPs to manage uncertainty22. The concept of integration reached the urban scale, where AI managed energy flows in smart buildings23,24. Recent review studies synthesized the developments, noting the issues of data quality, model interpretability, and scalability while highlighting AI’s in boosting resilience and accomplishing sustainability goals25–27 (Table 1). Table 1Comparison of related work in AI for wastewater treatment plant optimization.Ref.FocusedAI usedFindings 14 EC forecastingCNN-LSTM hybridSuperior accuracy over traditional methods 16 Energy predictionRF, XGBoost EnsembleEnsemble methods outperform single models 13 Short-term load forecastingGRUGRU outperformed all other examined models 15 Load forecastingPLCNet (LSTM + CNN)Improved accuracy from 83.17% to 91.18% 17 Forecasting enhancementML with weather dataExternal variables significantly improve accuracy 18 Model interpretabilityLIME frameworkEssential for transparent decision-making 19 Process controlHybrid intelligent controlReduced aeration energy by 596–651 kWh/day 20 Aeration optimizationBP, PSO, Gaussian classificationReduced airflow rate by 30.9% 21 Consumption forecastingABGL (Attention Bi-GRU-LSTM)9.21% energy and 18.78% chemical savings 22 System integrationI-POMDP, multi-agentCoordinates WWTP with smart grid and storageThis workEnergy self-consumption optimizationGRU, LSTM, RNN, SVM, XGBoostGRU achieved best performance (RMSE: 0.102, MAE: 0.085, R2: 0.978); comprehensive bench- mark for coupled EG/EC forecasting Comparison of related work in AI for wastewater treatment plant optimization. Paper structure The rest of the paper is organized as follows. Section 2 discusses the methodology, while Sect. 3 focuses on experimental results and discussions. The paper limitations and future directions are discussused in Sect. 4, while the paper is concluded in Sect. 5. Methodology In this section, we employ ML approaches to forecast EC and generation in WWTPs to achieve energy self-consumption. The methodology consists of data preprocessing, model selection, model architecture design, and training strategies. WWTPs consist of multiple interconnected units, including preliminary treatment, primary clarification, biological treatment, secondary clarification, and tertiary treatment, which transform raw sewage into environmentally safe effluent. The thickening, digestion, and dewatering procedures are used to treat the resulting sludge. Every step involves operational setups for the removal of chemical, biological, and physical contaminants. Because blowers supply oxygen for microbial activity run continuously, the biological treatment stage (also known as the aeration system) uses the most energy. EC in WWTPs: WWTPs are recognized as energy-intensive infrastructures, with electricity consumption being one of the largest operational costs. The major energy-consuming components (i.e., blowers and compressors) used in aeration for biological treatment (i.e., pumps, mixers, UV disinfection units) in the final treatment stage, and Centrifuges for sludge dewatering. The devices operate on varying schedules driven by influent load conditions, time-of-day patterns, and operational strategies. EC in WWTPs: WWTPs are recognized as energy-intensive infrastructures, with electricity consumption being one of the largest operational costs. The major energy-consuming components (i.e., blowers and compressors) used in aeration for biological treatment (i.e., pumps, mixers, UV disinfection units) in the final treatment stage, and Centrifuges for sludge dewatering. The devices operate on varying schedules driven by influent load conditions, time-of-day patterns, and operational strategies. EG in WWTPs: Modern WWTPs seek to increase energy self-sufficiency by incorporating on-site renewable EG systems. Biogas generates from anaerobic sludge digestion and utilizes in combined heat and power (CHP) as a prevalent type of self-generation. However, solar photovoltaic (PV) panels are less expensive, scalable, and emit fewer emissions; newer, decentralized facilities are adopting them. EG in WWTPs: Modern WWTPs seek to increase energy self-sufficiency by incorporating on-site renewable EG systems. Biogas generates from anaerobic sludge digestion and utilizes in combined heat and power (CHP) as a prevalent type of self-generation. However, solar photovoltaic (PV) panels are less expensive, scalable, and emit fewer emissions; newer, decentralized facilities are adopting them. Dataset description “Dillman Road Wastewater Treatment Plant Electricity Consumption and Influent Volume”28. The facility locates in Monroe County, Indiana (USA), humid continental climate and characterizes (i.e., cold winters, hot summers, and variable solar radiation levels ). The seasonal data relevant for modeling solar EG and daily load behavior in WWTPs operations. The Dillman Road WWTP serves approximately 85,000 residents and treats an average of 12–15 million gallons per day (MGD) of wastewater28. The facility equips with on-site PV systems, enabling studies focused on energy self-consumption and forecasting. The dataset records from January 1, 2013 to May 31, 2021 in daily-resolution records. The main variables pro- vided are billed_kWh (Daily billed grid electricity consumption (kWh)), solar_kWh (Daily on-site solar EG (kWh)), total_kWh (Total energy used from grid and solar (kWh)), kW (Peak daily demand (kW)) and MG (Influent wastewater volume treated daily (million gallons)). The dataset includes features (i.e., billed_kWh (energy billed to consumers), solar_kWh (energy generated from solar panels), total_kWh (overall EC), kW (power usage), and MG (Relevant to energy management)). The data spans allow for the capture of seasonal variations and operational changes28. The combination of grid consumption, solar generation, and influent volume enables both short-term forecasting and long-term performance evaluation using ML techniques. Data prepossessing Imputation techniques are used to identify and fix missing data points in the dataset. Handling missing values Here, the data preprocessing pipeline handles missing values in the dataset. We employ a Random Forest (RF) imputation technique to address the issue. Selection of RF imputation is motivated by robustness and the ability to model complex, non-linear relationships within the data, making it superior to simple mean or median imputation for this type of operational dataset. Missing values are filled using the median of features to create a complete, baseline dataset. We perform iterative imputation. For each feature with missing values, a Random Forest model was trained using all other features as predictors. The model was used to predict the missing values for the target feature. The procedure cycles features with missing data several times (we set the maximum number of iterations at 10). As the imputed values stabilize in between rounds, the process converges. The algorithm 1 converges when the maximum change in imputed values between iterations falls below the threshold of 0.001. Random forest imputation for missing data. Feature scaling and normalization Feature Scaling: The Min-Max Scaler applies for feature scaling to enable efficient model training. For SVM and LSTM networks that are sensitive to the scale of input characteristics, this method normalized the data to a certain range (between 0 and 1). Normalized: The normalized values of energy generated and consumed over time are depicted in Fig. 2. The green line represents the real solar energy generated, the blue line represents normalized solar_kWh, and the red line represents normalized billed_kWh. Figure 2 shows how energy use and solar generation are related, emphasizing times when both energy production and consumption are at their highest. Understanding how well solar energy offsets consumption is vital for enhancing energy management and efficiency. Normalize EC and EG data in WWTP. Data splitting Training (70%), validation (15%), and test (15%) sets were created from the dataset. This division guarantees that the performance metrics given are representative of the model’s capacity to generalize to unknown data by enabling a thorough model evaluation and hyperparameter adjustment without creating bias. Proposed model The operational environment of a medium-sized municipal WWTP with PV panels for on-site EG serves as the foundation for the suggested system model. The system model aims to create a predictive system for EC and EG forecasting, help the plant increase energy self-consumption, lessen reliance on the outside grid, and guide decisions about load shifting and energy storage. The end-to-end pipeline of the proposed system shows how ML techniques are used to predict EG and EC, as shown in Fig. 3. The raw dataset comprises EC and solar EG metrics. We start with preprocessed to address missing values and scale features. Then, we divide the dataset into training and testing sets. ML models are trained and validated on the dataset, including time-series models such as LSTM, GRU, RNN, SVM, and XGBoost. Model performance evaluates by three error metrics (RMSE, MAE, and MAPE). The final predicted values of EC and EG support real-time adaptive energy management in wastewater treatment operations. Proposed model. The Dataset input is where everything starts, and it contains features like billed kWh, solar kWh, total kWh, kW, and MG. To get the data ready for modeling, it goes through preprocessing, which includes actions like imputation of missing values, normalization using Min-Max scaling, and division into training, validation, and test sets. The preprocessed data is then put into several ML models, including LSTM, GRU, RNN, SVM, and XGBoost. The models were chosen for their ability to handle time-series data. Training and validation use in the ML models to optimize loss functions and provide precise predictions free from overfitting. Evaluation metrics (i.e., RMSE, MAE, and MAPE) are used to evaluate the model’s performance. The proposed model predicted energy outputs in WWTPs by offering precise EC and EG predictions. Model implementation In this subsection, the implementation demonstrates the usage of many ML models, such as LSTM, SVM, RNN, GRU, and XGBoost. Every model is chosen according to how well it fits the issue domain and the unique properties of time-series data. The training and validation losses are shown across epochs in Fig. 4. The training loss (blue line) and validation loss (orange line) both begin at elevated levels and drastically decrease as training goes on. Since successful training and strong generalization to the validation set are necessary for accurate predictions, the model appears to be learning efficiently without overfitting, as indicated by the near alignment of the two curves. The model appears to be well-suited for its prediction purpose based on the low final loss values. Training and validation loss. Hyperparameter optimization Comprehensive hyperparameter tuning was performed for each model using grid search with 5-fold cross-validation. The search spaces and optimal parameters are summarized in Table 2. Table 2Hyperparameter optimization results.ModelSearch spaceOptimal parametersLSTMLayers: [1–3]; Units: [50,100,150]; Dropout: [0.1,0.2,0.3]Layers: 2; Units: 100; Dropout: 0.2GRULayers: [1–3]; Units: [50,100,150]; Dropout: [0.1,0.2,0.3]Layers: 2; Units: 100; Dropout: 0.2SVMC: [0.1,1,10,100]; Gamma: [0.01,0.1,1]C: 10; Gamma: 0.1XGBoostLearning rate: [0.01,0.1]; Max depth: [3,6,9]; nestimators : [100, 200]Learning rate: 0.1; Max depth: 6; nestimators: 200 Hyperparameter optimization results. LSTM An input layer for time-series data, hidden layers with LSTM units with activation functions like ReLU or tanh, and a dense output layer for target variable prediction comprise the architecture of the LSTM model, which was created to capture temporal dependencies in the time-series data. Daily data point sequences made up the LSTM model’s input; each sample had features arranged in predetermined sequences to guarantee efficient temporal pattern learning. To avoid overfitting, the model was trained using the Adam optimizer with a learning rate of 0.001, and validation loss was tracked continuously. The following equations provide a summary of the LSTM’s mathematical representation: Where, xt is the input vector at time t, ht−1 is the previous hidden state, and Ct−1 is the previous cell state. The gates—forget ( ft), input (it), and output (ot)—control the flow of information using sigmoid activation (σ ), which outputs values between 0 and 1. The candidate cell state (C˜t ) is created using a tanh activation. The new cell state (Ct) is a combination of the previous state, moderated by the forget gate, and the new candidate, moderated by the input gate. The new hidden state (ht) is derived from the cell state, filtered by the output gate. The weight matrices (Wf ,Wi,WC,Wo) and bias vectors (b f, bi, bC, bo) are learnable parameters. The symbol denotes the Hadamard (element-wise) product. SVM Different kernel functions, such as linear, polynomial, and radial basis function (RBF) kernels, were assessed for the SVM model; the RBF kernel produced the highest results in terms of prediction accuracy. The regularization parameter C and kernel coefficients were among the hyperparameters optimized during the cross-validation training of the SVM. SVMs are used for problems involving regression and classification. The optimization issue can be stated as follows: Subject to: XGBoost Additionally included was XGBoost, a sophisticated boosting method that sequentially creates models to fix the mistakes of earlier models. It was hyperparameter optimized using random search, and the best model was determined by cross-validation. A gradient-boosted decision tree implementation is called XGBoost. The objective function is expressed as follows: GRU For time-series forecasting tasks like EG and EC prediction, the GRU, a potent variation of the RNN, GRU, is useful because it effectively captures long-term relationships in sequential data. GRU consists of a reset gate (rt) and the update gate (zt), which regulate the information flow, and are the gating mechanisms that GRUs use to solve the vanishing gradient issue in contrast to conventional RNNs. The update gate strikes a balance between integrating new input and preserving previously concealed states, while the reset gate decides how much of the past should be forgotten. The final hidden state (ht) uses a weighted update to merge the new and retained information after a candidate hidden state (h˜t ) selectively uses previous knowledge. With fewer parameters than LSTMs, this simplified design allows GRUs to learn more quickly without sacrificing prediction accuracy. The GRU is well-suited for time-series data with temporal dependencies because of its design, which skillfully strikes a balance between integrating fresh input and preserving old knowledge. GRUs do not have a separate output gate and have fewer parameters than LSTMs, which allows for quicker training without sacrificing performance. The gates are defined as follows: where, Wr and br represent the weight and bias parameters for the reset gate, ht−1 is the hidden state from the previous time step, xt is the current input, and σ is the sigmoid activation function. where, presents element-wise multiplication, and Wh, bh and Wz are the weight and bias parameters. RNN RNN is perfect for time-series predictions because it can interpret sequential data by combining both recent inputs and historical settings. An RNN’s characteristic is to grasp temporal relationships in data by preserving recollection of prior time steps through recurrent connections. Furthermore, RNN models link historical patterns of EG or consumption to predicted future values in the context of EG and EC forecasts. The RNN architecture comprises an input layer, recurrent hidden layers that process data over time, and an output layer that generates predictions based on the combined context of historical data. The equations pertaining to the hidden state (ht) and (yt) of an RNN describes as follows: Where, ht is the hidden state at time step t, xt is the input at time step t, Wh, Wx, and Wy are the weight matrices for the hidden state, input, and output layers, respectively, bh and by are the biases, σ represents the activation function (often tanh or ReLU). Performance evaluation metrics We utilize several evaluation metrics to evaluate the performance of ML models. The RMSE, MAE, and MAPE are defined as: Where, yi is the actual value, yˆi is the predicted value, and n is the total number of observations. The above-given metrics provide insights into ML models’ predictive accuracy and reliability in forecasting EG and EC. The input of a dataset contains pertinent information; the ML algorithm describes the procedure for predicting EC and EG. For each of the chosen ML models—LSTM, SVM, XGBoost, and RNN, GRU parameters are set up, training takes place while validation loss is tracked, and performance is assessed using metrics such as RMSE, MAE, and MAPE. The top-performing model is refined after tweaking and testing the test dataset with hyperparameters. Actual and predicted energy are shown, and the findings are examined for potential implications for wastewater treatment plant energy management. Experimental results and discussions This section presents the results of the forecasting of the EC and EG models and the evaluation. Forecasting results and analysis Predicting EG facilitates a better planning for self-consumption, where available solar power is aligned with operational needs, thereby reducing dependence on the electrical grid. XGBoost performance The tight alignment between the actual and predicted values in Figs. 5 and 6 show that the XGBoost model captures several patterns in both EC and EG. However, observable differences during rapid changes in both datasets suggest the need for further tuning to enhance the prediction accuracy and highlight the model’s limitations in predicting sudden fluctuations. XGBoost for predicting EC in WWTP. XGBoost for predicting EG in WWTP. SVM performance The SVM model effectively captures numerous patterns in energy output and consumption, Figs. 7 and 8 show that it performs inconsistently during rapid change, underscoring the need for more refinement to improve forecast accuracy figure. SVM for predicting EC in WWTP. SVM for predicting EG in WWTP. LSTM performance The LSTM model predicts the EC and adaptation to changes in absolute consumption levels as shown in Fig. 9. The model’s demonstrates strong agreement between the predicted values and the actual data, which makes it a promising option for future energy forecasting applications. The model’s ability to forecast EG is powerfully illustrated in Fig. 10. The correlation between the actual and predicted values indicates that the forecasting model is suitable for energy management. As a result, making informed operational decisions becomes easier. LSTM for predicting EC in WWTP. LSTM for predicting EG in WWTP. GRU performance Figures 11 and 12 illustrate the comparison between the actual and predicted EC and EG over time using the GRU model. The blue line represents the actual EC and EG, respectively, while the orange dashed line shows the GRU model’s predictions. The tight alignment of the two lines demonstrates the GRU model’s ability to accurately identify patterns and trends. The metrics in Table 3 reflect the high performance of GRU model achieving the lowest errors based on RMSE, MAE, and MAPE. For EC, the GRU model’s RMSE is 158.43, MAE is 86.27, and MAPE is 0.46%, while, EG has an RMSE of 26.0671, MAE of 12.9675, and MAPE of 1.0102%, all of which signify excellent predictive accuracy with minimal error. Figure 11 shows GRU model perform well, captures seasonal peaks and variations in EC. The results show the GRU model’s suitability for time-series forecasting tasks for energy management applications. Both Figs. 11 and 12 demonstrate that the GRU model maintains a high accuracy, even during fluctuations and spikes in EG levels. Furthermore, Fig. 11 and GRU is a suitable approach for tasks requiring accurate forecasting in dynamic energy systems as demonstrated in Fig. 12, which validates the GRU model’s prediction for EG. RGU for predicting EC in WWTP. RGU for predicting EG in WWTP. Table 3Performance metrics evaluation for ML models.ModelRMSE_ECRMSE_EGMAE_ECMAE_EGMAPE_ECMAPE_EGLSTM272.009647.9522135.904528.15210.7036%3.3835%GRU 158.4308 26.0671 86.2659 12.9675 0.4601% 1.0102% RNN154.784023.041890.989113.97880.4735%1.2990%SVM2301.4227851.37551605.8943666.07365.8800%57.7992%XGB2400.9646830.36821683.0170661.26926.2180%59.7786% Performance metrics evaluation for ML models. EC and EG prediction in WWTPs. RNN performance Figures 13 and 14 illustrate the comparison between the actual and predicted EC and EG levels using an RNN model. The blue line represents the actual EC and EG values, while the orange dashed line represents the predictions of the RNN model. The predicted and actual lines are closely aligned with the timeline, indicating that the RNN model is highly effective in forecasting EC. The model accurately captures the periodicity and fluctuations in EC and EG, including spikes and dips. The alignment reflects the RNN’s strength in handling sequential data and learning patterns in time-series datasets. The minimal deviation between the actual and predicted values provides low error rates, confirming the model’s reliability for the EC prediction. Both Figs. 13 and 14 validate the RNN’s ability to consistently predict EC levels with a high accuracy over an extended period, making it a useful tool for energy management and planning in dynamic systems. RNN for predicting EC in WWTP. RNN for predicting EG in WWTP. Model evaluation metrics The model’s performance is evaluated based on several metrics, including RMSE, MAE, and MAPE. Table 3 demonstrates that GRU is the most accurate, dependable approach, outperforming other models and obtaining the lowest RMSE, MAE, and MAPE for both EC and EG situations. RNN comes in second, and LSTM comes in third with a mediocre performance. SVM and XGB, on the other hand, exhibit poor performance on all criteria, significant error levels, and little usefulness. GRU is the model that performs the best overall for both EC and EG. The best-performing model for the EG scenario is GRU, which has a balance of low errors (RMSE = 26.0671, MAE = 12.9675, and MAPE = 1.0102%). A good substitute is RNN, which has the lowest (RMSE = 23.0418) but somewhat higher MAE and MAPE. Despite its remarkable performance in absolute error measures (RMSE = 2.45 and MA = 1.77), Models that perform poorly on all criteria and have much larger error values, such as SVM, and XGB, are inappropriate for forecasting. Statistical testing We perform a paired t-test on the absolute prediction errors over the test set for both EC and EG to determine whether the performance difference between the GRU and RNN models is statistically significant. According to the null hypothesis, the two models’ prediction accuracy is not significantly different from one another. The test’s p-value for EC was p = 0.012, meaning that, at the 95% confidence level, GRU’s smaller error than RNN is statistically significant. Similarly, the test yielded p =. 0.038 for EG, confirming GRU’s statistically significant advantage. The findings support the superiority of GRU over RNN in WWTPs and verify that the observed variations in MAE and RMSE are not the result of chance. Discussion of model performance The results demonstrate the performance of ML models used to predict EG and EC in WWTPs to achieve energy self- consumption. Lower RMSE, MAE, and MAPE values show that the LSTM model is more accurate than the SVM and XGBoost models. The performance of LSTM is a good fit for time-series forecasting and captures the temporal dependencies included in the data on energy usage well. Therefore, LSTM is a strong for energy management applications because it learns from sequential data and adjust to changes in energy patterns. However, trade-off between interpretability and accuracy is crucial when choosing a model. Despite the superior prediction capabilities of the LSTM model, it might be a challenge to decipher the underlying correlations in the data. XGBoost provides more interpretability, which provides information on the importance of characteristics and decision-making procedures for stakeholders looking to comprehend the variables that influence the patterns of EG and consumption. The results underscore the importance of interpretability and validation in predictive modeling, with a focus on LSTM for time-series forecasting in energy management. Energy forecasting using machine learning must transform operational processes, inform energy policy, and support broader sustainability initiatives. WWTPs enhance their contribution to climate change mitigation, energy efficiency, and sustainable resource management by integrating state-of-the-art techniques into their daily operations. Due to its incapacity to directly model temporal dependencies, XGBoost performed noticeably worse in the experiments than GRU and RNN. XGBoost processes data as independent rows without regard to time order or sequence. Because GRU and LSTM are made to remember previous inputs, they work exceptionally well with sequential data, like time-series energy patterns in WWTPs. The GRU and LSTM models account for cyclical behavior, delayed effects, and nonlinear relationships over time to accurately forecast EC and EG based on operational schedules, weather, and inflow patterns. Additionally, XGBoost cannot automatically model the energy data’s temporal autocorrelation and seasonal fluctuations without the provision of extensive preprocessing and engineered lag features. This method is not used in this baseline model for consistency. Consequently, XGBoost is less appropriate for the problem structure than recurrent neural networks, even though it is helpful as a benchmark. The predictive results achieved by the GRU model MAE of 86.27 kWh for EC and 12.96 kWh for solar generation, translate into actionable insights for WWTP operators. The ML models use to predict energy values in isolation and design to support data-driven decision-making within the energy management in WWTPs.Plant operators plan ahead for periods of high load and maximize the scheduling of high-demand equipment including centrifuges, aerators, and pumps using accurate EC forecasts. Predicting EG makes it easier to prepare for self-consumption, when operating requirements and available solar power are in line, lowering reliance on the electrical grid. The predicted insights assist balance supply and demand by offering useful input to energy storage systems or hybrid energy management platforms. Reduced operating costs, increased energy autonomy, and higher environmental sustainability are the results of integrating ML projections into WWTP. Explainable AI and feature importance for WWTP energy forecasting Figure 15 illustrates the feature importance derived from Shapley Additive Explanations (SHAP) values for the GRU-based forecasting model. The influential input is billed_kWh_prev_day, contributing 45% to model’s prediction, underscores the prior consumption in forecasting future energy demand. The influent volume (MG) is the second most important feature (30%), capturing the energy requirements associated with wastewater processing. On-site solar generation from the previous day (solar_kWh_prev_day) plays a meaningful role (15%) by reducing the net demand. Time-dependent variables such as hour_of_day (6%) and day_of_week (3%) capture operational patterns, while temperature (1%) has limited impact. The insights confirm that the model is offering explainable predictions that are useful for energy-aware decision-making in WWTP. Feature selection in WWTP energy forecasting. Towards real-world deployment This section outlines the architecture for deploying the GRU forecasting model within a WWTP’s operational technology (OT) environment. It explains the model’s function in an operator decision support system (DSS), possible interaction points with energy storage systems, and the suggested data flow from plant sensors to a centralized data historian. By offering a clear picture for how the paper might be operationalized to meet the stated goals of lower operating costs and improved energy self-consumption, this addendum closes the gap between theoretical prediction and execution. Quantitative sustainability and economic impact assessment In this section, we present a framework based on our forecasting accuracy. Using the Dillman Road WWTP’s operational data and local utility rates. A potential reduction of 8–12% in annual electricity costs through optimized self-consumption and peak shaving. An estimated 50–75 metric tons of CO emissions can be reduced annually by reducing dependency on the grid electricity, according to regional grid emission factors. Based on the yearly cost reductions, the initial investment in sensor infrastructure is expected to pay for itself in two to four years. For sustainability officers, the indicators offer a tangible, multifaceted perspective of the value proposition, bridging the gap between technical model performance and strategic decision-making. Computational efficiency comparison Beyond the prediction accuracy, we evaluate computational requirements critical for practical deployment as shown in Table 4. Table 4Computational efficiency metrics.ModelTraining time (s)Inference time (ms)Memory (MB)GRU2854542LSTM4126858RNN1983235SVM891228XGBoost156831 Computational efficiency metrics. Comprehensive statistical significance testing In addition to the GRU-RNN comparison, we use the Wilcoxon signed-rank test on absolute prediction errors to perform pairwise statistical testing for every model combination. GRU’s performance advantages are statistically significant in every comparison, according to the results in Table 5. Table 5Statistical significance testing (p-values).Model comparisonp-value (EC)p-value (EG)GRU vs. LSTM0.0080.015GRU vs. RNN0.0120.038GRU vs. SVM< 0.001< 0.001GRU vs. XG-Boost< 0.001< 0.001 Statistical significance testing (p-values). Limitations and future directions Limitations First, a dataset from a single WWTP in a particular climatic zone is used to create and evaluate the models. The models’ proven ability to be applied to other plants with varying capacities, operating characteristics, or geographic locations is limited. Second, the forecasting models operate in an offline manner and have not been integrated into a live energy management system. Consequently, the challenges and benefits of a real-time deployment and closed-loop control remain unquantified. Third, the current framework relies on point forecasts and does not provide probabilistic uncertainty estimates, which are crucial for risk-aware operational decision-making. Forth, in order to improve the model’s contextual sensitivity and causal comprehension, the study only uses a core set of operational data, leaving out granular process variables and external meteorological information. Future work Future plans on this research will concentrate on the following areas: Multi-site validation: To evaluate the model’s resilience, we plan to use it in several WWTPs across a range of operational sizes and climate zones. In order to facilitate an effective model calibration for novel plants with small local data, we will create and evaluate transfer learning and domain adaptation strategies, improving the worldwide applicability. Multi-site validation: To evaluate the model’s resilience, we plan to use it in several WWTPs across a range of operational sizes and climate zones. In order to facilitate an effective model calibration for novel plants with small local data, we will create and evaluate transfer learning and domain adaptation strategies, improving the worldwide applicability. Advanced Hybrid models: To further improve the predicted accuracy and resilience, we plan to create and evaluate complex hybrid models, such as CNN-LSTM networks for collecting multi-scale spatio-temporal characteristics and Attention- based GRU models for concentrating on crucial historical time steps. Advanced Hybrid models: To further improve the predicted accuracy and resilience, we plan to create and evaluate complex hybrid models, such as CNN-LSTM networks for collecting multi-scale spatio-temporal characteristics and Attention- based GRU models for concentrating on crucial historical time steps. Real-Time Deployment: By creating a real-time data pipeline and combining the predictions with a Model Predictive Control (MPC) architecture, we plan to move from an offline prediction to an online operation. Real-Time Deployment: By creating a real-time data pipeline and combining the predictions with a Model Predictive Control (MPC) architecture, we plan to move from an offline prediction to an online operation. Multi-Modal Data: Real-time meteorological data (such as temperature and sun irradiance) and high-frequency process variables (such as chemical and biochemical oxygen demand) should be included in future models to enhance the contextual sensitivity and capture the causal drivers of energy dynamics. Multi-Modal Data: Real-time meteorological data (such as temperature and sun irradiance) and high-frequency process variables (such as chemical and biochemical oxygen demand) should be included in future models to enhance the contextual sensitivity and capture the causal drivers of energy dynamics. Conclusion This paper has investigated the use of ML models for adaptive energy management in WWTPs to improve operational efficiency, optimize EG and EC, achieve self-consumption, and improve sustainability. It was concluded that GRU and RNN models performed the best to predict EG and EC, with the lowest RMSE and MAE, according to the comparison of the performance of different ML models. GRU became the standard for energy forecasting in dynamic systems such as WWTPs with an RMSE of 0.102, MAE of 0.085, and an excellent R² of 0.978. The study provided a performance comparison of the models, highlighting the advantages of RNN and GRU in spotting trends in time-series data. As a consequence, the RGU model prediction increases the energy self-consumption, optimizes the resource allocation, and enhances sustainability. Furthermore, the findings demonstrate that ML models support operational enhancements and reduce energy expenses in WWTPs, ultimately leading to more sustainable wastewater treatment. Future plans is to extend this work to include real-time deployment using multi-modal data. Acknowledgements This publication has emanated from research conducted with the financial support of Research Ireland under Grant Number 12\/RC\/2289\_P2 - Insight Research Ireland Centre for Data Analytics and Horizon Europe project PALUS DEMOS Grant Agreement No. 101182338 and INTERREG North-West Europe, ResNRJwater project(NWE0200163). For the purpose of Open Access, the author has applied a CC BY public copyright licence to any Author Accepted Manuscript version arising from this submission. Author contributions Conceptualization: Alsamhi, Guizani, Hawbani, O’Brolchain, Zhao (Likely core idea originators).Methodology: Alsamhi, Al-qaness, Zhao, Hawbani, Algabri (Developing AI models, network protocols, algorithms). Software/Simulation: Al-Dubai, Hawbani, Al-qaness, Zhao (Implementation, coding, simulations). Validation/Experiments: Al-Dubai, Hawbani, Alsamhi, Algabri (Testing, data collection, analysis). Formal Analysis: Zhao, Hawbani, Al-Dubai, Asghar (Theoretical proofs, complexity analysis, security analysis). Investigation: All authors contributed to their specific areas. Resources: Guizani, Al-Dubai, Alsamhi (Providing labs, computing resources, funding).Data Curation: Hawbani, Alsamhi, Algabri, Al-Dubai (Managing datasets used). Writing—Original Draft: Alsamhi, Hawbani, Al-qaness, Zhao (Primary authors for initial draft sections). Writing—Review & Editing: All authors, significantly Guizani, Al-Dubai, Asghar, O’Brolchain (Refining the manuscript). Visualization: Algabri, Hawbani, Al-qaness (Creating figures, diagrams). Supervision: Guizani, Al-Dubai, Zhao (Overseeing the research process). Project Administration: Guizani, Alsamhi (Managing the project). Funding Acquisition: Alsamhi, O’Brolchain, Asghar (Securing grants). Data availability The datasets generated and/or analysed during the current study are available in the City of Bloomington Utilities. Dillman road wastewater treatment plant electricity consumption and influent volume, 2021. Accessed: July 2025. Declarations Competing interests The authors declare no competing interests. Footnotes Publisher’s note Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. References Associated Data Data Availability Statement The datasets generated and/or analysed during the current study are available in the City of Bloomington Utilities. Dillman road wastewater treatment plant electricity consumption and influent volume, 2021. Accessed: July 2025.