Efficiency Comparison of Ant Colony Algorithms in different languages

Source: Internet
Author: User

Ant Colony Optimization for TSP in Psyco Python

Http://go2web0.appspot.com /_? Bytes

This is a continuation of Parallel Ant Colony Optimization for TSP in Standard ML, Multi-Core Ant Colony Optimization for TSP in Haskell, Multi-Core Ant Colony Optimization for TSP in Erlang, and Multi-Core Ant Colony Optimization for TSP in Scala. see first page for Ant Colony and TSP problem description. here the program has been rewritten in the programming language Python.

Python is a dynamically typed language and is normally interpreted. it is object-oriented but has some functional features such as map, reduce, and lambda functions. all functions in Python are Parametrically Polymorphic (see my article Types and Programming versions for details), which creates difficulties for efficient compilation.

Psyco is a compiler for Python. it is a just-in-time compiler, and uses the run-time type usage information to determine which functions shoshould be native-compiled. it is a specializing compiler -- it will create multiple instantiations of the same function with different type parameters. it is very easy to use; just add 2 lines to the top of your program:
Import psyco
Psyco. full ()
It is an experimental project. the documentation warns that map and lambda perform poorly, and that list comprehensions (often a reasonable substitute) shocould be used instead. the original developer has moved on to work on the PyPy project; I shoshould investigate that later.

Compared to other tested versions the performance of uncompiled Python is average; with Psyco compilation it is surprisingly good.

See previous for details of test environment. Same test as before, but only a single core and 1/4 the work.
Versions
Python 2.5.2 (r252: 60911, Jun 25 2008, 17:58:32) [GCC 4.3.1] On linux2 from Debian apt-Get.

Psyco psyco-1.6-linux.i386-2.5 from SourceForge
Command lines
Time./ant. py
Results

Erlang Haskell Scala mlton_sml Python psyco
93 22 10 1.5 40 5.5
All times in seconds.

Python version:

 

#! /Usr/bin/Python

# Ant. py
# Eric rol00002008

# This program generates a random array of distances between cities, then uses
# Ant Colony Optimization to find a short path traversing all the cities --
# The travelling salesman problem.
#
# In this version of Ant Colony Optimization each ant starts in a random city.
# Paths are randomly chosed with probability inversely proportional to
# Distance to the next city. At the end of its travel the ant updates
# Pheromone matrix with its path if this path is the shortest one yet found.
# The probability of later ants taking a path is increased by the pheromone
# Value on that path. pheromone values evaporate (decrease) over time.
#
# In this impementation weights between cities actually represent
# (Maxdistance-Dist), so we are trying to maximize the score.
#
# Usage: ant seed boost iterations cities
# Seed for random number generator (1, 2, 3 ...).
# This seed controls the city distance array. Remote
# Executions have their seed values fixed (1, 2) So each will
# Produce a different result.
# Boost pheromone boost for best path. 5 appears good.
#0 disables pheromones, providing random search.
# Iterations Number of ants to be run.
# Cities number of cities.

# Enable psyco Compiler
Import psyco
Psyco. Full ()

Import random

# Type Matrix = array [array [double]
# Type Path = list [int]
# Type cityset = hashset [int]

# Int * int-> Matrix
Def randommatrix (n, upperbound, seed ):
Random. Seed (SEED)
M = []
For R in range (n ):
Sm = []
M. append (sm)
For c in range (n ):
Sm. append (upperBound * random. random ())
Return m

# Path-> Path
Def wrappedPath (path ):
Return path [1:] + [path [0]

# Matrix * Path-> double
Def pathLength (cities, path ):
Pairs = zip (path, wrappedPath (path ))
Return sum ([cities [r] [c] for (r, c) in pairs])

# Boosts pheromones for cities on path.
# Matrix * Path * int-> unit
Def updatePher (pher, path, boost ):
Pairs = zip (path, wrappedPath (path ))
For (r, c) in pairs:
Pher [r] [c] = pher [r] [c] + boost

# Matrix * int-> unit
Def evaporatePher (pher, maxIter, boost ):
Decr = boost/float (maxIter)
For r in range (len (pher )):
For c in range (len (pher [r]):
If pher [r] [c]> decr:
Pher [r] [c] = pher [r] [c]-decr
Else:
Pher [r] [c] = 0.0

# Sum weights for all paths to cities adjacent to current.
# Matrix * cityset * int-> double
Def dosumweight (cities, Pher, used, current ):
Runningtotal = 0.0
For city in range (LEN (cities )):
If not used. has_key (city ):
Runningtotal = (runningtotal +
Cities [current] [City] * (1.0 + Pher [current] [City])
Return runningtotal

# Returns city at soughttotal.
# Matrix * cityset * int * double-> int
Def findsumweight (cities, Pher, used, current, soughttotal ):
Runningtotal = 0.0
Next = 0
For city in range (len (cities )):
If runningTotal> = soughtTotal:
Break
If not used. has_key (city ):
RunningTotal = (runningTotal +
Cities [current] [city] * (1.0 + pher [current] [city])
Next = city
Return next

# Matrix * Matrix-> Path
Def genPath (cities, pher ):
Current = random. randint (0, len (cities)-1)
Path = [current]
Used = {current: 1}
While len (used) <len (cities ):
SumWeight = doSumWeight (cities, pher, used, current)
RndValue = random. random () * sumWeight
Current = findSumWeight (cities, pher, used, current, rndValue)
Path. append (current)
Used [current] = 1
Return path

# Matrix * int-> Path
Def bestPath (cities, seed, maxIter, boost ):
Pher = randomMatrix (len (cities), 0, 0)
Random. seed (seed)
Bestlename = 0.0
BestPath = []
For iter in range (maxIter ):
Path = genPath (cities, pher)
PathLen = pathLength (cities, path)
If pathLen> bestLen:
# Remember we are trying to maximize score.
UpdatePher (pher, path, boost)
BestLen = pathLen
BestPath = path
EvaporatePher (pher, maxIter, boost)
Return bestPath

Def main ():
Seed = 1
Boost = 5
Iter = 1000
NumCities = 1, 200
MaxDistance = 100
CityDistanceSeed = 1
Print "starting"
Cities = randomMatrix (numCities, maxDistance, cityDistanceSeed)
Path = bestPath (cities, seed, iter, boost)
Print path
Print "len =", pathLength (cities, path)

If _ name _ = "_ main __":
Main ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.