4

I need to figure out how to read in this data of the filename 'berlin52.tsp'

This is the format I'm using

NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0

And this is my current code

# Open input file
infile = open('berlin52.tsp', 'r')

# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()

# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
    x,y = infile.readline().strip().split()[1:]
    nodelist.append([int(x), int(y)])

# Close input file
infile.close()

The code should read in the file, output out a list of tours with the values "1, 2, 3..." and more while the x and y values are stored to be calculated for distances. It can collect the headers, at least. The problem arises when creating a list of nodes.

This is the error I get though

ValueError: invalid literal for int() with base 10: '565.0'

What am I doing wrong here?

Leggerless
  • 321
  • 4
  • 16

4 Answers4

4

This is a file in TSPLIB format. To load it in python, take a look at the python package tsplib95, available through PyPi or on Github

Documentation is available on https://tsplib95.readthedocs.io/

You can convert the TSPLIB file to a networkx graph and retrieve the necessary information from there.

0

You are feeding the string "565.0" into nodelist.append([int(x), int(y)]). It is telling you it doesn't like that because that string is not an integer. The .0 at the end makes it a float.

So if you change that to nodelist.append([float(x), float(y)]), as just one possible solution, then you'll see that your problem goes away.

Alternatively, you can try removing or separating the '.0' from your string input.

Philip B.
  • 637
  • 6
  • 12
0

There are two problem with the code above.I have run the code and found the following problem in lines below:

Dimension = infile.readline().strip().split()[1] 

This line should be like this

`Dimension = infile.readline().strip().split()[2]`

instead of 1 it will be 2 because for 1 Dimension = : and for 2 Dimension = 52. Both are of string type.

Second problem is with line

N = int(intDimension)

It will be

 N = int(Dimension)

And lastly in line

for i in range(0, int(intDimension)):

Just simply use

for i in range(0, N):

Now everything will be alright I think.

Zakaria
  • 445
  • 4
  • 10
0

nodelist.append([int(x), int(y)]) int(x) function int() cant convert x(string(565.0)) to int because of "."

add x=x[:len(x)-2] y=y[:len(y)-2] to remove ".0"