TypeError: unsupported operand type(s) for *: 'int' and 'Var'
AnsweredI'm going to solve the optimization porblem
$$
\begin{align*}
\text{Minimize:} \quad & \sum_{i=0}^{n-1} \binom{m - x_i}{n} \\
\text{Subject to:} \quad & \sum_{i=0}^{n-1} x_i = m \\
& x_i \in \{1, 2, \dots, m-n+1\}, \quad \forall i = 0, \dots, n-1 \\
\text{Where:} \quad & n = 314, \, m = 2025 \\
\end{align*}
$$
It can be converted to the below problem:
$$
\begin{align*}
\text{Minimize:} \quad & \sum_{i=0}^{n-1} \sum_{k=0}^{m} \binom{m - k}{n} y_{i,k} \\
\text{Subject to:} \quad & \sum_{i=0}^{n-1} x_i = m \\
& x_i = \sum_{k=0}^{m} k \cdot y_{i,k}, \quad \forall i = 0, \dots, n-1 \\
& \sum_{k=0}^{m} y_{i,k} = 1, \quad \forall i = 0, \dots, n-1 \\
& x_i \in \{1, 2, \dots, m\}, \quad \forall i = 0, \dots, n-1 \\
& y_{i,k} \in \{0, 1\}, \quad \forall i = 0, \dots, n-1, \, k = 0, \dots, m \\
\text{Where:} \quad & n = 314, \, m = 2025 \\
& \binom{m - k}{n} \text{ is pre-computed for } m - k \geq n, \, 0 \text{ otherwise}
\end{align*}
$$
below is my gurobipy code
```
from gurobipy import Model, GRB, quicksum
import math
# Parameters
n = 314
m = 2025
# Pre-compute possible binomial coefficients
bin_coeffs = {(m - k, n): math.comb(m - k, n)
for k in range(m + 1) if m - k >= n}
# Create model
model = Model("binomial_minimization")
# Add variables
x = model.addVars(n, vtype=GRB.INTEGER, lb=1, ub=m, name="x")
# Add constraint
model.addConstr(quicksum(x[i] for i in range(n)) == m, "sum_constraint")
# Create binary variables for each possible value of (m-x_k)
y = model.addVars(n, m + 1, vtype=GRB.BINARY, name="y")
# Link x and y variables
for i in range(n):
model.addConstr(x[i] == quicksum(k * y[i,k] for k in range(m + 1)))
model.addConstr(quicksum(y[i,k] for k in range(m + 1)) == 1)
# Set objective
obj = quicksum(bin_coeffs.get((m - k, n), 0) * y[i,k]
for i in range(n) for k in range(m + 1))
model.setObjective(obj, GRB.MINIMIZE)
# Optimize
model.optimize()
# Print results
if model.status == GRB.OPTIMAL:
print("\nOptimal solution found:")
for i in range(n):
print(f"x[{i}] = {x[i].X}")
print(f"Objective value = {model.ObjVal}")
```
There is an error `TypeError: unsupported operand type(s) for *: 'int' and 'Var'`
How to fix it? The code works correctly for `n=30, m=2025`
-
Hi,
Your question has already been answered on OR Stackexchange (by me).
https://or.stackexchange.com/a/13089/10108
- Riley
0
Please sign in to leave a comment.
Comments
1 comment