{"id":61293,"date":"2024-03-30T11:06:35","date_gmt":"2024-03-30T11:06:35","guid":{"rendered":"https:\/\/www.askpython.com\/?p=61293"},"modified":"2025-04-10T20:32:49","modified_gmt":"2025-04-10T20:32:49","slug":"delivery-route-optimization-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/delivery-route-optimization-python","title":{"rendered":"Delivery Route Optimization using Python: A Step-by-Step Guide"},"content":{"rendered":"\n<p><a href=\"https:\/\/www.bluecart.com\/blog\/delivery-route-planning#:~:text=The%20process%20of%20delivery%20route%20planning%20includes%20calculating,stops%2C%20minimizing%20travel%20distance%2C%20and%20improving%20delivery%20efficiency.\" target=\"_blank\" rel=\"noopener\">Delivery route planning<\/a> is one of the most important aspects that helps minimize drivers&#8217; delivery cost and travel time. Popular techniques like Just in Time ( JIT ) and lean management depend tremendously on Delivery route planning.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>Delivery route optimization involves finding the most efficient sequence of stops for a delivery vehicle to minimize time, distance, and resources. Python&#8217;s powerful libraries like Numpy, Scipy, and Pandas provide tools for data manipulation, mathematical optimization, and network analysis, making it an ideal choice for solving complex delivery route optimization problems. With these optimization algorithms in Python, businesses can reduce operational costs and improve efficiency in their delivery processes.<\/em><\/p>\n<\/blockquote>\n\n\n\n<p>In this article, we will use Python&#8217;s tremendous power to find the optimum delivery routes. We will also observe how different libraries in Python are utilized to achieve this purpose.<\/p>\n\n\n\n<p>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/non-linear-equations-constraints\">A Beginner\u2019s Guide to Non-linear Equations and Constraints<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Delivery Route Optimization<\/h2>\n\n\n\n<p>Delivery route optimization generally requires finding a delivery vehicle&#8217;s most efficient sequence of stops to minimize time, distance, and resources. Additionally, certain constraints include time, vehicle capacity, fuel, and traffic conditions. Generally, this problem has been tackled with simple heuristics and human judgment, leading to increased operational costs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Role of Python in Delivery Route Optimization<\/h2>\n\n\n\n<p>Python has a rich environment with powerful optimization tools and algorithms. Python libraries like Numpy, Scipy, and Pandas provide us with different functions for data manipulation, mathematical optimization, network analysis, etc. This makes Python a popular choice for solving complex optimization problems.<\/p>\n\n\n\n<p>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/random-forest-accuracy-linear-regression\">Improve Random Forest Accuracy with Linear Regression Stacking<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Implementing Delivery Route Optimization in Python<\/h2>\n\n\n\n<p>Let us first understand how delivery route optimization is done in Python. Let us look at the different steps involved in the same.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Step 1: Data Collection<\/li>\n\n\n\n<li>Step 2: Data Preprocessing<\/li>\n\n\n\n<li>Step 3: Graph Visualization<\/li>\n\n\n\n<li>Step 4: Defining the Objective Function<\/li>\n\n\n\n<li>Step 5: Optimization Algorithm<\/li>\n\n\n\n<li>Step 6: Result Analysis<\/li>\n<\/ul>\n\n\n\n<p>Now let us understand the topic with the Python code below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Sample delivery locations (latitude, longitude)\ndelivery_locations = np.array(&#x5B;\n    &#x5B;37.7749, -122.4194],  # San Francisco\n    &#x5B;34.0522, -118.2437],  # Los Angeles\n    &#x5B;40.7128, -74.0060],   # New York\n    &#x5B;41.8781, -87.6298]    # Chicago\n])\n\n# Calculate pairwise distances between locations\ndef calculate_distances(locations):\n    num_locations = locations.shape&#x5B;0]\n    distances = np.zeros((num_locations, num_locations))\n    for i in range(num_locations):\n        for j in range(num_locations):\n            if i != j:\n                # Using Haversine formula to calculate distances between coordinates\n                lat1, lon1 = np.radians(locations&#x5B;i])\n                lat2, lon2 = np.radians(locations&#x5B;j])\n                dlon = lon2 - lon1\n                dlat = lat2 - lat1\n                a = np.sin(dlat \/ 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon \/ 2) ** 2\n                c = 2 * np.arcsin(np.sqrt(a))\n                distances&#x5B;i]&#x5B;j] = 6371 * c  # Radius of Earth in kilometers\n    return distances\n\ndistances = calculate_distances(delivery_locations)\n\n# Define optimization objective function (total distance)\ndef total_distance(route, distances):\n    total = 0\n    for i in range(len(route) - 1):\n        total += distances&#x5B;route&#x5B;i]]&#x5B;route&#x5B;i + 1]]\n    total += distances&#x5B;route&#x5B;-1]]&#x5B;route&#x5B;0]]  # Return to starting point\n    return total\n\n# Implement simple greedy algorithm for route optimization\ndef optimize_route_greedy(distances):\n    num_locations = distances.shape&#x5B;0]\n    route = &#x5B;0]  # Starting location\n    remaining_locations = list(range(1, num_locations))  # Exclude starting location\n\n    while remaining_locations:\n        last_location = route&#x5B;-1]\n        nearest_location = min(remaining_locations, key=lambda x: distances&#x5B;last_location]&#x5B;x])\n        route.append(nearest_location)\n        remaining_locations.remove(nearest_location)\n\n    return route\n\n# Perform route optimization\noptimized_route = optimize_route_greedy(distances)\ntotal_dist = total_distance(optimized_route, distances)\n\n# Plot delivery locations and optimized route\ndef plot_route(locations, route):\n    plt.figure(figsize=(10, 6))\n    plt.scatter(locations&#x5B;:, 1], locations&#x5B;:, 0], c=&#039;blue&#039;, label=&#039;Delivery Locations&#039;)\n    for i in range(len(route) - 1):\n        start = route&#x5B;i]\n        end = route&#x5B;i + 1]\n        plt.plot(&#x5B;locations&#x5B;start]&#x5B;1], locations&#x5B;end]&#x5B;1]], &#x5B;locations&#x5B;start]&#x5B;0], locations&#x5B;end]&#x5B;0]], c=&#039;red&#039;)\n    plt.plot(&#x5B;locations&#x5B;route&#x5B;-1]]&#x5B;1], locations&#x5B;route&#x5B;0]]&#x5B;1]], &#x5B;locations&#x5B;route&#x5B;-1]]&#x5B;0], locations&#x5B;route&#x5B;0]]&#x5B;0]], c=&#039;red&#039;)\n    plt.title(&#039;Optimized Delivery Route&#039;)\n    plt.xlabel(&#039;Longitude&#039;)\n    plt.ylabel(&#039;Latitude&#039;)\n    plt.legend()\n    plt.grid(True)\n    plt.show()\n\n# Plot the route\nplot_route(delivery_locations, optimized_route)\n\nprint(&quot;Optimized Route:&quot;, optimized_route)\nprint(&quot;Total Distance:&quot;, total_dist, &quot;km&quot;)\n<\/pre><\/div>\n\n\n<p>From the code above, we can randomly create data using the libraries. We then calculate delivery locations between every pair. We minimize the objective function and optimize it afterwards using a simple greedy algorithm. Let us look at the result below.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"841\" height=\"547\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-Optimization-output.png\" alt=\"Route Optimization Output\" class=\"wp-image-61330\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-Optimization-output.png 841w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-Optimization-output-300x195.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-Optimization-output-768x500.png 768w\" sizes=\"auto, (max-width: 841px) 100vw, 841px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Route Optimization Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"496\" height=\"75\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-optimization-algorithm-result.png\" alt=\"Route Optimization Algorithm Result\" class=\"wp-image-61331\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-optimization-algorithm-result.png 496w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/03\/Route-optimization-algorithm-result-300x45.png 300w\" sizes=\"auto, (max-width: 496px) 100vw, 496px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Route Optimization Algorithm Result<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<p>Here [0,1,2,3] refers to [ San Francisco, Los Angeles, New York, Chicago ] as defined in the code above.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Here you go! Now you know how to optimize delivery routes, which is very important in operational efficiency. Moreover, we also learned how to leverage the power of Python programming language and its optimization algorithms to achieve our purpose.<\/p>\n\n\n\n<p>Hope you enjoyed reading it!!<\/p>\n\n\n\n<p>Recommended: <a href=\"https:\/\/www.askpython.com\/python-modules\/pytorch-to-numpy-conversion\">Converting Between Pytorch Tensors and Numpy Arrays in Python<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Delivery route planning is one of the most important aspects that helps minimize drivers&#8217; delivery cost and travel time. Popular techniques like Just in Time ( JIT ) and lean management depend tremendously on Delivery route planning. Delivery route optimization involves finding the most efficient sequence of stops for a delivery vehicle to minimize time, [&hellip;]<\/p>\n","protected":false},"author":80,"featured_media":63895,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-61293","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/61293","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/80"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=61293"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/61293\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/63895"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=61293"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=61293"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=61293"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}