Exemple #1
0
def main():
    # Check command-line arguments.
    print('Python version:', sys.version)

    if len(sys.argv) < 4:
        print("Program did not received enough correct argument.")
        print("Start Preset Testing.")
        test()
        return

    # GB = gameboard.GameBoard(
    #      12,3,4,[[0 for j in range(12)] for i in range(12)])
    # print(GB)

    TOTAL_START = time.time()
    sudokudata = filereader.SudokuFileReader(sys.argv[1])
    print(sudokudata)
    # cn = filereader.GameBoardToConstraintNetwork(sudokudata)
    # print(cn)
    solver = btsolver.BTSolver(sudokudata)
    tokens = sys.argv[4:]
    solver.setTokens(tokens)

    if len(sys.argv) == 4 or sys.argv[4] == 'BT':
        print("Default option tokens detected: Backtracking Search (BT)")

    for method in tokens:
        if method == 'FC':
            print("FC/ACP/NKD/NKT token detected: Forward Checking (FC)")
            solver.setConsistencyChecks(
                btsolver.ConsistencyCheck['ForwardChecking'])
        elif method == 'ACP':
            print("FC/ACP/NKD/NKT token detected: Arc Consistency (ACP)")
            solver.setConsistencyChecks(
                btsolver.ConsistencyCheck['ArcConsistency'])
        elif method == 'NKD':
            print("FC/ACP/NKD/NKT token detected: Naked Double (NKD)")
            solver.setConsistencyChecks(btsolver.ConsistencyCheck['NKD'])
        elif method == 'NKT':
            print("FC/ACP/NKD/NKT token detected: Naked Triple (NKT)")
            solver.setConsistencyChecks(btsolver.ConsistencyCheck['NKT'])
        elif method == 'MRV':
            print("MRV/DH token detected: Minimum Remaining Values (MRV)")
            solver.setVariableSelectionHeuristic(
                btsolver.VariableSelectionHeuristic['MRV'])
        elif method == 'DH':
            print("MRV/DH token detected: Degree Heuristic (DH)")
            solver.setVariableSelectionHeuristic(
                btsolver.VariableSelectionHeuristic['DH'])
        elif method == 'LCV':
            print("LCV token detected: Least Constraining Value (LCV)")
            solver.setValueSelectionHeuristic(
                btsolver.ValueSelectionHeuristic['LCV'])

    isTimeOut = False
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(int(sys.argv[3]))
    try:
        solver.solve()
        signal.alarm(0)  # cancel alarm
    except Exception:
        isTimeOut = True
        solver.endTime = time.time()
        print("Timed out by " + sys.argv[3] + " seconds !!!")

    print(printSolverStats(solver, TOTAL_START, isTimeOut))

    with open(sys.argv[2], "w") as outfile:
        outfile.write(printSolverStats(solver, TOTAL_START, isTimeOut))
    output += "\nCOUNT_NODES=" + str(solverObj.numAssignments)
    output += "\nCOUNT_DEADENDS=" + str(solverObj.numBacktracks)
    output += "\n" + str(solverObj.gameboard)

    return output


if __name__ == '__main__':
    # Check command-line arguments.
    print('Python version:', sys.version)

    # GB = gameboard.GameBoard(12,3,4,[[0 for j in range(12)] for i in range(12)])
    # print(GB)

    TOTAL_START = time.time()
    sudokudata = filereader.SudokuFileReader(sys.argv[1])
    print(sudokudata)
    # cn = filereader.GameBoardToConstraintNetwork(sudokudata)
    # print(cn)
    solver = btsolver.BTSolver(sudokudata)

    #three examples of how you would change the various aspects of solver
    # solver.setConsistencyChecks(btsolver.ConsistencyCheck['None'])
    # solver.setValueSelectionHeuristic(btsolver.ValueSelectionHeuristic['None'])
    # solver.setVariableSelectionHeuristic(btsolver.VariableSelectionHeuristic['None'])
    tokens = sys.argv[4:]
    solver.setTokens(tokens)
    '''once you have implemented more heuristics, you can add the appropriate lines to this conditional clause'''
    if len(sys.argv) < 4:
        raise ValueError("Program did not received enough correct argument.")
    elif len(sys.argv
Exemple #3
0
def test():
    """
    Test Function for Solver.

    Recommanded configuration:
    -------------------------------
    numTest | difficulty | timeout
    -------------------------------
       20   |    'E'     |  30/60
        5   |    'M'     |  60/120
        1   |    'H'     | 300/600
    -------------------------------
    """
    numTest = 1  # number of tests for each configuration
    difficulty = 'H'  # E - easy, M - medium, H - high
    timeout = 600  # set timeout to exit, will display 'infs'

    consisList = ['ForwardChecking', 'ArcConsistency', 'NKD', 'NKT']
    outfile = open('log/P' + difficulty + '.txt', 'w+')
    headline = 'id numBacktracks numAssignments avgtime'
    print('\n' + headline)
    outfile.write(headline + '\n')
    ph5_comb = [
        21, 27, 93, 75, 81, 87, 69, 159, 387, 63, 147, 141, 381, 351, 339, 363,
        345, 333, 15, 153, 22, 327, 375, 279, 321, 369, 129
    ]
    for root, dirs, files in os.walk("ExampleSudokuFiles/"):
        # for name in [x for x in files if x.startswith('P' + difficulty)]:
        name = "PH5.txt"
        combid = 0
        logline = name
        outfile.write(logline + '\n')
        print('\n' + logline)
        print('Unordered Result:')
        data = filereader.SudokuFileReader("ExampleSudokuFiles/" + name)
        timeHeap = []
        for consisNum in range(16):
            consisChk = []
            consisBits = "{0:04b}".format(consisNum)
            for bit, consisBit in enumerate(consisBits):
                if consisBit == '1':
                    consisChk.append(consisList[bit])
            if not consisChk:
                consisChk = ['None']
            for consisChkPermute in permutations(consisChk):
                for VarH in ['None', 'MRV', 'DH']:
                    for ValH in ['None', 'LCV']:
                        combid += 1
                        if combid in ph5_comb:
                            avgtime = 0
                            for i in range(numTest):
                                solver = btsolver.BTSolver(data)
                                for consis in consisChkPermute:
                                    solver.setConsistencyChecks(
                                        btsolver.ConsistencyCheck[consis])
                                solver.setVariableSelectionHeuristic(
                                    btsolver.VariableSelectionHeuristic[VarH])
                                solver.setValueSelectionHeuristic(
                                    btsolver.ValueSelectionHeuristic[ValH])
                                signal.signal(signal.SIGALRM, signal_handler)
                                signal.alarm(timeout)
                                try:
                                    avgtime += float(solver.solve())
                                    signal.alarm(0)  # cancel alarm
                                except Exception:
                                    avgtime = float('inf')
                                    break
                                if i == numTest - 1:
                                    avgtime /= numTest
                            status = str(combid) + ' ' +\
                                str(solver.numBacktracks) + ' ' +\
                                str(solver.numAssignments) + ' ' +\
                                str(avgtime)
                            print(status)
                            heappush(timeHeap, (avgtime, status))
        print('Ordered Result:')
        while timeHeap:
            avgtime, status = heappop(timeHeap)
            outfile.write(status + '\n')
            print(status)
    outfile.close()