Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from subprocess import call
- import os
- def tsp(points=[], max_time=10, mode=None):
- """Wraps the concorde and linkern binaries.
- Automatically uses concorde for less than 1000 points,
- and uses linkern for more. Maximum of 10 seconds only
- applies to linkern. mode can also be set manually."""
- if len(points) < 3:
- return list(range(len(points)))
- if mode is None:
- if len(points) < 1000:
- mode = 'concorde'
- else:
- mode = 'linkern'
- with open('concorde.dat', 'w') as fp:
- fp.write('TYPE : TSP\n')
- fp.write('DIMENSION : {}\n'.format(len(points)))
- fp.write('EDGE_WEIGHT_TYPE : EUC_2D\n')
- fp.write('NODE_COORD_SECTION\n')
- for i, point in enumerate(points):
- fp.write('{} {} {}\n'.format(i, point[0], point[1]))
- fp.write('EOF\n')
- if mode == 'concorde':
- cmd = 'concorde -x -o concorde.sol concorde.dat'
- if mode == 'linkern':
- cmd = 'linkern -Q -r 1 -t {} -o concorde.sol concorde.dat'.format(max_time)
- call(cmd.split(' '))
- os.remove('concorde.dat')
- with open('concorde.sol') as fp:
- entries = fp.read().split()
- if mode == 'concorde':
- sol = entries[1:]
- else:
- sol = entries[2::3]
- sol = map(int, sol)
- os.remove('concorde.sol')
- return sol
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement