Created
December 28, 2021 15:26
-
-
Save MaxvanHaastrecht/67799f674fd84735b8b13f0248eab607 to your computer and use it in GitHub Desktop.
Creating a TSP ILP in PuLP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pulp as pl | |
| # Define PuLP model | |
| model = pl.LpProblem('TSP', pl.LpMinimize) | |
| # Define binary variables | |
| x = pl.LpVariable.dicts('x', ((i, j) for i in range(n_perm) for j in range(n_perm)), cat = 'Binary') | |
| # Set the objective function | |
| model += pl.lpSum(cost_dict[permutations[i], permutations[j]] * x[i, j] for i in range(n_perm) for j in range(n_perm)) | |
| # Define the constraints | |
| for i in range(n_perm): | |
| # Do not allow loops | |
| model += x[i, i] == 0 | |
| for i in range(n_perm): | |
| # Exactly one outgoing edge | |
| model += pl.lpSum(x[i, j] for j in range(n_perm)) == 1 | |
| # Exactly one incoming edge | |
| model += pl.lpSum(x[j, i] for j in range(n_perm)) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment