Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. from subprocess import call
  2. import os
  3. def tsp(points=[], max_time=10, mode=None):
  4. """Wraps the concorde and linkern binaries.
  5. Automatically uses concorde for less than 1000 points,
  6. and uses linkern for more. Maximum of 10 seconds only
  7. applies to linkern. mode can also be set manually."""
  8. if len(points) < 3:
  9. return list(range(len(points)))
  10. if mode is None:
  11. if len(points) < 1000:
  12. mode = 'concorde'
  13. else:
  14. mode = 'linkern'
  15. with open('concorde.dat', 'w') as fp:
  16. fp.write('TYPE : TSP\n')
  17. fp.write('DIMENSION : {}\n'.format(len(points)))
  18. fp.write('EDGE_WEIGHT_TYPE : EUC_2D\n')
  19. fp.write('NODE_COORD_SECTION\n')
  20. for i, point in enumerate(points):
  21. fp.write('{} {} {}\n'.format(i, point[0], point[1]))
  22. fp.write('EOF\n')
  23. if mode == 'concorde':
  24. cmd = 'concorde -x -o concorde.sol concorde.dat'
  25. if mode == 'linkern':
  26. cmd = 'linkern -Q -r 1 -t {} -o concorde.sol concorde.dat'.format(max_time)
  27. call(cmd.split(' '))
  28. os.remove('concorde.dat')
  29. with open('concorde.sol') as fp:
  30. entries = fp.read().split()
  31. if mode == 'concorde':
  32. sol = entries[1:]
  33. else:
  34. sol = entries[2::3]
  35. sol = map(int, sol)
  36. os.remove('concorde.sol')
  37. return sol
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement