scieee AI-readable full text Open interactive document viewer

Driven real-time scheduling of multiple AGVs in an ACT yard

Uriach Dasca, Javier

Abstract

Automated Guided Vehicle (AGV) systems have emerged as a key element within contemporary intralogistics. The prevailing technological standard and extensive expertise in this automation technology have facilitated the widespread adoption of AGVs across diverse industrial sectors and production domains, especially for material handling in flexible workshops driven by Industry 4.0 and industrial artificial intelligence. Although ports, according to McKinsey’s report on the future of automated ports [1] have adopted this automation more slowly than comparable sectors, the pace is now starting to accelerate. Automated ports provide numerous benefits in comparison to traditional ones; however, they also pose certain challenges. The occurrence of disruptions caused by human error decreases, and the overall performance becomes more reliable. However, the initial investment required for automation is considerably high, and there are several operational challenges that need to be addressed, such as a shortage of specialized personnel, poor data quality, siloed operations, and difficulty in handling exceptions. Since the first automated container terminal (ACT) was introduced at Europe Container Terminals Delta Terminal in Port Rotterdam back in the year 1992 [2] the emergence of ACT has paved the way for a new era in the port industry, prompting a significant revolution in port construction. In order to enhance the efficiency of Automated Container Terminal (ACT), it is imperative to concentrate on the coordination of time and space synchronization ofAGVs ) and automated cranes during equipment loading and unloading, equipment transportation, and the reduction of task completion time. Conventional scheduling methods have limitations in terms of dynamic response capabilities and are unsuitable for managing dynamic terminal operating environments. Hence, this paper studies the challenges that ACT pose on real-time scheduling of AGVs. To address these challenges, an adaptive mixed-rule AGVs real-time scheduling method based on Deep Reinforcement Learning (DRL) is proposed to minimize the total make span of AGVs in an ACT yard. This framework first models the AGV scheduling process as a Markov Decision Process (MDP). Furthermore, an optimal mixed-rule policy is implemented through the utilization of a Deep Q-network (DQN) algorithm. This approach enables the selection of both suitable scheduling rules and automated guided vehicles with the purpose of scheduling various states. By means of efficient scheduling, superfluous waiting time and resource depletion can be minimized, thereby enhancing the efficiency of the ACT. Finally, simulation experiments show that the proposed approach effectively serves the accurate coordination of AGVs in automated terminals, therefore validating the feasibility and effectiveness of the proposed method.

Full text

Beijing Institute of Technology Bachelor’s Thesis Driven real-time scheduling of multiple AGVs in an ACT yard Department: School of Mechanical Engineering Major: Mechanical Engineering Class: 2023 Author: Javier Uriach Dasca Student ID: 3820239006 Supervisor: Kane Liu January 25 2024 Beijing Institute of Technology Bachelor’s Thesis i Declaration of Originality I hereby declare that this academic thesis summarizes my research work and findings under the guidance of my supervisor. To the best of my knowledge and belief, the work presented in this thesis, except as acknowledged in the text, is original and does not contain any research achievements published or written by others. Any contributions made by any individuals or groups have been clearly stated and acknowledged in the thesis. Signature of the author: Javier Uriach Date: 25/01/2024 Authorization for Copyright Use of Thesis The author of this thesis is fully aware of the provisions of Beijing Institute of Technology on the retention, and use of the thesis. I hereby authorize Beijing Institute of Technology to preserves the right to (1) save, and send the original or copy of the thesis to the relevant organizations; (2) compile all or part of the thesis into relevant database for retrieval, and can be saved and compiled by means of photocopying, scanning or other means of reproducing; (3) allow the thesis to be read and borrowed; (4) for academic purpose, copy, gift and exchange the thesis; (5) publish all or part of the contents of the thesis. Signature of the author: Javier Uriach Date: 25/01/2024 Signature of the supervisor: Date: Beijing Institute of Technology Bachelor’s Thesis ii Driven real-time scheduling of multiple AGVs in an ACT yard Abstract Automated Guided Vehicle (AGV) systems have emerged as a key element within contemporary intralogistics. The prevailing technological standard and extensive expertise in this automation technology have facilitated the widespread adoption of AGVs across diverse industrial sectors and production domains, especially for material handling in flexible workshops driven by Industry 4.0 and industrial artificial intelligence. Although ports, according to McKinsey’s report on the future of automated ports [1] have adopted this automation more slowly than comparable sectors, the pace is now starting to accelerate. Automated ports provide numerous benefits in comparison to traditional ones; however, they also pose certain challenges. The occurrence of disruptions caused by human error decreases, and the overall performance becomes more reliable. However, the initial investment required for automation is considerably high, and there are several operational challenges that need to be addressed, such as a shortage of specialized personnel, poor data quality, siloed operations, and difficulty in handling exceptions. Since the first automated container terminal (ACT) was introduced at Europe Container Terminals Delta Terminal in Port Rotterdam back in the year 1992 [2] the emergence of ACT has paved the way for a new era in the port industry, prompting a significant revolution in port construction. In order to enhance the efficiency of Automated Container Terminal (ACT), it is imperative to concentrate on the coordination of time and space synchronization ofAGVs ) and automated cranes during equipment loading and unloading, equipment transportation, Beijing Institute of Technology Bachelor’s Thesis iii and the reduction of task completion time. Conventional scheduling methods have limitations in terms of dynamic response capabilities and are unsuitable for managing dynamic terminal operating environments. Hence, this paper studies the challenges that ACT pose on real-time scheduling of AGVs. To address these challenges, an adaptive mixed-rule AGVs real-time scheduling method based on Deep Reinforcement Learning (DRL) is proposed to minimize the total make span of AGVs in an ACT yard. This framework first models the AGV scheduling process as a Markov Decision Process (MDP). Furthermore, an optimal mixed-rule policy is implemented through the utilization of a Deep Q-network (DQN) algorithm. This approach enables the selection of both suitable scheduling rules and automated guided vehicles with the purpose of scheduling various states. By means of efficient scheduling, superfluous waiting time and resource depletion can be minimized, thereby enhancing the efficiency of the ACT. Finally, simulation experiments show that the proposed approach effectively serves the accurate coordination of AGVs in automated terminals, therefore validating the feasibility and effectiveness of the proposed method. Key Words: AGV; real-time scheduling; reinforcement learning, simulation; logistics Beijing Institute of Technology Bachelor’s Thesis iv MENU Abstract ............................................................................................................................................................. ii Chapter 1 Introduction .................................................................................................................................... 1 1.1 RESEARCH BACKGROUND AND SIGNIFICANCE ..................................................................................... 1 1.2 RESEARCH STATUS ................................................................................................................................... 3 1.3 THE ORGANIZATION OF THE THESIS .......................................................................................................... 6 Chapter 2 Relevant theoretical basis and research review .......................................................................... 8 2.1 REINFORCEMENT LEARNING .................................................................................................................... 8 2.2 TERMS USED IN REINFORCEMENT LEARNING ......................................................................................... 10 2.3 DQN ALGORITHM .................................................................................................................................. 11 2.3.1 Q-LEARNING.................................................................................................................................. 11 2.3.2 DEEP NEURAL NETWORKS .............................................................................................................. 12 Chapter 3 Problem description and modeling ............................................................................................ 15 3.1 PROBLEM DESCRIPTION ......................................................................................................................... 15 3.2 MODEL BUILDING .................................................................................................................................. 16 3.3 STATE SPACE .......................................................................................................................................... 18 3.4 ACTION SPACE ....................................................................................................................................... 19 3.5 REWARD FUNCTION DESIGN .................................................................................................................. 20 3.6 SCHEDULING BEHAVIOR POLICY ............................................................................................................ 21 Chapter 4 Experimental study ...................................................................................................................... 23 4.1 EXPERIMENTAL SETUP ............................................................................................................................ 23 4.2 TASK GENERATION SETTINGS ................................................................................................................ 24 4.3 SIMULATION PLATFORM CONSTRUCTION ............................................................................................... 25 Chapter5 Summary and prospect ................................................................................................................ 27 5.1 STATISTICAL RESULTS............................................................................................................................. 27 5.2 CONCLUSION .......................................................................................................................................... 28 References ....................................................................................................................................................... 30 Appendices ...................................................................................................................................................... 41 APPENDIX A ................................................................................................................................................. 32 Beijing Institute of Technology Bachelor’s Thesis 1 Chapter 1 Introduction 1.1 Research Background and Significance In recent years, with the rapid development of manufacturing technologies and the sprouting of diverse demand of customers, the continuous growth of markets around the entire globe is presenting domestic enterprises with more opportunities to develop and expand themselves. This tendency will prevail in the upcoming year as, according to a report published by Goldman Sachs [3], worldwide GDP is forecast to expand 2.6% next year on an annual average basis and 2.7% in 2025. China will notably be surpassing these numbers with an expected growth year-over-year of 4.8% and 4.2% respectively. Under these circumstances, manufacturing systems must develop towards the direction of discretization, intelligence, and autonomy. As an important part of the manufacturing system, the material handling system must be efficient and automated. Significant changes already have occurred in the demand and supply aspects of ocean shipping. Both shipping and seaports have played a crucial role in the process of globalization. The advancement of maritime transport and the introduction of containerization have been key factors in enabling the globalization we witness today. In particular, and as a result of this booming in international logistics trade nowadays the volume of containerized seaborne trade accounts for over 70% of the total trade transportation. So there exists no doubt that the shipping industry plays a crucial role in maintaining and developing the global economy. And, as mentioned above, one of its most important assets is the ports. More specifically, the capacity of ports to manage the entry and exit of goods, whether as a transshipment point, origin, or final destination. Automated container terminals (ACTs), a key complex seaborne trade logistics system composed of quay cranes (QC), yard cranes (YC) and automated guided vehicles (AGVs), have seen significant improvements in their throughputs. Beijing Institute of Technology Bachelor’s Thesis 2 Figure 1. Quay cranes unloading containers in an ACT yard. Regardless of these improvements, and due to the steadily growth of twenty-foot equivalent units (TEUs) this operation systems manage year over year, a major challenge continues to be present. Both in terms of time efficiency and money, it requires the development of optimal systems that can help solve these obstacles. As AGVs are utilized throughout the entirety of container operations within ACTs and play a crucial role in determining the operational efficiency of the entire ACT yard, it is imperative that AGV scheduling be optimized as the primary focus. In the dynamic and complex environment of ACTs many uncertainties must be taken into account. Among them, special focus will be placed in explaining the ones connected to the research developed in this paper. AGVs scheduling is a crucial aspect of AGVs control, as it involves determining the most efficient transport time and equipment for each task, while adhering to the company's production specifications. The traditional approach to static scheduling assumes that all task information is fixed and obtained in advance. However, in a real-world ACT environment, it is unrealistic to have all task information beforehand. Additionally, the shop floor environment is dynamic and complex, with uncertainties such as urgent tasks and task reworks. This is where the requirement of giving real-time response plays a major role, as the static scheduling approach falls short in addressing the complexities of the real-world ACTs. This focus on real-time scheduling in AGVs aims to tackle the dynamic nature of ACTs operations and create more efficient scheduling solutions. Beijing Institute of Technology Bachelor’s Thesis 3 Finally, a clear objective needs to be defined amidst all the possible options. Various alternatives could be to minimize the total time, the cost, or the delay ratio. They are not mutually exclusive but should be weighted and optimized. Over the past few years, Reinforcement Learning (RL) has been widely used to solve this problem. This will also be the case in the actual research. RL is particularly useful for solving problems that involve sequential decision-making and long-term goals, such as the one treated in this paper. Through interaction with its environment, the agent learns to act in a more effective manner based on its accumulated experience. Hence, we can say that "Reinforcement learning is a type of machine learning method where an intelligent agent (AGVs) interacts with the environment (ACTs) and learns to act within that." The adaptative nature and learning capacities RL offers match perfectly with the dynamic scheduling problems in ACTs and we will therefore be gaining more in-depth knowledge in the topic through the development of this paper. 1.2 Research Status This chapter will be divided in two main sections. The first one focuses on reviewing the existing status of the scheduling problem already presented and analyzing how previous projects presented the model. It will also state the ongoing study and the development trends inside the research topic. On the other hand, the latest section rivets in the different methodology and algorithms used in previous studies to solve the problem. In recent decades, numerous scholars have significantly contributed to the advancement of port dispatching research and development, particularly in the area of terminal AGVs. The basic ideas of dispatching primarily revolve around the problem model and solution algorithm, which are formulated and optimized based on the predetermined assumptions of the port operating environment. The most common approach in existing studies tackle the scheduling optimization problem from the time minimization side. Inside this field, many papers have been published. [1,2,3] all focus in presenting models closer to reality regarding the dispatching method for AGV in Automated Port Container Terminals. Beijing Institute of Technology Bachelor’s Thesis 4 But as mentioned in [12], although the vast majority of studies have managed to model the problem and afterwards reduce the time spent on tasks by AGVs in ACT environments, they have neglected two important issues: the AGV path-conflict and the charging problem of AGVs. It is important to notice that these two issues fall out of the scope of this research project, but it is considered of added value to mention some of the advances made. On the first topic, the AGV conflict is caused by the existence of narrow lanes. Some examples of studies trying to solve this problem are [13] that introduced a novel approach for coordinating the control of cross-shaped AGVs or [15] that using deep reinforcement learning, presented an approach to enhance the anti-conflict path planning of AGVs in ACT. Regarding the energy problem, [16] utilized the principle of optimal control to mitigate the energy consumption of AGVs. Furthermore, the inter-cranial and inter-vehicular limitations have not been adequately considered, as most of the studies (this one included) have presumed that the presence of multiple yard cranes does not cause any interference with each other. This is the reason why nowadays, there exists a lack of literature on the combined coordination of cranes and vehicles in scheduling. These constraints mentioned can be considered the latest ongoing research topics inside this field. Theoretically, the use of traditional scheduling rules to solve the problem stimulates a better performance. That is the reason why they have been widely applied to real-time AGV scheduling problems in existing studies [21-22]. These rules determine the way in which all the different tasks are assigned to each AGVs. Some of the more popular ones are: firstcome-first-served (FCFS), shortest traveling distance (STD), earliest due date priority (EDD), longest waiting time (LWT), and nearest vehicle priority (NVF). Following the evolution from heuristic rules, it can be seen that in relatively simple environments, where the agent can select from pre-defined actions and be in pre-defined known state, the Q-Learning algorithm [24-25] is commonly employed. This algorithm finds the optimal policy in a Markov Decision Process (MDP) by maintaining a Q-Table with all possible states and actions and iteratively updating the Q-values for each stateaction pair using the Bellman equation until the Q-function converges to the optimal Q- value. But ACTs are very dynamic and complex environments and therefore static scheduling Beijing Institute of Technology Bachelor’s Thesis 11 Value(V): It is expected long-term return with the discount factor and opposite to the shortterm reward. Value Function: Value functions are functions of state action pairs that estimate how good it is for the agent to perform a given action in a given state. This notion of how good a state action pair is given in terms of expected return. In other words, a reward indicates the immediate signal for each good and bad action, whereas a value function specifies the good state and action for the future. The value function depends on the reward as, without reward, there could be no value. The goal of estimating values is to achieve more rewards. Model of the environment: This mimics the behavior of the environment. It helps you to make inferences to be made and determine how the environment will behave. Model based methods: It is a method for solving reinforcement learning problems which use model-based methods. 2.3 DQN Algorithm DQN is a reinforcement learning algorithm that combines Q-Learning with deep neural networks to let RL work for complex, high-dimensional environments. To understand how a Deep Q-Network works, both the Q-Learning algorithm and the concept of Deep Neural Network (DNN) need to be introduced. 2.3.1 Q-Learning Q-learning is an algorithm in the field of RL that operates in an Off-policy manner. It is specifically designed for Temporal Difference (TD) Learning, which involves comparing predictions made at temporally successive instances. The primary objective of Q-learning is to determine an optimal policy that maximizes the expected return across all subsequent time steps. In simpler terms, the goal is to identify the policy that yields the highest achievable outcome by acquiring knowledge about the optimal values associated with each state-action pair. Q-learning achieves this by learning the value function Q(S, a), which quantifies the desirability (“How good it is”) of taking a specific action a at a given state s. The agent shall employ a Q-table to determine the optimal course of action, taking into account the Beijing Institute of Technology Bachelor’s Thesis 12 anticipated reward for each state within the environment. In essence, a Q-table is a structured collection of actions and states, and the Q-learning algorithm is utilized to update the values contained within the table. The following flowchart provides a visual representation of the operational process of Q- learning: Figure 4. Q-learning process. In conclusion, the Q-learning algorithm literately updates the Q-values for each state action pair using the Bellman equation until the Q-function converges to the optimal Q function Q*. This iterative approach is called Value Iteration. 2.3.2 Deep Neural Networks In the realm of neural networks, a rudimentary configuration for addressing elementary problem-solving tasks may comprise solely three layers. However, it is also plausible for a neural network to encompass numerous intermediary layers between the input and output. This richer architecture is referred to as a deep neural network (DNN), and it is commonly employed to tackle considerably more intricate problems. In principle, a DNN possesses the capability to establish a mapping between any kind of input and any kind of output. Nonetheless, a notable drawback of employing a DNN is the substantial increase in training it requires. In order to attain proficiency, a DNN necessitates exposure to a significantly larger volume of training data, often in the range of millions or billions of examples, in contrast to the hundreds or thousands that would be sufficient for a simpler network. In this research we will use an architecture that consists of 1 input layer, 1 output layer and 4 hidden layers. In our neural network the transmission of information occurs through two distinct pathways. Firstly, during the learning phase (being trained), information patterns are introduced into the network via the input units. These input units then activate the hidden units, which Beijing Institute of Technology Bachelor’s Thesis 13 subsequently propagate the information to the output units. This prevalent architectural configuration is commonly referred to as a feedforward network. It is important to note that not all units within the network are consistently active. Each unit receives inputs from the units positioned to its left, and these inputs are weighted according to the connections they travel along. Subsequently, each unit accumulates the weighted inputs it receives, and in the simplest form of network, if the cumulative sum surpasses a predetermined threshold value, the unit becomes activated and triggers the units it is connected to, namely those positioned to its right. For a neural network to acquire knowledge, it is essential to incorporate a feedback mechanism, similar to how children learn through receiving guidance on their right or wrong actions. In fact, feedback is a ubiquitous aspect of human learning: you use feedback to compare the desired outcome with the actual result, identified the disparity between the two, and employ the information to modify your actions in subsequent attempts. Neural networks learn things in exactly the same manner through a feedback mechanism known as backpropagation. This process entails comparing the output obtained with the desired output and utilizing the disparity between them to adjust the weights of the connections between the network's units. This adjustment occurs in a backward manner, starting from the output units, passing through the hidden units, and reaching the input units. Over time, backpropagation enables the network to learn by minimizing the discrepancy between the actual and intended output until they align perfectly, allowing the network to accurately comprehend the given information. Figure 5. Representation of backpropagation. Beijing Institute of Technology Bachelor’s Thesis 14 Once the neural network used has undergone sufficient training using a substantial number of learning examples, it reaches a stage where it can be exposed to an entirely novel set of inputs that it has not encountered previously and observe its response. In conclusion, and as stated in the beginning of the chapter, Deep Q-network uses a neural network to approximate a state value function in a Q-Learning framework. When performing actions, the DQN algorithm employs epsilon-greedy strategies or alternative strategies to determine the selection of actions. The framework used in this project will follow the one used by Zhao Xirui in his research paper: Figure 6. Framework of DQN algorithm. Beijing Institute of Technology Bachelor’s Thesis 15 Chapter 3 Problem description and modeling In this section, we first describe the AGV scheduling problem in an ACT yard, and next formulate the AGV scheduling problem mathematically. 3.1 Problem Description On the global port scene, most of the main players are in Asia. In fact: - 15 of the world's top 20 ports are in Asia.[30] - The top 9 ports in the world are Asian. Specifically, China is not only home to the world's largest port, but also hosts almost half of the ranking of the world's top 20 ports. So, it will be assumed that the port we are looking to is a simplified prototype version of the number 1 port in the world in volume of TEUs, located in Shanghai. The four steps followed in a general unloading process of the storage and transport is depicted below: 1. Initially, a vessel docks at its designated berth, as seen in Figure 2. Then a QC retrieves the containers from the berth. The starting point of all AGVs is the carport. 2. Subsequently, specific blocks in the yard, are selected and assigned for containers. An AGV receives a command from the dynamic dispatching system and proceeds to the QC location. 3. AGVs are required to move along the traffic lanes. 4. The containers delivered to the blocks are retrieved by a YC and stored within the block. Steps 2 to 4 are repeated until all containers have been transported. As observed in the container unloading process, the optimization of the AGV scheduling system plays a crucial role in the efficiency of terminal operations, as the scheduling system must determine the paths to be followed by each AGV transportation task in advance. Therefore, it is essential to optimize the AGV scheduling. Beijing Institute of Technology Bachelor’s Thesis 16 Figure 7. The scheduling of a single AGV. 3.2 Model Building To establish the multi-AGV scheduling model, and ensure that the experiment is feasible the following assumptions are considered: (1) All AGVs are initially located in the carport until the first dispatch order is given. (2) The loading and unloading time of AGVs is a fixed value. And the speed of AGVs is also constant. (3) AGVs can perform the next task only after completing the current task. (4) AGVs will stay at their current place if they do not receive the next order task. (5) The scheduling of other equipment in ACTs are not considered, such as QCs scheduling and YCs scheduling. (6) Automated Guided Vehicles possess sufficient energy to successfully accomplish a given set of tasks within a turn. (7) The road consists of a two-way path where vehicles can travel in both directions without any interference between them. The AGV dynamic scheduling, considered as a real-time decisionmaking problem, can be Beijing Institute of Technology Bachelor’s Thesis 17 represented as a Markov Decision Process (MDP). This framework is capable of addressing most RL problems, including the one discussed in this research. Within an MDP, there exists a set of states S, a set of actions A, and a set of rewards R, each of which is assumed to have a finite number of elements. The AGV, regarded as the “agent” receives information, named “states”, from the ACT yard and uses them accordingly to reach decisions, known as “actions”, in order to maximize the “reward” and move to the subsequent states. The procedure is shown in the Figure below: Figure 8. AGV procedure. From a mathematical standpoint, it can be ascertained that a state St is deemed Markov if and only if: (1) ℙ [𝑆𝑡+1 | 𝑆𝑡]= ℙ[𝑆𝑡+1 | 𝑆1,𝑆2,…,𝑆𝑡 This is called the Markov property, which asserts that the future is independent of the past and can solely be determined by the present. In conclusion, the MDP in the research can be represented by a 6-tuple (𝑆, 𝐴, 𝑃, 𝛾, 𝑅, 𝜋), each term representing the following: 𝑺 State space 𝑨 Action space 𝑷 transfer probability 𝜸 Discount factor 𝑹(𝒔,𝒂,𝒔′) Reward function 𝝅(𝒔,𝒂) Mapping strategy from S to A Table 1. Terms needed in the MDP. Beijing Institute of Technology Bachelor’s Thesis 18 In order to achieve the most effective scheduling decisions, the primary objective is to acquire knowledge of a function that produces the best possible action based on the current state. This function is what was defined in Section 2 as the policy, denoted as 𝜋. In the subsequent sections, we will provide a detailed explanation of the components of MDP corresponding to the multi-AGV scheduling problem under consideration. These components encompass the state, action, reward function, and behavior policy, respectively. 3.3 State Space As stated in the previous point, in the framework of Markov Decision Processes (MDP), the state S represents the feature information of an AGV, and directly supplies the basic information to the scheduling system, enabling it to make informed decisions. In order to define and represent the State Space S in every moment of the process state vectors are used. The state at time t can be defined as the vector: (2) (𝑁𝑡,𝑡𝑟,𝑙𝑡,𝐴𝑓𝑖(𝑖=1,2,3,4),𝑡𝑤,𝑅𝑡𝑟,𝑅𝑡𝑤,𝑅𝑙𝑡) Each term has the following meaning: 𝑵𝒕 Total number of tasks in the task pool 𝒕𝒓 Average time remaining for tasks 𝒍𝒕 Average distance to task 𝑨𝒇𝒊 𝒊=𝟏,…,𝑲 State of AGVs 0 = AGV is idle, 1 = AGV is working, K is the total number of AGSv 𝒕𝒘 Task average waiting time 𝑹𝒕𝒓 Task remaining time range difference 𝑹𝒕𝒘 Task waiting time range 𝑹𝒍𝒕 Task distance range Table 2. State vectors terms needed in the MDP. Beijing Institute of Technology Bachelor’s Thesis 19 3.4 Action Space As new containers arrive to the port, the scheduling system must allocate transportation tasks to AGVs. In this context, the decision-making process is regarded as actions in MDP. The action space encompasses all feasible actions that the agent can undertake. However, due to the great amount of potential solutions the scheduling problem offers, the action space would be excessively large, making it challenging to generate efficient scheduling results favorable for convergence within a reasonable timeframe. Consequently, this study proposes the utilization of a set of heuristic scheduling rules instead of directly outputting scheduling solutions. This approach significantly reduces the decision space and focuses solely on the solution space, where highly efficient solutions are more likely to be found. As stated in [27] these rules should follow some principles like diversity, effectiveness and orderliness. In this project we will use the 5 main rules that are explained on the following table: 𝐹𝐶𝐹𝑆 Priority is given to tasks in the order in which they arrive 𝑆𝑇𝐷 Priority is given to the task with the shortest distance 𝐸𝐷𝐷 Priority is given to tasks with the closest deadlines 𝐿𝑊𝑇 Priority is given to the task with the longest waiting time 𝑁𝑉𝐹 Priority is given to the task closest to the AGV Table 3. Basic scheduling rules. The action of scheduling a task (𝒂) is described as: - Step 1 Select an AGVi from the AGVs that are not working. - Step 2 Select a scheduling rule rj from 5 rules in Table 3. Therefore, 𝒂 is represented by a binary group: (3) 𝑎=(𝑖,𝑗) Beijing Institute of Technology Bachelor’s Thesis 20 Then the size of the set of possible actions is: (4) 𝑛𝑎=𝑛𝑖∙𝑛𝑗 3.5 Reward Function Design The reward function plays a crucial role in evaluating the value of an action and serving as a foundation for optimizing strategies. It is necessary to customize the reward function according to our requirements. For instance, we aim to assign higher rewards when the AGV successfully accomplishes a satisfactory scheduling, while lower or even negative rewards are given when the outcome is not the desired. The reward function can take into account various metrics, including completion time, energy consumption, delay rate, maintenance cost, equipment utilization, and more. In this project, we establish multiple sub-reward functions and formulate the overall reward function as a linear combination of these sub-rewards. Each sub-reward function is defined as follows: (1) Distance cost incentives 𝑅𝐷 𝑅𝐷=𝐶𝐷∗(1.2−𝑤𝑡) where 𝐶𝐷 is the distance cost, which describes the distance advantage of the executed task and is calculated as follows: 𝐶𝐷=sigmoid(0.25∗(𝑙𝑡+𝑙𝑡𝑓−𝑑))∗0.25 𝑙𝑡𝑓is the average distance to the starting point of the task, d is the distance of the executed task 𝑤𝑡 as a load factor that expresses the current stacking of tasks and adjusts for each sub−award 𝑤𝑡={0.1+0.8∗𝑁𝑡 20 𝑁𝑡≤20 1 𝑁𝑡>20 (2) Waiting time rewards 𝑅𝑤 𝑅𝑤={−0.2 𝑡𝑤>50 0 𝑡𝑤≤50 Beijing Institute of Technology Bachelor’s Thesis 27 Chapter5 Summary and prospect 5.1 Statistical results To validate the effectiveness of the proposed method and demonstrate that our method performs better than traditional methods, different experiments are conducted. These experiments consist of using single-scheduling rules only to obtain different parameters like the reward or the delay rate and compare the results obtained from these traditional heuristic rules with those from the RL-based method. Otherwise, the advantage of the method cannot be proven. Figure 11. Reward curve of each algorithm Beijing Institute of Technology Bachelor’s Thesis 28 Figure 11. Delay rate of each algorithm In the reward graphic we can see the convergence curve of the results in the DQN method. This phenomenon indicates a good performance in the effectiveness of the proposed method. Although at the beginning the results of the algorithm seem similar than those obtained with the heuristic rules, as the number of rounds increase, the adaptive learning nature of the algorithm (DRL) enables the DQN method to achieve better to achieve better scheduling results than other single, non-adaptive rule scheduling. Another metric to check the validity of the method is the delay rate. In this second graphic it is showed that, inversely to what happens with the reward, as the number of episodes increase, the delay rate decreases. 5.2 Conclusion In this paper, the online AGV scheduling problem in ACT yards was studied to improve the scheduling efficiency with an adaptive mixed-rule AGVs real-time scheduling method based on Deep Reinforcement Learning (DRL). To begin with, we modeled the AGV scheduling process as a Markov Decision Process (MDP) and specified the state information, action expression, reward function and optimal mixed rule policy. Following this initial step, an optimal mixed-rule policy was implemented through the utilization of a Deep Q-network (DQN) algorithm. In order to enhance the selection of both suitable scheduling rules and automated guided vehicles (AGVs) in different states. Beijing Institute of Technology Bachelor’s Thesis 29 Experimental results demonstrated that the proposed algorithm could yield the highest reward and lowest delay ratio among all methods. Hence, the effectiveness and advantages of the proposed modeling approach and optimization method for the multi-AGV scheduling system of the ACT yard were confirmed. Beijing Institute of Technology Bachelor’s Thesis 30 References [1] The future of automated ports. December 4, 2018 | Article By Fox Chu, Sven Gailus, Lisa Liu, and Liumin Ni [2] The global trends of automated container terminal: a systematic literature review W.K. Kon, Noorul Shaiful Fitri Abdul Rahman, Rudiah Md Hanafiah, Saharuddin Abdul Hamid. Maritime Business Review. ISSN: 2397-3757. Article publication date: 26 October 2020 [3] The global economy will perform better than many expect in 2024. Published on10 NOV 2023. Goldman Sachs. [1] Narasimhan A., and U.S.Palekar. ”Analysis and algorithms for the transtainer routing problem in container port operations.” Transportation Science 36.1(2002):63-78 [2] Chung-Lun Li., and Vairaktarakis G.L. ”Loading and unloading operations in container terminals.” Iie Transactions 36.4(2004):287-297. [3] Kap Hwan Kim, Jong Wook Bae. ”SPECIAL ISSUE ON FREIGHT TRANSPORTATION —— A Look-Ahead Dispatching Method for Automated Guided Vehicles in Automated Port Container Terminals.” Transportation Science 38.2(2004):224-234. [4] Kim, J., R.Choe, and K.R.Ryu. ”Multi-objective optimization of dispatching strategies for situation-adaptive AGV operation in an automated container terminal.” Research in Adaptive Convergent Systems ACM, 2013:1-6. [5] Tran, M.Q. ”Development of an IoT Architecture Based on a Deep Neural Network against Cyber Attacks for Automated Guided Vehicles.” Sensors 21(2021). [6] Grunow, M.; Günther, H.O.; Lehmann, M. Strategies for dispatching AGVs at automated seaport container terminals. In Container Terminals and Cargo Systems; Springer: Berlin/Heidelberg, Germany, 2007; pp. 155–178. [7] Hu, H., et al. ”Deep reinforcement learning based AGVs real-time scheduling with mixed rule for flexible shop floor in industry 4.0.” Computers Industrial Engineering 149(2020):106749. [8] Hu, H.; Jia, X.; He, Q.; Fu, S.; Liu, K. Deep reinforcement learning based AGVs real-time scheduling with mixed rule for flexible shop floor in industry 4.0. Comput. Ind. Eng. 2020, 149, 106749. [9] Yao, Z.; Wang, Y.; Meng, L.; Qiu, X.; Yu, P. DDPG-Based Energy-Efficient Flow Scheduling Algorithm in Software-Defined Data Centers. Wirel. Commun. Mob. Comput. 2021, 2021, 6629852. [10] Luo, S.; Lin, X.; Zheng, Z. A novel CNN-DDPG based AI-trader: Performance and roles in business operations. Transp. Res. Part E Logist. Transp. Rev. 2019, 131, 68–79. Beijing Institute of Technology Bachelor’s Thesis 31 [11] Ying, C.; Chow, A.H.F.; Chin, K.S. An actor-critic deep reinforcement learning approach for metro train scheduling with rolling stock circulation under stochastic demand. Transp. Res. Part B Methodol. 2020, 140, 210–235. [12] Energy-reducing AGV scheduling in an ACT yard based on deep reinforcement learning Lin Gonga, Zijie Huanga, Xi Xianga, Xin Liuaa, School of Mechanical Engineering, Beijing Institute of Technology, Beijing, People’s Republic of China. [13] Lombard, A., et al. ”Decentralized management of intersections of automated guided vehicles.” IFAC-PapersOnLine 49.12(2016):497-502. [14] Zhong, M., et al. ”Multi-AGV scheduling for conflict-free path planning in automated container terminals.” Computers Industrial Engineering 142.Apr.(2020):106371.1-106371.11. [15] Hu Hongtao, et al. ”Anti-conflict AGV path planning in automated container terminals based on multi-agent reinforcement learning.”International Journal of Production Research 61.1(2023). doi:10.1080/00207543.2021.1998695. [16] Wang, Cong, C.Jin, and Z.Li. ”Bilevel programming model of low energy consumption AGV scheduling problem at automated container terminal.” 2019 IEEE International Conference on Smart Manufacturing, Industrial Logistics Engineering (SMILE) IEEE, 2019. [17] Ming F.H., et al. ”Joint Configuration and Scheduling Optimization of Dual-trolley Quay Crane and AGV for Container Terminal with Considering Energy Saving.”Acta Automatica Sinica 47.10(2021):15. [18] Li, C.L., Vairaktarakis, G.L., 2004. Loading and unloading operations in container terminals. IIE Trans. 36 (4), 287–297. [19] Bish, E.K., 2003. A multiple-crane-constrained scheduling problem in a container terminal. Eur. J. Oper. Res. 144 (1), 83–107. [20] Tang, L., Zhao, J., Liu, J., 2014. Modeling and solution of the joint quay crane and truck scheduling problem. Eur. J. Oper. Res. 236 (3), 978–990. [21] Sabuncuoglu I. A study of scheduling rules of flexible manufacturing systems: a simulation approach[J]. International Journal of Production Research, 1998, 36(2): 527-546. [22]Klei C M, Kim J. AGV dispatching[J]. International Journal of Production Research, 1996, 34(1): 95-110. [23] Scheduling of AGVs in Automated Container Terminal Based on the Deep Deterministic Policy Gradient (DDPG) Using the Convolutional Neural Network (CNN) Chun Chen, Zhi-Hua Hu and Lei Wang [24] Chen C, Xia B, Zhou B, et al. A reinforcement learning based approach for a multiple-load carrier scheduling problem[J]. Journal of Intelligent Manufacturing, 2015, 26: 1233-1245. [25] Qiu C, Yu F R, Yao H, et al. Blockchain-based software-defined industrial Internet of Things: A Beijing Institute of Technology Bachelor’s Thesis 32 dueling deep ${Q} $-learning approach[J]. IEEE Internet of Things Journal, 2018, 6(3): 4627- 4639. [26] Reinforcement Learning-Driven Real-Time Scheduling of Multiple AGVs, Zhao Xirui, Beijing Institute of Technology [27] Ihsan Sabuncuoglu, and Don L.Hommertzheim. ”Experimental investigation of FMS machine and AGV scheduling rules against the mean flow-time criterion.” International Journal of Production Research 30.7(1992). doi:10.1080/00207549208948110. [28] What Is Reinforcement Learning? Mathworks. [29]F ¿Cuáles son los 10 puertos más importantes del mundo por volumen de tráfico de 2022?por AupaTrans Transporte Internacional | 15 Nov 2022 | Logístics Beijing Institute of Technology Bachelor’s Thesis 33 Appendix/coding Main function import numpy as np import random import torch from WORLD_AGV import World from AGENT_AGV import Agent from render import image_generate import pandas as pd import cv2 import time print("import done") #%% agent = Agent(network_mode=0) world = World() world.reset() stations = cv2.imread("ACT.png") episilon_s = 0.9 episilon_e = 0 n_update_net = 5 n_task = 1000 n_episode = 600 all_reward_buffer = [] all_late_rate_buffer = [] all_average_waiting_time_buffer = [] all_average_distence_buffer = [] all_average_remanent_time_buffer = [] all_average_task_num_buffer = [] all_loss_buffer = [] update_optimizer = False print("ini done") #%% Beijing Institute of Technology Bachelor’s Thesis 34 for network_mode in [0,1,2,3,4,5]: agent = Agent(network_mode=network_mode) world = World() world.reset() ig = image_generate(world.task_pool, world.timeline, world.state, world.AGV_location, n_task) reward_buffer = np.zeros(shape=n_episode) late_rate_buffer = np.zeros(shape=n_episode) average_waiting_time_buffer = np.zeros(shape=n_episode) average_distence_buffer = np.zeros(shape=n_episode) average_remanent_time_buffer = np.zeros(shape=n_episode) average_task_num_buffer = np.zeros(shape=n_episode) loss_buffer = np.zeros(shape=n_episode) for episode_i in range(n_episode): print("network_mode=",network_mode) episode_reward = 0 world.reset() episode_loss = 0 i_step = 0 sumtime_step = 0 sumtime_backward = 0 sumtime_forward = 0 while world.n_task <= n_task: i_step += 1 # print(" >>>>>>>>当前轮次: ",episode_i," 当前步数: ",i_step," <<<<<<<<\n" ) # time.sleep(0.1) epsl = np.interp(episode_i + world.n_task/15,[0, 400] ,[episilon_s, episilon_e]) Beijing Institute of Technology Bachelor’s Thesis 35 # print(" episilon:", epsl) ig.last_AGV_location = world.AGV_location.copy() random_sample = random.random() schedule_OR_not = world.event_settlement() ig.world_time = world.world_time ig.AGV_location = world.AGV_location.copy() # print(ig.AGV_location,ig.last_AGV_location) ig.draw_AGV() ig.draw_arrow() ig.draw_imformation(episode_i, episode_reward/world.n_task,world.late_num/world.n_task) ig.show_img() # time.sleep(1) if cv2.waitKey(1) != -1: break ig.img = stations.copy() ig.timeline = world.timeline ig.state = world.state state = world.state.copy() last_state = world.state.copy() if schedule_OR_not: if random_sample <= epsl: act = world.action_space.sample(world.state[3]) Beijing Institute of Technology Bachelor’s Thesis 36 else: act = agent.online_net.choose_act(world.state) time1 = time.time() state_next, reward, done, info = world.step(act) time2 = time.time() time_step = time2 - time1 sumtime_step += time_step # print(state_next, reward, done) AVG_state_string = state[3] # print(state) AVG_state_list = [int(char) for char in AVG_state_string] state_new = state[:3] + AVG_state_list + state[4:] AVG_state_string = state_next[3] # print(state_next) AVG_state_list = [int(char) for char in AVG_state_string] state_next_new = state_next[:3] + AVG_state_list + state_next[4:] agent.e_pool.add_e(state_new, act, reward, done, state_next_new) # print('state, act, reward, done, state_next\n',state, act, reward, done, state_next) state = state_next episode_reward += reward #simple batch batch_s_tensor, batch_a_tensor, batch_r_tensor, batch_done_tensor, batch_s_next_tensor = agent.e_pool.sample() Beijing Institute of Technology Bachelor’s Thesis 43 def __init__(self, n_task_in_episode = 1500, n_station = 11, distance_between_stations = dbs, n_AGV = 4): self.waiting_weight = 1 self.remanent_weight = 1 self.distance_weight = 1 self.action_space = space(20) self.late_num = 0 self.waiting_time = 0 self.distance = 0 self.remanent_time = 0 self.task_pool_num = 0 self.n_task_in_episode = n_task_in_episode self.n_station = n_station self.distance_between_stations = distance_between_stations self.n_AGV = n_AGV self.AGV_speed = [1.2, 1.4, 1.6, 1.8] self.AGV_location = [3,3,3,3] self.task_pool = {} self.timeline = [] self.n_task = 0 self.world_time = 0 self.state = [0, 0, 0, '0000',0,0,0,0,] #This method needs to be called to initialize the environment each round def reset(self): self.late_num = 0 self.waiting_time = 0 self.distance = 0 self.remanent_time = 0 self.task_pool_num = 0 self.task_pool = {} Beijing Institute of Technology Bachelor’s Thesis 44 self.timeline = [] self.n_task = 0 self.world_time = 0 self.state = [0, 0, 0, '0000',0,0,0,0] self.n_task += 1 self.new_task = generate_task((self.n_task)) new_task = self.new_task.copy() self.timeline.append(['arrival', new_task, -1, new_task[3]]) #This function was used by me to simplify the subsequent code and actually belongs in the STEP section def event_settlement(self): event = self.timeline[0] self.world_time = event[3] self.task_pool_num += len(self.task_pool) if event[0] == 'arrival': self.task_pool[self.n_task] = self.new_task[1:] self.n_task += 1 self.new_task = generate_task(self.n_task, world_time = self.world_time) new_task = self.new_task.copy() if len(self.task_pool) < 100: self.timeline.append(['arrival', new_task, -1, new_task[3]]) else: print(" 任务池中任务数已经达到 100,不加入新任务事件到时间线 ") self.timeline = self.timeline[1:] or [] self.timeline.sort(key = lambda x : x[3]) Beijing Institute of Technology Bachelor’s Thesis 45 all_task_info = self.task_pool.values() remanent_times = [value[3] - self.world_time for value in all_task_info] distences = [value[4] for value in all_task_info] waiting_times = [self.world_time - value[2] for value in all_task_info] task_in_pool = len(self.task_pool) average_remanent_time = np.mean(remanent_times) average_distence = np.mean(distences) average_waiting_time = np.mean(waiting_times) range_remanent_time = np.max(remanent_times) - np.min(remanent_times) range_distence = np.max(distences) - np.min(distences) range_waiting_time = np.max(waiting_times) - np.min(waiting_times) self.state[:3] = [task_in_pool, average_remanent_time, average_distence] self.state[4:] = [average_waiting_time, range_waiting_time, range_remanent_time, range_distence] if '0' in self.state[3]: return True else: return False else: self.timeline = self.timeline[1:] or [] Beijing Institute of Technology Bachelor’s Thesis 46 AGV_released = event[2] AGV_state_string = self.state[3] AGV_state_list = list(AGV_state_string) AGV_state_list[AGV_released] = '0' self.AGV_location[AGV_released] = event[1][1][1] self.state[3] = AGV_state_string[:AGV_released] + '0' + AGV_state_string[AGV_released + 1:] if len(self.task_pool) > 0: return True else: return False #In this section, STEP transfers state based on the selected action, don't forget to update world.state #The content of which is not standardized and will not be explained here def step(self, action): AGV_number = action // 5 rule_number = action % 5 k_v = list(self.task_pool.items()) if rule_number == 0: # print('FCFS') performed = k_v[-1] elif rule_number == 1: # print('STD') k_v.sort(key = lambda x : x[1][4]) Beijing Institute of Technology Bachelor’s Thesis 47 performed = k_v[0] elif rule_number == 2: # print('EDD') k_v.sort(key=lambda x : x[1][3]) performed = k_v[0] elif rule_number == 3: # print('LWT') k_v.sort(key = lambda x : self.world_time - x[1][2]) performed = k_v[-1] elif rule_number == 4: # print('NVF') k_v.sort(key = lambda x : self.distance_between_stations[self.AGV_location[AGV_number], x[1][0]]) performed = k_v[0] f, t, arrival_time, deadline, estimate_distence, ft_distence = performed[1] AGV_state_string = self.state[3] free_AGV = [] for index, character in enumerate(AGV_state_string): if character == '0': free_AGV.append(index) average_tf_distence = np.mean([np.mean([ self.distance_between_stations[self.AGV_location[AGV_ num], task[1][0]] for task in k_v]) for AGV_num in free_AGV]) AGVf_distence = self.distance_between_stations[self.AGV_location[AGV_number], f] distence = AGVf_distence + ft_distence transport_time = np.round(distence / self.AGV_speed[AGV_number], 5) completed_time = self.world_time + transport_time Beijing Institute of Technology Bachelor’s Thesis 48 waiting_time = self.world_time - arrival_time completed_remanent_time = deadline - completed_time remanent_time = deadline - self.world_time free_AGV_speed = np.mean([self.AGV_speed[AGV_num] for AGV_num in free_AGV]) all_task_info = self.task_pool.values() remanent_times = [value[3] - self.world_time for value in all_task_info] distences = [value[4] for value in all_task_info] waiting_times = [self.world_time - value[2] for value in all_task_info] task_in_pool = len(self.task_pool) average_remanent_time = np.mean(remanent_times) if len(all_task_info) > 0 else 0 average_distence = np.mean(distences) if len(all_task_info) > 0 else 0 average_waiting_time = np.mean(waiting_times) if len(all_task_info) > 0 else 0 average_transport_time = (average_distence + average_tf_distence) / free_AGV_speed average_completed_remanent_time = average_remanent_time - average_transport_time if completed_remanent_time < 0: self.late_num += 1 self.waiting_time += waiting_time self.distance += distence self.remanent_time += completed_remanent_time del self.task_pool[performed[0]] Beijing Institute of Technology Bachelor’s Thesis 49 all_task_info = self.task_pool.values() task_in_pool_next = len(self.task_pool) average_remanent_time_next = np.mean([value[3] - self.world_time for value in all_task_info]) if len(all_task_info) > 0 else 0 average_distence_next = np.mean([value[4] for value in all_task_info]) if len(all_task_info) > 0 else 0 average_waiting_time_next = np.mean(waiting_times) if len(all_task_info) > 0 else 0 range_remanent_time_next = np.max(remanent_times) - np.min(remanent_times) range_distence_next = np.max(distences) - np.min(distences) range_waiting_time_next = np.max(waiting_times) - np.min(waiting_times)# 奖励函数 distence_cost = sigmoid(0.25*(average_distence + average_tf_distence - distence)) * 0.25 late_cost = sigmoid(0.02*(completed_remanent_time - average_completed_remanent_time))*2 + sigmoid(0.2*(completed_remanent_time - average_completed_remanent_time)) * 1 time_cost = sigmoid(0.02*((average_distence+average_tf_distence)/free_AGV_speed - transport_time))*0.3 + sigmoid(0.3*((average_distence+average_tf_distence)/free_AGV_speed - transport_time))*0.1 remanent_cost = average_remanent_time_next - average_remanent_time if average_remanent_time_next > 0 else 0 tasknum_amend_weight = np.interp(task_in_pool, [0,20],[0.1,1.0]) remanent_cost_reward = sigmoid(remanent_cost) * 0.3 * (1.5 - tasknum_amend_weight) late_cost_reward = late_cost * (1.1 - tasknum_amend_weight) time_cost_reward = time_cost distence_cost_reward = distence_cost * (1.2 - tasknum_amend_weight) Beijing Institute of Technology Bachelor’s Thesis 50 waiting_reward = - 0.2 if waiting_time > 50 and average_waiting_time_next - average_waiting_time > 0 else 0 delay_reward = -0.4 if completed_remanent_time < 0 and average_remanent_time_next - average_remanent_time < 0 else 0 reward = distence_cost_reward + waiting_reward + delay_reward + remanent_cost_reward + late_cost_reward * 1.1 + time_cost_reward * 1.5 self.state[3] = AGV_state_string[:AGV_number] + '1' + AGV_state_string[AGV_number + 1:] self.state[:3] = [task_in_pool_next, average_remanent_time_next , average_distence_next] self.state[4:] = [average_waiting_time_next , range_waiting_time_next, range_remanent_time_next, range_distence_next] state_next = self.state.copy() self.timeline.append(['complete', performed, AGV_number, np.round(completed_time,5)]) self.timeline.sort(key=lambda x: x[3]) timeline = [(event[0],event[3]) for event in self.timeline] if len(self.task_pool) < 100 and 'arrival' not in [eve[0] for eve in timeline]: new_task = generate_task(self.n_task) self.timeline.append(['arrival', new_task, -1, new_task[3]]) if performed[0] == 800: done = 1 else: done = 0 info = None #Return to next status, reward, completion or not, information return state_next, reward, done, info Beijing Institute of Technology Bachelor’s Thesis 51 #render is an emulation module and is not used here. def render(self, mode='human'): return 0 Agent AGV import numpy as np import random import torch from torch.utils.data.dataset import Dataset from torch import nn from WORLD_AGV import World wd = World(5,5) # experience pool #Define a pool of experience to be used for experience playback. #Agent will retrieve several 4-tuples from the experience pool for loss computation and update the neural network parameters for each completed task class memory: def __init__(self, lenth_of_state, num_of_atpyes, memory_size = 500, batch_size = 50): self.ls = lenth_of_state self.ka = num_of_atpyes self.batch_size = batch_size self.memory_size = memory_size self.s = np.empty(shape=(self.memory_size, self.ls), dtype=np.float32) self.a = np.random.randint(low=0, high=5, size=self.memory_size, dtype=np.uint8) self.done = np.random.randint(low=0, high=2, Beijing Institute of Technology Bachelor’s Thesis 52 size=self.memory_size, dtype=np.uint8) self.r = np.empty(shape=self.memory_size, dtype=np.float32) self.s_next = np.empty(shape=(self.memory_size, self.ls), dtype=np.float32) self.t_e = 0 self.saved_e = 0 #Used to add experience to the experience pool def add_e(self,state, action, reward, done, state_next): state_copy = state.copy() state_next_copy = state_next.copy() self.s[self.t_e] = state_copy self.a[self.t_e] = action self.done[self.t_e] = done self.r[self.t_e] = reward self.s_next[self.t_e] = state_next_copy self.t_e = (self.t_e + 1) % self.memory_size if self.t_e == 0: self.saved_e = self.memory_size self.saved_e = max(self.saved_e, self.t_e) # # print("当前经验池 reward:", self.r[:self.saved_e]) # # print(self.t_e,self.saved_e) #For randomly drawing 4-tuples from the experience pool def sample(self): if self.saved_e > self.batch_size: ridxs = random.sample(range(self.saved_e), self.batch_size) else: ridxs = range(0,self.saved_e) Beijing Institute of Technology Bachelor’s Thesis 59 update_optimizer = False #%% for rule_mode in [0,1,2,3,4]: world = World() world.reset() reward_buffer = np.zeros(shape=n_episode) late_rate_buffer = np.zeros(shape=n_episode) average_waiting_time_buffer = np.zeros(shape=n_episode) average_distence_buffer = np.zeros(shape=n_episode) average_remanent_time_buffer = np.zeros(shape=n_episode) average_task_num_buffer = np.zeros(shape=n_episode) loss_buffer = np.zeros(shape=n_episode) for episode_i in range(n_episode): print("============\n") print("rule_mode=",rule_mode) episode_reward = 0 world.reset() i_step = 0 sumtime_step = 0 while world.n_task <= 1500: i_step += 1 # print(" >>>>>>>>当前轮次: ",episode_i," 当前步数: ",i_step," <<<<<<<<\n" ) schedule_OR_not = world.event_settlement() state = world.state.copy() last_state = world.state.copy() if schedule_OR_not: Beijing Institute of Technology Bachelor’s Thesis 60 AVG_state = world.state[3] act = AVG_state.find("0")*5 + rule_mode time1 = time.time() state_next, reward, done, info = world.step(act) time2 = time.time() time_step = time2 - time1 sumtime_step += time_step # print(state_next, reward, done) episode_reward += reward #Current round print("EPISODE :",episode_i) #Current round average reward print("E_reward:", episode_reward/n_task) #Total time of the current round print("world time:",world.world_time) reward_buffer[episode_i] = episode_reward/n_task late_rate = world.late_num/world.n_task_in_episode average_waiting_time = world.waiting_time/world.n_task_in_episode average_distence = world.distance/world.n_task_in_episode average_remanent_time = world.remanent_time/world.n_task_in_episode average_task_num = world.task_pool_num/world.n_task_in_episode late_rate_buffer[episode_i] = late_rate average_waiting_time_buffer[episode_i] = average_waiting_time average_distence_buffer[episode_i] = average_distence average_remanent_time_buffer[episode_i] = average_remanent_time average_task_num_buffer[episode_i] = average_task_num print("Delay rate:",late_rate) print("Average waiting time:",average_waiting_time) Beijing Institute of Technology Bachelor’s Thesis 61 print("Average transportation distance:",average_distence) print("Average time remaining:",average_remanent_time) print("Average number of tasks in the task pool:",average_task_num) #Time consumed in training print("Total time spent by the step function:",sumtime_step) print("============\n") #Put the above data into a lists all_reward_buffer.append(reward_buffer) all_late_rate_buffer.append(late_rate_buffer) all_average_waiting_time_buffer.append(average_waiting_time_buffer) all_average_distence_buffer.append(average_distence_buffer) all_average_remanent_time_buffer.append(average_remanent_time_buffer) all_average_task_num_buffer.append(average_task_num_buffer) #Storing 2-dimensional lists into excel sheets,you can change the path and filename to suit your situation pd.DataFrame(np.array(all_reward_buffer)).to_excel(r"D:\results\reward_s ingle_rule.xlsx") pd.DataFrame(np.array(all_late_rate_buffer)).to_excel(r"D:\results\late_ rate_single_rule.xlsx") pd.DataFrame(np.array(all_average_waiting_time_buffer)).to_excel(r"D:\re sults\waiting_time_single_rule.xlsx") pd.DataFrame(np.array(all_average_distence_buffer)).to_excel(r"D:\result s\distence_single_rule.xlsx") pd.DataFrame(np.array(all_average_remanent_time_buffer)).to_excel(r"D:\r esults\remanent_time_single_rule.xlsx") pd.DataFrame(np.array(all_average_task_num_buffer)).to_excel(r"D:\result s\task_num_single_rule.xlsx" Beijing Institute of Technology Bachelor’s Thesis 62 Get distance import cv2 # Define the mouse count callback function def mouse_callback(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: print(f"({x}, {y}),") # Read image,put your map image here image = cv2.imread("ACT.png") # Specify target width and height target_width = 1500 target_height = 1500 # Isometric scaling of images, you may not need this step ratio = min(target_width / image.shape[1], target_height / image.shape[0]) new_width = int(image.shape[1] * ratio) new_height = int(image.shape[0] * ratio) resized_image = cv2.resize(image, (new_width, new_height)) # Create a window and set the mouse callback function cv2.namedWindow("image") cv2.setMouseCallback("image", mouse_callback) while True: # Show image cv2.imshow("image", image) # Press ESC to exit the loop if cv2.waitKey(1) == 27: break Beijing Institute of Technology Bachelor’s Thesis 63 # cv2.imwrite("ACT.png", resized_image) # Release windows and destroy all windows cv2.destroyAllWindows() Draw import pandas as pd import numpy as np from matplotlib import pyplot as plt #Change this number to select the data to be plotted model = 0 #When you have finished collecting data from DQNs and #other single rules, you need to reassemble the data # into a table file and store it in the order of the # "color" dictionary below, # e.g.,DQN data in the first row, FCFS data in the second row and so on. color = { "DQN":'b', "FCFS":'y', "STD":'r', "EDD":'c', "LWT":'purple', "NVF":'brown' } algorithms = list(color.keys()) colors = list(color.values()) #Drawing the reward data if model == 0: reward = pd.read_excel(r"finalexcel.xlsx",header=0) print(reward.values[:]) plt.style.use('default') plt.title("reward") plt.xlabel("n_episode") Beijing Institute of Technology Bachelor’s Thesis 64 for i in range(6): plt.plot(reward.values[i,1:],label=algorithms[i],color=colors[i]) plt.legend() plt.gca().set_facecolor('white') plt.grid(True) plt.show() elif model == 1: delay_rate = pd.read_excel(r"finalexcel_delay",header=None) plt.style.use('default') plt.title("delay_rate") plt.xlabel("n_episode") for i in range(6): plt.plot(delay_rate.values[i,1:] ,label=algorithms[i],color=colors[i]) plt.legend() plt.gca().set_facecolor('white') plt.grid(True) plt.show() elif model == 2: reward = pd.read_excel(r"D:\桌面临时 \AGV_RL\final_sheet\final_remanent_time.xlsx", header=None) plt.style.use('default') plt.title("remanent_time") plt.xlabel("n_episode") for i in range(6): plt.plot(reward.values[i, 1:], label=algorithms[i],color=colors[i]) Beijing Institute of Technology Bachelor’s Thesis 65 plt.legend() plt.gca().set_facecolor('white') plt.grid(True) plt.show() Render import random import time import numpy as np import cv2 import matplotlib.pyplot as plt import pandas as pd stations = cv2.imread("ACT.png") AGVs = [] for i in range(4): AGVs.append(cv2.imread(f"AGV{i+1}_mini.png")) print(AGVs[0]) stations_positions = [ (434, 1238), (1046, 1237), (1749, 747), (215, 811), (504, 806), (796, 805), (1085, 806), (1374, 806), (1377, 326), (1085, 325), (791, 325), (501, 325), (217, 325), ] Beijing Institute of Technology Bachelor’s Thesis 66 rectangle_position = [ (430, 1178), (1049, 1178), (1679, 600), (221, 674), (506, 671), (801, 671), (1083, 674), (1382, 673), (1382, 194), (1084, 192), (799, 192), (508, 190), (223, 192), ] info_position = [ (1340,1220),(1630,1220), (1340,1330),(1630,1330) ] dbs_excel = pd.read_csv(r"dbs1.csv",encoding = "utf-8" ,header= 0 ,index_col = 0) dbs = dbs_excel.values[:] # AGV_colors = ["#4472C4","#FFC000","#7030A0","#FF0000"] AGV_colors = [(196,114,68),(0,192,255),(160,48,112),(0,0,255)] class image_generate(): def __init__(self, task_pool, timeline, state, AGV_location, n_task, img=stations): self.img = img self.n_task = n_task self.timeline = timeline self.state = state self.AGV_location = AGV_location Beijing Institute of Technology Bachelor’s Thesis 67 self.last_AGV_location = AGV_location self.last_xy = [(1679, 600),(1679, 600),(1679, 600),(1679, 600)] self.world_time = 0 def draw_arrow(self): St = 0 for AGV in range(4): color = AGV_colors[AGV] rx, ry = info_position[AGV] A, B, C, D = ([rx - 3, ry + 3], [rx - 3, ry - 21], [rx + 80, ry - 21], [rx + 80, ry + 3]) ABCD = np.array([A, B, C, D], dtype=np.int32).reshape(-1, 1, 2) cv2.polylines(self.img, [ABCD], color=color, isClosed=True, thickness=2) for event in self.timeline: if event[1][0] > St: St = event[1][0] if event[0] == 'complete': AGV = event[2] color = AGV_colors[AGV] cv2.putText(self.img, f"{round(event[3]- self.world_time,1)}", info_position[AGV],cv2.FONT_HERSHEY_SIMPLEX, 0.7,color=color, thickness=2) x1, y1 = self.last_xy[AGV] x2, y2 = rectangle_position[event[1][1][0]] x3, y3 = rectangle_position[event[1][1][1]] angle1 = np.arctan2(y2 - y1 , x2 - x1) angle2 = np.arctan2(y3 - y2, x3 - x2) headlenth = 50 headangle = 180 / 13 B2 = [x2 - headlenth / np.cos(np.pi / headangle) * np.cos(angle1 - np.pi / headangle), y2 - headlenth / np.cos(np.pi / Beijing Institute of Technology Bachelor’s Thesis 68 headangle) * np.sin(angle1 - np.pi / headangle)] C2 = [x2 - headlenth / np.cos(np.pi / headangle) * np.cos(angle1 + np.pi / headangle), y2 - headlenth / np.cos(np.pi / headangle) * np.sin(angle1 + np.pi / headangle)] B3 = [x3 - headlenth / np.cos(np.pi / headangle) * np.cos(angle2 - np.pi / headangle),y3 - headlenth / np.cos(np.pi / headangle) * np.sin(angle2 - np.pi / headangle)] C3 = [x3 - headlenth / np.cos(np.pi / headangle) * np.cos(angle2 + np.pi / headangle),y3 - headlenth / np.cos(np.pi / headangle) * np.sin(angle2 + np.pi / headangle)] ABC2 = np.array([[x2, y2], B2, C2],dtype=np.int32).reshape(-1,1,2) ABC3 = np.array([[x3, y3], B3, C3], dtype=np.int32).reshape(-1, 1, 2) # print(ABC2) middle1 = (int((x2 + x1) / 2), int((y2 + y1) / 2)) middle2 = (int((x3 + x2) / 2), int((y3 + y2) / 2)) lenth1 = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 lenth2 = ((x3 - x2) ** 2 + (y3 - y2) ** 2) ** 0.5 tl1 = 30/lenth1 if lenth1 > 0 else 0 tl2 = 30/lenth2 if lenth2 > 0 else 0 if lenth1 > 0: # cv2.polylines(self.img, np.array([(x2,y2),B1,C1]), isClosed=True, color=(0, 255, 0), thickness=2) x = 0 y = 0 space = 12 tline = 15 tx1, ty1, tx2, ty2 = (x1, y1, x1, y1) while abs(x) < abs(x2 - x1) or abs(y) < abs(y2 - y1): cv2.line(self.img, (int(tx1), int(ty1)), (int(tx2), int(ty2)), color=color, thickness=3)