Skip to content

Commit

Permalink
Merge pull request #19 from matheusdiogenesandrade/master
Browse files Browse the repository at this point in the history
Handling asymmetric TSP instances
  • Loading branch information
chkwon authored Mar 14, 2024
2 parents 929a336 + 75e709c commit 5b2664b
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 5 deletions.
51 changes: 47 additions & 4 deletions src/solver.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
#=
# Roy Jonker, Ton Volgenant. Transforming asymmetric into symmetric traveling salesman problems
# (https://doi.org/10.1016/0167-6377(83)90048-2)
=#
function convert_atsp_to_tsp(dist_mtx::Matrix{Int})

n_nodes = size(dist_mtx, 1)

# infinity constant
U::Int = sum(filter(x::Int -> x > 0, dist_mtx)) + 1

# negative constant
M::Int = U

# symmetric matrix
sym_dist_mtx::Matrix{Int} = fill(U, (2 * n_nodes, 2 * n_nodes))

# fill
for i::Int in 1:n_nodes
for j::Int in 1:n_nodes
value::Int = i == j ? - M : dist_mtx[i, j]

sym_dist_mtx[j, n_nodes + i] = value
sym_dist_mtx[n_nodes + i, j] = value
end
end

return sym_dist_mtx, M
end

function solve_tsp(dist_mtx::Matrix{Int})
if ! issymmetric(dist_mtx)
error("Asymmetric TSP is not supported.")

is_sym_mtx = issymmetric(dist_mtx)

# asymmetric case
if ! is_sym_mtx
# error("Asymmetric TSP is not supported.")
dist_mtx, M::Int = convert_atsp_to_tsp(dist_mtx)
end

n_nodes = size(dist_mtx, 1)
Expand Down Expand Up @@ -36,7 +71,15 @@ function solve_tsp(dist_mtx::Matrix{Int})
write(io, "EOF\n")
end

return __solve_tsp__(filename)
opt_tour, opt_len = __solve_tsp__(filename)

# asymmetric case
if ! is_sym_mtx
opt_tour = opt_tour[isodd.(eachindex(opt_tour))]
opt_len = Int(opt_len + M * n_nodes / 2)
end

return opt_tour, opt_len
end


Expand Down Expand Up @@ -96,4 +139,4 @@ function __solve_tsp__(tsp_file::String)
cleanup(name)

return opt_tour, opt_len
end
end
18 changes: 17 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,29 @@ using Test
end

@testset "Asymmetric TSP" begin

# instance 1
M = [
0 1 7 14
16 0 1 5
7 5 0 1
1 3 16 0
]
@test_throws ErrorException solve_tsp(M)
opt_tour, opt_len = solve_tsp(M)
@show opt_tour, opt_len
@test opt_tour == [1, 2, 3, 4]
@test opt_len == 4

# instance 2
M = [
0 5 19
12 0 15
3 9 0
]
opt_tour, opt_len = solve_tsp(M)
@show opt_tour, opt_len
@test opt_tour == [1, 2, 3]
@test opt_len == 23
end

@testset "Coordinates" begin
Expand Down

0 comments on commit 5b2664b

Please sign in to comment.