AttributeError:模块“ cplex”没有属性“ Cplex”

时间:2019-10-08 07:05:41

标签: python attributeerror cplex

我正在尝试使用Python中的CPLEX优化线性编程问题。 我已经安装了IBM ILOG CPLEX Studio以及Python中的docplex。

运行程序时,出现以下错误:

AttributeError: module 'cplex' has no attribute 'Cplex'

有用的代码:

import docplex.mp.model as cpx

import random

import pandas as pd

n = 10
m = 5
set_I = range(1, n+1)
set_J = range(1, m+1)
c = {(i,j): random.normalvariate(0,1) for i in set_I for j in set_J}
a = {(i,j): random.normalvariate(0,5) for i in set_I for j in set_J}
l = {(i,j): random.randint(0,10) for i in set_I for j in set_J}
u = {(i,j): random.randint(10,20) for i in set_I for j in set_J}
b = {j: random.randint(0,30) for j in set_J}


opt_model = cpx.Model(name="MIP Model")

# if x is Binary
x_vars  = {(i,j): opt_model.binary_var(name="x_{0}_{1}".format(i,j)) for i in set_I for j in set_J}


# <= constraints
constraints = {j : opt_model.add_constraint(ct=opt_model.sum(a[i,j] * x_vars[i,j] for i in set_I) <= b[j], ctname="constraint_{0}".format(j)) for j in set_J}

objective = opt_model.sum(x_vars[i,j] * c[i,j] for i in set_I  for j in set_J)

opt_model.minimize(objective)

opt_model.solve()


opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns = ["variable_object"])

opt_df.index = pd.MultiIndex.from_tuples(opt_df.index, names=["column_i", "column_j"])
opt_df.reset_index(inplace=True)

opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.solution_value)

print(opt_df)

我从以下位置提取了此代码:https://medium.com/@m.moarefdoost/optimization-modeling-in-python-pulp-gurobi-and-cplex-7f25acb03d7d

我是CPLEX和Python的初学者,所以我只是尝试运行此代码来验证是否已正确安装所有内容。

有人遇到过类似的问题吗?

2 个答案:

答案 0 :(得分:1)

我发现了我的代码错误。 实际上,在运行代码之前,我没有正确安装setup.py。

这样做之后,一切都很好!

答案 1 :(得分:0)

我遇到了同样的问题。设置CPLEX的Python API时,我犯了几个错误。

  1. 我使用了yourCplexhome/python/VERSION/PLATFORM中的脚本setup.py,而不是使用CPLEX_Studio1210/python中的脚本setup.py。
  2. 我没有将Python路径环境变量PYTHONPATH设置为yourCplexhome/python/VERSION/PLATFORM的值

Source