4

I am really new to CVXPY. I am trying to solve the 8 queens problem, i.e., the problem of placing 8 chess queens on an 8 x 8 chessboard so that no two queens threaten each other. As I understand it, the constrainsts should be:

  1. sum of each row equals to 1.
  2. sum of each column equals to 1.
  3. sum of each diagonal equals to 1.
  4. all variables should be larger than 0.

Moreover, the objective function should be: maximize the 2-norm of the matrix (so that we get only 1's and 0's, because we can get a sum of 1 also with floats, but norm of 1 with zeros is larger than norm of floats between 0 to 1 that also sum up to 1 (for example: 0.8^2+0.2^2 < 1^2+0^2).

Is it possible to solve this kind of problem in CVXPY? I am pretty clueless on how to form the constraints and the objective function in CVXPY, but here are my initial initial attempts (I immediately got a "DCP Error" so I had no reason to continue, but still):

from cvxpy import *
x=Variable(shape=(9,9), name='board')
obj = Maximize(norm(x))
const = [sum(x, axis=1)==1]
prob=Problem(objective=obj,constraints=const)
prob.solve()

Any help will be appreciated!!!

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
Binyamin Even
  • 3,318
  • 1
  • 18
  • 45

1 Answers1

5

As I already said in the comments:

Maximize(norm(x)) causes the problem to be non-convex. CVXPY is for convex problems only.

8-queens problems are typically modeled with binary variables (link). You try to use a non-convex objective to bypass this. In general this does not work:

  • Convex solvers will not accept your problem
  • Local NLP solvers will end up in a local optimum
  • So a global NLP solver is required (e.g. Baron, Antigone, or Couenne). But that is not easier than using a linear MIP solver.

An essentially difficult, discrete problem can, in general, not be made "easy-to-solve" using tricks. Another such trick is to use the constraint x(1-x)=0. This suffers from the same problem: you need a global solver for a difficult non-convex problem. So it is better to stick with a linear formulation with binary variables. If there would be an easy way to make this convex and continuous, basically, MIP solver developers would be out of business. On the other hand, if you find such a transformation, I am sure a Nobel prize will be waiting for you.

Also, as mentioned in the comments, note that

3. sum of each diagonal equals to 1.

should read

3. sum of each diagonal <= 1.
Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39
  • thanks for the link. Is there a way in cvxpy, to force the variables to be 0 or 1? – Binyamin Even Feb 13 '19 at 09:21
  • 1
    Yes, CVXPY supports binary variables and MIP solvers (see the [documentation](https://www.cvxpy.org/tutorial/advanced/index.html#mixed-integer-programs)). So you can just formulate linear MIP models (they are convex by nature, so CVXPY will not complain about non-convexities). – Erwin Kalvelagen Feb 13 '19 at 09:48