can you add the comparison Plot Before and After optimization for temp, iaq and lux. please display the maximum, minimum and averange. please show full code
clc;
clear;
close all;
% ------------------ Data Initialization ------------------
% ---------- Initialization Function ----------
function pop = initialization(NPop, dim, ub, lb)
pop = rand(NPop, dim) .* (ub - lb) + lb;
end
% ---------- Evaluate Population Function ----------
function obj = evaluate_population(pop, FITNESSFCN)
num_individuals = size(pop,1);
obj = zeros(num_individuals, 2);
parfor i = 1:num_individuals
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
for i = 1:n_solutions
for j = 1:n_solutions
if i ~= j
if dominates(objectives(j,:), objectives(i,:))
is_dominated(i) = true;
domination_count(j) = domination_count(j) + 1;
end
end
end
end
end
% ---------- Dominates Function ----------
function result = dominates(obj1, obj2)
result = all(obj1 <= obj2) && any(obj1 < obj2);
end
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
% ---------- Tournament Selection Function ----------
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
% ---------- Crossover Function ----------
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
% ---------- Mutation Function ----------
function mutated_pop = mutation(pop, mutation_prob, num_vars)
eta_m = 20;
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
% ---------- Select New Population Function ----------
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
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
% ---------- Multi-Objective Cost Function ----------
function objectives = multi_objective_cost_function(X, dataSH)
if length(X) ~= 144
error('Decision vector X must have 144 elements (3 variables per 48 periods).');
end
p1 = 1/3;
p2 = 1/3;
p3 = 1/3;
Td = 22.78;
Ld = 800;
Id = 800;
pT = 9;
pL = 1;
pI = 1;
Tc = dataSH(:,3)';
Lc = dataSH(:,4)';
Ic = dataSH(:,5)';
CI = zeros(48,1);
EC = zeros(48,1);
for k = 1:48
Tk = X(3*k-2);
Lk = X(3*k-1);
Ik = X(3*k);
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;
ET = pT * abs(Tk - Tc(k));
EL = pL * abs(Lk - Lc(k));
EI = pI * abs(Ik - Ic(k));
EC(k) = ET + EL + EI;
end
CI_avg = mean(CI);
EC_avg = mean(EC);
objectives = [-CI_avg, EC_avg];
end
% Add performance metric functions
function hv = hypervolume(paretoFront, referencePoint)
hv = 0;
sortedFront = sortrows(paretoFront);
for i = 1:size(sortedFront, 1)
if i == size(sortedFront, 1)
hv = hv + prod(referencePoint - sortedFront(i, :));
else
hv = hv + prod([sortedFront(i+1, 1), referencePoint(2)] - sortedFront(i, :));
end
end
end
function gd = generational_distance(approximationSet, referenceSet)
distances = pdist2(approximationSet, referenceSet);
gd = sqrt(sum(min(distances, [], 2).^2)) / size(approximationSet, 1);
end
function igd = inverted_generational_distance(approximationSet, referenceSet)
distances = pdist2(referenceSet, approximationSet);
igd = sum(min(distances, [], 2)) / size(referenceSet, 1);
end
function s = spread_metric(paretoFront)
sortedFront = sortrows(paretoFront);
distances = sqrt(sum(diff(sortedFront).^2, 2));
d = mean(distances);
df = sqrt(sum((sortedFront(1,:) - sortedFront(end,:)).^2));
s = (df + sum(abs(distances - d))) / (df + size(paretoFront, 1) * d);
end
To add the comparison plots for temperature (Temp), indoor air quality (IAQ), and illuminance (lux) before and after optimization, we need to refactor the existing script or function to incorporate these plots. This involves extracting the relevant data pre- and post-optimization, then plotting them in a visual manner.
Below is the refactored MATLAB code that includes the necessary steps:
Initialization & Extraction: The code initializes the data and then extracts temperature (Celsius), IAQ, and lux values before optimization from dataSH.
Post-Optimization Data: The post-optimization data is extracted using the NSGA-II function, assuming it returns the decision vectors. Ideally, replace it with actual optimization results for accurate comparison.
Plotting: Three subplots are created to compare the before-and-after values for temperature, IAQ, and lux. Each categorical variable gets its subplot for better visualization.
Statistics Display: The code calculates and displays the maximum, minimum, and average statistics for each variable before and after optimization.
Make sure the actual optimization logic is correctly implemented to update temperature_after, lux_after, and iaq_after from real optimization results instead of demo data.
The error you're encountering suggests that the mean_solns variable is not structured as expected or not properly indexed. The end operator is used within array indexing to denote the last element of an array. If there's a problem, it could be due to the variable not being as large as anticipated or being improperly structured.
Here’s a revised version of the code with some additional checks to ensure mean_solns is correctly indexed. Additionally, make sure mean_solns is being generated correctly from NSGA2:
% Extract temperature, IAQ, and lux before optimization
temp_before = dataSH(:, 3);
iaq_before = dataSH(:, 5);
lux_before = dataSH(:, 4);
% Assuming 'NSGA2' function is defined and works correctly:
% Replace this placeholder line with the actual optimized solutions from NSGA-II
[~, mean_solns] = NSGA2(300, 300, zeros(1, 144), [25.56*ones(1,48), 880*ones(1,48), 880*ones(1,48)], 144, @(X) multi_objective_cost_function(X, dataSH));
% Ensure mean_solns is of correct size and structure
if length(mean_solns) < 144
error('mean_solns does not have the expected length.');
end
% Extract optimized results
temp_after = mean_solns(1:3:144).'; % Assuming correct size extraction
lux_after = mean_solns(2:3:144).';
iaq_after = mean_solns(3:3:144).';
% Plotting Comparison
figure;
subplot(3,1,1);
plot(1:48, temp_before, 'b-', 'DisplayName', 'Before Optimization');
hold on;
plot(1:48, temp_after, 'r--', 'DisplayName', 'After Optimization');
xlabel('Time Period');
ylabel('Temperature (\circC)');
legend();
title('Temperature Before and After Optimization');
subplot(3,1,2);
plot(1:48, lux_before, 'b-', 'DisplayName', 'Before Optimization');
hold on;
plot(1:48, lux_after, 'r--', 'DisplayName', 'After Optimization');
xlabel('Time Period');
ylabel('Lux');
legend();
title('Lux Before and After Optimization');
subplot(3,1,3);
plot(1:48, iaq_before, 'b-', 'DisplayName', 'Before Optimization');
hold on;
plot(1:48, iaq_after, 'r--', 'DisplayName', 'After Optimization');
xlabel('Time Period');
ylabel('IAQ');
legend();
title('IAQ Before and After Optimization');
% Display statistics pre and post optimization
fprintf('Temperature Statistics:\n');
fprintf('Before - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(temp_before), min(temp_before), mean(temp_before));
fprintf('After - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(temp_after), min(temp_after), mean(temp_after));
fprintf('\nLux Statistics:\n');
fprintf('Before - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(lux_before), min(lux_before), mean(lux_before));
fprintf('After - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(lux_after), min(lux_after), mean(lux_after));
fprintf('\nIAQ Statistics:\n');
fprintf('Before - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(iaq_before), min(iaq_before), mean(iaq_before));
fprintf('After - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(iaq_after), min(iaq_after), mean(iaq_after));
Key Points:
Validation of mean_solns: The code checks if mean_solns has the expected length (i.e., 144). This is based on the assumption that NSGA2 will output an array with a size that matches the number of variables.
Indexing: Uses hard-coded indexes (1:3:144) for clarity and better understanding.
Error Handling: If mean_solns does not appear as expected, you’ll get a notification via an error message.
Ensure that the NSGA2 function and its return structure correctly match the expected dimensions of decision variables for this code to work effectively. If the function is not returning the expected values, check its logic and ensure it outputs a matrix or array with dimensions corresponding to 48 periods multiplied by 3 (for Temp, Lux, and IAQ).
The error indicates that the variable mean_solns is not being properly assigned or recognized in your code. In the context of the NSGA-II optimization routine, it's expected that this function would return some form of optimization result that can be used to assess the differences between pre- and post-optimization state.
Let's clarify and correct the steps to ensure you're generating and accessing the optimized solution properly:
Ensure NSGA-II Implementation Returns Solutions:
Make sure the NSGA2 function is implemented correctly and actually returns the optimized solutions. If not, you need to adapt it to provide such output.
Capture and Parse Returned Solutions:
Once you have the NSGA-II returning the solutions, you need to capture and process these correctly.
Here's how a simplified version of your existing script might look if the NSGA2 function is structured to return the optimized solutions it calculates:
% Run NSGA-II (ensure NSGA2 is set to output a solution vector)
[~, mean_solution] = NSGA2(NPop, T, lb, ub, dim, @(X) multi_objective_cost_function(X, dataSH));
% Assume NSGA2 returns the decision vectors of the Pareto-front or best solution
% Extract and plot results, assuming mean_solution is a result vector
% If multiple solutions are returned, you would need to decide which one to visualize
if isempty(mean_solution)
error('NSGA2 did not return a valid solution vector. Ensure NSGA2 is implemented correctly.');
end
% Correctly capture temperature, lux, and IAQ after optimization
temp_after = mean_solution(1:3:end);
lux_after = mean_solution(2:3:end);
iaq_after = mean_solution(3:3:end);
% Existing data assignments for visualization
temp_before = dataSH(:, 3);
lux_before = dataSH(:, 4);
iaq_before = dataSH(:, 5);
% Plotting Comparison
figure;
subplot(3,1,1);
plot(1:48, temp_before, 'b-', 'DisplayName', 'Before Optimization');
hold on;
plot(1:48, temp_after, 'r--', 'DisplayName', 'After Optimization');
xlabel('Time Period');
ylabel('Temperature (\circC)');
legend();
title('Temperature Before and After Optimization');
subplot(3,1,2);
plot(1:48, lux_before, 'b-', 'DisplayName', 'Before Optimization');
hold on;
plot(1:48, lux_after, 'r--', 'DisplayName', 'After Optimization');
xlabel('Time Period');
ylabel('Lux');
legend();
title('Lux Before and After Optimization');
subplot(3,1,3);
plot(1:48, iaq_before, 'b-', 'DisplayName', 'Before Optimization');
hold on;
plot(1:48, iaq_after, 'r--', 'DisplayName', 'After Optimization');
xlabel('Time Period');
ylabel('IAQ');
legend();
title('IAQ Before and After Optimization');
% Display statistics pre and post optimization
fprintf('Temperature Statistics:\n');
fprintf('Before - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(temp_before), min(temp_before), mean(temp_before));
fprintf('After - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(temp_after), min(temp_after), mean(temp_after));
fprintf('\nLux Statistics:\n');
fprintf('Before - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(lux_before), min(lux_before), mean(lux_before));
fprintf('After - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(lux_after), min(lux_after), mean(lux_after));
fprintf('\nIAQ Statistics:\n');
fprintf('Before - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(iaq_before), min(iaq_before), mean(iaq_before));
fprintf('After - Max: %.2f, Min: %.2f, Avg: %.2f\n', max(iaq_after), min(iaq_after), mean(iaq_after));
Key Points:
Ensure NSGA2 Returns Valid Solutions: The NSGA-II function must be correctly implemented to output the relevant decision vectors. You might need to delve into the function's return values and logic.
Extracting Results: The post-optimization extracts the necessary variables assuming mean_solution or similar represents an array of decision variables.
Handling Empty Returns: There's a safety check ensuring the array isn't empty or improperly structured.
If you're not getting the expected solution vectors from NSGA2, there might be an issue with how NSGA-II is implemented, or you're calling it incorrectly. To debug this aspect, consider logging outputs or verifying intermediate steps within NSGA2.