Skip to content

Commit

Permalink
reformatted with black
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderdittrich committed Feb 29, 2024
1 parent b055bd1 commit 63aeeeb
Show file tree
Hide file tree
Showing 14 changed files with 685 additions and 412 deletions.
29 changes: 20 additions & 9 deletions exercise.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,16 @@
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"# Reversed Ackley function\n",
"def ackley(x, y):\n",
" return -1*(-20.0 * np.exp(-0.2 * np.sqrt(0.5 * (x**2 + y**2))) - np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y))) + np.e + 20)\n",
" return -1 * (\n",
" -20.0 * np.exp(-0.2 * np.sqrt(0.5 * (x**2 + y**2)))\n",
" - np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y)))\n",
" + np.e\n",
" + 20\n",
" )\n",
"\n",
"\n",
"# define range for input\n",
"r_min, r_max = -5.0, 5.0\n",
Expand All @@ -144,8 +151,8 @@
"results = ackley(x, y)\n",
"# create a surface plot with the jet color scheme\n",
"fig = plt.figure()\n",
"ax = fig.add_subplot(projection='3d')\n",
"surf = ax.plot_surface(x, y, results, cmap='jet')\n",
"ax = fig.add_subplot(projection=\"3d\")\n",
"surf = ax.plot_surface(x, y, results, cmap=\"jet\")\n",
"ax.set_xlabel(\"param x\")\n",
"ax.set_ylabel(\"param y\")\n",
"ax.set_zlabel(\"Ackley\")\n",
Expand Down Expand Up @@ -216,11 +223,12 @@
"env.reset()\n",
"\n",
"# Create a widget for displaying the environment\n",
"image_widget = widgets.Image(format='jpeg')\n",
"image_widget = widgets.Image(format=\"jpeg\")\n",
"\n",
"# Display the widget\n",
"display(image_widget)\n",
"\n",
"\n",
"def update_image(env):\n",
" img = env.render()\n",
" img = Image.fromarray(img)\n",
Expand All @@ -229,14 +237,15 @@
" image_data = output.getvalue()\n",
" image_widget.value = image_data\n",
"\n",
"\n",
"# Run and update environment\n",
"for _ in range(1000):\n",
" action = env.action_space.sample() # Replace with your action policy\n",
" observation, reward, terminated, truncated, info = env.step(action)\n",
" \n",
"\n",
" if terminated or truncated:\n",
" observation, info = env.reset()\n",
" \n",
"\n",
" update_image(env)\n",
" clear_output(wait=True)\n",
"\n",
Expand Down Expand Up @@ -299,11 +308,12 @@
"env.reset()\n",
"\n",
"# Create a widget for displaying the environment\n",
"image_widget = widgets.Image(format='jpeg')\n",
"image_widget = widgets.Image(format=\"jpeg\")\n",
"\n",
"# Display the widget\n",
"display(image_widget)\n",
"\n",
"\n",
"def update_image(env):\n",
" img = env.render()\n",
" img = Image.fromarray(img)\n",
Expand All @@ -312,14 +322,15 @@
" image_data = output.getvalue()\n",
" image_widget.value = image_data\n",
"\n",
"\n",
"# Run and update environment\n",
"for _ in range(400):\n",
" action = env.action_space.sample() # Replace with your action policy\n",
" observation, reward, terminated, truncated, info = env.step(action)\n",
" \n",
"\n",
" if terminated or truncated:\n",
" observation, info = env.reset()\n",
" \n",
"\n",
" update_image(env)\n",
" clear_output(wait=True)\n",
"\n",
Expand Down
26 changes: 14 additions & 12 deletions exercise_1_ga/assets/utility.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
import numpy as np


def highlight_mutations(original, mutated):
if original.shape != mutated.shape:
raise ValueError("Original and mutated populations must have the same shape")

# ANSI escape code for red text and reset
RED = '\033[91m'
RESET = '\033[0m'
RED = "\033[91m"
RESET = "\033[0m"

for i in range(original.shape[0]):
highlighted_row = ''
highlighted_row = ""
for j in range(original.shape[1]):
if original[i, j] != mutated[i, j]:
highlighted_row += f'{RED}{mutated[i, j]}{RESET} '
highlighted_row += f"{RED}{mutated[i, j]}{RESET} "
else:
highlighted_row += f'{mutated[i, j]} '
highlighted_row += f"{mutated[i, j]} "

if i == 0:
print(f"[[{highlighted_row[:-1]}]")
continue
if i == original.shape[0]-1:

if i == original.shape[0] - 1:
print(f" [{highlighted_row[:-1]}]]")
continue

print(f" [{highlighted_row[:-1]}]")



def search_index_in_columns(population, winner):
index = None
for i in range(population.shape[0]):
Expand All @@ -36,5 +38,5 @@ def search_index_in_columns(population, winner):
# Print the result
if index is None:
print("Winner not found in population!")
return index

return index
44 changes: 24 additions & 20 deletions exercise_1_ga/genetic_algorithm.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"import numpy as np\n",
"\n",
"%run assets/utility.py\n",
"np.set_printoptions(precision=4, suppress=True) # for better printing"
"np.set_printoptions(precision=4, suppress=True) # for better printing"
]
},
{
Expand Down Expand Up @@ -129,12 +129,12 @@
"# Solution 1:\n",
"def generate_initial_population(population_size, chromosome_length):\n",
" population = np.zeros((population_size, chromosome_length))\n",
" \n",
"\n",
" chromosome = np.random.randint(0, 2, size=(chromosome_length,))\n",
" for i in range(population_size):\n",
" np.random.shuffle(chromosome) # shuffles in-place\n",
" population[i,:] = chromosome\n",
" \n",
" np.random.shuffle(chromosome) # shuffles in-place\n",
" population[i, :] = chromosome\n",
"\n",
" return population"
]
},
Expand All @@ -158,7 +158,9 @@
"def generate_initial_population(population_size, chromosome_length):\n",
" binary_values = [0, 1]\n",
" probabilities = [0.5, 0.5]\n",
" population = np.random.choice(binary_values, size=(population_size, chromosome_length), p=probabilities)\n",
" population = np.random.choice(\n",
" binary_values, size=(population_size, chromosome_length), p=probabilities\n",
" )\n",
"\n",
" return population"
]
Expand Down Expand Up @@ -321,14 +323,14 @@
"def tournament_selection(population, fitnesses, tournament_size):\n",
" # Choose tournament participants\n",
" indices = np.random.choice(population.shape[0], tournament_size, replace=False)\n",
" \n",
"\n",
" # Evaluate winner\n",
" contenders_fitness = fitnesses[indices]\n",
" max_contenders_fitness_index = np.argmax(contenders_fitness)\n",
" winner_index = indices[max_contenders_fitness_index]\n",
" \n",
" winner = population[winner_index,:]\n",
" \n",
"\n",
" winner = population[winner_index, :]\n",
"\n",
" return winner.reshape(1, -1)"
]
},
Expand Down Expand Up @@ -374,7 +376,7 @@
"\n",
"population = np.random.randint(0, 2, size=(population_size, chromosome_length))\n",
"fitness = np.random.uniform(size=(population_size,))\n",
"tournament_size = 8 # we can only test for the full population, otherwise you need to add prints in your function.\n",
"tournament_size = 8 # we can only test for the full population, otherwise you need to add prints in your function.\n",
"\n",
"winner = tournament_selection(population, fitness, tournament_size)\n",
"\n",
Expand Down Expand Up @@ -465,15 +467,15 @@
"def stochastic_one_point_crossover(parent_1, parent_2, crossover_probability):\n",
" if np.random.rand() < crossover_probability:\n",
" idx = np.random.randint(1, parent_1.shape[1])\n",
" \n",
"\n",
" child_1 = np.concatenate((parent_1[0, :idx], parent_2[0, idx:]))\n",
" child_2 = np.concatenate((parent_2[0, :idx], parent_1[0, idx:]))\n",
" \n",
"\n",
" return child_1, child_2\n",
" else:\n",
" child_1 = parent_1\n",
" child_2 = parent_2\n",
" \n",
"\n",
" return child_1, child_2"
]
},
Expand All @@ -497,15 +499,15 @@
"def stochastic_one_point_crossover(parent_1, parent_2, crossover_probability):\n",
" if np.random.rand() >= crossover_probability:\n",
" return parent_1, parent_2\n",
" \n",
"\n",
" idx = np.random.randint(low=1, high=parent_1.shape[1])\n",
" \n",
"\n",
" child_1 = np.concatenate((parent_1[0, :idx], parent_2[0, idx:]))\n",
" child_2 = np.concatenate((parent_2[0, :idx], parent_1[0, idx:]))\n",
" \n",
"\n",
" child_1 = child_1.reshape(1, -1)\n",
" child_2 = child_2.reshape(1, -1)\n",
" \n",
"\n",
" return child_1, child_2"
]
},
Expand Down Expand Up @@ -551,7 +553,9 @@
"parent_1 = np.random.randint(0, 2, size=(1, chromosome_length))\n",
"parent_2 = np.random.randint(0, 2, size=(1, chromosome_length))\n",
"\n",
"child_1, child_2 = stochastic_one_point_crossover(parent_1, parent_2, crossover_probability)\n",
"child_1, child_2 = stochastic_one_point_crossover(\n",
" parent_1, parent_2, crossover_probability\n",
")\n",
"\n",
"print(f\"Parent 1: {parent_1}\\nParent 2: {parent_2}\\n\")\n",
"print(f\"Child 1: {child_1}\\nChild 2: {child_2}\\n\")\n",
Expand Down Expand Up @@ -648,7 +652,7 @@
"def mutate_genotypes(population, mutation_probability):\n",
" # Create a boolean mask where True indicates potential mutation sites\n",
" mutation_mask = np.random.rand(*population.shape) < mutation_probability\n",
" \n",
"\n",
" # Flip the bits where the mask is True\n",
" mutated_population = population ^ mutation_mask\n",
"\n",
Expand Down
Loading

0 comments on commit 63aeeeb

Please sign in to comment.