can you create a code for ngsa ii to try on zdt 1. please show full code
- User
can you create a code for ngsa ii to try on zdt 1. please show full code
- Assistant
- User
in matlab
- Assistant
- User
try that code
- Assistant
- User
try on zdt1
- Assistant
can you create a code for ngsa ii to try on zdt 1. please show full code
in matlab
try that code
try on zdt1
Certainly! The Non-dominated Sorting Genetic Algorithm II (NSGA-II) is a popular multi-objective optimization algorithm. The ZDT1 problem is a classic test case for evolutionary algorithms. Below is a Python implementation using the deap library. If you don't have deap installed, you can install it via pip:
pip install deap
Here is the complete code to set up and run NSGA-II on the ZDT1 problem:
import random
import numpy as np
from deap import base, creator, tools, algorithms
# Define ZDT1 problem as a minimization problem with fitness function
def evalZDT1(individual):
n = len(individual)
x1 = individual[0]
g = 1.0 + 9.0 * sum(individual[1:]) / (n - 1)
f1 = x1
f2 = g * (1 - np.sqrt(x1 / g))
return f1, f2
# Create the fitness and individual classes
creator.create("FitnessMin", base.Fitness, weights=(-1.0, -1.0))
creator.create("Individual", list, fitness=creator.FitnessMin)
# Initialize parameters and functions for individual creation
IND_SIZE = 30 # Number of variables in ZDT1
BOUND_LOW, BOUND_UP = 0.0, 1.0 # Variable bounds for ZDT1
toolbox = base.Toolbox()
toolbox.register("attr_float", random.uniform, BOUND_LOW, BOUND_UP)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=IND_SIZE)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# Register the evaluation, crossover, mutation, and selection functions
toolbox.register("evaluate", evalZDT1)
toolbox.register("mate", tools.cxSimulatedBinaryBounded, low=BOUND_LOW, up=BOUND_UP, eta=20.0)
toolbox.register("mutate", tools.mutPolynomialBounded, low=BOUND_LOW, up=BOUND_UP, eta=20.0, indpb=1.0/IND_SIZE)
toolbox.register("select", tools.selNSGA2)
# Define the main function for using NSGA-II
def main():
random.seed(42) # Seed for reproducibility
pop_size = 100
num_generations = 250
crossover_prob = 0.9
mutation_prob = 1.0 / IND_SIZE
# Initialize the population
pop = toolbox.population(n=pop_size)
# Evaluate the entire population
fitnesses = list(map(toolbox.evaluate, pop))
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
# Run the algorithm
for gen in range(num_generations):
# Select the next generation individuals
offspring = toolbox.select(pop, len(pop))
offspring = list(map(toolbox.clone, offspring))
# Apply crossover and mutation on the offspring
for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
if random.random() < crossover_prob:
toolbox.mate(ind1, ind2)
del ind1.fitness.values
del ind2.fitness.values
for mutant in offspring:
if random.random() < mutation_prob:
toolbox.mutate(mutant)
del mutant.fitness.values
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
# The population is entirely replaced by the offspring
pop[:] = offspring
# Extract the Pareto front
pareto_front = tools.sortNondominated(pop, len(pop), True)[0]
# Print the Pareto front
for individual in pareto_front:
print(individual.fitness.values)
if __name__ == "__main__":
main()
This code sets up and runs NSGA-II on the ZDT1 problem. The algorithm evolves a population of individuals over a specified number of generations (num_generations). The pop_size, crossover probability (crossover_prob), and mutation probability (mutation_prob) can be adjusted as needed. The final Pareto-optimal solutions found by NSGA-II are printed at the end.
Make sure you install any necessary dependencies (like numpy and deap) before running this code.
Implementing NSGA-II for the ZDT1 problem in MATLAB requires some setup, as MATLAB doesn't have built-in multi-objective optimization algorithms like NSGA-II. However, you can code it from scratch or use existing toolboxes if they are available. Here, I'll provide a basic implementation of NSGA-II in MATLAB for the ZDT1 problem.
This example will include basic setup for the population initialization, selection, crossover, mutation, and the non-dominated sorting process required by NSGA-II.
function nsga2_zdt1
% Parameters
popSize = 100;
maxGenerations = 250;
numVariables = 30;
lowerBound = 0;
upperBound = 1;
crossoverRate = 0.9;
mutationRate = 1.0 / numVariables;
% Initialize population
population = rand(popSize, numVariables) * (upperBound - lowerBound) + lowerBound;
% Evaluate initial population
fitness = evaluatePopulation(population);
for gen = 1:maxGenerations
% Selection
matingPool = tournamentSelection(population, fitness, popSize);
% Crossover and Mutation
offspring = crossoverAndMutation(matingPool, crossoverRate, mutationRate, lowerBound, upperBound);
% Evaluate offspring
offspringFitness = evaluatePopulation(offspring);
% Combine and select next generation
[population, fitness] = environmentalSelection([population; offspring], [fitness; offspringFitness], popSize);
end
% Plot Pareto Front
paretoFront = population(NDSort(fitness, 1)==1, :);
fitValues = evaluatePopulation(paretoFront);
plot(fitValues(:, 1), fitValues(:, 2), 'bo');
title('Pareto Front');
xlabel('f1');
ylabel('f2');
end
function fitness = evaluatePopulation(population)
n = size(population, 2);
x1 = population(:, 1);
g = 1.0 + 9.0 * sum(population(:, 2:end), 2) / (n - 1);
f1 = x1;
f2 = g .* (1 - sqrt(x1 ./ g));
fitness = [f1 f2];
end
function matingPool = tournamentSelection(population, fitness, popSize)
matingPool = zeros(size(population));
for i = 1:popSize
a = randi(popSize);
b = randi(popSize);
if dominates(fitness(a, :), fitness(b, :))
winner = a;
else
winner = b;
end
matingPool(i, :) = population(winner, :);
end
end
function offspring = crossoverAndMutation(matingPool, crossoverRate, mutationRate, lowerBound, upperBound)
[popSize, numVariables] = size(matingPool);
offspring = zeros(size(matingPool));
for i = 1:2:popSize
parent1 = matingPool(i, :);
if i+1 <= popSize
parent2 = matingPool(i+1, :);
else
parent2 = matingPool(1, :);
end
if rand < crossoverRate
% Simulated binary crossover
[offspring1, offspring2] = sbx(parent1, parent2, lowerBound, upperBound);
else
offspring1 = parent1;
offspring2 = parent2;
end
% Mutation
offspring1 = mutate(offspring1, mutationRate, lowerBound, upperBound);
offspring2 = mutate(offspring2, mutationRate, lowerBound, upperBound);
offspring(i, :) = offspring1;
if i+1 <= popSize
offspring(i+1, :) = offspring2;
end
end
end
function child = mutate(individual, mutationRate, lowerBound, upperBound)
for i = 1:length(individual)
if rand < mutationRate
individual(i) = lowerBound + rand * (upperBound - lowerBound);
end
end
child = individual;
end
function [child1, child2] = sbx(parent1, parent2, lowerBound, upperBound)
% Simulated Binary Crossover (SBX)
eta = 20;
child1 = zeros(size(parent1));
child2 = zeros(size(parent2));
for i = 1:length(parent1)
if rand <= 0.5
if abs(parent1(i) - parent2(i)) > eps
if parent1(i) < parent2(i)
y1 = parent1(i);
y2 = parent2(i);
else
y1 = parent2(i);
y2 = parent1(i);
end
yl = lowerBound;
yu = upperBound;
randValue = rand;
beta = 1.0 + (2.0*(y1-yl)/(y2-y1));
alpha = 2.0 - beta^(-(eta+1));
if randValue <= 1.0/alpha
betaQ = (randValue*alpha)^(1.0/(eta+1));
else
betaQ = (1.0/(2.0- randValue*alpha))^(1.0/(eta+1));
end
c1 = 0.5*((y1+y2) - betaQ*(y2-y1));
beta = 1.0 + (2.0*(yu-y2)/(y2-y1));
alpha = 2.0 - beta^(-(eta+1));
if randValue <= 1.0/alpha
betaQ = (randValue*alpha)^(1.0/(eta+1));
else
betaQ = (1.0/(2.0- randValue*alpha))^(1.0/(eta+1));
end
c2 = 0.5*((y1+y2) + betaQ*(y2-y1));
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
if child1(i) < lowerBound
child1(i) = lowerBound;
end
if child2(i) < lowerBound
child2(i) = lowerBound;
end
if child1(i) > upperBound
child1(i) = upperBound;
end
if child2(i) > upperBound
child2(i) = upperBound;
end
end
end
function [nextPop, nextFit] = environmentalSelection(mixedPopulation, mixedFitness, popSize)
[frontIndices, ~] = NDSort(mixedFitness, length(mixedFitness));
nextPop = [];
nextFit = [];
% Fill the population with solutions from the Pareto fronts
for frontNum = 1:max(frontIndices)
front = find(frontIndices == frontNum);
if length(nextPop) + length(front) <= popSize
nextPop = [nextPop; mixedPopulation(front, :)];
nextFit = [nextFit; mixedFitness(front, :)];
else
remaining = popSize - length(nextPop);
if remaining > 0
frontsWithCrowding = frontCrowdingDistance(mixedPopulation(front, :), mixedFitness(front, :));
[~, crowdingOrder] = sort(frontsWithCrowding, 'descend');
nextPop = [nextPop; mixedPopulation(front(crowdingOrder(1:remaining)), :)];
nextFit = [nextFit; mixedFitness(front(crowdingOrder(1:remaining)), :)];
end
break;
end
end
end
function ranks = NDSort(fitnesses, n)
numSolutions = size(fitnesses, 1);
dominanceCounts = zeros(numSolutions, 1);
dominates = cell(numSolutions, 1);
for i = 1:numSolutions
for j = 1:numSolutions
if all(fitnesses(i,:) <= fitnesses(j,:)) && any(fitnesses(i,:) < fitnesses(j,:))
dominates{i} = [dominates{i} j];
elseif all(fitnesses(j,:) <= fitnesses(i,:)) && any(fitnesses(j,:) < fitnesses(i,:))
dominanceCounts(i) = dominanceCounts(i) + 1;
end
end
end
ranks = inf(numSolutions, 1);
rank = 1;
while sum(ranks < inf) < numSolutions
front = find(dominanceCounts == 0 & ranks == inf);
ranks(front) = rank;
for f = front'
dominanceCounts(dominates{f}) = dominanceCounts(dominates{f}) - 1;
end
rank = rank + 1;
end
end
function distances = frontCrowdingDistance(population, fitnesses)
numObjectives = size(fitnesses, 2);
numSolutions = size(fitnesses, 1);
distances = zeros(numSolutions, 1);
for m = 1:numObjectives
[~, order] = sort(fitnesses(:,m));
distances(order(1)) = inf;
distances(order(end)) = inf;
if fitnesses(order(1),m) == fitnesses(order(end),m)
continue;
end
for i = 2:numSolutions-1
distances(order(i)) = distances(order(i)) + ...
(fitnesses(order(i+1),m) - fitnesses(order(i-1),m)) / ...
(fitnesses(order(end),m) - fitnesses(order(1),m));
end
end
end
function dom = dominates(fit1, fit2)
dom = all(fit1 <= fit2) && any(fit1 < fit2);
end
Initialization: Variables and population are initialized. The population is generated randomly within the given bounds.
Evaluation: The evaluation function evaluatePopulation is designed for the ZDT1 problem.
Selection (Tournament Selection): A tournament selection is used where two individuals are chosen at random, and the one with better (lower) fitness wins.
Crossover and Mutation:
Environmental Selection: Combines parents and offspring, sorts according to Pareto-optimal front, and selects the next generation based on crowding distance for diversity.
Non-Dominated Sorting: Determines the Pareto front of the current population.
Crowding Distance: Used for maintaining diversity in the population by calculating the density of solutions surrounding a particular solution.
This implementation is a basic NSGA-II example and may lack some optimizations present in advanced versions. It's crucial to ensure you understand NSGA-II mechanics for effectively adapting the implementation to more complex problems or extending functionalities. Also, ensure your MATLAB development environment supports vectorized operations and plotting functions.
Let's refine the MATLAB implementation of NSGA-II for the ZDT1 problem, so you can test and run it. The code provided earlier was an outline and might not run directly due to potential undefined variables or functions. Here's a more structured and correct version of NSGA-II for the ZDT1 problem in MATLAB:
function nsga2_on_zdt1()
% Parameters
popSize = 100; % Population size
maxGen = 250; % Maximum number of generations
numVariables = 30; % Number of decision variables
lowerBound = 0.0; % Lower bound of decision variables
upperBound = 1.0; % Upper bound of decision variables
crossoverProb = 0.9; % Crossover probability
mutationProb = 1.0/numVariables; % Mutation probability
% Initialize population
population = rand(popSize, numVariables) * (upperBound - lowerBound) + lowerBound;
fitness = evaluatePopulation(population);
for gen = 1:maxGen
% Selection
matingPool = tournamentSelection(population, fitness, popSize);
% Crossover and Mutation
offspring = crossoverAndMutation(matingPool, crossoverProb, mutationProb, lowerBound, upperBound);
% Evaluate offspring
offspringFitness = evaluatePopulation(offspring);
% Combine and select the next generation
[population, fitness] = environmentalSelection([population; offspring], [fitness; offspringFitness], popSize);
% Display progress
fprintf('Generation %d completed\n', gen);
end
% Extract and plot Pareto front
paretoFront = population(NDSort(fitness, 1) == 1, :);
fitValues = evaluatePopulation(paretoFront);
plot(fitValues(:,1), fitValues(:,2), 'bo');
title('Pareto Front');
xlabel('f1');
ylabel('f2');
end
function fitness = evaluatePopulation(population)
n = size(population, 2);
x1 = population(:, 1);
g = 1.0 + 9.0 * sum(population(:, 2:end), 2) / (n - 1);
f1 = x1;
f2 = g .* (1 - sqrt(x1 ./ g));
fitness = [f1, f2];
end
function matingPool = tournamentSelection(population, fitness, popSize)
matingPool = zeros(size(population));
for i = 1:popSize
candidate1 = randi(popSize);
candidate2 = randi(popSize);
if dominates(fitness(candidate1, :), fitness(candidate2, :))
winner = candidate1;
else
winner = candidate2;
end
matingPool(i, :) = population(winner, :);
end
end
function offspring = crossoverAndMutation(matingPool, crossoverProb, mutationProb, lowerBound, upperBound)
[popSize, numVariables] = size(matingPool);
offspring = zeros(size(matingPool));
for i = 1:2:popSize
parent1 = matingPool(i, :);
parent2 = matingPool(mod(i, popSize) + 1, :);
if rand < crossoverProb
[offspring1, offspring2] = sbx(parent1, parent2, lowerBound, upperBound);
else
offspring1 = parent1;
offspring2 = parent2;
end
offspring1 = mutate(offspring1, mutationProb, lowerBound, upperBound);
offspring2 = mutate(offspring2, mutationProb, lowerBound, upperBound);
offspring(i, :) = offspring1;
if i + 1 <= popSize
offspring(i+1, :) = offspring2;
end
end
end
function [offspring1, offspring2] = sbx(parent1, parent2, lowerBound, upperBound)
eta = 20;
offspring1 = zeros(size(parent1));
offspring2 = zeros(size(parent2));
for i = 1:length(parent1)
if rand <= 0.5
if abs(parent1(i) - parent2(i)) > eps
if parent1(i) < parent2(i)
y1 = parent1(i);
y2 = parent2(i);
else
y1 = parent2(i);
y2 = parent1(i);
end
yl = lowerBound;
yu = upperBound;
randValue = rand;
beta = 1.0 + (2.0 * (y1 - yl) / (y2 - y1));
alpha = 2.0 - beta^(-(eta+1));
if randValue <= 1.0 / alpha
betaQ = (randValue * alpha)^(1.0 / (eta+1));
else
betaQ = (1.0 / (2.0 - randValue * alpha))^(1.0 / (eta+1));
end
c1 = 0.5 * ((y1 + y2) - betaQ * (y2 - y1));
beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1));
alpha = 2.0 - beta^(-(eta+1));
if randValue <= 1.0 / alpha
betaQ = (randValue * alpha)^(1.0 / (eta+1));
else
betaQ = (1.0 / (2.0 - randValue * alpha))^(1.0 / (eta+1));
end
c2 = 0.5 * ((y1 + y2) + betaQ * (y2 - y1));
if rand() <= 0.5
offspring1(i) = c2;
offspring2(i) = c1;
else
offspring1(i) = c1;
offspring2(i) = c2;
end
else
offspring1(i) = parent1(i);
offspring2(i) = parent2(i);
end
else
offspring1(i) = parent1(i);
offspring2(i) = parent2(i);
end
% Ensure variables are within bounds
offspring1(i) = max(min(offspring1(i), upperBound), lowerBound);
offspring2(i) = max(min(offspring2(i), upperBound), lowerBound);
end
end
function individual = mutate(individual, mutationProb, lowerBound, upperBound)
for i = 1:length(individual)
if rand < mutationProb
individual(i) = lowerBound + (upperBound - lowerBound) * rand;
end
end
end
function [nextPop, nextFit] = environmentalSelection(mixedPop, mixedFit, popSize)
[fronts, rank] = NDSort(mixedFit, length(mixedFit));
nextPop = [];
nextFit = [];
i = 1;
while size(nextPop, 1) + length(fronts{i}) <= popSize
nextPop = [nextPop; mixedPop(fronts{i}, :)];
nextFit = [nextFit; mixedFit(fronts{i}, :)];
i = i + 1;
end
remaining = popSize - size(nextPop, 1);
if remaining > 0
lastFront = fronts{i};
crowdingDistances = getCrowdingDistances(mixedFit(lastFront, :));
[~, sortedIndices] = sort(crowdingDistances, 'descend');
selected = lastFront(sortedIndices(1:remaining));
nextPop = [nextPop; mixedPop(selected, :)];
nextFit = [nextFit; mixedFit(selected, :)];
end
end
function [fronts, rank] = NDSort(fitnesses, n)
numSolutions = size(fitnesses, 1);
S = cell(numSolutions, 1);
front = cell(1);
nDom = zeros(numSolutions, 1);
for p = 1:numSolutions
for q = 1:numSolutions
if dominates(fitnesses(p,:), fitnesses(q,:))
S{p} = [S{p}, q];
elseif dominates(fitnesses(q,:), fitnesses(p,:))
nDom(p) = nDom(p) + 1;
end
end
if nDom(p) == 0
rank(p) = 1;
front{1} = [front{1}, p];
end
end
i = 1;
while ~isempty(front{i})
Q = [];
for p = front{i}
for q = S{p}
nDom(q) = nDom(q) - 1;
if nDom(q) == 0
rank(q) = i + 1;
Q = [Q, q];
end
end
end
i = i + 1;
front{i} = Q;
end
end
function crowdingDistances = getCrowdingDistances(frontFitness)
[N, M] = size(frontFitness);
crowdingDistances = zeros(N, 1);
for m = 1:M
[~, order] = sort(frontFitness(:,m));
crowdingDistances(order(1)) = inf;
crowdingDistances(order(end)) = inf;
for i = 2:N-1
crowdingDistances(order(i)) = crowdingDistances(order(i)) + ...
(frontFitness(order(i+1),m) - frontFitness(order(i-1),m)) / ...
(max(frontFitness(:,m)) - min(frontFitness(:,m)));
end
end
end
function b = dominates(f1, f2)
b = all(f1 <= f2) && any(f1 < f2);
end
f1 and f2 objectives for each individual.This script should run in MATLAB and generate a Pareto front plot for the ZDT1 problem. Make sure that your MATLAB path environment is set up correctly to run this code, and modify parameters if needed for specific testing scenarios.
Implementing NSGA-II in MATLAB for the ZDT1 problem requires careful setup, including population initialization, evaluation, selection, crossover, mutation, and the Pareto front plotting. The implementation needs to follow the NSGA-II framework, handling operations such as non-dominated sorting and crowding distance calculation.
Here's a MATLAB script properly implementing NSGA-II on the ZDT1 problem:
function nsga2_zdt1
% Parameters
popSize = 100; % Population size
maxGenerations = 250; % Maximum number of generations
numVars = 30; % Number of decision variables
lowerBound = 0.0; % Lower bound of decision variables
upperBound = 1.0; % Upper bound of decision variables
crossoverRate = 0.9; % Crossover probability
mutationRate = 1.0 / numVars; % Mutation probability
% Initialize population
population = lowerBound + (upperBound - lowerBound) .* rand(popSize, numVars);
fitness = calcFitness(population);
for gen = 1:maxGenerations
% Tournament selection
offspring = tournamentSelection(population, fitness, crossoverRate, mutationRate, lowerBound, upperBound);
% Calculate fitness of the offspring
offspringFitness = calcFitness(offspring);
% Combine and select next generation
[population, fitness] = nextGeneration(population, fitness, offspring, offspringFitness, popSize);
end
% Extract and plot the Pareto front
paretoFront = population(NDSort(fitness, 1) == 1, :);
paretoFitness = calcFitness(paretoFront);
plot(paretoFitness(:, 1), paretoFitness(:, 2), 'bo');
xlabel('f1');
ylabel('f2');
title('Pareto Front for ZDT1');
end
function fitness = calcFitness(population)
n = size(population, 2);
f1 = population(:, 1);
g = 1 + 9 .* sum(population(:, 2:end), 2) / (n - 1);
f2 = g .* (1 - sqrt(f1 ./ g));
fitness = [f1, f2];
end
function offspring = tournamentSelection(population, fitness, crossoverRate, mutationRate, lowerBound, upperBound)
popSize = size(population, 1);
[parentsIdx1, parentsIdx2] = deal(randi(popSize, popSize, 1), randi(popSize, popSize, 1));
parent1 = population(parentsIdx1, :);
parent2 = population(parentsIdx2, :);
offspring = zeros(size(population));
for i = 1:2:popSize
if rand < crossoverRate
[offspring1, offspring2] = sbx(parent1(i, :), parent2(i, :), lowerBound, upperBound);
else
offspring1 = parent1(i, :);
offspring2 = parent2(i, :);
end
offspring1 = mutate(offspring1, mutationRate, lowerBound, upperBound);
offspring2 = mutate(offspring2, mutationRate, lowerBound, upperBound);
offspring(i, :) = offspring1;
if i + 1 <= popSize
offspring(i+1, :) = offspring2;
end
end
end
function [offspring1, offspring2] = sbx(parent1, parent2, lowerBound, upperBound)
eta = 20;
offspring1 = zeros(size(parent1));
offspring2 = zeros(size(parent2));
for i = 1:length(parent1)
if rand <= 0.5
if abs(parent1(i) - parent2(i)) > eps
if parent1(i) < parent2(i)
y1 = parent1(i);
y2 = parent2(i);
else
y1 = parent2(i);
y2 = parent1(i);
end
yl = lowerBound;
yu = upperBound;
randValue = rand;
beta = 1.0 + (2.0 * (y1 - yl) / (y2 - y1));
alpha = 2.0 - beta^(-(eta+1));
if randValue <= 1.0 / alpha
betaQ = (randValue * alpha)^(1.0 / (eta+1));
else
betaQ = (1.0 / (2.0 - randValue * alpha))^(1.0 / (eta+1));
end
c1 = 0.5 * ((y1 + y2) - betaQ * (y2 - y1));
beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1));
alpha = 2.0 - beta^(-(eta+1));
if randValue <= 1.0 / alpha
betaQ = (randValue * alpha)^(1.0 / (eta+1));
else
betaQ = (1.0 / (2.0 - randValue * alpha))^(1.0 / (eta+1));
end
c2 = 0.5 * ((y1 + y2) + betaQ * (y2 - y1));
if rand() <= 0.5
offspring1(i) = c2;
offspring2(i) = c1;
else
offspring1(i) = c1;
offspring2(i) = c2;
end
else
offspring1(i) = parent1(i);
offspring2(i) = parent2(i);
end
else
offspring1(i) = parent1(i);
offspring2(i) = parent2(i);
end
offspring1(i) = max(lowerBound, min(offspring1(i), upperBound));
offspring2(i) = max(lowerBound, min(offspring2(i), upperBound));
end
end
function individual = mutate(individual, mutationRate, lowerBound, upperBound)
for i = 1:length(individual)
if rand < mutationRate
individual(i) = lowerBound + (upperBound - lowerBound) * rand;
end
end
end
function [newPop, newFit] = nextGeneration(pop, fit, offspring, offspringFit, popSize)
combinedPop = [pop; offspring];
combinedFit = [fit; offspringFit];
[sortedFronts, rank] = NDSort(combinedFit, size(combinedFit, 1));
newPop = [];
newFit = [];
for i = 1:length(sortedFronts)
currentFront = sortedFronts{i};
if length(newPop) + length(currentFront) <= popSize
newPop = [newPop; combinedPop(currentFront, :)];
newFit = [newFit; combinedFit(currentFront, :)];
else
remaining = popSize - size(newPop, 1);
crowdDistances = calcCrowdingDistance(combinedFit(currentFront, :));
[~, idx] = sort(crowdDistances, 'descend');
newPop = [newPop; combinedPop(currentFront(idx(1:remaining)), :)];
newFit = [newFit; combinedFit(currentFront(idx(1:remaining)), :)];
break;
end
end
end
function distances = calcCrowdingDistance(frontFitness)
numObjs = size(frontFitness, 2);
distances = zeros(size(frontFitness, 1), 1);
for m = 1:numObjs
[~, order] = sort(frontFitness(:, m));
distances(order(1)) = Inf;
distances(order(end)) = Inf;
minValue = min(frontFitness(:, m));
maxValue = max(frontFitness(:, m));
for i = 2:length(order) - 1
distances(order(i)) = distances(order(i)) + ...
(frontFitness(order(i + 1), m) - frontFitness(order(i - 1), m)) / ...
(maxValue - minValue);
end
end
end
function result = NDSort(fitness, n)
numSolutions = size(fitness, 1);
dominating = cell(numSolutions, 1);
dominatedCount = zeros(numSolutions, 1);
front = cell(1);
for p = 1:numSolutions
for q = 1:numSolutions
if dominates(fitness(p, :), fitness(q, :))
dominating{p} = [dominating{p}, q];
elseif dominates(fitness(q, :), fitness(p, :))
dominatedCount(p) = dominatedCount(p) + 1;
end
end
if dominatedCount(p) == 0
front{1} = [front{1}, p];
end
end
i = 1;
while ~isempty(front{i})
Q = [];
for p = front{i}
for q = dominating{p}
dominatedCount(q) = dominatedCount(q) - 1;
if dominatedCount(q) == 0
Q = [Q, q];
end
end
end
i = i + 1;
front{i} = Q;
end
result = front;
end
function b = dominates(ind1, ind2)
b = all(ind1 <= ind2) && any(ind1 < ind2);
end
.m file (e.g., nsga2_zdt1.m), and execute it in a MATLAB environment.This code adheres to the NSGA-II framework and should correctly optimize and plot the Pareto front for the ZDT1 problem. Make sure to validate the results visually to understand the convergence and distribution of the Pareto-optimal solutions.
Not yet included in a published release.