|
| 1 | +import cpmpy as cp |
| 2 | +from cpmpy.transformations.normalize import toplevel_list |
| 3 | +from ..answering_queries.constraint_oracle import ConstraintOracle |
| 4 | +from ..problem_instance import ProblemInstance, absvar |
| 5 | + |
| 6 | + |
| 7 | +def construct_gtsudoku(block_size_row=2, block_size_col=2, grid_size=4): |
| 8 | + """ |
| 9 | + :return: a ProblemInstance object, along with a constraint-based oracle |
| 10 | + """ |
| 11 | + |
| 12 | + # Create a dictionary with the parameters |
| 13 | + parameters = {"block_size_row": block_size_row, "block_size_col": block_size_col, "grid_size": grid_size} |
| 14 | + |
| 15 | + # Variables |
| 16 | + grid = cp.intvar(1, grid_size, shape=(grid_size, grid_size), name="grid") |
| 17 | + |
| 18 | + model = cp.Model() |
| 19 | + |
| 20 | + # Constraints on rows and columns |
| 21 | + for row in grid: |
| 22 | + model += cp.AllDifferent(row).decompose() |
| 23 | + |
| 24 | + for col in grid.T: # numpy's Transpose |
| 25 | + model += cp.AllDifferent(col).decompose() |
| 26 | + |
| 27 | + # Constraints on blocks |
| 28 | + for i in range(0, grid_size, block_size_row): |
| 29 | + for j in range(0, grid_size, block_size_col): |
| 30 | + model += cp.AllDifferent(grid[i:i + block_size_row, j:j + block_size_col]).decompose() # python's indexing |
| 31 | + |
| 32 | + true_horizontal_gt = [ |
| 33 | + (0, 0, 0, 1), |
| 34 | + (1, 1, 1, 2), |
| 35 | + (2, 2, 2, 3), |
| 36 | + (3, 3, 3, 4), |
| 37 | + (4, 4, 4, 5), |
| 38 | + ] |
| 39 | + |
| 40 | + for r1, c1, r2, c2 in true_horizontal_gt: |
| 41 | + if r2 < grid_size and c2 < grid_size: |
| 42 | + model += (grid[r1, c1] > grid[r2, c2]) |
| 43 | + |
| 44 | + true_vertical_gt = [ |
| 45 | + (0, 2, 1, 2), |
| 46 | + (1, 3, 2, 3), |
| 47 | + (2, 4, 3, 4), |
| 48 | + (3, 5, 4, 5), |
| 49 | + (4, 6, 5, 6), |
| 50 | + ] |
| 51 | + |
| 52 | + for r1, c1, r2, c2 in true_vertical_gt: |
| 53 | + if r1 < grid_size and r2 < grid_size and c1 < grid_size and c2 < grid_size: |
| 54 | + model += (grid[r1, c1] > grid[r2, c2]) |
| 55 | + |
| 56 | + |
| 57 | + C_T = list(set(toplevel_list(model.constraints))) |
| 58 | + |
| 59 | + # Create the language: |
| 60 | + AV = absvar(2) # create abstract vars - as many as maximum arity |
| 61 | + |
| 62 | + # create abstract relations using the abstract vars |
| 63 | + lang = [AV[0] == AV[1], AV[0] != AV[1], AV[0] < AV[1], AV[0] > AV[1], AV[0] >= AV[1], AV[0] <= AV[1]] |
| 64 | + |
| 65 | + instance = ProblemInstance(variables=grid, params=parameters, language=lang, name=f"sudoku_{block_size_row}_{block_size_col}_{grid_size}") |
| 66 | + |
| 67 | + oracle = ConstraintOracle(C_T) |
| 68 | + |
| 69 | + return instance, oracle |
0 commit comments