예제 #1
0
def predictOutput(board, syzygy, numPieces):
    features = {}
    if numPieces == 3:
        weights = weight_vector_3_piece
        features = featureExtractor_3(board)

    elif numPieces == 4:
        weights = weight_vector_4_piece
    elif numPieces == 5:
        weights = weight_vector_5_piece

    print board

    expectVal = syzygy.probe_wdl(board)
    if (expectVal is None):
        print "Illegal move"
        return (-100, -100)

    elif (expectVal == 0):
        expectVal = -1
    else:
        expectVal = 1

    ourVal = 0

    for val in features:
        ourVal += weights[val] * features[val]

    if (ourVal <= 0):
        ourVal = -1
    elif (ourVal > 0):
        ourVal = 1

    return (expectVal, ourVal)
예제 #2
0
def getVal(FEN):
	syzygy = chess.syzygy.Tablebases()
	num = 0
	num += syzygy.open_directory(os.path.join(os.path.dirname(__file__), "four-men"))

	board = chess.Board(FEN)
	expectVal = syzygy.probe_wdl(board)
	return expectVal
예제 #3
0
def test(examples, color, weights, syzygy):
    total = 0
    correct = 0
    incorrect = 0
    for t in examples:
        if isIllegal(t):
                continue

        board = chess.Board(t + " " + color + " - - 0 1")
        expectVal = syzygy.probe_wdl(board)
        features = extractWordFeatures(board)

        if (expectVal is None):
            continue
        elif (expectVal == 0):
            expectVal = -1
        else:
            expectVal = 1
        

        ourVal = 0

        for val in features:
            ourVal += weights[val] * features[val]

        if (ourVal <= 0):
            ourVal = -1
        elif (ourVal > 0):
            ourVal = 1


        if ourVal == expectVal:
            correct = correct + 1
        # else:
        #     incorrect = incorrect + 1
        #     print board
        #     print expectVal
        #     print ourVal
        #     print " "
        #     if incorrect == 100:
        #         break
        
        # print ourVal

        total = total + 1

        if (total % 1000 == 0):
            print correct
            print total
            print " "

    print correct
    print total
예제 #4
0
def train(trainExamples, testExamples, featureExtractor, color, syzygy):
    weights = {}
    weights = defaultdict(lambda: 0.0, weights)

    numIters = 1;
    curIters = 0;
    n = 0.01

    pos = 0

    blackPos = 0
    blackNeg = 0
    for i in range (0,numIters):


        for xl,t in enumerate(trainExamples):

            if isIllegal(t):
                continue

            dotProd = 0.0

            board = chess.Board(t + " " + color + " - - 0 1")
            print board
            print xl
            print ""
           
            expectVal = syzygy.probe_wdl(board)

            if (expectVal is None):
                continue
            elif (expectVal == 0):
                expectVal = -1.0
            else:
                expectVal = 1.0

            print str(xl) + " " + str(expectVal)

            features = featureExtractor(board)

            for val in features:
                dotProd += weights[val] * features[val]

            if (1 - dotProd * expectVal) >= 0:
                for val in features:
                    weights[val] = weights[val] +  n * features[val] * expectVal

            curIters = curIters + 1
    return weights
예제 #5
0
def test(examples, color, weights, syzygy):
    total = 0
    correct = 0
    incorrect = 0
    for t in examples:
        if isIllegal(t):
            continue

        board = chess.Board(t + " " + color + " - - 0 1")
        expectVal = syzygy.probe_wdl(board)
        features = extractFeatures(board)
        
        if (expectVal is None):
            continue
        elif (expectVal == 0):
            expectVal = -1
        else:
            expectVal = 1


        ourVal = 0
            
        for val in features:
            ourVal += weights[val] * features[val]

        if (ourVal <= 0):
            ourVal = -1

        elif (ourVal > 0):
            ourVal = 1
        
        
        if ourVal == expectVal:
            correct = correct + 1

        total = total + 1
            
        if (total % 1000 == 0):
            print correct
            print total
            print " "

    print correct
    print total
예제 #6
0
def predictOutput(board, syzygy, numPieces):
	features = {}
	if numPieces == 3:
		weights = weight_vector_3_piece
		features = featureExtractor_3(board)

	elif numPieces == 4:
		weights = weight_vector_4_piece
		features = featureExtractor_4(board)
	elif numPieces == 5:
		weights = weight_vector_5_piece

	print board

	expectVal = syzygy.probe_wdl(board)
	if (expectVal is None):
	    print "Illegal move"
	    return (-100, -100)

	elif (expectVal == 0):
	    expectVal = -1
	else:
	    expectVal = 1


	ourVal = 0

	for val in features:
	    ourVal += weights[val] * features[val]

	if (ourVal <= 0):
	    ourVal = -1
	elif (ourVal > 0):
	    ourVal = 1


	return (expectVal, ourVal)
예제 #7
0
    name += "Q" * chess.pop_count(board.queens & board.occupied_co[chess.BLACK])
    name += "R" * chess.pop_count(board.rooks & board.occupied_co[chess.BLACK])
    name += "B" * chess.pop_count(board.bishops & board.occupied_co[chess.BLACK])
    name += "N" * chess.pop_count(board.knights & board.occupied_co[chess.BLACK])
    name += "P" * chess.pop_count(board.pawns & board.occupied_co[chess.BLACK])
    return name



print("Something works....")
board = chess.Board(FEN_TEST)
print(board)

print('now we try to get dtz: ')
A = syzygy.probe_dtz(board)
B = syzygy.probe_wdl(board)
print A
print B

print('going after material extraction: ')
Material = material(board)
print Material

print("Something works part 2....")
board = chess.Board(DEFAULT_FEN)
print(board)

print('now we try to get dtz: ')
A = syzygy.probe_dtz(board)
B = syzygy.probe_wdl(board)
print A
예제 #8
0
def learnPredictor(trainExamples, testExamples, featureExtractor, color, syzygy):
    '''
    Given |trainExamples| and |testExamples| (each one is a list of (x,y)
    pairs), a |featureExtractor| to apply to x, and the number of iterations to
    train |numIters|, return the weight vector (sparse feature vector) learned.

    You should implement stochastic gradient descent.

    Note: only use the trainExamples for training!
    You should call evaluatePredictor() on both trainExamples and testExamples
    to see how you're doing as you learn after each iteration.
    numIters refers to a variable you need to declare. It is not passed in.
    '''
    weights = {}  # feature => weight
    weights = defaultdict(lambda: 0.0, weights)
   
    
    # BEGIN_YOUR_CODE (around 15 lines of code expected)
    numIters = 1;
    curIters = 0;
    n = 0.01

    pos = 0

    blackPos = 0
    blackNeg = 0
    for i in range (0,numIters):


        for t in trainExamples:
            if isIllegal(t):
                continue

            dotProd = 0.0
            
            board = chess.Board(t + " " + color + " - - 0 1")
            expectVal = syzygy.probe_wdl(board)

            if (expectVal is None):
                continue
            elif (expectVal == 0):
                expectVal = -1.0
            else:
                expectVal = 1.0

            # pos = pos + 1

            # if pos%10000 == 0:
            #     print pos

            features = featureExtractor(board)

            if(features['black_can_capture'] == 1):
                if (expectVal == -1):
                    blackPos = blackPos + 1
                elif (expectVal == 1):
                    blackNeg = blackNeg + 1
                    # print board
                    # print isIllegal(t)
                    # print ""
                # if (blackNeg == 100):
                #     break
                # print weights['black_can_capture']
                # print expectVal
                # print " "

            for val in features:
                dotProd += weights[val] * features[val]

            if (1 - dotProd * expectVal) >= 0:
                for val in features:
                    weights[val] = weights[val] +  n * features[val] * expectVal

            curIters = curIters + 1
        print blackPos
        print blackNeg
        print i
        print weights
    
    # END_YOUR_CODE
    print weights
    return weights
예제 #9
0
def probe(board):
    moves = {}

    # The best move will be determined in this order.
    mating_move = None
    zeroing_move = None
    winning_move, winning_dtz = None, -9999
    stalemating_move = None
    insuff_material_move = None
    drawing_move = None
    losing_move, losing_dtz = None, -9999
    losing_zeroing_move, losing_zeroing_dtz = None, -9999

    # Look at all moves and probe for the result position.
    for move in board.legal_moves:
        uci_move = board.uci(move)
        board.push(move)

        dtz = syzygy.probe_dtz(board)
        dtm = gaviota.probe_dtm(board)

        moves[uci_move] = {
            "dtz": dtz,
            "dtm": dtm,
        }

        # Mate.
        if board.is_checkmate():
            mating_move = uci_move

        # Winning zeroing move.
        if dtz is not None and dtz < 0 and board.halfmove_clock == 0:
            zeroing_move = uci_move

        # Winning move.
        if dtz is not None and dtz < 0 and dtz > winning_dtz:
            winning_move = uci_move
            winning_dtz = dtz

        # Stalemating move.
        if board.is_stalemate():
            stalemating_move = uci_move

        # Insufficient material.
        if board.is_insufficient_material():
            insuff_material_move = uci_move

        # Drawing move.
        if dtz is not None and dtz == 0:
            drawing_move = uci_move

        # Losing move.
        if dtz is not None and board.halfmove_clock != 0 and dtz > losing_dtz:
            losing_move = uci_move
            losing_dtz = dtz

        # Losing move.
        if dtz is not None and dtz > losing_zeroing_dtz:
            losing_zeroing_move = uci_move
            losing_zeroing_dtz = dtz

        board.pop()

    return {
        "dtz":
        syzygy.probe_dtz(board),
        "wdl":
        syzygy.probe_wdl(board),
        "dtm":
        gaviota.probe_dtm(board),
        "bestmove":
        mating_move or zeroing_move or winning_move or stalemating_move
        or insuff_material_move or drawing_move or losing_move
        or losing_zeroing_move,
        "moves":
        moves,
    }
예제 #10
0
def index():
    # Setup a board from the given valid FEN or fall back to the default FEN.
    board = chess.Board(DEFAULT_FEN)

    # Get FENs with the current side to move, black and white to move.
    original_turn = board.turn
    board.turn = chess.WHITE
    white_fen = board.fen()
    board.turn = chess.BLACK
    black_fen = board.fen()
    board.turn = original_turn
    fen = board.fen()

    wdl = None
    winning_side = None
    winning_moves = []
    drawing_moves = []
    losing_moves = []

    if not board.is_valid():
        status = "Invalid position"
    elif board.is_stalemate():
        status = "Draw by stalemate"
        wdl = 0
    elif board.is_checkmate():
        wdl = 2
        if board.turn == chess.WHITE:
            status = "Black won by checkmate"
            winning_side = "black"
        else:
            status = "White won by checkmate"
            winning_side = "white"
    else:
        wdl = syzygy.probe_wdl(board)
        dtz = syzygy.probe_dtz(board)
        if board.is_insufficient_material():
            status = "Draw by insufficient material"
            wdl = 0
        elif dtz is None:
            status = "Position not found in tablebases"
        elif dtz == 0:
            status = "Tablebase draw"
        elif dtz > 0 and board.turn == chess.WHITE:
            status = "White is winning with DTZ %d" % (abs(dtz), )
            winning_side = "white"
            losing_side = "black"
        elif dtz < 0 and board.turn == chess.WHITE:
            status = "White is losing with DTZ %d" % (abs(dtz), )
            winning_side = "black"
            losing_side = "white"
        elif dtz > 0 and board.turn == chess.BLACK:
            status = "Black is winning with DTZ %d" % (abs(dtz), )
            winning_side = "black"
            losing_side = "white"
        elif dtz < 0 and board.turn == chess.BLACK:
            status = "Black is losing with DTZ %d" % (abs(dtz), )
            winning_side = "white"
            losing_side = "black"

        for move in board.legal_moves:
            san = board.san(move)
            uci = board.uci(move)
            board.push(move)

            move_info = {
                "uci": uci,
                "san": san,
                "fen": board.epd() + " 0 1",
                "dtz": syzygy.probe_dtz(board),
                "dtm": gaviota.probe_dtm(board),
                "zeroing": board.halfmove_clock == 0,
                "checkmate": board.is_checkmate(),
                "stalemate": board.is_stalemate(),
                "insufficient_material": board.is_insufficient_material(),
            }

            move_info["dtm"] = abs(
                move_info["dtm"]) if move_info["dtm"] is not None else None

            move_info["winning"] = move_info["checkmate"] or (
                move_info["dtz"] is not None and move_info["dtz"] < 0)
            move_info["drawing"] = move_info["stalemate"] or move_info[
                "insufficient_material"] or (move_info["dtz"] == 0 or
                                             (move_info["dtz"] is None
                                              and wdl is not None and wdl < 0))

            if move_info["winning"]:
                if move_info["checkmate"]:
                    move_info["badge"] = "Checkmate"
                elif move_info["zeroing"]:
                    move_info["badge"] = "Zeroing"
                else:
                    move_info["badge"] = "Win with DTZ %d" % (abs(
                        move_info["dtz"]), )

                winning_moves.append(move_info)
            elif move_info["drawing"]:
                if move_info["stalemate"]:
                    move_info["badge"] = "Stalemate"
                elif move_info["insufficient_material"]:
                    move_info["badge"] = "Insufficient material"
                elif move_info["dtz"] == 0:
                    move_info["badge"] = "Draw"
                else:
                    move_info["badge"] = "Unknown"

                drawing_moves.append(move_info)
            else:
                if move_info["dtz"] is None:
                    move_info["badge"] = "Unknown"
                elif move_info["zeroing"]:
                    move_info["badge"] = "Zeroing"
                else:
                    move_info["badge"] = "Loss with DTZ %d" % (abs(
                        move_info["dtz"]), )
                losing_moves.append(move_info)

            board.pop()

    winning_moves.sort(key=lambda move: move["uci"])
    winning_moves.sort(key=lambda move: (move["dtm"] is None, move["dtm"]))
    winning_moves.sort(key=lambda move: (move["dtz"] is None, move["dtz"]),
                       reverse=True)
    winning_moves.sort(key=lambda move: move["zeroing"], reverse=True)
    winning_moves.sort(key=lambda move: move["checkmate"], reverse=True)

    drawing_moves.sort(key=lambda move: move["uci"])
    drawing_moves.sort(key=lambda move: move["insufficient_material"],
                       reverse=True)
    drawing_moves.sort(key=lambda move: move["stalemate"], reverse=True)

    losing_moves.sort(key=lambda move: move["uci"])
    losing_moves.sort(key=lambda move: (move["dtm"] is not None, move["dtm"]),
                      reverse=True)
    losing_moves.sort(key=lambda move: (move["dtz"] is None, move["dtz"]),
                      reverse=True)
    losing_moves.sort(key=lambda move: move["zeroing"])

    return html_minify(
        render_template("index.html",
                        fen_input=board.epd() +
                        " 0 1" if board.epd() + " 0 1" != DEFAULT_FEN else "",
                        fen=fen,
                        status=status,
                        insufficient_material=board.is_insufficient_material(),
                        winning_side=winning_side,
                        winning_moves=winning_moves,
                        drawing_moves=drawing_moves,
                        losing_moves=losing_moves,
                        blessed_loss=wdl == -1,
                        cursed_win=wdl == 1,
                        illegal=not board.is_valid(),
                        not_yet_solved=board.epd() +
                        " 0 1" == chess.STARTING_FEN,
                        unknown=wdl is None,
                        turn="white" if board.turn == chess.WHITE else "black",
                        white_fen=white_fen,
                        black_fen=black_fen,
                        horizontal_fen=mirror_horizontal(fen),
                        vertical_fen=mirror_vertical(fen),
                        swapped_fen=swap_colors(fen),
                        clear_fen=clear_fen(fen),
                        DEFAULT_FEN=DEFAULT_FEN,
                        material=material(board)))
예제 #11
0
    name += "R" * chess.pop_count(board.rooks & board.occupied_co[chess.BLACK])
    name += "B" * chess.pop_count(board.bishops
                                  & board.occupied_co[chess.BLACK])
    name += "N" * chess.pop_count(board.knights
                                  & board.occupied_co[chess.BLACK])
    name += "P" * chess.pop_count(board.pawns & board.occupied_co[chess.BLACK])
    return name


print("Something works....")
board = chess.Board(FEN_TEST)
print(board)

print('now we try to get dtz: ')
A = syzygy.probe_dtz(board)
B = syzygy.probe_wdl(board)
print A
print B

print('going after material extraction: ')
Material = material(board)
print Material

print("Something works part 2....")
board = chess.Board(DEFAULT_FEN)
print(board)

print('now we try to get dtz: ')
A = syzygy.probe_dtz(board)
B = syzygy.probe_wdl(board)
print A
예제 #12
0
def probe(board):
    moves = {}

    # The best move will be determined in this order.
    mating_move = None
    zeroing_move = None
    winning_move, winning_dtz = None, -9999
    stalemating_move = None
    insuff_material_move = None
    drawing_move = None
    losing_move, losing_dtz = None, -9999
    losing_zeroing_move, losing_zeroing_dtz = None, -9999

    # Look at all moves and probe for the result position.
    for move in board.legal_moves:
        uci_move = board.uci(move)
        board.push(move)

        dtz = syzygy.probe_dtz(board)
        dtm = gaviota.probe_dtm(board)

        moves[uci_move] = {
            "dtz": dtz,
            "dtm": dtm,
        }

        # Mate.
        if board.is_checkmate():
            mating_move = uci_move

        # Winning zeroing move.
        if dtz is not None and dtz < 0 and board.halfmove_clock == 0:
            zeroing_move = uci_move

        # Winning move.
        if dtz is not None and dtz < 0 and dtz > winning_dtz:
            winning_move = uci_move
            winning_dtz = dtz

        # Stalemating move.
        if board.is_stalemate():
            stalemating_move = uci_move

        # Insufficient material.
        if board.is_insufficient_material():
            insuff_material_move = uci_move

        # Drawing move.
        if dtz is not None and dtz == 0:
            drawing_move = uci_move

        # Losing move.
        if dtz is not None and board.halfmove_clock != 0 and dtz > losing_dtz:
            losing_move = uci_move
            losing_dtz = dtz

        # Losing move.
        if dtz is not None and dtz > losing_zeroing_dtz:
            losing_zeroing_move = uci_move
            losing_zeroing_dtz = dtz

        board.pop()

    return {
        "dtz": syzygy.probe_dtz(board),
        "wdl": syzygy.probe_wdl(board),
        "dtm": gaviota.probe_dtm(board),
        "bestmove": mating_move or zeroing_move or winning_move or stalemating_move or insuff_material_move or drawing_move or losing_move or losing_zeroing_move,
        "moves": moves,
    }
예제 #13
0
def index():
    # Setup a board from the given valid FEN or fall back to the default FEN.
    try:
        board = chess.Board(request.args.get("fen", DEFAULT_FEN))
    except ValueError:
        try:
            board, _ = chess.Board.from_epd(request.args.get("fen", DEFAULT_FEN))
        except ValueError:
            board = chess.Board(DEFAULT_FEN)

    # Get FENs with the current side to move, black and white to move.
    original_turn = board.turn
    board.turn = chess.WHITE
    white_fen = board.fen()
    board.turn = chess.BLACK
    black_fen = board.fen()
    board.turn = original_turn
    fen = board.fen()

    wdl = None
    winning_side = None
    winning_moves = []
    drawing_moves = []
    losing_moves = []

    if not board.is_valid():
        status = "Invalid position"
    elif board.is_stalemate():
        status = "Draw by stalemate"
        wdl = 0
    elif board.is_checkmate():
        wdl = 2
        if board.turn == chess.WHITE:
            status = "Black won by checkmate"
            winning_side = "black"
        else:
            status = "White won by checkmate"
            winning_side = "white"
    else:
        wdl = syzygy.probe_wdl(board)
        dtz = syzygy.probe_dtz(board)
        if board.is_insufficient_material():
            status = "Draw by insufficient material"
            wdl = 0
        elif dtz is None:
            status = "Position not found in tablebases"
        elif dtz == 0:
            status = "Tablebase draw"
        elif dtz > 0 and board.turn == chess.WHITE:
            status = "White is winning with DTZ %d" % (abs(dtz), )
            winning_side = "white"
            losing_side = "black"
        elif dtz < 0 and board.turn == chess.WHITE:
            status = "White is losing with DTZ %d" % (abs(dtz), )
            winning_side = "black"
            losing_side = "white"
        elif dtz > 0 and board.turn == chess.BLACK:
            status = "Black is winning with DTZ %d" % (abs(dtz), )
            winning_side = "black"
            losing_side = "white"
        elif dtz < 0 and board.turn == chess.BLACK:
            status = "Black is losing with DTZ %d" % (abs(dtz), )
            winning_side = "white"
            losing_side = "black"

        for move in board.legal_moves:
            san = board.san(move)
            uci = board.uci(move)
            board.push(move)

            move_info = {
                "uci": uci,
                "san": san,
                "fen": board.epd() + " 0 1",
                "dtz": syzygy.probe_dtz(board),
                "dtm": gaviota.probe_dtm(board),
                "zeroing": board.halfmove_clock == 0,
                "checkmate": board.is_checkmate(),
                "stalemate": board.is_stalemate(),
                "insufficient_material": board.is_insufficient_material(),
            }

            move_info["dtm"] = abs(move_info["dtm"]) if move_info["dtm"] is not None else None

            move_info["winning"] = move_info["checkmate"] or (move_info["dtz"] is not None and move_info["dtz"] < 0)
            move_info["drawing"] = move_info["stalemate"] or move_info["insufficient_material"] or (move_info["dtz"] == 0 or (move_info["dtz"] is None and wdl is not None and wdl < 0))

            if move_info["winning"]:
                if move_info["checkmate"]:
                    move_info["badge"] = "Checkmate"
                elif move_info["zeroing"]:
                    move_info["badge"] = "Zeroing"
                else:
                    move_info["badge"] = "Win with DTZ %d" % (abs(move_info["dtz"]), )

                winning_moves.append(move_info)
            elif move_info["drawing"]:
                if move_info["stalemate"]:
                    move_info["badge"] = "Stalemate"
                elif move_info["insufficient_material"]:
                    move_info["badge"] = "Insufficient material"
                elif move_info["dtz"] == 0:
                    move_info["badge"] = "Draw"
                else:
                    move_info["badge"] = "Unknown"

                drawing_moves.append(move_info)
            else:
                if move_info["dtz"] is None:
                    move_info["badge"] = "Unknown"
                elif move_info["zeroing"]:
                    move_info["badge"] = "Zeroing"
                else:
                    move_info["badge"] = "Loss with DTZ %d" % (abs(move_info["dtz"]), )
                losing_moves.append(move_info)

            board.pop()

    winning_moves.sort(key=lambda move: move["uci"])
    winning_moves.sort(key=lambda move: (move["dtm"] is None, move["dtm"]))
    winning_moves.sort(key=lambda move: (move["dtz"] is None, move["dtz"]), reverse=True)
    winning_moves.sort(key=lambda move: move["zeroing"], reverse=True)
    winning_moves.sort(key=lambda move: move["checkmate"], reverse=True)

    drawing_moves.sort(key=lambda move: move["uci"])
    drawing_moves.sort(key=lambda move: move["insufficient_material"], reverse=True)
    drawing_moves.sort(key=lambda move: move["stalemate"], reverse=True)

    losing_moves.sort(key=lambda move: move["uci"])
    losing_moves.sort(key=lambda move: (move["dtm"] is not None, move["dtm"]), reverse=True)
    losing_moves.sort(key=lambda move: (move["dtz"] is None, move["dtz"]), reverse=True)
    losing_moves.sort(key=lambda move: move["zeroing"])

    return html_minify(render_template("index.html",
        fen_input=board.epd() + " 0 1" if board.epd() + " 0 1" != DEFAULT_FEN else "",
        fen=fen,
        status=status,
        insufficient_material=board.is_insufficient_material(),
        winning_side=winning_side,
        winning_moves=winning_moves,
        drawing_moves=drawing_moves,
        losing_moves=losing_moves,
        blessed_loss=wdl == -1,
        cursed_win=wdl == 1,
        illegal=not board.is_valid(),
        not_yet_solved=board.epd() + " 0 1" == chess.STARTING_FEN,
        unknown=wdl is None,
        turn="white" if board.turn == chess.WHITE else "black",
        white_fen=white_fen,
        black_fen=black_fen,
        horizontal_fen=mirror_horizontal(fen),
        vertical_fen=mirror_vertical(fen),
        swapped_fen=swap_colors(fen),
        clear_fen=clear_fen(fen),
        DEFAULT_FEN=DEFAULT_FEN,
        material=material(board)
    ))