File: tsp_04.py

package info (click to toggle)
opencamlib 2023.01.11-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 29,800 kB
  • sloc: cpp: 8,722; python: 5,530; sh: 604; javascript: 310; makefile: 209
file content (54 lines) | stat: -rw-r--r-- 1,369 bytes parent folder | download | duplicates (2)
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
from opencamlib import ocl, camvtk
import time
import csv

def readPts():
    spamReader = csv.reader(open('tsplib/graph.txt', 'rb'), delimiter=',', quotechar='|')
    pts=[]
    for row in spamReader:
        pts.append( ocl.Point( float(row[0]), float(row[1]) ) )
    return pts

def drawTour(myscreen, pts, tour, tourColor = camvtk.red):
    for n in range(0,len(tour)-1):
        idx0 = n
        idx1 = n+1
        ip1 = pts[ tour[idx0] ]
        ip2 = pts[ tour[idx1] ]
        myscreen.addActor( camvtk.Line(p1=(ip1.x,ip1.y,ip1.z),p2=(ip2.x,ip2.y,ip2.z), color=tourColor) )

def drawPoints(myscreen, pts):
    c=camvtk.PointCloud( pts ) 
    c.SetPoints()
    myscreen.addActor(c )
    

if __name__ == "__main__":  
    
    myscreen = camvtk.VTKScreen()
    
    
    tsp = ocl.TSPSolver()
    pts = readPts()
    drawPoints(myscreen, pts)
    print("got ",len(pts)," points")
    #exit()
    for p in pts:
        tsp.addPoint( p.x , p.y)
    start_time = time.time()
    tsp.run()
    run_time = time.time() - start_time
    l = tsp.getLength()
    print("tour length ",l)
    out = tsp.getOutput()
    for o in out:
        print(o,)
    
    drawTour(myscreen, pts, out)

    myscreen.camera.SetPosition(0.0, 0.0, 200)
    myscreen.camera.SetViewUp(0.0, 0.0, 0)
    myscreen.camera.SetFocalPoint(50, 50, 0)
    myscreen.render()

    myscreen.iren.Start()