简体   繁体   English

如何在CPLEX的Python API中导入CSV文件

[英]How to import CSV file in Python API of CPLEX

I would like to import this filehttp://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/scp61.txt .我想导入这个文件http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/scp61.txt Does CPLEX support this format in Python? CPLEX 在 Python 中是否支持这种格式? I converted the text file to a CSV file then wrote this code cplex.read("scp61.csv") but I got this error "CPLEX Error 1436: Max or Min missing."我将文本文件转换为 CSV 文件,然后编写此代码cplex.read("scp61.csv")但我收到此错误"CPLEX Error 1436: Max or Min missing."
There isn't any Max or Min word in the text file.文本文件中没有任何 Max 或 Min 字样。

scp61 contains the data but not the model. scp61 包含数据,但不包含 model。

In python it's possible to parse the file and then call cplex through the docplex python API.在 python 中,可以解析文件,然后通过docplex python API 调用 cplex。

from docplex.mp.model import Model


file = open('scp61.txt', 'r')
count = 0

values=[]
print("Using for loop")
for line in file:
    count += 1
    ar=line.split()
    for i in ar:
        values.append(int(i))
 
file.close()

n=values[0]
m=values[1]

print("n=",n)
print("m=",m)

values2=values[2:]

mdl = Model(name='scp')

#decision variables
x=[mdl.binary_var(name='x'+str(i)) for i in range(1,m+1) ]

#objective
mdl.minimize(mdl.sum(x[i-1]*values2[i-1] for i in range(1,m+1)))

index=0
index=index+m
i=0

while (index!=len(values2)):
    
    i=i+1
    nbr=values2[index]
   
    index=index+1
    which=[]
    for j in range(0,nbr):
        index=index+1
        
        
        if index==len(values2):
            break
        which.append(values2[index])
    #constraint    
    mdl.add(1<=mdl.sum(x[j-1] for j in which),"ct"+str(i))

mdl.solve(log_output=True,)

for v in mdl.iter_binary_vars():
    if (v.solution_value!=0):
        print(v," = ",v.solution_value)

DOcplex supports three model formats: LP, SAV and MPS for MP models, plus CPO format for CP problems. DOcplex 支持三种 model 格式:用于 MP 模型的 LP、SAV 和 MPS,以及用于 CP 问题的 CPO 格式。

For other formats, you need to write custom reader code to import to a DOcplex model, as Alex did in the above post.对于其他格式,您需要编写自定义阅读器代码以导入 DOcplex model,正如 Alex 在上述帖子中所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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