Exemplo n.º 1
0
def testAllNPCs():
    masterCombination = Colorcombination(random.sample(range(0, numberOfColors), lengthOfGuess))
    gameCoordinator = GameCoordinator(lengthOfGuess, numberOfColors, masterCombination, maximumNumberOfGuesses)
    print("\nStart all performance tests.\n")

    print("NPC_random performance test")
    npc = NPC_random(lengthOfGuess, numberOfColors, gameCoordinator.attempts)
    npc.strategy = npc.strategy_automaticRandom
    gameCoordinator.player = npc
    startPerformanceTests(gameCoordinator)

    print("NPC_hardCoded performance test")
    npc = NPC_hardCoded(lengthOfGuess, numberOfColors, gameCoordinator.attempts)
    npc.strategy = npc.strategy_automaticImprovedRandom
    gameCoordinator.player = npc
    startPerformanceTests(gameCoordinator)

    print("NPC_csp performance test ")
    npc = NPC_csp(lengthOfGuess, numberOfColors, gameCoordinator.attempts)
    npc.strategy = npc.strategy_getNextPossibleCombination
    npc.cspSolvingStrategy = constraint.BacktrackingSolver()
    gameCoordinator.player = npc
    startPerformanceTests(gameCoordinator, npc.resetProblems)

    print("\nSucessfully performed all performance tests.")
Exemplo n.º 2
0
 def __init__(self, class_of_problems, solver=constraint.BacktrackingSolver()):
     #logging.basicConfig(filename='stats_{}.log'.format(class_of_problems), level=logging.INFO)
     self.path= 'data/{}/data'.format(class_of_problems)
     self.parser_func = parser.PARSE[class_of_problems]
     self.class_of_problems = class_of_problems
     self.output_file = 'stats_{}_{}.log'.format(class_of_problems, solver.name)
     self.solver = solver
Exemplo n.º 3
0
    def create_csp_problem(self,
                           solver=constraint.BacktrackingSolver(),
                           symmetry_break=False):
        p = constraint.Problem(solver)
        p.addVariables(self.nodes(), self.colors())

        self.add_edge_constraint(p)
        return p
Exemplo n.º 4
0
def solve(problem,
          solver=constraint.BacktrackingSolver(),
          symmetry_break=False):
    p = problem.create_csp_problem(solver, symmetry_break)
    fixed = p.getSolution()
    problem2 = copy.deepcopy(problem)
    problem2.fixed = fixed
    return problem2
Exemplo n.º 5
0
 def __init__(self, lengthOfGuess, numberOfColors, attempts):
     self.__lengthOfGuess = lengthOfGuess
     self.__numberOfColors = numberOfColors
     self.__attempts = attempts
     self.__cspVariables = []
     self.__cspVariablesStrings = []
     self.cspSolvingStrategy = constraint.BacktrackingSolver()
     self.__cspProblem = self.__createBasicCSP()
     self.strategy = self.strategy_getNextPossibleCombination
Exemplo n.º 6
0
def solve2(problem,
           solver=constraint.BacktrackingSolver(),
           queue=None,
           symmetry_break=False):
    p = problem.create_csp_problem(solver, symmetry_break)
    fixed = p.getSolution()
    problem2 = copy.deepcopy(problem)
    problem2.fixed = fixed
    queue.put(problem2)
Exemplo n.º 7
0
def puzzle_as_CP(fixed, boxsize, solver=constraint.BacktrackingSolver()):
    """puzzle_as_CP(fixed, boxsize) -> constraint.Problem

    Returns a constraint problem representing a Sudoku puzzle, based on 
    'fixed' cell dictionary."""
    p = empty_puzzle_as_CP(boxsize, solver)
    for cell in fixed:
        p.addConstraint(constraint.ExactSumConstraint(fixed[cell]), [cell])
    return p
Exemplo n.º 8
0
def solve_all(problem,
              solver=constraint.BacktrackingSolver(),
              symmetry_break=False):
    p = problem.create_csp_problem(solver, symmetry_break)
    fixed_list = p.getSolutions()
    problems = []
    for fixed in fixed_list:
        problem2 = copy.deepcopy(problem)
        problem2.fixed = fixed
        problems.append(problem2)
    return problems
Exemplo n.º 9
0
def empty_puzzle_as_CP(boxsize, solver=constraint.BacktrackingSolver()):
    """empty_puzzle(boxsize) -> constraint.Problem

    Returns a constraint problem representing an empty Sudoku puzzle of 
    box-dimension 'boxsize'."""
    p = constraint.Problem(solver)
    p.addVariables(cells(boxsize), symbols(boxsize))
    add_row_constraints(p, boxsize)
    add_col_constraints(p, boxsize)
    add_box_constraints(p, boxsize)
    return p
Exemplo n.º 10
0
    def create_csp_problem(self,
                           solver=constraint.BacktrackingSolver(),
                           symmetry_break=False):
        p = constraint.Problem(solver)
        p.addVariables(self.rows(), self.cols())

        p.addConstraint(constraint.AllDifferentConstraint(), self.rows())
        self.add_diag_left_constraints(p)
        self.add_diag_right_constraints(p)
        if symmetry_break:
            #self.add_axes_sym_constraints(p)
            #self.add_rotation_sym_constraints(p)
            self.sym_constraints(p)
        return p
Exemplo n.º 11
0
def solve_with_timeout(problem,
                       solver=constraint.BacktrackingSolver(),
                       timeout_sec=300,
                       symmetry_break=False):
    def solve():
        finished = True
        queue = Queue()
        proc = Process(target=solve2,
                       args=(problem, solver, queue, symmetry_break))
        proc.start()
        try:
            problem2 = queue.get(timeout=timeout_sec)
        except:
            proc.terminate()
            problem2 = copy.deepcopy(problem)
            finished = False
        finally:
            return problem2, finished

    return solve
Exemplo n.º 12
0
def solve(board):
    problem = constraint.Problem(constraint.BacktrackingSolver())
    
    # Build Variables
    for y in range(SIZE):
        for x in range(SIZE):
            if board[y,x] == -1:
                problem.addVariable(str([y,x]), [1, 100])

    # Constraints for variables near numbers
    for y in range(SIZE):
        for x in range(SIZE):
            if board[y,x] in [0,1,2,3,4]:
                val = 0
                adj_vars = []
                if y>0 and board[y-1,x] == -1: adj_vars.append(str([y-1,x]))
                if y<SIZE-1 and board[y+1,x] == -1: adj_vars.append(str([y+1,x]))
                if x>0 and board[y,x-1] == -1: adj_vars.append(str([y,x-1]))
                if x<SIZE-1 and board[y,x+1] == -1: adj_vars.append(str([y,x+1]))
                val += 100*board[y,x] + len(adj_vars) - board[y,x]
                problem.addConstraint(constraint.ExactSumConstraint(val), adj_vars)

    # Sum of each scan must be less than 200, since only 1 light per scan
    # For horizontal scans 
    for y in range(SIZE):
        curr_scan = []
        for x in range(SIZE):
            if board[y,x] == -1: curr_scan.append(str([y,x]))
            else:
                if len(curr_scan) > 0:
                    problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)
                curr_scan = []
        if len(curr_scan) > 0:
            problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)
    # For vertical scans 
    for x in range(SIZE):
        curr_scan = []
        for y in range(SIZE):
            if board[y,x] == -1: curr_scan.append(str([y,x]))
            else:
                if len(curr_scan) > 0:
                    problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)
                curr_scan = []
        if len(curr_scan) > 0:
            problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)

    # For each point, pair of scans passing through point must contain 100 at least once
    scans = []
    for y in range(SIZE):
        for x in range(SIZE):
            if board[y,x] != -1: continue
            scan = []
            scan.append(str([y,x]))
            # Up
            for i in reversed(range(y)):
                if board[i,x] >= 0: break
                else: scan.append(str([i,x]))
            # Down
            for i in range(y+1,SIZE):
                if board[i,x] >= 0: break
                else: scan.append(str([i,x]))
            # Left
            for i in reversed(range(x)):
                if board[y,i] >= 0: break
                else: scan.append(str([y,i]))
            # Right
            for i in range(x+1,SIZE):
                if board[y,i] >= 0: break
                else: scan.append(str([y,i]))
            scan.sort()
            if scan not in scans: scans.append(scan)
    for scan in scans:
        problem.addConstraint(constraint.SomeInSetConstraint([100]), scan)
    
    solution = problem.getSolution()

    for y in range(SIZE):
        for x in range(SIZE):
            if str([y,x]) in solution:
                board[y,x] = -1 if solution[str([y,x])] == 1 else 100
    return board
Exemplo n.º 13
0
 def is_solved(self):
     p = self.create_csp_problem(solver=constraint.BacktrackingSolver(),
                                 symmetry_break=False)
     return p.isSolution(self.fixed)
Exemplo n.º 14
0
 def create_csp_problem(self,
                        solver=constraint.BacktrackingSolver(),
                        symmetry_break=False):
     pass
Exemplo n.º 15
0
def solve_as_CP(fixed, boxsize, solver=constraint.BacktrackingSolver()):
    """Use constraint programming to solve Sudoku puzzle of dimension 'boxsize'
    with 'fixed' cells."""
    return puzzle_as_CP(fixed, boxsize, solver).getSolution()
Exemplo n.º 16
0
                #new_csp_object = csp_problems.solve(csp_object, solver=solver)
                end_time = time.time()
                res = {'filename':filename, 'time':round(end_time-start_time, 5), 'solver':self.solver.name, 'solved':new_csp_object.is_solved()}
                self.write(str(res))
            except:
                self.write('{} encountered an error'.format(filename))
                continue
            print('processing for {} finished'.format(filename))
        return True
                
                
if __name__ == '__main__':  
    if True:
        # Launch all experiments
        
        solvers = [constraint.BacktrackingSolver(),
                   constraint.NMCSSolver(level=1),
                   constraint.NMCSSolver(level=2),
                   constraint.NRPA(level=1, playouts=100, iterative=True, heuristics=True)]
        problems = [('sudoku',False),
                    ('nqueens-early', False),
                    ('nqueens-early', True),
                    ('nqueens-late', True),
                    ('coloring', False)
                    ]
        for solver in solvers:
            for pb, symmetric_break in problems:
                exp = Experiment(pb, solver=solver)
                exp.launch(None, timeout=300, symmetry_break=symmetric_break)
        
    if False: