summaryrefslogtreecommitdiff
path: root/tsp.py
blob: 5530fb084eec8975052db114c004febd83e995f0 (plain)
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#!/usr/bin/env python
# coding=utf-8

'''
 Various Travelling Salesman Problem algorithms
 Author : Guillaume "iXce" Seguin
 Email  : guillaume@segu.in

 Copyright (C) 2007 Guillaume Seguin

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor,
 Boston, MA  02110-1301, USA.
'''

import pygtk
pygtk.require ("2.0")
import gtk
import gobject

gtk.gdk.threads_init ()

import random
import math
import cairo
import threading

MAX_X = 500 # Max X (virtual) coordinate
MAX_Y = 500 # Max Y (virtual) coordinate
OFFSET_X = 20 # Left & right offsets (for drawing purpose)
OFFSET_Y = 20 # Top & bottom offsets (for drawing purpose)

CITY_RADIUS = 3 # Radius of the visual city points

SHOW_NAMES = True

INIT_RANDOM = "Random"
INIT_GREEDY = "Greedy"
INIT_GREEDY_BEST = "Greedy (Best)"

INITS = [INIT_RANDOM, INIT_GREEDY, INIT_GREEDY_BEST]  # Init methods choices
ALGOS = ["2opt", "Annealing"] # Algorithms choices 
COUNTS = [10, 25, 50, 100, 250] # City counts choices

# Default settings
DEFAULT_INIT = INIT_RANDOM
DEFAULT_ALGO = "Annealing"
DEFAULT_COUNT = 50

class Color:
    '''Helper object for color handling'''

    def __init__ (self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

CITY_COLOR = Color (0.9, 0, 0) # Red
TEXT_COLOR = Color (0, 0, 0)   # Black
PATH_COLOR = Color (0, 0, 0.8) # Blue

def distance (c1, c2):
    '''Compute the distance between two points'''
    return math.sqrt ((c2.x - c1.x) ** 2 + (c2.y - c1.y) ** 2)

def draw_map (cities, cr):
    '''Draw a map of points on a Cairo context'''
    global CITY_COLOR, TEXT_COLOR, SHOW_NAMES
    def draw_point (city):
        '''Helper function to draw a point'''
        cr.arc (city.x, city.y, CITY_RADIUS, 0, 2 * math.pi)
        cr.fill ()
    def draw_name (city):
        '''Helper function to draw a point label'''
        cr.move_to (city.x + 6, city.y + 6)
        cr.show_text ("%d" % city.i)
        cr.fill ()
    cr.set_operator (cairo.OPERATOR_OVER)
    cr.set_source_rgb (CITY_COLOR.r, CITY_COLOR.g, CITY_COLOR.b)
    map (draw_point, cities.values ())
    if not SHOW_NAMES:
        return
    cr.set_source_rgb (TEXT_COLOR.r, TEXT_COLOR.g, TEXT_COLOR.b)
    map (draw_name, cities.values ())

def draw_path (cities, path, cr):
    '''Draw a path on a Cairo context'''
    global PATH_COLOR
    prev = path[0]
    list = path[1:] + [prev]
    length = 0
    cr.set_operator (cairo.OPERATOR_OVER)
    cr.set_source_rgb (PATH_COLOR.r, PATH_COLOR.g, PATH_COLOR.b)
    cr.set_line_width (1)
    cr.move_to (cities[prev].x, cities[prev].y)
    for i in list:
        cr.line_to (cities[i].x, cities[i].y)
    cr.stroke ()

class City:
    '''Helper object for points map handling'''

    i = 0
    x = 0
    y = 0

    def __init__ (self, i):
        '''Initialize object (generate random coordinates)'''
        self.i = i
        self.x = OFFSET_X + random.uniform (0, MAX_X)
        self.y = OFFSET_Y + random.uniform (0, MAX_Y)

class Path (list):
    '''Helper object that automagically computes the path length'''

    context = None

    def __init__ (self, context, list):
        '''Initalize list & object'''
        self.context = context
        for i in list:
            self.append (i)
        self.compute_length ()

    def compute_length (self):
        '''Compute length, the computation is pretty straight-forward'''
        prev = self[0]
        list = self[1:] + [prev] # Add the first element of the list to 
                                 # the end to close the path
        length = 0
        for i in list:
            length += self.context.dists[prev][i]
            prev = i
        self.length = length

class Context:
    '''Helper object handling the city map and distances computations, and
featuring some basic methods such as nearest neighbours (a.k.a. greedy)
algorithm'''

    count = 0
    dists = {}
    map = {}

    def __init__ (self, delayed = False, count = DEFAULT_COUNT):
        '''Initialize object'''
        self.count = count
        if not delayed:
            self.prepare ()

    def prepare (self):
        '''Prepare context data'''
        self.generate_map ()
        self.compute_dists ()
    
    def generate_map (self):
        '''Generate a map of random points'''
        # FIXME: maybe should we check for duplicates?
        self.map = {}
        for i in range (0, self.count):
            self.map[i] = City (i)

    def compute_dists (self):
        '''Compute the distances array'''
        self.dists = {}
        # Only compute half of the array, it's symetric
        for i in range (0, self.count):
            self.dists[i] = {}
            for j in range (i, self.count):
                self.dists[i][j] = distance (self.map[i], self.map[j])
        for i in range (0, self.count):
            for j in range (0, i):
                self.dists[i][j] = self.dists[j][i]

    def draw_to_cr (self, cr, path = None):
        '''Draw map & path (if any) to the given Cairo context'''
        if path:
            draw_path (self.map, path, cr)
        draw_map (self.map, cr)

    def draw_png (self, filename, path = None):
        '''Dump map & path (if any) to a PNG file'''
        surface = cairo.ImageSurface (cairo.FORMAT_ARGB32,
                                      MAX_X + 2 * OFFSET_X,
                                      MAX_Y + 2 * OFFSET_Y)
        cr = cairo.Context (surface)
        cr.set_operator (cairo.OPERATOR_CLEAR)
        cr.paint ()
        self.draw_to_cr (cr, path)
        surface.write_to_png (filename)

    def nearest_neighbours (self, start = 0):
        '''Nearest neighbours (a.k.a. greedy) algorithm'''
        def reduce_nearest (d1, d2):
            '''Reduce function to find the nearest point of a list'''
            if d1[1] < d2[1]: return d1
            else: return d2
        path = [start]
        while len (path) < len (self.map):
            current = path[-1]
            dists = self.dists[current].items ()
            dists = filter (lambda (i, dist): i not in path, dists)
            next = reduce (reduce_nearest, dists)
            path.append (next[0])
        return Path (self, path)

    def nearest_neighbours_best (self):
        '''Nearest neighbours algorithm applied to each city of the list'''
        best = None
        for i in self.map.keys ():
            path = self.nearest_neighbours (start = i)
            if not best or path.length < best.length:
                best = path
        return best

    def random_path (self):
        '''Random path generator'''
        path = range (0, self.count)
        random.shuffle (path)
        return Path (self, path)

'''
A few notes about the way algorithms should be implemented:
* The class name should look like "Algo_Name" where Name is the name that will
be displayed in the GUI
* The "run" method is what will be run by the running thread
* The "run" method must use the "yield" mechanism to raise the current path as
it goes on. This lets the running thread nicely interrupt execution if needed,
and lets it quickly halt.
'''

class Algo:
    '''Base class for algorithm, please extend me!'''

    context = None

    def __init__ (self, context):
        '''Initialize object'''
        self.context = context

    def run (self):
        '''Implement this in your algorithm subclass'''

class Algo_2opt (Algo):
    '''Classic 2opt algorithm'''

    def run (self, path = None):
        '''Algorithm main loop'''
        if not path:
            path = self.context.nearest_neighbours_best ()
        best = path
        while True:
            yield path
            path = self.do_2opt (best)
            if path.length < best.length:
                best = path

    def do_2opt (self, path):
        '''Do a simple transformation: given two points i and j, reverse the
path between i and j (e.g. [0, 1, 2, 3, 4, 5] with i = 1 and j = 4 becomes
[0, 1, 3, 2, 4, 5]. This is better than just exchanging two points because the
former only breaks 2 links while the latters breaks 4.'''
        i, j = random.sample (path, 2)
        if i < j:
            segment = path[i + 1:j]
            segment.reverse ()
            return Path (self.context, path[:i + 1] + segment + path[j:])
        else:
            '''If i > j, loop around the list'''
            segment = path[i + 1:] + path[:j]
            segment.reverse ()
            return Path (self.context, path[j:i + 1] + segment)

class Algo_Annealing (Algo_2opt):
    '''Simulated annealing algorithm'''

    t0      = 10 # Initial temperature
    updates = 0  # Accepted updates counter

    def run (self, path = None):
        '''Algorithm main loop'''
        self.updates = 0
        if not path:
            path = self.context.nearest_neighbours_best ()
        current = best = path
        while True:
            yield current
            next = self.do_2opt (current)
            if next.length < best.length:
                current = best = next
                self.updates += 1
            elif next.length <= current.length \
              or self.accept_change (current, next):
                current = next
                self.updates += 1

    def accept_change (self, current, next):
        '''Choose if a worse path is accepted anyway, this is the key of the
simulated annealing algorithm: the path will be accepted if the result of
exp (- (next length - current length) / temperature) is greater than a random
floating point number, where temperature evolves according to a given law
based on the current number of iterations (or so)'''
        delta = next.length - current.length
        p0 = random.random ()
        t0 = 1
        p = math.exp (- delta / self.temp ())
        if p0 <= p:
            return True
        else:
            return False

    def temp (self):
        '''Temperature law: t = t0 - accepted_updates * 0.001 (min'd to 0.1)'''
        return max (self.t0 - self.updates * 0.001, 0.1)

class AlgoThread (threading.Thread):
    '''Threading running a given algorithm'''

    context   = None
    algo      = None
    gui       = None
    canvas    = None
    init      = False
    terminate = False

    runner    = None
    best      = None

    def __init__ (self, context, algo, gui, canvas, init = None):
        '''Initialize the thread'''
        threading.Thread.__init__ (self)
        self.context = context
        self.algo = algo
        self.gui = gui
        self.canvas = canvas
        self.init = init

    def update_best (self, path):
        '''Update GUI to reflect the finding of a better solution'''
        gtk.gdk.threads_enter ()
        if not path: length = None
        else: length = path.length
        self.gui.update_best (length)
        self.canvas.redraw (path = path, damage = True)
        gtk.gdk.threads_leave ()

    def run (self):
        '''Main thread loop: generate a path (randomly or not, according to
the current settings) and run the algorithm on it until the stop () function
is called.'''
        if not self.runner:
            self.update_best (path = None)
            if self.init == INIT_GREEDY_BEST:
                for i in self.context.map:
                    if self.terminate:
                        return
                    path = self.context.nearest_neighbours (start = i)
                    if not best or path.length < best.length:
                        self.best = path
            elif self.init == INIT_GREEDY:
                self.best = self.context.nearest_neighbours ()
            else:
                self.best = self.context.random_path ()
            self.update_best (path = self.best)
            self.runner = self.algo.run (self.best)
        while not self.terminate:
            path = self.runner.next ()
            if not self.best or path.length < self.best.length:
                self.best = path
                self.update_best (path = self.best)

    def resume (self):
        '''Resume thread: since we can't start a Thread twice, let's copy
its data into a new Thread, start the new one and return it'''
        thread = AlgoThread (self.context, self.algo, self.gui, self.canvas,
                             self.init)
        thread.runner = self.runner
        thread.best = self.best
        thread.start ()
        return thread

    def stop (self):
        '''Stop thread'''
        self.terminate = True

class AlgoCanvas (gtk.DrawingArea):
    '''Canvas widget for displaying maps & paths'''

    context = None
    surface = None
    path    = None

    def __init__ (self, context):
        '''Initialize widget'''
        gtk.DrawingArea.__init__ (self)
        self.context = context
        self.connect ("expose-event", self.expose)
        self.set_size_request (MAX_X + 2 * OFFSET_X, MAX_Y + 2 * OFFSET_Y)

    def redraw (self, path = None, damage = False):
        '''Redraw surface using the given path (if any)'''
        self.path = path
        self.surface = cairo.ImageSurface (cairo.FORMAT_ARGB32,
                                           MAX_X + 2 * OFFSET_X,
                                           MAX_Y + 2 * OFFSET_Y)
        cr = cairo.Context (self.surface)
        cr.set_operator (cairo.OPERATOR_CLEAR)
        cr.paint ()
        self.context.draw_to_cr (cr, self.path)
        if damage:
            '''Damage widget if requested'''
            self.queue_draw ()

    def expose (self, widget, event):
        '''Handle expose events: copy the saved surface to the new widget
Cairo context, clipping the draw area if needed'''
        cr = self.window.cairo_create ()
        if not self.surface:
            self.redraw ()
        cr.set_source_surface (self.surface)
        cr.rectangle (event.area.x, event.area.y,
                      event.area.width, event.area.height)
        cr.clip ()
        cr.paint ()
        return False

class AlgoGui (gtk.Window):
    '''GUI for testing TSP algorithms'''

    context = None
    algo    = None
    thread  = None

    canvas       = None
    init_box     = None
    algo_box     = None
    count_box    = None
    gen_button   = None
    start_button = None
    stop_button  = None

    best_label   = None
    config_label = None

    def __init__ (self):
        '''Initialize GUI'''
        global INITS, ALGOS, COUNTS
        gtk.Window.__init__ (self)
        self.context = Context (delayed = True) # Prepare Context
        self.algo = None
        # GTK stuff
        self.set_title ("TSP Algorithm test GUI")
        self.set_position (gtk.WIN_POS_CENTER)
        self.connect ("delete-event", gtk.main_quit)
        box = gtk.VBox ()
        self.add (box)
        self.canvas = AlgoCanvas (self.context) # Our canvas
        alignment = gtk.Alignment (0.5, 0.5, 0, 0)
        alignment.add (self.canvas)
        box.pack_start (alignment, False, False)
        # Settings
        hbox = gtk.HBox ()
        alignment = gtk.Alignment (0.5, 0.5, 0, 0)
        alignment.add (hbox)
        box.pack_start (alignment, False, False)
        # Init methods
        self.init_box = gtk.combo_box_new_text ()
        map (self.init_box.append_text, INITS)
        self.init_box.set_active (INITS.index (DEFAULT_INIT))
        hbox.pack_start (self.init_box, False, False)
        # Algorithms
        self.algo_box = gtk.combo_box_new_text ()
        map (self.algo_box.append_text, ALGOS)
        self.algo_box.set_active (ALGOS.index (DEFAULT_ALGO))
        hbox.pack_start (self.algo_box, False, False)
        # City counts
        self.count_box = gtk.combo_box_new_text ()
        map (lambda i: self.count_box.append_text ("%d cities" % i), COUNTS)
        self.count_box.set_active (COUNTS.index (DEFAULT_COUNT))
        hbox.pack_start (self.count_box, False, False)
        # Show labels button
        names_button = gtk.CheckButton (label = "Show labels")
        names_button.connect ("toggled", self.toggle_show_names)
        names_button.set_active (True)
        hbox.pack_start (names_button, False, False)
        # Buttons
        hbox = gtk.HBox ()
        alignment = gtk.Alignment (0.5, 0.5, 0, 0)
        alignment.add (hbox)
        box.pack_start (alignment, False, False)
        # Generate button
        self.gen_button = gtk.Button ("Generate")
        self.gen_button.connect ("clicked", self.generate)
        hbox.pack_start (self.gen_button, False, False)
        # Start button
        self.start_button = gtk.Button ("Start")
        self.start_button.connect ("clicked", self.start)
        self.start_button.set_sensitive (False)
        hbox.pack_start (self.start_button, False, False)
        # Resume button
        self.resume_button = gtk.Button ("Resume")
        self.resume_button.connect ("clicked", self.resume)
        self.resume_button.set_sensitive (False)
        hbox.pack_start (self.resume_button, False, False)
        # Stop button
        self.stop_button = gtk.Button ("Stop")
        self.stop_button.connect ("clicked", self.stop)
        self.stop_button.set_sensitive (False)
        hbox.pack_start (self.stop_button, False, False)
        # Informative labels
        self.best_label = gtk.Label ()
        self.update_best (length = None)
        box.pack_start (self.best_label, False, False)
        self.config_label = gtk.Label ()
        self.update_config (config = False)
        box.pack_start (self.config_label, False, False)

    def toggle_show_names (self, button):
        '''Toggle SHOW_NAMES setting & damage canvas'''
        global SHOW_NAMES
        SHOW_NAMES = button.get_active ()
        self.canvas.redraw (path = self.canvas.path, damage = True)

    def get_count (self):
        '''Get currently selected city count'''
        count = self.count_box.get_active_text ().split (" ")[0]
        return int (count)

    def get_algo (self):
        '''Get currently selected algorithm'''
        return self.algo_box.get_active_text ()

    def get_init (self):
        '''Get currently selected init method'''
        return self.init_box.get_active_text ()

    def generate (self, *args):
        '''Generate a new map'''
        self.context.count = self.get_count ()
        self.context.prepare ()
        self.start_button.set_sensitive (True)
        self.resume_button.set_sensitive (False)
        self.canvas.redraw (damage = True)

    def start (self, *args):
        '''Run algorithm'''
        global INITS
        self.stop ()
        self.update_config ()
        self.algo = eval ("Algo_%s" % self.get_algo ()) (self.context)
        self.thread = AlgoThread (self.context, self.algo, self, self.canvas,
                                  init = self.get_init ())
        self.thread.start ()
        self.gen_button.set_sensitive (False)
        self.start_button.set_sensitive (False)
        self.resume_button.set_sensitive (False)
        self.stop_button.set_sensitive (True)

    def resume (self, *args):
        '''Resume algorithm execution'''
        if not self.thread or self.thread.isAlive ():
            return
        self.thread = self.thread.resume ()
        self.gen_button.set_sensitive (False)
        self.start_button.set_sensitive (False)
        self.resume_button.set_sensitive (False)
        self.stop_button.set_sensitive (True)

    def stop (self, *args):
        '''Halt algorithm'''
        if self.thread:
            self.thread.stop ()
            self.thread.join (0.1)
            if self.thread.isAlive ():
                gobject.timeout_add (100, self.stop)
                return
        self.gen_button.set_sensitive (True)
        self.start_button.set_sensitive (True)
        self.resume_button.set_sensitive (True)
        self.stop_button.set_sensitive (False)

    def update_best (self, length):
        '''Update best solution length label'''
        if not length:
            self.best_label.set_markup ("<b>Best length yet</b>: N/A")
            return
        length = round (length, 2)
        self.best_label.set_markup ("<b>Best length yet</b>: %s" % length)

    def update_config (self, config = True):
        '''Update current configuration label'''
        if not config:
            self.config_label.set_markup ("<b>Configuration</b>: N/A")
            return
        config = '''<b>Configuration</b>: %d cities, using %s algorithm and \
%s init'''
        self.config_label.set_markup (config % (self.get_count (),
                                                self.get_algo (),
                                                self.get_init ()))

if __name__ == "__main__":
    gui = AlgoGui ()
    gui.show_all ()
    try:
        gtk.main ()
    except KeyboardInterrupt:
        pass
    gui.stop ()