Untitled

mail@pastecode.io avatar
unknown
python
a year ago
1.4 kB
1
Indexable
# Create a custom heuristic class
class MyHeuristic(scip.Heur):
    def __init__(self):
        scip.Heur.__init__(self, name="my_custom_heuristic", desc="Greedy Heuristic for TSP with 2 Vehicles")

    def heur_exec(self, heurtiming, heurtimingmask, result):
        # Create tours for two vehicles using a simple greedy heuristic (nearest neighbor)
        unvisited_cities = set(range(num_cities))
        tours = [[], []]

        # Start from the first city for both vehicles
        current_cities = [0, 0]

        for vehicle in range(2):
            while unvisited_cities:
                current_city = current_cities[vehicle]
                nearest_city = min(unvisited_cities, key=lambda city: scip.distance.euclidean(city_coords[current_city], city_coords[city]))
                tours[vehicle].append(nearest_city)
                current_cities[vehicle] = nearest_city
                unvisited_cities.remove(nearest_city)

        # Set the variables in the solution to represent the tours for both vehicles
        for vehicle in range(2):
            for i in range(num_cities):
                for j in range(num_cities):
                    if i != j:
                        result[x[i, j]] = 1 if (tours[vehicle].index(i) + 1) % num_cities == tours[vehicle].index(j) else 0

# Create an instance of the custom heuristic class
my_heuristic = MyHeuristic()