Форум программистов, компьютерный форум, киберфорум
Haskell
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
1 / 1 / 0
Регистрация: 18.02.2015
Сообщений: 15
1

TSP

20.10.2015, 19:11. Показов 511. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Вечер добрый, сказано мне заниматься задачей коммивояжёра, но на сей раз используя алгоритм муравьиной колонии и многопоточность. Поискал, полистал, наткнулся на эту известную реализацию. Решил несколько облагородить и приблизить к реальности. С вашей помощью привёл в итоге к тому виду, который хотел: теперь GPS-координаты считываются из файла с реальными данными вместо генерации матрицы со случайными числами, ответ так же записывается в выходной файл, который потом можно построить в виде графика в Matlab\Scilab\etc. И вот тут я заметил некоторый подвох:

TSP


Вид ответа наводит на мысль, что тут вообще работает подобие чистого случайного поиска, а полученное итоговое расстояние хуже, чем у того же алгоритма ближайшего соседа. В чём проблема? Как такое может быть? Я уже просто не могу заметить эту мелочь (склоняюсь к некоторым местам со сравнениями параметров в коде).

Haskell
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)
P.S.: многопоточность с оптимизацией реализую через -threaded -O2 -rtsopts при компиляции и +RTS -N4 -H4096m при запуске

P.P.S: на всякий случай:
код для Scilab
Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[array] = read("luxembourg_problem.dat", -1, 2);
x = array(:,1);
y = array(:,2);
figure(1);
driver("PNG");
xinit("luxembourg_problem.png");
xset("colormap", graycolormap(33));
plot(x, y, "o");
title("Original set");
xend();
 
[array] = read("luxembourg_solution.dat", -1, 2);
x = array(:,1);
y = array(:,2);
figure(2);
driver("PNG");
xinit("luxembourg_solution.png");
xset("colormap", graycolormap(33));
plot(x, y, "-o");
title("Shortest path");
xend();
Код для Matlab
Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
tsp = load('luxembourg_problem.dat');
x = tsp(:,1);
y = tsp(:,2);
figure(1);
plot(x, y, 'o');
saveas(1, 'luxembourg_problem.png');
title('Original set');
 
tsp_res = load('luxembourg_solution.dat');
x1 = tsp_res(:,1);
y1 = tsp_res(:,2);
figure(2);
plot(x1, y1, '-o');
saveas(2, 'luxembourg_solution.png');
title('Shortest path');
Вложения
Тип файла: txt luxembourg_problem.dat.txt (1.4 Кб, 1 просмотров)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.10.2015, 19:11
Ответы с готовыми решениями:

метрическая TSP
Есть граф,все грани имеют вес 3 или 1. Почему может не сработать неравенство треугольника,если при...

TSP локальный поток
Люди добрые помогите пожалуйста. Как мне вывести локальный tsp поток на сайт. Можно целый тег...

TSP: теорема о корректности метода полного перебора
Добрый день! Пишу работу по задаче коммивояжера. Описываю метод brute force - полного перебора....


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
0
20.10.2015, 19:11
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru