Skip to content

Commit 78c8dd7

Browse files
committed
Update function_optimization.py
1 parent d28af66 commit 78c8dd7

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

genetic_algorithm/function_optimization.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import numpy as np
2-
2+
import sympy as sp
33

44
def parse_function(user_input):
55
"""
@@ -23,16 +23,18 @@ def parse_function(user_input):
2323
else:
2424
raise ValueError("Invalid function format. Please use 'f(x, y) = ...'.")
2525

26-
# Replace variable names and power operator
27-
expression = expression.replace("^", "**").replace("x", "x[0]").replace("y", "x[1]")
26+
# Create sympy symbols for x and y
27+
x, y = sp.symbols('x y')
28+
29+
# Replace power operator and parse the expression
30+
expression = expression.replace('^', '**')
31+
func_expr = eval(expression) # Safe to use as we're controlling the input format
2832

29-
# Create the fitness function
30-
def fitness(x):
31-
return eval(expression)
33+
# Create the fitness function using sympy
34+
fitness = sp.lambdify((x, y), func_expr)
3235

3336
return fitness
3437

35-
3638
def genetic_algorithm(user_fitness_function) -> None:
3739
"""
3840
Execute the genetic algorithm to optimize the user-defined fitness function.
@@ -63,7 +65,8 @@ def genetic_algorithm(user_fitness_function) -> None:
6365
fitness_values = []
6466

6567
for individual in population:
66-
fitness_value = user_fitness_function(individual)
68+
# Call the fitness function with individual x and y
69+
fitness_value = user_fitness_function(individual[0], individual[1])
6770

6871
if fitness_value is None or not isinstance(fitness_value, (int, float)):
6972
print(
@@ -90,7 +93,7 @@ def genetic_algorithm(user_fitness_function) -> None:
9093

9194
# Selection
9295
selected_parents = population[rng.choice(population_size, population_size)]
93-
96+
9497
# Crossover
9598
offspring = []
9699
for i in range(0, population_size - 1, 2): # Ensure even number of parents
@@ -127,7 +130,6 @@ def genetic_algorithm(user_fitness_function) -> None:
127130
f"{best_solution[1]:.6f}) = {function_value:.6f}"
128131
)
129132

130-
131133
if __name__ == "__main__":
132134
user_input = input(
133135
"Please enter your fitness function in the format 'f(x, y) = ...':\n"

0 commit comments

Comments
 (0)