一、核心框架设计
1.1 系统整体架构
否
是
电网历史数据
小波多尺度分解
特征提取
(负荷波动性/周期性)
建立多目标优化模型
粒子群算法优化
发电机出力调整
变压器分接头优化
电容器投切控制
潮流计算验证
满足约束?
输出最优解
网损降低
电压稳定
运行成本减少
1.2 技术路线
- 小波分析:提取负荷的时频特征,识别峰谷时段和波动模式
- 粒子群算法:优化发电机出力、变压器变比、无功补偿等控制变量
- 潮流计算:基于MATPOWER进行精确的潮流验证
二、小波分析模块实现
2.1 负荷数据多尺度分解
matlab
function [load_features, wavelet_coeffs] = wavelet_load_analysis(load_data, fs, wavelet_name)
% 基于小波的电网负荷特征分析
% 输入:
% load_data - 负荷时间序列 (kW或MW)
% fs - 采样频率 (Hz)
% wavelet_name - 小波基名称,如'db4', 'sym8'
% 输出:
% load_features - 提取的特征结构体
% wavelet_coeffs - 小波系数
% 确保输入为列向量
if size(load_data, 1) < size(load_data, 2)
load_data = load_data';
end
N = length(load_data);
t = (0:N-1)/fs; % 时间轴
% ========== 1. 多尺度小波分解 ==========
% 确定最大分解层数
max_level = floor(log2(N)) - 1;
level = min(6, max_level); % 通常分解4-6层
% 执行小波分解
[C, L] = wavedec(load_data, level, wavelet_name);
% 提取各层细节系数和近似系数
wavelet_coeffs.detail = cell(level, 1);
wavelet_coeffs.approx = zeros(N, level);
for i = 1:level
wavelet_coeffs.detail{i} = wrcoef('d', C, L, wavelet_name, i);
wavelet_coeffs.approx(:, i) = wrcoef('a', C, L, wavelet_name, i);
end
% ========== 2. 负荷特征提取 ==========
load_features = struct();
% 基本统计特征
load_features.mean_load = mean(load_data);
load_features.std_load = std(load_data);
load_features.max_load = max(load_data);
load_features.min_load = min(load_data);
load_features.load_factor = mean(load_data) / max(load_data); % 负荷率
% 基于小波系数的特征
% 各层能量分布
energy_total = sum(load_data.^2);
energy_detail = zeros(level, 1);
for i = 1:level
energy_detail(i) = sum(wavelet_coeffs.detail{i}.^2);
end
load_features.energy_ratio = energy_detail / energy_total;
% 波动性指标(基于高频分量)
load_features.volatility_index = std(wavelet_coeffs.detail{1}) / mean(load_data);
% 周期性检测(基于第3-4层细节)
if level >= 4
% 使用自相关函数检测周期
[acf_detail3, lags] = xcorr(wavelet_coeffs.detail{3}, 'coeff');
[peaks, locs] = findpeaks(acf_detail3(length(wavelet_coeffs.detail{3}):end), ...
'MinPeakHeight', 0.3);
if ~isempty(peaks)
load_features.periodicity = lags(locs(1) + length(wavelet_coeffs.detail{3}) - 1) / fs;
else
load_features.periodicity = 0;
end
end
% ========== 3. 负荷预测(基于小波重构) ==========
% 使用低频近似系数进行短期预测
approx_last = wavelet_coeffs.approx(:, level);
predict_horizon = 24; % 预测未来24个点(假设每小时1点)
% ARIMA预测模型(简化版)
mdl = arima(2, 1, 2); % ARIMA(2,1,2)
estMdl = estimate(mdl, approx_last);
[pred_approx, pred_ci] = forecast(estMdl, predict_horizon, 'Y0', approx_last);
% 重构预测负荷(添加高频波动)
predicted_load = pred_approx;
% 添加典型的高频波动模式(基于历史统计)
if level >= 2
% 获取历史高频分量的统计特性
detail1_stats = [mean(wavelet_coeffs.detail{1}), std(wavelet_coeffs.detail{1})];
% 生成随机高频分量
random_detail = detail1_stats(1) + detail1_stats(2) * randn(predict_horizon, 1);
predicted_load = predicted_load + random_detail * 0.3; % 适当缩放
end
load_features.predicted_load = predicted_load;
load_features.prediction_horizon = predict_horizon;
% ========== 4. 可视化分析结果 ==========
figure('Position', [50, 50, 1400, 900]);
% 子图1:原始负荷与近似分量
subplot(3, 3, 1);
plot(t/(3600*24), load_data, 'b-', 'LineWidth', 1.5); hold on;
plot(t/(3600*24), wavelet_coeffs.approx(:, level), 'r-', 'LineWidth', 2);
xlabel('时间 (天)'); ylabel('负荷 (MW)');
legend('原始负荷', sprintf('近似分量 (L%d)', level), 'Location', 'best');
title('原始负荷与低频近似'); grid on;
% 子图2:各层细节分量
subplot(3, 3, 2);
colors = jet(level);
for i = 1:min(4, level) % 显示前4层细节
plot(t/(3600*24), wavelet_coeffs.detail{i}, 'Color', colors(i, :), 'LineWidth', 1);
hold on;
end
xlabel('时间 (天)'); ylabel('幅值');
legend(arrayfun(@(x) sprintf('细节D%d', x), 1:min(4, level), 'UniformOutput', false));
title('小波细节分量'); grid on;
% 子图3:负荷预测
subplot(3, 3, 3);
future_t = (N:N+predict_horizon-1)/fs;
plot(t/(3600*24), load_data, 'b-', 'LineWidth', 1.5); hold on;
plot(future_t/(3600*24), predicted_load, 'r--', 'LineWidth', 2);
plot(future_t/(3600*24), pred_ci(:, 1), 'g:', 'LineWidth', 1);
plot(future_t/(3600*24), pred_ci(:, 2), 'g:', 'LineWidth', 1);
xlabel('时间 (天)'); ylabel('负荷 (MW)');
legend('历史负荷', '预测负荷', '95%置信区间', 'Location', 'best');
title('负荷预测结果'); grid on;
% 子图4:能量分布
subplot(3, 3, 4);
pie(load_features.energy_ratio);
title('各层小波能量分布');
labels = arrayfun(@(x) sprintf('D%d', x), 1:level, 'UniformOutput', false);
labels{end+1} = '近似分量';
legend(labels, 'Location', 'eastoutside');
% 子图5:负荷统计特征
subplot(3, 3, 5);
features_to_plot = [load_features.mean_load, load_features.std_load, ...
load_features.max_load, load_features.min_load, ...
load_features.load_factor];
bar(1:5, features_to_plot);
set(gca, 'XTickLabel', {'均值', '标准差', '最大值', '最小值', '负荷率'});
ylabel('数值'); title('负荷统计特征');
grid on;
% 子图6:自相关分析(检测周期性)
subplot(3, 3, 6);
if level >= 3
plot(lags/fs, acf_detail3, 'b-', 'LineWidth', 1.5);
xlabel('时延 (小时)'); ylabel('自相关系数');
title(sprintf('细节D3的自相关 (周期≈%.1fh)', load_features.periodicity*fs));
grid on;
end
% 子图7:频谱分析
subplot(3, 3, 7);
NFFT = 2^nextpow2(N);
Y = fft(load_data, NFFT)/N;
f = fs/2*linspace(0, 1, NFFT/2+1);
plot(f*24, 2*abs(Y(1:NFFT/2+1)), 'b-', 'LineWidth', 1.5); % 转换为每天周期
xlabel('频率 (周期/天)'); ylabel('|幅值|');
title('负荷频谱分析'); grid on;
% 子图8:负荷持续时间曲线
subplot(3, 3, 8);
sorted_load = sort(load_data, 'descend');
plot((1:N)/N*100, sorted_load, 'b-', 'LineWidth', 1.5);
xlabel('时间百分比 (%)'); ylabel('负荷 (MW)');
title('负荷持续时间曲线'); grid on;
% 子图9:日负荷曲线(如果数据足够)
if N >= 24*7 % 至少一周数据
subplot(3, 3, 9);
daily_profiles = reshape(load_data(1:floor(N/24)*24), 24, []);
plot(1:24, mean(daily_profiles, 2), 'b-', 'LineWidth', 2); hold on;
plot(1:24, mean(daily_profiles, 2) + std(daily_profiles, 0, 2), 'r--');
plot(1:24, mean(daily_profiles, 2) - std(daily_profiles, 0, 2), 'r--');
xlabel('小时'); ylabel('负荷 (MW)');
legend('平均日曲线', '±1标准差', 'Location', 'best');
title('典型日负荷曲线'); grid on;
end
fprintf('\n========== 负荷特征分析结果 ==========\n');
fprintf('平均负荷: %.2f MW\n', load_features.mean_load);
fprintf('负荷标准差: %.2f MW\n', load_features.std_load);
fprintf('峰谷差: %.2f MW\n', load_features.max_load - load_features.min_load);
fprintf('负荷率: %.2f%%\n', load_features.load_factor * 100);
fprintf('波动性指数: %.4f\n', load_features.volatility_index);
if load_features.periodicity > 0
fprintf('检测到周期性: %.1f 小时\n', load_features.periodicity * fs);
end
fprintf('预测未来%.0f点负荷: [%.2f ~ %.2f] MW\n', ...
predict_horizon, min(predicted_load), max(predicted_load));
end
三、粒子群算法优化模块
3.1 多目标优化问题建模
matlab
function [fitness, constraints_violation] = power_flow_fitness(particle, system_data, load_features)
% 电网潮流多目标适应度函数
% 输入:
% particle - 粒子位置向量 [Pg2...Pgn, Qg1...Qgn, V1...Vn, Tap1...Tapm]
% system_data - 系统数据(包含网络参数、发电机信息等)
% load_features - 负荷特征(用于确定负荷水平)
% 输出:
% fitness - 适应度值(越小越好)
% constraints_violation - 约束违反程度
% ========== 1. 解码粒子位置 ==========
[gen_power, gen_reactive, bus_voltage, transformer_taps] = ...
decode_particle(particle, system_data);
% ========== 2. 更新系统数据 ==========
% 更新发电机出力
mpc = system_data.mpc;
ngen = length(mpc.gen(:, 1));
for i = 1:ngen
if i == 1
% 平衡节点(通常为第一个发电机)只更新电压
mpc.gen(i, 6) = bus_voltage(mpc.gen(i, 1)); % Vg
else
% PV节点更新有功和电压
mpc.gen(i, 2) = gen_power(i); % Pg (MW)
mpc.gen(i, 6) = bus_voltage(mpc.gen(i, 1)); % Vg (p.u.)
end
mpc.gen(i, 3) = gen_reactive(i); % Qg (MVAr)
end
% 更新变压器变比
if ~isempty(transformer_taps)
for i = 1:length(transformer_taps)
mpc.branch(i, 9) = transformer_taps(i); % 变压器变比
end
end
% 更新负荷(基于预测或当前特征)
load_scale = load_features.current_scale; % 负荷水平标度
mpc.bus(:, 3) = system_data.base_load(:, 1) * load_scale; % P load
mpc.bus(:, 4) = system_data.base_load(:, 2) * load_scale; % Q load
% ========== 3. 运行潮流计算 ==========
try
results = runpf(mpc); % 使用MATPOWER进行潮流计算
converged = results.success;
catch
converged = 0;
results = [];
end
% ========== 4. 计算目标函数 ==========
if converged
% 目标1:最小化网损
total_gen_p = sum(results.gen(:, 2));
total_load_p = sum(results.bus(:, 3));
total_loss = total_gen_p - total_load_p;
% 目标2:最小化电压偏差
voltage_deviation = 0;
for i = 1:length(results.bus(:, 1))
v_mag = results.bus(i, 8);
if v_mag < 0.95
voltage_deviation = voltage_deviation + (0.95 - v_mag)^2;
elseif v_mag > 1.05
voltage_deviation = voltage_deviation + (v_mag - 1.05)^2;
end
end
% 目标3:最小化运行成本(简化:与发电机出力成正比)
gen_cost = 0;
for i = 1:ngen
% 假设二次成本函数: cost = a*Pg^2 + b*Pg + c
a = system_data.gen_cost(i, 1);
b = system_data.gen_cost(i, 2);
c = system_data.gen_cost(i, 3);
Pg = results.gen(i, 2);
gen_cost = gen_cost + (a*Pg^2 + b*Pg + c);
end
% 目标4:最小化控制动作代价(变压器调节、电容器投切等)
control_cost = 0;
if ~isempty(transformer_taps)
% 变压器调节代价
control_cost = control_cost + 0.1 * sum(abs(diff(transformer_taps)));
end
% 多目标加权求和(可根据偏好调整权重)
w1 = 0.4; % 网损权重
w2 = 0.3; % 电压偏差权重
w3 = 0.2; % 运行成本权重
w4 = 0.1; % 控制代价权重
fitness = w1 * total_loss + w2 * voltage_deviation + ...
w3 * gen_cost/1000 + w4 * control_cost;
% ========== 5. 约束违反检查 ==========
constraints_violation = 0;
% 发电机出力约束
for i = 1:ngen
Pg = results.gen(i, 2);
Qg = results.gen(i, 3);
if Pg < system_data.Pmin(i) || Pg > system_data.Pmax(i)
constraints_violation = constraints_violation + 1;
end
if Qg < system_data.Qmin(i) || Qg > system_data.Qmax(i)
constraints_violation = constraints_violation + 1;
end
end
% 电压约束
for i = 1:length(results.bus(:, 1))
v_mag = results.bus(i, 8);
if v_mag < 0.95 || v_mag > 1.05
constraints_violation = constraints_violation + 1;
end
end
% 线路容量约束
for i = 1:length(results.branch(:, 1))
p_from = results.branch(i, 14); % 从端有功
q_from = results.branch(i, 15); % 从端无功
s_from = sqrt(p_from^2 + q_from^2);
if s_from > system_data.line_limits(i)
constraints_violation = constraints_violation + 1;
end
end
else
% 潮流计算不收敛,惩罚
fitness = 1e6;
constraints_violation = 1e3;
end
end
function [Pg, Qg, V, taps] = decode_particle(particle, system_data)
% 解码粒子位置到实际控制变量
idx = 1;
ngen = system_data.ngen;
nbus = system_data.nbus;
ntap = system_data.ntap;
% 发电机有功出力(除了平衡节点)
Pg = zeros(ngen, 1);
Pg(1) = system_data.Pg0(1); % 平衡节点固定
for i = 2:ngen
Pg(i) = particle(idx) * (system_data.Pmax(i) - system_data.Pmin(i)) + system_data.Pmin(i);
idx = idx + 1;
end
% 发电机无功出力
Qg = zeros(ngen, 1);
for i = 1:ngen
Qg(i) = particle(idx) * (system_data.Qmax(i) - system_data.Qmin(i)) + system_data.Qmin(i);
idx = idx + 1;
end
% 节点电压幅值(PV节点固定,PQ节点优化)
V = ones(nbus, 1) * 1.0; % 默认1.0 p.u.
pv_buses = system_data.pv_buses;
pq_buses = system_data.pq_buses;
% PV节点电压(发电机节点)
for i = 1:length(pv_buses)
bus_idx = pv_buses(i);
V(bus_idx) = particle(idx) * 0.1 + 1.0; % 在[0.95, 1.05]范围内
idx = idx + 1;
end
% 变压器变比
taps = ones(ntap, 1);
for i = 1:ntap
taps(i) = particle(idx) * 0.2 + 0.9; % 在[0.9, 1.1]范围内
idx = idx + 1;
end
end
3.2 改进粒子群算法实现
matlab
function [best_solution, convergence_curve] = enhanced_pso_power_flow(system_data, load_features, pso_params)
% 增强型粒子群算法用于电网潮流优化
% 改进:自适应权重、多种群协作、混沌初始化
% ========== 1. 参数设置 ==========
if nargin < 3
pso_params = struct();
end
% 算法参数
default_params.pop_size = 50; % 种群大小
default_params.max_iter = 100; % 最大迭代次数
default_params.w_max = 0.9; % 惯性权重上限
default_params.w_min = 0.4; % 惯性权重下限
default_params.c1 = 2.0; % 个体学习因子
default_params.c2 = 2.0; % 社会学习因子
default_params.c3 = 1.0; % 多种群协作因子
default_params.adaptive = true; % 自适应参数
default_params.multi_swarm = true; % 多种群优化
default_params.chaos_init = true; % 混沌初始化
% 合并参数
pso_fields = fieldnames(default_params);
for i = 1:length(pso_fields)
if ~isfield(pso_params, pso_fields{i})
pso_params.(pso_fields{i}) = default_params.(pso_fields{i});
end
end
% 问题维度(控制变量数量)
dim = calculate_dimension(system_data);
% ========== 2. 初始化种群 ==========
if pso_params.chaos_init
% 混沌初始化(Logistic映射)
population = chaos_initialization(pso_params.pop_size, dim);
else
% 随机初始化
population = rand(pso_params.pop_size, dim);
end
% 初始化速度和适应度
velocity = zeros(pso_params.pop_size, dim);
fitness = inf(pso_params.pop_size, 1);
constraint_violation = zeros(pso_params.pop_size, 1);
% 个人最佳位置和适应度
personal_best_pos = population;
personal_best_fitness = inf(pso_params.pop_size, 1);
% 全局最佳
global_best_fitness = inf;
global_best_pos = [];
% 多种群:划分为多个子群
if pso_params.multi_swarm
num_subswarms = 3;
subswarm_size = floor(pso_params.pop_size / num_subswarms);
subswarm_best = cell(num_subswarms, 1);
for s = 1:num_subswarms
subswarm_best{s}.fitness = inf;
subswarm_best{s}.position = [];
end
end
% ========== 3. 初始评估 ==========
fprintf('开始增强型PSO优化...\n');
for i = 1:pso_params.pop_size
[fitness(i), constraint_violation(i)] = ...
power_flow_fitness(population(i, :), system_data, load_features);
% 惩罚约束违反
if constraint_violation(i) > 0
fitness(i) = fitness(i) * (1 + 0.1 * constraint_violation(i));
end
personal_best_fitness(i) = fitness(i);
% 更新全局最佳
if fitness(i) < global_best_fitness
global_best_fitness = fitness(i);
global_best_pos = population(i, :);
end
% 更新子群最佳
if pso_params.multi_swarm
subswarm_idx = ceil(i / subswarm_size);
subswarm_idx = min(subswarm_idx, num_subswarms);
if fitness(i) < subswarm_best{subswarm_idx}.fitness
subswarm_best{subswarm_idx}.fitness = fitness(i);
subswarm_best{subswarm_idx}.position = population(i, :);
end
end
end
% ========== 4. 主优化循环 ==========
convergence_curve = zeros(pso_params.max_iter, 1);
diversity_history = zeros(pso_params.max_iter, 1);
for iter = 1:pso_params.max_iter
% 自适应参数调整
if pso_params.adaptive
% 线性递减惯性权重
w = pso_params.w_max - (pso_params.w_max - pso_params.w_min) * ...
(iter / pso_params.max_iter);
% 自适应学习因子(前期探索,后期开发)
if iter < pso_params.max_iter/3
c1_current = pso_params.c1 * 1.2;
c2_current = pso_params.c2 * 0.8;
elseif iter < 2*pso_params.max_iter/3
c1_current = pso_params.c1;
c2_current = pso_params.c2;
else
c1_current = pso_params.c1 * 0.8;
c2_current = pso_params.c2 * 1.2;
end
else
w = 0.9;
c1_current = pso_params.c1;
c2_current = pso_params.c2;
end
% 计算种群多样性
diversity_history(iter) = calculate_diversity(population);
% 更新每个粒子
for i = 1:pso_params.pop_size
% 多种群协作:除了个人最佳和全局最佳,还考虑子群最佳
if pso_params.multi_swarm
subswarm_idx = ceil(i / subswarm_size);
subswarm_idx = min(subswarm_idx, num_subswarms);
subswarm_best_pos = subswarm_best{subswarm_idx}.position;
% 速度更新(添加子群协作项)
velocity(i, :) = w * velocity(i, :) + ...
c1_current * rand(1, dim) .* (personal_best_pos(i, :) - population(i, :)) + ...
c2_current * rand(1, dim) .* (global_best_pos - population(i, :)) + ...
pso_params.c3 * rand(1, dim) .* (subswarm_best_pos - population(i, :));
else
% 标准PSO速度更新
velocity(i, :) = w * velocity(i, :) + ...
c1_current * rand(1, dim) .* (personal_best_pos(i, :) - population(i, :)) + ...
c2_current * rand(1, dim) .* (global_best_pos - population(i, :));
end
% 速度限制
v_max = 0.2;
velocity(i, :) = sign(velocity(i, :)) .* min(abs(velocity(i, :)), v_max);
% 位置更新
population(i, :) = population(i, :) + velocity(i, :);
% 边界处理(反射边界)
for d = 1:dim
if population(i, d) < 0
population(i, d) = -population(i, d);
velocity(i, d) = -velocity(i, d) * 0.5;
elseif population(i, d) > 1
population(i, d) = 2 - population(i, d);
velocity(i, d) = -velocity(i, d) * 0.5;
end
end
% 评估新位置
[new_fitness, new_constraint] = ...
power_flow_fitness(population(i, :), system_data, load_features);
% 惩罚约束违反
if new_constraint > 0
new_fitness = new_fitness * (1 + 0.1 * new_constraint);
end
% 更新个人最佳
if new_fitness < personal_best_fitness(i)
personal_best_fitness(i) = new_fitness;
personal_best_pos(i, :) = population(i, :);
% 更新全局最佳
if new_fitness < global_best_fitness
global_best_fitness = new_fitness;
global_best_pos = population(i, :);
% 输出当前最佳结果
if mod(iter, 10) == 0
fprintf('迭代 %d: 最佳适应度 = %.6f\n', iter, global_best_fitness);
end
end
% 更新子群最佳
if pso_params.multi_swarm
if new_fitness < subswarm_best{subswarm_idx}.fitness
subswarm_best{subswarm_idx}.fitness = new_fitness;
subswarm_best{subswarm_idx}.position = population(i, :);
end
end
end
end
convergence_curve(iter) = global_best_fitness;
% 定期进行混沌扰动(避免早熟)
if mod(iter, 20) == 0 && iter < pso_params.max_iter * 0.8
% 选择适应度最差的10%粒子进行混沌扰动
[~, worst_idx] = sort(personal_best_fitness, 'descend');
num_perturb = ceil(0.1 * pso_params.pop_size);
for p = 1:num_perturb
idx = worst_idx(p);
% 混沌扰动(Tent映射)
chaos_seq = tent_chaos(10, dim);
population(idx, :) = 0.7 * population(idx, :) + 0.3 * chaos_seq(end, :);
end
end
% 早停条件
if iter > 30
improvement = abs(convergence_curve(iter-30) - convergence_curve(iter)) / ...
convergence_curve(iter-30);
if improvement < 1e-6
fprintf('早停于迭代 %d (改进小于1e-6)\n', iter);
break;
end
end
end
% ========== 5. 解码最佳解 ==========
[gen_power, gen_reactive, bus_voltage, transformer_taps] = ...
decode_particle(global_best_pos, system_data);
best_solution = struct();
best_solution.gen_power = gen_power;
best_solution.gen_reactive = gen_reactive;
best_solution.bus_voltage = bus_voltage;
best_solution.transformer_taps = transformer_taps;
best_solution.fitness = global_best_fitness;
best_solution.convergence_curve = convergence_curve(1:iter);
best_solution.diversity_history = diversity_history(1:iter);
% ========== 6. 结果验证 ==========
% 使用最佳解运行详细潮流计算
mpc_optimal = update_system_with_solution(system_data.mpc, best_solution, load_features);
results_optimal = runpf(mpc_optimal);
best_solution.power_loss = sum(results_optimal.gen(:, 2)) - sum(results_optimal.bus(:, 3));
best_solution.voltage_profile = results_optimal.bus(:, 8);
best_solution.iterations = iter;
fprintf('\n========== 优化结果 ==========\n');
fprintf('最优适应度: %.6f\n', best_solution.fitness);
fprintf('总网损: %.4f MW\n', best_solution.power_loss);
fprintf('电压越限节点数: %d\n', sum(best_solution.voltage_profile < 0.95 | best_solution.voltage_profile > 1.05));
fprintf('发电机出力调整次数: %d\n', length(find(abs(diff(gen_power)) > 0.1)));
fprintf('变压器变比调整: %s\n', num2str(transformer_taps', '%.3f '));
end
% ========== 辅助函数 ==========
function dim = calculate_dimension(system_data)
% 计算问题维度
ngen = system_data.ngen;
nbus = system_data.nbus;
ntap = system_data.ntap;
% 维度包括:
% 1. 发电机有功(除了平衡节点):ngen-1
% 2. 发电机无功:ngen
% 3. PV节点电压:length(system_data.pv_buses)
% 4. 变压器变比:ntap
dim = (ngen - 1) + ngen + length(system_data.pv_buses) + ntap;
end
function population = chaos_initialization(pop_size, dim)
% 混沌初始化(Logistic映射)
population = zeros(pop_size, dim);
for i = 1:pop_size
% 每个粒子使用不同的混沌序列
x = rand(1); % 初始值
chaos_seq = zeros(1, dim);
for d = 1:dim
x = 3.9 * x * (1 - x); % Logistic映射
chaos_seq(d) = x;
end
population(i, :) = chaos_seq;
end
end
function diversity = calculate_diversity(population)
% 计算种群多样性(平均欧氏距离)
pop_size = size(population, 1);
center = mean(population, 1);
distances = zeros(pop_size, 1);
for i = 1:pop_size
distances(i) = norm(population(i, :) - center);
end
diversity = mean(distances);
end
function chaos_seq = tent_chaos(length_seq, dim)
% Tent混沌映射
chaos_seq = zeros(length_seq, dim);
x = rand(1, dim); % 初始值
for t = 1:length_seq
x(x <= 0.5) = 2 * x(x <= 0.5);
x(x > 0.5) = 2 * (1 - x(x > 0.5));
chaos_seq(t, :) = x;
end
end
四、完整系统集成与测试
4.1 主程序:小波-PSO潮流优化
matlab
%% 主程序:基于小波分析和PSO的电网潮流优化
clear; close all; clc;
% ========== 1. 加载电网数据 ==========
fprintf('步骤1: 加载电网数据...\n');
% 使用MATPOWER的IEEE 30节点系统作为测试案例
mpc = loadcase('case30');
system_data = prepare_system_data(mpc);
% ========== 2. 加载和处理负荷数据 ==========
fprintf('步骤2: 处理负荷数据...\n');
% 生成或加载历史负荷数据(这里生成模拟数据)
num_points = 24*30; % 30天,每小时一个点
time = (1:num_points)';
base_load = 100; % 基础负荷
% 创建模拟负荷数据(包含日周期、周周期和随机波动)
daily_pattern = 50 * sin(2*pi*(0:23)/24) + 100;
weekly_pattern = repmat(daily_pattern, 30, 1);
load_data = weekly_pattern(:) + 20 * randn(num_points, 1);
% 小波分析负荷特征
fs = 1/3600; % 每小时采样一次
[load_features, wavelet_coeffs] = wavelet_load_analysis(load_data, fs, 'db4');
% ========== 3. 设置优化场景 ==========
fprintf('步骤3: 设置优化场景...\n');
% 基于小波分析结果确定优化时段
% 选择负荷波动最大的时段进行优化
[~, peak_indices] = findpeaks(load_data, 'MinPeakHeight', mean(load_data) + std(load_data));
if isempty(peak_indices)
peak_indices = [12, 36, 60]; % 默认值
end
% 设置多个优化场景(峰、平、谷)
optimization_scenarios = struct();
for s = 1:min(3, length(peak_indices))
scenario_time = peak_indices(s);
load_features.current_scale = load_data(scenario_time) / mean(load_data);
optimization_scenarios(s).load_features = load_features;
optimization_scenarios(s).time_index = scenario_time;
end
% ========== 4. 运行PSO优化 ==========
fprintf('步骤4: 运行PSO优化...\n');
optimization_results = cell(length(optimization_scenarios), 1);
for s = 1:length(optimization_scenarios)
fprintf('\n--- 场景 %d (时间点: %d) ---\n', s, optimization_scenarios(s).time_index);
% PSO参数设置
pso_params = struct();
pso_params.pop_size = 40;
pso_params.max_iter = 80;
pso_params.adaptive = true;
pso_params.multi_swarm = true;
% 运行增强PSO
[best_solution, convergence_curve] = enhanced_pso_power_flow(...
system_data, optimization_scenarios(s).load_features, pso_params);
optimization_results{s} = best_solution;
% 保存该场景结果
save(sprintf('optimization_scenario_%d.mat', s), 'best_solution');
end
% ========== 5. 结果分析与对比 ==========
fprintf('\n步骤5: 结果分析与对比...\n');
analyze_and_visualize_results(optimization_results, system_data, load_features);
% ========== 6. 生成优化报告 ==========
generate_optimization_report(optimization_results, load_data, system_data);
fprintf('\n======= 优化完成 =======\n');
4.2 结果可视化与分析
matlab
function analyze_and_visualize_results(opt_results, system_data, load_features)
% 分析并可视化优化结果
num_scenarios = length(opt_results);
figure('Position', [50, 50, 1600, 1000]);
% 子图1:各场景收敛曲线对比
subplot(3, 4, 1);
colors = lines(num_scenarios);
for s = 1:num_scenarios
plot(opt_results{s}.convergence_curve, 'Color', colors(s, :), 'LineWidth', 2);
hold on;
end
xlabel('迭代次数'); ylabel('适应度值');
legend(arrayfun(@(x) sprintf('场景%d', x), 1:num_scenarios, 'UniformOutput', false));
title('各场景收敛曲线对比'); grid on;
% 子图2:网损降低对比
subplot(3, 4, 2);
loss_reduction = zeros(num_scenarios, 1);
for s = 1:num_scenarios
% 计算相对于初始情况的网损降低
initial_loss = calculate_initial_loss(system_data, load_features);
loss_reduction(s) = (initial_loss - opt_results{s}.power_loss) / initial_loss * 100;
end
bar(1:num_scenarios, loss_reduction);
xlabel('场景'); ylabel('网损降低百分比 (%)');
title('网损优化效果'); grid on;
ylim([0, max(loss_reduction)*1.1]);
% 子图3:电压分布对比
subplot(3, 4, 3);
voltage_profiles = zeros(system_data.nbus, num_scenarios);
for s = 1:num_scenarios
voltage_profiles(:, s) = opt_results{s}.voltage_profile;
end
boxplot(voltage_profiles);
xlabel('场景'); ylabel('电压幅值 (p.u.)');
title('节点电压分布'); grid on;
hold on;
plot([0, num_scenarios+1], [0.95, 0.95], 'r--', 'LineWidth', 1.5);
plot([0, num_scenarios+1], [1.05, 1.05], 'r--', 'LineWidth', 1.5);
% 子图4:发电机出力优化
subplot(3, 4, 4);
gen_power_matrix = zeros(system_data.ngen, num_scenarios);
for s = 1:num_scenarios
gen_power_matrix(:, s) = opt_results{s}.gen_power;
end
bar(gen_power_matrix', 'grouped');
xlabel('场景'); ylabel('发电机出力 (MW)');
title('各场景发电机出力优化'); grid on;
legend(arrayfun(@(x) sprintf('G%d', x), 1:system_data.ngen, 'UniformOutput', false), ...
'Location', 'best');
% 子图5:变压器变比优化
subplot(3, 4, 5);
if system_data.ntap > 0
tap_matrix = zeros(system_data.ntap, num_scenarios);
for s = 1:num_scenarios
tap_matrix(:, s) = opt_results{s}.transformer_taps;
end
bar(tap_matrix', 'grouped');
xlabel('场景'); ylabel('变比值');
title('变压器变比优化'); grid on;
legend(arrayfun(@(x) sprintf('Tap%d', x), 1:system_data.ntap, 'UniformOutput', false));
end
% 子图6:种群多样性变化
subplot(3, 4, 6);
for s = 1:num_scenarios
plot(opt_results{s}.diversity_history, 'Color', colors(s, :), 'LineWidth', 1.5);
hold on;
end
xlabel('迭代次数'); ylabel('种群多样性');
title('PSO种群多样性变化'); grid on;
legend(arrayfun(@(x) sprintf('场景%d', x), 1:num_scenarios, 'UniformOutput', false));
% 子图7:优化前后潮流对比(第一个场景)
subplot(3, 4, 7);
if num_scenarios >= 1
% 计算初始潮流
mpc_initial = system_data.mpc;
mpc_initial.bus(:, 3) = mpc_initial.bus(:, 3) * load_features.current_scale;
results_initial = runpf(mpc_initial);
% 优化后潮流
mpc_optimal = update_system_with_solution(system_data.mpc, opt_results{1}, load_features);
results_optimal = runpf(mpc_optimal);
% 绘制线路负载率对比
initial_loading = abs(results_initial.branch(:, 14) + 1i*results_initial.branch(:, 15)) ./ ...
system_data.line_limits * 100;
optimal_loading = abs(results_optimal.branch(:, 14) + 1i*results_optimal.branch(:, 15)) ./ ...
system_data.line_limits * 100;
plot(1:length(initial_loading), initial_loading, 'bo-', 'LineWidth', 1.5, 'MarkerSize', 6);
hold on;
plot(1:length(optimal_loading), optimal_loading, 'rs--', 'LineWidth', 1.5, 'MarkerSize', 6);
plot([0, length(initial_loading)+1], [100, 100], 'r--', 'LineWidth', 1.5);
xlabel('线路编号'); ylabel('负载率 (%)');
title('优化前后线路负载对比'); grid on;
legend('优化前', '优化后', '限值', 'Location', 'best');
end
% 子图8:成本节约分析
subplot(3, 4, 8);
cost_savings = zeros(num_scenarios, 1);
for s = 1:num_scenarios
% 简化成本计算
initial_cost = calculate_operating_cost(system_data, load_features, 'initial');
optimal_cost = calculate_operating_cost(system_data, load_features, 'optimal', opt_results{s});
cost_savings(s) = (initial_cost - optimal_cost) / initial_cost * 100;
end
bar(1:num_scenarios, cost_savings);
xlabel('场景'); ylabel('成本节约 (%)');
title('运行成本节约分析'); grid on;
% 子图9:小波特征与优化效果关系
subplot(3, 4, 9);
if num_scenarios >= 3
% 提取小波特征
wavelet_features = [load_features.volatility_index, ...
mean(load_features.energy_ratio(1:2)), ...
load_features.load_factor];
% 优化效果指标
optimization_metrics = [loss_reduction, cost_savings];
% 绘制相关性图
imagesc(corrcoef([wavelet_features, optimization_metrics]));
colorbar; colormap('jet');
set(gca, 'XTick', 1:5, 'XTickLabel', {'波动性', '高频能量', '负荷率', '网损降低', '成本节约'});
set(gca, 'YTick', 1:5, 'YTickLabel', {'波动性', '高频能量', '负荷率', '网损降低', '成本节约'});
title('小波特征与优化效果相关性');
end
% 子图10-12:详细分析
for s = 1:min(3, num_scenarios)
subplot(3, 4, 9+s);
% 显示该场景的关键指标
metrics = [opt_results{s}.power_loss, ...
mean(opt_results{s}.voltage_profile), ...
std(opt_results{s}.voltage_profile), ...
max(abs(diff(opt_results{s}.gen_power)))];
bar(1:4, metrics);
set(gca, 'XTickLabel', {'网损(MW)', '平均电压', '电压偏差', '最大出力变化'});
title(sprintf('场景%d关键指标', s));
grid on;
% 添加数值标签
for i = 1:4
text(i, metrics(i)*1.02, sprintf('%.3f', metrics(i)), ...
'HorizontalAlignment', 'center', 'FontSize', 8);
end
end
end
五、实际应用建议
5.1 系统配置要求
-
软件环境:
- MATLAB R2018b或更高版本
- 安装MATPOWER工具箱(用于潮流计算)
- 信号处理工具箱(用于小波分析)
-
硬件建议:
- 8GB以上内存
- 4核以上CPU
- 对于大规模电网(>100节点),建议使用16GB内存
5.2 参数调优指南
| 参数 | 推荐范围 | 调优建议 |
|---|---|---|
| 小波分解层数 | 4-6层 | 负荷数据越长,可选更多层数 |
| 小波基函数 | db4, sym8 | db4适合突变信号,sym8更平滑 |
| PSO种群大小 | 30-100 | 问题维度高时需增大种群 |
| 惯性权重 | 0.4-0.9 | 自适应递减策略效果最佳 |
| 学习因子 | c1=2.0, c2=2.0 | 可尝试c1递减、c2递增策略 |
5.3 针对不同电网规模的调整
matlab
% 大规模电网优化策略调整
function params = adjust_for_large_scale(system_size)
params = struct();
if system_size.nbus < 50
% 小型电网
params.pso_pop_size = 30;
params.pso_max_iter = 50;
params.wavelet_level = 4;
elseif system_size.nbus < 200
% 中型电网
params.pso_pop_size = 50;
params.pso_max_iter = 80;
params.wavelet_level = 5;
params.use_parallel = true; % 启用并行计算
else
% 大型电网
params.pso_pop_size = 80;
params.pso_max_iter = 120;
params.wavelet_level = 6;
params.use_parallel = true;
params.use_reduced_model = true; % 使用简化模型
end
end
5.4 常见问题与解决方案
| 问题 | 症状 | 解决方案 |
|---|---|---|
| PSO早熟收敛 | 适应度快速收敛但未达最优 | 增加种群多样性,添加混沌扰动 |
| 潮流计算不收敛 | 优化过程中频繁不收敛 | 放宽约束条件,增加惩罚系数 |
| 计算时间过长 | 单次优化超过30分钟 | 减少种群大小,使用并行计算 |
| 电压越限严重 | 优化后仍有电压越限 | 增加电压偏差权重,强化电压约束 |
六、快速测试模板
matlab
%% 快速测试模板(简化版)
clear; clc;
% 1. 加载测试数据
test_case = 'case14'; % IEEE 14节点系统
mpc = loadcase(test_case);
% 2. 生成模拟负荷数据(24小时)
hourly_load = [85, 80, 78, 76, 75, 80, 90, 95, 100, 105, 110, 115, ...
120, 125, 130, 135, 140, 145, 140, 130, 120, 110, 100, 90];
% 3. 小波分析(快速模式)
[load_features, ~] = wavelet_load_analysis(hourly_load', 1, 'db4');
% 4. 准备系统数据
system_data = prepare_system_data(mpc);
% 5. 运行快速PSO优化
fprintf('开始快速优化...\n');
pso_params.pop_size = 20;
pso_params.max_iter = 30;
pso_params.adaptive = false;
load_features.current_scale = 1.0; % 当前负荷水平
[best_solution, ~] = enhanced_pso_power_flow(system_data, load_features, pso_params);
% 6. 显示关键结果
fprintf('\n优化结果概要:\n');
fprintf('网损: %.4f MW → %.4f MW (降低 %.1f%%)\n', ...
calculate_initial_loss(system_data, load_features), ...
best_solution.power_loss, ...
(calculate_initial_loss(system_data, load_features) - best_solution.power_loss) / ...
calculate_initial_loss(system_data, load_features) * 100);
fprintf('电压越限节点数: %d → %d\n', ...
count_voltage_violations(system_data, load_features), ...
sum(best_solution.voltage_profile < 0.95 | best_solution.voltage_profile > 1.05));
% 7. 可视化
figure;
subplot(1,2,1);
plot(best_solution.convergence_curve, 'b-o', 'LineWidth', 1.5);
xlabel('迭代次数'); ylabel('适应度'); grid on;
title('收敛曲线');
subplot(1,2,2);
bar(best_solution.gen_power);
xlabel('发电机编号'); ylabel('出力 (MW)'); grid on;
title('优化后的发电机出力');
参考代码 基于小波分析,粒子群算法的在matlab开发环境中的电网潮流优化 www.3dddown.com/csa/96290.html
七、总结
该方案成功将小波分析的时频分析能力 与粒子群算法的全局优化能力相结合,实现了对电网潮流的智能优化。主要优势包括:
- 精准特征提取:小波分析能有效识别负荷的周期性、波动性特征
- 智能优化:改进PSO算法避免局部最优,提高优化质量
- 多目标平衡:同时考虑网损、电压质量、运行成本等多个目标
- 实用性强:可直接应用于实际电网调度系统