4 Drawings

Specially for the presentation of the results, figures and drawings are very helpful to understand the solution of a model. Therefore, LPL contains a small drawing library to generate an vector graph in SVG format. The following model show the use of this library (open chess5b to run the model and to see the graphic) :

model chess; 
  set i,j := [1..8]; 
  integer variable x{i} [1..#i]; 
  constraint 
    D: Alldiff({i} x[i]); 
    S: Alldiff({i} (x[i]+i)); 
    T: Alldiff({i} (x[i]-i)); 
  solve; 
  parameter X{i,j} := if(j=x[i],1); 
  Draw.Scale(50,50); 
  {i,j} Draw.Rect(i,j,1,1,if((i+j)%2,0,1),0); 
  {i,j|X} Draw.Circle(j+.5,i+.5,.3,5); 
end

This model implements a placement of 8 queens on a chessboard which cannot attack each other. The model shows some more interesting features:

  1. The same set definition has two names: i and j (they are separated by a comma, not by semicolon). This is handy because they are used for the rows and the columns on the chessboard.

  2. The variable are declared as integer variable in the range [1..8]. (#i is a notation for the cardinality of the set i). For example, x2 = 3 means that the queen on the second row should be placed in column 3.

  3. The constraints implements a global constraint called Alldiff meaning that all the variables must be different from each other. (It goes too far here, but an Alldiff constraint is either passed directly to a solver like LocalSolver, or it is automatically translated by LPL to integer linear constraints – for a linear solver like Gurobi.)

  4. The solve statement says to solve the constraints and return (any) possible solution.

After the solution has been found, a graphic is generated using the library Draw. This library contains a dozens of functions such as Scale (for the x - y sizing), Rect (to draw a rectangle), Circle (to draw an circle), etc. (Note that {i,j} is a shortcut for for{i,j} do ... end;). Hence, 8 × 8 rectangles are drawn at position (i,j) with size (1, 1) (multiplied by 50 pixels), alternating with color black (0) and white (1) forming the chessboard grid. Then a circle is drawn on each field with color blue (5) if xi,j is 1 (8 of them are 1).