Project-Platypus / Platypus

A Free and Open Source Python Library for Multiobjective Optimization
GNU General Public License v3.0
563 stars 153 forks source link

TSP example does not make a roundtrip #141

Closed grafkevin closed 4 years ago

grafkevin commented 4 years ago

Hello everyone,

I was looking into the example code for a traveling salesman problem (TSP) however the code does not ensure a roundtrip, i.e. it does not return to the first node. You can check this by printing the full result object.

algorithm = GeneticAlgorithm(problem)
algorithm.run(1000, callback = lambda a : print(a.nfe, unique(nondominated(algorithm.result))[0]))

example result: 100 Solution[[56, 25, 45, 26, 72, 75, 5, 24, 20, 7, 62, 61, 64, 2, 74, 39, 35, 17, 73, 23, 52, 36, 65, 10, 27, 67, 11, 1, 15, 8, 30, 12, 60, 46, 54, 51, 31, 70, 69, 66, 49, 43, 14, 18, 71, 48, 0, 6, 13, 58, 41, 40, 3, 33, 44, 63, 55, 4, 28, 42, 68, 47, 21, 22, 29, 16, 34, 9, 59, 19, 37, 50, 32, 57, 53, 38]|507916|0]

TSP code: https://github.com/Project-Platypus/Platypus/blob/master/examples/tsp.py

Thanks in advance! Kevin

dhadka commented 4 years ago

@grafkevin There's an implicit step from the last city back to the first. This shows up in the objective function calculation using the modulo (%) operator:

sum([dist(cities[tour[i]], cities[tour[(i + 1) % len(cities)]]) for i in range(len(tour))])

To verify, we can plug in the optimal tour for the PR76 problem:

opt = [[0, 75, 74, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 73, 14, 15, 16, 17, 36, 35, 37, 38, 39, 33, 34, 32, 31, 28, 29, 30, 18, 19, 25, 26, 27, 42, 41, 53, 52, 51, 54, 55, 56, 57, 58, 59, 40, 60, 61, 62, 63, 72, 71, 70, 64, 65, 50, 48, 49, 66, 69, 67, 68, 46, 47, 43, 44, 45, 23, 24, 20, 21, 22]]
print(tsp(opt))

> 108159