finished??

master
Ruben-FreddyLoafers 2025-10-28 15:41:22 +01:00
parent f95f848b22
commit 9a61a7f1d6
2 changed files with 34 additions and 12 deletions

View File

@ -13,7 +13,6 @@ import random
import struct
import time
import utils
# import matplotlib.pyplot as plt
POPULATION_SIZE = 10
SELECTION_SIZE = (POPULATION_SIZE * 7) // 10 # 70% of population, rounded down for selection
@ -28,8 +27,6 @@ bin_pop = [] # 32 Bit-Binary as String
bin_pop_params = [] # Arrays with 4 Binary values of 8s
new_pop = [] # 32 Bit Gray-Code as String
e_func = lambda x: np.e**x
def generate_random_population(num=POPULATION_SIZE):
""" Puts random 32 Bit binary strings into 4 * 8 Bit long params. """
@ -63,12 +60,12 @@ def eval_fitness(bin_pop_values):
# Create polynomial function with current parameters
approx = lambda x: a*x**3 + b*x**2 + c*x + d
quad_error = quadratic_error(e_func, approx, 6)
e_func = lambda x: np.e**x
quad_error = quadratic_error(e_func, approx, 3)
inverse_fitness = 1 / quad_error # the bigger the error, the worse the fitness
print("Fitness: " + str(inverse_fitness)) # debugging
# print("Fitness: " + str(inverse_fitness)) # debugging
fitness_arr.append(inverse_fitness) # save fitness
# save params # already saved in gray_pop
return fitness_arr
@ -96,14 +93,13 @@ def select(fitness_arr):
break # break for loop
return selected_pop
# TODO: xover the old population not the new one
def xover(population):
"""Performs crossover on pairs of individuals from population."""
offspring = []
# Process pairs while we have enough individuals and haven't reached xover_rate
i = 0
while i < len(population) - 1 and len(population) + len(offspring) < 10:
while i < XOVER_PAIR_SIZE:
parent_a = population[i]
parent_b = population[i + 1]
@ -139,8 +135,9 @@ def main():
bin_pop_values = generate_random_population(POPULATION_SIZE)
iteration = 0
while not np.all((1 / np.array(fitness_arr)) <= 1): # Continue while any fitness value is > 1
print("Iteration: " + str(iteration)) # debugging
print("Working...")
while not np.any((np.array(fitness_arr)) > 200): # Continue while any fitness value is > 1
# print("Iteration: " + str(iteration)) # debugging
# Evaluate fitness
fitness_arr = eval_fitness(bin_pop_values)
@ -149,7 +146,7 @@ def main():
new_pop = select(fitness_arr) # assigns
# Crossover
offspring = xover(new_pop)
offspring = xover(gray_pop)
new_pop.extend(offspring) # Add offspring to population
# Mutation
@ -163,10 +160,19 @@ def main():
params = [bin_str[i:i+7] for i in range(0, 31, 8)]
bin_pop_values.append(params)
# print(new_pop)
# time.sleep(0.5)
iteration += 1
max_fitness_index = np.argmax(np.array(fitness_arr))
a, b, c, d = [utils.bin_to_param(param) for param in bin_pop_values[max_fitness_index]]
print("index: " + str(max_fitness_index))
print("a: " + str(a) + "; b: " + str(b) + "; c: " + str(c) + "; d: " + str(d) )
utils.plot_graph(a, b, c, d)
return 0
if __name__ == "__main__":

View File

@ -1,3 +1,6 @@
import matplotlib.pyplot as plt
import numpy as np
def gray_to_bin(gray):
"""
Convert Gray code to binary, operating on the integer value directly.
@ -40,3 +43,16 @@ def bin_to_param(binary, q_min = 0.0, q_max = 10.0):
except ValueError as e:
print(f"Error in bin_to_param with input: '{binary}'")
raise e
def plot_graph(a, b, c, d):
x = np.arange(-5., 5., 0.1)
fig, ax = plt.subplots()
y_approx = a*x**3 + b*x**2 + c*x + d
y_exact = np.e**x
ax.plot(x, y_approx, label='approx. func.')
ax.plot(x, y_exact, label='e^x')
ax.set_xlim(-5, 5)
ax.set_ylim(-1, 5)
plt.legend()
plt.show()