import gurobipy as gp import numpy as np # 定义参数 c_p = 225 tau = 13500 C_re = 20 C_se = 30 h = 3.25 q = 0.2 e = 18.98 S = 10 T = 20 expr2_1 = (C_re*q+C_se)*e m = np.full((1, T), 3) z = np.around((1-1*np.random.rand(T, S)) * 3) # 创建模型 model = gp.Model() # 创建变量 x = model.addVar(lb=0, name='x') k = model.addVar(lb=0, name='k') y = model.addVars(S, lb=0, name='y') a = model.addVars(T,S, vtype=gp.GRB.BINARY, name="C") # a = model.addVars(T, S, lb=0, name='a') b = model.addVars(T, S, lb=0, name='b') # 创建约束 for s in range(S): expa = c_p * x + e * h * x + (1/S) * gp.quicksum(y[t] for t in range(S)) model.addConstr(expa <= tau, name=f'c1_{s}') expb1=gp.quicksum(3*a[t,s] for t in range(T)) expb2=gp.quicksum((expr2_1-a[t,s]+b[t,s])*z[t,s] for t in range (T)) expb = expb1+expb2 model.addConstr(y[s] >= expb, name=f'c2_{s}') expc = gp.quicksum(abs(expr2_1-a[t,s]+b[t,s]) for t in range (T)) model.addConstr(expc <= k, name=f'c3_{s}') # 创建目标 model.setObjective(k, gp.GRB.MINIMIZE) # 求解 model.optimize() # 输出结果 print(f'最优解: {model.objVal}')遇到了expc = gp.quicksum(abs(expr2_1-a[t,s]+b[t,s]) for t in range (T)) TypeError: bad operand type for abs(): 'gurobipy.LinExpr'
时间: 2023-07-15 21:14:17 浏览: 187
这个错误是因为 `abs()` 函数不能直接作用于 `gurobipy.LinExpr` 类型,需要将其转化为可计算的类型。可以使用 `gurobipy.quicksum()` 函数将 `a[t,s]` 和 `b[t,s]` 的差值转化为可计算的表达式:
```
expc = gp.quicksum(gp.abs_(expr2_1-a[t,s]+b[t,s]) for t in range (T))
```
这样就可以避免这个错误了。
阅读全文