Certainly! Below is a complete MATLAB implementation of the NSGA-II (Non-dominated Sorting Genetic Algorithm II) applied to the ZDT1 test function. This implementation includes all essential components of NSGA-II, such as population initialization, non-dominated sorting, crowding distance calculation, selection, crossover, and mutation.
Overview of the Implementation
Parameters Setup: Define the algorithm parameters such as population size, number of generations, crossover and mutation probabilities, etc.
Population Initialization: Generate an initial population of solutions with random decision variables within the specified bounds.
Objective Function Evaluation: Calculate the two objective functions of ZDT1 for each individual.
Non-dominated Sorting: Sort the population into different fronts based on Pareto dominance.
Crowding Distance Calculation: Calculate the crowding distance for individuals to maintain diversity.
Selection: Use binary tournament selection based on rank and crowding distance.
Crossover and Mutation: Generate offspring using Simulated Binary Crossover (SBX) and Polynomial Mutation.
Replacement: Combine parent and offspring populations and select the next generation based on sorting and crowding distance.
Termination: Repeat the process for a predefined number of generations.
Result Visualization: Plot the final Pareto front obtained.
Let's dive into the MATLAB code.
MATLAB Code for NSGA-II on ZDT1
matlab
% NSGA-II Implementation for ZDT1 Function
clear; clc; close all;
%% Parameters
pop_size = 100; % Population size
max_gen = 250; % Number of generations
eta_c = 20; % Crossover distribution index
eta_m = 20; % Mutation distribution index
p_c = 0.9; % Crossover probability
p_m = 1/30; % Mutation probability
num_vars = 30; % Number of decision variables
lb = zeros(1, num_vars); % Lower bounds
ub = ones(1, num_vars); % Upper bounds
%% Initialize Population
population = initialize_population(pop_size, num_vars, lb, ub);
%% Evaluate Initial Population
[population.obj, population.f1, population.f2] = evaluate_objective(population, num_vars);
%% Evolution
for gen = 1:max_gen
% Non-dominated Sorting
fronts = non_dominated_sorting(population);
% Crowding Distance Calculation
population = calculate_crowding_distance(population, fronts);
% Selection (Binary Tournament)
mating_pool = selection(population, pop_size);
% Crossover and Mutation
offspring = crossover_and_mutation(mating_pool, eta_c, eta_m, p_c, p_m, lb, ub);
% Evaluate Offspring
[offspring.obj, offspring.f1, offspring.f2] = evaluate_objective(offspring, num_vars);
% Combine Parent and Offspring Populations
combined_population = [population, offspring];
% Non-dominated Sorting on Combined Population
fronts = non_dominated_sorting(combined_population);
% Sort Population based on fronts and crowding distance
population = sort_population(combined_population, fronts, pop_size);
% Display Generation Info
if mod(gen, 50) == 0 || gen == 1
disp(['Generation ', num2str(gen), ' completed.']);
end
end
%% Plot Pareto Front
figure;
plot([population.f1], [population.f2], 'ro');
xlabel('f1');
ylabel('f2');
title('Pareto Front obtained by NSGA-II on ZDT1');
grid on;
%% Functions
function population = initialize_population(pop_size, num_vars, lb, ub)
population = struct('dec', [], 'obj', [], 'f1', [], 'f2', [], 'rank', [], 'distance', []);
for i = 1:pop_size
individual.dec = lb + (ub - lb) .* rand(1, num_vars);
population(i) = individual;
end
end
function [obj, f1, f2] = evaluate_objective(population, num_vars)
pop_size = length(population);
f1 = zeros(pop_size,1);
f2 = zeros(pop_size,1);
for i = 1:pop_size
f1(i) = population(i).dec(1);
g = 1 + 9 * sum(population(i).dec(2:end)) / (num_vars - 1);
h = 1 - sqrt(f1(i)/g);
f2(i) = g * h;
end
obj = [f1, f2];
end
function fronts = non_dominated_sorting(population)
pop_size = length(population);
S = cell(pop_size,1);
n = zeros(pop_size,1);
rank = zeros(pop_size,1);
fronts = {};
for p = 1:pop_size
S{p} = [];
n(p) = 0;
for q = 1:pop_size
if dominates(population(p), population(q))
S{p} = [S{p}, q];
elseif dominates(population(q), population(p))
n(p) = n(p) +1;
end
end
if n(p) == 0
rank(p) = 1;
fronts{1} = [fronts{1}, p];
end
end
i =1;
while ~isempty(fronts{i})
Q = [];
for p = fronts{i}
for q = S{p}
n(q) = n(q) -1;
if n(q) ==0
rank(q) = i +1;
Q = [Q, q];
end
end
end
i = i +1;
fronts{i} = Q;
end
fronts(end) = []; % Remove empty last front
end
function b = dominates(p, q)
% Returns true if p dominates q
b = false;
if (p.obj(1) <= q.obj(1) && p.obj(2) <= q.obj(2)) && ...
(p.obj(1) < q.obj(1) || p.obj(2) < q.obj(2))
b = true;
end
end
function population = calculate_crowding_distance(population, fronts)
for i =1:length(fronts)
front = fronts{i};
l = length(front);
if l ==0
continue;
end
for j =1:l
population(front(j)).distance =0;
end
for m =1:size(population(front(1)).obj,2)
[~, order] = sort([population(front).obj].', m);
population(front(order(1))).distance = inf;
population(front(order(end))).distance = inf;
f_min = population(front(order(1))).obj(m);
f_max = population(front(order(end))).obj(m);
if f_max - f_min ==0
continue;
end
for j =2:l-1
population(front(order(j))).distance = ...
population(front(order(j))).distance + ...
(population(front(order(j+1))).obj(m) - population(front(order(j-1))).obj(m)) / (f_max - f_min);
end
end
end
end
function selected = selection(population, pop_size)
selected = population([]);
while length(selected) < pop_size
i1 = randi(length(population));
i2 = randi(length(population));
if tournament_selection(population(i1), population(i2))
selected = [selected, population(i1)];
else
selected = [selected, population(i2)];
end
end
end
function winner = tournament_selection(ind1, ind2)
if ind1.rank < ind2.rank
winner = true;
elseif ind1.rank > ind2.rank
winner = false;
else
if ind1.distance > ind2.distance
winner = true;
else
winner = false;
end
end
end
function offspring = crossover_and_mutation(mating_pool, eta_c, eta_m, p_c, p_m, lb, ub)
offspring = [];
for i=1:2:length(mating_pool)-1
parent1 = mating_pool(i).dec;
parent2 = mating_pool(i+1).dec;
if rand < p_c
[child1, child2] = sbx_crossover(parent1, parent2, eta_c, lb, ub);
else
child1 = parent1;
child2 = parent2;
end
child1 = polynomial_mutation(child1, eta_m, p_m, lb, ub);
child2 = polynomial_mutation(child2, eta_m, p_m, lb, ub);
offspring = [offspring, struct('dec', child1)];
offspring = [offspring, struct('dec', child2)];
end
% If population size is odd, handle last individual
if mod(length(mating_pool),2) ~=0
offspring = [offspring, struct('dec', mating_pool(end).dec)];
end
end
function [child1, child2] = sbx_crossover(parent1, parent2, eta_c, lb, ub)
num_vars = length(parent1);
child1 = parent1;
child2 = parent2;
for i=1:num_vars
if rand <= 0.5
if abs(parent1(i) - parent2(i)) > 1e-14
if parent1(i) < parent2(i)
y1 = parent1(i);
y2 = parent2(i);
else
y1 = parent2(i);
y2 = parent1(i);
end
rand_num = rand;
beta = 1.0 + (2.0*(y1 - lb(i))/(y2 - y1));
alpha = 2.0 - beta^-(eta_c+1);
if rand_num <= 1.0/alpha
betaq = (rand_num * alpha)^(1.0/(eta_c+1));
else
betaq = (1.0/(2.0 - rand_num * alpha))^(1.0/(eta_c+1));
end
c1 = 0.5*((y1 + y2) - betaq*(y2 - y1));
beta = 1.0 + (2.0*(ub(i) - y2)/(y2 - y1));
alpha = 2.0 - beta^-(eta_c+1);
if rand_num <= 1.0/alpha
betaq = (rand_num * alpha)^(1.0/(eta_c+1));
else
betaq = (1.0/(2.0 - rand_num * alpha))^(1.0/(eta_c+1));
end
c2 = 0.5*((y1 + y2) + betaq*(y2 - y1));
c1 = min(max(c1, lb(i)), ub(i));
c2 = min(max(c2, lb(i)), ub(i));
if rand < 0.5
child1(i) = c2;
child2(i) = c1;
else
child1(i) = c1;
child2(i) = c2;
end
else
child1(i) = parent1(i);
child2(i) = parent2(i);
end
else
child1(i) = parent1(i);
child2(i) = parent2(i);
end
end
end
function mutant = polynomial_mutation(child, eta_m, p_m, lb, ub)
num_vars = length(child);
mutant = child;
for i=1:num_vars
if rand < p_m
delta1 = (mutant(i) - lb(i)) / (ub(i) - lb(i));
delta2 = (ub(i) - mutant(i)) / (ub(i) - lb(i));
rand_num = rand;
mut_pow = 1.0/(eta_m+1.0);
if rand_num < 0.5
xy = 1.0 - delta1;
val = 2.0*rand_num + (1.0 - 2.0*rand_num)*(xy)^(eta_m+1);
deltaq = val^(mut_pow) -1.0;
else
xy = 1.0 - delta2;
val = 2.0*(1.0 - rand_num) + 2.0*(rand_num - 0.5)*(xy)^(eta_m+1);
deltaq = 1.0 - val^(mut_pow);
end
mutant(i) = mutant(i) + deltaq*(ub(i) - lb(i));
mutant(i) = min(max(mutant(i), lb(i)), ub(i));
end
end
end
function population = sort_population(combined_population, fronts, pop_size)
new_population = [];
for i=1:length(fronts)
front = fronts{i};
if length(new_population) + length(front) > pop_size
% Calculate crowding distance
temp_front = combined_population(front);
temp_front = calculate_crowding_distance(temp_front, {front});
% Sort based on distance in descending order
[~, sorted_indices] = sort([temp_front.distance], 'descend');
remaining = pop_size - length(new_population);
new_population = [new_population, temp_front(sorted_indices(1:remaining))];
break;
else
new_population = [new_population, combined_population(front)];
end
end
population = new_population;
end
Explanation of the Code Components
Parameters Setup: The algorithm parameters are defined at the beginning, including population size, number of generations, distribution indices for crossover and mutation, and probabilities for crossover and mutation.
Population Initialization:
matlab
population = initialize_population(pop_size, num_vars, lb, ub);
Each individual in the population has a dec field representing decision variables, initialized randomly within the bounds.
Individuals are sorted into different fronts based on Pareto dominance. The first front consists of non-dominated individuals, the second front is dominated only by those in the first front, and so on.
Crowding Distance Calculation:
matlab
population = calculate_crowding_distance(population, fronts);
Calculates the crowding distance for each individual to maintain diversity within the population.
Selection:
matlab
mating_pool = selection(population, pop_size);
Binary tournament selection is performed based on rank and crowding distance to select parents for reproduction.
Crossover and Mutation:
matlab
Running the Code
Save the Code: Copy and paste the above MATLAB code into a new script file, for example, nsga2_zdt1.m.
Execute: Run the script in MATLAB. The algorithm will iterate through the generations, and upon completion, it will display the Pareto front obtained by NSGA-II applied to the ZDT1 function.
Visualization: The final plot will show the trade-off between the two objectives (f1 and f2), representing the Pareto-optimal solutions.
Notes
Parameters Tuning: The parameters such as population size, number of generations, crossover and mutation probabilities, and distribution indices can be tuned based on the specific requirements or for better performance.
Computational Efficiency: For larger populations or more complex objective functions, consider optimizing the code further for computational efficiency.
Extensibility: This implementation can be extended to handle more objectives or different benchmark functions with appropriate modifications to the objective function evaluation.
Feel free to reach out if you have any questions or need further assistance with the implementation!