0% found this document useful (0 votes)
6 views3 pages

Genetic Algorithm

Uploaded by

varun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Genetic Algorithm

Uploaded by

varun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

12/2/24, 6:55 AM Untitled5.

ipynb - Colab

import random
import numpy as np
import matplotlib.pyplot as plt

#--- COST FUNCTION AND PENALTY ------------------------------------------------+

# Function to maximize
def func1(x):
return -(x[0]**5 - 81*x[0]**4 + 2330*x[0]**3 - 28750*x[0]**2 +
150000*x[0] + 0.5*x[1]**5 - 65*x[1]**4 + 2950*x[1]**3 -
53500*x[1]**2 + 305000*x[1])

# Penalty function for constraints


def constraint_penalty(x):
penalty = 0
# Constraint 1: x1 + 2x2 <= 110
if x[0] + 2*x[1] > 110:
penalty += (x[0] + 2*x[1] - 110)**2
# Constraint 2: 3x1 + x2 <= 120
if 3*x[0] + x[1] > 120:
penalty += (3*x[0] + x[1] - 120)**2
# Constraint 3: 0 <= x1 <= 36
if x[0] < 0:
penalty += (0 - x[0])**2
if x[0] > 36:
penalty += (x[0] - 36)**2
# Constraint 4: 0 <= x2 <= 50
if x[1] < 0:
penalty += (0 - x[1])**2
if x[1] > 50:
penalty += (x[1] - 50)**2
return penalty

# Combined cost function with penalty


def constrained_func(x):
base_cost = func1(x)
penalty = constraint_penalty(x)
return base_cost + penalty

#--- GENETIC ALGORITHM IMPLEMENTATION -----------------------------------------+

def genetic_algorithm(func, bounds, population_size, generations, mutation_rate, crossover_rate):


# Initialize population
population = [
[random.uniform(bounds[i][0], bounds[i][1]) for i in range(len(bounds))]
for _ in range(population_size)
]

# Track best solution


best_solution = None
best_score = float('-inf')

# Log data for visualization


gen_scores = []
best_x1 = []
best_x2 = []

for gen in range(generations):


# Evaluate fitness of the population
fitness = [func(ind) for ind in population]

# Find the best individual


gen_best_idx = np.argmax(fitness)
gen_best_ind = population[gen_best_idx]
gen_best_score = fitness[gen_best_idx]

if gen_best_score > best_score:


best_solution = gen_best_ind
best_score = gen_best_score

# Logging for plots


gen_scores.append(best_score)
best_x1.append(best_solution[0])
best_x2.append(best_solution[1])

# Selection (Roulette Wheel Selection)


total_fitness = sum(fitness)
probabilities = [f / total_fitness for f in fitness]
selected_population = random.choices(population, probabilities, k=population_size)

# Crossover
i []
https://colab.research.google.com/drive/1aUjS0Beoa1xzNzpubPXccOJrsYimFJmV#printMode=true 1/3
12/2/24, 6:55 AM Untitled5.ipynb - Colab
next_generation = []
for _ in range(population_size // 2):
if random.random() < crossover_rate:
parent1 = random.choice(selected_population)
parent2 = random.choice(selected_population)
crossover_point = random.randint(1, len(bounds) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
next_generation.extend([child1, child2])
else:
next_generation.extend(random.sample(selected_population, 2))

# Mutation
for individual in next_generation:
if random.random() < mutation_rate:
index = random.randint(0, len(bounds) - 1)
individual[index] = random.uniform(bounds[index][0], bounds[index][1])

population = next_generation

# Plotting
plt.plot(range(generations), gen_scores, label='Objective Function Value')
plt.xlabel('Generation')
plt.ylabel('Objective Function Value')
plt.title('GA Optimization Progress')
plt.legend()
plt.grid()
plt.show()

print("Best Solution:", best_solution)


print("Best Score:", best_score)

# Plot positions vs iterations


plt.plot(range(generations), best_x1, label="x1")
plt.plot(range(generations), best_x2, label="x2")
plt.xlabel("Generation")
plt.ylabel("Position")
plt.legend()
plt.title("Variable Positions vs Generations")
plt.grid()
plt.show()

return best_solution, best_score

#--- RUN GA -------------------------------------------------------------------+

# Parameters
bounds = [(20, 21), (35,36)] # Variable bounds: [(x1_min, x1_max), (x2_min, x2_max)]
population_size = 50 # Number of individuals in the population
generations = 100 # Number of generations to run
mutation_rate = 0.1 # Probability of mutation
crossover_rate = 0.7 # Probability of crossover

# Initial run
best_sol, best_val = genetic_algorithm(
constrained_func, bounds, population_size, generations, mutation_rate, crossover_rate
)

# Print final result


print("Optimal Solution Found:", best_sol)
print("Optimal Value:", best_val)

https://colab.research.google.com/drive/1aUjS0Beoa1xzNzpubPXccOJrsYimFJmV#printMode=true 2/3
12/2/24, 6:55 AM Untitled5.ipynb - Colab

Best Solution: [20.059028968447304, 35.99723424389268]


Best Score: -717497.028987119

Optimal Solution Found: [20.059028968447304, 35.99723424389268]


Optimal Value: -717497.028987119

https://colab.research.google.com/drive/1aUjS0Beoa1xzNzpubPXccOJrsYimFJmV#printMode=true 3/3

You might also like