首页 > 编程问答 >类型错误:+ 不支持的操作数类型:目标函数中的“生成器”和“生成器”

类型错误:+ 不支持的操作数类型:目标函数中的“生成器”和“生成器”

时间:2024-07-30 16:55:21浏览次数:14  
标签:python gurobi

晕,我发现一个问题

我有护士人数21的数据,但是方程中使用的是从护士5号开始的,n=1,2,3,...,N,序列为1,2 ,3,4是高级护士(T)。如果 i=n-T (i=5,6,...,21),则护士长的数据被排除在方差计算之外,即 |T|表示集合 T 的基数。

perawat=np.genfromtxt("Jumlah Perawat.txt", dtype='str')
shift=np.genfromtxt("Shift.txt", dtype='str')
hari=np.genfromtxt ("Jumlah Hari.txt", dtype='str')
p=np.genfromtxt("Jadwal.txt", dtype='str')
i=np.genfromtxt("tanpa_kepalajaga.txt", dtype='str')

T = np.loadtxt("Kepala jaga.txt")

###
D = hari.shape[0] #Jumlah Hari 
print('D:',D)
N = perawat.shape[0] #Jumlah perawat
print('N:',N)
S = shift.shape[0] #Shift
print('S:',S)
I = i.shape[0] #tanpa kepala jaga
print('I:', I)

# Model
m = gp.Model("BnB")

# Decision variable
x = m.addVars(N,D,S, vtype=GRB.BINARY, name="x")   

# Obj Function
m.setObjective(((sum(sum(x[n,d,1]) ** 2) / (21-4)) - (sum(sum(x[n,d,1])/(21-4)) ** 2) for n in range(5,N) for d in range (D)) + ((sum(sum(x[n,d,2]) ** 2) / (21-4)) - (sum(sum(x[n,d,2])/(21-4)) ** 2) for n in range(5,N) for d in range (D)) + ((sum(sum(x[n,d,3]) ** 2) / (21-4)) - (sum(sum(x[n,d,3])/(21-4)) ** 2) for n in range(5,N) for d in range (D)) + ((sum(sum(x[n,d,4]) ** 2) / (21-4)) - (sum(sum(x[n,d,4])/(21-4)) ** 2) for n in range(5,N) for d in range (D)) , GRB.MINIMIZE)

图像 O[id] 中目标函数的公式 显示 shift(s)=1

导致错误的原因是什么?和 问题是我不知道如何在 Gurobi Python 中编写这个表达式!

谢谢!


此代码中出现“TypeError: unsupported operand type(s) for +: 'generator' and 'generator'”错误是因为在 m.setObjective 中将多个生成器表达式使用 + 运算符连接起来。在 Python 中,不能直接将生成器表达式相加。

以下是如何解决此问题并正确编写 Gurobi 模型的步骤:

1. 使用 quicksum 函数

Gurobi 提供了 quicksum 函数,可以有效地对生成器表达式求和。可以使用它来替换目标函数中的 sum 函数。

2. 将所有表达式组合到一个生成器表达式中

与其创建多个生成器表达式并将它们相加,不如将所有内容组合到一个生成器表达式中,并使用 quicksum 对其求和。

以下代码展示了如何修改的目标函数:

from gurobipy import quicksum

m.setObjective(
    quicksum(
        (x[n, d, s] ** 2) / (N - len(T)) - (x[n, d, s] / (N - len(T))) ** 2
        for n in range(len(T), N)
        for d in range(D)
        for s in range(1, S + 1)
    ),
    GRB.MINIMIZE,
)

解释:

  • 我们使用 quicksum 函数对整个表达式求和。
  • 外层循环迭代 n ,从 len(T) 开始,表示从护士长之后开始计算。
  • 内层循环迭代 d s ,分别表示天数和班次。
  • 表达式 (x[n, d, s] ** 2) / (N - len(T)) - (x[n, d, s] / (N - len(T))) ** 2 计算每个护士在每个班次每一天的方差贡献。

其他建议:

  • 使用更具描述性的变量名,例如 num_nurses , num_days , num_shifts
  • 将常量值(如 21 4 )替换为变量或从数据中获取,以提高代码的可读性和可维护性。

通过这些更改,的代码应该可以正常运行并解决优化问题。

标签:python,gurobi
From: 78810657

相关文章

  • Python - Creating alternative initializers using class Methods
    Classmethodsallowustodefinealternativeinitializers(alsoknownasfactorymethods)inaclass.Thesemethodshelpuscreateinstanceobjectsfromdifferenttypesofinputdata.Letusunderstandthiswiththehelpofanexample.Again,wetakethe......
  • 如何让 Python 请求信任自签名 SSL 证书?
    importrequestsdata={'foo':'bar'}url='https://foo.com/bar'r=requests.post(url,data=data)如果URL使用自签名证书,则会失败requests.exceptions.SSLError:[Errno1]_ssl.c:507:error:14090086:SSLroutines:SSL3_GET_SERVER_CERTIF......
  • python 偏函数
    如下代码loop=tornado.ioloop.IOLoop.current()ctx=contextvars.copy_context()func_call=functools.partial(ctx.run,func,*args,**kwargs)returnawaitloop.run_in_executor(executor,func_call)偏函数一个函数作为模板,通过提供部分参数来产生一个新的函数。......
  • Chapter 18 Python异常
    欢迎大家订阅【Python从入门到精通】专栏,一起探索Python的无限可能!文章目录前言一、什么是异常二、捕获异常三、异常的传递前言在Python中,异常是一种特定的对象,能够在程序运行过程中被抛出和处理。有效地管理异常不仅可以增强程序的稳定性,还可以提高用户体验,使程......
  • Python正则表达式匹配数字的第一次重复
    示例:For0123123123,1应匹配,因为第二个1出现在任何其他数字重复之前。For01234554321,5应该匹配,因为第二个5出现在任何其他数字的重复之前。我尝试过的一些正则表达式:......
  • 当 python 极坐标中某些列条目为空时,如何分解 List[_] 列?
    给定如下所示的Polarsdf,如何在两列上调用explode(),同时将空条目扩展到正确的长度以与其行匹配?shape:(3,2)┌───────────┬─────────────────────┐│x┆y││---┆---......
  • 使用python从网站自动下载pdf时出错
    我想从一个名为epadossier.nl的网站自动批量下载pdf我用谷歌搜索了这个并找到了一段代码并修复了一个小错误。所以现在我得到了这个`importrequestsurl="https://www.epadossier.nl/adres/plaats/straat/num"response=requests.get(url)ifresponse.status_cod......
  • 避免字符串连接的嵌套循环的 Pythonic 方法
    我想找到所有5位数字的字符串,其中前三位数字在我的第一个列表中,第二个槽第四个数字在我的第二个列表中,第三到第五个数字在我的最后一个列表中:l0=["123","567","451"]l1=["234","239","881"]l2=["348","551","399"......
  • Python 环境配置(二)安装jupyter、matplotlib、numpy库
    Python环境配置(二)安装jupyter、matplotlib、numpy库一、numpypipinstallnumpy二、matplotlibpipinstallmatplotlib三、jupyter1、anaconda自带Jupyter2、pycharm插件只有Pycharm的Professional版才支持JupyterNotebook,请注意版本3、新建文件#%......
  • 如何使用 PIPE 并行运行 python 子进程?
    我正在使用inkscape将一堆SVG图像转换为PNG。单线程:importsubprocessimporttimeimportosinkscape_path=r'C:\ProgramFiles\Inkscape\bin\inkscape.com'steps=30filenames=[]processes=[]#t_start=time.process_time()t_start=time.time()f......