code 1:
function [paretoFront, paretoSet] = NSGA2(NPop, T, lb, ub, dim, fitnessFcn)
% Initialize population
pop = initialization(NPop, dim, ub, lb);
fitness = evaluatePopulation(pop, fitnessFcn);
code
for gen = 1:T
% Non-dominated sorting
[fronts, ranks] = nonDominatedSort(fitness);
% Create mating pool using tournament selection
matingPool = tournamentSelection(pop, ranks, NPop);
% Generate offspring using SBX crossover and polynomial mutation
offspring = crossover(matingPool, 0.9, dim);
offspring = mutation(offspring, 1/dim, dim);
% Evaluate offspring
offspringFitness = evaluatePopulation(offspring, fitnessFcn);
% Combine population and offspring
combinedPop = [pop; offspring];
combinedFitness = [fitness; offspringFitness];
% Non-dominated sorting on combined population
[fronts, ~] = nonDominatedSort(combinedFitness);
% Create new population
[pop, fitness] = selectNewPopulation(combinedPop, combinedFitness, fronts, NPop);
% Display generation progress
if mod(gen, 10) == 0
fprintf('Generation #%d/%d completed.\n', gen, T);
end
end
% Return last population as Pareto front
paretoFront = fitness;
paretoSet = pop;
end
function pop = initialization(NPop, dim, ub, lb)
pop = rand(NPop, dim) .* (ub - lb) + lb;
end
function fitness = evaluatePopulation(pop, fitnessFcn)
numIndividuals = size(pop, 1);
numObjectives = 2; % This should be set based on the problem
fitness = zeros(numIndividuals, numObjectives);
for i = 1:numIndividuals
fitness(i, :) = fitnessFcn(pop(i, :));
end
end
for i = 1:numIndividuals
for j = 1:numIndividuals
if i ~= j
if dominates(fitness(i, :), fitness(j, :))
dominatedSet{i}(end+1) = j;
elseif dominates(fitness(j, :), fitness(i, :))
dominationCount(i) = dominationCount(i) + 1;
end
end
end
if dominationCount(i) == 0
rank(i) = 1;
fronts{1}(end+1) = i;
end
end
currentFront = 1;
while ~isempty(fronts{currentFront})
nextFront = [];
for i = fronts{currentFront}
for j = dominatedSet{i}
dominationCount(j) = dominationCount(j) - 1;
if dominationCount(j) == 0
rank(j) = currentFront + 1;
nextFront(end+1) = j;
end
end
end
currentFront = currentFront + 1;
fronts{currentFront} = nextFront;
end
fronts = fronts(1:currentFront-1);
end
function isDominated = dominates(x, y)
isDominated = all(x <= y) && any(x < y);
end
function selectedPop = tournamentSelection(pop, ranks, numSelected)
selectedPop = zeros(numSelected, size(pop, 2));
for i = 1:numSelected
candidates = randperm(size(pop, 1), 2);
if ranks(candidates(1)) < ranks(candidates(2))
selectedPop(i, :) = pop(candidates(1), :);
else
selectedPop(i, :) = pop(candidates(2), :);
end
end
end
function offspring = crossover(pop, crossoverProb, numVars)
etaC = 20; % Distribution index for crossover
numIndividuals = size(pop, 1);
offspring = zeros(numIndividuals, numVars);
code
for i = 1:2:numIndividuals
if rand < crossoverProb
parent1 = pop(i, :);
parent2 = pop(i+1, :);
child1 = zeros(1, numVars);
child2 = zeros(1, numVars);
for j = 1:numVars
u = rand;
if u <= 0.5
beta = (2*u)^(1/(etaC+1));
else
beta = (1/(2*(1-u)))^(1/(etaC+1));
end
child1(j) = 0.5 * ((1+beta) * parent1(j) + (1-beta) * parent2(j));
child2(j) = 0.5 * ((1-beta) * parent1(j) + (1+beta) * parent2(j));
% Handle bounds
child1(j) = min(max(child1(j), 0), 1);
child2(j) = min(max(child2(j), 0), 1);
end
offspring(i, :) = child1;
offspring(i+1, :) = child2;
else
offspring(i, :) = pop(i, :);
offspring(i+1, :) = pop(i+1, :);
end
end
end
function mutatedPop = mutation(pop, mutationProb, numVars)
etaM = 20; % Mutation distribution index
mutatedPop = pop;
numIndividuals = size(pop, 1);
code
for i = 1:numIndividuals
for j = 1:numVars
if rand < mutationProb
r = rand;
if r < 0.5
delta = (2*r)^(1/(etaM + 1)) - 1;
else
delta = 1 - (2*(1-r))^(1/(etaM + 1));
end
mutatedPop(i, j) = pop(i, j) + delta;
mutatedPop(i, j) = min(max(mutatedPop(i, j), 0), 1);
end
end
end
end
function [pop, fitness] = selectNewPopulation(combinedPop, combinedFitness, fronts, NPop)
pop = [];
fitness = [];
for i = 1:length(fronts)
if size(pop, 1) + length(fronts{i}) > NPop
break;
end
pop = [pop; combinedPop(fronts{i}, :)];
fitness = [fitness; combinedFitness(fronts{i}, :)];
end
for m = 1:numObjectives
[sortedValues, sortedIdx] = sort(fitness(:, m));
distances(sortedIdx(1)) = inf;
distances(sortedIdx(end)) = inf;
for i = 2:numIndividuals-1
range = sortedValues(end) - sortedValues(1);
if range > 0
distances(sortedIdx(i)) = distances(sortedIdx(i)) + ...
(sortedValues(i+1) - sortedValues(i-1)) / range;
end
end
end
% Initialize population
chromosome = initializeVariables(NPop, dim, ub, lb);
fitness = evaluatePopulation(chromosome, fitnessFcn);
% Non-dominated sorting of initialized population
[fronts, ranks] = nonDominatedSort(fitness);
% Start the evolution process
for i = 1:T
% Selection
matingPool = tournamentSelection(chromosome, ranks, NPop);
% Genetic operators (crossover and mutation)
offspring = crossover(matingPool, 0.9, dim);
offspring = mutation(offspring, 1/dim, dim);
% Evaluate offspring
offspringFitness = evaluatePopulation(offspring, fitnessFcn);
% Combine populations
combinedChromosome = [chromosome; offspring];
combinedFitness = [fitness; offspringFitness];
% Non-dominated sorting on combined population
[fronts, ~] = nonDominatedSort(combinedFitness);
% Create new population
[chromosome, fitness] = replaceChromosome(combinedChromosome, combinedFitness, fronts, NPop);
% Record history
fitnessHistory(:,i,:) = fitness;
positionHistory(:,i,:) = chromosome;
% Update Trajectories (using the best ranked solution)
trajectories(:,i) = chromosome(1, :)';
if ~mod(i,50)
disp(['Iteration #', num2str(i), ' completed']);
end
end
% Extract Pareto front and set
paretoFront = fitness;
paretoSet = chromosome;
end
function chromosome = initializeVariables(N, dim, ub, lb)
chromosome = rand(N, dim) .* (ub - lb) + lb;
end
function fitness = evaluatePopulation(chromosome, fitnessFcn)
numIndividuals = size(chromosome, 1);
fitness = zeros(numIndividuals, 2);
for i = 1:numIndividuals
fitness(i, :) = fitnessFcn(chromosome(i, :));
end
end
for i = 1:numIndividuals
for j = 1:numIndividuals
if i ~= j
if dominates(fitness(i, :), fitness(j, :))
dominatedSet{i}(end+1) = j;
elseif dominates(fitness(j, :), fitness(i, :))
dominationCount(i) = dominationCount(i) + 1;
end
end
end
if dominationCount(i) == 0
rank(i) = 1;
fronts{1}(end+1) = i;
end
end
currentFront = 1;
while ~isempty(fronts{currentFront})
nextFront = [];
for i = fronts{currentFront}
for j = dominatedSet{i}
dominationCount(j) = dominationCount(j) - 1;
if dominationCount(j) == 0
rank(j) = currentFront + 1;
nextFront(end+1) = j;
end
end
end
currentFront = currentFront + 1;
fronts{currentFront} = nextFront;
end
fronts = fronts(1:currentFront-1);
end
function isDominated = dominates(x, y)
isDominated = all(x <= y) && any(x < y);
end
function selectedChromosome = tournamentSelection(chromosome, ranks, numSelected)
selectedChromosome = zeros(numSelected, size(chromosome, 2));
for i = 1:numSelected
candidates = randperm(size(chromosome, 1), 2);
if ranks(candidates(1)) < ranks(candidates(2))
selectedChromosome(i, :) = chromosome(candidates(1), :);
else
selectedChromosome(i, :) = chromosome(candidates(2), :);
end
end
end
function offspring = crossover(chromosome, crossoverProb, numVars)
etaC = 20; % Distribution index for crossover
numIndividuals = size(chromosome, 1);
offspring = zeros(numIndividuals, numVars);
code
for i = 1:2:numIndividuals
if rand < crossoverProb
parent1 = chromosome(i, :);
parent2 = chromosome(i+1, :);
child1 = zeros(1, numVars);
child2 = zeros(1, numVars);
for j = 1:numVars
u = rand;
if u <= 0.5
beta = (2*u)^(1/(etaC+1));
else
beta = (1/(2*(1-u)))^(1/(etaC+1));
end
child1(j) = 0.5 * ((1+beta) * parent1(j) + (1-beta) * parent2(j));
child2(j) = 0.5 * ((1-beta) * parent1(j) + (1+beta) * parent2(j));
% Handle bounds
child1(j) = min(max(child1(j), 0), 1);
child2(j) = min(max(child2(j), 0), 1);
end
offspring(i, :) = child1;
offspring(i+1, :) = child2;
else
offspring(i, :) = chromosome(i, :);
offspring(i+1, :) = chromosome(i+1, :);
end
end
end
function mutatedChromosome = mutation(chromosome, mutationProb, numVars)
etaM = 20; % Mutation distribution index
mutatedChromosome = chromosome;
numIndividuals = size(chromosome, 1);
code
for i = 1:numIndividuals
for j = 1:numVars
if rand < mutationProb
r = rand;
if r < 0.5
delta = (2*r)^(1/(etaM + 1)) - 1;
else
delta = 1 - (2*(1-r))^(1/(etaM + 1));
end
mutatedChromosome(i, j) = chromosome(i, j) + delta;
mutatedChromosome(i, j) = min(max(mutatedChromosome(i, j), 0), 1);
end
end
end
end
function [chromosome, fitness] = replaceChromosome(combinedChromosome, combinedFitness, fronts, NPop)
chromosome = [];
fitness = [];
for i = 1:length(fronts)
if size(chromosome, 1) + length(fronts{i}) > NPop
break;
end
chromosome = [chromosome; combinedChromosome(fronts{i}, :)];
fitness = [fitness; combinedFitness(fronts{i}, :)];
end
for m = 1:numObjectives
[sortedValues, sortedIdx] = sort(fitness(:, m));
distances(sortedIdx(1)) = inf;
distances(sortedIdx(end)) = inf;
for i = 2:numIndividuals-1
range = sortedValues(end) - sortedValues(1);
if range > 0
distances(sortedIdx(i)) = distances(sortedIdx(i)) + ...
(sortedValues(i+1) - sortedValues(i-1)) / range;
end
end
end
end
To determine which of the two NSGA2 codes is better, we must consider several factors like readability, functionality, extensibility, performance tracking, and ease of use. Both codes are implementations of the NSGA2 algorithm, but they have some differences in their design and features.
Key Differences:
History Tracking:
Code 2 tracks fitness and position history throughout the generations (fitnessHistory and positionHistory) and provides trajectories of the best-ranked solutions over time. This can be very useful for analyzing the evolutionary process and examining how solutions evolve.
Code 1 does not maintain this historical data, making it more challenging to analyze and visualize the algorithm's progress over time.
Output:
Code 2 returns additional outputs (trajectories, fitnessHistory, positionHistory), which can be beneficial for post-analysis.
Code 1 is more minimal, returning only the paretoFront and paretoSet, which might be sufficient for final result evaluation but lacks deeper insights.
Performance Feedback:
Code 2 displays progress updates every 50 generations, providing feedback during long runs.
Code 1 only prints progress every 10 generations, which might be more frequent but less detailed.
Implementation:
Both codes use standard practices for NSGA2, such as non-dominated sorting, tournament selection, SBX crossover, and polynomial mutation.
They manage crowded comparison using crowding distance, essential for diversity maintenance in multi-objective optimization.
Variable Names:
Code 2 uses more descriptive variable names (chromosome for population), enhancing code readability compared to Code 1 (pop).
Which One is Better?
Depends on Use Case and User Needs:
Analysis and Debugging: If your priority is detailed analysis or education, Code 2 is better because of its history and trajectory tracking.
Simplicity and Minimalism: If you want a simpler and more straightforward implementation, or you are not concerned with detailed progression analysis, Code 1 might be preferable due to its simplicity.
Performance and Insights:Code 2 may provide better insights into how the algorithm performs over time, making it a better choice for research and development purposes.
In summary, if you are choosing based on features and potential for in-depth analysis and understanding, Code 2 would generally be considered better. If simplicity and straightforward results are your primary goals, you might opt for Code 1.