import random
import math
import matplotlib.pyplot as plt
import numpy as np
# Define the keyboard grid (for simplicity, a 3-row keyboard like QWERTY)
# Let's assume a grid with 10 keys per row
KEY_ROWS = [
['q','w','e','r','t','y','u','i','o','p'],
['a','s','d','f','g','h','j','k','l',';'],
['z','x','c','v','b','n','m',',','.','/']
]
ALL_KEYS = [key for row in KEY_ROWS for key in row if key.isalpha()]
# Parameters
POPULATION_SIZE = 100
GENERATIONS = 1000
MUTATION_RATE = 0.1
TOURNAMENT_SIZE = 5
ELITISM_COUNT = 2
TEXT = "the quick brown fox jumps over the lazy dog"
# Preprocess the text
text = TEXT.lower()
# Filter to only include keys present in the keyboard
filtered_text = [c for c in text if c in ALL_KEYS]
# Define the keyboard layout class
class KeyboardLayout:
def __init__(self, arrangement):
self.arrangement = arrangement # List of characters representing the layout
self.fitness = None
def calculate_fitness(self, text_sequence):
# Create a mapping from character to position
key_map = {}
for index, key in enumerate(self.arrangement):
row = index // 10
col = index % 10
key_map[key] = (row, col)
total_distance = 0
for i in range(len(text_sequence) - 1):
key1 = text_sequence[i]
key2 = text_sequence[i+1]
pos1 = key_map[key1]
pos2 = key_map[key2]
distance = math.sqrt((pos1[0]-pos2[0])**2 + (pos1[1]-pos2[1])**2)
total_distance += distance
self.fitness = total_distance
return self.fitness
def generate_initial_population():
population = []
for _ in range(POPULATION_SIZE):
arrangement = ALL_KEYS.copy()
random.shuffle(arrangement)
population.append(KeyboardLayout(arrangement))
return population
def tournament_selection(population):
tournament = random.sample(population, TOURNAMENT_SIZE)
tournament = sorted(tournament, key=lambda x: x.fitness)
return tournament[0]
def crossover(parent1, parent2):
# Order Crossover (OX)
size = len(parent1.arrangement)
child_p1 = [None]*size
child_p2 = []
start, end = sorted(random.sample(range(size), 2))
# Copy a slice from parent1 to child
child_p1[start:end] = parent1.arrangement[start:end]
# Fill the rest from parent2
child_p2 = [item for item in parent2.arrangement if item not in child_p1]
child = child_p1[:start] + child_p2[:start] + child_p1[start:end] + child_p2[start:]
return KeyboardLayout(child)
def mutate(layout):
arrangement = layout.arrangement.copy()
if random.random() < MUTATION_RATE:
idx1, idx2 = random.sample(range(len(arrangement)), 2)
arrangement[idx1], arrangement[idx2] = arrangement[idx2], arrangement[idx1]
return KeyboardLayout(arrangement)
def genetic_algorithm():
population = generate_initial_population()
# Calculate fitness
for layout in population:
layout.calculate_fitness(filtered_text)
population = sorted(population, key=lambda x: x.fitness)
best_fitness = population[0].fitness
best_layout = population[0]
for generation in range(GENERATIONS):
new_population = []
# Elitism
new_population.extend(population[:ELITISM_COUNT])
# Create the rest of the population
while len(new_population) < POPULATION_SIZE:
parent1 = tournament_selection(population)
parent2 = tournament_selection(population)
child = crossover(parent1, parent2)
child = mutate(child)
child.calculate_fitness(filtered_text)
new_population.append(child)
population = sorted(new_population, key=lambda x: x.fitness)
if population[0].fitness < best_fitness:
best_fitness = population[0].fitness
best_layout = population[0]
print(f"Generation {generation}: Best Fitness = {best_fitness}")
return best_layout
def visualize_keyboard(layout):
# Create grid based on KEY_ROWS structure
grid = []
for row in KEY_ROWS:
grid_row = []
for key in row:
if key in layout.arrangement:
grid_row.append(layout.arrangement[layout.arrangement.index(key)])
else:
grid_row.append(key)
grid.append(grid_row)
fig, ax = plt.subplots()
ax.axis('off')
table = ax.table(cellText=grid, loc='center', cellLoc='center')
table.scale(1, 2)
plt.title('Optimized Keyboard Layout')
plt.show()
def main():
best_layout = genetic_algorithm()
print("Optimized Keyboard Layout:")
for row in range(3):
row_keys = best_layout.arrangement[row*10:(row+1)*10]
print(' '.join(row_keys))
visualize_keyboard(best_layout)
if __name__ == "__main__":
main()