• Stars
    star
    316
  • Rank 132,587 (Top 3 %)
  • Language
    Python
  • License
    Other
  • Created almost 13 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Travelling Salesman Problem solver in pure Python + some visualizers

Suboptimal Travelling Salesman Problem (TSP) solver

In pure Python.

This project provides a pure Python code for searching sub-optimal solutions to the TSP. Additionally, demonstration scripts for visualization of results are provided.

The library does not requires any libraries, but demo scripts require:

  • Numpy
  • PIL (Python imaging library)
  • Matplotlib

The library works under both Python 2 and 3.

Modules provided:

  • tsp_solver.greedy : Basic greedy TSP solver in Python
  • tsp_solver.greedy_numpy : Version that uses Numpy matrices, which reduces memory use, but performance is several percents lower
  • tsp_solver.demo : Code for the demo applicaiton

Scripts provided

  • demo_tsp : Generates random TSP, solves it and visualises the result. Optionally, result can be saved to the numpy-format file.
  • tsp_numpy2svg : Generates neat SVG image from the numpy file, generated by the demo_tsp.

Both applications support a variety of command-line keys, run them with --help option to see additional info.

Installation

Install from PyPi:

 # pip install tsp_solver2

or

 $ pip install --user tsp_solver2

(Note taht tsp_solver package contains an older version).

Manual installation:

 # python setup.py install

Alternatively, you may simply copy the tsp_solver/greedy.py to your project.

Usage

The library provides a greedy solver for the symmetric TSP. Basic usage is:

from tsp_solver.greedy import solve_tsp

#Prepare the square symmetric distance matrix for 3 nodes:
#  Distance from A to B is 1.0
#                B to C is 3.0
#                A to C is 2.0
D = [[],
     [1.0],
     [2.0, 3.0]]

path = solve_tsp( D )

#will print [1,0,2], path with total length of 3.0 units
print(path)

The triangular matrix D in the above example represents the following graph with three nodes A, B, and C:

Square matrix may be provided, but only left triangular part is used from it.

Utility functions

tsp_solver.util.path_cost(distance_matrix, path) Caclulate total length of the given path, using the provided distance matrix.

Using fixed endpoints

It is also possible to manually specify desired start and/or end nodes of the path. Note that this would usually increase total length of the path. Example, using the same distance matrix as above, but now requiring that path starts at A (index 0) and ends at C (index 2):

D = [[],
     [1.0],
     [2.0, 3.0]]

path = solve_tsp( D, endpoints = (0,2) )
#will print path [0,1,2]
print(path)

New in version 0.4: it is not possible to specify only one of two end points:

solve_tsp( D, endpoints = (None,2) )
solve_tsp( D, endpoints = (0,None) )

Round trip paths

To find a round trip path, that returns to the starting node, specify the same value to both endpoints:

path = solve_tsp( D, endpoints = (0,0) )
#will print path [0,1,2,0]
print(path)

Note that round trip paths are one step longer.

Neither solution quality nor complexity depends on the endpoints specified, so it is safe to use (0,0) when don't care.

Algorithm

The library implements a simple "greedy" algorithm:

  1. Initially, each vertex belongs to its own path fragment. Each path fragment has length 1.
  2. Find 2 nearest disconnected path fragments and connect them.
  3. Repeat, until there are at least 2 path fragments.

This algorightm has polynomial complexity.

Optimization

Greedy algorithm sometimes produces highly non-optimal solutions. To solve this, optimization is provided. It tries to rearrange points in the paths to improve the solution. One optimization pass has O(n^4) complexity. Note that even unlimited number of optimization paths does not guarantees to find the optimal solution.

Performance

This library neither implements a state-of-the-art algorithm, nor it is tuned for a high performance.

It however can find a decent suboptimal solution for the TSP with 4000 points in several minutes. The biggest practical limitation is memory: O(n^2) memory is used.

Demo

To see a demonstration, run

$ make demo

without installation. The demo requires Numpy and Matplotlib python libraries to be installed.

Testing

To execute unit tests, run

$ make test

Change log

Version 0.4.1

Added possibility to search for round trip paths, when endpoints coincide.

Version 0.4

Added possibility to specify only one of end points.

More Repositories

1

fft-image-experiments

Experiments with applying Fourier transofrms to various plane-filling curves and patterns
Python
218
star
2

hyperbolic-ca-simulator

Simulator of cellular automata on hyperbolic (Lobachevsky) plane, in browser.
CoffeeScript
38
star
3

js-revca

Reversible cellular automata simulator in HTML5 + Java Script.
CoffeeScript
32
star
4

singlerot-smooth

"Single Rotation" cellular automaton demonstration with Lanczos smoothing
CoffeeScript
21
star
5

Pentagrid

Cellular automation simulator on hyperbolic plane
Java
13
star
6

slit-scan

Make slit-scan photos from video files
C++
12
star
7

pylinprog

Pure Python implementation of Simplex Method for Linear Programming problem
Python
12
star
8

log-zoom

Transform images to logarithmic polar coordinates, and create composite images from the sequence of zooms.
Python
12
star
9

minkovski-ca

Simulator for cellular automata defined on regular lattices on Minkovski plane
CoffeeScript
11
star
10

babushkin_arch

An implementation of the rational approximation encoding algorithm ("Babushkin compression")
Python
9
star
11

knuth_bendix

Knuth-Bendix algorithm implementation for finitely generated groups, in Python.
Python
7
star
12

t2dca

Exploring cellular automata with 2 dimensions of time
JavaScript
7
star
13

json-stream-writer

A simple class for streamed generation of JSON format
C++
5
star
14

ca-freq-colorizer

Use frequency analysys to make colorful animations from binary cellular automata
Python
4
star
15

markdown-simplechem

Markdown extension to write simple chemical equations conveniently
Python
4
star
16

revca_spaceship_searcher

C++
2
star
17

pyla

Pure Python linear algebra
Python
2
star
18

critters

Critters and other cellular automatons, with Python, Numpy and C++.
Python
2
star
19

text2fb2

Convert simple text to FB2 format, with python.
Python
2
star
20

dmishin.github.io

Publishing html/js projects
HTML
2
star
21

python-remote

Library for transparent communication between several python processes
Python
1
star
22

dmishin-pyscript

(Just my own toy projects, I will never finish)
Python
1
star
23

aozora2odt

Simple converter from txt files with Aozora ruby to the *.odt documents with ruby and other formatting.
Python
1
star
24

ifs

playing with iterated function systems
C++
1
star
25

py-invars

playing with nonlinear algorithm of determining invariants of the vector cloud
Python
1
star
26

irotate-visualizer

Visualize invariants of integer rotation
C++
1
star
27

pseudo_generator

A simple header-only C++ library, that imitates Python's generators (i.e. continuations)
C++
1
star
28

pick-geometry

CLI program to query user coordinates of a rectangle on a image
Python
1
star
29

libeuler

A small library of number-theoretic fucntions, written during solving Euler quest.
Python
1
star
30

speedread

Speed reading application with smart alignment rules and adjustable scheduling. Java+Swing.
Java
1
star