修复了储能电量不平衡的问题。

This commit is contained in:
dmy
2025-12-27 12:25:01 +08:00
parent a522132ede
commit 164b9da026
2 changed files with 251 additions and 101 deletions

89
main.py
View File

@@ -25,11 +25,11 @@ plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
def plot_system_curves(solar_output, wind_output, thermal_output, load_demand, result, storage_efficiency=0.9, show_window=False, display_only=False):
def plot_system_curves(solar_output, wind_output, thermal_output, load_demand, result, storage_efficiency=0.9, show_window=False, display_only=False, output_dir=None):
"""
绘制系统运行曲线
Args:
Args:
solar_output: 光伏出力曲线 (MW) - 支持24小时或8760小时
wind_output: 风电出力曲线 (MW) - 支持24小时或8760小时
thermal_output: 火电出力曲线 (MW) - 支持24小时或8760小时
@@ -37,6 +37,7 @@ def plot_system_curves(solar_output, wind_output, thermal_output, load_demand, r
result: 优化结果字典
show_window: 是否显示图形窗口
display_only: 是否只显示不保存文件
output_dir: 输出目录路径,默认为 None当前目录
"""
import matplotlib.pyplot as plt
import numpy as np
@@ -148,15 +149,17 @@ def plot_system_curves(solar_output, wind_output, thermal_output, load_demand, r
plt.tight_layout()
# 根据参数决定是否保存和显示图形
if display_only:
# 只显示,不保存
try:
plt.show()
except Exception as e:
print(f"无法显示图形窗口:{str(e)}")
else:
# 保存图片
plt.savefig('system_curves.png', dpi=300, bbox_inches='tight')
if not display_only:
# 确定输出目录
if output_dir is None:
output_dir = 'results'
# 创建输出目录(如果不存在)
os.makedirs(output_dir, exist_ok=True)
# 保存图片到指定目录
output_path = os.path.join(output_dir, 'system_curves.png')
plt.savefig(output_path, dpi=300, bbox_inches='tight')
# 根据参数决定是否显示图形窗口
if show_window:
@@ -164,7 +167,7 @@ def plot_system_curves(solar_output, wind_output, thermal_output, load_demand, r
plt.show()
except Exception as e:
print(f"无法显示图形窗口:{str(e)}")
print("图形已保存为 'system_curves.png'")
print(f"图形已保存为 '{output_path}'")
else:
plt.close() # 关闭图形,不显示窗口
@@ -238,7 +241,7 @@ def plot_system_curves(solar_output, wind_output, thermal_output, load_demand, r
print(f"储能损耗率: {(storage_loss/total_charge*100) if total_charge > 0 else 0:.2f}%")
def export_results_to_excel(solar_output, wind_output, thermal_output, load_demand, result, params, filename=None):
def export_results_to_excel(solar_output, wind_output, thermal_output, load_demand, result, params, filename=None, output_dir=None):
"""
将多能互补系统储能优化结果导出到Excel文件包含运行数据、统计结果和系统参数。
@@ -262,6 +265,7 @@ def export_results_to_excel(solar_output, wind_output, thermal_output, load_dema
- capacity_limit_reached: 容量限制是否达到
params (object): 系统参数对象,包含各种技术参数
filename (str, optional): 输出文件名,如未提供则自动生成
output_dir (str, optional): 输出目录路径,默认为 None使用 results 目录)
Returns:
str: 生成的Excel文件路径
@@ -287,8 +291,18 @@ def export_results_to_excel(solar_output, wind_output, thermal_output, load_dema
if filename is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"storage_optimization_results_{timestamp}.xlsx"
# 确定输出目录
if output_dir is None:
output_dir = 'results'
# 创建输出目录(如果不存在)
os.makedirs(output_dir, exist_ok=True)
# 构建完整的输出路径
output_path = os.path.join(output_dir, filename)
print(f"\n正在导出结果到Excel文件: {filename}")
print(f"\n正在导出结果到Excel文件: {output_path}")
# 准备数据
hours = list(range(1, len(solar_output) + 1))
@@ -410,7 +424,7 @@ def export_results_to_excel(solar_output, wind_output, thermal_output, load_dema
})
# 写入Excel文件
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
# 写入主要数据
data_df.to_excel(writer, sheet_name='运行数据', index=False)
@@ -439,8 +453,8 @@ def export_results_to_excel(solar_output, wind_output, thermal_output, load_dema
})
description_df.to_excel(writer, sheet_name='说明', index=False)
print(f"结果已成功导出到: {filename}")
return filename
print(f"结果已成功导出到: {output_path}")
return output_path
def generate_yearly_data():
@@ -491,6 +505,17 @@ def main():
command = sys.argv[1]
show_window = '--show' in sys.argv # 检查是否包含--show参数
display_only = '--display-only' in sys.argv # 检查是否只显示不保存
# 解析输出目录参数
output_dir = None
if '--output' in sys.argv:
output_index = sys.argv.index('--output')
if output_index + 1 < len(sys.argv):
output_dir = sys.argv[output_index + 1]
else:
print("错误:--output 参数需要指定目录路径")
print("用法python main.py --output <目录路径>")
return
if command == '--excel':
if len(sys.argv) < 3:
@@ -619,38 +644,46 @@ def main():
# 绘制曲线
print("正在绘制系统运行曲线...")
plot_system_curves(solar_output, wind_output, thermal_output, load_demand, result, params.storage_efficiency, show_window, display_only)
plot_system_curves(solar_output, wind_output, thermal_output, load_demand, result, params.storage_efficiency, show_window, display_only, output_dir)
# 导出结果到Excel
try:
export_results_to_excel(solar_output, wind_output, thermal_output, load_demand, result, params)
export_results_to_excel(solar_output, wind_output, thermal_output, load_demand, result, params, output_dir=output_dir)
except Exception as e:
print(f"导出Excel文件失败{str(e)}")
if display_only:
print("\n正在显示图形窗口...")
elif show_window:
print("\n曲线图已保存为 'system_curves.png' 并显示图形窗口")
output_path = os.path.join(output_dir if output_dir else 'results', 'system_curves.png')
print(f"\n曲线图已保存为 '{output_path}' 并显示图形窗口")
else:
print("\n曲线图已保存为 'system_curves.png'")
output_path = os.path.join(output_dir if output_dir else 'results', 'system_curves.png')
print(f"\n曲线图已保存为 '{output_path}'")
def print_usage():
"""打印使用说明"""
print("多能互补系统储能容量优化程序")
print("\n使用方法:")
print(" python main.py --excel <文件路径> # 从Excel文件读取数据")
print(" python main.py --create-template [类型] # 创建Excel模板(24或8760)")
print(" python main.py # 使用24小时示例数据")
print(" python main.py --show # 显示图形窗口(可与其他参数组合使用)")
print(" python main.py --display-only # 只显示图形窗口,不保存文件")
print(" python main.py --excel <文件路径> # 从Excel文件读取数据")
print(" python main.py --output <目录路径> # 指定输出目录默认results")
print(" python main.py --create-template [类型] # 创建Excel模板(24或8760)")
print(" python main.py # 使用24小时示例数据")
print(" python main.py --show # 显示图形窗口(可与其他参数组合使用)")
print(" python main.py --display-only # 只显示图形窗口,不保存文件")
print("\n示例:")
print(" python main.py --excel data.xlsx")
print(" python main.py --excel data.xlsx --show")
print(" python main.py --excel data.xlsx --output my_results")
print(" python main.py --excel data.xlsx --display-only")
print(" python main.py --create-template 8760")
print(" python main.py --create-template 24")
print(" python main.py --display-only # 使用示例数据并只显示图形窗口")
print(" python main.py --display-only # 使用示例数据并只显示图形窗口")
print(" python main.py --output custom_results # 使用示例数据,输出到 custom_results 目录")
print("\n说明:")
print(" - 结果文件默认保存到 results 目录")
print(" - 使用 --output 参数可指定自定义输出目录")
print(" - 如果输出目录不存在,程序会自动创建")
if __name__ == "__main__":