Define the standard QWERTY layout with coordinates, including space
STANDARD_QWERTY = [
['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'],
[' '] # Space bar in a separate row
]
Create a list of positions based on the standard layout
def get_position_list(layout):
positions = []
for row_idx, row in enumerate(layout):
for col_idx, key in enumerate(row):
positions.append((col_idx, row_idx))
return positions
POPULATION_SIZE = 200 # Increased population size for better diversity
GENERATIONS = 1000
MUTATION_RATE = 0.2 # Increased mutation rate for more exploration
TOURNAMENT_SIZE = 5
ELITISM_COUNT = 5 # Number of top individuals to carry over to the next generation
Function to calculate Euclidean distance between two positions
def fitness(layout, text, position_coords):
total_distance = 0
# Map each key to its position based on the layout
key_to_pos = {key: position_coords[idx] for idx, key in enumerate(layout)}
code
for i in range(len(text) - 1):
key1 = text[i]
key2 = text[i + 1]
if key1 in key_to_pos and key2 in key_to_pos:
pos1 = key_to_pos[key1]
pos2 = key_to_pos[key2]
total_distance += distance(pos1, pos2)
else:
# Assign a large penalty if key not in layout
total_distance += 100
return total_distance
Initialize population with random layouts
def initialize_population(characters, population_size):
population = []
for _ in range(population_size):
individual = characters[:]
random.shuffle(individual)
population.append(individual)
return population
Selection: Tournament Selection with Elitism
def selection(population, fitnesses, tournament_size, elitism_count):
# Sort population based on fitness
sorted_population = [x for _, x in sorted(zip(fitnesses, population), key=lambda pair: pair[0])]
# Elitism: carry the top individuals to the next generation
elites = sorted_population[:elitism_count]
selected = elites.copy()
# Tournament selection for the rest
while len(selected) < len(population):
tournament = random.sample(list(zip(population, fitnesses)), tournament_size)
tournament = sorted(tournament, key=lambda x: x[1])
winner = copy.deepcopy(tournament[0][0])
selected.append(winner)
return selected
Assistant
Crossover: Partially Mapped Crossover (PMX) for better genetic diversity
# Choose crossover points
pt1, pt2 = sorted(random.sample(range(size), 2))
# Create offspring by copying the slice from parents
child1[pt1:pt2] = parent1[pt1:pt2]
child2[pt1:pt2] = parent2[pt1:pt2]
def fill_child(child, parent_other):
for gene in parent_other[pt1:pt2]:
if gene not in child:
pos = parent_other.index(gene)
while child[pos] is not None:
pos = parent_other.index(child[pos])
child[pos] = gene
# Fill remaining positions with genes from parent_other
for gene in parent_other:
if gene not in child:
for i in range(size):
if child[i] is None:
child[i] = gene
break
return child
child1 = fill_child(child1, parent2)
child2 = fill_child(child2, parent1)
return child1, child2
Mutation: Swap two keys
def mutate(individual, mutation_rate):
for i in range(len(individual)):
if random.random() < mutation_rate:
j = random.randint(0, len(individual) - 1)
individual[i], individual[j] = individual[j], individual[i]
return individual
Genetic Algorithm
def genetic_algorithm(text, position_coords, population_size, generations, mutation_rate, tournament_size, elitism_count):
# Sanitize and prepare the characters to include in the keyboard
text = text.lower()
valid_chars = set('abcdefghijklmnopqrstuvwxyz ')
sanitized_text = ''.join([c for c in text if c in valid_chars])
characters = list(set(sanitized_text))
if ' ' in sanitized_text and ' ' not in characters:
characters.append(' ')
# Ensure we have exactly the required number of keys, pad if necessary
required_keys = len(position_coords) # 27 positions (a-z and space)
if len(characters) < required_keys:
# Add random characters to fill
while len(characters) < required_keys:
char = random.choice('abcdefghijklmnopqrstuvwxyz ')
if char not in characters:
characters.append(char)
elif len(characters) > required_keys:
# Truncate to required keys
characters = characters[:required_keys]
code
# Initialize population
population = initialize_population(characters, population_size)
best_layout = None
best_fitness = float('inf')
for gen in range(1, generations + 1):
# Evaluate fitness
fitnesses = [fitness(ind, sanitized_text, position_coords) for ind in population]
# Find the best in current population
min_fitness = min(fitnesses)
if min_fitness < best_fitness:
best_fitness = min_fitness
best_layout = population[fitnesses.index(min_fitness)]
print(f"Generation {gen}: Best Fitness = {best_fitness}")
# Early stopping if perfect fitness is achieved
if best_fitness == 0:
print("Perfect layout found!")
break
# Selection with Elitism
selected = selection(population, fitnesses, tournament_size, elitism_count)
# Crossover to produce offspring
offspring = []
for i in range(0, population_size - elitism_count, 2):
parent1 = selected[i]
parent2 = selected[i + 1] if i + 1 < population_size - elitism_count else selected[0]
child1, child2 = crossover(parent1, parent2)
offspring.extend([child1, child2])
# Add elites to the offspring
offspring.extend(selected[:elitism_count])
# Mutation
population = [mutate(child, mutation_rate) for child in offspring]
return best_layout, best_fitness
Example usage
if name == "main":
# Example text
text = "hello world this is an example text to optimize the keyboard layout using genetic algorithm and the quick brown fox jumps over the lazy dog"
code
# Get position coordinates based on the standard layout
position_coords = POSITION_COORDS
# Run genetic algorithm
best_layout, best_fitness = genetic_algorithm(
text=text,
position_coords=position_coords,
population_size=200, # Increased population size for better diversity
generations=1000,
mutation_rate=0.2, # Increased mutation rate for more exploration
tournament_size=5,
elitism_count=5
)
# Define row lengths for visualization, including the space bar
row_lengths = [10, 9, 7, 1] # Adjusted to include the space
print("\nBest Keyboard Layout:")
# Arrange the best layout back to QWERTY rows
output_layout = []
idx = 0
for length in row_lengths:
row = best_layout[idx:idx + length]
output_layout.append(row)
idx += length
for row in output_layout:
print(' '.join(row))
print(f"\nBest Fitness (Total Distance): {best_fitness}") // Explain what this code does.
Sure! Let's walk through the provided Python script step by step to understand how it works. This script implements a Genetic Algorithm (GA) to optimize a keyboard layout based on a given input text, aiming to minimize the total typing distance between consecutive characters.
Overview
The main goal of this script is to find a keyboard layout that reduces the physical distance between characters that frequently appear next to each other in the provided text. By optimizing the layout, typing can become more efficient and ergonomic.
Detailed Breakdown
1. Importing Necessary Libraries
python
import random
import math
import copy
random: For generating random numbers, shuffling layouts, and selecting individuals.
math: To perform mathematical operations, specifically calculating Euclidean distances.
copy: To create deep copies of individuals (keyboard layouts) during selection.
2. Defining the Standard QWERTY Layout
python
STANDARD_QWERTY = [
['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'],
[' '] # Space bar in a separate row
]
This represents the conventional QWERTY keyboard layout, organized into rows.
The space bar is included as a separate row for accurate positioning.
3. Creating Position Coordinates
python
def get_position_list(layout):
positions = []
for row_idx, row in enumerate(layout):
for col_idx, key in enumerate(row):
positions.append((col_idx, row_idx))
return positions
POSITION_COORDS = get_position_list(STANDARD_QWERTY)
get_position_list: Converts the keyboard layout into a list of (x, y) coordinates for each key.
x: Column index (horizontal position).
y: Row index (vertical position).
POSITION_COORDS: Stores the coordinates of each key in the standard layout, which serves as a reference for initial positioning.
4. Genetic Algorithm Parameters
python
POPULATION_SIZE = 200 # Increased population size for better diversity
GENERATIONS = 1000
MUTATION_RATE = 0.2 # Increased mutation rate for more exploration
TOURNAMENT_SIZE = 5
ELITISM_COUNT = 5 # Number of top individuals to carry over to the next generation
POPULATION_SIZE: Number of individual layouts in each generation. A larger population promotes diversity.
GENERATIONS: Number of iterations the algorithm will run.
MUTATION_RATE: Probability of a mutation occurring in an individual, encouraging exploration of new layouts.
TOURNAMENT_SIZE: Number of individuals competing in each tournament selection.
ELITISM_COUNT: Number of top-performing individuals automatically carried over to the next generation, preserving good solutions.
distance: Computes the Euclidean distance between two keys based on their coordinates.
This metric quantifies how physically far apart two keys are on the keyboard.
6. Fitness Function
python
def fitness(layout, text, position_coords):
total_distance = 0
# Map each key to its position based on the layout
key_to_pos = {key: position_coords[idx] for idx, key in enumerate(layout)}
for i in range(len(text) - 1):
key1 = text[i]
key2 = text[i + 1]
if key1 in key_to_pos and key2 in key_to_pos:
pos1 = key_to_pos[key1]
pos2 = key_to_pos[key2]
total_distance += distance(pos1, pos2)
else:
# Assign a large penalty if key not in layout
total_distance += 100
return total_distance
fitness: Evaluates how "good" a particular keyboard layout is based on the input text.
Mapping: Creates a dictionary mapping each key to its (x, y) position in the current layout.
Calculation:
Iterates through each pair of consecutive characters in the text.
Adds the Euclidean distance between the two characters' positions to total_distance.
If a character isn't present in the layout, a large penalty (100) is added to discourage incomplete layouts.
Objective: Minimize the total_distance. Lower values indicate a more efficient layout for the given text.
7. Initializing the Population
python
def initialize_population(characters, population_size):
population = []
for _ in range(population_size):
individual = characters[:]
random.shuffle(individual)
population.append(individual)
return population
initialize_population: Creates the initial set of random keyboard layouts.
characters: List of unique characters from the input text that need to be placed on the keyboard.
Each individual in the population is a shuffled version of the characters list, representing a unique keyboard layout.
8. Selection Process with Tournament Selection and Elitism
python
def selection(population, fitnesses, tournament_size, elitism_count):
# Sort population based on fitness
sorted_population = [x for _, x in sorted(zip(fitnesses, population), key=lambda pair: pair[0])]
# Elitism: carry the top individuals to the next generation
elites = sorted_population[:elitism_count]
selected = elites.copy()
# Tournament selection for the rest
while len(selected) < len(population):
tournament = random.sample(list(zip(population, fitnesses)), tournament_size)
tournament = sorted(tournament, key=lambda x: x[1])
winner = copy.deepcopy(tournament[0][0])
selected.append(winner)
return selected
selection: Chooses which individuals will be passed on to the next generation.
Elitism: Automatically retains the top elitism_count individuals with the best fitness scores.
Tournament Selection:
Randomly selects tournament_size individuals.
The individual with the best fitness in the tournament wins and is selected.
This process continues until the desired population size is reached.
Purpose: Balances preserving good solutions (elitism) with exploring new ones (tournament selection).
def crossover(parent1, parent2):
size = len(parent1)
child1, child2 = [None]*size, [None]*size
# Choose crossover points
pt1, pt2 = sorted(random.sample(range(size), 2))
# Create offspring by copying the slice from parents
child1[pt1:pt2] = parent1[pt1:pt2]
child2[pt1:pt2] = parent2[pt1:pt2]
def fill_child(child, parent_other):
for gene in parent_other[pt1:pt2]:
if gene not in child:
pos = parent_other.index(gene)
while child[pos] is not None:
pos = parent_other.index(child[pos])
child[pos] = gene
# Fill remaining positions with genes from parent_other
for gene in parent_other:
if gene not in child:
for i in range(size):
if child[i] is None:
child[i] = gene
break
return child
child1 = fill_child(child1, parent2)
child2 = fill_child(child2, parent1)
return child1, child2
crossover: Combines two parent layouts to produce two child layouts.
Partially Mapped Crossover (PMX) ensures that each key appears exactly once in the child, maintaining a valid permutation.
Process:
Crossover Points: Two random points (pt1 and pt2) are selected to define a segment.
Copy Segment: The segment between pt1 and pt2 from each parent is copied directly to the corresponding child.
Fill Remaining Genes:
For each gene outside the copied segment, ensure it's placed in the child without duplication.
Handles conflicts by mapping positions based on the swapped genes.
Outcome: Two new layouts (children) that inherit traits from both parents while maintaining valid key arrangements.
10. Mutation: Swapping Two Keys
python
def mutate(individual, mutation_rate):
for i in range(len(individual)):
if random.random() < mutation_rate:
j = random.randint(0, len(individual) - 1)
individual[i], individual[j] = individual[j], individual[i]
return individual
mutate: Introduces variations to prevent the algorithm from getting stuck in local optima.
Mechanism: For each key in the layout, there's a mutation_rate chance to swap it with another randomly chosen key.
Purpose: Ensures exploration of the solution space by slightly altering layouts.
11. Main Genetic Algorithm Function
python
def genetic_algorithm(text, position_coords, population_size, generations, mutation_rate, tournament_size, elitism_count):
# Sanitize and prepare the characters to include in the keyboard
text = text.lower()
valid_chars = set('abcdefghijklmnopqrstuvwxyz ')
sanitized_text = ''.join([c for c in text if c in valid_chars])
characters = list(set(sanitized_text))
if ' ' in sanitized_text and ' ' not in characters:
characters.append(' ')
# Ensure we have exactly the required number of keys, pad if necessary
required_keys = len(position_coords) # 27 positions (a-z and space)
if len(characters) < required_keys:
# Add random characters to fill
while len(characters) < required_keys:
char = random.choice('abcdefghijklmnopqrstuvwxyz ')
if char not in characters:
characters.append(char)
elif len(characters) > required_keys:
# Truncate to required keys
characters = characters[:required_keys]
# Initialize population
population = initialize_population(characters, population_size)
best_layout = None
best_fitness = float('inf')
for gen in range(1, generations + 1):
# Evaluate fitness
fitnesses = [fitness(ind, sanitized_text, position_coords) for ind in population]
# Find the best in current population
min_fitness = min(fitnesses)
if min_fitness < best_fitness:
best_fitness = min_fitness
best_layout = population[fitnesses.index(min_fitness)]
print(f"Generation {gen}: Best Fitness = {best_fitness}")
# Early stopping if perfect fitness is achieved
if best_fitness == 0:
print("Perfect layout found!")
break
# Selection with Elitism
selected = selection(population, fitnesses, tournament_size, elitism_count)
# Crossover to produce offspring
offspring = []
for i in range(0, population_size - elitism_count, 2):
parent1 = selected[i]
parent2 = selected[i + 1] if i + 1 < population_size - elitism_count else selected[0]
child1, child2 = crossover(parent1, parent2)
offspring.extend([child1, child2])
# Add elites to the offspring
offspring.extend(selected[:elitism_count])
# Mutation
population = [mutate(child, mutation_rate) for child in offspring]
return best_layout, best_fitness
Step-by-Step Explanation:
Text Preparation:
Converts the input text to lowercase.
Removes any characters not in the set 'a' to 'z' and space.
Extracts unique characters from the sanitized text.
Ensures the space character is included if present.
Adjusts the list of characters to match the number of required keys (27: 26 letters + space). It either pads with random characters or truncates the list as needed.
Population Initialization:
Generates an initial population of random keyboard layouts based on the prepared characters.
GA Loop (Generations):
Fitness Evaluation: Calculates the fitness of each individual in the population based on the input text.
Tracking Best Layout: Keeps track of the layout with the lowest fitness score found so far.
Early Stopping: If a layout achieves a fitness of 0 (i.e., optimal), the algorithm stops early.
Selection: Chooses individuals for the next generation using tournament selection and elitism.
Crossover: Produces offspring layouts by combining selected parents using PMX.
Elitism: Ensures the top-performing individuals are retained without changes.
Mutation: Applies random swaps to the offspring to maintain diversity.
Next Generation: The new population for the next iteration is formed from the offspring and elites.
Result:
After completing all generations (or stopping early), the function returns the best keyboard layout found and its corresponding fitness score.
12. Executing the Genetic Algorithm
python
if __name__ == "__main__":
# Example text
text = "hello world this is an example text to optimize the keyboard layout using genetic algorithm and the quick brown fox jumps over the lazy dog"
# Get position coordinates based on the standard layout
position_coords = POSITION_COORDS
# Run genetic algorithm
best_layout, best_fitness = genetic_algorithm(
text=text,
position_coords=position_coords,
population_size=200, # Increased population size for better diversity
generations=1000,
mutation_rate=0.2, # Increased mutation rate for more exploration
tournament_size=5,
elitism_count=5
)
# Define row lengths for visualization, including the space bar
row_lengths = [10, 9, 7, 1] # Adjusted to include the space
print("\nBest Keyboard Layout:")
# Arrange the best layout back to QWERTY rows
output_layout = []
idx = 0
for length in row_lengths:
row = best_layout[idx:idx + length]
output_layout.append(row)
idx += length
for row in output_layout:
print(' '.join(row))
print(f"\nBest Fitness (Total Distance): {best_fitness}")
Example Text: A sample sentence containing all letters of the English alphabet (a pangram) to provide a comprehensive dataset for optimization.
Running the GA:
Calls the genetic_algorithm function with the specified parameters.
The algorithm processes the input text over 1000 generations, evolving the population towards optimal layouts.
Displaying Results:
Row Lengths: Defines how many keys are in each row to format the output similar to a standard keyboard.
row_lengths = [10, 9, 7, 1] corresponds to the number of keys per row in STANDARD_QWERTY.
Best Layout:
Arranges the best-performing layout into rows based on row_lengths for easy visualization.
Prints each row of the optimized keyboard layout.
Best Fitness: Outputs the total distance score of the best layout, indicating its efficiency.
Summary
This script leverages the principles of Genetic Algorithms to iteratively improve a keyboard layout tailored to a specific text. By minimizing the total distance between consecutive characters in the text, it seeks to create a layout that enhances typing efficiency. The combination of selection, crossover, mutation, and elitism ensures a balance between exploiting the best solutions and exploring new possibilities, ultimately leading to an optimized keyboard configuration.