Skip to content

Commit 6e6de4d

Browse files
committed
fitness level added
1 parent ed8fcbc commit 6e6de4d

1 file changed

Lines changed: 24 additions & 14 deletions

File tree

‎geneticAlgorithm.py‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -88,24 +88,34 @@ def run_simulation(p_cross, p_mut):
8888
total_Q_history.append(total_Q)
8989
variance_history.append(Variance(outputs_list))
9090

91-
# A. RECOMBINATION (Tournament Selection)
92-
mating_pool = []
91+
# A. RECOMBINATION
92+
# Calculate fitness scores (profits) for all firms
93+
fitness_scores = []
94+
for firm in Population:
95+
q_i = BinaryToOutput(firm)
96+
profit = CalculateProfit(q_i, current_price)
97+
fitness_scores.append(profit)
9398

94-
for _ in range(n):
95-
# Pick two random firms
96-
firm_a = random.choice(Population)
97-
firm_b = random.choice(Population)
99+
# Check if we can use fitness-based selection
100+
min_fitness = min(fitness_scores)
101+
total_fitness = sum(fitness_scores)
98102

99-
q_a = BinaryToOutput(firm_a)
100-
q_b = BinaryToOutput(firm_b)
103+
# If negative fitness or zero total fitness, restart population
104+
if min_fitness < 0 or total_fitness <= 0:
105+
Population = []
106+
for i in range(n):
107+
genes = [random.randint(0, 1) for _ in range(l)]
108+
Population.append(genes)
109+
continue
101110

102-
profit_a = CalculateProfit(q_a, current_price)
103-
profit_b = CalculateProfit(q_b, current_price)
111+
# Normalize to get probabilities
112+
probabilities = [f / total_fitness for f in fitness_scores]
104113

105-
if profit_a > profit_b:
106-
mating_pool.append(firm_a.copy())
107-
else:
108-
mating_pool.append(firm_b.copy())
114+
# Select firms based on their fitness probabilities
115+
mating_pool = []
116+
for _ in range(n):
117+
selected_firm_idx = np.random.choice(len(Population), p=probabilities)
118+
mating_pool.append(Population[selected_firm_idx].copy())
109119

110120
# B. CROSSOVER
111121
offspring_pool = []

0 commit comments

Comments
 (0)