2021-12-07 09:13:09 +01:00
|
|
|
#!/usr/bin/env python3
|
2015-12-03 08:58:56 +01:00
|
|
|
from collections import namedtuple
|
|
|
|
|
from ortools.constraint_solver import pywrapcp
|
|
|
|
|
|
2020-09-19 18:37:36 +02:00
|
|
|
VEHICLE_COUNT = 30
|
2015-12-03 08:58:56 +01:00
|
|
|
VEHICLE_CAPACITY = 200
|
|
|
|
|
Customer = namedtuple("Customer", ['index', 'demand', 'x', 'y'])
|
|
|
|
|
|
2020-09-19 18:37:36 +02:00
|
|
|
print('Init')
|
2015-12-03 08:58:56 +01:00
|
|
|
|
|
|
|
|
customers = list()
|
2020-09-19 18:37:36 +02:00
|
|
|
customers.append(Customer(0, 0, 0, 0))
|
|
|
|
|
customers.append(Customer(1, 1, 1.0, 1.0))
|
|
|
|
|
customers.append(Customer(1, 1, 2.0, 2.0))
|
2015-12-03 08:58:56 +01:00
|
|
|
customer_count = len(customers)
|
|
|
|
|
|
2020-09-19 18:37:36 +02:00
|
|
|
manager = pywrapcp.RoutingIndexManager(3, VEHICLE_COUNT, 0)
|
|
|
|
|
routing = pywrapcp.RoutingModel(manager)
|
2015-12-03 08:58:56 +01:00
|
|
|
|
2020-09-19 18:37:36 +02:00
|
|
|
print('Demand Constraint')
|
|
|
|
|
demands = []
|
2015-12-03 08:58:56 +01:00
|
|
|
for i in range(0, customer_count):
|
|
|
|
|
demands.append(customers[i][1])
|
2020-09-19 18:37:36 +02:00
|
|
|
routing.AddVectorDimension(demands, VEHICLE_CAPACITY, True, "Demand")
|
2015-12-03 08:58:56 +01:00
|
|
|
|
2020-09-19 18:37:36 +02:00
|
|
|
print('Adding Costs')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def distance_callback(from_index, to_index):
|
2015-12-03 08:58:56 +01:00
|
|
|
#static just for the sake of the example
|
|
|
|
|
return 1
|
2020-09-19 18:37:36 +02:00
|
|
|
|
|
|
|
|
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
|
|
|
|
|
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
|
2015-12-03 08:58:56 +01:00
|
|
|
|
|
|
|
|
routing.CloseModel()
|
|
|
|
|
|
2020-09-19 18:37:36 +02:00
|
|
|
assignment = routing.Solve(None)
|
2015-12-03 08:58:56 +01:00
|
|
|
|
|
|
|
|
# Inspect solution and extract routes
|
2020-09-19 18:37:36 +02:00
|
|
|
routes = []
|
2015-12-03 08:58:56 +01:00
|
|
|
for i in range(0, routing.vehicles()):
|
|
|
|
|
|
|
|
|
|
route_number = i
|
|
|
|
|
routes.append([])
|
|
|
|
|
node = routing.Start(route_number)
|
2020-09-19 18:37:36 +02:00
|
|
|
route = []
|
2015-12-03 08:58:56 +01:00
|
|
|
route.append(0)
|
|
|
|
|
if routing.IsVehicleUsed(assignment, i):
|
|
|
|
|
while True:
|
|
|
|
|
node = assignment.Value(routing.NextVar(node))
|
|
|
|
|
|
|
|
|
|
if not routing.IsEnd(node):
|
|
|
|
|
route.append(int(node))
|
2020-09-19 18:37:36 +02:00
|
|
|
else:
|
2015-12-03 08:58:56 +01:00
|
|
|
break
|
|
|
|
|
|
|
|
|
|
route.append(0)
|
|
|
|
|
routes[route_number].append(route)
|
|
|
|
|
|
|
|
|
|
#This are the routes as list of lists
|
|
|
|
|
routes = [el[0] for el in routes]
|
|
|
|
|
|
|
|
|
|
#Now try to read the routes into a new assigment object fails
|
2020-09-19 18:37:36 +02:00
|
|
|
assignment2 = routing.ReadAssignmentFromRoutes(routes, True)
|