Ejemplo n.º 1
0
def solve_routing(points, nodeCount):

    distanceMatrix = DistanceMatrix(points)

    routing = pywrapcp.RoutingModel(nodeCount, 1)
    routing.UpdateTimeLimit(5 * 60000)

    parameters = pywrapcp.RoutingSearchParameters()
    # Setting first solution heuristic (cheapest addition).
    parameters.first_solution = 'PathCheapestArc'
    #parameters.solution_limit = 10
    parameters.guided_local_search = True
    #parameters.simulated_annealing = True
    #parameters.tabu_search = True
    parameters.no_lns = True

    cost = distanceMatrix.get

    routing.SetCost(cost)

    #search_log = routing.solver().SearchLog(10000000, routing.CostVar())
    #routing.AddSearchMonitor(search_log)

    assignment = routing.SolveWithParameters(parameters, None)

    solution = []

    node = routing.Start(0)
    while not routing.IsEnd(node):
        solution.append(node)
        node = assignment.Value(routing.NextVar(node))

    return (assignment.ObjectiveValue(), solution)
Ejemplo n.º 2
0
    def tsp_path(vec_list):
        param = pywrapcp.RoutingParameters()
        param.use_light_propagation = False
        pywrapcp.RoutingModel.SetGlobalParameters(param)
        routing = pywrapcp.RoutingModel(len(vec_list), 1)
        parameters = pywrapcp.RoutingSearchParameters()
        # parameters.first_solution = 'Savings'
        parameters.no_lns = False
        parameters.no_tsp = False
        parameters.no_tsplns = True
        func = Pathfinder.get_distance_func(vec_list)
        routing.SetArcCostEvaluatorOfAllVehicles(func)

        # Solve, returns a solution if any.
        path = list()
        assignment = routing.SolveWithParameters(parameters, None)
        if assignment:
            route_number = 0
            node = routing.Start(route_number)
            while not routing.IsEnd(node):
                path.append(vec_list[node])
                node = assignment.Value(routing.NextVar(node))
            return path
        else:
            return list()
Ejemplo n.º 3
0
    def setup(self, size):
        '''
        Configuration of the TSP module
        :param size: the size of the matrix
        '''
        param = pywrapcp.RoutingParameters()
        param.use_light_propagation = self.use_light_propagation
        pywrapcp.RoutingModel.SetGlobalParameters(param)

        # TSP of size FLAGS.tsp_size
        # Second argument = 1 to build a single tour (it's a TSP).
        # Nodes are indexed from 0 to FLAGS_tsp_size - 1, by default the start of
        # the route is node 0.
        self.routing = pywrapcp.RoutingModel(size, 1)

        self.parameters = pywrapcp.RoutingSearchParameters()

        # Setting first solution heuristic (cheapest addition).
        self.parameters.first_solution = 'PathCheapestArc'

        # Disabling Large Neighborhood Search, comment out to activate it.
        self.parameters.no_lns = True
        self.parameters.no_tsp = False
Ejemplo n.º 4
0
def solve_routing(customers, customerCount, vehicleCount, vehicleCapacity):

    distanceMatrix = DistanceMatrix(customers)

    print customerCount
    print vehicleCount

    routing = pywrapcp.RoutingModel(customerCount, vehicleCount)
    routing.UpdateTimeLimit(15 * 60 * 1000)

    parameters = pywrapcp.RoutingSearchParameters()
    # Setting first solution heuristic (cheapest addition).
    #parameters.first_solution = 'PathCheapestArc'
    #parameters.solution_limit = 10
    parameters.guided_local_search = True
    #parameters.simulated_annealing = True
    #parameters.tabu_search = True
    parameters.no_lns = True
    

    cost = distanceMatrix.get

    routing.SetDepot(0)
    routing.SetCost(cost)

    capacity = lambda i,j: customers[i].demand

    routing.AddDimension(capacity, 0, vehicleCapacity, True, "capacity")


    search_log = routing.solver().SearchLog(1000000, routing.CostVar())
    routing.AddSearchMonitor(search_log)
    
    routing.CloseModel()
    
    (obj, initial) = solve_default(customers, customerCount, vehicleCount, vehicleCapacity)
    
    
    print "loading initial assignment"
    assignment = routing.solver().Assignment()
    for vehicle in range(vehicleCount):
    	tour = initial[vehicle]
    	fromIndex = routing.Start(vehicle)
    	for toIndex in tour:
    		fromVar = routing.NextVar(fromIndex)
    		if not assignment.Contains(fromVar):
    			assignment.Add(fromVar)
    		assignment.SetValue(fromVar, toIndex)
    		fromIndex = toIndex
    	
    	lastVar = routing.NextVar(fromIndex)
    	if not assignment.Contains(lastVar):
    		assignment.Add(lastVar)
    	assignment.SetValue(lastVar, routing.End(vehicle))
        		
    print "solving"
    assignment = routing.SolveWithParameters(parameters, assignment)

    vehicle_tours = []

    for vehicle in range(vehicleCount):

        node = routing.Start(vehicle)
        
        solution = []

        #skip empty route        
        if not routing.IsEnd(assignment.Value(routing.NextVar(node))):
            first = True
            while not routing.IsEnd(node):
                if not first: #first is the capacity left                
                    solution.append(node)
                first = False
                node = assignment.Value(routing.NextVar(node))

        vehicle_tours.append(solution)

    return (assignment.ObjectiveValue() / 100, vehicle_tours)
Ejemplo n.º 5
0
def main(_):
    # Create routing model
    if FLAGS.tsp_size > 0:
        # Set a global parameter.
        param = pywrapcp.RoutingParameters()
        param.use_light_propagation = FLAGS.light_propagation
        pywrapcp.RoutingModel.SetGlobalParameters(param)

        # TSP of size FLAGS.tsp_size
        # Second argument = 1 to build a single tour (it's a TSP).
        # Nodes are indexed from 0 to FLAGS_tsp_size - 1, by default the start of
        # the route is node 0.
        routing = pywrapcp.RoutingModel(FLAGS.tsp_size, 1)

        parameters = pywrapcp.RoutingSearchParameters()
        # Setting first solution heuristic (cheapest addition).
        parameters.first_solution = 'PathCheapestArc'
        # Disabling Large Neighborhood Search, comment out to activate it.
        parameters.no_lns = True
        parameters.no_tsp = False

        # Setting the cost function.
        # Put a callback to the distance accessor here. The callback takes two
        # arguments (the from and to node inidices) and returns the distance between
        # these nodes.
        matrix = RandomMatrix(FLAGS.tsp_size)
        matrix_callback = matrix.Distance
        if FLAGS.tsp_use_random_matrix:
            routing.SetArcCostEvaluatorOfAllVehicles(matrix_callback)
        else:
            routing.SetArcCostEvaluatorOfAllVehicles(Distance)
        # Forbid node connections (randomly).
        rand = random.Random()
        rand.seed(FLAGS.tsp_random_seed)
        forbidden_connections = 0
        while forbidden_connections < FLAGS.tsp_random_forbidden_connections:
            from_node = rand.randrange(FLAGS.tsp_size - 1)
            to_node = rand.randrange(FLAGS.tsp_size - 1) + 1
            if routing.NextVar(from_node).Contains(to_node):
                print 'Forbidding connection ' + str(from_node) + ' -> ' + str(
                    to_node)
                routing.NextVar(from_node).RemoveValue(to_node)
                forbidden_connections += 1

        # Solve, returns a solution if any.
        assignment = routing.SolveWithParameters(parameters, None)
        if assignment:
            # Solution cost.
            print assignment.ObjectiveValue()
            # Inspect solution.
            # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1
            route_number = 0
            node = routing.Start(route_number)
            route = ''
            while not routing.IsEnd(node):
                route += str(node) + ' -> '
                node = assignment.Value(routing.NextVar(node))
            route += '0'
            print route
        else:
            print 'No solution found.'
    else:
        print 'Specify an instance greater than 0.'
Ejemplo n.º 6
0
def main():
    # Create a set of customer, (and depot) stops.
    customers = Customers(num_stops=50,
                          min_demand=1,
                          max_demand=15,
                          box_size=40,
                          min_tw=3,
                          max_tw=6)

    # Create callback fns for distances, demands, service and transit-times.
    dist_fn = customers.return_dist_callback()
    dem_fn = customers.return_dem_callback()
    serv_time_fn = customers.make_service_time_call_callback()
    transit_time_fn = customers.make_transit_time_callback()

    def tot_time_fn(a, b):
        """
        The time function we want is both transit time and service time.
        """
        return serv_time_fn(a, b) + transit_time_fn(a, b)

    # Create a list of inhomgenious vehicle capacities as integer units.
    capacity = [50, 75, 100, 125, 150, 175, 200, 250]

    # Create a list of inhomogenious fixed vehicle costs.
    cost = [int(100 + 2 * np.sqrt(c)) for c in capacity]

    # Create a set of vehicles, the number set by the length of capacity.
    vehicles = Vehicles(capacity=capacity, cost=cost)

    # check to see that the problem is feasible, if we don't have enough
    # vehicles to cover the demand, there is no point in going further.
    assert (customers.get_total_demand() < vehicles.get_total_capacity())

    # Create callback functions for vehicle capacity
    cap_fn = vehicles.return_capacity_callback()
    # Set the starting nodes, and create a callback fn for the starting node.
    start_fn = vehicles.return_starting_callback(customers,
                                                 sameStartFinish=True)

    # Set a global parameter.
    glob_param = pywrapcp.RoutingParameters()
    glob_param.use_light_propagation = False
    pywrapcp.RoutingModel.SetGlobalParameters(glob_param)

    # Make the routing model instance.
    routing = pywrapcp.RoutingModel(
        customers.number,  # int number
        vehicles.number,  # int number
        vehicles.starts,  # List of int start depot
        vehicles.ends)  # List of int end depot

    parameters = pywrapcp.RoutingSearchParameters()
    # Setting first solution heuristic (cheapest addition).
    parameters.first_solution = 'PathCheapestArc'
    # Disabling Large Neighborhood Search, comment out to activate it.
    parameters.no_lns = False
    parameters.no_tsp = True
    parameters.time_limit = 10 * 1000  # 10 seconds

    # Set the cost function (distance callback) for each arc, homogenious for
    # all vehicles.
    routing.SetArcCostEvaluatorOfAllVehicles(dist_fn)

    # Set vehicle costs for each vehicle, not homogenious.
    for veh in vehicles.vehicles:
        routing.SetVehicleFixedCost(int(veh.index), veh.cost)

    # Add a dimension for vehicle capacities
    null_capacity_slack = 0
    routing.AddDimensionWithVehicleCapacity(
        dem_fn,  # demand callback
        null_capacity_slack,
        cap_fn,  # capacity callback
        True,
        "Capacity")
    # Add a dimension for time and a limit on the total time_horizon
    routing.AddDimension(
        tot_time_fn,  # total time function callback
        customers.time_horizon,
        customers.time_horizon,
        True,
        "Time")

    time_dimension = routing.GetDimensionOrDie("Time")
    for cust in customers.customers:
        if cust.tw_open is not None:
            time_dimension.CumulVar(int(cust.index)).SetRange(
                cust.tw_open.seconds, cust.tw_close.seconds)
    """
     To allow the dropping of orders, we add disjunctions to all the customer
    nodes. Each disjunction is a list of 1 index, which allows that customer to
    be active or not, with a penalty if not. The penalty should be larger
    than the cost of servicing that customer, or it will always be dropped!
    """
    # To add disjunctions just to the customers, make a list of non-depots.
    non_depot = set(range(customers.number))
    non_depot.difference_update(vehicles.starts)
    non_depot.difference_update(vehicles.ends)
    penalty = 400000  # The cost for dropping a node from the plan.
    nodes = [routing.AddDisjunction([int(c)], penalty) for c in non_depot]

    # This is how you would implement partial routes if you already knew part
    # of a feasible solution for example:
    # partial = np.random.choice(list(non_depot), size=(4,5), replace=False)

    # routing.CloseModel()
    # partial_list = [partial[0,:].tolist(),
    #                 partial[1,:].tolist(),
    #                 partial[2,:].tolist(),
    #                 partial[3,:].tolist(),
    #                 [],[],[],[],[]]
    # print(routing.ApplyLocksToAllVehicles(partial_list, False))

    # Solve the problem !
    assignment = routing.SolveWithParameters(parameters, None)

    # The rest is all optional for saving, printing or plotting the solution.
    if assignment:
        # save the assignment, (Google Protobuf format)
        save_file_base = os.path.realpath(__file__).split('.')[0]
        if routing.WriteAssignment(save_file_base + '_assignment.ass'):
            print('succesfully wrote assignment to file ' + save_file_base +
                  '_assignment.ass')

        print('The Objective Value is {0}'.format(assignment.ObjectiveValue()))

        plan_output, dropped = vehicle_output_string(routing, assignment)
        print(plan_output)
        print('dropped nodes: ' + ', '.join(dropped))

        # you could print debug information like this:
        # print(routing.DebugOutputAssignment(assignment, 'Capacity'))

        vehicle_routes = {}
        for veh in range(vehicles.number):
            vehicle_routes[veh] = build_vehicle_route(routing, assignment,
                                                      customers, veh)

        # Plotting of the routes in matplotlib.
        fig = plt.figure()
        ax = fig.add_subplot(111)
        # Plot all the nodes as black dots.
        clon, clat = zip(*[(c.lon, c.lat) for c in customers.customers])
        ax.plot(clon, clat, 'k.')
        # plot the routes as arrows
        plot_vehicle_routes(vehicle_routes, ax, customers, vehicles)

    else:
        print('No assignment')