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
一、基础信息 数据集名称:Bottle Fin实例分割数据集 图片数量: 训练集:4418张图片 验证集:1104张图片 总计:5522张图片 分类类别: - 类别0: 数字0 - 类别1: 数字1 - 类别2: 数字2 - 类别3: 数字3 - 类别4: 数字4 - 类别5: 数字5 - 类别6: Bottle Fin 标注格式:YOLO格式,包含多边形坐标,适用于实例分割任务。 数据格式:图片格式常见如JPEG或PNG,具体未指定。 二、适用场景 实例分割AI模型开发:数据集支持实例分割任务,帮助构建能够精确识别和分割图像中多个对象的AI模型,适用于对象检测和分割应用。 工业自动化与质量控制:可能应用于制造、物流或零售领域,用于自动化检测和分类物体,提升生产效率。 计算机视觉研究:支持实例分割算法的学术研究,促进目标检测和分割技术的创新。 教育与实践培训:可用于高校或培训机构的计算机视觉课程,作为实例分割任务的实践资源,帮助学生理解多类别分割。 三、数据集优势 多类别设计:包含7个不同类别,涵盖数字和Bottle Fin对象,增强模型对多样对象的识别和分割能力。 高质量标注:标注采用YOLO格式的多边形坐标,确保分割边界的精确性,提升模型训练效果。 数据规模适中:拥有超过5500张图片,提供充足的样本用于模型训练和验证,支持稳健的AI开发。 即插即用兼容性:标注格式直接兼容主流深度学习框架(如YOLO),便于快速集成到各种实例分割项目中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值