modify the code to make it more aligned with standard NSGA-II implementations. The main areas that need improvement are the crossover operator (should use Simulated Binary Crossover - SBX), crowding distance calculation, and selection mechanism.

clc;
clear;
close all;

% Set problem parameters
NPop = 300;  % Population size
T = 500;     % Number of iterations
dim = 30;    % Number of decision variables
lb = zeros(1, dim);  % Lower bound
ub = ones(1, dim);   % Upper bound
num_runs = 10;          % Number of runs for statistical evaluation

% Update the metrics storage section at the beginning
GD_values = zeros(num_runs, 1);
IGD_values = zeros(num_runs, 1);
Spacing_values = zeros(num_runs, 1);
Spread_values = zeros(num_runs, 1);
SP_values = zeros(num_runs, 1);
DU_values = zeros(num_runs, 1);     % Distribution Uniformity




%% Run MOEMA Multiple Times
for run = 1:num_runs
    fprintf('Run #%d/%d\n', run, num_runs);
    
   % Run NSGA-II
[paretoFront, paretoSet] = NSGA2(NPop, T, lb, ub, dim);
    
    % Get True Pareto Front
    true_pareto = get_true_pareto();
    
% Update the metrics calculation section in the main loop
[GD_values(run), IGD_values(run), Spacing_values(run), Spread_values(run), ...
    SP_values(run), DU_values(run)] = calculate_metrics(paretoFront, true_pareto);
 
end

% Update the metrics array when displaying statistics
metrics = {GD_values, IGD_values, Spacing_values, Spread_values, SP_values, DU_values};
metric_names = {'GD', 'IGD', 'Spacing', 'Spread', 'Hypervolume', 'SP', 'DU'};

% Print results
fprintf('\nPerformance Metrics over %d runs:\n', num_runs);
for i = 1:length(metrics)
    fprintf('\n%s Statistics:\n', metric_names{i});
    fprintf('  Best    = %.4f\n', min(metrics{i}));
    fprintf('  Average = %.4f\n', mean(metrics{i}));
    fprintf('  Median  = %.4f\n', median(metrics{i}));
    fprintf('  Worst   = %.4f\n', max(metrics{i}));
    fprintf('  Std Dev = %.4f\n', std(metrics{i}));
end
%% Plot Results
% Plot Pareto Front
figure;
plot(paretoFront(:,1), paretoFront(:,2), 'ro', 'MarkerSize', 6, 'MarkerFaceColor', 'r');
hold on;
plot(true_pareto(:,1), true_pareto(:,2), 'b--', 'LineWidth', 1.5);
xlabel('f1');
ylabel('f2');
title('Pareto Front for ZDT1 using MOEMA');
legend('Obtained Pareto Front', 'True Pareto Front');
grid on;
hold off;

% Plot the results
figure;
plot(paretoFront(:,1), paretoFront(:,2), 'ro', 'DisplayName', 'NSGA-II');
xlabel('f1');
ylabel('f2');
title('NSGA-II Pareto Front for ZDT1');
legend('show');
grid on;

function [paretoFront, paretoSet] = NSGA2(NPop, T, lb, ub, dim)
    % Initialize population
    pop = initialization(NPop, dim, ub, lb);
    fitness = evaluate_population(pop, @zdt1);

    for gen = 1:T
        % Non-dominated sorting
        [fronts, ranks] = non_dominated_sort(fitness);
        
        % Create mating pool using tournament selection
        mating_pool = tournament_selection(pop, ranks, NPop);
        
        % Generate offspring using crossover and mutation
        offspring = crossover(mating_pool, 0.9, dim);
        offspring = mutation(offspring, 1/dim, dim);
        
        % Evaluate offspring
        offspring_fitness = evaluate_population(offspring, @zdt1);
        
        % Combine population and offspring
        comb_pop = [pop; offspring];
        comb_fitness = [fitness; offspring_fitness];
        
        % Non-dominated sorting on combined population
        [fronts, ~] = non_dominated_sort(comb_fitness);
        
        % Create new population
        [pop, fitness] = select_new_population(comb_pop, comb_fitness, fronts, NPop);
        
        % Display generation progress
        disp(['Generation #', num2str(gen), ' completed.']);
    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 = evaluate_population(pop, FITNESSFCN)
    fitness = zeros(size(pop, 1), 2);  % Assuming 2 objectives
    for i = 1:size(pop, 1)
        fitness(i, :) = FITNESSFCN(pop(i, :));
    end
end

function [fronts, rank] = non_dominated_sort(fitness)
    num_individuals = size(fitness, 1);
    domination_count = zeros(num_individuals, 1);
    dominated_set = cell(num_individuals, 1);
    rank = zeros(num_individuals, 1);

    fronts = cell(1);
    for i = 1:num_individuals
        for j = 1:num_individuals
            if i ~= j
                if dominates(fitness(i, :), fitness(j, :))
                    dominated_set{i} = [dominated_set{i}, j];
                elseif dominates(fitness(j, :), fitness(i, :))
                    domination_count(i) = domination_count(i) + 1;
                end
            end
        end
        
        if domination_count(i) == 0
            rank(i) = 1;
            fronts{1} = [fronts{1}, i];
        end
    end
    
    current_front = 1;
    while ~isempty(fronts{current_front})
        next_front = [];
        for i = fronts{current_front}
            for j = dominated_set{i}
                domination_count(j) = domination_count(j) - 1;
                if domination_count(j) == 0
                    rank(j) = current_front + 1;
                    next_front = [next_front, j];
                end
            end
        end
        current_front = current_front + 1;
        fronts{current_front} = next_front;
    end
    fronts = fronts(1:current_front-1);
end

function is_dominated = dominates(x, y)
    is_dominated = all(x <= y) && any(x < y);
end

function selected_pop = tournament_selection(pop, ranks, num_selected)
    selected_pop = zeros(num_selected, size(pop, 2));
    for i = 1:num_selected
        candidates = randperm(size(pop, 1), 2);
        if ranks(candidates(1)) < ranks(candidates(2))
            selected_pop(i, :) = pop(candidates(1), :);
        else
            selected_pop(i, :) = pop(candidates(2), :);
        end
    end
end

function offspring = crossover(pop, crossover_prob, num_vars)
    offspring = zeros(size(pop));
    for i = 1:2:size(pop, 1)
        if rand < crossover_prob
            parent1 = pop(i, :);
            parent2 = pop(i+1, :);
            cross_point = randi([1, num_vars-1], 1, 1);
            offspring(i, :) = [parent1(1:cross_point), parent2(cross_point+1:end)];
            offspring(i+1, :) = [parent2(1:cross_point), parent1(cross_point+1:end)];
        else
            offspring(i, :) = pop(i, :);
            offspring(i+1, :) = pop(i+1, :);
        end
    end
end

function mutated_pop = mutation(pop, mutation_prob, num_vars)
    eta_m = 20;  % Mutation distribution index
    mutated_pop = pop;
    for i = 1:size(pop, 1)
        for j = 1:num_vars
            if rand < mutation_prob
                r = rand;
                if r < 0.5
                    delta = (2 * r)^(1/(eta_m + 1)) - 1;
                else
                    delta = 1 - (2 * (1 - r))^(1/(eta_m + 1));
                end
                mutated_pop(i, j) = pop(i, j) + delta;
                mutated_pop(i, j) = min(max(mutated_pop(i, j), 0), 1);
            end
        end
    end
end

function [pop, fitness] = select_new_population(comb_pop, comb_fitness, fronts, NPop)
    pop = [];
    fitness = [];
    for i = 1:length(fronts)
        if size(pop, 1) + length(fronts{i}) > NPop
            break;
        end
        pop = [pop; comb_pop(fronts{i}, :)];
        fitness = [fitness; comb_fitness(fronts{i}, :)];
    end
    
    remaining = NPop - size(pop, 1);
    if remaining > 0
        selected_front = fronts{i};
        distances = crowding_distance(comb_fitness(selected_front, :));
        [~, sorted_indices] = sort(distances, 'descend');
        selected = selected_front(sorted_indices(1:remaining));
        pop = [pop; comb_pop(selected, :)];
        fitness = [fitness; comb_fitness(selected, :)];
    end
end

function distances = crowding_distance(fitness)
    num_individuals = size(fitness, 1);
    num_objectives = size(fitness, 2);
    distances = zeros(num_individuals, 1);
    
    for m = 1:num_objectives
        [sorted_values, sorted_idx] = sort(fitness(:, m));
        distances(sorted_idx(1)) = inf;
        distances(sorted_idx(end)) = inf;
        for i = 2:num_individuals-1
            if sorted_values(end) ~= sorted_values(1)
                distances(sorted_idx(i)) = distances(sorted_idx(i)) + ...
                    (sorted_values(i+1) - sorted_values(i-1)) / (sorted_values(end) - sorted_values(1));
            end
        end
    end
end


function f = zdt1(x)
    f1 = x(1);
    g = 1 + 9 * sum(x(2:end)) / (length(x) - 1);
    h = 1 - sqrt(f1 / g);
    f2 = g * h;
    f = [f1, f2];
end

function true_pareto = get_true_pareto()
    num_points = 100;
    f1 = linspace(0, 1, num_points)';
    f2 = 1 - sqrt(f1);
    true_pareto = [f1, f2];
end

%% Performance Metrics Functions

% Update the calculate_metrics function
function [GD, IGD, Spacing, Spread, SP, DU] = calculate_metrics(obtained_pf, true_pf)
    GD = generational_distance(obtained_pf, true_pf);
    IGD = inverted_generational_distance(obtained_pf, true_pf);
    Spacing = spacing_metric(obtained_pf);
    Spread = spread_metric(obtained_pf, true_pf);
    SP = sigma_spacing(obtained_pf);
    DU = distribution_uniformity(obtained_pf);
end

function gd = generational_distance(obtained_pf, true_pf)
    if isempty(obtained_pf)
        gd = Inf;
        return;
    end
    
    distances = zeros(size(obtained_pf, 1), 1);
    for i = 1:size(obtained_pf, 1)
        dist_to_true = sqrt(sum((true_pf - obtained_pf(i,:)).^2, 2));
        distances(i) = min(dist_to_true);
    end
    
    p = 2;
    gd = (sum(distances.^p)/size(obtained_pf, 1))^(1/p);
end

function igd = inverted_generational_distance(obtained_pf, true_pf)
    if isempty(obtained_pf)
        igd = Inf;
        return;
    end
    
    distances = zeros(size(true_pf, 1), 1);
    for i = 1:size(true_pf, 1)
        dist_to_obtained = sqrt(sum((obtained_pf - true_pf(i,:)).^2, 2));
        distances(i) = min(dist_to_obtained);
    end
    
    p = 2;
    igd = (sum(distances.^p)/size(true_pf, 1))^(1/p);
end

function spacing = spacing_metric(obtained_pf)
    if size(obtained_pf, 1) < 2
        spacing = Inf;
        return;
    end
    
    n = size(obtained_pf, 1);
    distances = zeros(n, 1);
    
    for i = 1:n
        min_dist = Inf;
        for j = 1:n
            if i ~= j
                dist = sqrt(sum((obtained_pf(i,:) - obtained_pf(j,:)).^2));
                min_dist = min(min_dist, dist);
            end
        end
        distances(i) = min_dist;
    end
    
    d_bar = mean(distances);
    spacing = sqrt(sum((distances - d_bar).^2)/(n-1));
end

function spread = spread_metric(obtained_pf, true_pf)
    if size(obtained_pf, 1) < 2
        spread = Inf;
        return;
    end
    
    [~, idx] = sort(obtained_pf(:,1));
    obtained_pf = obtained_pf(idx,:);
    
    df = zeros(1, 2);
    for i = 1:2
        obtained_extreme = obtained_pf(i,:);
        true_extreme = true_pf(i,:);
        df(i) = sqrt(sum((obtained_extreme - true_extreme).^2));
    end
    
    distances = sqrt(sum(diff(obtained_pf).^2, 2));
    d_bar = mean(distances);
    
    spread = (sum(df) + sum(abs(distances - d_bar))) / (sum(df) + size(obtained_pf,1) * d_bar);
end


% Add the new metric functions
function sp = sigma_spacing(obtained_pf)
    if size(obtained_pf, 1) < 2
        sp = Inf;
        return;
    end
    
    n = size(obtained_pf, 1);
    d = zeros(n, 1);
    
    % Calculate distances between consecutive solutions
    for i = 1:n
        min_dist = Inf;
        for j = 1:n
            if i ~= j
                % Euclidean distance between solutions
                dist = sqrt(sum((obtained_pf(i,:) - obtained_pf(j,:)).^2));
                min_dist = min(min_dist, dist);
            end
        end
        d(i) = min_dist;
    end
    
    % Calculate mean distance
    d_bar = mean(d);
    
    % Calculate SP metric
    sp = sqrt(sum((d - d_bar).^2) / (n - 1));
end



% Add the Distribution Uniformity metric function
function du = distribution_uniformity(obtained_pf)
    if size(obtained_pf, 1) < 3
        du = 0;
        return;
    end
    
    % Sort solutions by first objective
    [~, idx] = sort(obtained_pf(:,1));
    sorted_pf = obtained_pf(idx,:);
    
    n = size(sorted_pf, 1);
    distances = zeros(n-1, 1);
    
    % Calculate Euclidean distances between consecutive solutions
    for i = 1:(n-1)
        distances(i) = sqrt(sum((sorted_pf(i+1,:) - sorted_pf(i,:)).^2));
    end
    
    % Calculate mean distance
    mean_dist = mean(distances);
    
    % Calculate standard deviation of distances
    std_dist = std(distances);
    
    % Calculate coefficient of variation (CV)
    cv = std_dist / mean_dist;
    
    % Calculate Distribution Uniformity
    % DU ranges from 0 (poor uniformity) to 1 (perfect uniformity)
    du = 1 / (1 + cv);
    
    % Alternative formulation (uncomment if you prefer):
    % du = exp(-cv);  % This also gives values between 0 and 1
end