简体   繁体   中英

Gurobi in Python: best way to read csv file

I'm learning how to solve combinatorial optimization problems in Gurobi using Python. I would like to know what is the best option to read a csv file to use the data as model parameters. I'm using 'genfromtxt' to read the csv file, but I'm having difficulties in using it for constraint construction (Gurobi doesn't support this type - see error).

Here my code and error message, my_data is composed by 4 columns: node index, x coordinate, y coordinate and maximum degree.

from gurobipy import *
from numpy import genfromtxt
import math

# Read data from csv file
my_data = genfromtxt('prob25.csv', delimiter=',')

# Number of vertices
n = len(my_data)

# Function to calculate euclidean distancces
dist = {(i,j) :
    math.sqrt(sum((my_data[i][k]-my_data[j][k])**2 for k in [1,2]))
    for i in range(n) for j in range(i)}

# Create a new model
m = Model("dcstNarula")

# Create variables

vars = m.addVars(dist.keys(), obj=dist, vtype=GRB.BINARY, name='e')
for i,j in vars.keys():
    vars[j,i] = vars[i,j] # edge in opposite direction

m.update()

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
             for i in range(n)), name='degree')

GurobiError: Unsupported type (<type 'numpy.ndarray'>) for LinExpr addition argument

First two lines of data

1,19.007,35.75,1
2,4.4447,6.0735,2

Actually it was a problem of indexing instead of data type. In the code:

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
         for i in range(n)), name='degree')

It should be used vars.sum('*',i) instead of vars.sum('*',j) and my_data[i,3] instead of my_data[:,3]

Even though this question is answered, for future visitors who are looking for good ways to read a csv file, pandas must be mentioned:

import pandas as pd
df = pd.read_csv('prob25.csv', header=None, index_col=0, names=['x', 'y', 'idx'])
df
         x        y  idx
1  19.0070  35.7500    1
2   4.4447   6.0735    2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM