Algorithms—168.Excel Sheet Column Title

本文深入探讨了代码优化的策略与技巧,通过实例分析,揭示了如何提高代码效率和性能,包括从数据结构选择到算法优化的全过程。重点介绍了Z=A0的概念及其在特定场景下的应用,同时分享了在不同编程环境下的最佳实践。

思路:同171题,记住Z=A0即可。

耗时:204ms,中上游。

public class Solution {
    public String convertToTitle(int n) {
    	List<Integer> list=new ArrayList<Integer>();
        while (n!=0) {
			list.add(n%26);
			n/=26;
		}
        boolean flag=false;
        List<Integer> l=new ArrayList<Integer>();
        for (int i = 0; i <list.size(); i++) {
        	int k=list.get(i);
			if(flag){
				if (k>1) {
					l.add(k-1);
					flag=false;
				}else if(k==1){
					l.add(26);
					flag=true;
				}else {
					l.add(25);
					flag=true;
				}
			}else {
				if (k!=0) {
					l.add(k);
					flag=false;
				}
				else {
					l.add(26);
					flag=true;
				}
			}
		}
        int m=l.size();
        if (flag) {
			m--;
		}
        String answer="";
         for (int i = m-1; i >=0; i--) {
			int k=l.get(i);
			k+=64;
			char c=(char) k;
			String s=String.valueOf(c);
			answer+=s;
		}
    	return answer;
    }
}



import pandas as pd import numpy as np from openpyxl import load_workbook # 参数设置 input_excel_file = 'output_data.xlsx' output_excel_file = '附件6-问题二答案表.xlsx' rho = 1.225 # 空气密度 (kg/m^3) A = 5026 # 截面积 (m^2) num_turbines_per_sheet = 100 # 每个工作表风机数量 num_time_steps = 2000 Cp=0.593 # 工作表名称与对应的数据源 sheet_config = { '主轴扭矩': 'WF_1', '塔架推力': 'WF_2' } # 构建时间列 time_column = np.arange(1, num_time_steps + 1).reshape(-1, 1) # (2000, 1) # 用于保存结果 results = { '主轴扭矩': [], '塔架推力': [] } # 遍历每个工作表及其对应的数据源 for sheet_name, source_sheet in sheet_config.items(): print(f"正在处理工作表: {sheet_name}") # 一次性读取整个数据源工作表 df = pd.read_excel(input_excel_file, sheet_name=source_sheet, header=None) data = df.values # 转为 numpy 数组 # 处理每台风机 for turbine_idx in range(num_turbines_per_sheet): start_row = turbine_idx * num_time_steps end_row = start_row + num_time_steps # 提取当前风机的数据块 turbine_data = data[start_row:end_row, :] # 提取第二列为有功功率 P,第三列为等效风速 v p = turbine_data[:, 1] v = turbine_data[:, 2] # 计算应力或扭矩 valid = v != 0 stress_or_torque = np.zeros_like(v, dtype=float) stress_or_torque[valid] = (0.5 * rho * v[valid]**3 * A*Cp - p[valid]) / v[valid] # 存入结果列表 results[sheet_name].append(stress_or_torque) # 写入 Excel 文件 with pd.ExcelWriter(output_excel_file, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer: for sheet_name in sheet_config: # 将所有风机数据拼接成 (2000, 100) turbines_data = np.column_stack(results[sheet_name]) # 合并为 100 列 # 添加时间列 final_df = pd.DataFrame(np.hstack([time_column, turbines_data]), columns=['时间'] + [f'风机{i+1}' for i in range(num_turbines_per_sheet)]) # 写入对应的工作表 final_df.to_excel(writer, sheet_name=sheet_name, index=False) print(f"应力/扭矩数据已成功写入文件:{output_excel_file}") 根据此代码中计算应力/扭矩的模型,对以下代码进行修改 import numpy as np import pandas as pd from pykalman import KalmanFilter from scipy.interpolate import interp1d from deap import base, creator, tools, algorithms import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示 plt.rcParams['axes.unicode_minus'] = False # 正常显示负号 # Step 1: 读取附件四原始数据 def load_attachment4_data(file_path): pref_df = pd.read_excel(file_path, sheet_name='Pref', header=None) vwin_df = pd.read_excel(file_path, sheet_name='Vwin', header=None) pref = pref_df.values.T # (10风机 x 300时间步) vwin = vwin_df.values.T # (10风机 x 300时间步) return pref, vwin # Step 2: 卡尔曼滤波降噪 def apply_kalman(signal): kf = KalmanFilter(transition_matrices=[1], observation_matrices=[1], initial_state_mean=signal[0], initial_state_covariance=1, observation_covariance=1, transition_covariance=0.01) state_means, _ = kf.filter(signal) return state_means.flatten() def kalman_filter_data(data): return np.apply_along_axis(apply_kalman, axis=1, arr=data) # Step 3: 延迟识别与对齐 def find_lag(x, y, max_lag=10): cross_corr = np.correlate(x - np.mean(x), y - np.mean(y), mode='full') lags = np.arange(-max_lag, max_lag + 1) best_lag = lags[np.argmax(cross_corr[len(cross_corr)//2 - max_lag : len(cross_corr)//2 + max_lag + 1])] return best_lag def align_signals(signal1, signal2, lag): t = np.arange(len(signal1)) if lag > 0: f = interp1d(t, signal1, kind='linear', fill_value='extrapolate') aligned = f(t + lag) return aligned[:len(signal2)], signal2 elif lag < 0: f = interp1d(t, signal2, kind='linear', fill_value='extrapolate') aligned = f(t - lag) return signal1, aligned[:len(signal1)] else: return signal1, signal2 def align_all_signals(pref, vwin): pref_aligned = np.zeros_like(pref) vwin_aligned = np.zeros_like(vwin) for i in range(pref.shape[0]): lag = find_lag(pref[i], vwin[i]) p, v = align_signals(pref[i], vwin[i], lag) pref_aligned[i] = p vwin_aligned[i] = v return pref_aligned, vwin_aligned # Step 4: 计算主轴扭矩和塔架推力 def calculate_shaft_torque(power, wind_speed, rotor_radius=50, efficiency=0.9): tip_speed_ratio = 8 angular_velocity = tip_speed_ratio * wind_speed / rotor_radius torque = power / angular_velocity return torque * efficiency def calculate_tower_thrust(wind_speed, rotor_radius=50): swept_area = np.pi * rotor_radius ** 2 thrust = 0.5 * 1.225 * swept_area * wind_speed ** 2 * 0.7 return thrust # Step 5: 遗传算法优化功率分配(带疲劳损伤最小化 + 误差惩罚) def optimize_power_with_ga(pref_aligned, vwin_aligned): total_power = np.sum(pref_aligned, axis=0) optimized_power = np.zeros_like(pref_aligned) creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() bounds = [(0, 5e6) for _ in range(10)] # 每台风机功率上限为5MW toolbox.register("power_gene", np.random.uniform, 0, 1) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.power_gene, n=10) toolbox.register("population", tools.initRepeat, list, toolbox.individual) def eval_func(individual, t, prev_power=None): powers = np.clip(individual, 0, 5e6) if abs(np.sum(powers) - total_power[t]) > 1e4: return 1e6, wind_speeds = vwin_aligned[:, t] # 计算载荷 torques = [calculate_shaft_torque(p, wind_speeds[i]) for i, p in enumerate(powers)] thrusts = [calculate_tower_thrust(w) for w in wind_speeds] # 疲劳损伤 shaft_damage = np.mean([(abs(t) / 1e8)**3 for t in torques]) tower_damage = np.mean([(abs(f) / 1.2e8)**4 for f in thrusts]) total_damage = 0.6 * shaft_damage + 0.4 * tower_damage # 功率误差惩罚 power_error = np.abs(powers - pref_aligned[:, t]) penalty = 1e3 * np.sum(power_error > 0.1 * np.abs(pref_aligned[:, t])) # 功率变化平滑性惩罚 smooth_penalty = 0 if prev_power is not None: smooth_penalty = 1e2 * np.sum((powers - prev_power) ** 2) return total_damage + penalty + smooth_penalty, toolbox.register("evaluate", lambda ind, t, prev=None: eval_func(ind, t, prev)) toolbox.register("mate", tools.cxSimulatedBinaryBounded, low=[b[0] for b in bounds], up=[b[1] for b in bounds], eta=20.0) toolbox.register("mutate", tools.mutPolynomialBounded, low=[b[0] for b in bounds], up=[b[1] for b in bounds], eta=20.0, indpb=0.1) toolbox.register("select", tools.selTournament, tournsize=3) prev_power = None for t in range(300): pop = toolbox.population(n=50) for gen in range(10): offspring = algorithms.varAnd(pop, toolbox, cxpb=0.7, mutpb=0.3) fits = [toolbox.evaluate(ind, t, prev_power) for ind in offspring] fits = [f[0] for f in fits] selected = tools.selBest(pop + offspring, k=50) pop = selected best = tools.selBest(pop, k=1)[0] optimized_power[:, t] = np.clip(best, 0, 5e6) prev_power = optimized_power[:, t] return optimized_power # Step 6: 计算疲劳损伤 def compute_cumulative_damage(power, wind_speed): cumulative_damage = [] for t in range(power.shape[1]): torques = [calculate_shaft_torque(power[i, t], wind_speed[i, t]) for i in range(10)] thrusts = [calculate_tower_thrust(wind_speed[i, t]) for i in range(10)] shaft_damage = np.mean([(abs(t) / 1e8)**3 for t in torques]) tower_damage = np.mean([(abs(f) / 1.2e8)**4 for f in thrusts]) total = 0.6 * shaft_damage + 0.4 * tower_damage cumulative_damage.append(total if t == 0 else cumulative_damage[-1] + total) return np.array(cumulative_damage) # Step 7: 动图可视化 def animate_damage_comparison(cumulative_damage_optimized, cumulative_damage_original): fig, ax = plt.subplots() line1, = ax.plot([], [], label='优化后累计损伤') line2, = ax.plot([], [], label='原始累计损伤') ax.set_xlim(0, 300) ax.set_ylim(0, 2) ax.set_xlabel('时间步') ax.set_ylabel('累计疲劳损伤') ax.legend() def update(frame): line1.set_data(range(frame), cumulative_damage_optimized[:frame]) line2.set_data(range(frame), cumulative_damage_original[:frame]) return line1, line2 ani = FuncAnimation(fig, update, frames=300, interval=100, blit=True) plt.title('优化前后累计疲劳损伤对比') plt.show() # Step 8: 对比图 def plot_damage_comparison(cumulative_damage_optimized, cumulative_damage_original): plt.plot(cumulative_damage_optimized, label='优化后累计损伤') plt.plot(cumulative_damage_original, label='原始累计损伤') plt.xlabel('时间步') plt.ylabel('累计疲劳损伤') plt.title('有无优化器的累计疲劳损伤对比') plt.legend() plt.grid() plt.show() # 主程序入口 if __name__ == "__main__": file_path = r'C:\Users\1\Desktop\附件4-噪声和延迟作用下的采集数据.xlsx' pref, vwin = load_attachment4_data(file_path) # Step 2: 卡尔曼滤波降噪 pref_clean = kalman_filter_data(pref) vwin_clean = kalman_filter_data(vwin) # Step 3: 延迟对齐 pref_aligned, vwin_aligned = align_all_signals(pref_clean, vwin_clean) # Step 4: 使用问题四更新模型优化功率分配 optimized_power = optimize_power_with_ga(pref_aligned, vwin_aligned) # Step 6: 计算疲劳损伤 cumulative_damage_optimized = compute_cumulative_damage(optimized_power, vwin_aligned) cumulative_damage_original = compute_cumulative_damage(pref_aligned, vwin_aligned) # Step 7 & 8: 可视化 animate_damage_comparison(cumulative_damage_optimized, cumulative_damage_original) plot_damage_comparison(cumulative_damage_optimized, cumulative_damage_original)
07-23
import numpy as np import pandas as pd from deap import base, tools, algorithms, creator import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from openpyxl import load_workbook # ================== 参数设置 ================== input_file = r'C:\Users\1\Desktop\附件2-风电机组采集数据.xlsx' # 原始功率和风速数据 output_result_file = '优化后的功率分配_问题三加权损伤.xlsx' output_damage_file = r'C:\Users\1\Desktop\附件6-问题二答案表.xlsx' output_damage_plot_file = '每秒疲劳损伤数据.xlsx' # S-N曲线参数 S0_shaft = 1e8 # 主轴基准应力 m_shaft = 3 # 主轴指数 S0_tower = 1.2e8 # 塔架基准应力 m_tower = 4 # 塔架指数 # 权重 weight_shaft = 0.6 weight_tower = 0.4 # 空气动力参数 rho = 1.225 # 空气密度 (kg/m^3) A = 5026 # 扫风面积 (m^2) Cp = 0.593 # 功率系数 # 时间步设置 num_turbines = 100 num_time_steps = 2000 # ================== 读取附件2中的功率和风速数据 ================== def load_original_data(file_path): df = pd.read_excel(file_path, sheet_name='Sheet1', header=None) data = df.values powers = [] winds = [] for i in range(num_turbines): start = i * num_time_steps end = start + num_time_steps powers.append(data[start:end, 1]) # 第2列为功率 winds.append(data[start:end, 2]) # 第3列为风速 return np.array(powers), np.array(winds) # (100 x 2000) # ================== 疲劳损伤计算函数 ================== def calculate_shaft_torque(power, wind_speed): valid = wind_speed != 0 torque = np.zeros_like(wind_speed) torque[valid] = (0.5 * rho * wind_speed[valid]**3 * A * Cp - power[valid]) / wind_speed[valid] return torque def calculate_tower_thrust(wind_speed): return 0.5 * rho * A * wind_speed**2 * 0.7 # ================== 目标函数 ================== def objective_function(individual, shaft_torques, tower_forces, total_power): powers = np.clip(individual, 0, 5e6) # 功率限制 if abs(np.sum(powers) - total_power) > 1e4: return 1e6, # 计算主轴和塔架的平均损伤 shaft_damages = [(abs(t) / S0_shaft) ** m_shaft for t in shaft_torques] tower_damages = [(abs(f) / S0_tower) ** m_tower for f in tower_forces] avg_shaft = np.mean(shaft_damages) avg_tower = np.mean(tower_damages) # 加权目标函数 total_damage = weight_shaft * avg_shaft + weight_tower * avg_tower return total_damage, # ================== 功率限制函数 ================== def get_bounds(avg_power): low = max(0, avg_power - 1e6) high = min(5e6, avg_power + 1e6) return [(low, high)] * num_turbines # ================== 遗传算法优化器 ================== def optimize_ga(power_initial, wind_initial): total_power = np.sum(power_initial) avg_power = total_power / num_turbines bounds = get_bounds(avg_power) if not hasattr(creator, "FitnessMin"): creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) if not hasattr(creator, "Individual"): creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() for i in range(num_turbines): toolbox.register(f"attr_{i}", np.random.uniform, bounds[i][0], bounds[i][1]) toolbox.register("individual", tools.initCycle, creator.Individual, [getattr(toolbox, f"attr_{i}") for i in range(num_turbines)], n=1) toolbox.register("population", tools.initRepeat, list, toolbox.individual) shaft_torques = calculate_shaft_torque(power_initial, wind_initial) tower_forces = calculate_tower_thrust(wind_initial) toolbox.register("evaluate", objective_function, shaft_torques=shaft_torques, tower_forces=tower_forces, total_power=total_power) toolbox.register("mate", tools.cxSimulatedBinaryBounded, low=[b[0] for b in bounds], up=[b[1] for b in bounds], eta=20.0) toolbox.register("mutate", tools.mutPolynomialBounded, low=[b[0] for b in bounds], up=[b[1] for b in bounds], eta=20.0, indpb=0.1) toolbox.register("select", tools.selTournament, tournsize=3) pop = toolbox.population(n=50) hof = tools.HallOfFame(1) stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean) stats.register("min", np.min) algorithms.eaSimple(pop, toolbox, cxpb=0.7, mutpb=0.3, ngen=50, stats=stats, halloffame=hof, verbose=False) # 修复点:使用统一的 min 和 max 数组进行 clip min_bounds = np.array([b[0] for b in bounds]) max_bounds = np.array([b[1] for b in bounds]) best_powers = np.clip(hof[0], min_bounds, max_bounds) return best_powers # ================== 计算每秒疲劳损伤 ================== def rainflow_counting(load_series): cycles = [] window = [] for val in load_series: window.append(val) if len(window) > 4: window.pop(0) if len(window) >= 4: a, b, c, d = window if (a < b and b > c and c < d) or (a > b and b < c and c > d): peaks = [b, c] Sa = (max(peaks) - min(peaks)) / 2 Sm = (max(peaks) + min(peaks)) / 2 cycles.append((Sa, Sm)) return cycles def calculate_cumulative_damage(load_series, S_ut, S0, m): cumulative_damage = [] history = [] for t in range(len(load_series)): history.append(load_series[t]) cycles = rainflow_counting(history) damage = 0 for Sa, Sm in cycles: if Sm >= S_ut: damage += float('inf') else: Seq = Sa / (1 - Sm / S_ut) life = (Seq / S0) ** (-m) damage += 1 / life cumulative_damage.append(damage) return cumulative_damage # ================== 主程序入口 ================== if __name__ == "__main__": # Step 1: 读取原始功率和风速数据 original_powers, original_winds = load_original_data(input_file) # Step 2: 遗传算法优化功率分配 optimized_powers = np.zeros_like(original_powers) for t in range(num_time_steps): print(f"正在优化时间步 {t + 1} / {num_time_steps}") optimized_powers[:, t] = optimize_ga(original_powers[:, t], original_winds[:, t]) # Step 3: 计算主轴扭矩和塔架推力 shaft_torques = np.zeros_like(optimized_powers) tower_forces = np.zeros_like(optimized_powers) for t in range(num_time_steps): shaft_torques[:, t] = calculate_shaft_torque(optimized_powers[:, t], original_winds[:, t]) tower_forces[:, t] = calculate_tower_thrust(original_winds[:, t]) # Step 4: 写入优化后的功率数据 time_column = np.arange(1, num_time_steps + 1).reshape(-1, 1) output_data = np.hstack([time_column, optimized_powers.T]) columns = ['时间'] + [f'风机{i+1}' for i in range(num_turbines)] result_df = pd.DataFrame(output_data, columns=columns) result_df.to_excel(output_result_file, index=False) print(f"优化后的功率已保存至 {output_result_file}") # Step 5: 写入主轴扭矩和塔架推力 with pd.ExcelWriter(output_damage_file, engine='openpyxl', mode='w') as writer: pd.DataFrame(shaft_torques.T, columns=[f'风机{i+1}' for i in range(num_turbines)], index=range(1, num_time_steps+1)) \ .to_excel(writer, sheet_name='主轴扭矩', index_label='时间') pd.DataFrame(tower_forces.T, columns=[f'风机{i+1}' for i in range(num_turbines)], index=range(1, num_time_steps+1)) \ .to_excel(writer, sheet_name='塔架推力', index_label='时间') print(f"主轴扭矩和塔架推力已保存至 {output_damage_file}") # Step 6: 计算并保存每秒疲劳损伤 shaft_damage_all = [] tower_damage_all = [] for i in range(num_turbines): print(f"正在计算风机 {i + 1} 的疲劳损伤...") shaft_damage = calculate_cumulative_damage(shaft_torques[i], S_ut_shaft, S0_shaft, m_shaft) tower_damage = calculate_cumulative_damage(tower_forces[i], S_ut_tower, S0_tower, m_tower) shaft_damage_all.append(shaft_damage) tower_damage_all.append(tower_damage) # 保存每秒疲劳损伤 with pd.ExcelWriter(output_damage_plot_file, engine='openpyxl', mode='w') as writer: pd.DataFrame(np.array(shaft_damage_all).T, columns=[f'风机{i+1}' for i in range(num_turbines)], index=range(1, num_time_steps+1)) \ .to_excel(writer, sheet_name='主轴疲劳数据', index_label='时间') pd.DataFrame(np.array(tower_damage_all).T, columns=[f'风机{i+1}' for i in range(num_turbines)], index=range(1, num_time_steps+1)) \ .to_excel(writer, sheet_name='塔架疲劳数据', index_label='时间') print(f"每秒疲劳损伤已保存至 {output_damage_plot_file}") # Step 7: 可视化典型风机的疲劳损伤增长曲线 import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) for i in range(min(5, num_turbines)): plt.plot(range(1, num_time_steps+1), shaft_damage_all[i], label=f'主轴 #{i+1}') plt.plot(range(1, num_time_steps+1), tower_damage_all[i], '--', label=f'塔架 #{i+1}') plt.xlabel("时间 (s)") plt.ylabel("累积疲劳损伤") plt.title("典型样本的累积疲劳损伤增长过程") plt.legend() plt.grid(True) plt.tight_layout() plt.show() 在此代码的基础上,不用将计算出来的代码输出至附件6中保存
07-23
import numpy as np import pandas as pd from deap import base, tools, algorithms, creator import matplotlib.pyplot as plt import matplotlib.animation as animation # ================== 参数设置 ================== input_damage_file = '附件6-问题二答案表.xlsx' # 来自问题二的输出文件 input_power_file = 'output_data.xlsx' # 原始功率数据文件 output_result_file = '优化后的功率分配_问题三加权损伤.xlsx' # S-N曲线参数 S0_shaft = 1e8 # 主轴基准应力 m_shaft = 3 # 主轴指数 S0_tower = 1.2e8 # 塔架基准应力 m_tower = 4 # 塔架指数 # 权重 weight_shaft = 0.6 weight_tower = 0.4 # ================== 读取问题二输出的载荷数据 ================== def load_damage_data(file_path): # 读取主轴扭矩 shaft_df = pd.read_excel(file_path, sheet_name='主轴扭矩', header=0) shaft_torques = shaft_df.iloc[:, 1:].values.T # 转置后 (100风机 x 2000时间步) # 读取塔架推力 tower_df = pd.read_excel(file_path, sheet_name='塔架推力', header=0) tower_forces = tower_df.iloc[:, 1:].values.T # 转置后 (100风机 x 2000时间步) return shaft_torques, tower_forces # ================== 读取原始功率数据 ================== def load_power_data(file_path, sheet_name='WF_1'): df = pd.read_excel(file_path, sheet_name=sheet_name, header=None) data = df.values num_turbines = 100 num_time_steps = 2000 powers = [] for i in range(num_turbines): start = i * num_time_steps end = start + num_time_steps powers.append(data[start:end, 1]) # 第2列是功率 return np.array(powers) # (100风机 x 2000时间步) # ================== 疲劳损伤计算函数 ================== def calculate_shaft_damage(torque): stress = abs(torque) return (stress / S0_shaft) ** m_shaft def calculate_tower_damage(force): stress = abs(force) return (stress / S0_tower) ** m_tower # ================== 目标函数 ================== def objective_function(individual, shaft_torques, tower_forces, total_power): powers = np.clip(individual, 0, 5e6) # 功率限制 if abs(np.sum(powers) - total_power) > 1e4: return 1e6, # 计算主轴和塔架的平均损伤 shaft_damages = [calculate_shaft_damage(t) for t in shaft_torques] tower_damages = [calculate_tower_damage(f) for f in tower_forces] avg_shaft = np.mean(shaft_damages) avg_tower = np.mean(tower_damages) # 加权目标函数 total_damage = weight_shaft * avg_shaft + weight_tower * avg_tower return total_damage, # ================== 功率限制函数 ================== def get_bounds(avg_power): low = max(0, avg_power - 1e6) high = min(5e6, avg_power + 1e6) return [(low, high)] * 100 # ================== 遗传算法优化器 ================== def optimize_ga(shaft_torques, tower_forces, power_initial): total_power = np.sum(power_initial) avg_power = total_power / 100 bounds = get_bounds(avg_power) creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() for i in range(100): toolbox.register(f"attr_{i}", np.random.uniform, bounds[i][0], bounds[i][1]) toolbox.register("individual", tools.initCycle, creator.Individual, [getattr(toolbox, f"attr_{i}") for i in range(100)], n=1) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", objective_function, shaft_torques=shaft_torques, tower_forces=tower_forces, total_power=total_power) toolbox.register("mate", tools.cxSimulatedBinaryBounded, low=[b[0] for b in bounds], up=[b[1] for b in bounds], eta=20.0) toolbox.register("mutate", tools.mutPolynomialBounded, low=[b[0] for b in bounds], up=[b[1] for b in bounds], eta=20.0, indpb=0.1) toolbox.register("select", tools.selTournament, tournsize=3) pop = toolbox.population(n=50) hof = tools.HallOfFame(1) stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean) stats.register("min", np.min) algorithms.eaSimple(pop, toolbox, cxpb=0.7, mutpb=0.3, ngen=50, stats=stats, halloffame=hof, verbose=False) # 修复点:使用统一的 min 和 max 数组进行 clip min_bounds = np.array([b[0] for b in bounds]) max_bounds = np.array([b[1] for b in bounds]) best_powers = np.clip(hof[0], min_bounds, max_bounds) best_damage = objective_function(best_powers, shaft_torques, tower_forces, total_power)[0] return best_powers, best_damage # ================== 主程序入口 ================== if __name__ == "__main__": # Step 1: 加载问题二的数据 shaft_torques, tower_forces = load_damage_data(input_damage_file) power_data = load_power_data(input_power_file) n_time_steps = 2000 optimized_results = [] # 存储历史数据用于动画展示 history = { 'time_step': [], 'total_power': [], 'damage_before': [], 'damage_after': [], 'constraint_ok': [] } print("开始逐时间步进行功率优化分配...") fig, axs = plt.subplots(3, 1, figsize=(10, 8)) def animate(i): if i >= len(history['time_step']): return axs[0].clear() axs[1].clear() axs[2].clear() time_steps = history['time_step'][:i+1] powers = history['total_power'][:i+1] damage_before = history['damage_before'][:i+1] damage_after = history['damage_after'][:i+1] constraints = history['constraint_ok'][:i+1] # 总功率变化 axs[0].plot(time_steps, powers, label='总功率', color='blue') axs[0].set_title(f"时间步: {time_steps[-1]} | 总功率: {powers[-1]:.2f} W") axs[0].legend() # 损伤对比 axs[1].plot(time_steps, damage_before, label='优化前损伤', color='orange') axs[1].plot(time_steps, damage_after, label='优化后损伤', color='green') axs[1].set_title("主轴+塔架加权损伤") axs[1].legend() # 约束状态 status = "满足" if constraints[-1] else "不满足" color = "green" if constraints[-1] else "red" axs[2].text(0.5, 0.5, f"约束条件: {status}", fontsize=20, ha='center', va='center', color=color) axs[2].axis('off') plt.tight_layout() ani = None # 定义全局动画对象 def run_animation(t): print(f"处理第 {t + 1} 时间步...") shaft_t = shaft_torques[:, t] tower_f = tower_forces[:, t] power_initial = power_data[:, t] opt_powers, damage_after = optimize_ga(shaft_t, tower_f, power_initial) total_power_after = np.sum(opt_powers) constraint_ok = abs(np.sum(opt_powers) - np.sum(power_initial)) < 1e4 # 计算损伤(优化前 vs 优化后) damage_before_val = weight_shaft * np.mean([calculate_shaft_damage(t) for t in shaft_t]) + \ weight_tower * np.mean([calculate_tower_damage(f) for f in tower_f]) damage_after_val = objective_function(opt_powers, shaft_t, tower_f, np.sum(power_initial))[0] # 存入历史数据 history['time_step'].append(t + 1) history['total_power'].append(total_power_after) history['damage_before'].append(damage_before_val) history['damage_after'].append(damage_after_val) history['constraint_ok'].append(constraint_ok) optimized_results.append(opt_powers) for t in range(n_time_steps): run_animation(t) # 保存动画为 GIF ani = animation.FuncAnimation(fig, animate, frames=n_time_steps, interval=1000, repeat=False) ani.save('real_time_optimization.gif', writer='pillow') plt.close() # 将结果转换为 numpy 数组 (2000时间步 x 100风机) optimized_array = np.array(optimized_results) # shape: (2000, 100) # 添加时间列 n_time_steps = 2000 time_column = np.arange(1, n_time_steps + 1).reshape(-1, 1) # shape: (2000, 1) output_data = np.hstack([time_column, optimized_array]) # shape: (2000, 101) # 构建 DataFrame columns = ['时间'] + [f'风机{i+1}' for i in range(100)] result_df = pd.DataFrame(output_data, columns=columns) # 写入 Excel 文件 result_df.to_excel(output_result_file, index=False) print(f"优化完成,结果已保存至 {output_result_file}") 将代码改为只需输出每秒功率分配的图并且配上计时器;单独生成一张比较优化前后的所有风机的累积疲劳损伤总和的图
07-19
【电动车】基于多目标优化遗传算法NSGAII的峰谷分时电价引导下的电动汽车充电负荷优化研究(Matlab代码实现)内容概要:本文围绕“基于多目标优化遗传算法NSGA-II的峰谷分时电价引导下的电动汽车充电负荷优化研究”展开,利用Matlab代码实现优化模型,旨在通过峰谷分时电价机制引导电动汽车有序充电,降低电网负荷波动,提升能源利用效率。研究融合了多目标优化思想与遗传算法NSGA-II,兼顾电网负荷均衡性、用户充电成本和充电满意度等多个目标,构建了科学合理的数学模型,并通过仿真验证了方法的有效性与实用性。文中还提供了完整的Matlab代码实现路径,便于复现与进一步研究。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的高校研究生、科研人员及从事智能电网、电动汽车调度相关工作的工程技术人员。; 使用场景及目标:①应用于智能电网中电动汽车充电负荷的优化调度;②服务于峰谷电价政策下的需求侧管理研究;③为多目标优化算法在能源系统中的实际应用提供案例参考; 阅读建议:建议读者结合Matlab代码逐步理解模型构建与算法实现过程,重点关注NSGA-II算法在多目标优化中的适应度函数设计、约束处理及Pareto前沿生成机制,同时可尝试调整参数或引入其他智能算法进行对比分析,以深化对优化策略的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值