Permutation optimization with gaoptim package

[This article was first published on Random Miner, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

My recent update of gaoptim package brings up a new function, GAPerm, which can be used to perform combinatorial optimization using the Genetic Algorithm approach.

The example below solves a TSP instance with 10 points around a circumference, then plots the results.
Enjoy it!

# TSP with 10 cities around a circular pattern
require(gaoptim)
op <- par(mfrow = c(2, 1))
n = 10
R = 10
angs = seq(0, 2*pi, length = n)
xp = R * cos(angs) + rnorm(n)
yp = R * sin(angs) + rnorm(n)
xp = c(xp, xp[1])
yp = c(yp, yp[1])
base.M = matrix(c(xp, yp), ncol = 2)
dist.FUN = function(p)
{
p = c(p, p[1])
M.diff = diff(base.M[p, ])
dists = apply(M.diff, 1, function(x)x[1]^2 + x[2]^2)
1/sum(dists)
}
ga1 = GAPerm(dist.FUN, n, popSize = 100, mutRate = 0.3)
ga1$evolve(100)
plot(ga1)
plot(xp, yp, type = 'n', xlab = '', ylab = '', main = 'Best Tour')
res = ga1$bestIndividual()
res = c(res, res[1])
i = 1:n
xi = base.M[res[i], 1]
yi = base.M[res[i], 2]
xf = base.M[res[i + 1], 1]
yf = base.M[res[i + 1], 2]
arrows(xi, yi, xf, yf, col = 'red', angle = 10)
text(base.M[res, 1], base.M[res, 2], 1:n, cex = 0.9, col = 'gray20')
par(op)
view raw ga_perm.R hosted with ❤ by GitHub

To leave a comment for the author, please follow the link and comment on their blog: Random Miner.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)