一、设计
┌─────────────────────────────────────────────────────────────┐
│ 遗传算法无功补偿优化系统 │
├─────────────────────────────────────────────────────────────┤
│ 电网建模层 │ 遗传算法层 │ 适应度评估层 │ 优化输出层 │
│ │ │ │ │
│ • 线路参数 │ • 染色体编码 │ • 网损计算 │ • 最优配置 │
│ • 负荷模型 │ • 选择算子 │ • 电压偏差 │ • 补偿方案 │
│ • 节点导纳 │ • 交叉算子 │ • 约束处理 │ • 经济性分析 │
│ • 电容器组 │ • 变异算子 │ • 罚函数设计 │ • 灵敏度分析 │
└─────────────────────────────────────────────────────────────┘
二、C# 实现
2.1 电力系统模型定义 (PowerSystemModel.cs)
csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace ReactivePowerOptimization
{
/// <summary>
/// 输电线路参数
/// </summary>
public class TransmissionLine
{
public int FromNode { get; set; }
public int ToNode { get; set; }
public double Resistance { get; set; } // 电阻 (Ω)
public double Reactance { get; set; } // 电抗 (Ω)
public double Susceptance { get; set; } // 电纳 (S)
public double CurrentRating { get; set; } // 额定电流 (A)
public double VoltageRating { get; set; } // 额定电压 (kV)
}
/// <summary>
/// 负荷节点
/// </summary>
public class LoadNode
{
public int NodeId { get; set; }
public double ActivePower { get; set; } // 有功负荷 (MW)
public double ReactivePower { get; set; } // 无功负荷 (MVAr)
public double VoltageMagnitude { get; set; } // 电压幅值 (p.u.)
public double VoltageAngle { get; set; } // 电压相角 (度)
public double MinVoltage { get; set; } = 0.95; // 最低电压 (p.u.)
public double MaxVoltage { get; set; } = 1.05; // 最高电压 (p.u.)
}
/// <summary>
/// 电容器组
/// </summary>
public class CapacitorBank
{
public int NodeId { get; set; }
public double RatedPower { get; set; } // 额定容量 (MVAr)
public int MaxSteps { get; set; } // 最大投切档位
public double StepSize { get; set; } // 单步容量 (MVAr)
public double InstallationCost { get; set; } // 安装成本 ($/MVAr)
public double OperationCost { get; set; } // 运行成本 ($/小时)
public int CurrentStep { get; set; } = 0; // 当前档位
}
/// <summary>
/// 电力系统模型
/// </summary>
public class PowerSystemModel
{
public List<TransmissionLine> Lines { get; set; } = new List<TransmissionLine>();
public List<LoadNode> Nodes { get; set; } = new List<LoadNode>();
public List<CapacitorBank> Capacitors { get; set; } = new List<CapacitorBank>();
// 系统基准值
public double BasePower { get; set; } = 100.0; // 基准功率 (MVA)
public double BaseVoltage { get; set; } = 230.0; // 基准电压 (kV)
public double Frequency { get; set; } = 60.0; // 系统频率 (Hz)
/// <summary>
/// 计算系统总负荷
/// </summary>
public (double totalP, double totalQ) CalculateTotalLoad()
{
double totalP = Nodes.Sum(n => n.ActivePower);
double totalQ = Nodes.Sum(n => n.ReactivePower);
return (totalP, totalQ);
}
/// <summary>
/// 计算系统总有功损耗
/// </summary>
public double CalculateTotalLosses()
{
double totalLosses = 0;
foreach (var line in Lines)
{
// 简化计算:基于电流平方的损耗
double current = CalculateLineCurrent(line);
totalLosses += 3 * line.Resistance * Math.Pow(current, 2) / 1000; // MW
}
return totalLosses;
}
private double CalculateLineCurrent(TransmissionLine line)
{
// 简化的电流计算
var fromNode = Nodes.FirstOrDefault(n => n.NodeId == line.FromNode);
var toNode = Nodes.FirstOrDefault(n => n.NodeId == line.ToNode);
if (fromNode == null || toNode == null) return 0;
double power = Math.Sqrt(Math.Pow(fromNode.ActivePower, 2) +
Math.Pow(fromNode.ReactivePower, 2));
return power * 1000 / (Math.Sqrt(3) * line.VoltageRating); // A
}
}
}
2.2 遗传算法核心实现 (GeneticAlgorithm.cs)
csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace ReactivePowerOptimization
{
/// <summary>
/// 遗传算法染色体(电容器投切方案)
/// </summary>
public class Chromosome
{
public int[] CapacitorSteps { get; set; } // 各电容器组投切档位
public double Fitness { get; set; } // 适应度值
public double Losses { get; set; } // 网损 (MW)
public double VoltageViolation { get; set; } // 电压越限惩罚
public double Cost { get; set; } // 总成本 ($)
public Chromosome(int capacitorCount)
{
CapacitorSteps = new int[capacitorCount];
}
/// <summary>
/// 克隆染色体
/// </summary>
public Chromosome Clone()
{
var clone = new Chromosome(CapacitorSteps.Length);
Array.Copy(CapacitorSteps, clone.CapacitorSteps, CapacitorSteps.Length);
clone.Fitness = Fitness;
clone.Losses = Losses;
clone.VoltageViolation = VoltageViolation;
clone.Cost = Cost;
return clone;
}
}
/// <summary>
/// 遗传算法优化器
/// </summary>
public class GeneticAlgorithmOptimizer
{
private readonly PowerSystemModel _powerSystem;
private readonly Random _random = new Random();
// 遗传算法参数
public int PopulationSize { get; set; } = 100;
public int Generations { get; set; } = 200;
public double CrossoverRate { get; set; } = 0.85;
public double MutationRate { get; set; } = 0.05;
public int TournamentSize { get; set; } = 3;
// 适应度权重
public double LossWeight { get; set; } = 0.4; // 网损权重
public double VoltageWeight { get; set; } = 0.4; // 电压权重
public double CostWeight { get; set; } = 0.2; // 成本权重
public GeneticAlgorithmOptimizer(PowerSystemModel powerSystem)
{
_powerSystem = powerSystem ?? throw new ArgumentNullException(nameof(powerSystem));
}
/// <summary>
/// 执行优化
/// </summary>
public Chromosome Optimize()
{
Console.WriteLine("开始遗传算法优化...");
Console.WriteLine($"种群大小: {PopulationSize}, 代数: {Generations}");
// 1. 初始化种群
var population = InitializePopulation();
var bestChromosome = population[0].Clone();
// 2. 进化循环
for (int generation = 0; generation < Generations; generation++)
{
// 评估适应度
EvaluatePopulation(population);
// 记录最佳个体
var currentBest = population.OrderByDescending(c => c.Fitness).First();
if (currentBest.Fitness > bestChromosome.Fitness)
{
bestChromosome = currentBest.Clone();
}
// 显示进度
if (generation % 20 == 0)
{
Console.WriteLine($"代数 {generation}: 最佳适应度 = {bestChromosome.Fitness:F4}, " +
$"网损 = {bestChromosome.Losses:F2} MW, " +
$"成本 = ${bestChromosome.Cost:F2}");
}
// 3. 选择
var selected = Selection(population);
// 4. 交叉
var offspring = Crossover(selected);
// 5. 变异
Mutate(offspring);
// 6. 新一代种群
population = offspring;
}
Console.WriteLine("优化完成!");
return bestChromosome;
}
/// <summary>
/// 初始化种群
/// </summary>
private List<Chromosome> InitializePopulation()
{
var population = new List<Chromosome>();
for (int i = 0; i < PopulationSize; i++)
{
var chromosome = new Chromosome(_powerSystem.Capacitors.Count);
// 随机生成初始解
for (int j = 0; j < chromosome.CapacitorSteps.Length; j++)
{
var capacitor = _powerSystem.Capacitors[j];
chromosome.CapacitorSteps[j] = _random.Next(0, capacitor.MaxSteps + 1);
}
population.Add(chromosome);
}
return population;
}
/// <summary>
/// 评估种群适应度
/// </summary>
private void EvaluatePopulation(List<Chromosome> population)
{
foreach (var chromosome in population)
{
// 应用电容器投切方案
ApplyCapacitorConfiguration(chromosome);
// 计算网损
chromosome.Losses = _powerSystem.CalculateTotalLosses();
// 计算电压越限惩罚
chromosome.VoltageViolation = CalculateVoltageViolation();
// 计算总成本
chromosome.Cost = CalculateTotalCost(chromosome);
// 计算适应度(越大越好)
chromosome.Fitness = CalculateFitness(chromosome);
}
}
/// <summary>
/// 应用电容器配置
/// </summary>
private void ApplyCapacitorConfiguration(Chromosome chromosome)
{
for (int i = 0; i < _powerSystem.Capacitors.Count; i++)
{
var capacitor = _powerSystem.Capacitors[i];
capacitor.CurrentStep = chromosome.CapacitorSteps[i];
// 更新节点无功功率(简化模型)
var node = _powerSystem.Nodes.FirstOrDefault(n => n.NodeId == capacitor.NodeId);
if (node != null)
{
double reactiveCompensation = capacitor.CurrentStep * capacitor.StepSize;
node.ReactivePower = Math.Max(0, node.ReactivePower - reactiveCompensation);
}
}
}
/// <summary>
/// 计算电压越限惩罚
/// </summary>
private double CalculateVoltageViolation()
{
double totalViolation = 0;
foreach (var node in _powerSystem.Nodes)
{
if (node.VoltageMagnitude < node.MinVoltage)
{
totalViolation += (node.MinVoltage - node.VoltageMagnitude) * 1000;
}
else if (node.VoltageMagnitude > node.MaxVoltage)
{
totalViolation += (node.VoltageMagnitude - node.MaxVoltage) * 1000;
}
}
return totalViolation;
}
/// <summary>
/// 计算总成本
/// </summary>
private double CalculateTotalCost(Chromosome chromosome)
{
double totalCost = 0;
for (int i = 0; i < _powerSystem.Capacitors.Count; i++)
{
var capacitor = _powerSystem.Capacitors[i];
double installedCapacity = capacitor.CurrentStep * capacitor.StepSize;
totalCost += installedCapacity * capacitor.InstallationCost;
totalCost += capacitor.OperationCost * 8760; // 年运行成本
}
// 加上网损成本
totalCost += chromosome.Losses * 50 * 8760; // $50/MWh
return totalCost;
}
/// <summary>
/// 计算适应度
/// </summary>
private double CalculateFitness(Chromosome chromosome)
{
// 适应度 = 1 / (加权目标函数)
double objective = LossWeight * chromosome.Losses +
VoltageWeight * chromosome.VoltageViolation +
CostWeight * chromosome.Cost / 1000000; // 归一化
return 1.0 / (objective + 1e-6); // 避免除零
}
/// <summary>
/// 锦标赛选择
/// </summary>
private List<Chromosome> Selection(List<Chromosome> population)
{
var selected = new List<Chromosome>();
for (int i = 0; i < population.Count; i++)
{
var tournament = new List<Chromosome>();
// 随机选择个体参加锦标赛
for (int j = 0; j < TournamentSize; j++)
{
int randomIndex = _random.Next(population.Count);
tournament.Add(population[randomIndex]);
}
// 选择适应度最高的个体
var winner = tournament.OrderByDescending(c => c.Fitness).First();
selected.Add(winner.Clone());
}
return selected;
}
/// <summary>
/// 交叉操作
/// </summary>
private List<Chromosome> Crossover(List<Chromosome> parents)
{
var offspring = new List<Chromosome>();
for (int i = 0; i < parents.Count; i += 2)
{
if (i + 1 >= parents.Count) break;
var parent1 = parents[i];
var parent2 = parents[i + 1];
if (_random.NextDouble() < CrossoverRate)
{
// 单点交叉
int crossoverPoint = _random.Next(parent1.CapacitorSteps.Length);
var child1 = parent1.Clone();
var child2 = parent2.Clone();
for (int j = crossoverPoint; j < parent1.CapacitorSteps.Length; j++)
{
child1.CapacitorSteps[j] = parent2.CapacitorSteps[j];
child2.CapacitorSteps[j] = parent1.CapacitorSteps[j];
}
offspring.Add(child1);
offspring.Add(child2);
}
else
{
offspring.Add(parent1.Clone());
offspring.Add(parent2.Clone());
}
}
return offspring;
}
/// <summary>
/// 变异操作
/// </summary>
private void Mutate(List<Chromosome> population)
{
foreach (var chromosome in population)
{
for (int i = 0; i < chromosome.CapacitorSteps.Length; i++)
{
if (_random.NextDouble() < MutationRate)
{
var capacitor = _powerSystem.Capacitors[i];
chromosome.CapacitorSteps[i] = _random.Next(0, capacitor.MaxSteps + 1);
}
}
}
}
}
}
2.3 主程序与测试 (Program.cs)
csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace ReactivePowerOptimization
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("====== 基于遗传算法的输电线路无功补偿优化 ======\n");
// 1. 创建电力系统模型
var powerSystem = CreateTestPowerSystem();
// 2. 显示系统基本信息
DisplaySystemInfo(powerSystem);
// 3. 计算初始状态
Console.WriteLine("\n--- 初始状态(无补偿) ---");
var initialLosses = powerSystem.CalculateTotalLosses();
var initialLoad = powerSystem.CalculateTotalLoad();
Console.WriteLine($"总负荷: {initialLoad.totalP:F2} MW + j{initialLoad.totalQ:F2} MVAr");
Console.WriteLine($"初始网损: {initialLosses:F2} MW");
Console.WriteLine($"网损率: {initialLosses / initialLoad.totalP * 100:F2}%");
// 4. 创建并配置遗传算法优化器
var optimizer = new GeneticAlgorithmOptimizer(powerSystem)
{
PopulationSize = 80,
Generations = 150,
CrossoverRate = 0.85,
MutationRate = 0.08,
TournamentSize = 4,
LossWeight = 0.5,
VoltageWeight = 0.3,
CostWeight = 0.2
};
// 5. 执行优化
Console.WriteLine("\n--- 开始优化计算 ---");
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var bestSolution = optimizer.Optimize();
stopwatch.Stop();
// 6. 显示优化结果
DisplayOptimizationResults(powerSystem, bestSolution, stopwatch.ElapsedMilliseconds);
// 7. 敏感性分析
PerformSensitivityAnalysis(powerSystem, bestSolution);
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
static PowerSystemModel CreateTestPowerSystem()
{
var system = new PowerSystemModel
{
BasePower = 100.0, // 100 MVA
BaseVoltage = 230.0, // 230 kV
Frequency = 60.0 // 60 Hz
};
// 创建输电线路
system.Lines.Add(new TransmissionLine
{
FromNode = 1,
ToNode = 2,
Resistance = 0.1,
Reactance = 0.4,
Susceptance = 0.01,
CurrentRating = 1000,
VoltageRating = 230
});
system.Lines.Add(new TransmissionLine
{
FromNode = 2,
ToNode = 3,
Resistance = 0.15,
Reactance = 0.6,
Susceptance = 0.015,
CurrentRating = 800,
VoltageRating = 230
});
// 创建负荷节点
system.Nodes.Add(new LoadNode
{
NodeId = 1,
ActivePower = 50.0,
ReactivePower = 30.0,
VoltageMagnitude = 1.0,
VoltageAngle = 0.0
});
system.Nodes.Add(new LoadNode
{
NodeId = 2,
ActivePower = 80.0,
ReactivePower = 50.0,
VoltageMagnitude = 0.98,
VoltageAngle = -2.5
});
system.Nodes.Add(new LoadNode
{
NodeId = 3,
ActivePower = 70.0,
ReactivePower = 40.0,
VoltageMagnitude = 0.97,
VoltageAngle = -5.0
});
// 创建电容器组
system.Capacitors.Add(new CapacitorBank
{
NodeId = 2,
RatedPower = 60.0, // 60 MVAr
MaxSteps = 6,
StepSize = 10.0, // 10 MVAr/步
InstallationCost = 50000, // $50k/MVAr
OperationCost = 100 // $100/小时
});
system.Capacitors.Add(new CapacitorBank
{
NodeId = 3,
RatedPower = 40.0, // 40 MVAr
MaxSteps = 4,
StepSize = 10.0, // 10 MVAr/步
InstallationCost = 60000, // $60k/MVAr
OperationCost = 120 // $120/小时
});
return system;
}
static void DisplaySystemInfo(PowerSystemModel system)
{
Console.WriteLine("电力系统配置:");
Console.WriteLine($" 基准容量: {system.BasePower} MVA");
Console.WriteLine($" 基准电压: {system.BaseVoltage} kV");
Console.WriteLine($" 线路数量: {system.Lines.Count}");
Console.WriteLine($" 节点数量: {system.Nodes.Count}");
Console.WriteLine($" 电容器组数量: {system.Capacitors.Count}");
}
static void DisplayOptimizationResults(PowerSystemModel system, Chromosome solution, long elapsedMs)
{
Console.WriteLine("\n=== 优化结果 ===");
Console.WriteLine($"计算时间: {elapsedMs} ms");
Console.WriteLine($"最佳适应度: {solution.Fitness:F4}");
Console.WriteLine($"优化后网损: {solution.Losses:F2} MW");
Console.WriteLine($"总成本: ${solution.Cost:F2}");
Console.WriteLine("\n--- 最优电容器投切方案 ---");
for (int i = 0; i < solution.CapacitorSteps.Length; i++)
{
var capacitor = system.Capacitors[i];
double compensation = solution.CapacitorSteps[i] * capacitor.StepSize;
Console.WriteLine($" 节点 {capacitor.NodeId}: {solution.CapacitorSteps[i]} 档, " +
$"补偿容量 {compensation:F1} MVAr");
}
// 计算节能效果
var initialLosses = system.CalculateTotalLosses();
double savings = (initialLosses - solution.Losses) * 50 * 8760; // 年节约电费
Console.WriteLine($"\n--- 经济效益分析 ---");
Console.WriteLine($"年节约网损: {(initialLosses - solution.Losses) * 8760:F0} MWh");
Console.WriteLine($"年节约电费: ${savings:F0}");
Console.WriteLine($"投资回收期: {solution.Cost / savings:F1} 年");
}
static void PerformSensitivityAnalysis(PowerSystemModel system, Chromosome baseSolution)
{
Console.WriteLine("\n--- 敏感性分析 ---");
// 分析不同负荷水平下的性能
double[] loadFactors = { 0.8, 0.9, 1.0, 1.1, 1.2 };
foreach (var factor in loadFactors)
{
// 调整负荷
foreach (var node in system.Nodes)
{
node.ActivePower *= factor;
node.ReactivePower *= factor;
}
// 应用最优方案
foreach (var capacitor in system.Capacitors)
{
capacitor.CurrentStep = baseSolution.CapacitorSteps[system.Capacitors.IndexOf(capacitor)];
}
var losses = system.CalculateTotalLosses();
Console.WriteLine($"负荷因子 {factor:F1}: 网损 {losses:F2} MW");
}
}
}
}
三、算法特点与工业应用
3.1 算法优势
| 特性 | 说明 |
|---|---|
| 全局优化 | 避免陷入局部最优,找到全局最优解 |
| 多目标优化 | 同时考虑网损、电压质量和经济性 |
| 约束处理 | 通过罚函数处理电压和容量约束 |
| 鲁棒性 | 对初始条件不敏感,结果稳定 |
3.2 工业应用场景
- 输电网络优化:大容量输电线路的动态无功补偿
- 配电网络规划:分布式电容器组的优化配置
- 新能源并网:风电场、光伏电站的无功支撑优化
- 微电网调度:孤岛运行时的无功电压控制
3.3 参数调优建议
| 参数 | 建议值 | 说明 |
|---|---|---|
| PopulationSize | 50-200 | 种群越大,搜索越充分,但计算越慢 |
| Generations | 100-500 | 根据问题复杂度调整 |
| CrossoverRate | 0.7-0.9 | 交叉概率越高,收敛越快 |
| MutationRate | 0.05-0.1 | 变异概率太低易早熟,太高不稳定 |
参考代码 基于遗传算法的无功补偿程序,可用于对输电线路进行无功补偿 www.youwenfan.com/contentcsu/63147.html
四、扩展功能建议
- 并行计算:使用多线程或GPU加速遗传算法
- 混合算法:结合粒子群优化(PSO)提高收敛速度
- 实时优化:结合SCADA系统进行在线无功优化
- 不确定性处理:考虑负荷预测误差和设备故障概率