0% found this document useful (0 votes)
15 views8 pages

PID Optimization Using GA Omar Ibrahim

The document presents a method for optimizing PID controller parameters for a missile control system using a Genetic Algorithm (GA). It includes the simulation of system dynamics, the definition of a fitness function to evaluate performance, and the implementation of GA for parameter tuning. Results are compared between Ziegler-Nichols tuned parameters and GA optimized parameters, with visualizations of the system responses.

Uploaded by

omar akwah
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)
15 views8 pages

PID Optimization Using GA Omar Ibrahim

The document presents a method for optimizing PID controller parameters for a missile control system using a Genetic Algorithm (GA). It includes the simulation of system dynamics, the definition of a fitness function to evaluate performance, and the implementation of GA for parameter tuning. Results are compared between Ziegler-Nichols tuned parameters and GA optimized parameters, with visualizations of the system responses.

Uploaded by

omar akwah
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/ 8

PID Optimization using GA

Omar Ibrahim Ismael


Mahmoud
import numpy as np

import matplotlib.pyplot as plt

from scipy.integrate import odeint

# Define the missile control system dynamics

def missile_system(y, t, u):

x1, x2 = y

dx1 = x2

dx2 = -x2 - x1 + u # Steering engine dynamics

return [dx1, dx2]

# Simulate system response with PID controller

def simulate_system(Kp, Ki, Kd, time):

y0 = [0, 0] # Initial conditions

dt = time[1] - time[0]

error_prev = 0

integral = 0

response = []

y = y0

for t in time:

error = 1 - y[0] # Desired altitude is 1

integral += error * dt # Accumulate integral

derivative = (error - error_prev) / dt # Compute derivative

u = Kp * error + Ki * integral + Kd * derivative # PID control signal

y = odeint(missile_system, y, [t, t + dt], args=(u,))[-1] # Solve system dynamics


response.append(y[0]) # Store position (altitude)

error_prev = error # Update error for next loop

return np.array(response)

# Enhanced fitness function

def fitness_function(params):

Kp, Ki, Kd = params

time = np.linspace(0, 10, 1000)

response = simulate_system(Kp, Ki, Kd, time)

# Performance metrics

overshoot = np.max(response) - 1 if np.max(response) > 1 else 0

rise_time = next((t for t, y in zip(time, response) if y >= 0.9), 10)

settling_time = next((t for t, y in zip(time[::-1], response[::-1]) if abs(y - 1) > 0.05), 10)

mse = np.mean((1 - response) ** 2) # Mean square error

# Weighted fitness value

return mse + 10 * overshoot + 5 * rise_time + 5 * settling_time

# Enhanced Genetic Algorithm

def genetic_algorithm(fitness_func, bounds, n_pop=100, n_generations=200,


mutation_rate=0.2):

population = np.random.uniform(bounds[:, 0], bounds[:, 1], (n_pop, bounds.shape[0])) #


Initialize population

best_solutions = []

fitness_history = []
for generation in range(n_generations):

fitness = np.array([fitness_func(ind) for ind in population]) # Evaluate fitness

fitness_history.append(np.min(fitness)) # Track the best fitness

best_solutions.append(population[np.argmin(fitness)])

# Tournament selection

def tournament_selection():

indices = np.random.choice(range(n_pop), size=5, replace=False)

return population[indices[np.argmin(fitness[indices])]]

parents = np.array([tournament_selection() for _ in range(n_pop)])

# Simulated Binary Crossover (SBX)

o`spring = []

for i in range(0, n_pop, 2):

p1, p2 = parents[i], parents[i + 1]

alpha = np.random.uniform(0, 1, size=bounds.shape[0])

o`spring.append(alpha * p1 + (1 - alpha) * p2)

o`spring.append((1 - alpha) * p1 + alpha * p2)

# Mutation

o`spring = np.array(o`spring)

mutations = np.random.uniform(-mutation_rate, mutation_rate, o`spring.shape)

o`spring += mutations

o`spring = np.clip(o`spring, bounds[:, 0], bounds[:, 1]) # Enforce bounds


# Update population

population = o`spring

# Plot fitness convergence

plt.figure(figsize=(8, 5))

plt.plot(range(n_generations), fitness_history, label="Fitness over Generations")

plt.title("Genetic Algorithm Optimization Progress")

plt.xlabel("Generation")

plt.ylabel("Fitness (Lower is Better)")

plt.legend()

plt.show()

return best_solutions, best_solutions[-1]

# Parameters from the Ziegler-Nichols method

zn_params = [6.3843, 281.25, 0.01004] # Ziegler-Nichols tuned parameters

# Genetic Algorithm bounds for Kp, Ki, and Kd

bounds = np.array([[0, 400], [0, 400], [0, 400]])

# Run Genetic Algorithm

best_solutions, best_params = genetic_algorithm(fitness_function, bounds)

# Simulate responses

time = np.linspace(0, 10, 1000)


zn_response = simulate_system(*zn_params, time) # Z-N response

ga_response = simulate_system(*best_params, time) # GA response

# Plot comparison of responses

plt.figure(figsize=(12, 8))

# Ziegler-Nichols response

plt.subplot(2, 1, 1)

plt.plot(time, zn_response, label="Ziegler-Nichols PID Response")

plt.axhline(1, color='r', linestyle="--", label="Desired Altitude")

plt.title("Ziegler-Nichols PID Response")

plt.xlabel("Time (s)")

plt.ylabel("Altitude")

plt.legend()

# GA-optimized response

plt.subplot(2, 1, 2)

plt.plot(time, ga_response, label="GA Tuned PID Response")

plt.axhline(1, color='r', linestyle="--", label="Desired Altitude")

plt.title("GA Tuned PID Response")

plt.xlabel("Time (s)")

plt.ylabel("Altitude")

plt.legend()

plt.tight_layout()

plt.savefig("Missile_Control_Comparison_Enhanced.png")
plt.show()

# Print results

print("Ziegler-Nichols PID Parameters: Kp = {}, Ki = {}, Kd = {}".format(*zn_params))

print("GA Optimized PID Parameters: Kp = {:.4f}, Ki = {:.4f}, Kd =


{:.4f}".format(*best_params))

You might also like