should i improve crowding distance?
% run_MOEMA_MultiObjective.m
% Comprehensive script to run MOEMA optimization for Smart Building Comfort and Energy Consumption

%% ------------------ Initialization ------------------

clc;
clear;
close all;

% ------------------ Data Initialization ------------------

% Data from UTHM 
% Columns: Time_instance, Temp_(F), Temp_(C), lux, IAQ
dataSH = [    
    1.0000   60.0000   15.5600  711.0000  610.0000
    2.0000   65.0000   18.3300  717.0000  670.0000
    3.0000   67.0000   19.4400  718.0000  650.0000
    4.0000   66.0000   18.8900  717.0000  640.0000
    5.0000   67.0000   19.4400  700.0000  600.0000
    6.0000   63.0000   17.2200  713.0000  620.0000
    7.0000   62.0000   16.6700  724.0000  670.0000
    8.0000   81.0000   27.2200  710.0000  920.0000
    9.0000   80.0000   26.6700  914.0000  920.0000
   10.0000   81.0000   27.2200  900.0000  960.0000
   11.0000   83.0000   28.3300  897.0000  900.0000
   12.0000   80.0000   26.6700  895.0000  930.0000
   13.0000   79.0000   26.1100  904.0000  950.0000
   14.0000   82.0000   27.7800  903.0000  960.0000
   15.0000   81.0000   27.2200  906.0000  970.0000
   16.0000   80.0000   26.6700  898.0000  925.0000
   17.0000   66.0000   18.8900  728.0000  610.0000
   18.0000   63.0000   17.2200  703.0000  670.0000
   19.0000   66.0000   18.8900  714.0000  630.0000
   20.0000   66.0000   18.8900  721.0000  645.0000
   21.0000   66.0000   18.8900  722.0000  650.0000
   22.0000   67.0000   19.4400  703.0000  600.0000
   23.0000   66.0000   18.8900  701.0000  670.0000
   24.0000   81.0000   27.2200  728.0000  980.0000
   25.0000   81.0000   27.2200  891.0000  930.0000
   26.0000   82.0000   27.7800  906.0000  948.0000
   27.0000   80.0000   26.6700  901.0000  965.0000
   28.0000   81.0000   27.2200  901.0000  916.0000
   29.0000   79.0000   26.1100  915.0000  900.0000
   30.0000   83.0000   28.3300  914.0000  960.0000
   31.0000   79.0000   26.1100  890.0000  970.0000
   32.0000   81.0000   27.2200  912.0000  930.0000
   33.0000   65.0000   18.3300  717.0000  610.0000
   34.0000   67.0000   19.4400  714.0000  620.0000
   35.0000   65.0000   18.3300  724.0000  670.0000
   36.0000   67.0000   19.4400  726.0000  680.0000
   37.0000   66.0000   18.8900  723.0000  650.0000
   38.0000   64.0000   17.7800  726.0000  660.0000
   39.0000   65.0000   18.3300  708.0000  640.0000
   40.0000   80.0000   26.6700  712.0000  900.0000
   41.0000   83.0000   28.3300  917.0000  910.0000
   42.0000   79.0000   26.1100  905.0000  920.0000
   43.0000   82.0000   27.7800  893.0000  980.0000
   44.0000   80.0000   26.6700  920.0000  940.0000
   45.0000   81.0000   27.2200  913.0000  950.0000
   46.0000   81.0000   27.2200  905.0000  940.0000
   47.0000   82.0000   27.7800  896.0000  970.0000
   48.0000   80.0000   26.6700  898.0000  980.0000
];

% ------------------ MOEMA Parameters ------------------

% Number of decision variables: 3 per period for 48 periods
dim = 144;

% Population size and number of iterations
NPop = 50;  % Population size
T = 500;     % Number of iterations

% Define lower and upper bounds for each variable
% Each period has T, L, IAQ variables with specific bounds
lb = zeros(1, dim);
ub = zeros(1, dim);

% Define bounds per variable type
% T: Temperature [20, 25.56]
% L: Light [720, 880]
% IAQ: IAQ [700, 880]

% Assign bounds for each variable in the decision vector
for k = 1:48
    idx = 3*(k-1) + 1;
    lb(idx) = 20;       % Temperature lower bound
    ub(idx) = 25.56;    % Temperature upper bound
    
    lb(idx+1) = 720;    % Light lower bound
    ub(idx+1) = 880;    % Light upper bound
    
    lb(idx+2) = 700;    % IAQ lower bound
    ub(idx+2) = 880;    % IAQ upper bound
end


% Number of runs
num_runs = 20;

% Initialize arrays to store Pareto fronts, Pareto sets, and spacing metrics
all_paretoFronts = cell(1, num_runs);
all_paretoSets = cell(1, num_runs);
spacing_metrics = zeros(1, num_runs);


% ------------------ Define Fitness Function ------------------

% Define the fitness function handle with dataSH
fitness_fcn = @(X) multi_objective_cost_function(X, dataSH);

% ------------------ Run MOEMA ------------------
% Run MOEMA optimization 10 times
for i = 1:num_runs
    disp(['Run ', num2str(i), ' of ', num2str(num_runs)]);
    
    % Run MOEMA optimization
    [paretoFront, paretoSet, Trajectories, fitness_history, position_history, spacing] = MOEMA(NPop, T, lb, ub, dim, fitness_fcn);
    
  % Store results for this run
    all_paretoFronts{i} = paretoFront;
    all_paretoSets{i} = paretoSet;
    spacing_metrics(i) = spacing;
    
end

% Find the run with the best (lowest) spacing metric
[~, best_run_index] = min(spacing_metrics);

% Get the best Pareto front and set from the best run
best_paretoFront = all_paretoFronts{best_run_index};
best_paretoSet = all_paretoSets{best_run_index};

% Plot the Pareto front for the best run
figure;
plot(best_paretoFront(:,1), best_paretoFront(:,2), 'ro', 'MarkerSize',8, 'LineWidth',1.5);
xlabel('-Average Comfort Index');
ylabel('Average Energy Consumption');
title('Best Pareto Front for Smart Building Optimization using MOEMA');
grid on;
set(gca, 'FontSize', 12);

% First, find the best balanced solution from Pareto front
% Convert -CI_avg back to CI_avg
CI_values = -best_paretoFront(:,1);
EC_values = best_paretoFront(:,2);

% Normalize the values
CI_norm = (CI_values - min(CI_values)) / (max(CI_values) - min(CI_values));
EC_norm = (EC_values - min(EC_values)) / (max(EC_values) - min(EC_values));

% Find the solution closest to ideal point (1,0)
distances = sqrt((1-CI_norm).^2 + EC_norm.^2);
[~, best_idx] = min(distances);

% Get the best solution settings
optimized_solution = best_paretoSet(best_idx, :);  % 1x144 vector

% Extract optimized settings for each period
optimized_settings = reshape(optimized_solution, 3, 48)';  % 48x3 matrix: [T, L, IAQ]

% Original settings from dataSH
original_temp = dataSH(:,3);   % Temperature in C
original_lux = dataSH(:,4);    % lux
original_IAQ = dataSH(:,5);    % IAQ

% Optimized settings from the best balanced solution
optimized_temp = optimized_settings(:,1);
optimized_lux = optimized_settings(:,2);
optimized_IAQ = optimized_settings(:,3);

% Desired values
desired_temp = 22.78;  % As per cost function
desired_lux = 800;     % As per cost function
desired_IAQ = 800;     % As per cost function

% Create a time vector for 48 periods
time = dataSH(:,1);  % Assuming time instance is from 1 to 48

% Temperature Plot
figure;
plot(time, original_temp, 'b-', 'LineWidth',1.5); hold on;
plot(time, optimized_temp, 'r--', 'LineWidth',1.5);
yline(desired_temp, 'g:', 'LineWidth',1.5);
xlabel('Time Instance');
ylabel('Temperature (°C)');
title('Temperature Before and After Optimization (Best Balanced Solution)');
legend('Original', 'Optimized', 'Desired', 'Location', 'best');
grid on;
set(gcf, 'Position', [100, 100, 800, 400]);  % Set window size

% Light Level Plot
figure;
plot(time, original_lux, 'b-', 'LineWidth',1.5); hold on;
plot(time, optimized_lux, 'r--', 'LineWidth',1.5);
yline(desired_lux, 'g:', 'LineWidth',1.5);
xlabel('Time Instance');
ylabel('Light Level (lux)');
title('LUX Before and After Optimization (Best Balanced Solution)');
legend('Original', 'Optimized', 'Desired', 'Location', 'best');
grid on;
set(gcf, 'Position', [200, 200, 800, 400]);  % Set window size

% IAQ Plot
figure;
plot(time, original_IAQ, 'b-', 'LineWidth',1.5); hold on;
plot(time, optimized_IAQ, 'r--', 'LineWidth',1.5);
yline(desired_IAQ, 'g:', 'LineWidth',1.5);
xlabel('Time Instance');
ylabel('IAQ');
title('IAQ Before and After Optimization (Best Balanced Solution)');
legend('Original', 'Optimized', 'Desired', 'Location', 'best');
grid on;
set(gcf, 'Position', [300, 300, 800, 400]);  % Set window size

% Display metrics for the best balanced solution
fprintf('\nBest Balanced Solution Metrics:\n');
fprintf('Comfort Index: %.5f\n', CI_values(best_idx));
fprintf('Energy Consumption: %.2f\n', EC_values(best_idx));

% ------------------ plot for the best pareto ------------------
figure;
% Plot all Pareto front points in red
plot(best_paretoFront(:,1), best_paretoFront(:,2), 'ro', 'MarkerSize',8, 'LineWidth',1.5);
hold on;
% Plot the balanced solution point in green
plot(best_paretoFront(best_idx,1), best_paretoFront(best_idx,2), 'go', 'MarkerSize',12, 'LineWidth',2, 'MarkerFaceColor','g');
xlabel('-Average Comfort Index');
ylabel('Average Energy Consumption');
title('Pareto Front for Smart Building Optimization using MOEMA');
legend('Pareto Front', 'Balanced Solution', 'Location', 'best');
grid on;
set(gca, 'FontSize', 12);

% ------------------ Display Metrics ------------------

% Calculate statistics
best_spacing = min(spacing_metrics);
avg_spacing = mean(spacing_metrics);
median_spacing = median(spacing_metrics);
worst_spacing = max(spacing_metrics);
std_dev_spacing = std(spacing_metrics);

% Display results
fprintf('Best Spacing: %.4f\n', best_spacing);
fprintf('Average Spacing: %.4f\n', avg_spacing);
fprintf('Median Spacing: %.4f\n', median_spacing);
fprintf('Worst Spacing: %.4f\n', worst_spacing);
fprintf('Standard Deviation of Spacing: %.4f\n', std_dev_spacing);

%% ------------------ Functions ------------------

% ---------- Multi-Objective Cost Function ----------
function objectives = multi_objective_cost_function(X, dataSH)
    % MULTI_OBJECTIVE_COST_FUNCTION Evaluates user comfort and energy consumption.
    %
    % This function is designed for multi-objective optimization with two objectives:
    %   1. Maximize User Comfort (to be minimized as -CI_avg)
    %   2. Minimize Energy Consumption (EC_avg)
    %
    % Inputs:
    %   X      - A vector of decision variables for 48 periods, structured as:
    %            [T1, L1, IAQ1, T2, L2, IAQ2, ..., T48, L48, IAQ48]
    %   dataSH - A 48x5 matrix where:
    %            dataSH(:,3) = Temperature coefficients (Tc)
    %            dataSH(:,4) = Light coefficients (Lc)
    %            dataSH(:,5) = IAQ coefficients (IAQc)
    %
    % Output:
    %   objectives - A 2-element vector:
    %                [ -Average Comfort Index, Average Energy Consumption ]
    
    % Ensure that X has the correct length
    if length(X) ~= 144
        error('Decision vector X must have 144 elements (3 variables per 48 periods).');
    end
    
    % Weight coefficients for comfort components
    p1 = 1/3; % Temperature Weight
    p2 = 1/3; % Light Weight
    p3 = 1/3; % IAQ Weight
    
    % Desired setpoints for comfort
    Td = 22.78; % Desired Temperature (°C)
    Ld = 800;   % Desired Light Level (lux)
    Id = 800;   % Desired IAQ Level
    
    % Energy consumption weights
    pT = 9; % Temperature Energy Consumption Weight
    pL = 1; % Light Energy Consumption Weight
    pI = 1; % IAQ Energy Consumption Weight
    
    % Extract coefficients from dataSH for all 48 periods
    Tc = dataSH(:,3)'; % Temperature coefficients (1x48 vector)
    Lc = dataSH(:,4)'; % Light coefficients (1x48 vector)
    Ic = dataSH(:,5)'; % IAQ coefficients (1x48 vector)
    
    % Initialize vectors to store metrics for each period
    CI = zeros(48,1);    % Comfort Index for each period
    EC = zeros(48,1);    % Energy Consumption for each period
    
    % Loop through each of the 48 periods to compute metrics
    for k = 1:48
        % Extract decision variables for period k
        Tk = X(3*k-2); % Temperature setting
        Lk = X(3*k-1); % Light setting
        Ik = X(3*k);   % IAQ setting
        
        % --- Calculate Comfort Index Components ---
        Ti = 1 - ((Tk - Td) / Tc(k))^2;
        Li = 1 - ((Lk - Ld) / Lc(k))^2;
        Ii = 1 - ((Ik - Id) / Ic(k))^2;
        CI(k) = p1 * Ti + p2 * Li + p3 * Ii;
        
        % --- Calculate Energy Consumption ---
        ET = pT * abs(Tk - Tc(k));
        EL = pL * abs(Lk - Lc(k));
        EI = pI * abs(Ik - Ic(k));
        EC(k) = ET + EL + EI;
    end
    
    % --- Aggregate Metrics Over All Periods ---
    CI_avg = mean(CI);   % Average Comfort Index
    EC_avg = mean(EC);   % Average Energy Consumption
    
    % --- Prepare Objectives for Multi-Objective Optimization ---
    % Objective 1: Maximize User Comfort -> Minimize (-CI_avg)
    % Objective 2: Minimize Energy Consumption -> Minimize (EC_avg)
    objectives = [-CI_avg, EC_avg];
end

function [paretoFront, paretoSet, Trajectories, fitness_history, position_history, spacing] = MOEMA(NPop, T, lb, ub, dim, FITNESSFCN)
  % Multi-Objective Evolutionary Mating Algorithm (MOEMA) with improvements

% 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, :);  % Eqn (1) in the paper
pop_mum = pop(NPop/2+1:end, :); % Eqn (2) in the paper

% 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) in the paper
        p = randn(1, dim);  % Eqn (6) in the paper
        r = levy_flights(1, dim);  % Using Levy flights
        
        if Imates >= 0  % Upper part of Eqn (5) in the paper
            temp1 = p .* k1x(k, :);
            temp2 = (1-p) .* k2x(k, :);
            pop_child = temp1 + temp2;
        else  % Lower part of Eqn (5) in the paper
            temp1 = p .* k2x(k, :);
            temp2 = (1-p) .* k1x(k, :);
            pop_child = temp1 + temp2;
        end
        
        % Enhanced Impact of best environment (using random non-dominated solution)
        if ~isempty(archive.pop)
            best_pop = archive.pop(randi(size(archive.pop, 1)), :);
            K = rand(1, dim) < 0.1;  % Eqn (8) in the paper
            pop_child = best_pop .* (1-K) + pop_child .* K;  % Eqn (7) in the paper
        end
        
                % Mutation operator
            if rand() < 0.1
                % Special handling for x1
                if rand() < 0.5
                    pop_child(1) = pop_child(1) + randn() * 0.1;
                    pop_child(1) = max(0, min(1, pop_child(1)));
                end
                % Regular mutation for other variables
                mutation_idx = rand(1, dim-1) < 0.1;
                pop_child(2:end) = pop_child(2:end) + mutation_idx .* randn(1, dim-1) * 0.1;
            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, k1(k));
        [pop_mum, obj_mum] = update_population(pop_mum, obj_mum, pop_child, obj_child, k2(k));
        
        % Exploration process with levy flight
        if rand() < 0.9
            if ~isempty(archive.pop)
                temp1 = archive.pop(randi(size(archive.pop, 1)), :);
                pop_child = levy_flights(1, dim) .* temp1;  % Exploring with Levy flights
                pop_child = max(min(ub, pop_child), lb);
                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, randi(NPop/2));
                [pop_mum, obj_mum] = update_population(pop_mum, obj_mum, pop_child, obj_child, 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 every 10 iterations
    if mod(gen, 50) == 0
        disp(['Iteration #', num2str(gen), ' completed. Archive size: ', num2str(size(archive.pop, 1))]);
    end
end

% Return Pareto front and Pareto set
paretoFront = archive.obj;
paretoSet = archive.pop;

 % Calculate spacing metric
    spacing = spacing_metric(paretoFront);
end

% ---------- Spacing Metric Function ----------
function spacing = spacing_metric(obtained_pf)
    if size(obtained_pf, 1) < 2
        spacing = Inf;
        return;
    end
    
    n = size(obtained_pf, 1);
    d = zeros(n, 1);
    
    % Calculate di for each solution
    for i = 1:n
        % Calculate distances to all other solutions
        min_dist = Inf;
        for j = 1:n
            if i ~= j
                % Calculate |f1(x) - f1(x')| + |f2(x) - f2(x')|
                dist = abs(obtained_pf(i,1) - obtained_pf(j,1)) + ...
                       abs(obtained_pf(i,2) - obtained_pf(j,2));
                min_dist = min(min_dist, dist);
            end
        end
        d(i) = min_dist;
    end
    
    % Calculate mean of distances
    d_bar = mean(d);
    
    % Calculate spacing metric SP
    spacing = sqrt(sum((d_bar - d).^2) / (n - 1));
end


% Helper Functions

function pop = initialization(NPop, dim, ub, lb)
    pop = rand(NPop, dim) .* (ub - lb) + lb;
end

function obj = evaluate_population(pop, FITNESSFCN)
    obj = zeros(size(pop, 1), 2);  % Assuming 2 objectives
    for i = 1:size(pop, 1)
        obj(i, :) = FITNESSFCN(pop(i, :));
    end
end

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

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, :);
    archive_size_max =1000;
    % Enhanced crowding distance (using NSGA-II inspired technique)
    if size(archive.pop, 1) > archive_size_max
        crowding_distances = calculate_crowding_distances(archive.obj);
        [~, sorted_indices] = sort(crowding_distances, 'descend');
        archive.pop = archive.pop(sorted_indices(1:archive_size_max), :);
        archive.obj = archive.obj(sorted_indices(1:archive_size_max), :);
    end
end

function distances = calculate_crowding_distances(objectives)
    num_solutions = size(objectives, 1);
    distances = zeros(num_solutions, 1);

    for m = 1:size(objectives, 2)
        [values, idx] = sort(objectives(:, m));
        distances(idx(1)) = inf;
        distances(idx(end)) = inf;

        for i = 2:num_solutions-1
            distances(idx(i)) = distances(idx(i)) + ...
                (values(i+1) - values(i-1)) / (max(values) - min(values));
        end
    end
end

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

function result = dominates(obj1, obj2)
    result = all(obj1 <= obj2) && any(obj1 < obj2);
end

function steps = levy_flights(n, dim, beta)
    % Generates n Levy flight steps in dim dimensions based on Mantegna's algorithm
    if nargin < 3
        beta = 1.5;
    end
    sigma_u = (gamma(1 + beta) * sin(pi * beta / 2) / ...
        (gamma((1 + beta) / 2) * beta * 2^((beta - 1) / 2)))^(1/beta);
    u = random('Normal', 0, sigma_u, n, dim);
    v = random('Normal', 0, 1, n, dim);
    steps = u ./ abs(v).^(1 / beta);
end