예제 #1
0
파일: driver.py 프로젝트: leyulin/CS550
def play():
    #  get from sudoku.py
    easy1 = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
    harder1 = '4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'

    for puzzle in [easy1, harder1]:
        # for puzzle in [easy1]:
        s = Sudoku(puzzle)
        # Initial sudoku state
        print("\nInitial problem:")
        s.display(s.infer_assignment())

        # The state of the puzzle after running AC3.
        AC3(s)
        if s.goal_test(s.curr_domains):
            print("\nAfter AC3 constraint propagation\n")
            s.display(s.infer_assignment())

        # if goal test fail try to find solution
        elif not s.goal_test(s.curr_domains):
            # run back track search
            solution = backtracking_search(s, select_unassigned_variable=mrv)
            if solution:
                print("\nSolved using backtracking:")
                s.display(s.infer_assignment())
            else:
                print("\nCould not be solved using backtrack\n")
                s.display(s.infer_assignment())
예제 #2
0
def solve(params, initial_guess, converge_step):

    (X,y,m) = params

    #A function which calculates the gradient at a point
    grad_func = lc.gen_gradient_function(X,y,m)

    # A function which calculates the likelihood at a point
    llh_func = lc.gen_likelihood_function(X,y,m)

    delta = sys.float_info.max   # Initial values for change between iteration
    guess = initial_guess
    LLVal = 0             # Dummy likelihood value
    iterct = 0

    # For storing likelihoods (for tracking convergence)
    likelihood_record = []

    ## Main Steepest Descent Lofunc
    while delta > converge_step:
        oldLLVal = LLVal
        oldGuess = guess

        grad = grad_func(guess)
        searchDir = -grad
        step = backtracking_search(grad_func, llh_func, guess, searchDir)

        guess = guess + searchDir * step

        # Calculate current likelihood for convergence determination
        LLVal = llh_func(guess)
        delta = abs( oldLLVal - LLVal )

        likelihood_record.append(LLVal)

        # Update the user and break out if needed
        iterct += 1
        print("Iter: " + str(iterct) + ", objective is " + str(LLVal) + " step size: " + str(step)) 
        if iterct > 10000:
            print("Reached 10000 iterations w/o convergence, aborting computation")
            break

    return (guess,likelihood_record)
예제 #3
0
파일: input.py 프로젝트: Auzzy/school
def main():
	file_text,select_unassigned_var,order_domain_vals,inference,domains = get_input()

	input_lines = [line.strip() for line in file_text.split('\n')]
	variables,values,limits,unary_inc,unary_ex,binary_eq,binary_ne,binary_mutual_ex = read_file(input_lines)

	var_names = variables.keys()
	val_names = values.keys()
	create_constraint_matrices(var_names,val_names,unary_inc,unary_ex,binary_eq,binary_ne,binary_mutual_ex)

	result = backtracking_search(values,variables,limits[0],limits[1],_constraint_matrices, select_unassigned_var, order_domain_vals, inference, domains)

	if result is None:
		print "Unsolvable!!!"
		exit(0)

	result_keys = result.keys()
	result_keys.sort()
	for valuable in result_keys:
		print "%s %s" % (valuable,result[valuable])
예제 #4
0
def game():
    print("================================= Sudoku ==================================")
    print("CS 550 Artificial Intelligence | Prof. Roch | Assignment 4 | kingofthenorth")
    print("============================= Creating game... ============================")

    game_start = time.time()

    for puzzle in [easy1, harder1]:

        # Creates an instance of the puzzle to work with
        s = Sudoku(puzzle)

        # Creates a viewable interface of the working sudoku puzzle
        print("\nInitial problem:")
        s.display(s.infer_assignment())

        # Applies the AC3 constraint
        AC3(s)
        print("\nAfter AC3 constraint propagation applied!")

        # Keeps track of time of the puzzle
        puzzle_start = time.time()

        # If goal is not reached yet, keep trying to find a solution
        if not s.goal_test(s.curr_domains):
            print("\nBacktracking search starting...")
            result = backtracking_search(s, select_unassigned_variable=mrv)
            if result:
                # Success
                print("\nBacktracking solution:")
                s.display(s.infer_assignment())
            else:
                # Failure
                print("\nBacktracking failed! :(")

        current = time.time()

        # Time information to be relayed
        print("\nPuzzle time: {} | Overall time: {}".format(
            elapsed(puzzle_start, current), elapsed(game_start, current)))
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from backtrack import backtracking_search
from csp_lib.backtrack_util import mrv, mac

easy_puzzle = Sudoku(easy1)
easy_puzzle.display(easy_puzzle.infer_assignment())
print(AC3(easy_puzzle))
easy_puzzle.display(easy_puzzle.infer_assignment())


hard_puzzle = Sudoku(harder1)
hard_puzzle.display(hard_puzzle.infer_assignment())
print(AC3(easy_puzzle))
result = backtracking_search(hard_puzzle, select_unassigned_variable=mrv, inference=mac)
#print("result = " + str(result))
hard_puzzle.display(hard_puzzle.infer_assignment())



#easy_puzzle.display(easy_puzzle.infer_assignment())
'''
print("\n")
print("Domains Stuff")
print("print(easy_puzzle.domains)")
print(easy_puzzle.domains)
print("print(len(easy_puzzle.domains))")
print(len(easy_puzzle.domains))
print("print(type(easy_puzzle.domains[0]))")
print(type(easy_puzzle.domains[0]))
print("print(type(easy_puzzle.domains[2]))")
예제 #6
0
파일: driver.py 프로젝트: tpaulus/CS550

def is_solved(sudoku: Sudoku):
    for var in sudoku.curr_domains:
        if len(sudoku.curr_domains[var]) is not 1:
            return False
    return True


if __name__ == "__main__":
    for puzzle in [easy1, harder1]:
        # for puzzle in [easy1]:
        s = Sudoku(puzzle)  # construct a Sudoku problem
        print("New Sudoku Puzzle")
        s.display(s.infer_assignment())
        AC3(s)
        if is_solved(s):
            print("Solved via AC3")
            s.display(s.infer_assignment())
        else:
            print("Could not solve via AC3: Current Puzzle")
            s.display(s.infer_assignment())
            print("Trying to solve via Back Track")
            backtracking_search(s, inference=forward_checking, order_domain_values=lcv, select_unassigned_variable=mrv)
            if is_solved(s):
                print("Solved via Back Track")
                s.display(s.infer_assignment())
            else:
                print("Puzzle could not be solved: Current State")
                s.display(s.infer_assignment())
예제 #7
0
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv, forward_checking, first_unassigned_variable, unordered_domain_values, no_inference
from backtrack import backtracking_search

for puzzle in [easy1, harder1]:
    s = Sudoku(puzzle)  # construct a Sudoku problem
    print("---initial state---")
    s.display(s.infer_assignment())
    print("\n")
    AC3(s)

    print("---after AC3---")
    s.display(s.infer_assignment())
    print("\n")

    if not s.goal_test(s.curr_domains):
        solved = backtracking_search(s,
                                     select_unassigned_variable=mrv,
                                     inference=forward_checking)
        print("---after backtracking---")
        s.display(solved)
for puzzle in [easy1, harder1]:
    sudoku_instance = Sudoku(puzzle)

    print("We have the following Sudoku puzzle to solve:", end="\n\n")
    sudoku_instance.display(sudoku_instance.infer_assignment())
    print("\nStarting constraint propagation (AC3) algorithm.")
    AC3(sudoku_instance)
    print("AC3 algorithm was successfully completed.")

    if sudoku_instance.goal_test(sudoku_instance.curr_domains):
        print("Problem was solved by AC3. Here is the solution:", end="\n\n")
        sudoku_instance.display(sudoku_instance.infer_assignment())
        print()
    else:
        print("Problem was not solved by AC3. Here is how it looks like:",
              end="\n\n")
        sudoku_instance.display(sudoku_instance.infer_assignment())
        print()
        print("We should start searching ...")
        search_result = backtracking_search(sudoku_instance, mrv, lcv, mac)
        print("Search has been completed successfully.")
        if sudoku_instance.goal_test(search_result):
            print("Given constraint satisfaction problem has been "
                  "successfully solved by backtracking search algorithm. Here "
                  "it the solution:", end='\n\n')
            sudoku_instance.display(sudoku_instance.infer_assignment())
        else:
            print("Backtracking search algorithm was not able to solve the "
                  "problem.", end='\n\n')
            sudoku_instance.display(sudoku_instance.infer_assignment())
예제 #9
0
        h = Sudoku(puzzle)  # construct a Sudoku problem hard1
        print("Initial State hard")
        print()
        h.display(h.infer_assignment())
        print()
        print('Solving the problem. Apply AC3...')
        print()
        AC3(h)
        print()
        for var in h.curr_domains:
            h.curr_domains[var] = list(h.domains[var])
        if not h.goal_test(h.curr_domains):
            print("After AC3")
            h.display(h.infer_assignment())
            print()
            print("Try backtraking")
            print()
            solved = backtracking_search(h,
                                         select_unassigned_variable=mrv,
                                         order_domain_values=lcv,
                                         inference=forward_checking)
            print("Final status")
            print()
            if solved is None:
                print("The problem was not solved")
            else:
                if h.goal_test(solved):
                    h.display(solved)
                else:
                    print("Invalid solution")
예제 #10
0
def solve(params, initial_guess, converge_step):

    ### VALUE INITIALIZATION

    (X, y, m) = params
    (N, P) = np.shape(X)

    #A function which calculates the gradient at a point
    grad_func = lc.gen_gradient_function(X, y, m)

    # A function which calculates the likelihood at a point
    llh_func = lc.gen_likelihood_function(X, y, m)

    # A function to calculate the Hessian (only used for initialization)
    hess_func = gen_hessian_function(X, y, m)

    delta = sys.float_info.max  # Initial values for change between iteration
    guess = initial_guess
    LLVal = 0  # Dummy likelihood value
    iterct = 0

    # For storing likelihoods (for tracking convergence)
    likelihood_record = []

    ### STEEPEST DESCENT BURN-IN

    # Do a few iterations of steepest descent to burn in Hessian
    B = hess_func(guess)
    while npla.cond(B) > 1e6:
        oldLLVal = LLVal
        oldGuess = guess

        grad = grad_func(guess)
        searchDir = -grad
        step = backtracking_search(grad_func, llh_func, guess, searchDir)

        guess = guess + searchDir * step
        B = hess_func(guess)

        oldGrad = grad

    ### ACTUAL BFGS CODE

    # We now have a suitable B for inversion. Calculate it and update w/ BFGS
    H = B.I
    grad = grad_func(
        guess)  #Also compute gradient so BGFS has a "previous gradient"

    # BFGS Mainloop
    while delta > converge_step:
        # Find search direction and update
        searchDir = -np.dot(H, oldGrad)
        step = backtracking_search(grad_func, llh_func, guess, searchDir)
        guess = guess + searchDir * step

        # Update gradient guess
        grad = grad_func(guess)

        # Update inverse Hessian approximation
        s = (guess - oldGuess)
        y = (grad - oldGrad)
        p = 1 / np.asscalar(np.dot(y.T, s))
        I = np.identity(P)

        # Calculate update matrix (I - p * s * y.T)
        updMat = I - p * s * y.T

        # Update H
        H = updMat * H * updMat + p * s * s.T

        # Calculate current likelihood for convergence determination
        LLVal = llh_func(guess)
        delta = abs(oldLLVal - LLVal)

        # Update recordkeeping values
        oldLLVal = LLVal
        oldGuess = guess
        oldGrad = grad
        likelihood_record.append(LLVal)

        # Update the user and break out if needed
        iterct += 1
        print("Iter: " + str(iterct) + ", objective is: " + str(LLVal)\
              + " Step size is: "  + str(step))
        if iterct > 10000:
            print(
                "Reached 10000 iterations w/o convergence, aborting computation"
            )
            break

    return (guess, likelihood_record)
예제 #11
0
파일: driver.py 프로젝트: nibichua/CS550_A4
for puzzle in [easy1]:
    easy = Sudoku(easy1)  # constructing the easy Sudoku problem
    print("Easy Sudoku Problem:")
    easy.display(easy.infer_assignment())

    AC3(easy)  #Calling Constraint Propagation to solve

    print("\n")
    print("After calling AC3:")
    easy.display(easy.infer_assignment())

    if not easy.goal_test(easy.curr_domains):
        print("\n")
        print("Backtracking easy problem...")
        result = backtracking_search(easy, select_unassigned_variable=mrv)
        if result:
            print("After backtracking:")
            easy.display(easy.infer_assignment())

for puzzle in [harder1]:
    hard = Sudoku(puzzle)  # constructing the hard Sudoku problem
    print("\n")
    print("Hard Sudoku Problem:")
    hard.display(hard.infer_assignment())

    AC3(hard)  #Calling Constraint Propagation to solve

    print("\n")
    print("After calling AC3:")
    hard.display(hard.infer_assignment())
예제 #12
0
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv, mac
from backtrack import backtracking_search
import queue

for puzzle in [easy1, harder1]:
    s = Sudoku(puzzle)  # construct a Sudoku problem
    s.display(s.infer_assignment())
    constraints_satisfied = AC3(
        s
    )  # returns true or false This is to trigger Backtrack_search, Revise alters domains
    if constraints_satisfied is True:  # goal test instead
        solved = backtracking_search(csp=s,
                                     select_unassigned_variable=mrv,
                                     inference=mac)
        if solved is not None:
            print("backtrack search solution:")
            s.display(s.infer_assignment())
        else:
            print("This sudoku puzzle is not solvable")
    else:
        s.display(
            s.infer_assignment()
        )  # will display an updated board, because e was manipulated inside algorithm using revise def
        # or do I test to see if its solved, # goalstate
'''Output
. . 3 | . 2 . | 6 . .
9 . . | 3 . 5 | . . 1
. . 1 | 8 . 6 | 4 . .
------+-------+------
예제 #13
0
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv
from backtrack import backtracking_search

for puzzle in [easy1, harder1]:
    s = Sudoku(puzzle)  # construct a Sudoku problem

    # display initial state
    print("\nSudoku puzzle initial state")
    s.display(s.infer_assignment())

    # run constraint satisfaction arc consistency
    AC3(s)
    # iterate through variables and add them to puzzle if possible
    for val in s.domains:
        if len(s.domains[val]) == 1:
            s.suppose(val, s.domains[val][0])

    # display state after AC3
    print("\nSudoku puzzle state after AC3")
    s.display(s.infer_assignment())

    # check if goal has been reached by AC3
    if not s.goal_test(s.curr_domains):
        # run backtracking search if domains need work
        solved = backtracking_search(s)
        print("\nSudoku state after AC3 and backtracking search")
        s.display(s.infer_assignment())