TypeError: only size-1 arrays can be converted to Python scalars
AnsweredI am trying to index into a Vector p, which is an MVar to perform the following operation.
p[j] * u[i] @ m[i]
Note u is a scalar matrix, and m is a matrix of variables.
However, I get the error mentioned in the title even though p[j] is a size-1 array. This was confirmed by printing the shape/size. p[0, 0] for example prints (1,) as the shape/size.
Isn't this a size-1 array? How can I accomplish the above operation?
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Can you please post a self-contained code example that shows exactly how you define \( \texttt{p} \), \( \texttt{u} \), and \( \texttt{m} \)?
0 -
Sure,x = 4y = 3
gurobi_model = gp.Model("price_mechanism")
p = gurobi_model.addMVar((y, 1), name='p')
m = gurobi_model.addMVar((x, y), name='m')
u = np.array([[100, 1, 0], [0, 1, 100], [0, 1, 50], [0, 1, 0]])
# print(p[0, 0].shape)
gurobi_model.addConstrs(u[i, j] - p[j, 0] * u[i, ] @ m[i, ] <= 0 for i in range(x) for j in range(y))
gurobi_model.setObjective(0 , gp.GRB.MAXIMIZE)
gurobi_model.optimize()
print(gurobi_model.X)print('Obj: %g' % gurobi_model.objVal)I confirmed that removing p[j, 0] solves successfully. Changing p[j, 0] to p[j] throws the same error as above and definingp = gurobi_model.addMVar((y), name='p') throws the same error as above.0 -
Thanks. Does the following work?
gurobi_model.addConstrs(u[i, j] - p[j, 0] @ (u[i, ] @ m[i, ]) <= 0 for i in range(x) for j in range(y))
You'll probably have to set the NonConvex parameter to 2.
0 -
Hi, it did. Thank you for helping.
0 -
The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead. This means that when you're trying to cast into an integer something that isn't just one scalar. Once you will look at the call signature of np.int, you'll see that it accepts a single value, not an array.
What you can do is use .astype(int)
0
Post is closed for comments.
Comments
6 comments