1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
| import Control.Parallel -- 'par', 'seq'
import Control.Parallel.Strategies -- parMap
import Data.Array
import Data.Char
import Data.IntSet
import System.IO
import System.Random
boost :: Int
boost = 5
numCities :: Int
numCities = 100
iter :: Int
iter = 4000
input :: String
input = "luxembourg_problem.dat"
output :: String
output = "luxembourg_solution.dat"
-- Матрица является прямоугольным двумерным массивом.
matrix :: Int -> Array (Int,Int) Double
matrix n = array ((0,0),(n-1,n-1)) [((i,j),0.0) | i<-[0..n-1], j<-[0..n-1]]
-- Путь от последнего города к первому.
wrappedPath :: [Int] -> [Int]
wrappedPath path = ((tail path) ++ [(head path)])
pathLength :: Array (Int,Int) Double -> [Int] -> Double
pathLength cities path =
let
f x = cities ! x
pairs = zip path (wrappedPath path)
in
sum (Prelude.map f pairs)
-- Усиление феромонов для городов на путях.
updatePher :: Array (Int,Int) Double -> [Int] -> Array (Int,Int) Double
updatePher pher path =
let
wPath = wrappedPath path
pairs = zip path wPath
incrs = [ (fromIntegral boost) | n <- wPath ]
pairsWithInc = zip pairs incrs
in
accum (+) pher pairsWithInc
-- Испарение феромона.
evaporatePher :: Array (Int,Int) Double -> Int -> Array (Int,Int) Double
evaporatePher pher maxIter =
let
inds = indices pher
decrs = [ ((fromIntegral boost)/(fromIntegral maxIter)) | n <- inds ]
indsWithDecr = zip inds decrs
f x y = if x > y then (x - y) else 0.0
in
accum f pher indsWithDecr
-- Сумма весов для всех путей к городам, примыкающих к данному.
doSumWeight :: Int -> Array (Int,Int) Double -> Array (Int,Int) Double ->
IntSet -> Int -> Double -> Double
doSumWeight city cities pher used current runningTotal =
if city >= numCities then
runningTotal
else
let
incr =
if (member city used) then
0.0
else
(cities!(current, city)) * (1.0 + (pher!(current, city)))
in
doSumWeight (city+1) cities pher used current (runningTotal+incr)
-- Возвращает city в soughtTotal.
findSumWeight :: Int -> Int -> Array (Int,Int) Double ->
Array (Int,Int) Double -> IntSet -> Int -> Double ->
Double -> Int
findSumWeight city nextCity cities pher used current soughtTotal runningTotal =
if (city >= numCities) ||
((not (member city used)) && (runningTotal >= soughtTotal))
then
nextCity
else
let
(incr, nextNextCity) =
if (member city used) then
(0.0, nextCity)
else
((cities!(current,city))*(1.0+(pher!(current, city))),
city)
in
findSumWeight (city+1) nextNextCity cities pher used current
soughtTotal (runningTotal+incr)
-- Возвращает (path, newrGen)
genPathRecurse :: Array (Int,Int) Double -> Array (Int, Int) Double ->
IntSet -> [Int] -> Int -> StdGen -> ([Int],StdGen)
genPathRecurse cities pher used path current rGen =
if (size used) >= numCities then
(path, rGen)
else
let
sumWeight = doSumWeight 0 cities pher used current 0.0
(rndValue, newrGen) = randomR (0.0, sumWeight) rGen
nextCity = findSumWeight 0 0 cities pher used current rndValue 0.0
nextPath = path ++ [nextCity]
nextUsed = insert nextCity used
in
genPathRecurse cities pher nextUsed nextPath nextCity newrGen
-- Возвращает (path, newrGen)
genPath :: Array (Int,Int) Double -> Array (Int, Int) Double -> StdGen ->
([Int], StdGen)
genPath cities pher rGen =
let
(current, newrGen) = randomR (0, numCities-1) rGen
used = insert current empty
path = [current]
in
genPathRecurse cities pher used path current newrGen
-- Возвращает путь
bestPathRecurse :: Array (Int,Int) Double -> Array (Int,Int) Double ->
StdGen -> Int -> Int -> [Int] -> Double -> [Int]
bestPathRecurse cities pher rGen maxIter remainingIter bestPathSoFar
bestLength =
if remainingIter <= 0 then
bestPathSoFar
else
let
(path, newrGen) = genPath cities pher rGen
pathLen = pathLength cities path
(newBestPath,newBestLength,newPher) =
-- Remember we are trying to maximize score.
if pathLen > bestLength then
(path, pathLen, (updatePher pher path))
else
(bestPathSoFar, bestLength, pher)
evaporatedPher = evaporatePher newPher maxIter
in
bestPathRecurse cities evaporatedPher newrGen maxIter
(remainingIter-1) newBestPath newBestLength
-- Возвращает путь
bestPath :: Array (Int,Int) Double -> Int -> Int -> [Int]
bestPath cities rSeed numIter =
let
rGen = mkStdGen rSeed
pher = matrix numCities
in
bestPathRecurse cities pher rGen numIter numIter [] 0.0
-- Возвращает путь
wrapBestPath :: Array (Int,Int) Double -> Int -> Int -> [Int]
wrapBestPath cities rSeed numIter = bestPath cities rSeed numIter
----------------------------------------------------------------------------------
-- Возвращает (path, length)
parallelBestPath :: Array (Int,Int) Double -> Int -> ([Int], Double)
parallelBestPath cities iter =
let
-- 'par' says spark new thread for p1
-- 'seq' says start p2 now also
(path1, path2) = par p1 (seq p2 (p1, p2))
where p1 = wrapBestPath cities 1 iter
p2 = wrapBestPath cities 2 iter
len1 = pathLength cities path1
len2 = pathLength cities path2
(bestPath, bestLen) =
if
len1 > len2
then
(path1,len1)
else
(path2,len2)
in
(bestPath, bestLen)
-- Возвращает (path, length)
parallelBestPathStrategy :: Array (Int,Int) Double -> Int -> ([Int], Double)
parallelBestPathStrategy cities iter =
let
f rSeed = wrapBestPath cities rSeed iter
-- parMap применяет f к каждому элементу списка параллельно
paths = parMap rseq f [1,2]
(path1, path2) = (paths !! 0, paths !! 1)
len1 = pathLength cities path1
len2 = pathLength cities path2
(bestPath, bestLen) =
if
len1 > len2
then
(path1,len1)
else
(path2,len2)
in
(bestPath, bestLen)
----------------------------------------------------------------------------------
-- Преобразование строки GPS-координат к виду (x, y)
readDoubles :: String -> (Double, Double)
readDoubles x = (read y :: Double, read z :: Double)
where y:z:_ = words x
-- Возвращает дистанцию между городами
dist :: (Double, Double) -> (Double, Double) -> Double
dist (x0, y0) (x1, y1) = sqrt $ (x0 - x1) ** 2 + (y0 - y1) ** 2
-- Считывание файла с GPS-координатами
getCoordinats :: String -> IO [(Double, Double)]
getCoordinats file = fmap (Prelude.map readDoubles . Prelude.filter notEmpty . lines) (readFile file)
where notEmpty = not . all isSpace
-- Создание списка из номеров городов и расстояний между ними
distances :: [(Double, Double)] -> [((Int, Int), Double)]
distances coords = let cs = zip [0..] coords in
[ ((i,j), dist x y) | (i,x) <- cs, (j,y) <- cs ]
-- Запуск алгоритма
main :: IO ()
main = do
coordinatsList <- getCoordinats input
handleIn <- openFile input ReadMode
fileContent <- hGetContents handleIn
handleOut <- openFile output WriteMode
let distancesList = distances coordinatsList
cities = array ((0,0), fst $ last distancesList) distancesList
(path, len) = parallelBestPathStrategy cities iter
--(path, len) = parallelBestPath cities iter
mapM (hPutStrLn handleOut) $ Prelude.map (\ x -> (lines fileContent) !! (x-1)) (Prelude.map (+1) path)
hClose handleIn
hClose handleOut
putStrLn $ "Total length : " ++ (show len) |