can you change the zdt1 and zdt to the Multi-Objective Cost Function that i provided:
Multi-Objective Cost Function:
% ---------- 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
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! I'll help you integrate your custom multi_objective_cost_function into your existing optimization framework, replacing the default ZDT1 and ZDT functions. Here's a step-by-step guide along with the updated MATLAB code to achieve this:
1. Understanding the Integration Requirements
Your custom multi_objective_cost_function is designed to evaluate two objectives:
User Comfort (-CI_avg): This is a negated average Comfort Index, aiming to maximize comfort.
Energy Consumption (EC_avg): This represents the average energy consumption, which you aim to minimize.
Key Considerations:
Decision Variables (X): Your function expects a vector X with 144 elements, structured as [T1, L1, IAQ1, T2, L2, IAQ2, ..., T48, L48, IAQ48], representing temperature, light, and IAQ settings for 48 periods.
Data Matrix (dataSH): A 48x5 matrix containing coefficients related to temperature, light, and IAQ.
Optimization Algorithms: MOEMA, MOEA/D, and MOPSO will utilize this cost function. Each algorithm expects the cost function to accept a decision variable vector and return objective values.
2. Updating the Main Script
To integrate your custom cost function, we'll need to:
Adjust the Number of Decision Variables: Since your cost function expects 144 variables, update the dim, lb, and ub accordingly.
Provide the dataSH Matrix: Ensure that dataSH is loaded or defined within the main script so that it can be passed to the cost function.
Modify Function Handles: Replace @zdt1 and @ZDT with function handles that include dataSH.
Ensure Compatibility Across Algorithms: All optimization algorithms (MOEMA, MOEA/D, MOPSO) need to use the updated cost function.
3. Detailed MATLAB Code Update
Below is the updated MATLAB script incorporating all the necessary changes:
% Main script to run MOEMA, MOEA/D, and MOPSO optimization
clc;
clear;
close all;
% ------------------------- Parameters Setup -------------------------
% Set problem parameters
NPop_MOEMA = 100; % Population size for MOEMA
NPop_MOEAD = 200; % Population size for MOEA/D
NPop_MOPSO = 200; % Population size for MOPSO
T = 200; % Number of iterations
dim = 144; % Number of decision variables (3 variables per 48 periods)
lb = zeros(1, dim); % Lower bound
ub = ones(1, dim); % Upper bound
% ------------------------- Load or Define dataSH -------------------------
% TODO: Replace the following line with actual data loading if required
% Example: dataSH = load('dataSH.mat').dataSH;
% For demonstration, creating a dummy dataSH matrix
dataSH = ones(48, 5) .* 10; % Replace with actual coefficients
% ------------------------- Define Cost Function Handles -------------------------
% Create anonymous functions that pass dataSH to the cost function
MOEMA_FitnessFcn = @(X) multi_objective_cost_function(X, dataSH);
MOEAD_FitnessFcn = @(X) multi_objective_cost_function(X, dataSH);
MOPSO_FitnessFcn = @(POS) arrayfun(@(i) multi_objective_cost_function(POS(i,:), dataSH), 1:size(POS, 1), 'UniformOutput', false);
% ------------------------- Run MOEMA -------------------------
% Run MOEMA
[paretoFront_MOEMA, ~, ~, ~, ~] = MOEMA(NPop_MOEMA, T, lb, ub, dim, MOEMA_FitnessFcn);
% ------------------------- Run MOEA/D -------------------------
% MOEA/D parameters
nVar = dim;
VarMin = 0;
VarMax = 1;
nArchive = 50;
T_MOEAD = 15;
CostFunction_MOEAD = MOEAD_FitnessFcn;
crossover_params.gamma = 0.5;
crossover_params.VarMin = VarMin;
crossover_params.VarMax = VarMax;
% Run MOEA/D
[paretoFront_MOEAD, ~, ~, ~] = MOEAD(nVar, VarMin, VarMax, NPop_MOEAD, nArchive, T, T_MOEAD, CostFunction_MOEAD, crossover_params);
% ------------------------- Run MOPSO -------------------------
% MOPSO parameters
params.Np = NPop_MOPSO; % Population size
params.Nr = 50; % Repository size (adjusted as needed)
params.maxgen = T; % Maximum number of generations
params.W = 0.4; % Inertia weight
params.C1 = 2; % Individual confidence factor
params.C2 = 2; % Swarm confidence factor
params.ngrid = 20; % Number of grids in each dimension
params.maxvel = 5; % Maximum velocity in percentage
params.u_mut = 0.5; % Uniform mutation percentage
% Define MultiObj structure for MOPSO
MultiObj.nVar = dim;
MultiObj.var_min = lb';
MultiObj.var_max = ub';
MultiObj.fun = @(POS) cell2mat(arrayfun(@(i) multi_objective_cost_function(POS(i,:), dataSH), 1:size(POS, 1), 'UniformOutput', false)');
% Run MOPSO
REP_MOPSO = MOPSO(params, MultiObj);
paretoFront_MOPSO = REP_MOPSO.pos_fit;
% ------------------------- Plot 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('-Average Comfort Index');
ylabel('Average Energy Consumption');
title('Pareto Fronts for Custom Multi-Objective Cost Function');
legend;
% Optionally, plot the true Pareto front if known
% For custom problems, defining the true Pareto front may not be straightforward
% If available, uncomment and modify the following lines accordingly
% f1 = 0:0.01:1;
% g = 1;
% h = 1 - sqrt(f1 ./ g);
% f2 = g .* h;
% plot(f1, f2, 'k-', 'DisplayName', 'True Pareto Front');
% legend;
% ------------------------- Create Comparison Table -------------------------
% Create a table for comparison
MOEMA_solutions = size(paretoFront_MOEMA, 1);
MOEAD_solutions = size(paretoFront_MOEAD, 1);
MOPSO_solutions = size(paretoFront_MOPSO, 1);
MOEMA_min_f1 = min(paretoFront_MOEMA(:,1));
MOEAD_min_f1 = min(paretoFront_MOEAD(:,1));
MOPSO_min_f1 = min(paretoFront_MOPSO(:,1));
MOEMA_min_f2 = min(paretoFront_MOEMA(:,2));
MOEAD_min_f2 = min(paretoFront_MOEAD(:,2));
MOPSO_min_f2 = min(paretoFront_MOPSO(:,2));
comparison_table = table([MOEMA_solutions; MOEAD_solutions; MOPSO_solutions], ...
[MOEMA_min_f1; MOEAD_min_f1; MOPSO_min_f1], ...
[MOEMA_min_f2; MOEAD_min_f2; MOPSO_min_f2], ...
'VariableNames', {'Solutions', 'Min_f1', 'Min_f2'}, ...
'RowNames', {'MOEMA', 'MOEA/D', 'MOPSO'});
disp(comparison_table);
% ------------------------- Calculate Performance Metrics -------------------------
% Assuming you have a true Pareto front to compare against
% If not, you can skip IGD and Hypervolume or define a reference set
% Here, we'll proceed without the true Pareto front
% Calculate performance metrics
truePF = paretoFront_MOEMA; % Placeholder: replace with truePF if available
[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);
% ------------------------- Additional Plots -------------------------
figure;
subplot(2,2,1);
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('-Average Comfort Index');
ylabel('Average Energy Consumption');
title('Pareto Fronts Comparison');
legend('Location', 'southwest');
subplot(2,2,2);
bar([GD_MOEMA, GD_MOEAD, GD_MOPSO]);
title('Generation Distance (GD)');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
subplot(2,2,3);
bar([IGD_MOEMA, IGD_MOEAD, IGD_MOPSO]);
title('Inverted Generation Distance (IGD)');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
subplot(2,2,4);
bar([HV_MOEMA, HV_MOEAD, HV_MOPSO]);
title('Hypervolume (HV)');
set(gca, 'XTickLabel', {'MOEMA', 'MOEA/D', 'MOPSO'});
% ------------------------- Save Results -------------------------
% 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');
% ------------------------- Function Definitions -------------------------
% Replace existing functions with the updated multi-objective cost function
% Ensure that this function is either in a separate file or within this script
% ---------- 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
% ---------- MOEMA Function ----------
% (No changes needed inside, as it uses the provided FITNESSFCN)
% ... [Include other function definitions from your original script here without changes] ...
% ---------- MOEA/D Function ----------
% (No changes needed inside, as it uses the provided CostFunction_MOEAD)
% ---------- MOPSO Function ----------
% (Ensure that the MOPSO function correctly handles the updated MultiObj.fun)
% ---------- Performance Metrics Functions ----------
% ... (Ensure that calculateMetrics and hypervolume functions are correctly defined)
4. Explanation of Changes
Decision Variables Adjustment:
dim: Updated from 30 to 144 to match the structure expected by multi_objective_cost_function.
lb and ub: Remain as zeros and ones respectively, assuming normalization is appropriate. Adjust if necessary based on your problem's scaling.
Data Matrix (dataSH):
Loading Data: Ensure that dataSH is correctly loaded or defined. In the provided code, a dummy dataSH matrix is created for demonstration. Replace this with actual data as required.
Structure: dataSH should be a 48x5 matrix with relevant coefficients in columns 3, 4, and 5.
Function Handles:
MOEMA and MOEA/D: Modified to use anonymous functions that pass dataSH to multi_objective_cost_function.
MOPSO: Updated to correctly handle an array of positions by applying the cost function across all particles.
Plotting and Tables:
Axis Labels: Updated to reflect the new objectives (-Average Comfort Index and Average Energy Consumption).
Comparison Tables: Adjusted to ensure correct extraction and display of solutions and objective minima.
Performance Metrics:
True Pareto Front (truePF): Placeholder is used. If the true Pareto front is known for your specific problem, replace the placeholder accordingly.
Metrics Calculation: Ensure that calculateMetrics and related functions are correctly defined and capable of handling your custom objectives.
General Adjustments:
Population Sizes: Defined separately for each algorithm to provide flexibility.
Repository Size for MOPSO: Adjusted to 50 as an example; modify based on your requirements.
5. Additional Recommendations
Validation of dataSH: Ensure that dataSH contains the correct coefficients and is structured as expected. Incorrect coefficients can lead to erroneous evaluations.
Normalization: If your decision variables (Tk, Lk, Ik) have specific ranges beyond [0,1], consider normalizing them or adjusting the lb and ub accordingly.
Performance Metrics: The calculation of metrics like GD, IGD, Spread, and HV assumes the availability of a true or reference Pareto front. Ensure that truePF accurately represents the ground truth for meaningful comparisons.
Algorithm Parameters: Fine-tune parameters like population sizes, number of generations (T), inertia weights (W), and mutation rates (u_mut) based on the specific characteristics of your optimization problem for improved performance.
6. Final Notes
Integrating a custom multi-objective cost function requires careful alignment of decision variable structures and ensuring that all optimization algorithms are compatible with the new function's interface. The provided updates should serve as a comprehensive guide to facilitate this integration. Make sure to thoroughly test each component to verify correctness and performance.
If you encounter any specific issues or require further customization, feel free to ask for more detailed assistance!