diff --git a/03_euler_gen_alg/main.py b/03_euler_gen_alg/main.py index 550eaf5..ac7470e 100644 --- a/03_euler_gen_alg/main.py +++ b/03_euler_gen_alg/main.py @@ -19,9 +19,10 @@ POPULATION_SIZE = 10 SELECTION_SIZE = (POPULATION_SIZE * 7) // 10 # 70% of population, rounded down for selection XOVER_PAIR_SIZE = (POPULATION_SIZE - SELECTION_SIZE) // 2 # pairs needed for crossover XOVER_POINT = 3 # 4th position -MUTATION_BITS = POPULATION_SIZE * 1 +MUTATION_BITS = POPULATION_SIZE // 2 -fitness = 1 +fitness = 2 +fitness_arr = [2,2,2,2,2,2,2,2,2,2] grey_pop = [] bin_pop = [] # 32 Bit Binary bin_pop_params = [] @@ -63,30 +64,32 @@ def eval_fitness(bin_pop_values): # Create polynomial function with current parameters approx = lambda x: a*x**3 + b*x**2 + c*x + d fitness = quadratic_error(e_func, approx, 6) - print("Fitness: " + str(fitness)) # debugging - fitness_arr.append(fitness) # save fitness + inverse_fitness = 1 / fitness + print("Fitness: " + str(inverse_fitness)) # debugging + fitness_arr.append(inverse_fitness) # save fitness # save params # already saved in grey_pop return fitness_arr def select(population, fitness_arr): - sum_of_fitness = sum(fitness_arr) + fitness_arr_copy = fitness_arr.copy() + sum_of_fitness = sum(fitness_arr_copy) while len(population) < SELECTION_SIZE: # Roulette logic roulette_num = random.random() is_chosen = False while not is_chosen: cumulative_p = 0 # Track cumulative probability - for i, fitness in enumerate(fitness_arr): + for i, fitness in enumerate(fitness_arr_copy): cumulative_p += fitness / sum_of_fitness if roulette_num < cumulative_p: # Add the 32 Bit individual in grey code to population population.append(grey_pop[i]) # Calc new sum of fitness - fitness_arr.pop(i) - sum_of_fitness = sum(fitness_arr) + fitness_arr_copy.pop(i) + sum_of_fitness = sum(fitness_arr_copy) is_chosen = True # break while loop break # break for loop @@ -128,13 +131,14 @@ def mutate(population, mutation_rate): population[random_num] = ''.join(bits) # will work because lists are passed by reference def main(): - global grey_pop, bin_pop, bin_pop_params, new_pop, fitness + global grey_pop, bin_pop, bin_pop_params, new_pop, fitness, fitness_arr bin_pop_values = generate_random_population(POPULATION_SIZE) new_pop = grey_pop.copy() # Make a copy of the populated grey_pop iteration = 0 - while fitness > 0.01: + # TODO: Have to decide with probability somehow + while not np.all(np.array(fitness_arr) <= 1): # Continue while any fitness value is > 1 print("Iteration: " + str(iteration)) # Evaluate fitness @@ -168,4 +172,5 @@ def main(): return 0 if __name__ == "__main__": - main() \ No newline at end of file + main() + print("found that shit") \ No newline at end of file diff --git a/03_euler_gen_alg/utils.py b/03_euler_gen_alg/utils.py index b81288a..5767a41 100644 --- a/03_euler_gen_alg/utils.py +++ b/03_euler_gen_alg/utils.py @@ -1,22 +1,45 @@ +def clean_binary_string(binary_str, length=32): + """Clean and format a binary string to ensure proper format""" + # Remove any whitespace and ensure proper length + cleaned = ''.join(binary_str.split()) + return cleaned.zfill(length) + def grey_to_bin(gray): """Convert Gray code to binary, operating on the integer value directly""" - num = int(gray, 2) # Convert string to integer - mask = num - while mask != 0: - mask >>= 1 - num ^= mask - return format(num, f'0{len(gray)}b') # Convert back to binary string with same length + # Clean and format input string + gray = clean_binary_string(gray, 32) + try: + num = int(gray, 2) # Convert string to integer + mask = num + while mask != 0: + mask >>= 1 + num ^= mask + return format(num, '032b') # Always return 32-bit string + except ValueError as e: + print(f"Error in grey_to_bin with input: '{gray}'") + raise e def bin_to_grey(binary): """Convert binary to Gray code using XOR with right shift""" - num = int(binary, 2) # Convert string to integer - gray = num ^ (num >> 1) # Gray code formula: G = B ^ (B >> 1) - return format(gray, f'0{len(binary)}b') # Convert back to binary string with same length + # Clean and format input string + binary = clean_binary_string(binary, 32) + try: + num = int(binary, 2) # Convert string to integer + gray = num ^ (num >> 1) # Gray code formula: G = B ^ (B >> 1) + return format(gray, '032b') # Always return 32-bit string + except ValueError as e: + print(f"Error in bin_to_grey with input: '{binary}'") + raise e def bin_to_param(binary, q_min = 0.0, q_max = 10.0): """Convert one binary string to float parameter in range [q_min, q_max]""" - val = int(binary, 2) / 25.5 * 10 # conversion to 0.0 - 10.0 float - # Scale to range [q_min, q_max] - q = q_min + ((q_max - q_min) / (2**len(binary))) * val - - return q + # Clean and format input string + binary = clean_binary_string(binary, 7) # 7 bits for parameters + try: + val = int(binary, 2) / 25.5 * 10 # conversion to 0.0 - 10.0 float + # Scale to range [q_min, q_max] + q = q_min + ((q_max - q_min) / (2**len(binary))) * val + return q + except ValueError as e: + print(f"Error in bin_to_param with input: '{binary}'") + raise e