Files
multi_energy_complementarity/tests/test_multi_scenario.py
2025-12-27 20:40:18 +08:00

131 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""测试多场景聚类模块"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
from multi_scenario import MultiScenarioAnalyzer
import numpy as np
def test_multi_scenario_basic():
"""测试基本功能"""
print("测试多场景聚类基本功能...")
# 生成简单的测试数据24小时
hours = 24
solar_output = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0,
5.0, 4.0, 3.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
wind_output = [2.0, 3.0, 4.0, 3.0, 2.0, 1.0, 1.0, 2.0, 3.0, 4.0, 3.0, 2.0,
2.0, 3.0, 4.0, 3.0, 2.0, 1.0, 1.0, 2.0, 3.0, 4.0, 3.0, 2.0]
load_demand = [3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 18.0,
16.0, 14.0, 12.0, 10.0, 8.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 2.0]
# 创建分析器
analyzer = MultiScenarioAnalyzer(n_clusters=3, random_state=42)
try:
# 执行聚类分析
result = analyzer.fit_predict(solar_output, wind_output, load_demand)
print("✅ 基本聚类测试通过")
print(f" - 识别场景数: {result.n_scenarios}")
print(f" - 轮廓系数: {result.silhouette_score:.3f}")
print(f" - 场景名称: {result.scenario_names}")
return True
except Exception as e:
print(f"❌ 测试失败: {str(e)}")
import traceback
traceback.print_exc()
return False
def test_multi_scenario_yearly():
"""测试年度数据聚类"""
print("\n测试年度数据聚类...")
# 生成模拟的8760小时数据
np.random.seed(42)
# 简单的模拟数据
solar_output = []
wind_output = []
load_demand = []
for day in range(365):
# 光伏白天有出力夜间为0
daily_solar = [0.0] * 6 + list(np.random.uniform(1, 6, 12)) + [0.0] * 6
solar_output.extend(daily_solar)
# 风电:相对随机
daily_wind = np.random.exponential(2.5, 24).tolist()
wind_output.extend(daily_wind)
# 负荷:日内变化,夜间低,白天高
daily_load = [3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 18.0,
16.0, 14.0, 12.0, 10.0, 8.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 2.0]
load_demand.extend(daily_load)
try:
analyzer = MultiScenarioAnalyzer(n_clusters=5, random_state=42)
result = analyzer.fit_predict(solar_output, wind_output, load_demand, find_optimal_k=True)
print("✅ 年度数据聚类测试通过")
print(f" - 最优聚类数: {result.n_scenarios}")
print(f" - 轮廓系数: {result.silhouette_score:.3f}")
# 输出前3个场景的统计
for i in range(min(3, result.n_scenarios)):
stats = result.scenario_stats[f'scenario_{i}']
print(f" - 场景{i+1}: 频率{stats['frequency']:.1%}, "
f"光伏{stats['solar_mean']:.1f}MW, "
f"风电{stats['wind_mean']:.1f}MW, "
f"负荷{stats['load_mean']:.1f}MW")
# 测试图表生成
print(" - 测试图表生成...")
analyzer.plot_scenario_analysis(result, solar_output, wind_output, load_demand,
save_path="test_scenario_analysis.png")
print(" ✅ 图表生成成功")
return True
except Exception as e:
print(f"❌ 年度数据测试失败: {str(e)}")
import traceback
traceback.print_exc()
return False
def test_data_validation():
"""测试数据验证"""
print("\n测试数据验证...")
# 测试数据长度不一致
try:
analyzer = MultiScenarioAnalyzer(n_clusters=2)
analyzer.fit_predict([1, 2, 3], [1, 2], [1, 2, 3]) # 长度不一致
print("❌ 应该检测到数据长度不一致")
return False
except ValueError as e:
print("✅ 正确检测到数据长度不一致")
return True
if __name__ == "__main__":
print("=== 多场景聚类模块测试 ===\n")
success = True
success &= test_multi_scenario_basic()
success &= test_multi_scenario_yearly()
success &= test_data_validation()
print(f"\n{'='*50}")
if success:
print("🎉 所有测试通过!多场景聚类模块工作正常。")
else:
print("💥 部分测试失败,请检查代码。")
print(f"{'='*50}")