Optimize this python code:
import math
import time
class TranspositionTable:
def init(self,Size:int=256):
self.KeyIndex=[str(-X) for X in range(1,Size+1)]
self.Table={str(-X):-X for X in range(1,Size+1)}
code
def Put(self,Index,Value):
#print(self.Table,self.KeyIndex)
#print(self.KeyIndex[0])
#print(self.Table[str(Index)])
self.Table.pop(str(list(self.Table.keys())[0]))
#self.KeyIndex.pop(0)
self.Table[str(Index)]=Value
#self.KeyIndex.append(str(Index))
def Get(self,Index):
if Index in self.KeyIndex:
return self.Table[Index]
return 0
def BoardFull(self):
return len(self.State) >= self.Width * self.Height
def MoveNumber(self):
return len(self.State)
@staticmethod
def _TranslateToBoard(State:str,Width:int,Height:int):
Board=[[0 for X in range(Width)] for Y in range(Height)]
for N,Move in enumerate(State):
for Y in range(Height - 1,-1,-1):
if Board[Y][int(Move)-1] == 0:
Board[Y][int(Move)-1]=1 if N%2==0 else 2
break
return Board
def IsWinningMove(self,Move:int):
Move=Move+1
NewState=self.State+str(Move)
MovePos=(Move-1,self.Height-self.State.count(str(Move))-1,1 if len(self.State)%2==0 else 2)
Board=BoardState._TranslateToBoard(NewState,self.Width,self.Height)
#print(MovePos)
#BoardState(NewState,self.Width,self.Height).Render()
if NewState.count(str(Move)) > 3:
if Board[MovePos[1]+1][MovePos[0]] == MovePos[2] and Board[MovePos[1]+2][MovePos[0]] == MovePos[2] and Board[MovePos[1]+3][MovePos[0]] == MovePos[2]:
return True
RowN=0
DiaN1=0
DiaN2=0
#print(MovePos)
for OX in range(-3,4):
NewX=MovePos[0]+OX
NewY=MovePos[1]+OX
if NewX >= 0 and NewX < self.Width:
if Board[MovePos[1]][NewX] == MovePos[2]:
RowN+=1
else:
RowN=0
if RowN >= self.WinLength:
return True
if NewY >=0 and NewY < self.Height:
#print(NewX,NewY)
if Board[NewY][NewX] == MovePos[2]:
DiaN1+=1
else:
DiaN1=0
if DiaN1 >= self.WinLength:
return True
NewX=MovePos[0]-OX
if NewX >= 0 and NewX < self.Width:
if NewY >=0 and NewY < self.Height:
if Board[NewY][NewX] == MovePos[2]:
DiaN2+=1
else:
DiaN2=0
if DiaN2 >= self.WinLength:
return True
return False
@staticmethod
def _FormatPiece(Piece):
if Piece == 1:
return "🔴"
if Piece == 2:
return "🟡"
if Piece == 0:
return " "
def Render(self):
Board=BoardState._TranslateToBoard(self.State,self.Width,self.Height)
Output=[]
for Y in range(self.Height):
Output.append("|".join([BoardState._FormatPiece(Board[Y][X]) for X in range(self.Width)]))
print(f"\n{('--+'*self.Width)[:-1]}\n".join(Output))
class NegMaxSolver:
MoveOrder=[]
@staticmethod
def InitMoveOrder(Width:int):
for X in range(0,Width):
NegMaxSolver.MoveOrder.append((Width//2)+(-X//2 if X%2==0 else math.ceil(X/2)))
@staticmethod
def NegMax(Board:BoardState,Alpha:int,Beta:int,TransTable:TranspositionTable):
ColumnStates=[Board.ColFull(X) for X in range(Board.Width)]
#print("Col States",ColumnStates)
if all(ColumnStates) == True:
return 0
code
for X in range(0,Board.Width):
if ColumnStates[NegMaxSolver.MoveOrder[X]] == False:
if Board.IsWinningMove(NegMaxSolver.MoveOrder[X]):
return (((Board.Width*Board.Height)+1)-Board.MoveNumber())//2
"""
TempHash=BoardState._TranslateToBoard(Board.State,Board.Width,Board.Height)
Hash=[]
for X in TempHash:
Hash+=[str(Y) for Y in X]
Hash="".join(Hash)
"""
Max=(((Board.Width*Board.Height)-1)-Board.MoveNumber())//2
"""
Transvalue=int(TransTable.Get(Hash))
if Transvalue != 0:
Max=Transvalue + Board.MinScore - 1
"""
if Beta > Max:
Beta=Max
if Alpha >= Beta:
return Beta
for X in range(0,Board.Width):
if ColumnStates[NegMaxSolver.MoveOrder[X]] == False:
NewBoard=BoardState(f"{Board.State}{NegMaxSolver.MoveOrder[X]+1}",Board.Width,Board.Height,Board.WinLength)
Score=-NegMaxSolver.NegMax(NewBoard,-Beta,-Alpha,TransTable)
if Score >= Beta:
return Score
if Score > Alpha:
Alpha=Score
#TransTable.Put(Hash,Alpha - Board.MinScore + 1)
return Alpha
@staticmethod
def Solve(Board:BoardState,Weak:bool=False,TableSize:int=81):
TransTable=TranspositionTable(TableSize)
Min=-(((Board.Width*Board.Height))-Board.MoveNumber())//2
Max=(((Board.Width*Board.Height)+1)-Board.MoveNumber())//2
if Weak:
Min=-1
Max=1
while Min < Max:
Med = Min + (Max - Min)//2
if Med <= 0 and Min//2 < Med:
Med = Min//2
elif Med >= 0 and Max//2 > Med:
Med = Max//2
Score = NegMaxSolver.NegMax(Board, Med, Med + 1,TransTable)
if Score <= Med:
Max = Score
else:
Min = Score
return Min
Optimizing Python code, especially for performance-critical applications like game solvers, involves several strategies. Below is an optimized version of your Connect Four-like game solver that addresses key performance bottlenecks in your original implementation. The optimizations focus on:
Data Structures: Replacing strings with lists for mutable and faster operations.
Efficient Board Representation: Maintaining the board state incrementally to avoid reconstructing it repeatedly.
Optimized Transposition Table: Using OrderedDict for efficient LRU caching with integer-based keys.
Improved Win Checking: Streamlining the is_winning_move method for faster win condition verification.
Avoiding Unnecessary Object Creation: Modifying the board in place during the negamax search instead of creating new instances.
Here’s the optimized code with detailed explanations:
python
import math
from collections import OrderedDict
class TranspositionTable:
def __init__(self, size=256):
self.size = size
self.table = OrderedDict()
def get(self, key):
"""Retrieve a value from the transposition table and mark it as recently used."""
if key in self.table:
self.table.move_to_end(key)
return self.table[key]
return None
def put(self, key, value):
"""Add a key-value pair to the transposition table, evicting the oldest entry if necessary."""
if key in self.table:
self.table.move_to_end(key)
self.table[key] = value
if len(self.table) > self.size:
self.table.popitem(last=False)
class BoardState:
def __init__(self, state, width, height, win_length=4):
"""
Initialize the board state.
Args:
state (str): A string representing the sequence of moves.
width (int): Number of columns.
height (int): Number of rows.
win_length (int): Number of connected pieces needed to win.
"""
self.state = list(map(int, state)) # Convert state to a list of integers
self.width = width
self.height = height
self.win_length = win_length
self.column_heights = [0] * self.width # Tracks the number of pieces in each column
for move in self.state:
self.column_heights[move - 1] += 1
self.min_score = -((self.width * self.height) // 2) + 3
self.max_score = ((self.width * self.height + 1) // 2) - 3
self.board = self.translate_to_board() # Initialize the board
def translate_to_board(self):
"""Convert the move list into a 2D board representation."""
board = [[0 for _ in range(self.width)] for _ in range(self.height)]
for n, move in enumerate(self.state):
for y in range(self.height - 1, -1, -1):
if board[y][move - 1] == 0:
board[y][move - 1] = 1 if n % 2 == 0 else 2
break
return board
def col_full(self, column):
"""Check if a specific column is full."""
return self.column_heights[column] >= self.height
def board_full(self):
"""Check if the board is completely full."""
return len(self.state) >= self.width * self.height
def move_number(self):
"""Return the total number of moves made."""
return len(self.state)
def apply_move(self, column):
"""Apply a move to the board."""
player = 1 if len(self.state) % 2 == 0 else 2
self.state.append(column + 1)
self.board[self.height - 1 - self.column_heights[column]][column] = player
self.column_heights[column] += 1
def undo_move(self, column):
"""Undo the last move from a specific column."""
self.column_heights[column] -= 1
self.state.pop()
self.board[self.height - self.column_heights[column] - 1][column] = 0
def is_winning_move(self, column):
"""
Check if the last move in the specified column results in a win.
Args:
column (int): The column where the last move was made.
Returns:
bool: True if the move is a winning move, False otherwise.
"""
row = self.height - self.column_heights[column]
player = self.board[row][column]
directions = [(1, 0), (0, 1), (1, 1), (1, -1)] # Horizontal, Vertical, Diagonal /
for dx, dy in directions:
count = 1
for direction in [1, -1]:
x, y = column, row
while True:
x += dx * direction
y += dy * direction
if 0 <= x < self.width and 0 <= y < self.height and self.board[y][x] == player:
count += 1
else:
break
if count >= self.win_length:
return True
return False
def render(self):
"""Render the current board state to the console."""
piece_symbols = {0: " ", 1: "🔴", 2: "🟡"}
for row in self.board:
print("|".join(piece_symbols[p] for p in row))
print(("--+" * self.width)[:-1])
class NegMaxSolver:
def __init__(self, width):
"""Initialize the negamax solver with a specific move ordering."""
self.move_order = self.init_move_order(width)
def init_move_order(self, width):
"""
Initialize move order prioritizing the center columns for better pruning.
Args:
width (int): Number of columns.
Returns:
list: Ordered list of column indices.
"""
order = [width // 2]
for i in range(1, width // 2 + 1):
left = (width // 2) - i
right = (width // 2) + i
if left >= 0:
order.append(left)
if right < width:
order.append(right)
return order
def negamax(self, board: BoardState, alpha, beta, trans_table: TranspositionTable):
"""
Perform the negamax search with alpha-beta pruning and transposition table.
Args:
board (BoardState): Current state of the board.
alpha (int): Alpha value for pruning.
beta (int): Beta value for pruning.
trans_table (TranspositionTable): Transposition table for memoization.
Returns:
int: Evaluation score.
"""
key = self.hash_board(board)
cached = trans_table.get(key)
if cached is not None:
return cached
if board.board_full():
return 0 # Draw
for column in self.move_order:
if not board.col_full(column):
board.apply_move(column)
if board.is_winning_move(column):
board.undo_move(column)
return ((board.width * board.height + 1) - board.move_number()) // 2
board.undo_move(column)
max_score = ((board.width * board.height - 1) - board.move_number()) // 2
if beta > max_score:
beta = max_score
if alpha >= beta:
return beta
for column in self.move_order:
if not board.col_full(column):
board.apply_move(column)
score = -self.negamax(board, -beta, -alpha, trans_table)
board.undo_move(column)
if score >= beta:
return score
if score > alpha:
alpha = score
trans_table.put(key, alpha)
return alpha
def hash_board(self, board: BoardState):
"""
Create a hashable key for the current board state.
Args:
board (BoardState): Current state of the board.
Returns:
tuple: Hashable representation of the board state.
"""
return tuple(board.state)
def solve(self, board: BoardState, weak=False, table_size=256):
"""
Solve the game from the current board state.
Args:
board (BoardState): Current state of the board.
weak (bool): Whether to use a weak evaluation (for faster, less accurate results).
table_size (int): Size of the transposition table.
Returns:
int: Final evaluation score.
"""
trans_table = TranspositionTable(table_size)
min_score = -((board.width * board.height) - board.move_number()) // 2
max_score = ((board.width * board.height + 1) - board.move_number()) // 2
if weak:
min_score = -1
max_score = 1
while min_score < max_score:
med = min_score + (max_score - min_score) // 2
# Adjust med to ensure proper search bounds
if med <= 0 and min_score // 2 < med:
med = min_score // 2
elif med >= 0 and max_score // 2 > med:
med = max_score // 2
score = self.negamax(board, med, med + 1, trans_table)
if score <= med:
max_score = score
else:
min_score = score
return min_score
# Initialize move order for a 7-column board
solver = NegMaxSolver(width=7)
# Example usage:
# Initialize the board with a given state. Each digit represents a column (1-indexed).
# For example, "3642756176227637211322113551637574556" represents a specific game state.
initial_state = "3642756176227637211322113551637574556"
board = BoardState(initial_state, width=7, height=6)
# board.render() # Optional: visualize the board
# Solve the game from the initial state
result = solver.solve(board, weak=False)
print(result)
Key Optimizations Explained
Transposition Table (TranspositionTable Class):
OrderedDict: Utilizes OrderedDict to maintain the insertion order, enabling efficient implementation of an LRU (Least Recently Used) cache. This ensures that the most recently accessed items remain in the cache, and the oldest ones are evicted when the cache exceeds its size.
Integer Keys: By using tuples of moves as keys (tuple(board.state)), hashing becomes faster and more efficient compared to string-based keys.
Board Representation (BoardState Class):
List of Integers: The game state is stored as a list of integers instead of a string. This change drastically improves the performance of operations like appending moves and counting occurrences.
Incremental Board Maintenance: The board is maintained as a 2D list that's updated incrementally with each move. This avoids the need to reconstruct the entire board from scratch for every operation, saving computational resources.
Column Heights Tracking: By maintaining a separate column_heights list, checking if a column is full becomes an O(1) operation, eliminating the need for self.State.count() which is O(n).
Win Condition Checking (is_winning_move Method):
Directional Search: Instead of checking all possible win conditions globally, the method only examines lines passing through the last move. This localized search reduces the number of checks needed.
Early Exit: As soon as a winning condition is met, the method returns True, allowing the solver to prune unnecessary branches early.
Negamax Solver (NegMaxSolver Class):
Move Ordering: The move order is initialized to prioritize center columns, which are generally more advantageous in Connect Four. This heuristic enhances alpha-beta pruning efficiency.
In-Place Move Application: Moves are applied and undone in place without creating new BoardState instances. This reduces memory overhead and speeds up recursive calls.
Binary Search for Solving: The solve method uses a form of binary search to iteratively narrow down the score range, which can lead to faster convergence compared to traditional iterative deepening.
Additional Recommendations
Bitboard Representation: For even higher performance, especially in languages like C or C++, representing the board using bitboards can lead to significant speedups. However, implementing bitboards in Python can be more complex and may not yield proportional performance gains due to Python's inherent overhead.
Parallel Processing: Utilizing Python's multiprocessing or asyncio libraries can help perform parallel searches, especially useful for larger boards or deeper searches. However, this introduces complexity in managing shared state and synchronization.
Profile-Guided Optimizations: Use profiling tools like cProfile or line_profiler to identify and optimize remaining bottlenecks specific to your use case.
C Extensions or Just-In-Time Compilation: For performance-critical sections that remain slow, consider implementing them as C extensions or using libraries like Numba to compile Python code to machine code at runtime.
By implementing these optimizations, the solver should exhibit improved performance, making it more efficient and capable of handling more complex game states effectively.
Avoiding Redundant Computations: By caching results in the transposition table, the solver avoids recalculating the outcomes of previously encountered board states.
Efficient Data Access: Replacing string operations with list accesses and maintaining precomputed data structures like column_heights significantly improve access times.