Skip to main content

TypeError: only size-1 arrays can be converted to Python scalars

Answered

Comments

6 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff Gurobi Staff
    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?.
  • Eli Towle
    • Gurobi Staff Gurobi Staff

    Can you please post a self-contained code example that shows exactly how you define \( \texttt{p} \), \( \texttt{u} \), and \( \texttt{m} \)?

    0
  • Surya Narayanan Hari
    • Gurobi-versary
    • Curious
    • First Comment
    Sure, 
     
    x = 4
    y = 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 defining
    p = gurobi_model.addMVar((y), name='p') throws the same error as above. 
    0
  • Eli Towle
    • Gurobi Staff Gurobi Staff

    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
  • Surya Narayanan Hari
    • Gurobi-versary
    • Curious
    • First Comment

    Hi, it did. Thank you for helping. 

    0
  • rpnald gevern
    • Gurobi-versary
    • First Comment

    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.