import gradio as gr import numpy as np import pandas as pd import math from matplotlib import pyplot as plt from math import ceil # 读取文件 s = 1 T_max = 500 count=480 tzz=pd.read_excel('data.xlsx', header=None) Load = tzz.iloc[:count, 0] # 给定负荷 bat_power = tzz.iloc[0:count, 1] pv_power = [0] * count C_buy = tzz.iloc[0:count, 2] # 贵分时电价 # 如果上传文件,则读取 def choose_file(default_file, uploaded_file): global Load, bat_power, pv_power, C_buy if default_file: result, pic_path = main_func(20) else: filename = uploaded_file.name tzz = pd.read_excel(filename, header=None) Load = tzz.iloc[:count, 0] # 给定负荷 bat_power = tzz.iloc[0:count, 1] pv_power = [0] * count C_buy = tzz.iloc[0:count, 2] # 贵分时电价 result, pic_path = main_func(20) return result, pic_path # 计算适应度函数的函数 def fitness_caculate(pp): # 参数 duration = 0.05 net_power = np.zeros(count) bat_cha_power = np.zeros(count) bat_dis_power = np.zeros(count) dim = 480 # dim表示粒子维度 # 参数结束 t_duration = 0.05 F1 = 0 #F是惩罚项 F2 = 0 F3 = 0 C4 = 0 #购电成本 bat = pp[dim] * 0.4 bat_0 = pp[dim] bat_power = pp[0:count] T_max = 500 rate = 0.03 year = 20 n = 22.68 * T_max / 30 r = (rate * math.pow(1 + rate , year)) / (math.pow(1 + rate , year) - 1) sff = rate / (math.pow(1 + rate , year) - 1) sff_bat1 = rate / (math.pow(1 + rate , 6) - 1) sff_bat2 = rate / (math.pow(1 + rate , 12) - 1) sff_bat3 = rate / (math.pow(1 + rate , 18) - 1) sff_dc1 = rate / (math.pow(1 + rate , 8) - 1) sff_dc2 = rate / (math.pow(1 + rate , 16) - 1) sff_ac = rate / (math.pow(1 + rate , 10) - 1) S_bat = 2 / 3 S_dc = 1 / 2 S_ac = 0 for j in range(480): net_power[j] = (Load[j] + bat_power[j]) if bat_power[j] > 0: bat_cha_power[j] = bat_power[j] bat_dis_power[j] = 0 bat = (bat + bat_cha_power[j] * t_duration) elif bat_power[j] == 0: bat_cha_power[j] = 0 bat_dis_power[j] = 0 bat = (bat + bat_dis_power[j] * t_duration) else: bat_cha_power[j] = 0 bat_dis_power[j] = bat_power[j] bat = (bat + bat_dis_power[j] * t_duration) if (0.3 * bat_0 <= bat) and (bat <= 0.9 * bat_0): F1 = F1 + 0 else: F1 = F1 + 10000 # F1用来惩罚储能容量超出l. if (net_power[j] <= T_max): F3 = F3 + 0 else: F3 = F3 + 10000 C4 += net_power[j]* C_buy[j] * t_duration if abs(sum((1 / 0.95) * bat_dis_power[1: j]*t_duration + 0.95 * bat_cha_power[1: j]*t_duration)) <= 10: F2 = F2+0 else: F2 = F2+10000 dc = max(abs(bat_power)) dc = ceil(dc) ac = max(abs(net_power)) ac = ceil(ac) C1 = r * (4800 * T_max + 1414.2 * bat_0 + 696.47 * ac + 471.56 * dc) / 365 C2 = 0.01 * C1 C3 = (1414.2 * bat_0 * (sff_bat1 + sff_bat2 + sff_bat3 - S_bat * sff) + \ 471.56 * dc * (sff_dc1+sff_dc2-S_dc * sff) + 696.47 * ac * (sff_ac - S_ac * sff)) / 365 C4 C = C4+ C1 + C2 + C3+ F1 + F2 + F3 + n return C4+ C1 + C2 + C3+ F1 + F2 + F3 + n def main_func(sizepop): # 参数 w_max = 0.9 # w越大,全局搜索能力越强,w越小,局部搜索能力越佳 w_min = 0.4 # 我们用的权重是变化的 v1_max = 10 # 粒子最大速度,设置速度限制 v1_min = -10 # %如果粒子飞行速度过快,很可能直接飞过最优解位置, v2_max = 50 # 粒子最大速度,设置速度限制 v2_min = -50 # %如果粒子飞行速度过快,很可能直接飞过最优解位置, # 设置种群参数 sizepop = 20 # 粒子个数,每个粒子都是一个解 iteration = 100 # 迭代次数 dim = 480 # dim表示粒子维度 B_max = 1300 B_min = 1000 # 参数结束 # print('sizepop', sizepop) sizepop = int(sizepop) # 所有粒子位置和速度初始化 pop_v = np.zeros((sizepop, dim + 1)) pop_x = np.zeros((sizepop, dim + 1)) for i in range(sizepop): pop_v[i, count] = v1_min + (v1_max - v1_min) * np.random.rand() pop_x[i, count] = B_min + (B_max - B_min) * np.random.rand() pop_x[i, count] = np.round(pop_x[i, count]) for j in range(count): pop_v[i, j] = v2_min + (v2_max - v2_min) * np.random.rand() pop_x[i, j] = bat_power[j] # 保存最佳粒子的位置 pbest_all = np.zeros((sizepop, dim + 1)) pbest = np.zeros((sizepop, 1)) # 参数结尾 for i in range(sizepop): pop_v[i, count] = v1_min + (v1_max - v1_min) * np.random.rand() pop_x[i, count] = B_min + (B_max - B_min) * np.random.rand() pop_x[i, count] = np.round(pop_x[i, count]) for j in range(count): pop_v[i, j] = v2_min + (v2_max - v2_min) * np.random.rand() pop_x[i, j] = bat_power[j] # 保存最佳粒子的位置 pbest_all = np.zeros((sizepop, dim + 1)) pbest = np.zeros((sizepop, 1)) # 计算所有粒子的适应度函数值 for i in range(0, sizepop): pbest[i] = fitness_caculate(pop_x[i, :]) pbest_all[i, :] = pop_x[i, :] # 先默认第一个最好 gbest_all = pop_x[0, :] gbest = pbest[0] # 全局最优更新,找出哪个粒子最优 for i in range(1, sizepop): if pbest[i] < gbest: gbest_all[:] = pop_x[i, :] gbest = pbest[i] # 开始主循环 uu = np.zeros(iteration) for t in range(iteration): for i in range(sizepop): w = w_max - (w_max - w_min) * t / iteration c1 = (0.5 - 2.5) * t / iteration + 2.5 c2 = (2.5 - 0.5) * t / iteration + 0.5 pop_v[i, :] = w * pop_v[i, :] + c1 * np.random.rand() * ( pbest_all[i, :] - pop_x[i, :]) + c2 * np.random.rand() * (gbest_all - pop_x[i, :]) for j in range(dim): if pop_v[i, j] > v2_max: pop_v[i, j] = v2_max elif pop_v[i, j] < v2_min: pop_v[i, j] = v2_min pop_x[i, :] += pop_v[i, :] for j in range(dim): if pop_x[i, j] > min(T_max - Load[j], 0.5 * pop_x[i, dim]): pop_x[i, j] = min(T_max - Load[j], 0.5 * pop_x[i, dim]) pop_v[i, j] = -pop_v[i, j] elif (pop_x[i, j] + Load[j]) > T_max: pop_x[i, j] = T_max - Load[j] pop_v[i, j] = -pop_v[i, j] for j in range(dim): if pop_x[i, j] < max(-Load[j], -0.5 * pop_x[i, dim]): pop_x[i, j] = max(-Load[j], -0.5 * pop_x[i, dim]) pop_v[i, j] = -pop_v[i, j] elif pop_x[i, j] < -(Load[j] + T_max): pop_x[i, j] = -(Load[j] + T_max) pop_v[i, j] = -pop_v[i, j] for j in range(dim): if pop_x[i, j] < 0 and Load[j] == 0: pop_x[i, j] = 0 pop_x[i, dim] = ceil(pop_x[i, dim]) y = fitness_caculate(pop_x[i, :]) if y < pbest[i]: pbest_all[i, :] = pop_x[i, :] pbest[i] = y if pbest[i] < gbest: gbest_all[:] = pop_x[i, :] gbest = pbest[i] uu[t] = ceil(gbest) plt.figure(1) x1_ticks = np.arange(0, iteration + 1, 20) plt.xticks(x1_ticks, fontproperties='Times New Roman', size=16) plt.yticks(fontproperties='Times New Roman', size=16) plt.plot(uu) plt.xlabel('iteration', font={'family': 'Times New Roman', 'size': 16}) plt.ylabel('Cost/RMB', font={'family': 'Times New Roman', 'size': 16}) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.figure(2) x2_ticks = np.arange(0, dim + 1, 80) y2_ticks = np.arange(-600, 200, 1000) plt.plot(gbest_all[0:dim], label='Energy storage power') plt.xticks(x2_ticks, ('0', '4', '8', '12', '16', '20', '24'), fontproperties='Times New Roman', size=16) plt.yticks(y2_ticks, fontproperties='Times New Roman', size=16) plt.plot(Load[0:dim], label='Load power') plt.xlabel('time/hour', font={'family': 'Times New Roman', 'size': 16}) plt.ylabel('Power/kW', font={'family': 'Times New Roman', 'size': 16}) # print('\n', '成本(元)', ceil(gbest), '\n', '储能容量(kWh)', gbest_all[dim], '\n') plt.legend() # plt.show() result = f'成本(元): {ceil(gbest)};\n储能容量(kWh): {gbest_all[dim]}.' pic_path = '.\\rf_Demo.png' plt.savefig(pic_path) return result, pic_path demo = gr.Interface( fn = choose_file, inputs=["checkbox", gr.inputs.File()], outputs=["text", "image"], examples='', title="群体智能优化算法", description="请上传历史负荷电价数据或选择使用默认文件" ) demo.launch()