{'fraction_non_alphanumeric': 0.02394550816909321, 'fraction_numerical': 0.006179485979120828, 'mean_word_length': 4.719277108433735, 'pattern_counts': {'":': 0, '<': 1, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Deep Reinforcement Learning for Real-Time Optimization of Pumps in Water Distribution Systems

Real-time control of pumps can be an infeasible task in water distribution systems (WDSs) because the calculation to find the optimal pump speeds is resource-intensive. The computational need cannot be lowered even with the capabilities of smart water networks when conventional optimization techniques are used. Deep reinforcement learning (DRL) is presented here as a controller of pumps in two WDSs. An agent based on a dueling deep q-network is trained to maintain the pump speeds based on instantaneous nodal pressure data. General optimization techniques (e.g., Nelder-Mead method, differential evolution) serve as baselines. The total efficiency achieved by the DRL agent compared to the best performing baseline is above 0.98, whereas the speedup is around 2x compared to that. The main contribution of the presented approach is that the agent can run the pumps in real-time because it depends only on measurement data. If the WDS is replaced with a hydraulic simulation, the agent still outperforms conventional techniques in search speed.


Introduction
Ongoing efforts in the development of online measurement sensors and data acquisition [1] let new techniques emerge in real-time control of water distribution systems (WDSs). The need for smart water networks and economic water supply is motivated mostly by the rapidly growing and urbanizing human population ( [2] and [3]). Ever-growing water networks challenge operators in achieving cost-effective, yet satisfactory operation. According to the comprehensive literature review of Mala-Jetmarova et al. [4], operation optimization is the third most active topic among water supply-related applications.
Operation optimization is often treated as a pump scheduling problem, where dynamic programming (DP) methods are widely utilized because they are able to provide the global optimum if the number of variables is low. The iterative DP method [5] is able to cope with the curse of dimensionality in large WDSs but its application is restricted to convex objective functions. A more recent work by Bene [6] introduces a method based on discrete dynamic programming that finds the optimal pump scheduling for medium-sized water networks. However, the multiple restrictions on the problem definition shows that modern variants of dynamic programming are computationally still too expensive.
Savic et al. [7] found that many state-of-the-art (SOTA) optimization techniques in WDS operation optimization involves some kind of metaheuristics. Ritter et al. [8] presents a multiobjective direct policy search technique where different heuristic approaches share the individuals of a population among different metaheuristics. This way the different beneficial properties are combined from different metaheuristics but incorrectly chosen hyperprameters of the distinct methods can alter the whole optimization process.
Moreover, these methods require a high amount of hydraulic evaluation which makes the use of surrogate models a reasonable approach. Surrogate models are approximation models that are computationally cheaper than the corresponding -physically valid -numerical simulation. The input of a surrogate model is usually the same as for the simulation (e.g. boundary and initial conditions) but its output is restricted to just a handful of variables.
Surrogate models with high complexity (e.g. Gaussian process regression, artificial neural networks, k-nearest neighbors) are found to be misleading for non-convex objective functions as these smooth the response surface that leads to suboptimal solutions [9]. In concordance, Razavi et al. [10] shows for water network simulations that substitutes with less complexity are more robust in cases where an unseen part of the explanatory variable space has to be discovered. Machell et al. [11] introduces a hybrid approach where, the governing equations of the hydraulic simulation are supported with an extended number of boundary conditions that reduces the computation cost of the hydraulic model. The additional information is extracted from online sensory data including pressure and flow rate measures.
Optimization convergence can be enhanced by improving the optimum search itself to reduce the time of the overall process. A promising branch of these efforts is about finding the optimal parameters of the optimization algorithm. These parameters are called hyperparameters, and methods that optimize these hyperparameters during the single optimization process are referred to as hyperheuristic methods [7]. McClymont et al. [12] present a Markov chain-based approximator that is superior in finding optimal hyperheuristics compared to Simple Random and TSRoulWheel methods.
Though heuristics are robust in finding the global optima, the computational burden is still too high for real-life WDSs. Model predictive control ( [13] and [14]) overcomes the computational issue by using a two-layer optimization approach where the layers predict optimal ON-OFF schedules for pumps and valves in different time horizons. The method is able to run large WDSs in real-time, the capabilities are presented on the example of the water network of Barcelona. Iterative extended lexicographic programming (iELGP), introduced by Abdallah and Kapelan [15] and Abdallah and Kapelan [16] copes even with continuous decision variables like the set-point of variable speed pumps (VSPs) and chlorine dosing machines. With iELGP, Abdallah and Kapelan [16] achieved SOTA performance on the C-Town benchmark problem wherein both fixed-speed and variable speed pumps were presented.
Water distribution system operation also benefits from recent advances in machine learning. Artificial neural networks are used in a wide variety of applications from demand forecast [17] through attack detection [18] to pump scheduling [19].
Bhattacharya et al. [19] uses an ANN-based reinforcement learning agent as an optimal controller for switching on or off pumps in a water network. The input of the ANN is water levels in reservoirs besides the water demand in the WDS, while its output is the decision about a pump to operate it or not. The neural network is trained with reinforcement learning (RL) in a manner the RL agent is encouraged to replicate the moves of the master controller algorithm.
Mahootchi et al. [20] introduces an agent, based on reinforcement learning for the control of one reservoir in a water distribution network and finds that the RL approach achieves comparable results to stochastic dynamic programming in the benchmark case.
A sophisticated optimization technique is introduced by Castelletti et al. [21] for multiobjective tasks, where the importance of the standalone objectives is unknown or uncertain at the beginning of the optimization. Recombining these objectives yields a different optimal solution, hence a movement on the Pareto frontier. Castelletti et al. [21] approximate the optimal policy with fitted q-iteration (FQI) during an optimization run but also add the weights of the standalone objectives to the state space of the environment used in FQI. The approximation of the optimal policy is constructed as the function of the importance weights, and the frontier can be drawn from one single run with sampling the weight space as well.
All the pump scheduling methods above rely on the simulation of the water distribution system that limits their usability when the size or the complexity of the water network is too large. The most resource-intensive method is finding optimal pump speeds for a time step since the descriptive variables are continuous and the evaluation of every trial needs to run the hydraulic simulation as well.
A reinforcement learning agent for real-time control for vari-able speed pumps is presented in this paper. The pump scheduling problem is omitted and only the optimum speed search for a given demand-distribution is realized in a smart water network. A significant novelty of the method is that the hydraulic simulation of the WDS is not needed for the controller because it relies only on measurement data. Moreover, the training is carried out in such a way that the agent is able to develop different policies compared to the reference, so that the agent can outperform the master algorithm it was trained with. If online pressure data are not available, the hydraulic simulation of the water distribution system can be used as a surrogate of the real WDS, like in the case of existing optimization methods. In such cases, the agent-based control is able to outperform current optimization techniques in the number of hydraulic model evaluation. As the proposed technique is able to cope with multiple objectives with a simple weighted sum of objectives, it can serve as the optimal pump speed search algorithm in hybrid pump schedule optimization solutions. The paper is organized as follows. First, the simplified problem is introduced including the reference methods. The details of reinforcement learning methodology are described thereafter. Then, the settings of the case study, including the water distribution networks and the training settings are presented. The performance of the agent is evaluated on the WDSs and the conclusions of the training are drawn. Finally, the key findings and possible applications are mentioned.

Problem definition and reference solutions
The present study aims at providing optimal set-points for variable speed pumps in a WDS according to given nodal pressures. Hence, the conventional pump scheduling problem is simplified and the problem is formulated as follows.
Instantaneous operation point optimization is carried out neglecting temporal changes in the demand. The competing algorithms have to find the optimal pump speeds in terms of hydraulic efficiency with respect to randomly generated demands. Besides, the inflow and outflow into and from the tanks should be minimized, and pressure (head) should be kept in a specific range in all of the nodes. Customer satisfaction implies a lower pressure limit, while the mechanical strength of water fittings and other elements of the water network implies an upper limit as well.
These objectives are formulated into a simple weighted sum of objectives. The meaning of this combined value is two-fold, as it serves as an objective value for the wide-spread optimization algorithms and is interpreted as the value of the state in the Markovian decision process described later. The rating of the final state is the same regardless, of whether it is achieved by the reference optimization methods or the reinforcement learningbased agent.
The calculation depends on the observation of the environment that is the ensemble of the state variables and some other quantities that are not involved in the decision-making but are measurable. The algorithm of the calculation is presented in Alg. 1. The input of the algorithm are the state variables S, the set of the pump efficiencies E pump , the volumetric flow rate F pump delivered by the pumps and the signed volumetric flow rate F tank of the tanks. ← satisfaction · satisfaction + eff · eff + feed · feed 15: return 16: end function The state value is a weighted combination of 3 objectives.
1. satisfaction represents the satisfaction of the consumers that is characterized by the number of the insufficiently supplied nodes wrong wherein the head is out of the acceptable range bounded by ℎ min and ℎ max . The number of problematic nodes is divided by the number of all nodes in the water distribution system, and the ratio is subtracted from 1. The outcome is the basis of the first weighted objective, the satisfaction ratio. 2. eff represents the efficiency of the pumps, and it is just the product of the standalone pumps feeding the network divided by the product of the theoretical peak efficiencies of all of the pumps. 3. feed represents the feed ratio of the water network that is solved by the pumps supplying water from the wells or other sources, on the one hand and by the tanks and reservoirs, on the other hand.
In the current experiment, using the water reserve is considered expensive, and using the reserve is punished by a lower objective value, which is a simplification of the problem. However, this methodology is easily changeable by adding the target inflows and outflows to the state value and comparing the actual ones to those. In this way, the agent would be forced to learn to maintain the water flux of the tanks but this is a harder problem to solve. For the time being, this is ignored by forcing the agent to minimize the water flux of the tanks. Thus, the feed ratio is the amount of total consumption divided by the sum of the total consumption and the water flux of the tanks. The standalone objectives are also presented in Eq. 1, where the notations are the same as for Alg. 1 except for tank that denotes the sum of the absolute value of inflow/outflow for every tank.
The above formulation of the standalone objectives leads to 3 measures, whose maximum values are 1.0 all. These are then weighted separately by constant factors. The coefficients in the presented experiments are chosen arbitrarily 8 /16, 5 /16 and 3 /16 as the ratio of the satisfaction, the efficiency and the feed, respectively.
The task was solved with different optimization techniques to provide reference: fixed step-size random search (FSSRS), particle swarm optimization (PSO), differential evolution (DE), and Nelder-Mead method. PSO, DE and Nelder-Mead method are able to solve operation point optimization of VSPs, see the work of Baltar and Fontane [22], Odan et al. [23] and Celi et al. [24], respectively.
A suboptimal optimization method was also applied on the task that is referred to as one-shot random trial (One-shot RT). This method sets pump speeds randomly inside the feasibility domain and it serves as a baseline: the reinforcement learning agent has to be able to outperform this approach if it can interpret any information on the connection of nodal pressures and optimal pump speed settings.

Dueling deep Q-network agent as a real-time controller for water networks
The drawback of the reference methods is the incapability to accomplish real-time control because of the necessity of computationally expensive simulation of the hydraulics. In this paper, a dueling deep q-network agent is introduced to optimize the speeds of the pumps in a water distribution system. The agent relies on simulation data in the training phase only; thus, the controlling is feasible real-time, regardless of the size of the water network and the number of pumps controlled.
The proposed technique is based on Markov decision processes (MDPs) that are key building blocks of reinforcement learning. In the terminology of MDPs an agent works in an environment by taking actions according to a policy. The environment is observable to the agent through its state that changes according to the actions. The instantaneous quality of a state is measured by the reward that is signaled to the agent. Rewards of a decision sequence are combined in the value function. The value function measures the overall quality of the starting state in the decision sequence according to the given policy. The goal of the learning is to find a policy with which the agent can govern the environment to the most advantageous state from any initial state.
In the present study, the agent is a dueling deep q-network and it interacts with the environment that is based on the water network. The decision-making sequence and most of its concepts are depicted in Fig. 1 (originating from Sutton and Barto [25]) where and + 1 refer to two consecutive steps (also referred to as time steps) in the sequence.
According to Fig. 1, the communication between the environment and the agent during the training is as follows.
1. The environment provides its state variables -the ensemble of the nodal pressures and the pump speed ratios -to the agent in a concatenated vector. Speed ratios are the actual pump speed divided by the nominal pump speed. 2. The agent maps the state values to an action according to its current policy and executes it in the environment. The action can be the increase or decrease of one of the pump speed ratios or keeping the speed ratios as they were set in the previous step. The latter is referred to as siesta. This cyclic process goes on until the environment reaches a terminal state, which can be caused by two distinct events. On the one hand, the agent is allowed to run until a fixed number of steps to get to the most advantageous state. The environment keeps track of the number of steps taken, and it terminates the episode when the agent reaches the limit. On the other hand, the agent can decide to do nothing instead of changing one of the speed ratios. If the agent adheres to a state for a predefined number of consecutive steps, the episode is terminated as well.
Seeking to achieve the optimal policy leads to the grading of different policies. A policy is regarded better than another one if the value function is equal or higher for all states by taking actions under that one. The value function can be formulated to depend on different variables, the related form is the actionvalue function, that is for policy : The value is represented as an expected value of the sum of rewards in the forthcoming sequence started from state and taking action under policy . The importance of future rewards can be attenuated with the discount-factor , such that ∈ (0, 1]. If the agent runs under the optimal policy, its actions maximize the reward in every state-transition; thus, the optimum of the action-value function is: where the forthcoming action and state is denoted by a prime and * refers to action-values under the optimal policy. Eq. 3 can be solved in different ways, for the relevant techniques see Sutton and Barto [25]. SOTA solutions use artificial neural networks as value function estimators to cope with the complexity of the equation. ANNs are good candidates for the task, because they are universal function approximators as shown by Cybenko [26]. A variant of deep q-networks (DQN, introduced by Mnih et al. [27]) is chosen in the present study to approximate the action-value function. The term deep refers here to the fact that the neural network architecture has two or more hidden layers. The agent can be trained by minimizing the loss (4) where corresponds to the weights in the ℎ update of the deep q-network (a deep neural network in this case) and is the mean squared error defined between the ( − 1) ℎ and ℎ approximation of the value function. A significant advantage of Eq. 4 over Eq. 3 is that it does not have to evaluate a whole decision sequence to get a new assumption on the value of the updated state; hence, it can be trained off-policy.
Eq. 4 is optimized with stochastic gradient descent method as it is a general, yet effective optimization algorithm for training ANNs [28]. Moreover, the last layer of the deep q-network is forked: one layer approximates the value of the current state, while the other layer estimates the advantage in the value by taking the action. This is intended to speed up training convergence and the technique is called dueling deep q-networks, as introduced by Wang et al. [29].
A crucial component of the reinforcement learning setting is the rewarding of the agent as it influences the behavior of the trained agent. Alg. 2 summarizes the step procedure with the rewarding system of the present study.
The reward is based upon the state value but it is not a direct match, as other goals have to be reached beside optimality, as shown in Alg. 1. As the control is realized stepwise, the agent has to be taught to set the optimal speeds in as few steps as possible. The basic idea behind the presented step function, including the reward calculation is as follows. At the beginning of every new scenario, i.e., after the generation of a new demand-distribution, the optimal setting of the pump speeds is if < * then 13: ← · 14: end if 15: S ← U S ( ) 16: end if 33: return , S, 34: end procedure agent intervenes, the reward is based upon the closeness of the reference solution and the agent's solution in the search space, defined by the feasible pump speed ratios. At this stage, the agent gets a reward if it gets closer to the reference solution on a monotonous trajectory, i.e., it does not make steps increasing the distance between the solutions. The agent can also choose to make a siesta; in this case, the reward is computed differently. In siestas, the actual value of the state is computed according to Alg. 1 and compared to the reference value. If the current state value is higher than the 98% percent of the reference value (i.e., the value of 1 − / ref is at most ), the agent is rewarded with a slightly higher score. The immediate reward achieved in the first siesta is doubled if the agent chooses to stay in this beneficial state for the second time. Finally, the episode is terminated after the third consecutive siesta, and the agent gets an extra reward that is significantly higher than the rewards that are achievable with the active moves. In contrast, the agent gets a negative reward whenever it recedes from the reference speed setting with an active action or if it stays in a suboptimal posi-tion, i.e., if it makes a siesta in a state, with a value below 98% of the reference. A penalty is given even when the agent tries to set pump speeds lower or higher as the feasibility limits lo and hi , respectively. With this concept, the agent is incited to move along the optimal position continuously and terminate the episode there. The 2% tolerance in the comparison of the state values is needed because of the different variable space from where the solution is acquired with the reference method and with the reinforcement learning agent: the Nelder-Mead method chooses candidate solutions from a continuous variable space while the dueling deep q-network handles a discrete action space; thus only a restricted set of pump speeds is available compared to Nelder-Mead. Although the discretization can be arbitrarily fine, the dimensionality of the q-function -hence, the length of the training of its estimator -depends on the size of the discrete parameter space. The soft guidance means in the above process that the agent can achieve high rewards even far from the reference solution if it has a similar value. This is encouraged during training by taking random actions in a part of the whole process, thanks to the -greedy policy.
After training, the agent relies only on the observation of the environment to take its next action; thus, the calculation of the reward -including the computationally expensive reference calculation -is completely omitted.

Reference water distribution systems
The proposed controller is trained and tested on the modified Anytown and D-Town (referred to as C-Town in some literature) water distribution systems that are common among the WDS design and management research community. These networks serve as benchmarks for water network design methods wherewith the networks can be modified and extended to comply with increased water needs and expanding consumption areas. The original topology of both WDSs is accessible online from the web page of the Centre of Water Systems research group at the University of Exeter [30]. Moreover, the numerical models of the WDSs are also available in an EPANET-compatible format. The modified versions are referred to as Anytown-mod and D-Town-mod in the following.
The topology of the networks is depicted in Fig. 2 Fig. 3 for the Anytown and D-Town test cases, that are the same for Anytown-mod and D-Town-mod, respectively. The networks are slightly modified as described below. The primary purpose of Anytown-mod is to provide a simple, easily solvable problem that serves as a proof of concept: it has a global optimum that can be found with conventional methods easily. If the agent performs poorly on Anytown-mod, then there is no chance that it can solve more complex tasks. D-Town-mod is a more challenging problem whose solution is not trivial because of the multidimensional parameter space of the optimization loss function. If the agent performs well on D-Town-mod, then the RL-based agent with the proposed reward function is a good candidate to serve as a real-time controller in real water networks. The  Table 1. Both water networks share their topology with its original version published by the University of Exeter [30]; the differences are summarized below.

and in
Anytown-mod is almost identical to Anytown as only the number of pumps in the single pumping station is reduced to two from three, and both of the pumps operate with the same continuously variable speed. The performance curves of the pumps are the same as in the original network.
In the case of D-Town-mod, the control logic is removed, and all pumps operate in the water distribution network. The performance curves are kept for the head, and fictitious curves are added for the efficiency.
An environment is created that serves as an interface between the agent and the water distribution system. The purposes of the environment are the interpretation of the commands of the agent, reward calculation and re-initialization of the water network. The state of the water network can be initialized by randomizing the demand map and by randomizing the pump speeds or resetting them to the original value. The original demands in the task definition of the water network are stored, and the total sum of the original nodal consumption is calculated and stored at the beginning of training. Demand variations are substituted with randomized demand distributions over the water distribution system. This can be done because of training the agent with an off-policy method. It is not necessary to show real-life demand variations to the agent in the training phase as it is trained off-policy.
The randomization of the nodal consumption is done in three steps to be able to mimic the total demand variation during day and night and the nodal demand variation as well. First, new demand is generated in every node as the product of the original demand and a random value from a truncated normal distribution. Second, new total demand is generated as the product of the original total demand and a random value from a uniform distribution. Third, the nodal consumptions are rescaled such that the sum is equal to the one generated in the second step. The process is summarized in Alg. 3 where the set of original nodal consumptions and the randomized nodal consumptions are denoted by C 0 and C, respectively. for all ∈ C do 10: ← · * 11: end for 12: return C

13: end function
This randomization method allows control on the demand map both in relative and in absolute terms. The nodal consumption randomized one-by-one mimics the relative variation of the demand map. Meanwhile, the overall change in consumption through the day-night cycle is imitated by the variation of the total demand. I.e., the total demand of the area covered by the water distribution network is considered first; then, the total value is partitioned among the nodes.
Both distributions are chosen arbitrarily and their probability density functions are depicted in Fig. 4. The lower and upper bounds of the uniform distribution are 0.3 and 1.1, respectively, while the normal distribution has a mean 1.0 and standard deviation 1.0 with tails cut off below 0.7 and above 1.3. The shape of the truncated normal distribution is similar to the uniform distribution with this parameter set, although multipliers close to one have slightly higher probabilities during the demand randomization than remote values.
The pumps feeding the water network are considered as variable-speed pumps driven by e.g., frequency converters, in case of both water networks. The absolute pump speed is not considered; the ratio compared to the nominal pump speed is recorded instead. In the current environment, the speeds can be lowered to half of the maximum speed as water transportation is infeasible at lower speeds due to insufficient pump heads relative to the geodetic height of the nodes. The cause of the lower speed limit is valid for both WDSs.
Finally, the well from where the pumps feed the network is considered as a reservoir with a water surface large enough to ensure a stationary water level during the speed-adjustment of the pumps.
The presented results are obtained with the default hyperparameters of optimization algorithms. In Fig. 5, the average performance of the different algorithms is presented on the test set in the case of Anytown-mod and D-Town-mod. Moreover, the box plot of the difference calculated for every test scenario is depicted in Fig. 6 where the results achieved by the differential evolution are chosen as a reference.
The similarity of the results suggests that each technique is able to find the empirical global optima, except for the one-shot random trial, which is reasonable.
The single pump station in Anytown-mod means that the pump speed optimization problem has a one-dimensional parameter space; hence, evolutionary algorithms and related techniques are inefficient in finding the solution as the crossoverlike operations are meaningless on a one-dimensional candidate solutions. Thus, only the performance achieved by the Nelder-Mead method was considered in the evaluation of scenarios from the Anytown-mod case.  Fig. 6. Box plots and swarm plots of the performance of the optimization algorithms compared to the differential evolution method. 1.00 means the same performance that is achieved with DE.

Training procedure of the agent
Two separate agents are trained during the experiment: one to solve the Anytown-mod problem and one to solve the D-Townmod problem, respectively.
The agents were trained on the water networks separately, thus, during a training session, only one of the water distribution systems is utilized in the environment, and the trained agent will perform well only on the specific water network that was used for training. The agents trained with different hyperparameters; the common part is just the underlying algorithm and the fact that a densely connected neural network is used as an action-value estimator.
The training will be described next. At the beginning of every episode, the demands are randomized according to Alg. 3, the pump speed ratios are randomized according to a uniform distribution between the feasibility limits. After every 1 /25 ℎ of the total number of training steps the training is suspended, and the performance of the agent is tested on 100 different scenarios. These scenarios are generated beforehand the training and A hyperparameter optimization was carried out prior to the training with a tree-structured parzen estimator (TPE) [31]. The critical hyperparameters were identified according to the previous experience of the authors. Table 2 summarizes possible hyperparameter values from where the optimal values were selected by the TPE. Additional information on the sensitivity on the parameters and on the hyperparameter optimization is not presented due to length considerations.
The input layers of the neural networks have exactly as many neurons, as nodes in the water network as the nodal pressures divided by the highest shut-off head of the pumps are handed over the action-value estimator. The activation functions are rectified linear units (ReLU) that are introduced in Nair and Hinton [32]. ReLU activation can handle input data outside the normalized range when the data are positive-valued, as is the case with nodal pressures under normal circumstances. Nodal pressures are handed over to the neural network in vectors in every scenario, i.e., the th element of the pressure vector belongs to the same node under all circumstances. The training is carried out with the -greedy policy starting with an exploration factor of 0.95 and linearly decreased to 0.0 at the final episode. -greedy policy means that the agent makes random moves with a probability of the exploration factor, i.e., acting off-policy. This behavior ensures the possibility to find better policies than the reference one, i.e., the agent is able to achieve high rewards even without mimicking the reference strategy. The discount-factor affects the anticipatory behavior of the agent, the higher the value, the more prescient the agent is. A scenario is 40 and 200 timesteps long in the case of Anytown-mod and D-Town-mod, respectively. Moreover, the agents make moves respectively 50000 and 1000000 times in the smaller and the larger water distribution network before the final test. The state-action-reward-new state data are saved to a so-called replay memory from where the training algorithm takes samples to fill the training batch for every update of the action-value estimator. The hyperparameters of both agents are summarized in Table 3.
The hydraulic backend system is ensured by the numerical model of the water distribution systems, and these models are evaluated in EPANET, which is a popular, open-source hydraulic simulator introduced by Rossmann [33]. As the main parts of the computer code are written in Python, only the core EPYNET is developed by IT experts at the Dutch drinking water company Vitens and is publicly available by Heinsbroek [34]. The dueling deep q-network agent is a pre-packaged one from the reinforcement learning library Stable Baselines [35]. The authors have developed the environment with which the agent interacts in Python, and its interface is compatible with OpenAI gym for the seamless pairing of pre-packaged agents with the same standard interface. Hyperparameter optimization was carried out with the Optuna package [36] for Python.

Evaluation and Results
The history of the rewards and episode rewards is presented first for the D-Town-mod case in Fig. 7 and Fig. 8, respectively. The history of the rewards and the episode rewards are similar in the Anytown-mod case; thus, those are not presented in the paper due to length considerations. As the parameters of the action-value estimator are initialized randomly, the agent has no prior knowledge of the problem. However, some initialization steps are taken by the agent to collect at least as many training samples with which the replay memory can be filled. The underlying model -the artificial neural network -is updated first only after the initialization steps; thus, the training history is not available for the preceding steps. Because of the random initialization, different training sessions can produce different results. Moreover, the exploration capability of the agent introduces some stochastic behavior in the test performance of the agent through training. Thus, 4 training sessions are presented for each problem, and the results are smoothed by exponential moving averaging at = 0.3. As the agent starts taking steps according to a random policy, the achieved rewards are low at the beginning of the training. The randomness of acting is maintained with a decreasing magnitude as the training goes on; thus, the rewards should increase as the action-value estimator is updated with more and more training samples. Both the immediate and episode rewards saturate at the end of the training indicating that the action-value estimator (the deep q-network) cannot be developed further. However, the ability of the agent to solve the task cannot be judged by only the training rewards because if the reward is improperly specified, the optimum-looking behavior can be related to a completely false policy from the viewpoint of the original objective. Evolving false policies is a common problem in optimization tasks as most of them are exposed to the curse of Goodhart's law, see e.g. the work of Manheim and Garrabrant [37] and Lehman et al. [38].
Thus, two additional metrics are examined in the agent's per- formance. The most important aspect of the DDQN agent's behavior is whether it can reach comparable results to the reference solutions. This property is examined on the test scenarios by looking at the terminal state value of the episodes denoted by the reference state value of the same scenario. This is depicted in Fig. 9 for the Anytown-mod case. The value ratio rises above 99% in the first quarter of the training, and it stays there from then on in 3 of the 4 training sessions. It implies that learning the optimal strategy in the sense of reaching high state value is relatively easy in the Anytown-mod case. However, the value ratio does not tell about the number of steps required to reach the terminal state. Thus, the average length of the test scenarios are depicted in Fig. 10 for the Anytown-mod case. The average number of steps taken before the termination is 6, which means, that the agent takes at most 3 active steps on average before terminating an episode with 3 consecutive siestas. As a reminder: there is only 1 pump station in this environment whose speed ratio can be varied between 0.7 and 1.1 with increments of 0.05. Moreover, the initial speed ratio is randomized uniformly between the feasibility limits; thus a full sweep can be done in 8 to 11 steps with these settings (the initialization of the state is not counted as a step) and then the termination could be signaled with 3 additional siesta steps. Thus, 3 active steps in the Anytown-mod means that the agent starts to move in the right direction. The fact that both the high rewards and the shortest trajectory are achieved at the beginning of the training means that this amount of training steps are unnecessarily high for the Anytown-mod problem.
The same metrics, i.e., average value ratio and average episode length over the test scenarios during the training are plotted from 4 different runs in Fig. 12 and Fig. 11 achieved with the D-Town-mod environment, respectively. According to Fig. 12, DDQN also performs well in terms of value ratio in the more challenging environment. However, the absolute performance is slightly lower than in the previous case: the agent achieves at most 98% of the reference state value on average. The average episode length differs from the previous case, where the shortest trajectories were found soon after the beginning of the training. In this case, the agent exhausts all its possibilities to move around the parameter space until it learns that choosing a shorter trajectory leads to a higher reward.
Finally, Fig. 13 and Fig. 14 represents the same performance metrics for the D-Town-mod environment but with the reference solution acquired with one-shot random trial. So, in this case, the agent was guided by a suboptimal policy, but it can choose moves off-policy thanks to the fairly high exploration factor at the beginning of the training. Owing to this, the DDQN agent performs reasonably well even with a poorly chosen reference algorithm as it outperforms that.
The average of the value ratios achieved on the test scenarios are summarized in Table 4. The performance on the test set is similar to the the performance on the validation set in the end of the training that means the agent is able to generalize among different demand distributions.

Conclusions
A methodology is presented for instantaneous pump control in water distribution systems with reinforcement learning. The proposed technique is novel in the sense that it relies entirely on live measurement data in the decision-making process. This property makes real-time optimal control of the pumps possible in a smart water network. The underlying algorithm of the agent is a dueling deep qnetwork (DDQN). As DDQN handles discrete action spaces only, the pump speed setting process is done by changing the speeds with fixed-size increments.
The performance of the agent is measured on two water networks with significantly different number of nodes, pipes and pump stations. Metrics are defined as value ratio and episode length. The former measures the value of the terminal state compared to the reference found by the Nelder-Mead method, while the latter shows whether the agent uses the shortest path to the optimum or is it just randomly seeking over the parameter space. The novel approach is found to be useful, as the agent can achieve comparable results to widespread optimization algorithms even with the restrictions mentioned above. In the more challenging case, the agent gets close to the reference solution with a difference in value ratio smaller than 2%. As the agent gets an extra bounty if it reaches a value ratio higher than 98%, this performance ought to be upgraded by fine-tuning the rewarding function. Another critical aspect of the agent-based  pump control is whether the agent can do its task in a limited number of time steps. The proposed rewarding algorithm is found to be appropriate to incite the agent to use the shortest possible trajectories towards the optimal state. In other words, the agent was able to solve the more challenging task in around 20 timesteps ( DQN ) compared to the 70 evaluations (3.5 DQN ) of the Nelder-Mead method and the few hundred evaluations (≈ 10 DQN ) of the evolutionary methods. Besides the number of evaluations, the classic methods rely on the hydraulic model of the water network, but the proposed technique is able to rely only on measurement data after training.
Moreover, the exploratory behavior during the training provides an opportunity to outperform the reference algorithm that is used for the training guide. This phenomenon is also observed with the presented technique in the case when suboptimal guidance is used.
The proposed technique is a novel operation point optimizer for variable speed pumps in the presented state that depends only on measurement data during control. It is also suitable for hybrid pump scheduling methods to assign optimal set-points to VSPs in real-time. As the deep q-network can be changed to handle temporal processes, the presented technique can be further developed to a real-time pump scheduling method for water distribution networks.

Data Availability Statement
• Some or all data, models, or code generated or used during the study are available in a repository online in accordance with funder data retention policies (Reinforcement learning algorithms implementation [35], Python API for EPANET [34], original numerical models of Anytown and D-Town [30], the code repository of the presented research including everything to reproduce the results [39].)