Logistics runs on decisions: how much stock to hold and where, which truck takes which order, in what order each driver visits the stops, and when each customer can expect a delivery. Data science in logistics is about making those decisions with data instead of habit, so goods arrive on time with fewer kilometres, fewer trucks and less stock tied up in warehouses.
This guide covers the main use cases of data science in logistics and supply chain management, then builds one of the oldest and most valuable in Python: planning delivery routes for a fleet of trucks, with capacity limits and customer delivery windows. Every number below comes straight from the code in this article.
Uses of data science in logistics
| Use case | Question it answers | Typical data | Common methods |
|---|---|---|---|
| Demand forecasting | How much will each location need next week? | Orders, sales history, promotions, seasonality | Time series forecasting, gradient boosting |
| Inventory optimization | How much stock should each warehouse hold? | Demand forecasts, lead times, stock levels, costs | Safety stock models, simulation, optimization |
| Route optimization | Which truck visits which customers, in what order? | Addresses, order sizes, delivery windows, travel times | Vehicle routing algorithms, local search |
| Delivery time (ETA) prediction | When will this parcel actually arrive? | GPS traces, traffic, past deliveries, weather | Regression, gradient boosting |
| Warehouse operations | Where should each product sit, and how should orders be picked? | Order lines, pick times, product sizes | Clustering, slotting heuristics, simulation |
| Network design | Where should warehouses and hubs be located? | Customer locations, volumes, transport and building costs | Mixed-integer optimization, simulation |
| Fleet maintenance | Which vehicle is likely to break down soon? | Telematics, engine data, service history | Classification, anomaly detection |
| Supplier and disruption risk | Which suppliers or lanes are likely to cause delays? | Lead time history, on-time rates, news and weather | Classification, scenario analysis |
The data usually comes from a few systems: a transport management system (TMS) for shipments and carriers, a warehouse management system (WMS) for stock and picking, the ERP system for orders, and GPS or telematics devices on vehicles. As in most industries, joining these sources, with their different IDs, time zones and levels of detail, is often more work than the modelling itself. Our guide on building and optimizing data pipelines covers that side.
Why route planning is hard
Planning routes sounds simple until you count the options. One truck with 100 stops can drive them in 100! (100 factorial) different orders, a number with 158 digits. Add several trucks, a capacity limit for each truck and a time window for each customer, and checking every plan is impossible. This is the vehicle routing problem with time windows (VRPTW), and it has been studied for decades because small improvements are worth a lot: fuel, driver hours and vehicles are a large part of logistics costs.
Instead of checking every plan, solvers start from a reasonable plan and improve it step by step: moving a stop to another truck, swapping two stops, reversing part of a route, and keeping the changes that make the plan shorter without breaking any rule. The project below compares that approach with the simple rule many people use by hand.
Python project: plan delivery routes with time windows
The data is the RC208 instance from the Solomon benchmark, a set of vehicle routing problems published by Marius Solomon in 1987 and still the standard test for routing algorithms. RC208 has one depot and 100 customers, some in clusters and some spread out, each with a delivery size and a time window. It is a benchmark, not real company data, and that is the point: researchers have found very good solutions for it, so we can measure exactly how close our plan gets to the best known answer.
The optimizer is PyVRP, an open-source vehicle routing solver for Python. You also need vrplib to read the benchmark file, plus NumPy, pandas and Matplotlib:
pip install pyvrp vrplib numpy pandas matplotlib1. Load the problem
The code downloads the RC208 file from the PyVRP repository on GitHub and puts the depot and customers in a pandas table:
import urllib.request
import numpy as np
import pandas as pd
import vrplib
URL = "https://raw.githubusercontent.com/PyVRP/PyVRP/main/tests/data/RC208.vrp"
urllib.request.urlretrieve(URL, "RC208.vrp")
inst = vrplib.read_instance("RC208.vrp")
stops = pd.DataFrame({
"x": inst["node_coord"][:, 0], "y": inst["node_coord"][:, 1],
"demand": inst["demand"],
"opens": inst["time_window"][:, 0], "closes": inst["time_window"][:, 1],
})
customers = stops.iloc[1:] # row 0 is the depot
print(f"{len(customers)} customers, vehicle capacity {inst['capacity']}, "
f"{inst['service_time']} minutes per stop")
print(f"Total demand: {customers['demand'].sum()} units "
f"(at least {int(np.ceil(customers['demand'].sum() / inst['capacity']))} vehicles)")
print(f"Depot open from {stops.loc[0, 'opens']} to {stops.loc[0, 'closes']}")
print((customers["closes"] - customers["opens"]).describe().round(0).to_string())Output:
100 customers, vehicle capacity 1000, 10 minutes per stop
Total demand: 1724 units (at least 2 vehicles)
Depot open from 0 to 960
count 100.0
mean 472.0
std 72.0
min 293.0
25% 420.0
50% 472.0
75% 518.0
max 664.0Times in the benchmark have no fixed unit, so read them as minutes: the depot is open from 0 to 960, a 16-hour day, and every stop takes 10 minutes to unload. Each truck carries up to 1,000 units and the 100 customers need 1,724 units in total, so capacity alone would allow just two trucks. The delivery windows are wide, about 8 hours on average (472 minutes), but they differ from customer to customer, and that turns out to matter a lot.
2. Compute the distances
Every algorithm below needs the distance between each pair of stops. In this benchmark it is the straight-line distance, and driving time equals distance:
# Straight-line distance between every pair of stops, truncated to one
# decimal (the convention used for this benchmark). Driving time = distance.
xy = stops[["x", "y"]].to_numpy()
dist = np.sqrt(((xy[:, None, :] - xy[None, :, :]) ** 2).sum(axis=2))
dist = np.floor(dist * 10) / 10
print(dist.shape)
print(dist[:4, :4])Output:
(101, 101)
[[ 0. 38. 30.8 39.3]
[38. 0. 10.4 3. ]
[30.8 10.4 0. 10. ]
[39.3 3. 10. 0. ]]The result is a 101 by 101 matrix: the depot plus 100 customers. With real addresses you would replace it with road distances and travel times from a routing service, a point covered at the end.
3. A simple plan: nearest neighbour
Before optimizing, build the plan a busy dispatcher might make: send each truck to the closest customer it can still serve, and start a new truck when nothing else fits. The function checks the three rules at every step: the load must fit, the truck must arrive before the customer’s window closes (waiting if it arrives early), and it must be able to get back before the depot closes.
def nearest_neighbour(dist, stops, capacity, service):
"""Send a truck to the nearest customer it can still serve; start a new truck when none is left."""
left = set(range(1, len(stops)))
routes = []
while left:
route, here, load, time = [], 0, 0, 0
while True:
options = []
for c in left:
arrive = max(time + dist[here, c], stops.loc[c, "opens"])
fits = load + stops.loc[c, "demand"] <= capacity
in_time = arrive <= stops.loc[c, "closes"]
back_ok = arrive + service + dist[c, 0] <= stops.loc[0, "closes"]
if fits and in_time and back_ok:
options.append((dist[here, c], c, arrive))
if not options:
break
_, c, arrive = min(options)
route.append(c)
left.remove(c)
load += stops.loc[c, "demand"]
time, here = arrive + service, c
routes.append(route)
return routes
def route_length(routes):
total = 0
for r in routes:
path = [0] + r + [0]
total += sum(dist[a, b] for a, b in zip(path, path[1:]))
return total
greedy = nearest_neighbour(dist, stops, inst["capacity"], inst["service_time"])
print(f"Nearest neighbour: {len(greedy)} trucks, {route_length(greedy):.1f} distance")Output:
Nearest neighbour: 5 trucks, 1391.5 distanceThis baseline is quick and every route is valid, but greedy choices pile up: the closest stop now often leaves a truck far from its remaining customers later.
4. Optimize the routes with PyVRP
Now build the same problem as a PyVRP model. PyVRP works in whole numbers, so the code multiplies distances and times by 10 to keep one decimal place, then divides the result by 10 again. A fixed number of iterations and a seed make the run repeatable:
from pyvrp import Model
from pyvrp.stop import MaxIterations
def build_model(time_windows=True):
"""PyVRP works in whole numbers, so times and distances are in tenths."""
m = Model()
closes = int(stops.loc[0, "closes"]) * 10
m.add_vehicle_type(num_available=inst["vehicles"], capacity=inst["capacity"],
tw_early=0, tw_late=closes)
locs = [m.add_location(x=s["x"], y=s["y"]) for _, s in stops.iterrows()]
m.add_depot(locs[0], tw_early=0, tw_late=closes)
for i, s in customers.iterrows():
m.add_client(locs[i], delivery=int(s["demand"]),
service_duration=inst["service_time"] * 10,
tw_early=int(s["opens"]) * 10 if time_windows else 0,
tw_late=int(s["closes"]) * 10 if time_windows else closes)
for i, a in enumerate(locs):
for j, b in enumerate(locs):
d = int(round(dist[i, j] * 10))
m.add_edge(a, b, distance=d, duration=d)
return m
result = build_model().solve(stop=MaxIterations(20_000), seed=42, display=False)
best = result.best
# Client numbers start at 0; in our table, row 0 is the depot, so add 1
routes = [[stop.idx + 1 for stop in r if stop.is_client()] for r in best.routes()]
print(f"PyVRP: {len(routes)} trucks, {result.cost() / 10:.1f} distance, "
f"feasible: {result.is_feasible()}")
BEST_KNOWN = 776.1
print(f"Gap to best known solution: {(result.cost() / 10 - BEST_KNOWN) / BEST_KNOWN:.1%}")
print(f"Saving vs nearest neighbour: {1 - result.cost() / 10 / route_length(greedy):.0%}")Output:
PyVRP: 5 trucks, 781.2 distance, feasible: True
Gap to best known solution: 0.7%
Saving vs nearest neighbour: 44%The optimized plan drives 781.2 distance units against 1,391.5 for nearest neighbour, a cut of 44% for the same 100 deliveries under the same rules. It is also within 0.7% of the best known solution for RC208, 776.1, and the run took about 10 seconds in our test.
One difference: the best known solution uses four trucks, and this plan uses five. That is because the model only minimizes distance, and an extra truck costs nothing in it. In a real fleet each vehicle and driver has a daily cost, which you can add with the fixed_cost argument of add_vehicle_type; the solver will then use fewer trucks whenever the saving outweighs the extra distance.
5. Draw the routes
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 7))
colors = ["#c8242c", "#1f4e79", "#2e8b57", "#d4a017", "#6a4c93", "#4a4a4a"]
for k, r in enumerate(routes):
path = [0] + r + [0]
ax.plot(stops.loc[path, "x"], stops.loc[path, "y"], "-o", ms=3, lw=1.4,
color=colors[k % len(colors)], label=f"Truck {k + 1}: {len(r)} stops")
ax.plot(stops.loc[0, "x"], stops.loc[0, "y"], "s", ms=11, color="black", label="Depot")
ax.set_title(f"{len(routes)} trucks, {result.cost() / 10:.1f} total distance")
ax.legend(frameon=False, fontsize=9, loc="upper center",
bbox_to_anchor=(0.5, 0), ncol=3)
ax.set_aspect("equal")
ax.set_xticks([]); ax.set_yticks([])
for side in ax.spines.values():
side.set_visible(False)
fig.savefig("routes.png", dpi=150, bbox_inches="tight")
plt.show()
A quick way to judge a routing plan is to look at it. Good plans give each truck its own area and have few crossing lines; the nearest-neighbour plan, by contrast, sends trucks back and forth across the map to reach customers left over at the end.
6. Check what limits the plan
Next, look at how full each truck is and how far it drives:
for k, r in enumerate(routes, 1):
load = customers.loc[r, "demand"].sum()
path = [0] + r + [0]
length = sum(dist[a, b] for a, b in zip(path, path[1:]))
print(f"Truck {k}: {len(r):>2} stops, load {load:>4} of {inst['capacity']} "
f"({load / inst['capacity']:.0%}), distance {length:.1f}")Output:
Truck 1: 21 stops, load 387 of 1000 (39%), distance 146.0
Truck 2: 15 stops, load 238 of 1000 (24%), distance 110.3
Truck 3: 24 stops, load 381 of 1000 (38%), distance 198.3
Truck 4: 23 stops, load 432 of 1000 (43%), distance 194.1
Truck 5: 17 stops, load 286 of 1000 (29%), distance 132.5No truck is even half full: loads run from 24% to 43% of capacity. Capacity is not what limits this plan. Time is: each truck has to reach every customer inside that customer’s window and still get back before the depot closes. This is common in real delivery operations too, and it changes what to fix. Bigger trucks would not help here; better time slots would.
7. What do delivery windows cost?
A model makes it easy to price a business rule. Solve the same problem again, with every customer accepting a delivery at any time of day:
loose = build_model(time_windows=False).solve(stop=MaxIterations(20_000), seed=42, display=False)
print(f"With delivery windows: {result.cost() / 10:.1f} distance, "
f"{result.best.num_routes()} trucks")
print(f"Without delivery windows: {loose.cost() / 10:.1f} distance, "
f"{loose.best.num_routes()} trucks")
print(f"Delivery windows add {result.cost() / loose.cost() - 1:.1%} to the distance")Output:
With delivery windows: 781.2 distance, 5 trucks
Without delivery windows: 652.6 distance, 2 trucks
Delivery windows add 19.7% to the distanceWithout the windows the same deliveries fit on 2 trucks and 652.6 distance units. The windows add 19.7% to the distance and 3 trucks to the plan. A logistics team can use exactly this kind of analysis to decide which delivery slots to offer, how much to charge for a narrow slot, or which customers to ask for more flexibility.
From benchmark to real routes
A real routing project keeps the same structure but needs more data and more rules:
- Road distances and travel times instead of straight lines, from a routing service or open-source tools such as OSRM, ideally varying by time of day.
- Clean addresses. Wrong or vague addresses become wrong coordinates, and every route built on them is wrong. Geocoding and checking addresses is often the first job; see cleaning and preprocessing data in Python.
- More rules: driver breaks and shift lengths, several depots, different vehicle types, pickups as well as deliveries. PyVRP supports several of these, including shift lengths, multiple depots, mixed fleets and pickups.
- Re-planning during the day when customers add or cancel orders, a truck runs late or traffic changes.
- Good forecasts of service time. Ten minutes per stop is a benchmark assumption; real stops vary with the size of the order and the building, and predicting them is a regression problem in its own right.
Demand forecasting and inventory
Routing decides how goods move; forecasting decides how many goods need to move at all. Demand forecasts drive how much stock each warehouse holds, how many drivers and vehicles to book, and when to order from suppliers. A forecast that is too low means empty shelves and expensive rush deliveries; one that is too high ties up cash in stock and warehouse space.
Most forecasting projects start with sales or order history per product and location, then add calendar effects, promotions and prices. The time series analysis tutorial covers the core techniques, and our retail data science guide shows how forecasts connect to stock decisions on the store side.
What does a logistics data scientist do?
Logistics data scientists work with transport planners, warehouse managers and supply chain teams. Typical projects include demand forecasting, route and network optimization, delivery time prediction, carrier performance analysis and warehouse layout. The work needs SQL, pandas and machine learning, and, more than in most fields, some knowledge of optimization, because many logistics questions ask for the best plan rather than a prediction. The data science career guide covers how to get started.
Project ideas for logistics data science
- Extend this project: add a fixed cost per truck and see how the plan changes, or narrow the time windows and measure how many trucks you need.
- More benchmark problems: the Solomon benchmark has 56 problems in six groups, with clustered, random and mixed customer locations and short or long planning horizons. Comparing nearest neighbour and PyVRP across them shows when optimization helps most.
- Demand forecasting: forecast daily orders per product or region, then use the forecast to set stock levels.
- Delivery time prediction: predict how long each delivery will take from distance, time of day and order size, and compare a linear regression with a gradient boosting model.
- Warehouse location: group customers with k-means clustering to suggest where depots could go, then test the suggestions with the routing model above.
The PyVRP documentation at pyvrp.org covers its features and options, and the Solomon benchmark page at SINTEF describes the benchmark and lists best known results.
Related reading
- Data science by industry
- Data science in manufacturing, with a predictive maintenance project
- Data science in retail, with a Python project
- Data science in insurance, with a Python project
- Time series analysis in Python
FAQ
How is data science used in logistics?
To forecast demand, set stock levels, plan delivery routes, predict delivery times, organize warehouses, choose where to put depots and hubs, maintain vehicles and spot supply chain risks. Demand forecasting and route optimization are usually the projects with the clearest savings.
What is route optimization?
Route optimization finds the best way to assign deliveries to vehicles and order the stops on each route, usually to minimize distance, time or cost, while respecting rules such as vehicle capacity, delivery time windows and driver shifts. Researchers call it the vehicle routing problem.
Which Python libraries can solve vehicle routing problems?
PyVRP, used in this article, is an open-source solver built for vehicle routing. Google OR-Tools also has a widely used routing solver, and general optimization libraries such as PuLP can model small routing problems exactly.
How much can route optimization save?
It depends on how routes are planned today. In this article’s benchmark, optimized routes were 44% shorter than a simple nearest-neighbour plan for the same 100 deliveries. Savings in practice are usually smaller when planners are already experienced, but even a few percent of fuel and driver time adds up across a fleet.
What data is used in logistics data science?
Orders and shipments from the transport and warehouse management systems, stock and orders from the ERP system, GPS and telematics data from vehicles, customer addresses, delivery windows, carrier performance records and, for forecasting, sales history and calendar data.
What is the Solomon benchmark?
A set of 56 vehicle routing problems with time windows, published by Marius Solomon in 1987. Each has 100 customers with delivery sizes and time windows. Because the best known solutions are published, the problems are a standard way to test routing algorithms.
