Certainly! Below is the complete MATLAB code that performs multiple runs of the Multi-Objective Evolutionary Mating Algorithm (MOEMA) on the ZDT3 problem. It calculates and displays the following metrics for each run:
- Generational Distance (GD): Measures the average distance from the obtained Pareto front to the nearest point in the true Pareto front.
- Inverted Generational Distance (IGD): Measures the average distance from the true Pareto front to the nearest point in the obtained Pareto front.
- Convergence Metric: Assessed using GD and IGD to evaluate how close the obtained front is to the true Pareto front.
- Diversity Metric: Assessed using the spread of solutions to evaluate the diversity of the obtained Pareto front.
After completing all runs, the script computes and displays the best, average, median, and worst values for GD and IGD, along with overall convergence and diversity metrics.
Complete MATLAB Code
clc;
clear;
close all;
%% Parameters
NPop = 100; % Population size
T = 100; % Number of iterations
dim = 30; % Number of decision variables
lb = zeros(1, dim); % Lower bounds
ub = ones(1, dim); % Upper bounds
num_runs = 30; % Number of independent runs
%% Precompute True Pareto Front for ZDT3
x1 = linspace(0, 1, 500)';
x2 = 1 - sqrt(x1) - x1 .* sin(10 * pi * x1);
true_pareto_front = [x1, x2];
true_pareto_front = true_pareto_front(x2 >= 0, :); % Remove invalid points
%% Initialize Metrics Storage
GD_values = zeros(num_runs,1);
IGD_values = zeros(num_runs,1);
Spread_values = zeros(num_runs,1);
Convergence_values = zeros(num_runs,1);
Diversity_values = zeros(num_runs,1);
%% Run MOEMA Multiple Times
for run = 1:num_runs
fprintf('Run #%d\n', run);
% Run MOEMA
[paretoFront, ~, ~, ~, ~] = MOEMA(NPop, T, lb, ub, dim, @zdt3);
% Ensure Pareto front is non-dominated
paretoFront = unique(paretoFront, 'rows');
paretoFront = paretoFront(paretoFront(:,2) >= 0, :); % Remove invalid points
% Calculate GD and IGD
GD = compute_GD(paretoFront, true_pareto_front);
IGD = compute_IGD(paretoFront, true_pareto_front);
% Calculate Spread (Diversity)
spread = calculate_spread(paretoFront);
% Store Metrics
GD_values(run) = GD;
IGD_values(run) = IGD;
Spread_values(run) = spread;
% Convergence can be assessed using GD and IGD (here we take average)
Convergence_values(run) = (GD + IGD) / 2;
% Diversity metric can be directly the spread
Diversity_values(run) = spread;
fprintf(' GD: %.4f, IGD: %.4f, Spread: %.4f\n', GD, IGD, spread);
end
%% Compute Statistics
% Generational Distance (GD)
best_GD = min(GD_values);
average_GD = mean(GD_values);
median_GD = median(GD_values);
worst_GD = max(GD_values);
% Inverted Generational Distance (IGD)
best_IGD = min(IGD_values);
average_IGD = mean(IGD_values);
median_IGD = median(IGD_values);
worst_IGD = max(IGD_values);
% Convergence Metric (Average over runs)
average_Convergence = mean(Convergence_values);
% Diversity Metric (Average Spread over runs)
average_Diversity = mean(Diversity_values);
%% Display Metrics in a Table
MetricsTable = table( ...
[best_GD; average_GD; median_GD; worst_GD], ...
[best_IGD; average_IGD; median_IGD; worst_IGD], ...
'RowNames', {'Best GD','Average GD','Median GD','Worst GD', ...
'Best IGD','Average IGD','Median IGD','Worst IGD'}, ...
'VariableNames', {'GD', 'IGD'});
disp('---------------------------------------------------------------');
disp('Metrics Summary:');
disp('---------------------------------------------------------------');
disp(MetricsTable);
fprintf('---------------------------------------------------------------\n');
fprintf('Average Convergence Metric: %.4f\n', average_Convergence);
fprintf('Average Diversity Metric (Spread): %.4f\n', average_Diversity);
fprintf('---------------------------------------------------------------\n');
%% Plotting Pareto Fronts for the Last Run
figure;
plot(paretoFront(:,1), paretoFront(:,2), 'ro', 'DisplayName', 'MOEMA');
hold on;
plot(true_pareto_front(:,1), true_pareto_front(:,2), 'b-', 'DisplayName', 'True Pareto Front');
xlabel('f1');
ylabel('f2');
title(sprintf('MOEMA vs True Pareto Front for ZDT3 (Run #%d)', num_runs));
legend('show');
grid on;
%% Helper Functions
% Multi-Objective Evolutionary Mating Algorithm (MOEMA)
function [paretoFront, paretoSet, Trajectories, fitness_history, position_history] = MOEMA(NPop, T, lb, ub, dim, FITNESSFCN)
% Preallocation
fitness_history = zeros(NPop, T, 2); % Assuming 2 objectives
position_history = zeros(NPop, T, dim);
Trajectories = zeros(dim, T);
% Generation of initial population
pop = initialization(NPop, dim, ub, lb);
pop_dad = pop(1:NPop/2, :); % First half
pop_mum = pop(NPop/2+1:end, :); % Second half
% Evaluation of objective function for initialization
obj_dad = evaluate_population(pop_dad, FITNESSFCN);
obj_mum = evaluate_population(pop_mum, FITNESSFCN);
obj = [obj_dad; obj_mum];
% Initialize archive with non-dominated solutions
archive = update_archive([], [], pop, obj);
for gen = 1:T % Start iteration
k1 = randperm(NPop/2);
k2 = randperm(NPop/2);
k1x = pop_dad(k1, :);
k2x = pop_mum(k2, :);
for k = 1:NPop/2
% Mating process
Imates = 1 + (var(k1x(k, :)) - var(k2x(k, :))); % Eqn (4)
p = rand(1, dim); % Eqn (6)
r = rand();
if Imates >= 0
% Upper part
temp1 = p .* k1x(k, :);
temp2 = (1-p) .* k2x(k, :);
pop_child = temp1 + temp2;
else
% Lower part
temp1 = p .* k2x(k, :);
temp2 = (1-p) .* k1x(k, :);
pop_child = temp1 + temp2;
end
% Impact of best environment
if ~isempty(archive.pop)
best_pop = archive.pop(randi(size(archive.pop, 1)), :);
K = rand(1, dim) < 0.8; % Eqn (8)
pop_child = best_pop .* (1-K) + pop_child .* K; % Eqn (7)
end
% Bounding of the solution
pop_child = max(min(ub, pop_child), lb);
% Evaluate child
obj_child = FITNESSFCN(pop_child);
% Update population using non-dominated sorting
[pop_dad, obj_dad] = update_population(pop_dad, obj_dad, pop_child, obj_child, k);
[pop_mum, obj_mum] = update_population(pop_mum, obj_mum, pop_child, obj_child, k);
% Exploration process
if r < 0.2
if ~isempty(archive.pop)
temp1 = archive.pop(randi(size(archive.pop, 1)), :);
pop_child_exp = rand(1, dim) .* temp1; % Eqn (9)
pop_child_exp = max(min(ub, pop_child_exp), lb);
obj_child_exp = FITNESSFCN(pop_child_exp);
% Update population using non-dominated sorting
[pop_dad, obj_dad] = update_population(pop_dad, obj_dad, pop_child_exp, obj_child_exp, randi(NPop/2));
[pop_mum, obj_mum] = update_population(pop_mum, obj_mum, pop_child_exp, obj_child_exp, randi(NPop/2));
end
end
end
% Combine updated pool dad and mum
pop = [pop_dad; pop_mum];
obj = [obj_dad; obj_mum];
% Update archive
archive = update_archive(archive.pop, archive.obj, pop, obj);
% Record the history at each iteration
fitness_history(:, gen, :) = obj;
position_history(:, gen, :) = pop;
% Update Trajectories (using a random non-dominated solution)
if ~isempty(archive.pop)
Trajectories(:, gen) = archive.pop(randi(size(archive.pop, 1)), :)';
end
% Display progress
disp(['Iteration #', num2str(gen), ' completed. Archive size: ', num2str(size(archive.pop, 1))]);
end
% Return Pareto front and Pareto set
paretoFront = archive.obj;
paretoSet = archive.pop;
end
% Initialization Function
function pop = initialization(NPop, dim, ub, lb)
pop = rand(NPop, dim) .* (ub - lb) + lb;
end
% Evaluation Function
function obj = evaluate_population(pop, FITNESSFCN)
obj = zeros(size(pop, 1), 2); % Assuming 2 objectives
parfor i = 1:size(pop, 1)
obj(i, :) = FITNESSFCN(pop(i, :));
end
end
% Update Population Function
function [pop, obj] = update_population(pop, obj, child, child_obj, index)
if dominates(child_obj, obj(index, :))
pop(index, :) = child;
obj(index, :) = child_obj;
elseif ~dominates(obj(index, :), child_obj)
if rand() < 0.5
pop(index, :) = child;
obj(index, :) = child_obj;
end
end
end
% Update Archive Function
function archive = update_archive(archive_pop, archive_obj, pop, obj)
combined_pop = [archive_pop; pop];
combined_obj = [archive_obj; obj];
[is_dominated, ~] = pareto_dominance(combined_obj);
non_dominated = ~is_dominated;
archive.pop = combined_pop(non_dominated, :);
archive.obj = combined_obj(non_dominated, :);
end
% Pareto Dominance Function
function [is_dominated, domination_count] = pareto_dominance(objectives)
[n_solutions, n_objectives] = size(objectives);
is_dominated = false(n_solutions, 1);
domination_count = zeros(n_solutions, 1);
for i = 1:n_solutions
for j = i+1:n_solutions
if dominates(objectives(i, :), objectives(j, :))
is_dominated(j) = true;
domination_count(i) = domination_count(i) + 1;
elseif dominates(objectives(j, :), objectives(i, :))
is_dominated(i) = true;
domination_count(j) = domination_count(j) + 1;
end
end
end
end
% Dominance Check
function result = dominates(obj1, obj2)
result = all(obj1 <= obj2) && any(obj1 < obj2);
end
% ZDT3 Objective Function
function f = zdt3(x)
f1 = x(1);
g = 1 + 9 * sum(x(2:end)) / (length(x) - 1);
h = 1 - sqrt(f1 / g) - (f1 / g) * sin(10 * pi * f1);
f2 = g * h;
f = [f1, f2];
end
% Generational Distance (GD) Calculation
function GD = compute_GD(obtained_front, true_front)
distances = zeros(size(obtained_front, 1), 1);
for i = 1:size(obtained_front, 1)
distances(i) = min(sqrt(sum((true_front - obtained_front(i,:)).^2, 2)));
end
GD = mean(distances);
end
% Inverted Generational Distance (IGD) Calculation
function IGD = compute_IGD(obtained_front, true_front)
distances = zeros(size(true_front, 1), 1);
for i = 1:size(true_front, 1)
distances(i) = min(sqrt(sum((obtained_front - true_front(i,:)).^2, 2)));
end
IGD = mean(distances);
end
% Spread (Diversity) Calculation
function spread = calculate_spread(front)
sorted_front = sortrows(front, 1);
num_points = size(sorted_front, 1);
if num_points < 2
spread = 0;
return;
end
% Calculate distances between consecutive points
distances = sqrt(sum(diff(sorted_front).^2, 2));
spread = std(distances) / mean(distances);
end
Explanation of the Code
-
Parameters Section:
- NPop: Population size for MOEMA.
- T: Number of iterations.
- dim: Dimensionality of the decision variables.
- lb & ub: Lower and upper bounds for the decision variables.
- num_runs: Number of independent runs to perform for statistical analysis.
-
True Pareto Front Generation:
- The true Pareto front for the ZDT3 problem is generated and stored in
true_pareto_front. Points with negative second objective values are removed to ensure validity.
-
Metrics Storage Initialization:
- Arrays to store GD, IGD, Spread (Diversity), Convergence, and Diversity metrics for each run are initialized.
-
MOEMA Execution Loop:
- The MOEMA algorithm is executed
num_runs times.
- After each run, the obtained Pareto front is processed to ensure it's non-dominated and valid.
- GD and IGD are calculated using the helper functions
compute_GD and compute_IGD, respectively.
- Spread is calculated using the
calculate_spread function to assess diversity.
- Convergence is assessed as the average of GD and IGD for each run.
- Metrics for each run are stored and also printed to the console for progress tracking.
-
Statistics Calculation:
- After all runs, the script calculates the best, average, median, and worst values for GD and IGD across all runs.
- Convergence Metric: Calculated as the average of GD and IGD across all runs.
- Diversity Metric: Calculated as the average spread across all runs.
-
Displaying Metrics:
- The calculated metrics are neatly displayed in a table format using MATLAB's
table data structure.
- Additionally, the average convergence and diversity metrics are printed.
-
Plotting:
- The Pareto front from the last run is plotted alongside the true Pareto front for visual comparison.
-
Helper Functions:
Notes and Recommendations
-
Parallel Computing: The evaluate_population function uses a parfor loop to parallelize objective function evaluations. Ensure that MATLAB's Parallel Computing Toolbox is installed and configured. If not, replace parfor with for.
-
Diversity Metric: The spread (diversity) metric used here assesses the uniformity of the distribution of solutions. Depending on specific requirements, other diversity metrics like Hypervolume can also be implemented.
-
Convergence Metric: Currently, the convergence metric is defined as the average of GD and IGD. Depending on your analysis needs, you might want to treat GD and IGD separately or use alternative definitions.
-
Randomness: MOEMA involves randomness. For reproducible results, you can set the random seed at the beginning of each run using rng(run) within the loop.
-
Performance: Running multiple independent runs can be time-consuming. Consider optimizing the code further or utilizing MATLAB's parallel processing capabilities to distribute the runs across multiple workers.
This comprehensive script should provide you with detailed insights into the performance of MOEMA on the ZDT3 problem across multiple runs, enabling robust statistical analysis of convergence and diversity metrics.