% 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
My code:
% Main script to run MOEMA, MOEA/D, and MOPSO optimization
clc;
clear;
close all;
% Set problem parameters
NPop = 100; % Population size
T = 200; % Number of iterations
dim = 30; % Number of decision variables
lb = zeros(1, dim); % Lower bound
ub = ones(1, dim); % Upper bound
disp('Optimization completed. Results saved to optimization_results.mat');
function [paretoFront, paretoSet, Trajectories, fitness_history, position_history] = MOEMA(NPop, T, lb, ub, dim, FITNESSFCN)
% Multi-Objective Evolutionary Mating Algorithm (MOEMA)
% MOEMA attempts to solve multi-objective problems of the following form:
% min F(X) = [f1(X), f2(X), ..., fm(X)] subject to: lb <= X <= ub
%
% FITNESSFCN - function handle of the multi-objective fitness function
% lb - lower bounds on X
% ub - upper bounds on X
% T - number of iterations
% NPop - size of the population (class size)
% paretoFront - set of non-dominated solutions in objective space
% paretoSet - set of non-dominated solutions in decision space
% Trajectories - best solution trajectory over iterations
% fitness_history - history of fitness values
% position_history - history of population positions
% 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];
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 = rand();
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
% 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.8; % Eqn (8) in the paper
pop_child = best_pop .* (1-K) + pop_child .* K; % Eqn (7) in the paper
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
if r < 0.2
if ~isempty(archive.pop)
temp1 = archive.pop(randi(size(archive.pop, 1)), :);
pop_child = rand(1, dim) .* temp1; % Eqn (9) in the paper
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
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
% 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
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
%% Main MOEA/D Function
function [paretoFront, paretoSet, fitness_history, position_history] = MOEAD(nVar, VarMin, VarMax, nPop, nArchive, MaxIt, T, CostFunction, crossover_params)
% Problem Definition
VarSize = [nVar, 1]; % Decision Variables Matrix Size
nObj = numel(CostFunction(unifrnd(VarMin, VarMax, VarSize))); % Number of Objectives
% Create Sub-problems
sp = CreateSubProblems(nObj, nPop, T);
% Empty Individual Template
empty_individual.Position = [];
empty_individual.Cost = [];
empty_individual.g = [];
empty_individual.IsDominated = [];
% Initialize Goal Point
z = zeros(nObj, 1);
% Create Initial Population
pop = repmat(empty_individual, nPop, 1);
for i = 1:nPop
pop(i).Position = unifrnd(VarMin, VarMax, VarSize);
pop(i).Cost = CostFunction(pop(i).Position);
z = min(z, pop(i).Cost); % Update goal point
end
for i = 1:nPop
pop(i).g = DecomposedCost(pop(i), z, sp(i).lambda);
end
% Determine Population Domination Status
pop = DetermineDomination(pop);
% Initialize Estimated Pareto Front (EP)
EP = pop(~[pop.IsDominated]);
% History variables for fitness and positions
fitness_history = zeros(nObj, MaxIt);
position_history = cell(nPop, MaxIt);
% Main Loop
for it = 1:MaxIt
for i = 1:nPop
% Reproduction (Crossover)
K = randsample(T, 2);
j1 = sp(i).Neighbors(K(1));
p1 = pop(j1);
j2 = sp(i).Neighbors(K(2));
p2 = pop(j2);
y = empty_individual;
y.Position = Crossover(p1.Position, p2.Position, crossover_params);
y.Cost = CostFunction(y.Position);
z = min(z, y.Cost); % Update goal point
% Update neighboring solutions
for j = sp(i).Neighbors
y.g = DecomposedCost(y, z, sp(j).lambda);
if y.g <= pop(j).g
pop(j) = y;
end
end
end
% Determine Population Domination Status
pop = DetermineDomination(pop);
ndpop = pop(~[pop.IsDominated]);
EP = [EP; ndpop]; %#ok<AGROW>
EP = DetermineDomination(EP);
EP = EP(~[EP.IsDominated]);
if numel(EP) > nArchive
Extra = numel(EP) - nArchive;
ToBeDeleted = randsample(numel(EP), Extra);
EP(ToBeDeleted) = [];
end
% Store fitness data and positions for this iteration
fitness_history(:, it) = mean([pop.Cost], 2); % Store average fitness
for i = 1:nPop
position_history{i, it} = pop(i).Position;
end
% Display Iteration Information
disp(['Iteration ' num2str(it) ': Number of Pareto Solutions = ' num2str(numel(EP))]);
end
% Prepare Results
paretoFront = [EP.Cost];
paretoSet = [EP.Position];
end
%% Helper Functions
% Plot Pareto Front
function PlotCosts(paretoFront)
plot(paretoFront(1,:), paretoFront(2,:), 'x');
xlabel('1^{st} Objective');
ylabel('2^{nd} Objective');
grid on;
end
% Check if one solution dominates another
function b = Dominates(x, y)
if isfield(x, 'Cost')
x = x.Cost;
end
if isfield(y, 'Cost')
y = y.Cost;
end
b = all(x <= y) && any(x < y);
end
% Determine Domination in the Population
function pop = DetermineDomination(pop)
nPop = numel(pop);
for i = 1:nPop
pop(i).IsDominated = false;
end
for i = 1:nPop
for j = i+1:nPop
if Dominates(pop(i), pop(j))
pop(j).IsDominated = true;
elseif Dominates(pop(j), pop(i))
pop(i).IsDominated = true;
end
end
end
end
% Decomposed Cost Calculation using Tchebycheff Approach
function g = DecomposedCost(individual, z, lambda)
if isfield(individual, 'Cost')
fx = individual.Cost;
else
fx = individual;
end
g = max(lambda .* abs(fx - z));
end
% Crossover Operation
function y = Crossover(x1, x2, params)
gamma = params.gamma;
VarMin = params.VarMin;
VarMax = params.VarMax;
alpha = unifrnd(-gamma, 1+gamma, size(x1));
y = alpha .* x1 + (1 - alpha) .* x2;
y = min(max(y, VarMin), VarMax);
end
% ZDT1 Objective Function
function y = zdt1(x)
n = length(x);
f1 = x(1);
g = 1 + (9/(n - 1)) * sum(x(2:end));
f2 = g * (1 - sqrt(f1 / g));
y = [f1, f2];
end
% ZDT Function for MOEA/D
function z = ZDT(x)
n = numel(x);
f1 = x(1);
g = 1 + 9 / (n-1) * sum(x(2:end));
h = 1 - sqrt(f1 / g);
f2 = g * h;
z = [f1; f2];
end
% Additional helper functions for MOEMA and MOEA/D (if needed)
% ... (Include any additional helper functions here)
% Hypervolume calculation
function hv = hypervolume(points, ref_point)
sorted_points = sortrows(points);
hv = 0;
for i = 1:size(sorted_points, 1)
if i == 1
area = (ref_point(1) - sorted_points(i, 1)) * (ref_point(2) - sorted_points(i, 2));
else
area = (sorted_points(i, 1) - sorted_points(i-1, 1)) * (ref_point(2) - sorted_points(i, 2));
end
hv = hv + area;
end
end
Certainly! To integrate your custom Multi-Objective Cost Function (multi_objective_cost_function) into your existing optimization framework, you'll need to make several key modifications to your main script. These changes involve updating the decision variable dimensions, adjusting the bounds, and ensuring that your optimization algorithms correctly utilize the new cost function with the provided dataSH.
Below is a step-by-step guide to modifying your code, along with the updated script.
1. Understanding the multi_objective_cost_function
Your multi_objective_cost_function is designed to handle:
Decision Variables (X): A 144-element vector representing 3 variables (T, L, IAQ) for each of the 48 periods.
Maximize User Comfort: ( \text{Objective 1} = -\text{CI_avg} ) (minimize the negative average comfort)
Minimize Energy Consumption: ( \text{Objective 2} = \text{EC_avg} )
2. Updating the Main Script
A. Define the Multi-Objective Cost Function
Instead of using zdt1 and ZDT, you'll leverage multi_objective_cost_function. Since it requires both X and dataSH, you can create anonymous functions to include dataSH as a fixed parameter.
B. Adjust Decision Variable Dimensions and Bounds
Given that you have 144 decision variables (3 variables for each of the 48 periods), update:
dim to 144
lb and ub to appropriately reflect the feasible ranges for each variable. (You'll need to set these based on your problem's constraints.)
C. Modify Optimization Algorithm Calls
Ensure that each optimization algorithm (MOEMA, MOEA/D, MOPSO) is provided with the correct function handle that includes dataSH.
D. Update Plot Labels and Titles
To reflect the new problem context, update plot titles and labels accordingly.
3. Complete Updated Code
Below is the fully updated main script incorporating all the necessary changes:
% Main script to run MOEMA, MOEA/D, and MOPSO optimization with Multi-Objective Cost Function
clc;
clear;
close all;
%% Data from UTHM
dataSH = [
% ... [Your 48x5 data matrix as provided]
% Ensure that dataSH is correctly defined here
];
%% Multi-Objective Cost Function
% (Assuming you have already defined multi_objective_cost_function as provided)
%% Set Problem Parameters
NPop = 100; % Population size for MOEMA
MOEAD_nPop = 200; % Population size for MOEA/D
T = 200; % Number of iterations/generations
dim = 144; % Number of decision variables (3 variables per 48 periods)
% Define lower and upper bounds for each decision variable
% Adjust these bounds based on the feasible ranges for T, L, IAQ
lb = zeros(1, dim); % Example: all variables >= 0
ub = ones(1, dim) * 1000; % Example: all variables <= 1000
% NOTE: Replace 1000 with appropriate upper bounds for your variables
%% Define Cost Functions with dataSH Included
MOEMA_CostFunction = @(x) multi_objective_cost_function(x, dataSH);
MOEAD_CostFunction = @(x) multi_objective_cost_function(x, dataSH);
MOPSO_CostFunction = @(x) multi_objective_cost_function(x, dataSH);
%% Run MOEMA
[paretoFront_MOEMA, ~, ~, ~, ~] = MOEMA(NPop, T, lb, ub, dim, MOEMA_CostFunction);
%% Run MOEA/D
nVar = dim;
VarMin = lb;
VarMax = ub;
nPop_MOEAD = MOEAD_nPop;
nArchive = 50;
MaxIt = T;
T_MOEAD = 15;
CostFunction = MOEAD_CostFunction;
crossover_params.gamma = 0.5;
crossover_params.VarMin = VarMin;
crossover_params.VarMax = VarMax;
[paretoFront_MOEAD, ~, ~, ~] = MOEAD(nVar, VarMin, VarMax, nPop_MOEAD, nArchive, MaxIt, T_MOEAD, CostFunction, crossover_params);
%% Run MOPSO
params.Np = 200; % Population size
params.Nr = 50; % Repository size
params.maxgen = T; % Maximum number of generations
params.W = 0.4; % Inertia weight
params.C1 = 2; % Particle personal best weight
params.C2 = 2; % Global best weight
params.ngrid = 20; % Number of grids per dimension for repository
params.maxvel = 5; % Maximum velocity (as a percentage of variable range)
params.u_mut = 0.5; % Uniform mutation percentage
MultiObj.nVar = dim;
MultiObj.var_min = lb';
MultiObj.var_max = ub';
MultiObj.fun = @(POS) multi_objective_cost_function_vectorized(POS, dataSH);
% Define a vectorized version of multi_objective_cost_function if possible for efficiency
REP_MOPSO = MOPSO(params, MultiObj);
paretoFront_MOPSO = REP_MOPSO.pos_fit;
%% Plot the Pareto Fronts
figure;
plot(paretoFront_MOEMA(:,1), paretoFront_MOEMA(:,2), 'ro', 'DisplayName', 'MOEMA');
hold on;
plot(paretoFront_MOEAD(1,:), paretoFront_MOEAD(2,:), 'bx', 'DisplayName', 'MOEA/D');
plot(paretoFront_MOPSO(:,1), paretoFront_MOPSO(:,2), 'g+', 'DisplayName', 'MOPSO');
xlabel('Objective 1: -CI_{avg}');
ylabel('Objective 2: EC_{avg}');
title('Pareto Fronts for Multi-Objective Optimization');
legend('Location', 'southwest');
% Optionally, remove the true Pareto front plot if it's not applicable to your custom objectives
% Or define a relevant true Pareto front for comparison
%% Create a Table for Comparison
MOEMA_solutions = size(paretoFront_MOEMA, 1);
MOEAD_solutions = size(paretoFront_MOEAD, 2);
MOPSO_solutions = size(paretoFront_MOPSO, 1);
MOEMA_min_obj1 = min(paretoFront_MOEMA(:,1));
MOEAD_min_obj1 = min(paretoFront_MOEAD(1,:));
MOPSO_min_obj1 = min(paretoFront_MOPSO(:,1));
MOEMA_min_obj2 = min(paretoFront_MOEMA(:,2));
MOEAD_min_obj2 = min(paretoFront_MOEAD(2,:));
MOPSO_min_obj2 = min(paretoFront_MOPSO(:,2));
comparisonTable = table(
[MOEMA_solutions; MOEAD_solutions; MOPSO_solutions],
[MOEMA_min_obj1; MOEAD_min_obj1; MOPSO_min_obj1],
[MOEMA_min_obj2; MOEAD_min_obj2; MOPSO_min_obj2],
'VariableNames', {'Number of Solutions', 'Min Objective1', 'Min Objective2'},
'RowNames', {'MOEMA', 'MOEA/D', 'MOPSO'}
);
disp(comparisonTable);
%% Calculate Performance Metrics
truePF = paretoFront_MOEMA; % If you have a known true Pareto front, define it accordingly
[GD_MOEMA, IGD_MOEMA, Spread_MOEMA, HV_MOEMA] = calculateMetrics(paretoFront_MOEMA, truePF);
[GD_MOEAD, IGD_MOEAD, Spread_MOEAD, HV_MOEAD] = calculateMetrics(paretoFront_MOEAD', truePF);
[GD_MOPSO, IGD_MOPSO, Spread_MOPSO, HV_MOPSO] = calculateMetrics(paretoFront_MOPSO, truePF);
%% Display Performance Metrics
disp('Performance Metrics:');
metrics_table = array2table([
GD_MOEMA, IGD_MOEMA, Spread_MOEMA, HV_MOEMA;
GD_MOEAD, IGD_MOEAD, Spread_MOEAD, HV_MOEAD;
GD_MOPSO, IGD_MOPSO, Spread_MOPSO, HV_MOPSO
], 'VariableNames', {'GD', 'IGD', 'Spread', 'HV'}, ...
'RowNames', {'MOEMA', 'MOEA/D', 'MOPSO'});
disp(metrics_table);
%% Plot Performance Metrics
figure;
subplot(2,2,1);
bar([GD_MOEMA, GD_MOEAD, GD_MOPSO]);
title('Generational Distance (GD)');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
ylabel('GD');
subplot(2,2,2);
bar([IGD_MOEMA, IGD_MOEAD, IGD_MOPSO]);
title('Inverted Generational Distance (IGD)');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
ylabel('IGD');
subplot(2,2,3);
bar([Spread_MOEMA, Spread_MOEAD, Spread_MOPSO]);
title('Spread Metric');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
ylabel('Spread');
subplot(2,2,4);
bar([HV_MOEMA, HV_MOEAD, HV_MOPSO]);
title('Hypervolume (HV)');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
ylabel('HV');
%% Save Results
save('optimization_results.mat', 'paretoFront_MOEMA', 'paretoFront_MOEAD', 'paretoFront_MOPSO', ...
'GD_MOEMA', 'IGD_MOEMA', 'Spread_MOEMA', 'HV_MOEMA', ...
'GD_MOEAD', 'IGD_MOEAD', 'Spread_MOEAD', 'HV_MOEAD', ...
'GD_MOPSO', 'IGD_MOPSO', 'Spread_MOPSO', 'HV_MOPSO');
disp('Optimization completed. Results saved to optimization_results.mat');
%% Define Necessary Functions Below
% Ensure that all helper functions (MOEMA, MOEAD, MOPSO, calculateMetrics, etc.) are below or in separate files
% Example of a Vectorized Multi-Objective Cost Function for MOPSO
function objectives = multi_objective_cost_function_vectorized(X, dataSH)
% X is an N x 144 matrix where each row is a solution
N = size(X,1);
objectives = zeros(N, 2);
for i = 1:N
objectives(i,:) = multi_objective_cost_function(X(i,:), dataSH);
end
end
% [Include all other helper functions and ensure they are compatible with the new cost function]
% For brevity, omitted here. Ensure all functions are updated to handle 144 variables.
4. Key Modifications Explained
A. Decision Variable Adjustment
Dimension (dim): Updated from 30 to 144 to accommodate 3 variables per each of the 48 periods.
dim = 144;
Bounds (lb and ub): Adjusted to match the required range for each variable. Replace 1000 with actual upper bounds based on the problem's context.
lb = zeros(1, dim); % Example lower bounds
ub = ones(1, dim) * 1000; % Example upper bounds
B. Cost Function Integration
Function Handles: Created anonymous functions that include dataSH when passing to optimization algorithms.
MOPSO Vectorization: For efficiency, especially with large populations, consider vectorizing the multi_objective_cost_function. An example multi_objective_cost_function_vectorized is provided. You may need to implement a fully vectorized version based on your function's capabilities.
Performance Metrics: Ensure that metrics like Generational Distance (GD), Inverted Generational Distance (IGD), Spread, and Hypervolume (HV) are correctly calculated based on the new objectives.
5. Additional Recommendations
Vectorization for Efficiency: Given the increased number of decision variables, especially in MOPSO, vectorizing the multi_objective_cost_function can significantly speed up computations.
Hyperparameter Tuning: With the increased problem size, consider adjusting populations sizes (NPop, MOEAD_nPop, params.Np) and other hyperparameters to ensure efficient convergence.
Validation: After implementing the changes, validate the optimization results to ensure that the multi_objective_cost_function is being correctly optimized and that the Pareto fronts make sense in the context of your problem.
Modularizing the Code: To enhance readability and maintainability, consider placing each optimization algorithm and helper function in separate files or clearly sectioned within the script.
Documentation: Update comments and documentation within the code to reflect the changes and provide clarity on how dataSH is utilized within the optimization process.
By following these modifications, your optimization framework should now effectively utilize the multi_objective_cost_function tailored to your specific dataset (dataSH), enabling more relevant and accurate optimization results for your problem domain.